Remove forgotten (debug).
[org-mode/org-tableheadings.git] / lisp / org.el
blob32e4b208557ad60770fc4865d57cd75465e6ce5a
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.02pre-06
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.02pre-06"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
178 (const :tag "C id: Global id's for identifying entries" org-id)
179 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
180 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
181 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
182 (const :tag "C mew: Support for links to messages in Mew" org-mew)
183 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
184 (const :tag "C registry: A registry for Org links" org-registry)
185 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
186 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
187 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
188 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
189 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
192 (defgroup org-startup nil
193 "Options concerning startup of Org-mode."
194 :tag "Org Startup"
195 :group 'org)
197 (defcustom org-startup-folded t
198 "Non-nil means, entering Org-mode will switch to OVERVIEW.
199 This can also be configured on a per-file basis by adding one of
200 the following lines anywhere in the buffer:
202 #+STARTUP: fold
203 #+STARTUP: nofold
204 #+STARTUP: content"
205 :group 'org-startup
206 :type '(choice
207 (const :tag "nofold: show all" nil)
208 (const :tag "fold: overview" t)
209 (const :tag "content: all headlines" content)))
211 (defcustom org-startup-truncated t
212 "Non-nil means, entering Org-mode will set `truncate-lines'.
213 This is useful since some lines containing links can be very long and
214 uninteresting. Also tables look terrible when wrapped."
215 :group 'org-startup
216 :type 'boolean)
218 (defcustom org-startup-align-all-tables nil
219 "Non-nil means, align all tables when visiting a file.
220 This is useful when the column width in tables is forced with <N> cookies
221 in table fields. Such tables will look correct only after the first re-align.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
224 #+STARTUP: align
225 #+STARTUP: noalign"
226 :group 'org-startup
227 :type 'boolean)
229 (defcustom org-insert-mode-line-in-empty-file nil
230 "Non-nil means insert the first line setting Org-mode in empty files.
231 When the function `org-mode' is called interactively in an empty file, this
232 normally means that the file name does not automatically trigger Org-mode.
233 To ensure that the file will always be in Org-mode in the future, a
234 line enforcing Org-mode will be inserted into the buffer, if this option
235 has been set."
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-replace-disputed-keys nil
240 "Non-nil means use alternative key bindings for some keys.
241 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
242 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
243 If you want to use Org-mode together with one of these other modes,
244 or more generally if you would like to move some Org-mode commands to
245 other keys, set this variable and configure the keys with the variable
246 `org-disputed-keys'.
248 This option is only relevant at load-time of Org-mode, and must be set
249 *before* org.el is loaded. Changing it requires a restart of Emacs to
250 become effective."
251 :group 'org-startup
252 :type 'boolean)
254 (if (fboundp 'defvaralias)
255 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
257 (defcustom org-disputed-keys
258 '(([(shift up)] . [(meta p)])
259 ([(shift down)] . [(meta n)])
260 ([(shift left)] . [(meta -)])
261 ([(shift right)] . [(meta +)])
262 ([(control shift right)] . [(meta shift +)])
263 ([(control shift left)] . [(meta shift -)]))
264 "Keys for which Org-mode and other modes compete.
265 This is an alist, cars are the default keys, second element specifies
266 the alternative to use when `org-replace-disputed-keys' is t.
268 Keys can be specified in any syntax supported by `define-key'.
269 The value of this option takes effect only at Org-mode's startup,
270 therefore you'll have to restart Emacs to apply it after changing."
271 :group 'org-startup
272 :type 'alist)
274 (defun org-key (key)
275 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
276 Or return the original if not disputed."
277 (if org-replace-disputed-keys
278 (let* ((nkey (key-description key))
279 (x (org-find-if (lambda (x)
280 (equal (key-description (car x)) nkey))
281 org-disputed-keys)))
282 (if x (cdr x) key))
283 key))
285 (defun org-find-if (predicate seq)
286 (catch 'exit
287 (while seq
288 (if (funcall predicate (car seq))
289 (throw 'exit (car seq))
290 (pop seq)))))
292 (defun org-defkey (keymap key def)
293 "Define a key, possibly translated, as returned by `org-key'."
294 (define-key keymap (org-key key) def))
296 (defcustom org-ellipsis nil
297 "The ellipsis to use in the Org-mode outline.
298 When nil, just use the standard three dots. When a string, use that instead,
299 When a face, use the standart 3 dots, but with the specified face.
300 The change affects only Org-mode (which will then use its own display table).
301 Changing this requires executing `M-x org-mode' in a buffer to become
302 effective."
303 :group 'org-startup
304 :type '(choice (const :tag "Default" nil)
305 (face :tag "Face" :value org-warning)
306 (string :tag "String" :value "...#")))
308 (defvar org-display-table nil
309 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
311 (defgroup org-keywords nil
312 "Keywords in Org-mode."
313 :tag "Org Keywords"
314 :group 'org)
316 (defcustom org-deadline-string "DEADLINE:"
317 "String to mark deadline entries.
318 A deadline is this string, followed by a time stamp. Should be a word,
319 terminated by a colon. You can insert a schedule keyword and
320 a timestamp with \\[org-deadline].
321 Changes become only effective after restarting Emacs."
322 :group 'org-keywords
323 :type 'string)
325 (defcustom org-scheduled-string "SCHEDULED:"
326 "String to mark scheduled TODO entries.
327 A schedule is this string, followed by a time stamp. Should be a word,
328 terminated by a colon. You can insert a schedule keyword and
329 a timestamp with \\[org-schedule].
330 Changes become only effective after restarting Emacs."
331 :group 'org-keywords
332 :type 'string)
334 (defcustom org-closed-string "CLOSED:"
335 "String used as the prefix for timestamps logging closing a TODO entry."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-clock-string "CLOCK:"
340 "String used as prefix for timestamps clocking work hours on an item."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-comment-string "COMMENT"
345 "Entries starting with this keyword will never be exported.
346 An entry can be toggled between COMMENT and normal with
347 \\[org-toggle-comment].
348 Changes become only effective after restarting Emacs."
349 :group 'org-keywords
350 :type 'string)
352 (defcustom org-quote-string "QUOTE"
353 "Entries starting with this keyword will be exported in fixed-width font.
354 Quoting applies only to the text in the entry following the headline, and does
355 not extend beyond the next headline, even if that is lower level.
356 An entry can be toggled between QUOTE and normal with
357 \\[org-toggle-fixed-width-section]."
358 :group 'org-keywords
359 :type 'string)
361 (defconst org-repeat-re
362 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
363 "Regular expression for specifying repeated events.
364 After a match, group 1 contains the repeat expression.")
366 (defgroup org-structure nil
367 "Options concerning the general structure of Org-mode files."
368 :tag "Org Structure"
369 :group 'org)
371 (defgroup org-reveal-location nil
372 "Options about how to make context of a location visible."
373 :tag "Org Reveal Location"
374 :group 'org-structure)
376 (defconst org-context-choice
377 '(choice
378 (const :tag "Always" t)
379 (const :tag "Never" nil)
380 (repeat :greedy t :tag "Individual contexts"
381 (cons
382 (choice :tag "Context"
383 (const agenda)
384 (const org-goto)
385 (const occur-tree)
386 (const tags-tree)
387 (const link-search)
388 (const mark-goto)
389 (const bookmark-jump)
390 (const isearch)
391 (const default))
392 (boolean))))
393 "Contexts for the reveal options.")
395 (defcustom org-show-hierarchy-above '((default . t))
396 "Non-nil means, show full hierarchy when revealing a location.
397 Org-mode often shows locations in an org-mode file which might have
398 been invisible before. When this is set, the hierarchy of headings
399 above the exposed location is shown.
400 Turning this off for example for sparse trees makes them very compact.
401 Instead of t, this can also be an alist specifying this option for different
402 contexts. Valid contexts are
403 agenda when exposing an entry from the agenda
404 org-goto when using the command `org-goto' on key C-c C-j
405 occur-tree when using the command `org-occur' on key C-c /
406 tags-tree when constructing a sparse tree based on tags matches
407 link-search when exposing search matches associated with a link
408 mark-goto when exposing the jump goal of a mark
409 bookmark-jump when exposing a bookmark location
410 isearch when exiting from an incremental search
411 default default for all contexts not set explicitly"
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-following-heading '((default . nil))
416 "Non-nil means, show following heading when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the heading following the
419 match is shown.
420 Turning this off for example for sparse trees makes them very compact,
421 but makes it harder to edit the location of the match. In such a case,
422 use the command \\[org-reveal] to show more context.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. See `org-show-hierarchy-above' for valid contexts."
425 :group 'org-reveal-location
426 :type org-context-choice)
428 (defcustom org-show-siblings '((default . nil) (isearch t))
429 "Non-nil means, show all sibling heading when revealing a location.
430 Org-mode often shows locations in an org-mode file which might have
431 been invisible before. When this is set, the sibling of the current entry
432 heading are all made visible. If `org-show-hierarchy-above' is t,
433 the same happens on each level of the hierarchy above the current entry.
435 By default this is on for the isearch context, off for all other contexts.
436 Turning this off for example for sparse trees makes them very compact,
437 but makes it harder to edit the location of the match. In such a case,
438 use the command \\[org-reveal] to show more context.
439 Instead of t, this can also be an alist specifying this option for different
440 contexts. See `org-show-hierarchy-above' for valid contexts."
441 :group 'org-reveal-location
442 :type org-context-choice)
444 (defcustom org-show-entry-below '((default . nil))
445 "Non-nil means, show the entry below a headline when revealing a location.
446 Org-mode often shows locations in an org-mode file which might have
447 been invisible before. When this is set, the text below the headline that is
448 exposed is also shown.
450 By default this is off for all contexts.
451 Instead of t, this can also be an alist specifying this option for different
452 contexts. See `org-show-hierarchy-above' for valid contexts."
453 :group 'org-reveal-location
454 :type org-context-choice)
456 (defcustom org-indirect-buffer-display 'other-window
457 "How should indirect tree buffers be displayed?
458 This applies to indirect buffers created with the commands
459 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
460 Valid values are:
461 current-window Display in the current window
462 other-window Just display in another window.
463 dedicated-frame Create one new frame, and re-use it each time.
464 new-frame Make a new frame each time. Note that in this case
465 previously-made indirect buffers are kept, and you need to
466 kill these buffers yourself."
467 :group 'org-structure
468 :group 'org-agenda-windows
469 :type '(choice
470 (const :tag "In current window" current-window)
471 (const :tag "In current frame, other window" other-window)
472 (const :tag "Each time a new frame" new-frame)
473 (const :tag "One dedicated frame" dedicated-frame)))
475 (defgroup org-cycle nil
476 "Options concerning visibility cycling in Org-mode."
477 :tag "Org Cycle"
478 :group 'org-structure)
480 (defcustom org-drawers '("PROPERTIES" "CLOCK")
481 "Names of drawers. Drawers are not opened by cycling on the headline above.
482 Drawers only open with a TAB on the drawer line itself. A drawer looks like
483 this:
484 :DRAWERNAME:
485 .....
486 :END:
487 The drawer \"PROPERTIES\" is special for capturing properties through
488 the property API.
490 Drawers can be defined on the per-file basis with a line like:
492 #+DRAWERS: HIDDEN STATE PROPERTIES"
493 :group 'org-structure
494 :type '(repeat (string :tag "Drawer Name")))
496 (defcustom org-cycle-global-at-bob nil
497 "Cycle globally if cursor is at beginning of buffer and not at a headline.
498 This makes it possible to do global cycling without having to use S-TAB or
499 C-u TAB. For this special case to work, the first line of the buffer
500 must not be a headline - it may be empty ot some other text. When used in
501 this way, `org-cycle-hook' is disables temporarily, to make sure the
502 cursor stays at the beginning of the buffer.
503 When this option is nil, don't do anything special at the beginning
504 of the buffer."
505 :group 'org-cycle
506 :type 'boolean)
508 (defcustom org-cycle-emulate-tab t
509 "Where should `org-cycle' emulate TAB.
510 nil Never
511 white Only in completely white lines
512 whitestart Only at the beginning of lines, before the first non-white char
513 t Everywhere except in headlines
514 exc-hl-bol Everywhere except at the start of a headline
515 If TAB is used in a place where it does not emulate TAB, the current subtree
516 visibility is cycled."
517 :group 'org-cycle
518 :type '(choice (const :tag "Never" nil)
519 (const :tag "Only in completely white lines" white)
520 (const :tag "Before first char in a line" whitestart)
521 (const :tag "Everywhere except in headlines" t)
522 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
525 (defcustom org-cycle-separator-lines 2
526 "Number of empty lines needed to keep an empty line between collapsed trees.
527 If you leave an empty line between the end of a subtree and the following
528 headline, this empty line is hidden when the subtree is folded.
529 Org-mode will leave (exactly) one empty line visible if the number of
530 empty lines is equal or larger to the number given in this variable.
531 So the default 2 means, at least 2 empty lines after the end of a subtree
532 are needed to produce free space between a collapsed subtree and the
533 following headline.
535 Special case: when 0, never leave empty lines in collapsed view."
536 :group 'org-cycle
537 :type 'integer)
539 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
540 org-cycle-hide-drawers
541 org-cycle-show-empty-lines
542 org-optimize-window-after-visibility-change)
543 "Hook that is run after `org-cycle' has changed the buffer visibility.
544 The function(s) in this hook must accept a single argument which indicates
545 the new state that was set by the most recent `org-cycle' command. The
546 argument is a symbol. After a global state change, it can have the values
547 `overview', `content', or `all'. After a local state change, it can have
548 the values `folded', `children', or `subtree'."
549 :group 'org-cycle
550 :type 'hook)
552 (defgroup org-edit-structure nil
553 "Options concerning structure editing in Org-mode."
554 :tag "Org Edit Structure"
555 :group 'org-structure)
557 (defcustom org-odd-levels-only nil
558 "Non-nil means, skip even levels and only use odd levels for the outline.
559 This has the effect that two stars are being added/taken away in
560 promotion/demotion commands. It also influences how levels are
561 handled by the exporters.
562 Changing it requires restart of `font-lock-mode' to become effective
563 for fontification also in regions already fontified.
564 You may also set this on a per-file basis by adding one of the following
565 lines to the buffer:
567 #+STARTUP: odd
568 #+STARTUP: oddeven"
569 :group 'org-edit-structure
570 :group 'org-font-lock
571 :type 'boolean)
573 (defcustom org-adapt-indentation t
574 "Non-nil means, adapt indentation when promoting and demoting.
575 When this is set and the *entire* text in an entry is indented, the
576 indentation is increased by one space in a demotion command, and
577 decreased by one in a promotion command. If any line in the entry
578 body starts at column 0, indentation is not changed at all."
579 :group 'org-edit-structure
580 :type 'boolean)
582 (defcustom org-special-ctrl-a/e nil
583 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
584 When t, `C-a' will bring back the cursor to the beginning of the
585 headline text, i.e. after the stars and after a possible TODO keyword.
586 In an item, this will be the position after the bullet.
587 When the cursor is already at that position, another `C-a' will bring
588 it to the beginning of the line.
589 `C-e' will jump to the end of the headline, ignoring the presence of tags
590 in the headline. A second `C-e' will then jump to the true end of the
591 line, after any tags.
592 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
593 and only a directly following, identical keypress will bring the cursor
594 to the special positions."
595 :group 'org-edit-structure
596 :type '(choice
597 (const :tag "off" nil)
598 (const :tag "after bullet first" t)
599 (const :tag "border first" reversed)))
601 (if (fboundp 'defvaralias)
602 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
604 (defcustom org-special-ctrl-k nil
605 "Non-nil means `C-k' will behave specially in headlines.
606 When nil, `C-k' will call the default `kill-line' command.
607 When t, the following will happen while the cursor is in the headline:
609 - When the cursor is at the beginning of a headline, kill the entire
610 line and possible the folded subtree below the line.
611 - When in the middle of the headline text, kill the headline up to the tags.
612 - When after the headline text, kill the tags."
613 :group 'org-edit-structure
614 :type 'boolean)
616 (defcustom org-M-RET-may-split-line '((default . t))
617 "Non-nil means, M-RET will split the line at the cursor position.
618 When nil, it will go to the end of the line before making a
619 new line.
620 You may also set this option in a different way for different
621 contexts. Valid contexts are:
623 headline when creating a new headline
624 item when creating a new item
625 table in a table field
626 default the value to be used for all contexts not explicitly
627 customized"
628 :group 'org-structure
629 :group 'org-table
630 :type '(choice
631 (const :tag "Always" t)
632 (const :tag "Never" nil)
633 (repeat :greedy t :tag "Individual contexts"
634 (cons
635 (choice :tag "Context"
636 (const headline)
637 (const item)
638 (const table)
639 (const default))
640 (boolean)))))
643 (defcustom org-blank-before-new-entry '((heading . nil)
644 (plain-list-item . nil))
645 "Should `org-insert-heading' leave a blank line before new heading/item?
646 The value is an alist, with `heading' and `plain-list-item' as car,
647 and a boolean flag as cdr."
648 :group 'org-edit-structure
649 :type '(list
650 (cons (const heading) (boolean))
651 (cons (const plain-list-item) (boolean))))
653 (defcustom org-insert-heading-hook nil
654 "Hook being run after inserting a new heading."
655 :group 'org-edit-structure
656 :type 'hook)
658 (defcustom org-enable-fixed-width-editor t
659 "Non-nil means, lines starting with \":\" are treated as fixed-width.
660 This currently only means, they are never auto-wrapped.
661 When nil, such lines will be treated like ordinary lines.
662 See also the QUOTE keyword."
663 :group 'org-edit-structure
664 :type 'boolean)
666 (defcustom org-goto-auto-isearch t
667 "Non-nil means, typing characters in org-goto starts incremental search."
668 :group 'org-edit-structure
669 :type 'boolean)
671 (defgroup org-sparse-trees nil
672 "Options concerning sparse trees in Org-mode."
673 :tag "Org Sparse Trees"
674 :group 'org-structure)
676 (defcustom org-highlight-sparse-tree-matches t
677 "Non-nil means, highlight all matches that define a sparse tree.
678 The highlights will automatically disappear the next time the buffer is
679 changed by an edit command."
680 :group 'org-sparse-trees
681 :type 'boolean)
683 (defcustom org-remove-highlights-with-change t
684 "Non-nil means, any change to the buffer will remove temporary highlights.
685 Such highlights are created by `org-occur' and `org-clock-display'.
686 When nil, `C-c C-c needs to be used to get rid of the highlights.
687 The highlights created by `org-preview-latex-fragment' always need
688 `C-c C-c' to be removed."
689 :group 'org-sparse-trees
690 :group 'org-time
691 :type 'boolean)
694 (defcustom org-occur-hook '(org-first-headline-recenter)
695 "Hook that is run after `org-occur' has constructed a sparse tree.
696 This can be used to recenter the window to show as much of the structure
697 as possible."
698 :group 'org-sparse-trees
699 :type 'hook)
701 (defgroup org-plain-lists nil
702 "Options concerning plain lists in Org-mode."
703 :tag "Org Plain lists"
704 :group 'org-structure)
706 (defcustom org-cycle-include-plain-lists nil
707 "Non-nil means, include plain lists into visibility cycling.
708 This means that during cycling, plain list items will *temporarily* be
709 interpreted as outline headlines with a level given by 1000+i where i is the
710 indentation of the bullet. In all other operations, plain list items are
711 not seen as headlines. For example, you cannot assign a TODO keyword to
712 such an item."
713 :group 'org-plain-lists
714 :type 'boolean)
716 (defcustom org-plain-list-ordered-item-terminator t
717 "The character that makes a line with leading number an ordered list item.
718 Valid values are ?. and ?\). To get both terminators, use t. While
719 ?. may look nicer, it creates the danger that a line with leading
720 number may be incorrectly interpreted as an item. ?\) therefore is
721 the safe choice."
722 :group 'org-plain-lists
723 :type '(choice (const :tag "dot like in \"2.\"" ?.)
724 (const :tag "paren like in \"2)\"" ?\))
725 (const :tab "both" t)))
727 (defcustom org-empty-line-terminates-plain-lists nil
728 "Non-nil means, an empty line ends all plain list levels.
729 When nil, empty lines are part of the preceeding item."
730 :group 'org-plain-lists
731 :type 'boolean)
733 (defcustom org-auto-renumber-ordered-lists t
734 "Non-nil means, automatically renumber ordered plain lists.
735 Renumbering happens when the sequence have been changed with
736 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
737 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
738 :group 'org-plain-lists
739 :type 'boolean)
741 (defcustom org-provide-checkbox-statistics t
742 "Non-nil means, update checkbox statistics after insert and toggle.
743 When this is set, checkbox statistics is updated each time you either insert
744 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
745 with \\[org-ctrl-c-ctrl-c\\]."
746 :group 'org-plain-lists
747 :type 'boolean)
750 (defgroup org-imenu-and-speedbar nil
751 "Options concerning imenu and speedbar in Org-mode."
752 :tag "Org Imenu and Speedbar"
753 :group 'org-structure)
755 (defcustom org-imenu-depth 2
756 "The maximum level for Imenu access to Org-mode headlines.
757 This also applied for speedbar access."
758 :group 'org-imenu-and-speedbar
759 :type 'number)
761 (defgroup org-table nil
762 "Options concerning tables in Org-mode."
763 :tag "Org Table"
764 :group 'org)
766 (defcustom org-enable-table-editor 'optimized
767 "Non-nil means, lines starting with \"|\" are handled by the table editor.
768 When nil, such lines will be treated like ordinary lines.
770 When equal to the symbol `optimized', the table editor will be optimized to
771 do the following:
772 - Automatic overwrite mode in front of whitespace in table fields.
773 This makes the structure of the table stay in tact as long as the edited
774 field does not exceed the column width.
775 - Minimize the number of realigns. Normally, the table is aligned each time
776 TAB or RET are pressed to move to another field. With optimization this
777 happens only if changes to a field might have changed the column width.
778 Optimization requires replacing the functions `self-insert-command',
779 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
780 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
781 very good at guessing when a re-align will be necessary, but you can always
782 force one with \\[org-ctrl-c-ctrl-c].
784 If you would like to use the optimized version in Org-mode, but the
785 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
787 This variable can be used to turn on and off the table editor during a session,
788 but in order to toggle optimization, a restart is required.
790 See also the variable `org-table-auto-blank-field'."
791 :group 'org-table
792 :type '(choice
793 (const :tag "off" nil)
794 (const :tag "on" t)
795 (const :tag "on, optimized" optimized)))
797 (defcustom org-table-tab-recognizes-table.el t
798 "Non-nil means, TAB will automatically notice a table.el table.
799 When it sees such a table, it moves point into it and - if necessary -
800 calls `table-recognize-table'."
801 :group 'org-table-editing
802 :type 'boolean)
804 (defgroup org-link nil
805 "Options concerning links in Org-mode."
806 :tag "Org Link"
807 :group 'org)
809 (defvar org-link-abbrev-alist-local nil
810 "Buffer-local version of `org-link-abbrev-alist', which see.
811 The value of this is taken from the #+LINK lines.")
812 (make-variable-buffer-local 'org-link-abbrev-alist-local)
814 (defcustom org-link-abbrev-alist nil
815 "Alist of link abbreviations.
816 The car of each element is a string, to be replaced at the start of a link.
817 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
818 links in Org-mode buffers can have an optional tag after a double colon, e.g.
820 [[linkkey:tag][description]]
822 If REPLACE is a string, the tag will simply be appended to create the link.
823 If the string contains \"%s\", the tag will be inserted there.
825 REPLACE may also be a function that will be called with the tag as the
826 only argument to create the link, which should be returned as a string.
828 See the manual for examples."
829 :group 'org-link
830 :type 'alist)
832 (defcustom org-descriptive-links t
833 "Non-nil means, hide link part and only show description of bracket links.
834 Bracket links are like [[link][descritpion]]. This variable sets the initial
835 state in new org-mode buffers. The setting can then be toggled on a
836 per-buffer basis from the Org->Hyperlinks menu."
837 :group 'org-link
838 :type 'boolean)
840 (defcustom org-link-file-path-type 'adaptive
841 "How the path name in file links should be stored.
842 Valid values are:
844 relative Relative to the current directory, i.e. the directory of the file
845 into which the link is being inserted.
846 absolute Absolute path, if possible with ~ for home directory.
847 noabbrev Absolute path, no abbreviation of home directory.
848 adaptive Use relative path for files in the current directory and sub-
849 directories of it. For other files, use an absolute path."
850 :group 'org-link
851 :type '(choice
852 (const relative)
853 (const absolute)
854 (const noabbrev)
855 (const adaptive)))
857 (defcustom org-activate-links '(bracket angle plain radio tag date)
858 "Types of links that should be activated in Org-mode files.
859 This is a list of symbols, each leading to the activation of a certain link
860 type. In principle, it does not hurt to turn on most link types - there may
861 be a small gain when turning off unused link types. The types are:
863 bracket The recommended [[link][description]] or [[link]] links with hiding.
864 angular Links in angular brackes that may contain whitespace like
865 <bbdb:Carsten Dominik>.
866 plain Plain links in normal text, no whitespace, like http://google.com.
867 radio Text that is matched by a radio target, see manual for details.
868 tag Tag settings in a headline (link to tag search).
869 date Time stamps (link to calendar).
871 Changing this variable requires a restart of Emacs to become effective."
872 :group 'org-link
873 :type '(set (const :tag "Double bracket links (new style)" bracket)
874 (const :tag "Angular bracket links (old style)" angular)
875 (const :tag "Plain text links" plain)
876 (const :tag "Radio target matches" radio)
877 (const :tag "Tags" tag)
878 (const :tag "Timestamps" date)))
880 (defcustom org-make-link-description-function nil
881 "Function to use to generate link descriptions from links. If
882 nil the link location will be used. This function must take two
883 parameters; the first is the link and the second the description
884 org-insert-link has generated, and should return the description
885 to use."
886 :group 'org-link
887 :type 'function)
889 (defgroup org-link-store nil
890 "Options concerning storing links in Org-mode."
891 :tag "Org Store Link"
892 :group 'org-link)
894 (defcustom org-email-link-description-format "Email %c: %.30s"
895 "Format of the description part of a link to an email or usenet message.
896 The following %-excapes will be replaced by corresponding information:
898 %F full \"From\" field
899 %f name, taken from \"From\" field, address if no name
900 %T full \"To\" field
901 %t first name in \"To\" field, address if no name
902 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
903 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
904 %s subject
905 %m message-id.
907 You may use normal field width specification between the % and the letter.
908 This is for example useful to limit the length of the subject.
910 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
911 :group 'org-link-store
912 :type 'string)
914 (defcustom org-from-is-user-regexp
915 (let (r1 r2)
916 (when (and user-mail-address (not (string= user-mail-address "")))
917 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
918 (when (and user-full-name (not (string= user-full-name "")))
919 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
920 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
921 "Regexp mached against the \"From:\" header of an email or usenet message.
922 It should match if the message is from the user him/herself."
923 :group 'org-link-store
924 :type 'regexp)
926 (defcustom org-context-in-file-links t
927 "Non-nil means, file links from `org-store-link' contain context.
928 A search string will be added to the file name with :: as separator and
929 used to find the context when the link is activated by the command
930 `org-open-at-point'.
931 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
932 negates this setting for the duration of the command."
933 :group 'org-link-store
934 :type 'boolean)
936 (defcustom org-keep-stored-link-after-insertion nil
937 "Non-nil means, keep link in list for entire session.
939 The command `org-store-link' adds a link pointing to the current
940 location to an internal list. These links accumulate during a session.
941 The command `org-insert-link' can be used to insert links into any
942 Org-mode file (offering completion for all stored links). When this
943 option is nil, every link which has been inserted once using \\[org-insert-link]
944 will be removed from the list, to make completing the unused links
945 more efficient."
946 :group 'org-link-store
947 :type 'boolean)
949 (defgroup org-link-follow nil
950 "Options concerning following links in Org-mode."
951 :tag "Org Follow Link"
952 :group 'org-link)
954 (defcustom org-follow-link-hook nil
955 "Hook that is run after a link has been followed."
956 :group 'org-link-follow
957 :type 'hook)
959 (defcustom org-tab-follows-link nil
960 "Non-nil means, on links TAB will follow the link.
961 Needs to be set before org.el is loaded."
962 :group 'org-link-follow
963 :type 'boolean)
965 (defcustom org-return-follows-link nil
966 "Non-nil means, on links RET will follow the link.
967 Needs to be set before org.el is loaded."
968 :group 'org-link-follow
969 :type 'boolean)
971 (defcustom org-mouse-1-follows-link
972 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
973 "Non-nil means, mouse-1 on a link will follow the link.
974 A longer mouse click will still set point. Does not work on XEmacs.
975 Needs to be set before org.el is loaded."
976 :group 'org-link-follow
977 :type 'boolean)
979 (defcustom org-mark-ring-length 4
980 "Number of different positions to be recorded in the ring
981 Changing this requires a restart of Emacs to work correctly."
982 :group 'org-link-follow
983 :type 'interger)
985 (defcustom org-link-frame-setup
986 '((vm . vm-visit-folder-other-frame)
987 (gnus . gnus-other-frame)
988 (file . find-file-other-window))
989 "Setup the frame configuration for following links.
990 When following a link with Emacs, it may often be useful to display
991 this link in another window or frame. This variable can be used to
992 set this up for the different types of links.
993 For VM, use any of
994 `vm-visit-folder'
995 `vm-visit-folder-other-frame'
996 For Gnus, use any of
997 `gnus'
998 `gnus-other-frame'
999 For FILE, use any of
1000 `find-file'
1001 `find-file-other-window'
1002 `find-file-other-frame'
1003 For the calendar, use the variable `calendar-setup'.
1004 For BBDB, it is currently only possible to display the matches in
1005 another window."
1006 :group 'org-link-follow
1007 :type '(list
1008 (cons (const vm)
1009 (choice
1010 (const vm-visit-folder)
1011 (const vm-visit-folder-other-window)
1012 (const vm-visit-folder-other-frame)))
1013 (cons (const gnus)
1014 (choice
1015 (const gnus)
1016 (const gnus-other-frame)))
1017 (cons (const file)
1018 (choice
1019 (const find-file)
1020 (const find-file-other-window)
1021 (const find-file-other-frame)))))
1023 (defcustom org-display-internal-link-with-indirect-buffer nil
1024 "Non-nil means, use indirect buffer to display infile links.
1025 Activating internal links (from one location in a file to another location
1026 in the same file) normally just jumps to the location. When the link is
1027 activated with a C-u prefix (or with mouse-3), the link is displayed in
1028 another window. When this option is set, the other window actually displays
1029 an indirect buffer clone of the current buffer, to avoid any visibility
1030 changes to the current buffer."
1031 :group 'org-link-follow
1032 :type 'boolean)
1034 (defcustom org-open-non-existing-files nil
1035 "Non-nil means, `org-open-file' will open non-existing files.
1036 When nil, an error will be generated."
1037 :group 'org-link-follow
1038 :type 'boolean)
1040 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1041 "Function and arguments to call for following mailto links.
1042 This is a list with the first element being a lisp function, and the
1043 remaining elements being arguments to the function. In string arguments,
1044 %a will be replaced by the address, and %s will be replaced by the subject
1045 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1046 :group 'org-link-follow
1047 :type '(choice
1048 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1049 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1050 (const :tag "message-mail" (message-mail "%a" "%s"))
1051 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1053 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1054 "Non-nil means, ask for confirmation before executing shell links.
1055 Shell links can be dangerous: just think about a link
1057 [[shell:rm -rf ~/*][Google Search]]
1059 This link would show up in your Org-mode document as \"Google Search\",
1060 but really it would remove your entire home directory.
1061 Therefore we advise against setting this variable to nil.
1062 Just change it to `y-or-n-p' of you want to confirm with a
1063 single keystroke rather than having to type \"yes\"."
1064 :group 'org-link-follow
1065 :type '(choice
1066 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1067 (const :tag "with y-or-n (faster)" y-or-n-p)
1068 (const :tag "no confirmation (dangerous)" nil)))
1070 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1071 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1072 Elisp links can be dangerous: just think about a link
1074 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1076 This link would show up in your Org-mode document as \"Google Search\",
1077 but really it would remove your entire home directory.
1078 Therefore we advise against setting this variable to nil.
1079 Just change it to `y-or-n-p' of you want to confirm with a
1080 single keystroke rather than having to type \"yes\"."
1081 :group 'org-link-follow
1082 :type '(choice
1083 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1084 (const :tag "with y-or-n (faster)" y-or-n-p)
1085 (const :tag "no confirmation (dangerous)" nil)))
1087 (defconst org-file-apps-defaults-gnu
1088 '((remote . emacs)
1089 (t . mailcap))
1090 "Default file applications on a UNIX or GNU/Linux system.
1091 See `org-file-apps'.")
1093 (defconst org-file-apps-defaults-macosx
1094 '((remote . emacs)
1095 (t . "open %s")
1096 ("ps" . "gv %s")
1097 ("ps.gz" . "gv %s")
1098 ("eps" . "gv %s")
1099 ("eps.gz" . "gv %s")
1100 ("dvi" . "xdvi %s")
1101 ("fig" . "xfig %s"))
1102 "Default file applications on a MacOS X system.
1103 The system \"open\" is known as a default, but we use X11 applications
1104 for some files for which the OS does not have a good default.
1105 See `org-file-apps'.")
1107 (defconst org-file-apps-defaults-windowsnt
1108 (list
1109 '(remote . emacs)
1110 (cons t
1111 (list (if (featurep 'xemacs)
1112 'mswindows-shell-execute
1113 'w32-shell-execute)
1114 "open" 'file)))
1115 "Default file applications on a Windows NT system.
1116 The system \"open\" is used for most files.
1117 See `org-file-apps'.")
1119 (defcustom org-file-apps
1121 ("txt" . emacs)
1122 ("tex" . emacs)
1123 ("ltx" . emacs)
1124 ("org" . emacs)
1125 ("el" . emacs)
1126 ("bib" . emacs)
1128 "External applications for opening `file:path' items in a document.
1129 Org-mode uses system defaults for different file types, but
1130 you can use this variable to set the application for a given file
1131 extension. The entries in this list are cons cells where the car identifies
1132 files and the cdr the corresponding command. Possible values for the
1133 file identifier are
1134 \"ext\" A string identifying an extension
1135 `directory' Matches a directory
1136 `remote' Matches a remote file, accessible through tramp or efs.
1137 Remote files most likely should be visited through Emacs
1138 because external applications cannot handle such paths.
1139 t Default for all remaining files
1141 Possible values for the command are:
1142 `emacs' The file will be visited by the current Emacs process.
1143 `default' Use the default application for this file type.
1144 string A command to be executed by a shell; %s will be replaced
1145 by the path to the file.
1146 sexp A Lisp form which will be evaluated. The file path will
1147 be available in the Lisp variable `file'.
1148 For more examples, see the system specific constants
1149 `org-file-apps-defaults-macosx'
1150 `org-file-apps-defaults-windowsnt'
1151 `org-file-apps-defaults-gnu'."
1152 :group 'org-link-follow
1153 :type '(repeat
1154 (cons (choice :value ""
1155 (string :tag "Extension")
1156 (const :tag "Default for unrecognized files" t)
1157 (const :tag "Remote file" remote)
1158 (const :tag "Links to a directory" directory))
1159 (choice :value ""
1160 (const :tag "Visit with Emacs" emacs)
1161 (const :tag "Use system default" default)
1162 (string :tag "Command")
1163 (sexp :tag "Lisp form")))))
1165 (defgroup org-refile nil
1166 "Options concerning refiling entries in Org-mode."
1167 :tag "Org Remember"
1168 :group 'org)
1170 (defcustom org-directory "~/org"
1171 "Directory with org files.
1172 This directory will be used as default to prompt for org files.
1173 Used by the hooks for remember.el."
1174 :group 'org-refile
1175 :group 'org-remember
1176 :type 'directory)
1178 (defcustom org-default-notes-file "~/.notes"
1179 "Default target for storing notes.
1180 Used by the hooks for remember.el. This can be a string, or nil to mean
1181 the value of `remember-data-file'.
1182 You can set this on a per-template basis with the variable
1183 `org-remember-templates'."
1184 :group 'org-refile
1185 :group 'org-remember
1186 :type '(choice
1187 (const :tag "Default from remember-data-file" nil)
1188 file))
1190 (defcustom org-goto-interface 'outline
1191 "The default interface to be used for `org-goto'.
1192 Allowed vaues are:
1193 outline The interface shows an outline of the relevant file
1194 and the correct heading is found by moving through
1195 the outline or by searching with incremental search.
1196 outline-path-completion Headlines in the current buffer are offered via
1197 completion."
1198 :group 'org-refile
1199 :type '(choice
1200 (const :tag "Outline" outline)
1201 (const :tag "Outline-path-completion" outline-path-completion)))
1203 (defcustom org-reverse-note-order nil
1204 "Non-nil means, store new notes at the beginning of a file or entry.
1205 When nil, new notes will be filed to the end of a file or entry.
1206 This can also be a list with cons cells of regular expressions that
1207 are matched against file names, and values."
1208 :group 'org-remember
1209 :type '(choice
1210 (const :tag "Reverse always" t)
1211 (const :tag "Reverse never" nil)
1212 (repeat :tag "By file name regexp"
1213 (cons regexp boolean))))
1215 (defcustom org-refile-targets nil
1216 "Targets for refiling entries with \\[org-refile].
1217 This is list of cons cells. Each cell contains:
1218 - a specification of the files to be considered, either a list of files,
1219 or a symbol whose function or variable value will be used to retrieve
1220 a file name or a list of file names. Nil means, refile to a different
1221 heading in the current buffer.
1222 - A specification of how to find candidate refile targets. This may be
1223 any of
1224 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1225 This tag has to be present in all target headlines, inheritance will
1226 not be considered.
1227 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1228 todo keyword.
1229 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1230 headlines that are refiling targets.
1231 - a cons cell (:level . N). Any headline of level N is considered a target.
1232 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1233 :group 'org-remember
1234 :type '(repeat
1235 (cons
1236 (choice :value org-agenda-files
1237 (const :tag "All agenda files" org-agenda-files)
1238 (const :tag "Current buffer" nil)
1239 (function) (variable) (file))
1240 (choice :tag "Identify target headline by"
1241 (cons :tag "Specific tag" (const :tag) (string))
1242 (cons :tag "TODO keyword" (const :todo) (string))
1243 (cons :tag "Regular expression" (const :regexp) (regexp))
1244 (cons :tag "Level number" (const :level) (integer))
1245 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1247 (defcustom org-refile-use-outline-path nil
1248 "Non-nil means, provide refile targets as paths.
1249 So a level 3 headline will be available as level1/level2/level3.
1250 When the value is `file', also include the file name (without directory)
1251 into the path. When `full-file-path', include the full file path."
1252 :group 'org-remember
1253 :type '(choice
1254 (const :tag "Not" nil)
1255 (const :tag "Yes" t)
1256 (const :tag "Start with file name" file)
1257 (const :tag "Start with full file path" full-file-path)))
1259 (defgroup org-todo nil
1260 "Options concerning TODO items in Org-mode."
1261 :tag "Org TODO"
1262 :group 'org)
1264 (defgroup org-progress nil
1265 "Options concerning Progress logging in Org-mode."
1266 :tag "Org Progress"
1267 :group 'org-time)
1269 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1270 "List of TODO entry keyword sequences and their interpretation.
1271 \\<org-mode-map>This is a list of sequences.
1273 Each sequence starts with a symbol, either `sequence' or `type',
1274 indicating if the keywords should be interpreted as a sequence of
1275 action steps, or as different types of TODO items. The first
1276 keywords are states requiring action - these states will select a headline
1277 for inclusion into the global TODO list Org-mode produces. If one of
1278 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1279 signify that no further action is necessary. If \"|\" is not found,
1280 the last keyword is treated as the only DONE state of the sequence.
1282 The command \\[org-todo] cycles an entry through these states, and one
1283 additional state where no keyword is present. For details about this
1284 cycling, see the manual.
1286 TODO keywords and interpretation can also be set on a per-file basis with
1287 the special #+SEQ_TODO and #+TYP_TODO lines.
1289 Each keyword can optionally specify a character for fast state selection
1290 \(in combination with the variable `org-use-fast-todo-selection')
1291 and specifiers for state change logging, using the same syntax
1292 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1293 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1294 indicates to record a time stamp each time this state is selected.
1296 Each keyword may also specify if a timestamp or a note should be
1297 recorded when entering or leaving the state, by adding additional
1298 characters in the parenthesis after the keyword. This looks like this:
1299 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1300 record only the time of the state change. With X and Y being either
1301 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1302 Y when leaving the state if and only if the *target* state does not
1303 define X. You may omit any of the fast-selection key or X or /Y,
1304 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1306 For backward compatibility, this variable may also be just a list
1307 of keywords - in this case the interptetation (sequence or type) will be
1308 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1309 :group 'org-todo
1310 :group 'org-keywords
1311 :type '(choice
1312 (repeat :tag "Old syntax, just keywords"
1313 (string :tag "Keyword"))
1314 (repeat :tag "New syntax"
1315 (cons
1316 (choice
1317 :tag "Interpretation"
1318 (const :tag "Sequence (cycling hits every state)" sequence)
1319 (const :tag "Type (cycling directly to DONE)" type))
1320 (repeat
1321 (string :tag "Keyword"))))))
1323 (defvar org-todo-keywords-1 nil
1324 "All TODO and DONE keywords active in a buffer.")
1325 (make-variable-buffer-local 'org-todo-keywords-1)
1326 (defvar org-todo-keywords-for-agenda nil)
1327 (defvar org-done-keywords-for-agenda nil)
1328 (defvar org-agenda-contributing-files nil)
1329 (defvar org-not-done-keywords nil)
1330 (make-variable-buffer-local 'org-not-done-keywords)
1331 (defvar org-done-keywords nil)
1332 (make-variable-buffer-local 'org-done-keywords)
1333 (defvar org-todo-heads nil)
1334 (make-variable-buffer-local 'org-todo-heads)
1335 (defvar org-todo-sets nil)
1336 (make-variable-buffer-local 'org-todo-sets)
1337 (defvar org-todo-log-states nil)
1338 (make-variable-buffer-local 'org-todo-log-states)
1339 (defvar org-todo-kwd-alist nil)
1340 (make-variable-buffer-local 'org-todo-kwd-alist)
1341 (defvar org-todo-key-alist nil)
1342 (make-variable-buffer-local 'org-todo-key-alist)
1343 (defvar org-todo-key-trigger nil)
1344 (make-variable-buffer-local 'org-todo-key-trigger)
1346 (defcustom org-todo-interpretation 'sequence
1347 "Controls how TODO keywords are interpreted.
1348 This variable is in principle obsolete and is only used for
1349 backward compatibility, if the interpretation of todo keywords is
1350 not given already in `org-todo-keywords'. See that variable for
1351 more information."
1352 :group 'org-todo
1353 :group 'org-keywords
1354 :type '(choice (const sequence)
1355 (const type)))
1357 (defcustom org-use-fast-todo-selection 'prefix
1358 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1359 This variable describes if and under what circumstances the cycling
1360 mechanism for TODO keywords will be replaced by a single-key, direct
1361 selection scheme.
1363 When nil, fast selection is never used.
1365 When the symbol `prefix', it will be used when `org-todo' is called with
1366 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1367 in an agenda buffer.
1369 When t, fast selection is used by default. In this case, the prefix
1370 argument forces cycling instead.
1372 In all cases, the special interface is only used if access keys have actually
1373 been assigned by the user, i.e. if keywords in the configuration are followed
1374 by a letter in parenthesis, like TODO(t)."
1375 :group 'org-todo
1376 :type '(choice
1377 (const :tag "Never" nil)
1378 (const :tag "By default" t)
1379 (const :tag "Only with C-u C-c C-t" prefix)))
1381 (defcustom org-after-todo-state-change-hook nil
1382 "Hook which is run after the state of a TODO item was changed.
1383 The new state (a string with a TODO keyword, or nil) is available in the
1384 Lisp variable `state'."
1385 :group 'org-todo
1386 :type 'hook)
1388 (defcustom org-log-done nil
1389 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1390 When equal to the list (done), also prompt for a closing note.
1391 This can also be configured on a per-file basis by adding one of
1392 the following lines anywhere in the buffer:
1394 #+STARTUP: logdone
1395 #+STARTUP: lognotedone
1396 #+STARTUP: nologdone"
1397 :group 'org-todo
1398 :group 'org-progress
1399 :type '(choice
1400 (const :tag "No logging" nil)
1401 (const :tag "Record CLOSED timestamp" time)
1402 (const :tag "Record CLOSED timestamp with closing note." note)))
1404 ;; Normalize old uses of org-log-done.
1405 (cond
1406 ((eq org-log-done t) (setq org-log-done 'time))
1407 ((and (listp org-log-done) (memq 'done org-log-done))
1408 (setq org-log-done 'note)))
1410 (defcustom org-log-note-clock-out nil
1411 "Non-nil means, recored a note when clocking out of an item.
1412 This can also be configured on a per-file basis by adding one of
1413 the following lines anywhere in the buffer:
1415 #+STARTUP: lognoteclock-out
1416 #+STARTUP: nolognoteclock-out"
1417 :group 'org-todo
1418 :group 'org-progress
1419 :type 'boolean)
1421 (defcustom org-log-done-with-time t
1422 "Non-nil means, the CLOSED time stamp will contain date and time.
1423 When nil, only the date will be recorded."
1424 :group 'org-progress
1425 :type 'boolean)
1427 (defcustom org-log-note-headings
1428 '((done . "CLOSING NOTE %t")
1429 (state . "State %-12s %t")
1430 (note . "Note taken on %t")
1431 (clock-out . ""))
1432 "Headings for notes added to entries.
1433 The value is an alist, with the car being a symbol indicating the note
1434 context, and the cdr is the heading to be used. The heading may also be the
1435 empty string.
1436 %t in the heading will be replaced by a time stamp.
1437 %s will be replaced by the new TODO state, in double quotes.
1438 %u will be replaced by the user name.
1439 %U will be replaced by the full user name."
1440 :group 'org-todo
1441 :group 'org-progress
1442 :type '(list :greedy t
1443 (cons (const :tag "Heading when closing an item" done) string)
1444 (cons (const :tag
1445 "Heading when changing todo state (todo sequence only)"
1446 state) string)
1447 (cons (const :tag "Heading when just taking a note" note) string)
1448 (cons (const :tag "Heading when clocking out" clock-out) string)))
1450 (unless (assq 'note org-log-note-headings)
1451 (push '(note . "%t") org-log-note-headings))
1453 (defcustom org-log-states-order-reversed t
1454 "Non-nil means, the latest state change note will be directly after heading.
1455 When nil, the notes will be orderer according to time."
1456 :group 'org-todo
1457 :group 'org-progress
1458 :type 'boolean)
1460 (defcustom org-log-repeat 'time
1461 "Non-nil means, record moving through the DONE state when triggering repeat.
1462 An auto-repeating tasks is immediately switched back to TODO when marked
1463 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1464 the TODO keyword definition, or recording a cloing note by setting
1465 `org-log-done', there will be no record of the task moving trhough DONE.
1466 This variable forces taking a note anyway. Possible values are:
1468 nil Don't force a record
1469 time Record a time stamp
1470 note Record a note
1472 This option can also be set with on a per-file-basis with
1474 #+STARTUP: logrepeat
1475 #+STARTUP: lognoterepeat
1476 #+STARTUP: nologrepeat
1478 You can have local logging settings for a subtree by setting the LOGGING
1479 property to one or more of these keywords."
1480 :group 'org-todo
1481 :group 'org-progress
1482 :type '(choice
1483 (const :tag "Don't force a record" nil)
1484 (const :tag "Force recording the DONE state" time)
1485 (const :tag "Force recording a note with the DONE state" note)))
1488 (defgroup org-priorities nil
1489 "Priorities in Org-mode."
1490 :tag "Org Priorities"
1491 :group 'org-todo)
1493 (defcustom org-highest-priority ?A
1494 "The highest priority of TODO items. A character like ?A, ?B etc.
1495 Must have a smaller ASCII number than `org-lowest-priority'."
1496 :group 'org-priorities
1497 :type 'character)
1499 (defcustom org-lowest-priority ?C
1500 "The lowest priority of TODO items. A character like ?A, ?B etc.
1501 Must have a larger ASCII number than `org-highest-priority'."
1502 :group 'org-priorities
1503 :type 'character)
1505 (defcustom org-default-priority ?B
1506 "The default priority of TODO items.
1507 This is the priority an item get if no explicit priority is given."
1508 :group 'org-priorities
1509 :type 'character)
1511 (defcustom org-priority-start-cycle-with-default t
1512 "Non-nil means, start with default priority when starting to cycle.
1513 When this is nil, the first step in the cycle will be (depending on the
1514 command used) one higher or lower that the default priority."
1515 :group 'org-priorities
1516 :type 'boolean)
1518 (defgroup org-time nil
1519 "Options concerning time stamps and deadlines in Org-mode."
1520 :tag "Org Time"
1521 :group 'org)
1523 (defcustom org-insert-labeled-timestamps-at-point nil
1524 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1525 When nil, these labeled time stamps are forces into the second line of an
1526 entry, just after the headline. When scheduling from the global TODO list,
1527 the time stamp will always be forced into the second line."
1528 :group 'org-time
1529 :type 'boolean)
1531 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1532 "Formats for `format-time-string' which are used for time stamps.
1533 It is not recommended to change this constant.")
1535 (defcustom org-time-stamp-rounding-minutes '(0 5)
1536 "Number of minutes to round time stamps to.
1537 These are two values, the first applies when first creating a time stamp.
1538 The second applies when changing it with the commands `S-up' and `S-down'.
1539 When changing the time stamp, this means that it will change in steps
1540 of N minutes, as given by the second value.
1542 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1543 numbers should be factors of 60, so for example 5, 10, 15.
1545 When this is larger than 1, you can still force an exact time-stamp by using
1546 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1547 and by using a prefix arg to `S-up/down' to specify the exact number
1548 of minutes to shift."
1549 :group 'org-time
1550 :get '(lambda (var) ; Make sure all entries have 5 elements
1551 (if (integerp (default-value var))
1552 (list (default-value var) 5)
1553 (default-value var)))
1554 :type '(list
1555 (integer :tag "when inserting times")
1556 (integer :tag "when modifying times")))
1558 ;; Normalize old customizations of this variable.
1559 (when (integerp org-time-stamp-rounding-minutes)
1560 (setq org-time-stamp-rounding-minutes
1561 (list org-time-stamp-rounding-minutes
1562 org-time-stamp-rounding-minutes)))
1564 (defcustom org-display-custom-times nil
1565 "Non-nil means, overlay custom formats over all time stamps.
1566 The formats are defined through the variable `org-time-stamp-custom-formats'.
1567 To turn this on on a per-file basis, insert anywhere in the file:
1568 #+STARTUP: customtime"
1569 :group 'org-time
1570 :set 'set-default
1571 :type 'sexp)
1572 (make-variable-buffer-local 'org-display-custom-times)
1574 (defcustom org-time-stamp-custom-formats
1575 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1576 "Custom formats for time stamps. See `format-time-string' for the syntax.
1577 These are overlayed over the default ISO format if the variable
1578 `org-display-custom-times' is set. Time like %H:%M should be at the
1579 end of the second format."
1580 :group 'org-time
1581 :type 'sexp)
1583 (defun org-time-stamp-format (&optional long inactive)
1584 "Get the right format for a time string."
1585 (let ((f (if long (cdr org-time-stamp-formats)
1586 (car org-time-stamp-formats))))
1587 (if inactive
1588 (concat "[" (substring f 1 -1) "]")
1589 f)))
1591 (defcustom org-deadline-warning-days 14
1592 "No. of days before expiration during which a deadline becomes active.
1593 This variable governs the display in sparse trees and in the agenda.
1594 When 0 or negative, it means use this number (the absolute value of it)
1595 even if a deadline has a different individual lead time specified."
1596 :group 'org-time
1597 :group 'org-agenda-daily/weekly
1598 :type 'number)
1600 (defcustom org-read-date-prefer-future t
1601 "Non-nil means, assume future for incomplete date input from user.
1602 This affects the following situations:
1603 1. The user gives a day, but no month.
1604 For example, if today is the 15th, and you enter \"3\", Org-mode will
1605 read this as the third of *next* month. However, if you enter \"17\",
1606 it will be considered as *this* month.
1607 2. The user gives a month but not a year.
1608 For example, if it is april and you enter \"feb 2\", this will be read
1609 as feb 2, *next* year. \"May 5\", however, will be this year.
1611 Currently this does not work for ISO week specifications.
1613 When this option is nil, the current month and year will always be used
1614 as defaults."
1615 :group 'org-time
1616 :type 'boolean)
1618 (defcustom org-read-date-display-live t
1619 "Non-nil means, display current interpretation of date prompt live.
1620 This display will be in an overlay, in the minibuffer."
1621 :group 'org-time
1622 :type 'boolean)
1624 (defcustom org-read-date-popup-calendar t
1625 "Non-nil means, pop up a calendar when prompting for a date.
1626 In the calendar, the date can be selected with mouse-1. However, the
1627 minibuffer will also be active, and you can simply enter the date as well.
1628 When nil, only the minibuffer will be available."
1629 :group 'org-time
1630 :type 'boolean)
1631 (if (fboundp 'defvaralias)
1632 (defvaralias 'org-popup-calendar-for-date-prompt
1633 'org-read-date-popup-calendar))
1635 (defcustom org-extend-today-until 0
1636 "The hour when your day really ends.
1637 This has influence for the following applications:
1638 - When switching the agenda to \"today\". It it is still earlier than
1639 the time given here, the day recognized as TODAY is actually yesterday.
1640 - When a date is read from the user and it is still before the time given
1641 here, the current date and time will be assumed to be yesterday, 23:59.
1643 FIXME:
1644 IMPORTANT: This is still a very experimental feature, it may disappear
1645 again or it may be extended to mean more things."
1646 :group 'org-time
1647 :type 'number)
1649 (defcustom org-edit-timestamp-down-means-later nil
1650 "Non-nil means, S-down will increase the time in a time stamp.
1651 When nil, S-up will increase."
1652 :group 'org-time
1653 :type 'boolean)
1655 (defcustom org-calendar-follow-timestamp-change t
1656 "Non-nil means, make the calendar window follow timestamp changes.
1657 When a timestamp is modified and the calendar window is visible, it will be
1658 moved to the new date."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defgroup org-tags nil
1663 "Options concerning tags in Org-mode."
1664 :tag "Org Tags"
1665 :group 'org)
1667 (defcustom org-tag-alist nil
1668 "List of tags allowed in Org-mode files.
1669 When this list is nil, Org-mode will base TAG input on what is already in the
1670 buffer.
1671 The value of this variable is an alist, the car of each entry must be a
1672 keyword as a string, the cdr may be a character that is used to select
1673 that tag through the fast-tag-selection interface.
1674 See the manual for details."
1675 :group 'org-tags
1676 :type '(repeat
1677 (choice
1678 (cons (string :tag "Tag name")
1679 (character :tag "Access char"))
1680 (const :tag "Start radio group" (:startgroup))
1681 (const :tag "End radio group" (:endgroup)))))
1683 (defcustom org-use-fast-tag-selection 'auto
1684 "Non-nil means, use fast tag selection scheme.
1685 This is a special interface to select and deselect tags with single keys.
1686 When nil, fast selection is never used.
1687 When the symbol `auto', fast selection is used if and only if selection
1688 characters for tags have been configured, either through the variable
1689 `org-tag-alist' or through a #+TAGS line in the buffer.
1690 When t, fast selection is always used and selection keys are assigned
1691 automatically if necessary."
1692 :group 'org-tags
1693 :type '(choice
1694 (const :tag "Always" t)
1695 (const :tag "Never" nil)
1696 (const :tag "When selection characters are configured" 'auto)))
1698 (defcustom org-fast-tag-selection-single-key nil
1699 "Non-nil means, fast tag selection exits after first change.
1700 When nil, you have to press RET to exit it.
1701 During fast tag selection, you can toggle this flag with `C-c'.
1702 This variable can also have the value `expert'. In this case, the window
1703 displaying the tags menu is not even shown, until you press C-c again."
1704 :group 'org-tags
1705 :type '(choice
1706 (const :tag "No" nil)
1707 (const :tag "Yes" t)
1708 (const :tag "Expert" expert)))
1710 (defvar org-fast-tag-selection-include-todo nil
1711 "Non-nil means, fast tags selection interface will also offer TODO states.
1712 This is an undocumented feature, you should not rely on it.")
1714 (defcustom org-tags-column -80
1715 "The column to which tags should be indented in a headline.
1716 If this number is positive, it specifies the column. If it is negative,
1717 it means that the tags should be flushright to that column. For example,
1718 -80 works well for a normal 80 character screen."
1719 :group 'org-tags
1720 :type 'integer)
1722 (defcustom org-auto-align-tags t
1723 "Non-nil means, realign tags after pro/demotion of TODO state change.
1724 These operations change the length of a headline and therefore shift
1725 the tags around. With this options turned on, after each such operation
1726 the tags are again aligned to `org-tags-column'."
1727 :group 'org-tags
1728 :type 'boolean)
1730 (defcustom org-use-tag-inheritance t
1731 "Non-nil means, tags in levels apply also for sublevels.
1732 When nil, only the tags directly given in a specific line apply there.
1733 If you turn off this option, you very likely want to turn on the
1734 companion option `org-tags-match-list-sublevels'.
1736 This may also be a list of tags that should be inherited, or a regexp that
1737 matches tags that should be inherited."
1738 :group 'org-tags
1739 :type '(choice
1740 (const :tag "Not" nil)
1741 (const :tag "Always" t)
1742 (repeat :tag "Specific tags" (string :tag "Tag"))
1743 (regexp :tag "Tags matched by regexp")))
1745 (defun org-tag-inherit-p (tag)
1746 "Check if TAG is one that should be inherited."
1747 (cond
1748 ((eq org-use-tag-inheritance t) t)
1749 ((not org-use-tag-inheritance) nil)
1750 ((stringp org-use-tag-inheritance)
1751 (string-match org-use-tag-inheritance tag))
1752 ((listp org-use-tag-inheritance)
1753 (member tag org-use-tag-inheritance))
1754 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1756 (defcustom org-tags-match-list-sublevels nil
1757 "Non-nil means list also sublevels of headlines matching tag search.
1758 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1759 the sublevels of a headline matching a tag search often also match
1760 the same search. Listing all of them can create very long lists.
1761 Setting this variable to nil causes subtrees of a match to be skipped.
1762 This option is off by default, because inheritance in on. If you turn
1763 inheritance off, you very likely want to turn this option on.
1765 As a special case, if the tag search is restricted to TODO items, the
1766 value of this variable is ignored and sublevels are always checked, to
1767 make sure all corresponding TODO items find their way into the list."
1768 :group 'org-tags
1769 :type 'boolean)
1771 (defvar org-tags-history nil
1772 "History of minibuffer reads for tags.")
1773 (defvar org-last-tags-completion-table nil
1774 "The last used completion table for tags.")
1775 (defvar org-after-tags-change-hook nil
1776 "Hook that is run after the tags in a line have changed.")
1778 (defgroup org-properties nil
1779 "Options concerning properties in Org-mode."
1780 :tag "Org Properties"
1781 :group 'org)
1783 (defcustom org-property-format "%-10s %s"
1784 "How property key/value pairs should be formatted by `indent-line'.
1785 When `indent-line' hits a property definition, it will format the line
1786 according to this format, mainly to make sure that the values are
1787 lined-up with respect to each other."
1788 :group 'org-properties
1789 :type 'string)
1791 (defcustom org-use-property-inheritance nil
1792 "Non-nil means, properties apply also for sublevels.
1794 This setting is chiefly used during property searches. Turning it on can
1795 cause significant overhead when doing a search, which is why it is not
1796 on by default.
1798 When nil, only the properties directly given in the current entry count.
1799 When t, every property is inherited. The value may also be a list of
1800 properties that should have inheritance, or a regular expression matching
1801 properties that should be inherited.
1803 However, note that some special properties use inheritance under special
1804 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1805 and the properties ending in \"_ALL\" when they are used as descriptor
1806 for valid values of a property.
1808 Note for programmers:
1809 When querying an entry with `org-entry-get', you can control if inheritance
1810 should be used. By default, `org-entry-get' looks only at the local
1811 properties. You can request inheritance by setting the inherit argument
1812 to t (to force inheritance) or to `selective' (to respect the setting
1813 in this variable)."
1814 :group 'org-properties
1815 :type '(choice
1816 (const :tag "Not" nil)
1817 (const :tag "Always" t)
1818 (repeat :tag "Specific properties" (string :tag "Property"))
1819 (regexp :tag "Properties matched by regexp")))
1821 (defun org-property-inherit-p (property)
1822 "Check if PROPERTY is one that should be inherited."
1823 (cond
1824 ((eq org-use-property-inheritance t) t)
1825 ((not org-use-property-inheritance) nil)
1826 ((stringp org-use-property-inheritance)
1827 (string-match org-use-property-inheritance property))
1828 ((listp org-use-property-inheritance)
1829 (member property org-use-property-inheritance))
1830 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1832 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1833 "The default column format, if no other format has been defined.
1834 This variable can be set on the per-file basis by inserting a line
1836 #+COLUMNS: %25ITEM ....."
1837 :group 'org-properties
1838 :type 'string)
1840 (defcustom org-effort-property "Effort"
1841 "The property that is being used to keep track of effort estimates.
1842 Effort estimates given in this property need to have the format H:MM."
1843 :group 'org-properties
1844 :group 'org-progress
1845 :type '(string :tag "Property"))
1847 (defcustom org-global-properties nil
1848 "List of property/value pairs that can be inherited by any entry.
1849 You can set buffer-local values for this by adding lines like
1851 #+PROPERTY: NAME VALUE"
1852 :group 'org-properties
1853 :type '(repeat
1854 (cons (string :tag "Property")
1855 (string :tag "Value"))))
1857 (defvar org-local-properties nil
1858 "List of property/value pairs that can be inherited by any entry.
1859 Valid for the current buffer.
1860 This variable is populated from #+PROPERTY lines.")
1862 (defgroup org-agenda nil
1863 "Options concerning agenda views in Org-mode."
1864 :tag "Org Agenda"
1865 :group 'org)
1867 (defvar org-category nil
1868 "Variable used by org files to set a category for agenda display.
1869 Such files should use a file variable to set it, for example
1871 # -*- mode: org; org-category: \"ELisp\"
1873 or contain a special line
1875 #+CATEGORY: ELisp
1877 If the file does not specify a category, then file's base name
1878 is used instead.")
1879 (make-variable-buffer-local 'org-category)
1881 (defcustom org-agenda-files nil
1882 "The files to be used for agenda display.
1883 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1884 \\[org-remove-file]. You can also use customize to edit the list.
1886 If an entry is a directory, all files in that directory that are matched by
1887 `org-agenda-file-regexp' will be part of the file list.
1889 If the value of the variable is not a list but a single file name, then
1890 the list of agenda files is actually stored and maintained in that file, one
1891 agenda file per line."
1892 :group 'org-agenda
1893 :type '(choice
1894 (repeat :tag "List of files and directories" file)
1895 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1897 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1898 "Regular expression to match files for `org-agenda-files'.
1899 If any element in the list in that variable contains a directory instead
1900 of a normal file, all files in that directory that are matched by this
1901 regular expression will be included."
1902 :group 'org-agenda
1903 :type 'regexp)
1905 (defcustom org-agenda-text-search-extra-files nil
1906 "List of extra files to be searched by text search commands.
1907 These files will be search in addition to the agenda files by the
1908 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1909 Note that these files will only be searched for text search commands,
1910 not for the other agenda views like todo lists, tag searches or the weekly
1911 agenda. This variable is intended to list notes and possibly archive files
1912 that should also be searched by these two commands.
1913 In fact, if the first element in the list is the symbol `agenda-archives',
1914 than all archive files of all agenda files will be added to the search
1915 scope."
1916 :group 'org-agenda
1917 :type '(set :greedy t
1918 (const :tag "Agenda Archives" agenda-archives)
1919 (repeat :inline t (file))))
1921 (if (fboundp 'defvaralias)
1922 (defvaralias 'org-agenda-multi-occur-extra-files
1923 'org-agenda-text-search-extra-files))
1925 (defcustom org-agenda-skip-unavailable-files nil
1926 "t means to just skip non-reachable files in `org-agenda-files'.
1927 Nil means to remove them, after a query, from the list."
1928 :group 'org-agenda
1929 :type 'boolean)
1931 (defcustom org-calendar-to-agenda-key [?c]
1932 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1933 The command `org-calendar-goto-agenda' will be bound to this key. The
1934 default is the character `c' because then `c' can be used to switch back and
1935 forth between agenda and calendar."
1936 :group 'org-agenda
1937 :type 'sexp)
1939 (eval-after-load "calendar"
1940 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1941 'org-calendar-goto-agenda))
1943 (defgroup org-latex nil
1944 "Options for embedding LaTeX code into Org-mode."
1945 :tag "Org LaTeX"
1946 :group 'org)
1948 (defcustom org-format-latex-options
1949 '(:foreground default :background default :scale 1.0
1950 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1951 :matchers ("begin" "$" "$$" "\\(" "\\["))
1952 "Options for creating images from LaTeX fragments.
1953 This is a property list with the following properties:
1954 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1955 `default' means use the forground of the default face.
1956 :background the background color, or \"Transparent\".
1957 `default' means use the background of the default face.
1958 :scale a scaling factor for the size of the images
1959 :html-foreground, :html-background, :html-scale
1960 The same numbers for HTML export.
1961 :matchers a list indicating which matchers should be used to
1962 find LaTeX fragments. Valid members of this list are:
1963 \"begin\" find environments
1964 \"$\" find math expressions surrounded by $...$
1965 \"$$\" find math expressions surrounded by $$....$$
1966 \"\\(\" find math expressions surrounded by \\(...\\)
1967 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1968 :group 'org-latex
1969 :type 'plist)
1971 (defcustom org-format-latex-header "\\documentclass{article}
1972 \\usepackage{fullpage} % do not remove
1973 \\usepackage{amssymb}
1974 \\usepackage[usenames]{color}
1975 \\usepackage{amsmath}
1976 \\usepackage{latexsym}
1977 \\usepackage[mathscr]{eucal}
1978 \\pagestyle{empty} % do not remove"
1979 "The document header used for processing LaTeX fragments."
1980 :group 'org-latex
1981 :type 'string)
1984 (defgroup org-font-lock nil
1985 "Font-lock settings for highlighting in Org-mode."
1986 :tag "Org Font Lock"
1987 :group 'org)
1989 (defcustom org-level-color-stars-only nil
1990 "Non-nil means fontify only the stars in each headline.
1991 When nil, the entire headline is fontified.
1992 Changing it requires restart of `font-lock-mode' to become effective
1993 also in regions already fontified."
1994 :group 'org-font-lock
1995 :type 'boolean)
1997 (defcustom org-hide-leading-stars nil
1998 "Non-nil means, hide the first N-1 stars in a headline.
1999 This works by using the face `org-hide' for these stars. This
2000 face is white for a light background, and black for a dark
2001 background. You may have to customize the face `org-hide' to
2002 make this work.
2003 Changing it requires restart of `font-lock-mode' to become effective
2004 also in regions already fontified.
2005 You may also set this on a per-file basis by adding one of the following
2006 lines to the buffer:
2008 #+STARTUP: hidestars
2009 #+STARTUP: showstars"
2010 :group 'org-font-lock
2011 :type 'boolean)
2013 (defcustom org-fontify-done-headline nil
2014 "Non-nil means, change the face of a headline if it is marked DONE.
2015 Normally, only the TODO/DONE keyword indicates the state of a headline.
2016 When this is non-nil, the headline after the keyword is set to the
2017 `org-headline-done' as an additional indication."
2018 :group 'org-font-lock
2019 :type 'boolean)
2021 (defcustom org-fontify-emphasized-text t
2022 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2023 Changing this variable requires a restart of Emacs to take effect."
2024 :group 'org-font-lock
2025 :type 'boolean)
2027 (defcustom org-highlight-latex-fragments-and-specials nil
2028 "Non-nil means, fontify what is treated specially by the exporters."
2029 :group 'org-font-lock
2030 :type 'boolean)
2032 (defcustom org-hide-emphasis-markers nil
2033 "Non-nil mean font-lock should hide the emphasis marker characters."
2034 :group 'org-font-lock
2035 :type 'boolean)
2037 (defvar org-emph-re nil
2038 "Regular expression for matching emphasis.")
2039 (defvar org-verbatim-re nil
2040 "Regular expression for matching verbatim text.")
2041 (defvar org-emphasis-regexp-components) ; defined just below
2042 (defvar org-emphasis-alist) ; defined just below
2043 (defun org-set-emph-re (var val)
2044 "Set variable and compute the emphasis regular expression."
2045 (set var val)
2046 (when (and (boundp 'org-emphasis-alist)
2047 (boundp 'org-emphasis-regexp-components)
2048 org-emphasis-alist org-emphasis-regexp-components)
2049 (let* ((e org-emphasis-regexp-components)
2050 (pre (car e))
2051 (post (nth 1 e))
2052 (border (nth 2 e))
2053 (body (nth 3 e))
2054 (nl (nth 4 e))
2055 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2056 (body1 (concat body "*?"))
2057 (markers (mapconcat 'car org-emphasis-alist ""))
2058 (vmarkers (mapconcat
2059 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2060 org-emphasis-alist "")))
2061 ;; make sure special characters appear at the right position in the class
2062 (if (string-match "\\^" markers)
2063 (setq markers (concat (replace-match "" t t markers) "^")))
2064 (if (string-match "-" markers)
2065 (setq markers (concat (replace-match "" t t markers) "-")))
2066 (if (string-match "\\^" vmarkers)
2067 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2068 (if (string-match "-" vmarkers)
2069 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2070 (if (> nl 0)
2071 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2072 (int-to-string nl) "\\}")))
2073 ;; Make the regexp
2074 (setq org-emph-re
2075 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2076 "\\("
2077 "\\([" markers "]\\)"
2078 "\\("
2079 "[^" border "]\\|"
2080 "[^" border (if (and nil stacked) markers) "]"
2081 body1
2082 "[^" border (if (and nil stacked) markers) "]"
2083 "\\)"
2084 "\\3\\)"
2085 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2086 (setq org-verbatim-re
2087 (concat "\\([" pre "]\\|^\\)"
2088 "\\("
2089 "\\([" vmarkers "]\\)"
2090 "\\("
2091 "[^" border "]\\|"
2092 "[^" border "]"
2093 body1
2094 "[^" border "]"
2095 "\\)"
2096 "\\3\\)"
2097 "\\([" post "]\\|$\\)")))))
2099 (defcustom org-emphasis-regexp-components
2100 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2101 "Components used to build the regular expression for emphasis.
2102 This is a list with 6 entries. Terminology: In an emphasis string
2103 like \" *strong word* \", we call the initial space PREMATCH, the final
2104 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2105 and \"trong wor\" is the body. The different components in this variable
2106 specify what is allowed/forbidden in each part:
2108 pre Chars allowed as prematch. Beginning of line will be allowed too.
2109 post Chars allowed as postmatch. End of line will be allowed too.
2110 border The chars *forbidden* as border characters.
2111 body-regexp A regexp like \".\" to match a body character. Don't use
2112 non-shy groups here, and don't allow newline here.
2113 newline The maximum number of newlines allowed in an emphasis exp.
2115 Use customize to modify this, or restart Emacs after changing it."
2116 :group 'org-font-lock
2117 :set 'org-set-emph-re
2118 :type '(list
2119 (sexp :tag "Allowed chars in pre ")
2120 (sexp :tag "Allowed chars in post ")
2121 (sexp :tag "Forbidden chars in border ")
2122 (sexp :tag "Regexp for body ")
2123 (integer :tag "number of newlines allowed")
2124 (option (boolean :tag "Stacking (DISABLED) "))))
2126 (defcustom org-emphasis-alist
2127 '(("*" bold "<b>" "</b>")
2128 ("/" italic "<i>" "</i>")
2129 ("_" underline "<u>" "</u>")
2130 ("=" org-code "<code>" "</code>" verbatim)
2131 ("~" org-verbatim "" "" verbatim)
2132 ("+" (:strike-through t) "<del>" "</del>")
2134 "Special syntax for emphasized text.
2135 Text starting and ending with a special character will be emphasized, for
2136 example *bold*, _underlined_ and /italic/. This variable sets the marker
2137 characters, the face to be used by font-lock for highlighting in Org-mode
2138 Emacs buffers, and the HTML tags to be used for this.
2139 Use customize to modify this, or restart Emacs after changing it."
2140 :group 'org-font-lock
2141 :set 'org-set-emph-re
2142 :type '(repeat
2143 (list
2144 (string :tag "Marker character")
2145 (choice
2146 (face :tag "Font-lock-face")
2147 (plist :tag "Face property list"))
2148 (string :tag "HTML start tag")
2149 (string :tag "HTML end tag")
2150 (option (const verbatim)))))
2152 ;;; Miscellaneous options
2154 (defgroup org-completion nil
2155 "Completion in Org-mode."
2156 :tag "Org Completion"
2157 :group 'org)
2159 (defcustom org-completion-fallback-command 'hippie-expand
2160 "The expansion command called by \\[org-complete] in normal context.
2161 Normal means, no org-mode-specific context."
2162 :group 'org-completion
2163 :type 'function)
2165 ;;; Functions and variables from ther packages
2166 ;; Declared here to avoid compiler warnings
2168 ;; XEmacs only
2169 (defvar outline-mode-menu-heading)
2170 (defvar outline-mode-menu-show)
2171 (defvar outline-mode-menu-hide)
2172 (defvar zmacs-regions) ; XEmacs regions
2174 ;; Emacs only
2175 (defvar mark-active)
2177 ;; Various packages
2178 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2179 (declare-function calendar-forward-day "cal-move" (arg))
2180 (declare-function calendar-goto-date "cal-move" (date))
2181 (declare-function calendar-goto-today "cal-move" ())
2182 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2183 (defvar calc-embedded-close-formula)
2184 (defvar calc-embedded-open-formula)
2185 (declare-function cdlatex-tab "ext:cdlatex" ())
2186 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2187 (defvar font-lock-unfontify-region-function)
2188 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2189 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2190 (defvar iswitchb-temp-buflist)
2191 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2192 (declare-function org-agenda-skip "org-agenda" ())
2193 (declare-function org-format-agenda-item "org-agenda"
2194 (extra txt &optional category tags dotime noprefix remove-re))
2195 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2196 (declare-function org-agenda-change-all-lines "org-agenda"
2197 (newhead hdmarker &optional fixface))
2198 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2199 (declare-function org-agenda-maybe-redo "org-agenda" ())
2200 (declare-function parse-time-string "parse-time" (string))
2201 (declare-function remember "remember" (&optional initial))
2202 (declare-function remember-buffer-desc "remember" ())
2203 (declare-function remember-finalize "remember" ())
2204 (defvar remember-save-after-remembering)
2205 (defvar remember-data-file)
2206 (defvar remember-register)
2207 (defvar remember-buffer)
2208 (defvar remember-handler-functions)
2209 (defvar remember-annotation-functions)
2210 (defvar texmathp-why)
2211 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2212 (declare-function table--at-cell-p "table" (position &optional object at-column))
2214 (defvar w3m-current-url)
2215 (defvar w3m-current-title)
2217 (defvar org-latex-regexps)
2219 ;;; Autoload and prepare some org modules
2221 ;; Some table stuff that needs to be defined here, because it is used
2222 ;; by the functions setting up org-mode or checking for table context.
2224 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2225 "Detects an org-type or table-type table.")
2226 (defconst org-table-line-regexp "^[ \t]*|"
2227 "Detects an org-type table line.")
2228 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2229 "Detects an org-type table line.")
2230 (defconst org-table-hline-regexp "^[ \t]*|-"
2231 "Detects an org-type table hline.")
2232 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2233 "Detects a table-type table hline.")
2234 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2235 "Searching from within a table (any type) this finds the first line
2236 outside the table.")
2238 ;; Autoload the functions in org-table.el that are needed by functions here.
2240 (eval-and-compile
2241 (org-autoload "org-table"
2242 '(org-table-align org-table-begin org-table-blank-field
2243 org-table-convert org-table-convert-region org-table-copy-down
2244 org-table-copy-region org-table-create
2245 org-table-create-or-convert-from-region
2246 org-table-create-with-table.el org-table-current-dline
2247 org-table-cut-region org-table-delete-column org-table-edit-field
2248 org-table-edit-formulas org-table-end org-table-eval-formula
2249 org-table-export org-table-field-info
2250 org-table-get-stored-formulas org-table-goto-column
2251 org-table-hline-and-move org-table-import org-table-insert-column
2252 org-table-insert-hline org-table-insert-row org-table-iterate
2253 org-table-justify-field-maybe org-table-kill-row
2254 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2255 org-table-move-column org-table-move-column-left
2256 org-table-move-column-right org-table-move-row
2257 org-table-move-row-down org-table-move-row-up
2258 org-table-next-field org-table-next-row org-table-paste-rectangle
2259 org-table-previous-field org-table-recalculate
2260 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2261 org-table-toggle-coordinate-overlays
2262 org-table-toggle-formula-debugger org-table-wrap-region
2263 orgtbl-mode turn-on-orgtbl)))
2265 (defun org-at-table-p (&optional table-type)
2266 "Return t if the cursor is inside an org-type table.
2267 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2268 (if org-enable-table-editor
2269 (save-excursion
2270 (beginning-of-line 1)
2271 (looking-at (if table-type org-table-any-line-regexp
2272 org-table-line-regexp)))
2273 nil))
2274 (defsubst org-table-p () (org-at-table-p))
2276 (defun org-at-table.el-p ()
2277 "Return t if and only if we are at a table.el table."
2278 (and (org-at-table-p 'any)
2279 (save-excursion
2280 (goto-char (org-table-begin 'any))
2281 (looking-at org-table1-hline-regexp))))
2282 (defun org-table-recognize-table.el ()
2283 "If there is a table.el table nearby, recognize it and move into it."
2284 (if org-table-tab-recognizes-table.el
2285 (if (org-at-table.el-p)
2286 (progn
2287 (beginning-of-line 1)
2288 (if (looking-at org-table-dataline-regexp)
2290 (if (looking-at org-table1-hline-regexp)
2291 (progn
2292 (beginning-of-line 2)
2293 (if (looking-at org-table-any-border-regexp)
2294 (beginning-of-line -1)))))
2295 (if (re-search-forward "|" (org-table-end t) t)
2296 (progn
2297 (require 'table)
2298 (if (table--at-cell-p (point))
2300 (message "recognizing table.el table...")
2301 (table-recognize-table)
2302 (message "recognizing table.el table...done")))
2303 (error "This should not happen..."))
2305 nil)
2306 nil))
2308 (defun org-at-table-hline-p ()
2309 "Return t if the cursor is inside a hline in a table."
2310 (if org-enable-table-editor
2311 (save-excursion
2312 (beginning-of-line 1)
2313 (looking-at org-table-hline-regexp))
2314 nil))
2316 (defvar org-table-clean-did-remove-column nil)
2318 (defun org-table-map-tables (function)
2319 "Apply FUNCTION to the start of all tables in the buffer."
2320 (save-excursion
2321 (save-restriction
2322 (widen)
2323 (goto-char (point-min))
2324 (while (re-search-forward org-table-any-line-regexp nil t)
2325 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2326 (beginning-of-line 1)
2327 (if (looking-at org-table-line-regexp)
2328 (save-excursion (funcall function)))
2329 (re-search-forward org-table-any-border-regexp nil 1))))
2330 (message "Mapping tables: done"))
2332 ;; Declare and autoload functions from org-exp.el
2334 (declare-function org-default-export-plist "org-exp")
2335 (declare-function org-infile-export-plist "org-exp")
2336 (declare-function org-get-current-options "org-exp")
2337 (eval-and-compile
2338 (org-autoload "org-exp"
2339 '(org-export org-export-as-ascii org-export-visible
2340 org-insert-export-options-template org-export-as-html-and-open
2341 org-export-as-html-batch org-export-as-html-to-buffer
2342 org-replace-region-by-html org-export-region-as-html
2343 org-export-as-html org-export-icalendar-this-file
2344 org-export-icalendar-all-agenda-files
2345 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2347 ;; Declare and autoload functions from org-exp.el
2349 (eval-and-compile
2350 (org-autoload "org-exp"
2351 '(org-agenda org-agenda-list org-search-view
2352 org-todo-list org-tags-view org-agenda-list-stuck-projects
2353 org-diary org-agenda-to-appt)))
2355 ;; Autoload org-remember
2357 (eval-and-compile
2358 (org-autoload "org-remember"
2359 '(org-remember-insinuate org-remember-annotation
2360 org-remember-apply-template org-remember org-remember-handler)))
2362 ;; Autoload org-clock.el
2364 (defvar org-clock-marker (make-marker)
2365 "Marker recording the last clock-in.")
2367 (eval-and-compile
2368 (org-autoload
2369 "org-clock"
2370 '(org-clock-in org-clock-out org-clock-cancel
2371 org-clock-goto org-clock-sum org-clock-display
2372 org-remove-clock-overlays org-clock-report
2373 org-clocktable-shift org-dblock-write:clocktable
2374 org-get-clocktable)))
2376 (defun org-clock-update-time-maybe ()
2377 "If this is a CLOCK line, update it and return t.
2378 Otherwise, return nil."
2379 (interactive)
2380 (save-excursion
2381 (beginning-of-line 1)
2382 (skip-chars-forward " \t")
2383 (when (looking-at org-clock-string)
2384 (let ((re (concat "[ \t]*" org-clock-string
2385 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2386 "\\([ \t]*=>.*\\)?"))
2387 ts te h m s)
2388 (if (not (looking-at re))
2390 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2391 (end-of-line 1)
2392 (setq ts (match-string 1)
2393 te (match-string 2))
2394 (setq s (- (time-to-seconds
2395 (apply 'encode-time (org-parse-time-string te)))
2396 (time-to-seconds
2397 (apply 'encode-time (org-parse-time-string ts))))
2398 h (floor (/ s 3600))
2399 s (- s (* 3600 h))
2400 m (floor (/ s 60))
2401 s (- s (* 60 s)))
2402 (insert " => " (format "%2d:%02d" h m))
2403 t)))))
2405 (defun org-check-running-clock ()
2406 "Check if the current buffer contains the running clock.
2407 If yes, offer to stop it and to save the buffer with the changes."
2408 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2409 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2410 (buffer-name))))
2411 (org-clock-out)
2412 (when (y-or-n-p "Save changed buffer?")
2413 (save-buffer))))
2415 (defun org-clocktable-try-shift (dir n)
2416 "Check if this line starts a clock table, if yes, shift the time block."
2417 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2418 (org-clocktable-shift dir n)))
2420 ;; Autoload archiving code
2421 ;; The stuff that is needed for cycling and tags has to be defined here.
2423 (defgroup org-archive nil
2424 "Options concerning archiving in Org-mode."
2425 :tag "Org Archive"
2426 :group 'org-structure)
2428 (defcustom org-archive-location "%s_archive::"
2429 "The location where subtrees should be archived.
2431 Otherwise, the value of this variable is a string, consisting of two
2432 parts, separated by a double-colon.
2434 The first part is a file name - when omitted, archiving happens in the same
2435 file. %s will be replaced by the current file name (without directory part).
2436 Archiving to a different file is useful to keep archived entries from
2437 contributing to the Org-mode Agenda.
2439 The part after the double colon is a headline. The archived entries will be
2440 filed under that headline. When omitted, the subtrees are simply filed away
2441 at the end of the file, as top-level entries.
2443 Here are a few examples:
2444 \"%s_archive::\"
2445 If the current file is Projects.org, archive in file
2446 Projects.org_archive, as top-level trees. This is the default.
2448 \"::* Archived Tasks\"
2449 Archive in the current file, under the top-level headline
2450 \"* Archived Tasks\".
2452 \"~/org/archive.org::\"
2453 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2455 \"basement::** Finished Tasks\"
2456 Archive in file ./basement (relative path), as level 3 trees
2457 below the level 2 heading \"** Finished Tasks\".
2459 You may set this option on a per-file basis by adding to the buffer a
2460 line like
2462 #+ARCHIVE: basement::** Finished Tasks
2464 You may also define it locally for a subtree by setting an ARCHIVE property
2465 in the entry. If such a property is found in an entry, or anywhere up
2466 the hierarchy, it will be used."
2467 :group 'org-archive
2468 :type 'string)
2470 (defcustom org-archive-tag "ARCHIVE"
2471 "The tag that marks a subtree as archived.
2472 An archived subtree does not open during visibility cycling, and does
2473 not contribute to the agenda listings.
2474 After changing this, font-lock must be restarted in the relevant buffers to
2475 get the proper fontification."
2476 :group 'org-archive
2477 :group 'org-keywords
2478 :type 'string)
2480 (defcustom org-agenda-skip-archived-trees t
2481 "Non-nil means, the agenda will skip any items located in archived trees.
2482 An archived tree is a tree marked with the tag ARCHIVE."
2483 :group 'org-archive
2484 :group 'org-agenda-skip
2485 :type 'boolean)
2487 (defcustom org-cycle-open-archived-trees nil
2488 "Non-nil means, `org-cycle' will open archived trees.
2489 An archived tree is a tree marked with the tag ARCHIVE.
2490 When nil, archived trees will stay folded. You can still open them with
2491 normal outline commands like `show-all', but not with the cycling commands."
2492 :group 'org-archive
2493 :group 'org-cycle
2494 :type 'boolean)
2496 (defcustom org-sparse-tree-open-archived-trees nil
2497 "Non-nil means sparse tree construction shows matches in archived trees.
2498 When nil, matches in these trees are highlighted, but the trees are kept in
2499 collapsed state."
2500 :group 'org-archive
2501 :group 'org-sparse-trees
2502 :type 'boolean)
2504 (defun org-cycle-hide-archived-subtrees (state)
2505 "Re-hide all archived subtrees after a visibility state change."
2506 (when (and (not org-cycle-open-archived-trees)
2507 (not (memq state '(overview folded))))
2508 (save-excursion
2509 (let* ((globalp (memq state '(contents all)))
2510 (beg (if globalp (point-min) (point)))
2511 (end (if globalp (point-max) (org-end-of-subtree t))))
2512 (org-hide-archived-subtrees beg end)
2513 (goto-char beg)
2514 (if (looking-at (concat ".*:" org-archive-tag ":"))
2515 (message "%s" (substitute-command-keys
2516 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2518 (defun org-force-cycle-archived ()
2519 "Cycle subtree even if it is archived."
2520 (interactive)
2521 (setq this-command 'org-cycle)
2522 (let ((org-cycle-open-archived-trees t))
2523 (call-interactively 'org-cycle)))
2525 (defun org-hide-archived-subtrees (beg end)
2526 "Re-hide all archived subtrees after a visibility state change."
2527 (save-excursion
2528 (let* ((re (concat ":" org-archive-tag ":")))
2529 (goto-char beg)
2530 (while (re-search-forward re end t)
2531 (and (org-on-heading-p) (hide-subtree))
2532 (org-end-of-subtree t)))))
2534 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2536 (eval-and-compile
2537 (org-autoload "org-archive"
2538 '(org-add-archive-files org-archive-subtree
2539 org-archive-to-archive-sibling org-toggle-archive-tag)))
2541 ;; Autoload Column View Code
2543 (declare-function org-columns-number-to-string "org-colview")
2544 (declare-function org-columns-get-format-and-top-level "org-colview")
2545 (declare-function org-columns-compute "org-colview")
2547 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2548 '(org-columns-number-to-string org-columns-get-format-and-top-level
2549 org-columns-compute org-agenda-columns org-columns-remove-overlays
2550 org-columns org-insert-columns-dblock))
2552 ;;; Variables for pre-computed regular expressions, all buffer local
2554 (defvar org-drawer-regexp nil
2555 "Matches first line of a hidden block.")
2556 (make-variable-buffer-local 'org-drawer-regexp)
2557 (defvar org-todo-regexp nil
2558 "Matches any of the TODO state keywords.")
2559 (make-variable-buffer-local 'org-todo-regexp)
2560 (defvar org-not-done-regexp nil
2561 "Matches any of the TODO state keywords except the last one.")
2562 (make-variable-buffer-local 'org-not-done-regexp)
2563 (defvar org-todo-line-regexp nil
2564 "Matches a headline and puts TODO state into group 2 if present.")
2565 (make-variable-buffer-local 'org-todo-line-regexp)
2566 (defvar org-complex-heading-regexp nil
2567 "Matches a headline and puts everything into groups:
2568 group 1: the stars
2569 group 2: The todo keyword, maybe
2570 group 3: Priority cookie
2571 group 4: True headline
2572 group 5: Tags")
2573 (make-variable-buffer-local 'org-complex-heading-regexp)
2574 (defvar org-todo-line-tags-regexp nil
2575 "Matches a headline and puts TODO state into group 2 if present.
2576 Also put tags into group 4 if tags are present.")
2577 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2578 (defvar org-nl-done-regexp nil
2579 "Matches newline followed by a headline with the DONE keyword.")
2580 (make-variable-buffer-local 'org-nl-done-regexp)
2581 (defvar org-looking-at-done-regexp nil
2582 "Matches the DONE keyword a point.")
2583 (make-variable-buffer-local 'org-looking-at-done-regexp)
2584 (defvar org-ds-keyword-length 12
2585 "Maximum length of the Deadline and SCHEDULED keywords.")
2586 (make-variable-buffer-local 'org-ds-keyword-length)
2587 (defvar org-deadline-regexp nil
2588 "Matches the DEADLINE keyword.")
2589 (make-variable-buffer-local 'org-deadline-regexp)
2590 (defvar org-deadline-time-regexp nil
2591 "Matches the DEADLINE keyword together with a time stamp.")
2592 (make-variable-buffer-local 'org-deadline-time-regexp)
2593 (defvar org-deadline-line-regexp nil
2594 "Matches the DEADLINE keyword and the rest of the line.")
2595 (make-variable-buffer-local 'org-deadline-line-regexp)
2596 (defvar org-scheduled-regexp nil
2597 "Matches the SCHEDULED keyword.")
2598 (make-variable-buffer-local 'org-scheduled-regexp)
2599 (defvar org-scheduled-time-regexp nil
2600 "Matches the SCHEDULED keyword together with a time stamp.")
2601 (make-variable-buffer-local 'org-scheduled-time-regexp)
2602 (defvar org-closed-time-regexp nil
2603 "Matches the CLOSED keyword together with a time stamp.")
2604 (make-variable-buffer-local 'org-closed-time-regexp)
2606 (defvar org-keyword-time-regexp nil
2607 "Matches any of the 4 keywords, together with the time stamp.")
2608 (make-variable-buffer-local 'org-keyword-time-regexp)
2609 (defvar org-keyword-time-not-clock-regexp nil
2610 "Matches any of the 3 keywords, together with the time stamp.")
2611 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2612 (defvar org-maybe-keyword-time-regexp nil
2613 "Matches a timestamp, possibly preceeded by a keyword.")
2614 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2615 (defvar org-planning-or-clock-line-re nil
2616 "Matches a line with planning or clock info.")
2617 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2619 (defconst org-plain-time-of-day-regexp
2620 (concat
2621 "\\(\\<[012]?[0-9]"
2622 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2623 "\\(--?"
2624 "\\(\\<[012]?[0-9]"
2625 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2626 "\\)?")
2627 "Regular expression to match a plain time or time range.
2628 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2629 groups carry important information:
2630 0 the full match
2631 1 the first time, range or not
2632 8 the second time, if it is a range.")
2634 (defconst org-plain-time-extension-regexp
2635 (concat
2636 "\\(\\<[012]?[0-9]"
2637 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2638 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2639 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2640 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2641 groups carry important information:
2642 0 the full match
2643 7 hours of duration
2644 9 minutes of duration")
2646 (defconst org-stamp-time-of-day-regexp
2647 (concat
2648 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2649 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2650 "\\(--?"
2651 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2652 "Regular expression to match a timestamp time or time range.
2653 After a match, the following groups carry important information:
2654 0 the full match
2655 1 date plus weekday, for backreferencing to make sure both times on same day
2656 2 the first time, range or not
2657 4 the second time, if it is a range.")
2659 (defconst org-startup-options
2660 '(("fold" org-startup-folded t)
2661 ("overview" org-startup-folded t)
2662 ("nofold" org-startup-folded nil)
2663 ("showall" org-startup-folded nil)
2664 ("content" org-startup-folded content)
2665 ("hidestars" org-hide-leading-stars t)
2666 ("showstars" org-hide-leading-stars nil)
2667 ("odd" org-odd-levels-only t)
2668 ("oddeven" org-odd-levels-only nil)
2669 ("align" org-startup-align-all-tables t)
2670 ("noalign" org-startup-align-all-tables nil)
2671 ("customtime" org-display-custom-times t)
2672 ("logdone" org-log-done time)
2673 ("lognotedone" org-log-done note)
2674 ("nologdone" org-log-done nil)
2675 ("lognoteclock-out" org-log-note-clock-out t)
2676 ("nolognoteclock-out" org-log-note-clock-out nil)
2677 ("logrepeat" org-log-repeat state)
2678 ("lognoterepeat" org-log-repeat note)
2679 ("nologrepeat" org-log-repeat nil)
2680 ("constcgs" constants-unit-system cgs)
2681 ("constSI" constants-unit-system SI))
2682 "Variable associated with STARTUP options for org-mode.
2683 Each element is a list of three items: The startup options as written
2684 in the #+STARTUP line, the corresponding variable, and the value to
2685 set this variable to if the option is found. An optional forth element PUSH
2686 means to push this value onto the list in the variable.")
2688 (defun org-set-regexps-and-options ()
2689 "Precompute regular expressions for current buffer."
2690 (when (org-mode-p)
2691 (org-set-local 'org-todo-kwd-alist nil)
2692 (org-set-local 'org-todo-key-alist nil)
2693 (org-set-local 'org-todo-key-trigger nil)
2694 (org-set-local 'org-todo-keywords-1 nil)
2695 (org-set-local 'org-done-keywords nil)
2696 (org-set-local 'org-todo-heads nil)
2697 (org-set-local 'org-todo-sets nil)
2698 (org-set-local 'org-todo-log-states nil)
2699 (let ((re (org-make-options-regexp
2700 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2701 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2702 "CONSTANTS" "PROPERTY" "DRAWERS")))
2703 (splitre "[ \t]+")
2704 kwds kws0 kwsa key log value cat arch tags const links hw dws
2705 tail sep kws1 prio props drawers)
2706 (save-excursion
2707 (save-restriction
2708 (widen)
2709 (goto-char (point-min))
2710 (while (re-search-forward re nil t)
2711 (setq key (match-string 1) value (org-match-string-no-properties 2))
2712 (cond
2713 ((equal key "CATEGORY")
2714 (if (string-match "[ \t]+$" value)
2715 (setq value (replace-match "" t t value)))
2716 (setq cat value))
2717 ((member key '("SEQ_TODO" "TODO"))
2718 (push (cons 'sequence (org-split-string value splitre)) kwds))
2719 ((equal key "TYP_TODO")
2720 (push (cons 'type (org-split-string value splitre)) kwds))
2721 ((equal key "TAGS")
2722 (setq tags (append tags (org-split-string value splitre))))
2723 ((equal key "COLUMNS")
2724 (org-set-local 'org-columns-default-format value))
2725 ((equal key "LINK")
2726 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2727 (push (cons (match-string 1 value)
2728 (org-trim (match-string 2 value)))
2729 links)))
2730 ((equal key "PRIORITIES")
2731 (setq prio (org-split-string value " +")))
2732 ((equal key "PROPERTY")
2733 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2734 (push (cons (match-string 1 value) (match-string 2 value))
2735 props)))
2736 ((equal key "DRAWERS")
2737 (setq drawers (org-split-string value splitre)))
2738 ((equal key "CONSTANTS")
2739 (setq const (append const (org-split-string value splitre))))
2740 ((equal key "STARTUP")
2741 (let ((opts (org-split-string value splitre))
2742 l var val)
2743 (while (setq l (pop opts))
2744 (when (setq l (assoc l org-startup-options))
2745 (setq var (nth 1 l) val (nth 2 l))
2746 (if (not (nth 3 l))
2747 (set (make-local-variable var) val)
2748 (if (not (listp (symbol-value var)))
2749 (set (make-local-variable var) nil))
2750 (set (make-local-variable var) (symbol-value var))
2751 (add-to-list var val))))))
2752 ((equal key "ARCHIVE")
2753 (string-match " *$" value)
2754 (setq arch (replace-match "" t t value))
2755 (remove-text-properties 0 (length arch)
2756 '(face t fontified t) arch)))
2758 (when cat
2759 (org-set-local 'org-category (intern cat))
2760 (push (cons "CATEGORY" cat) props))
2761 (when prio
2762 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2763 (setq prio (mapcar 'string-to-char prio))
2764 (org-set-local 'org-highest-priority (nth 0 prio))
2765 (org-set-local 'org-lowest-priority (nth 1 prio))
2766 (org-set-local 'org-default-priority (nth 2 prio)))
2767 (and props (org-set-local 'org-local-properties (nreverse props)))
2768 (and drawers (org-set-local 'org-drawers drawers))
2769 (and arch (org-set-local 'org-archive-location arch))
2770 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2771 ;; Process the TODO keywords
2772 (unless kwds
2773 ;; Use the global values as if they had been given locally.
2774 (setq kwds (default-value 'org-todo-keywords))
2775 (if (stringp (car kwds))
2776 (setq kwds (list (cons org-todo-interpretation
2777 (default-value 'org-todo-keywords)))))
2778 (setq kwds (reverse kwds)))
2779 (setq kwds (nreverse kwds))
2780 (let (inter kws kw)
2781 (while (setq kws (pop kwds))
2782 (setq inter (pop kws) sep (member "|" kws)
2783 kws0 (delete "|" (copy-sequence kws))
2784 kwsa nil
2785 kws1 (mapcar
2786 (lambda (x)
2787 ;; 1 2
2788 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2789 (progn
2790 (setq kw (match-string 1 x)
2791 key (and (match-end 2) (match-string 2 x))
2792 log (org-extract-log-state-settings x))
2793 (push (cons kw (and key (string-to-char key))) kwsa)
2794 (and log (push log org-todo-log-states))
2796 (error "Invalid TODO keyword %s" x)))
2797 kws0)
2798 kwsa (if kwsa (append '((:startgroup))
2799 (nreverse kwsa)
2800 '((:endgroup))))
2801 hw (car kws1)
2802 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2803 tail (list inter hw (car dws) (org-last dws)))
2804 (add-to-list 'org-todo-heads hw 'append)
2805 (push kws1 org-todo-sets)
2806 (setq org-done-keywords (append org-done-keywords dws nil))
2807 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2808 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2809 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2810 (setq org-todo-sets (nreverse org-todo-sets)
2811 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2812 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2813 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2814 ;; Process the constants
2815 (when const
2816 (let (e cst)
2817 (while (setq e (pop const))
2818 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2819 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2820 (setq org-table-formula-constants-local cst)))
2822 ;; Process the tags.
2823 (when tags
2824 (let (e tgs)
2825 (while (setq e (pop tags))
2826 (cond
2827 ((equal e "{") (push '(:startgroup) tgs))
2828 ((equal e "}") (push '(:endgroup) tgs))
2829 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2830 (push (cons (match-string 1 e)
2831 (string-to-char (match-string 2 e)))
2832 tgs))
2833 (t (push (list e) tgs))))
2834 (org-set-local 'org-tag-alist nil)
2835 (while (setq e (pop tgs))
2836 (or (and (stringp (car e))
2837 (assoc (car e) org-tag-alist))
2838 (push e org-tag-alist))))))
2840 ;; Compute the regular expressions and other local variables
2841 (if (not org-done-keywords)
2842 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2843 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2844 (length org-scheduled-string)
2845 (length org-clock-string)
2846 (length org-closed-string)))
2847 org-drawer-regexp
2848 (concat "^[ \t]*:\\("
2849 (mapconcat 'regexp-quote org-drawers "\\|")
2850 "\\):[ \t]*$")
2851 org-not-done-keywords
2852 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2853 org-todo-regexp
2854 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2855 "\\|") "\\)\\>")
2856 org-not-done-regexp
2857 (concat "\\<\\("
2858 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2859 "\\)\\>")
2860 org-todo-line-regexp
2861 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2862 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2863 "\\)\\>\\)?[ \t]*\\(.*\\)")
2864 org-complex-heading-regexp
2865 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2866 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2867 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2868 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2869 org-nl-done-regexp
2870 (concat "\n\\*+[ \t]+"
2871 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2872 "\\)" "\\>")
2873 org-todo-line-tags-regexp
2874 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2875 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2876 (org-re
2877 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2878 org-looking-at-done-regexp
2879 (concat "^" "\\(?:"
2880 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2881 "\\>")
2882 org-deadline-regexp (concat "\\<" org-deadline-string)
2883 org-deadline-time-regexp
2884 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2885 org-deadline-line-regexp
2886 (concat "\\<\\(" org-deadline-string "\\).*")
2887 org-scheduled-regexp
2888 (concat "\\<" org-scheduled-string)
2889 org-scheduled-time-regexp
2890 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2891 org-closed-time-regexp
2892 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2893 org-keyword-time-regexp
2894 (concat "\\<\\(" org-scheduled-string
2895 "\\|" org-deadline-string
2896 "\\|" org-closed-string
2897 "\\|" org-clock-string "\\)"
2898 " *[[<]\\([^]>]+\\)[]>]")
2899 org-keyword-time-not-clock-regexp
2900 (concat "\\<\\(" org-scheduled-string
2901 "\\|" org-deadline-string
2902 "\\|" org-closed-string
2903 "\\)"
2904 " *[[<]\\([^]>]+\\)[]>]")
2905 org-maybe-keyword-time-regexp
2906 (concat "\\(\\<\\(" org-scheduled-string
2907 "\\|" org-deadline-string
2908 "\\|" org-closed-string
2909 "\\|" org-clock-string "\\)\\)?"
2910 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2911 org-planning-or-clock-line-re
2912 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2913 "\\|" org-deadline-string
2914 "\\|" org-closed-string "\\|" org-clock-string
2915 "\\)\\>\\)")
2917 (org-compute-latex-and-specials-regexp)
2918 (org-set-font-lock-defaults)))
2920 (defun org-extract-log-state-settings (x)
2921 "Extract the log state setting from a TODO keyword string.
2922 This will extract info from a string like \"WAIT(w@/!)\"."
2923 (let (kw key log1 log2)
2924 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2925 (setq kw (match-string 1 x)
2926 key (and (match-end 2) (match-string 2 x))
2927 log1 (and (match-end 3) (match-string 3 x))
2928 log2 (and (match-end 4) (match-string 4 x)))
2929 (and (or log1 log2)
2930 (list kw
2931 (and log1 (if (equal log1 "!") 'time 'note))
2932 (and log2 (if (equal log2 "!") 'time 'note)))))))
2934 (defun org-remove-keyword-keys (list)
2935 "Remove a pair of parenthesis at the end of each string in LIST."
2936 (mapcar (lambda (x)
2937 (if (string-match "(.*)$" x)
2938 (substring x 0 (match-beginning 0))
2940 list))
2942 ;; FIXME: this could be done much better, using second characters etc.
2943 (defun org-assign-fast-keys (alist)
2944 "Assign fast keys to a keyword-key alist.
2945 Respect keys that are already there."
2946 (let (new e k c c1 c2 (char ?a))
2947 (while (setq e (pop alist))
2948 (cond
2949 ((equal e '(:startgroup)) (push e new))
2950 ((equal e '(:endgroup)) (push e new))
2952 (setq k (car e) c2 nil)
2953 (if (cdr e)
2954 (setq c (cdr e))
2955 ;; automatically assign a character.
2956 (setq c1 (string-to-char
2957 (downcase (substring
2958 k (if (= (string-to-char k) ?@) 1 0)))))
2959 (if (or (rassoc c1 new) (rassoc c1 alist))
2960 (while (or (rassoc char new) (rassoc char alist))
2961 (setq char (1+ char)))
2962 (setq c2 c1))
2963 (setq c (or c2 char)))
2964 (push (cons k c) new))))
2965 (nreverse new)))
2967 ;;; Some variables used in various places
2969 (defvar org-window-configuration nil
2970 "Used in various places to store a window configuration.")
2971 (defvar org-finish-function nil
2972 "Function to be called when `C-c C-c' is used.
2973 This is for getting out of special buffers like remember.")
2976 ;; FIXME: Occasionally check by commenting these, to make sure
2977 ;; no other functions uses these, forgetting to let-bind them.
2978 (defvar entry)
2979 (defvar state)
2980 (defvar last-state)
2981 (defvar date)
2982 (defvar description)
2984 ;; Defined somewhere in this file, but used before definition.
2985 (defvar org-html-entities)
2986 (defvar org-struct-menu)
2987 (defvar org-org-menu)
2988 (defvar org-tbl-menu)
2989 (defvar org-agenda-keymap)
2991 ;;;; Define the Org-mode
2993 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2994 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
2997 ;; We use a before-change function to check if a table might need
2998 ;; an update.
2999 (defvar org-table-may-need-update t
3000 "Indicates that a table might need an update.
3001 This variable is set by `org-before-change-function'.
3002 `org-table-align' sets it back to nil.")
3003 (defun org-before-change-function (beg end)
3004 "Every change indicates that a table might need an update."
3005 (setq org-table-may-need-update t))
3006 (defvar org-mode-map)
3007 (defvar org-mode-hook nil)
3008 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3009 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3010 (defvar org-table-buffer-is-an nil)
3011 (defconst org-outline-regexp "\\*+ ")
3013 ;;;###autoload
3014 (define-derived-mode org-mode outline-mode "Org"
3015 "Outline-based notes management and organizer, alias
3016 \"Carsten's outline-mode for keeping track of everything.\"
3018 Org-mode develops organizational tasks around a NOTES file which
3019 contains information about projects as plain text. Org-mode is
3020 implemented on top of outline-mode, which is ideal to keep the content
3021 of large files well structured. It supports ToDo items, deadlines and
3022 time stamps, which magically appear in the diary listing of the Emacs
3023 calendar. Tables are easily created with a built-in table editor.
3024 Plain text URL-like links connect to websites, emails (VM), Usenet
3025 messages (Gnus), BBDB entries, and any files related to the project.
3026 For printing and sharing of notes, an Org-mode file (or a part of it)
3027 can be exported as a structured ASCII or HTML file.
3029 The following commands are available:
3031 \\{org-mode-map}"
3033 ;; Get rid of Outline menus, they are not needed
3034 ;; Need to do this here because define-derived-mode sets up
3035 ;; the keymap so late. Still, it is a waste to call this each time
3036 ;; we switch another buffer into org-mode.
3037 (if (featurep 'xemacs)
3038 (when (boundp 'outline-mode-menu-heading)
3039 ;; Assume this is Greg's port, it used easymenu
3040 (easy-menu-remove outline-mode-menu-heading)
3041 (easy-menu-remove outline-mode-menu-show)
3042 (easy-menu-remove outline-mode-menu-hide))
3043 (define-key org-mode-map [menu-bar headings] 'undefined)
3044 (define-key org-mode-map [menu-bar hide] 'undefined)
3045 (define-key org-mode-map [menu-bar show] 'undefined))
3047 (org-load-modules-maybe)
3048 (easy-menu-add org-org-menu)
3049 (easy-menu-add org-tbl-menu)
3050 (org-install-agenda-files-menu)
3051 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3052 (org-add-to-invisibility-spec '(org-cwidth))
3053 (when (featurep 'xemacs)
3054 (org-set-local 'line-move-ignore-invisible t))
3055 (org-set-local 'outline-regexp org-outline-regexp)
3056 (org-set-local 'outline-level 'org-outline-level)
3057 (when (and org-ellipsis
3058 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3059 (fboundp 'make-glyph-code))
3060 (unless org-display-table
3061 (setq org-display-table (make-display-table)))
3062 (set-display-table-slot
3063 org-display-table 4
3064 (vconcat (mapcar
3065 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3066 org-ellipsis)))
3067 (if (stringp org-ellipsis) org-ellipsis "..."))))
3068 (setq buffer-display-table org-display-table))
3069 (org-set-regexps-and-options)
3070 ;; Calc embedded
3071 (org-set-local 'calc-embedded-open-mode "# ")
3072 (modify-syntax-entry ?# "<")
3073 (modify-syntax-entry ?@ "w")
3074 (if org-startup-truncated (setq truncate-lines t))
3075 (org-set-local 'font-lock-unfontify-region-function
3076 'org-unfontify-region)
3077 ;; Activate before-change-function
3078 (org-set-local 'org-table-may-need-update t)
3079 (org-add-hook 'before-change-functions 'org-before-change-function nil
3080 'local)
3081 ;; Check for running clock before killing a buffer
3082 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3083 ;; Paragraphs and auto-filling
3084 (org-set-autofill-regexps)
3085 (setq indent-line-function 'org-indent-line-function)
3086 (org-update-radio-target-regexp)
3088 ;; Comment characters
3089 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3090 (org-set-local 'comment-padding " ")
3092 ;; Align options lines
3093 (org-set-local
3094 'align-mode-rules-list
3095 '((org-in-buffer-settings
3096 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3097 (modes . '(org-mode)))))
3099 ;; Imenu
3100 (org-set-local 'imenu-create-index-function
3101 'org-imenu-get-tree)
3103 ;; Make isearch reveal context
3104 (if (or (featurep 'xemacs)
3105 (not (boundp 'outline-isearch-open-invisible-function)))
3106 ;; Emacs 21 and XEmacs make use of the hook
3107 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3108 ;; Emacs 22 deals with this through a special variable
3109 (org-set-local 'outline-isearch-open-invisible-function
3110 (lambda (&rest ignore) (org-show-context 'isearch))))
3112 ;; If empty file that did not turn on org-mode automatically, make it to.
3113 (if (and org-insert-mode-line-in-empty-file
3114 (interactive-p)
3115 (= (point-min) (point-max)))
3116 (insert "# -*- mode: org -*-\n\n"))
3118 (unless org-inhibit-startup
3119 (when org-startup-align-all-tables
3120 (let ((bmp (buffer-modified-p)))
3121 (org-table-map-tables 'org-table-align)
3122 (set-buffer-modified-p bmp)))
3123 (org-cycle-hide-drawers 'all)
3124 (cond
3125 ((eq org-startup-folded t)
3126 (org-cycle '(4)))
3127 ((eq org-startup-folded 'content)
3128 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3129 (org-cycle '(4)) (org-cycle '(4)))))))
3131 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3133 (defun org-current-time ()
3134 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3135 (if (> (car org-time-stamp-rounding-minutes) 1)
3136 (let ((r (car org-time-stamp-rounding-minutes))
3137 (time (decode-time)))
3138 (apply 'encode-time
3139 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3140 (nthcdr 2 time))))
3141 (current-time)))
3143 ;;;; Font-Lock stuff, including the activators
3145 (defvar org-mouse-map (make-sparse-keymap))
3146 (org-defkey org-mouse-map
3147 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3148 (org-defkey org-mouse-map
3149 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3150 (when org-mouse-1-follows-link
3151 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3152 (when org-tab-follows-link
3153 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3154 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3155 (when org-return-follows-link
3156 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3157 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3159 (require 'font-lock)
3161 (defconst org-non-link-chars "]\t\n\r<>")
3162 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3163 "shell" "elisp"))
3164 (defvar org-link-types-re nil
3165 "Matches a link that has a url-like prefix like \"http:\"")
3166 (defvar org-link-re-with-space nil
3167 "Matches a link with spaces, optional angular brackets around it.")
3168 (defvar org-link-re-with-space2 nil
3169 "Matches a link with spaces, optional angular brackets around it.")
3170 (defvar org-angle-link-re nil
3171 "Matches link with angular brackets, spaces are allowed.")
3172 (defvar org-plain-link-re nil
3173 "Matches plain link, without spaces.")
3174 (defvar org-bracket-link-regexp nil
3175 "Matches a link in double brackets.")
3176 (defvar org-bracket-link-analytic-regexp nil
3177 "Regular expression used to analyze links.
3178 Here is what the match groups contain after a match:
3179 1: http:
3180 2: http
3181 3: path
3182 4: [desc]
3183 5: desc")
3184 (defvar org-any-link-re nil
3185 "Regular expression matching any link.")
3187 (defun org-make-link-regexps ()
3188 "Update the link regular expressions.
3189 This should be called after the variable `org-link-types' has changed."
3190 (setq org-link-types-re
3191 (concat
3192 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3193 org-link-re-with-space
3194 (concat
3195 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3196 "\\([^" org-non-link-chars " ]"
3197 "[^" org-non-link-chars "]*"
3198 "[^" org-non-link-chars " ]\\)>?")
3199 org-link-re-with-space2
3200 (concat
3201 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3202 "\\([^" org-non-link-chars " ]"
3203 "[^]\t\n\r]*"
3204 "[^" org-non-link-chars " ]\\)>?")
3205 org-angle-link-re
3206 (concat
3207 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3208 "\\([^" org-non-link-chars " ]"
3209 "[^" org-non-link-chars "]*"
3210 "\\)>")
3211 org-plain-link-re
3212 (concat
3213 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3214 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3215 org-bracket-link-regexp
3216 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3217 org-bracket-link-analytic-regexp
3218 (concat
3219 "\\[\\["
3220 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3221 "\\([^]]+\\)"
3222 "\\]"
3223 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3224 "\\]")
3225 org-any-link-re
3226 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3227 org-angle-link-re "\\)\\|\\("
3228 org-plain-link-re "\\)")))
3230 (org-make-link-regexps)
3232 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3233 "Regular expression for fast time stamp matching.")
3234 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3235 "Regular expression for fast time stamp matching.")
3236 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3237 "Regular expression matching time strings for analysis.
3238 This one does not require the space after the date, so it can be used
3239 on a string that terminates immediately after the date.")
3240 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3241 "Regular expression matching time strings for analysis.")
3242 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3243 "Regular expression matching time stamps, with groups.")
3244 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3245 "Regular expression matching time stamps (also [..]), with groups.")
3246 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3247 "Regular expression matching a time stamp range.")
3248 (defconst org-tr-regexp-both
3249 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3250 "Regular expression matching a time stamp range.")
3251 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3252 org-ts-regexp "\\)?")
3253 "Regular expression matching a time stamp or time stamp range.")
3254 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3255 org-ts-regexp-both "\\)?")
3256 "Regular expression matching a time stamp or time stamp range.
3257 The time stamps may be either active or inactive.")
3259 (defvar org-emph-face nil)
3261 (defun org-do-emphasis-faces (limit)
3262 "Run through the buffer and add overlays to links."
3263 (let (rtn)
3264 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3265 (if (not (= (char-after (match-beginning 3))
3266 (char-after (match-beginning 4))))
3267 (progn
3268 (setq rtn t)
3269 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3270 'face
3271 (nth 1 (assoc (match-string 3)
3272 org-emphasis-alist)))
3273 (add-text-properties (match-beginning 2) (match-end 2)
3274 '(font-lock-multiline t))
3275 (when org-hide-emphasis-markers
3276 (add-text-properties (match-end 4) (match-beginning 5)
3277 '(invisible org-link))
3278 (add-text-properties (match-beginning 3) (match-end 3)
3279 '(invisible org-link)))))
3280 (backward-char 1))
3281 rtn))
3283 (defun org-emphasize (&optional char)
3284 "Insert or change an emphasis, i.e. a font like bold or italic.
3285 If there is an active region, change that region to a new emphasis.
3286 If there is no region, just insert the marker characters and position
3287 the cursor between them.
3288 CHAR should be either the marker character, or the first character of the
3289 HTML tag associated with that emphasis. If CHAR is a space, the means
3290 to remove the emphasis of the selected region.
3291 If char is not given (for example in an interactive call) it
3292 will be prompted for."
3293 (interactive)
3294 (let ((eal org-emphasis-alist) e det
3295 (erc org-emphasis-regexp-components)
3296 (prompt "")
3297 (string "") beg end move tag c s)
3298 (if (org-region-active-p)
3299 (setq beg (region-beginning) end (region-end)
3300 string (buffer-substring beg end))
3301 (setq move t))
3303 (while (setq e (pop eal))
3304 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3305 c (aref tag 0))
3306 (push (cons c (string-to-char (car e))) det)
3307 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3308 (substring tag 1)))))
3309 (unless char
3310 (message "%s" (concat "Emphasis marker or tag:" prompt))
3311 (setq char (read-char-exclusive)))
3312 (setq char (or (cdr (assoc char det)) char))
3313 (if (equal char ?\ )
3314 (setq s "" move nil)
3315 (unless (assoc (char-to-string char) org-emphasis-alist)
3316 (error "No such emphasis marker: \"%c\"" char))
3317 (setq s (char-to-string char)))
3318 (while (and (> (length string) 1)
3319 (equal (substring string 0 1) (substring string -1))
3320 (assoc (substring string 0 1) org-emphasis-alist))
3321 (setq string (substring string 1 -1)))
3322 (setq string (concat s string s))
3323 (if beg (delete-region beg end))
3324 (unless (or (bolp)
3325 (string-match (concat "[" (nth 0 erc) "\n]")
3326 (char-to-string (char-before (point)))))
3327 (insert " "))
3328 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3329 (char-to-string (char-after (point))))
3330 (insert " ") (backward-char 1))
3331 (insert string)
3332 (and move (backward-char 1))))
3334 (defconst org-nonsticky-props
3335 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3338 (defun org-activate-plain-links (limit)
3339 "Run through the buffer and add overlays to links."
3340 (catch 'exit
3341 (let (f)
3342 (while (re-search-forward org-plain-link-re limit t)
3343 (setq f (get-text-property (match-beginning 0) 'face))
3344 (if (or (eq f 'org-tag)
3345 (and (listp f) (memq 'org-tag f)))
3347 (add-text-properties (match-beginning 0) (match-end 0)
3348 (list 'mouse-face 'highlight
3349 'rear-nonsticky org-nonsticky-props
3350 'keymap org-mouse-map
3352 (throw 'exit t))))))
3354 (defun org-activate-code (limit)
3355 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3356 (unless (get-text-property (match-beginning 1) 'face)
3357 (remove-text-properties (match-beginning 0) (match-end 0)
3358 '(display t invisible t intangible t))
3359 t)))
3361 (defun org-activate-angle-links (limit)
3362 "Run through the buffer and add overlays to links."
3363 (if (re-search-forward org-angle-link-re limit t)
3364 (progn
3365 (add-text-properties (match-beginning 0) (match-end 0)
3366 (list 'mouse-face 'highlight
3367 'rear-nonsticky org-nonsticky-props
3368 'keymap org-mouse-map
3370 t)))
3372 (defun org-activate-bracket-links (limit)
3373 "Run through the buffer and add overlays to bracketed links."
3374 (if (re-search-forward org-bracket-link-regexp limit t)
3375 (let* ((help (concat "LINK: "
3376 (org-match-string-no-properties 1)))
3377 ;; FIXME: above we should remove the escapes.
3378 ;; but that requires another match, protecting match data,
3379 ;; a lot of overhead for font-lock.
3380 (ip (org-maybe-intangible
3381 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3382 'keymap org-mouse-map 'mouse-face 'highlight
3383 'font-lock-multiline t 'help-echo help)))
3384 (vp (list 'rear-nonsticky org-nonsticky-props
3385 'keymap org-mouse-map 'mouse-face 'highlight
3386 ' font-lock-multiline t 'help-echo help)))
3387 ;; We need to remove the invisible property here. Table narrowing
3388 ;; may have made some of this invisible.
3389 (remove-text-properties (match-beginning 0) (match-end 0)
3390 '(invisible nil))
3391 (if (match-end 3)
3392 (progn
3393 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3394 (add-text-properties (match-beginning 3) (match-end 3) vp)
3395 (add-text-properties (match-end 3) (match-end 0) ip))
3396 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3397 (add-text-properties (match-beginning 1) (match-end 1) vp)
3398 (add-text-properties (match-end 1) (match-end 0) ip))
3399 t)))
3401 (defun org-activate-dates (limit)
3402 "Run through the buffer and add overlays to dates."
3403 (if (re-search-forward org-tsr-regexp-both limit t)
3404 (progn
3405 (add-text-properties (match-beginning 0) (match-end 0)
3406 (list 'mouse-face 'highlight
3407 'rear-nonsticky org-nonsticky-props
3408 'keymap org-mouse-map))
3409 (when org-display-custom-times
3410 (if (match-end 3)
3411 (org-display-custom-time (match-beginning 3) (match-end 3)))
3412 (org-display-custom-time (match-beginning 1) (match-end 1)))
3413 t)))
3415 (defvar org-target-link-regexp nil
3416 "Regular expression matching radio targets in plain text.")
3417 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3418 "Regular expression matching a link target.")
3419 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3420 "Regular expression matching a radio target.")
3421 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3422 "Regular expression matching any target.")
3424 (defun org-activate-target-links (limit)
3425 "Run through the buffer and add overlays to target matches."
3426 (when org-target-link-regexp
3427 (let ((case-fold-search t))
3428 (if (re-search-forward org-target-link-regexp limit t)
3429 (progn
3430 (add-text-properties (match-beginning 0) (match-end 0)
3431 (list 'mouse-face 'highlight
3432 'rear-nonsticky org-nonsticky-props
3433 'keymap org-mouse-map
3434 'help-echo "Radio target link"
3435 'org-linked-text t))
3436 t)))))
3438 (defun org-update-radio-target-regexp ()
3439 "Find all radio targets in this file and update the regular expression."
3440 (interactive)
3441 (when (memq 'radio org-activate-links)
3442 (setq org-target-link-regexp
3443 (org-make-target-link-regexp (org-all-targets 'radio)))
3444 (org-restart-font-lock)))
3446 (defun org-hide-wide-columns (limit)
3447 (let (s e)
3448 (setq s (text-property-any (point) (or limit (point-max))
3449 'org-cwidth t))
3450 (when s
3451 (setq e (next-single-property-change s 'org-cwidth))
3452 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3453 (goto-char e)
3454 t)))
3456 (defvar org-latex-and-specials-regexp nil
3457 "Regular expression for highlighting export special stuff.")
3458 (defvar org-match-substring-regexp)
3459 (defvar org-match-substring-with-braces-regexp)
3460 (defvar org-export-html-special-string-regexps)
3462 (defun org-compute-latex-and-specials-regexp ()
3463 "Compute regular expression for stuff treated specially by exporters."
3464 (if (not org-highlight-latex-fragments-and-specials)
3465 (org-set-local 'org-latex-and-specials-regexp nil)
3466 (require 'org-exp)
3467 (let*
3468 ((matchers (plist-get org-format-latex-options :matchers))
3469 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3470 org-latex-regexps)))
3471 (options (org-combine-plists (org-default-export-plist)
3472 (org-infile-export-plist)))
3473 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3474 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3475 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3476 (org-export-html-expand (plist-get options :expand-quoted-html))
3477 (org-export-with-special-strings (plist-get options :special-strings))
3478 (re-sub
3479 (cond
3480 ((equal org-export-with-sub-superscripts '{})
3481 (list org-match-substring-with-braces-regexp))
3482 (org-export-with-sub-superscripts
3483 (list org-match-substring-regexp))
3484 (t nil)))
3485 (re-latex
3486 (if org-export-with-LaTeX-fragments
3487 (mapcar (lambda (x) (nth 1 x)) latexs)))
3488 (re-macros
3489 (if org-export-with-TeX-macros
3490 (list (concat "\\\\"
3491 (regexp-opt
3492 (append (mapcar 'car org-html-entities)
3493 (if (boundp 'org-latex-entities)
3494 org-latex-entities nil))
3495 'words))) ; FIXME
3497 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3498 (re-special (if org-export-with-special-strings
3499 (mapcar (lambda (x) (car x))
3500 org-export-html-special-string-regexps)))
3501 (re-rest
3502 (delq nil
3503 (list
3504 (if org-export-html-expand "@<[^>\n]+>")
3505 ))))
3506 (org-set-local
3507 'org-latex-and-specials-regexp
3508 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3509 re-rest) "\\|")))))
3511 (defun org-do-latex-and-special-faces (limit)
3512 "Run through the buffer and add overlays to links."
3513 (when org-latex-and-specials-regexp
3514 (let (rtn d)
3515 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3516 limit t))
3517 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3518 'face))
3519 '(org-code org-verbatim underline)))
3520 (progn
3521 (setq rtn t
3522 d (cond ((member (char-after (1+ (match-beginning 0)))
3523 '(?_ ?^)) 1)
3524 (t 0)))
3525 (font-lock-prepend-text-property
3526 (+ d (match-beginning 0)) (match-end 0)
3527 'face 'org-latex-and-export-specials)
3528 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3529 '(font-lock-multiline t)))))
3530 rtn)))
3532 (defun org-restart-font-lock ()
3533 "Restart font-lock-mode, to force refontification."
3534 (when (and (boundp 'font-lock-mode) font-lock-mode)
3535 (font-lock-mode -1)
3536 (font-lock-mode 1)))
3538 (defun org-all-targets (&optional radio)
3539 "Return a list of all targets in this file.
3540 With optional argument RADIO, only find radio targets."
3541 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3542 rtn)
3543 (save-excursion
3544 (goto-char (point-min))
3545 (while (re-search-forward re nil t)
3546 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3547 rtn)))
3549 (defun org-make-target-link-regexp (targets)
3550 "Make regular expression matching all strings in TARGETS.
3551 The regular expression finds the targets also if there is a line break
3552 between words."
3553 (and targets
3554 (concat
3555 "\\<\\("
3556 (mapconcat
3557 (lambda (x)
3558 (while (string-match " +" x)
3559 (setq x (replace-match "\\s-+" t t x)))
3561 targets
3562 "\\|")
3563 "\\)\\>")))
3565 (defun org-activate-tags (limit)
3566 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3567 (progn
3568 (add-text-properties (match-beginning 1) (match-end 1)
3569 (list 'mouse-face 'highlight
3570 'rear-nonsticky org-nonsticky-props
3571 'keymap org-mouse-map))
3572 t)))
3574 (defun org-outline-level ()
3575 (save-excursion
3576 (looking-at outline-regexp)
3577 (if (match-beginning 1)
3578 (+ (org-get-string-indentation (match-string 1)) 1000)
3579 (1- (- (match-end 0) (match-beginning 0))))))
3581 (defvar org-font-lock-keywords nil)
3583 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3584 "Regular expression matching a property line.")
3586 (defun org-set-font-lock-defaults ()
3587 (let* ((em org-fontify-emphasized-text)
3588 (lk org-activate-links)
3589 (org-font-lock-extra-keywords
3590 (list
3591 ;; Headlines
3592 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3593 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3594 ;; Table lines
3595 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3596 (1 'org-table t))
3597 ;; Table internals
3598 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3599 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3600 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3601 ;; Drawers
3602 (list org-drawer-regexp '(0 'org-special-keyword t))
3603 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3604 ;; Properties
3605 (list org-property-re
3606 '(1 'org-special-keyword t)
3607 '(3 'org-property-value t))
3608 (if org-format-transports-properties-p
3609 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3610 ;; Links
3611 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3612 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3613 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3614 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3615 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3616 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3617 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3618 '(org-hide-wide-columns (0 nil append))
3619 ;; TODO lines
3620 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3621 '(1 (org-get-todo-face 1) t))
3622 ;; DONE
3623 (if org-fontify-done-headline
3624 (list (concat "^[*]+ +\\<\\("
3625 (mapconcat 'regexp-quote org-done-keywords "\\|")
3626 "\\)\\(.*\\)")
3627 '(2 'org-headline-done t))
3628 nil)
3629 ;; Priorities
3630 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3631 ;; Special keywords
3632 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3633 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3634 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3635 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3636 ;; Emphasis
3637 (if em
3638 (if (featurep 'xemacs)
3639 '(org-do-emphasis-faces (0 nil append))
3640 '(org-do-emphasis-faces)))
3641 ;; Checkboxes
3642 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3643 2 'bold prepend)
3644 (if org-provide-checkbox-statistics
3645 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3646 (0 (org-get-checkbox-statistics-face) t)))
3647 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3648 '(1 'org-archived prepend))
3649 ;; Specials
3650 '(org-do-latex-and-special-faces)
3651 ;; Code
3652 '(org-activate-code (1 'org-code t))
3653 ;; COMMENT
3654 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3655 "\\|" org-quote-string "\\)\\>")
3656 '(1 'org-special-keyword t))
3657 '("^#.*" (0 'font-lock-comment-face t))
3659 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3660 ;; Now set the full font-lock-keywords
3661 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3662 (org-set-local 'font-lock-defaults
3663 '(org-font-lock-keywords t nil nil backward-paragraph))
3664 (kill-local-variable 'font-lock-keywords) nil))
3666 (defvar org-m nil)
3667 (defvar org-l nil)
3668 (defvar org-f nil)
3669 (defun org-get-level-face (n)
3670 "Get the right face for match N in font-lock matching of healdines."
3671 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3672 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3673 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3674 (cond
3675 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3676 ((eq n 2) org-f)
3677 (t (if org-level-color-stars-only nil org-f))))
3679 (defun org-get-todo-face (kwd)
3680 "Get the right face for a TODO keyword KWD.
3681 If KWD is a number, get the corresponding match group."
3682 (if (numberp kwd) (setq kwd (match-string kwd)))
3683 (or (cdr (assoc kwd org-todo-keyword-faces))
3684 (and (member kwd org-done-keywords) 'org-done)
3685 'org-todo))
3687 (defun org-unfontify-region (beg end &optional maybe_loudly)
3688 "Remove fontification and activation overlays from links."
3689 (font-lock-default-unfontify-region beg end)
3690 (let* ((buffer-undo-list t)
3691 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3692 (inhibit-modification-hooks t)
3693 deactivate-mark buffer-file-name buffer-file-truename)
3694 (remove-text-properties beg end
3695 '(mouse-face t keymap t org-linked-text t
3696 invisible t intangible t))))
3698 ;;;; Visibility cycling, including org-goto and indirect buffer
3700 ;;; Cycling
3702 (defvar org-cycle-global-status nil)
3703 (make-variable-buffer-local 'org-cycle-global-status)
3704 (defvar org-cycle-subtree-status nil)
3705 (make-variable-buffer-local 'org-cycle-subtree-status)
3707 ;;;###autoload
3708 (defun org-cycle (&optional arg)
3709 "Visibility cycling for Org-mode.
3711 - When this function is called with a prefix argument, rotate the entire
3712 buffer through 3 states (global cycling)
3713 1. OVERVIEW: Show only top-level headlines.
3714 2. CONTENTS: Show all headlines of all levels, but no body text.
3715 3. SHOW ALL: Show everything.
3717 - When point is at the beginning of a headline, rotate the subtree started
3718 by this line through 3 different states (local cycling)
3719 1. FOLDED: Only the main headline is shown.
3720 2. CHILDREN: The main headline and the direct children are shown.
3721 From this state, you can move to one of the children
3722 and zoom in further.
3723 3. SUBTREE: Show the entire subtree, including body text.
3725 - When there is a numeric prefix, go up to a heading with level ARG, do
3726 a `show-subtree' and return to the previous cursor position. If ARG
3727 is negative, go up that many levels.
3729 - When point is not at the beginning of a headline, execute
3730 `indent-relative', like TAB normally does. See the option
3731 `org-cycle-emulate-tab' for details.
3733 - Special case: if point is at the beginning of the buffer and there is
3734 no headline in line 1, this function will act as if called with prefix arg.
3735 But only if also the variable `org-cycle-global-at-bob' is t."
3736 (interactive "P")
3737 (org-load-modules-maybe)
3738 (let* ((outline-regexp
3739 (if (and (org-mode-p) org-cycle-include-plain-lists)
3740 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3741 outline-regexp))
3742 (bob-special (and org-cycle-global-at-bob (bobp)
3743 (not (looking-at outline-regexp))))
3744 (org-cycle-hook
3745 (if bob-special
3746 (delq 'org-optimize-window-after-visibility-change
3747 (copy-sequence org-cycle-hook))
3748 org-cycle-hook))
3749 (pos (point)))
3751 (if (or bob-special (equal arg '(4)))
3752 ;; special case: use global cycling
3753 (setq arg t))
3755 (cond
3757 ((org-at-table-p 'any)
3758 ;; Enter the table or move to the next field in the table
3759 (or (org-table-recognize-table.el)
3760 (progn
3761 (if arg (org-table-edit-field t)
3762 (org-table-justify-field-maybe)
3763 (call-interactively 'org-table-next-field)))))
3765 ((eq arg t) ;; Global cycling
3767 (cond
3768 ((and (eq last-command this-command)
3769 (eq org-cycle-global-status 'overview))
3770 ;; We just created the overview - now do table of contents
3771 ;; This can be slow in very large buffers, so indicate action
3772 (message "CONTENTS...")
3773 (org-content)
3774 (message "CONTENTS...done")
3775 (setq org-cycle-global-status 'contents)
3776 (run-hook-with-args 'org-cycle-hook 'contents))
3778 ((and (eq last-command this-command)
3779 (eq org-cycle-global-status 'contents))
3780 ;; We just showed the table of contents - now show everything
3781 (show-all)
3782 (message "SHOW ALL")
3783 (setq org-cycle-global-status 'all)
3784 (run-hook-with-args 'org-cycle-hook 'all))
3787 ;; Default action: go to overview
3788 (org-overview)
3789 (message "OVERVIEW")
3790 (setq org-cycle-global-status 'overview)
3791 (run-hook-with-args 'org-cycle-hook 'overview))))
3793 ((and org-drawers org-drawer-regexp
3794 (save-excursion
3795 (beginning-of-line 1)
3796 (looking-at org-drawer-regexp)))
3797 ;; Toggle block visibility
3798 (org-flag-drawer
3799 (not (get-char-property (match-end 0) 'invisible))))
3801 ((integerp arg)
3802 ;; Show-subtree, ARG levels up from here.
3803 (save-excursion
3804 (org-back-to-heading)
3805 (outline-up-heading (if (< arg 0) (- arg)
3806 (- (funcall outline-level) arg)))
3807 (org-show-subtree)))
3809 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3810 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3811 ;; At a heading: rotate between three different views
3812 (org-back-to-heading)
3813 (let ((goal-column 0) eoh eol eos)
3814 ;; First, some boundaries
3815 (save-excursion
3816 (org-back-to-heading)
3817 (save-excursion
3818 (beginning-of-line 2)
3819 (while (and (not (eobp)) ;; this is like `next-line'
3820 (get-char-property (1- (point)) 'invisible))
3821 (beginning-of-line 2)) (setq eol (point)))
3822 (outline-end-of-heading) (setq eoh (point))
3823 (org-end-of-subtree t)
3824 (unless (eobp)
3825 (skip-chars-forward " \t\n")
3826 (beginning-of-line 1) ; in case this is an item
3828 (setq eos (1- (point))))
3829 ;; Find out what to do next and set `this-command'
3830 (cond
3831 ((= eos eoh)
3832 ;; Nothing is hidden behind this heading
3833 (message "EMPTY ENTRY")
3834 (setq org-cycle-subtree-status nil)
3835 (save-excursion
3836 (goto-char eos)
3837 (outline-next-heading)
3838 (if (org-invisible-p) (org-flag-heading nil))))
3839 ((or (>= eol eos)
3840 (not (string-match "\\S-" (buffer-substring eol eos))))
3841 ;; Entire subtree is hidden in one line: open it
3842 (org-show-entry)
3843 (show-children)
3844 (message "CHILDREN")
3845 (save-excursion
3846 (goto-char eos)
3847 (outline-next-heading)
3848 (if (org-invisible-p) (org-flag-heading nil)))
3849 (setq org-cycle-subtree-status 'children)
3850 (run-hook-with-args 'org-cycle-hook 'children))
3851 ((and (eq last-command this-command)
3852 (eq org-cycle-subtree-status 'children))
3853 ;; We just showed the children, now show everything.
3854 (org-show-subtree)
3855 (message "SUBTREE")
3856 (setq org-cycle-subtree-status 'subtree)
3857 (run-hook-with-args 'org-cycle-hook 'subtree))
3859 ;; Default action: hide the subtree.
3860 (hide-subtree)
3861 (message "FOLDED")
3862 (setq org-cycle-subtree-status 'folded)
3863 (run-hook-with-args 'org-cycle-hook 'folded)))))
3865 ;; TAB emulation
3866 (buffer-read-only (org-back-to-heading))
3868 ((org-try-cdlatex-tab))
3870 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3871 (or (not (bolp))
3872 (not (looking-at outline-regexp))))
3873 (call-interactively (global-key-binding "\t")))
3875 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3876 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3877 (or (and (eq org-cycle-emulate-tab 'white)
3878 (= (match-end 0) (point-at-eol)))
3879 (and (eq org-cycle-emulate-tab 'whitestart)
3880 (>= (match-end 0) pos))))
3882 (eq org-cycle-emulate-tab t))
3883 (call-interactively (global-key-binding "\t")))
3885 (t (save-excursion
3886 (org-back-to-heading)
3887 (org-cycle))))))
3889 ;;;###autoload
3890 (defun org-global-cycle (&optional arg)
3891 "Cycle the global visibility. For details see `org-cycle'."
3892 (interactive "P")
3893 (let ((org-cycle-include-plain-lists
3894 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3895 (if (integerp arg)
3896 (progn
3897 (show-all)
3898 (hide-sublevels arg)
3899 (setq org-cycle-global-status 'contents))
3900 (org-cycle '(4)))))
3902 (defun org-overview ()
3903 "Switch to overview mode, shoing only top-level headlines.
3904 Really, this shows all headlines with level equal or greater than the level
3905 of the first headline in the buffer. This is important, because if the
3906 first headline is not level one, then (hide-sublevels 1) gives confusing
3907 results."
3908 (interactive)
3909 (let ((level (save-excursion
3910 (goto-char (point-min))
3911 (if (re-search-forward (concat "^" outline-regexp) nil t)
3912 (progn
3913 (goto-char (match-beginning 0))
3914 (funcall outline-level))))))
3915 (and level (hide-sublevels level))))
3917 (defun org-content (&optional arg)
3918 "Show all headlines in the buffer, like a table of contents.
3919 With numerical argument N, show content up to level N."
3920 (interactive "P")
3921 (save-excursion
3922 ;; Visit all headings and show their offspring
3923 (and (integerp arg) (org-overview))
3924 (goto-char (point-max))
3925 (catch 'exit
3926 (while (and (progn (condition-case nil
3927 (outline-previous-visible-heading 1)
3928 (error (goto-char (point-min))))
3930 (looking-at outline-regexp))
3931 (if (integerp arg)
3932 (show-children (1- arg))
3933 (show-branches))
3934 (if (bobp) (throw 'exit nil))))))
3937 (defun org-optimize-window-after-visibility-change (state)
3938 "Adjust the window after a change in outline visibility.
3939 This function is the default value of the hook `org-cycle-hook'."
3940 (when (get-buffer-window (current-buffer))
3941 (cond
3942 ; ((eq state 'overview) (org-first-headline-recenter 1))
3943 ; ((eq state 'overview) (org-beginning-of-line))
3944 ((eq state 'content) nil)
3945 ((eq state 'all) nil)
3946 ((eq state 'folded) nil)
3947 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3948 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3950 (defun org-compact-display-after-subtree-move ()
3951 (let (beg end)
3952 (save-excursion
3953 (if (org-up-heading-safe)
3954 (progn
3955 (hide-subtree)
3956 (show-entry)
3957 (show-children)
3958 (org-cycle-show-empty-lines 'children)
3959 (org-cycle-hide-drawers 'children))
3960 (org-overview)))))
3962 (defun org-cycle-show-empty-lines (state)
3963 "Show empty lines above all visible headlines.
3964 The region to be covered depends on STATE when called through
3965 `org-cycle-hook'. Lisp program can use t for STATE to get the
3966 entire buffer covered. Note that an empty line is only shown if there
3967 are at least `org-cycle-separator-lines' empty lines before the headeline."
3968 (when (> org-cycle-separator-lines 0)
3969 (save-excursion
3970 (let* ((n org-cycle-separator-lines)
3971 (re (cond
3972 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3973 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3974 (t (let ((ns (number-to-string (- n 2))))
3975 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3976 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3977 beg end)
3978 (cond
3979 ((memq state '(overview contents t))
3980 (setq beg (point-min) end (point-max)))
3981 ((memq state '(children folded))
3982 (setq beg (point) end (progn (org-end-of-subtree t t)
3983 (beginning-of-line 2)
3984 (point)))))
3985 (when beg
3986 (goto-char beg)
3987 (while (re-search-forward re end t)
3988 (if (not (get-char-property (match-end 1) 'invisible))
3989 (outline-flag-region
3990 (match-beginning 1) (match-end 1) nil)))))))
3991 ;; Never hide empty lines at the end of the file.
3992 (save-excursion
3993 (goto-char (point-max))
3994 (outline-previous-heading)
3995 (outline-end-of-heading)
3996 (if (and (looking-at "[ \t\n]+")
3997 (= (match-end 0) (point-max)))
3998 (outline-flag-region (point) (match-end 0) nil))))
4000 (defun org-cycle-hide-drawers (state)
4001 "Re-hide all drawers after a visibility state change."
4002 (when (and (org-mode-p)
4003 (not (memq state '(overview folded))))
4004 (save-excursion
4005 (let* ((globalp (memq state '(contents all)))
4006 (beg (if globalp (point-min) (point)))
4007 (end (if globalp (point-max) (org-end-of-subtree t))))
4008 (goto-char beg)
4009 (while (re-search-forward org-drawer-regexp end t)
4010 (org-flag-drawer t))))))
4012 (defun org-flag-drawer (flag)
4013 (save-excursion
4014 (beginning-of-line 1)
4015 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4016 (let ((b (match-end 0))
4017 (outline-regexp org-outline-regexp))
4018 (if (re-search-forward
4019 "^[ \t]*:END:"
4020 (save-excursion (outline-next-heading) (point)) t)
4021 (outline-flag-region b (point-at-eol) flag)
4022 (error ":END: line missing"))))))
4026 (defun org-subtree-end-visible-p ()
4027 "Is the end of the current subtree visible?"
4028 (pos-visible-in-window-p
4029 (save-excursion (org-end-of-subtree t) (point))))
4031 (defun org-first-headline-recenter (&optional N)
4032 "Move cursor to the first headline and recenter the headline.
4033 Optional argument N means, put the headline into the Nth line of the window."
4034 (goto-char (point-min))
4035 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4036 (beginning-of-line)
4037 (recenter (prefix-numeric-value N))))
4039 ;;; Org-goto
4041 (defvar org-goto-window-configuration nil)
4042 (defvar org-goto-marker nil)
4043 (defvar org-goto-map
4044 (let ((map (make-sparse-keymap)))
4045 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4046 (while (setq cmd (pop cmds))
4047 (substitute-key-definition cmd cmd map global-map)))
4048 (suppress-keymap map)
4049 (org-defkey map "\C-m" 'org-goto-ret)
4050 (org-defkey map [(return)] 'org-goto-ret)
4051 (org-defkey map [(left)] 'org-goto-left)
4052 (org-defkey map [(right)] 'org-goto-right)
4053 (org-defkey map [(control ?g)] 'org-goto-quit)
4054 (org-defkey map "\C-i" 'org-cycle)
4055 (org-defkey map [(tab)] 'org-cycle)
4056 (org-defkey map [(down)] 'outline-next-visible-heading)
4057 (org-defkey map [(up)] 'outline-previous-visible-heading)
4058 (if org-goto-auto-isearch
4059 (if (fboundp 'define-key-after)
4060 (define-key-after map [t] 'org-goto-local-auto-isearch)
4061 nil)
4062 (org-defkey map "q" 'org-goto-quit)
4063 (org-defkey map "n" 'outline-next-visible-heading)
4064 (org-defkey map "p" 'outline-previous-visible-heading)
4065 (org-defkey map "f" 'outline-forward-same-level)
4066 (org-defkey map "b" 'outline-backward-same-level)
4067 (org-defkey map "u" 'outline-up-heading))
4068 (org-defkey map "/" 'org-occur)
4069 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4070 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4071 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4072 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4073 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4074 map))
4076 (defconst org-goto-help
4077 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4078 RET=jump to location [Q]uit and return to previous location
4079 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4081 (defvar org-goto-start-pos) ; dynamically scoped parameter
4083 (defun org-goto (&optional alternative-interface)
4084 "Look up a different location in the current file, keeping current visibility.
4086 When you want look-up or go to a different location in a document, the
4087 fastest way is often to fold the entire buffer and then dive into the tree.
4088 This method has the disadvantage, that the previous location will be folded,
4089 which may not be what you want.
4091 This command works around this by showing a copy of the current buffer
4092 in an indirect buffer, in overview mode. You can dive into the tree in
4093 that copy, use org-occur and incremental search to find a location.
4094 When pressing RET or `Q', the command returns to the original buffer in
4095 which the visibility is still unchanged. After RET is will also jump to
4096 the location selected in the indirect buffer and expose the
4097 the headline hierarchy above."
4098 (interactive "P")
4099 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4100 (org-refile-use-outline-path t)
4101 (interface
4102 (if (not alternative-interface)
4103 org-goto-interface
4104 (if (eq org-goto-interface 'outline)
4105 'outline-path-completion
4106 'outline)))
4107 (org-goto-start-pos (point))
4108 (selected-point
4109 (if (eq interface 'outline)
4110 (car (org-get-location (current-buffer) org-goto-help))
4111 (nth 3 (org-refile-get-location "Goto: ")))))
4112 (if selected-point
4113 (progn
4114 (org-mark-ring-push org-goto-start-pos)
4115 (goto-char selected-point)
4116 (if (or (org-invisible-p) (org-invisible-p2))
4117 (org-show-context 'org-goto)))
4118 (message "Quit"))))
4120 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4121 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4122 (defvar org-goto-local-auto-isearch-map) ; defined below
4124 (defun org-get-location (buf help)
4125 "Let the user select a location in the Org-mode buffer BUF.
4126 This function uses a recursive edit. It returns the selected position
4127 or nil."
4128 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4129 (isearch-hide-immediately nil)
4130 (isearch-search-fun-function
4131 (lambda () 'org-goto-local-search-forward-headings))
4132 (org-goto-selected-point org-goto-exit-command))
4133 (save-excursion
4134 (save-window-excursion
4135 (delete-other-windows)
4136 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4137 (switch-to-buffer
4138 (condition-case nil
4139 (make-indirect-buffer (current-buffer) "*org-goto*")
4140 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4141 (with-output-to-temp-buffer "*Help*"
4142 (princ help))
4143 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4144 (setq buffer-read-only nil)
4145 (let ((org-startup-truncated t)
4146 (org-startup-folded nil)
4147 (org-startup-align-all-tables nil))
4148 (org-mode)
4149 (org-overview))
4150 (setq buffer-read-only t)
4151 (if (and (boundp 'org-goto-start-pos)
4152 (integer-or-marker-p org-goto-start-pos))
4153 (let ((org-show-hierarchy-above t)
4154 (org-show-siblings t)
4155 (org-show-following-heading t))
4156 (goto-char org-goto-start-pos)
4157 (and (org-invisible-p) (org-show-context)))
4158 (goto-char (point-min)))
4159 (org-beginning-of-line)
4160 (message "Select location and press RET")
4161 (use-local-map org-goto-map)
4162 (recursive-edit)
4164 (kill-buffer "*org-goto*")
4165 (cons org-goto-selected-point org-goto-exit-command)))
4167 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4168 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4169 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4170 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4172 (defun org-goto-local-search-forward-headings (string bound noerror)
4173 "Search and make sure that anu matches are in headlines."
4174 (catch 'return
4175 (while (search-forward string bound noerror)
4176 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4177 (and (member :headline context)
4178 (not (member :tags context))))
4179 (throw 'return (point))))))
4181 (defun org-goto-local-auto-isearch ()
4182 "Start isearch."
4183 (interactive)
4184 (goto-char (point-min))
4185 (let ((keys (this-command-keys)))
4186 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4187 (isearch-mode t)
4188 (isearch-process-search-char (string-to-char keys)))))
4190 (defun org-goto-ret (&optional arg)
4191 "Finish `org-goto' by going to the new location."
4192 (interactive "P")
4193 (setq org-goto-selected-point (point)
4194 org-goto-exit-command 'return)
4195 (throw 'exit nil))
4197 (defun org-goto-left ()
4198 "Finish `org-goto' by going to the new location."
4199 (interactive)
4200 (if (org-on-heading-p)
4201 (progn
4202 (beginning-of-line 1)
4203 (setq org-goto-selected-point (point)
4204 org-goto-exit-command 'left)
4205 (throw 'exit nil))
4206 (error "Not on a heading")))
4208 (defun org-goto-right ()
4209 "Finish `org-goto' by going to the new location."
4210 (interactive)
4211 (if (org-on-heading-p)
4212 (progn
4213 (setq org-goto-selected-point (point)
4214 org-goto-exit-command 'right)
4215 (throw 'exit nil))
4216 (error "Not on a heading")))
4218 (defun org-goto-quit ()
4219 "Finish `org-goto' without cursor motion."
4220 (interactive)
4221 (setq org-goto-selected-point nil)
4222 (setq org-goto-exit-command 'quit)
4223 (throw 'exit nil))
4225 ;;; Indirect buffer display of subtrees
4227 (defvar org-indirect-dedicated-frame nil
4228 "This is the frame being used for indirect tree display.")
4229 (defvar org-last-indirect-buffer nil)
4231 (defun org-tree-to-indirect-buffer (&optional arg)
4232 "Create indirect buffer and narrow it to current subtree.
4233 With numerical prefix ARG, go up to this level and then take that tree.
4234 If ARG is negative, go up that many levels.
4235 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4236 indirect buffer previously made with this command, to avoid proliferation of
4237 indirect buffers. However, when you call the command with a `C-u' prefix, or
4238 when `org-indirect-buffer-display' is `new-frame', the last buffer
4239 is kept so that you can work with several indirect buffers at the same time.
4240 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4241 requests that a new frame be made for the new buffer, so that the dedicated
4242 frame is not changed."
4243 (interactive "P")
4244 (let ((cbuf (current-buffer))
4245 (cwin (selected-window))
4246 (pos (point))
4247 beg end level heading ibuf)
4248 (save-excursion
4249 (org-back-to-heading t)
4250 (when (numberp arg)
4251 (setq level (org-outline-level))
4252 (if (< arg 0) (setq arg (+ level arg)))
4253 (while (> (setq level (org-outline-level)) arg)
4254 (outline-up-heading 1 t)))
4255 (setq beg (point)
4256 heading (org-get-heading))
4257 (org-end-of-subtree t) (setq end (point)))
4258 (if (and (buffer-live-p org-last-indirect-buffer)
4259 (not (eq org-indirect-buffer-display 'new-frame))
4260 (not arg))
4261 (kill-buffer org-last-indirect-buffer))
4262 (setq ibuf (org-get-indirect-buffer cbuf)
4263 org-last-indirect-buffer ibuf)
4264 (cond
4265 ((or (eq org-indirect-buffer-display 'new-frame)
4266 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4267 (select-frame (make-frame))
4268 (delete-other-windows)
4269 (switch-to-buffer ibuf)
4270 (org-set-frame-title heading))
4271 ((eq org-indirect-buffer-display 'dedicated-frame)
4272 (raise-frame
4273 (select-frame (or (and org-indirect-dedicated-frame
4274 (frame-live-p org-indirect-dedicated-frame)
4275 org-indirect-dedicated-frame)
4276 (setq org-indirect-dedicated-frame (make-frame)))))
4277 (delete-other-windows)
4278 (switch-to-buffer ibuf)
4279 (org-set-frame-title (concat "Indirect: " heading)))
4280 ((eq org-indirect-buffer-display 'current-window)
4281 (switch-to-buffer ibuf))
4282 ((eq org-indirect-buffer-display 'other-window)
4283 (pop-to-buffer ibuf))
4284 (t (error "Invalid value.")))
4285 (if (featurep 'xemacs)
4286 (save-excursion (org-mode) (turn-on-font-lock)))
4287 (narrow-to-region beg end)
4288 (show-all)
4289 (goto-char pos)
4290 (and (window-live-p cwin) (select-window cwin))))
4292 (defun org-get-indirect-buffer (&optional buffer)
4293 (setq buffer (or buffer (current-buffer)))
4294 (let ((n 1) (base (buffer-name buffer)) bname)
4295 (while (buffer-live-p
4296 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4297 (setq n (1+ n)))
4298 (condition-case nil
4299 (make-indirect-buffer buffer bname 'clone)
4300 (error (make-indirect-buffer buffer bname)))))
4302 (defun org-set-frame-title (title)
4303 "Set the title of the current frame to the string TITLE."
4304 ;; FIXME: how to name a single frame in XEmacs???
4305 (unless (featurep 'xemacs)
4306 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4308 ;;;; Structure editing
4310 ;;; Inserting headlines
4312 (defun org-insert-heading (&optional force-heading)
4313 "Insert a new heading or item with same depth at point.
4314 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4315 If point is at the beginning of a headline, insert a sibling before the
4316 current headline. If point is not at the beginning, do not split the line,
4317 but create the new hedline after the current line."
4318 (interactive "P")
4319 (if (= (buffer-size) 0)
4320 (insert "\n* ")
4321 (when (or force-heading (not (org-insert-item)))
4322 (let* ((head (save-excursion
4323 (condition-case nil
4324 (progn
4325 (org-back-to-heading)
4326 (match-string 0))
4327 (error "*"))))
4328 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4329 pos)
4330 (cond
4331 ((and (org-on-heading-p) (bolp)
4332 (or (bobp)
4333 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4334 ;; insert before the current line
4335 (open-line (if blank 2 1)))
4336 ((and (bolp)
4337 (or (bobp)
4338 (save-excursion
4339 (backward-char 1) (not (org-invisible-p)))))
4340 ;; insert right here
4341 nil)
4343 ;; in the middle of the line
4344 (org-show-entry)
4345 (let ((split
4346 (org-get-alist-option org-M-RET-may-split-line 'headline))
4347 tags pos)
4348 (if (org-on-heading-p)
4349 (progn
4350 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4351 (setq tags (and (match-end 2) (match-string 2)))
4352 (and (match-end 1)
4353 (delete-region (match-beginning 1) (match-end 1)))
4354 (setq pos (point-at-bol))
4355 (or split (end-of-line 1))
4356 (delete-horizontal-space)
4357 (newline (if blank 2 1))
4358 (when tags
4359 (save-excursion
4360 (goto-char pos)
4361 (end-of-line 1)
4362 (insert " " tags)
4363 (org-set-tags nil 'align))))
4364 (or split (end-of-line 1))
4365 (newline (if blank 2 1))))))
4366 (insert head) (just-one-space)
4367 (setq pos (point))
4368 (end-of-line 1)
4369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4370 (run-hooks 'org-insert-heading-hook)))))
4372 (defun org-get-heading (&optional no-tags)
4373 "Return the heading of the current entry, without the stars."
4374 (save-excursion
4375 (org-back-to-heading t)
4376 (if (looking-at
4377 (if no-tags
4378 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4379 "\\*+[ \t]+\\([^\r\n]*\\)"))
4380 (match-string 1) "")))
4382 (defun org-insert-heading-after-current ()
4383 "Insert a new heading with same level as current, after current subtree."
4384 (interactive)
4385 (org-back-to-heading)
4386 (org-insert-heading)
4387 (org-move-subtree-down)
4388 (end-of-line 1))
4390 (defun org-insert-todo-heading (arg)
4391 "Insert a new heading with the same level and TODO state as current heading.
4392 If the heading has no TODO state, or if the state is DONE, use the first
4393 state (TODO by default). Also with prefix arg, force first state."
4394 (interactive "P")
4395 (when (not (org-insert-item 'checkbox))
4396 (org-insert-heading)
4397 (save-excursion
4398 (org-back-to-heading)
4399 (outline-previous-heading)
4400 (looking-at org-todo-line-regexp))
4401 (if (or arg
4402 (not (match-beginning 2))
4403 (member (match-string 2) org-done-keywords))
4404 (insert (car org-todo-keywords-1) " ")
4405 (insert (match-string 2) " "))))
4407 (defun org-insert-subheading (arg)
4408 "Insert a new subheading and demote it.
4409 Works for outline headings and for plain lists alike."
4410 (interactive "P")
4411 (org-insert-heading arg)
4412 (cond
4413 ((org-on-heading-p) (org-do-demote))
4414 ((org-at-item-p) (org-indent-item 1))))
4416 (defun org-insert-todo-subheading (arg)
4417 "Insert a new subheading with TODO keyword or checkbox and demote it.
4418 Works for outline headings and for plain lists alike."
4419 (interactive "P")
4420 (org-insert-todo-heading arg)
4421 (cond
4422 ((org-on-heading-p) (org-do-demote))
4423 ((org-at-item-p) (org-indent-item 1))))
4425 ;;; Promotion and Demotion
4427 (defun org-promote-subtree ()
4428 "Promote the entire subtree.
4429 See also `org-promote'."
4430 (interactive)
4431 (save-excursion
4432 (org-map-tree 'org-promote))
4433 (org-fix-position-after-promote))
4435 (defun org-demote-subtree ()
4436 "Demote the entire subtree. See `org-demote'.
4437 See also `org-promote'."
4438 (interactive)
4439 (save-excursion
4440 (org-map-tree 'org-demote))
4441 (org-fix-position-after-promote))
4444 (defun org-do-promote ()
4445 "Promote the current heading higher up the tree.
4446 If the region is active in `transient-mark-mode', promote all headings
4447 in the region."
4448 (interactive)
4449 (save-excursion
4450 (if (org-region-active-p)
4451 (org-map-region 'org-promote (region-beginning) (region-end))
4452 (org-promote)))
4453 (org-fix-position-after-promote))
4455 (defun org-do-demote ()
4456 "Demote the current heading lower down the tree.
4457 If the region is active in `transient-mark-mode', demote all headings
4458 in the region."
4459 (interactive)
4460 (save-excursion
4461 (if (org-region-active-p)
4462 (org-map-region 'org-demote (region-beginning) (region-end))
4463 (org-demote)))
4464 (org-fix-position-after-promote))
4466 (defun org-fix-position-after-promote ()
4467 "Make sure that after pro/demotion cursor position is right."
4468 (let ((pos (point)))
4469 (when (save-excursion
4470 (beginning-of-line 1)
4471 (looking-at org-todo-line-regexp)
4472 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4473 (cond ((eobp) (insert " "))
4474 ((eolp) (insert " "))
4475 ((equal (char-after) ?\ ) (forward-char 1))))))
4477 (defun org-reduced-level (l)
4478 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4480 (defun org-get-valid-level (level &optional change)
4481 "Rectify a level change under the influence of `org-odd-levels-only'
4482 LEVEL is a current level, CHANGE is by how much the level should be
4483 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4484 even level numbers will become the next higher odd number."
4485 (if org-odd-levels-only
4486 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4487 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4488 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4489 (max 1 (+ level change))))
4491 (if (boundp 'define-obsolete-function-alias)
4492 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4493 (define-obsolete-function-alias 'org-get-legal-level
4494 'org-get-valid-level)
4495 (define-obsolete-function-alias 'org-get-legal-level
4496 'org-get-valid-level "23.1")))
4498 (defun org-promote ()
4499 "Promote the current heading higher up the tree.
4500 If the region is active in `transient-mark-mode', promote all headings
4501 in the region."
4502 (org-back-to-heading t)
4503 (let* ((level (save-match-data (funcall outline-level)))
4504 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4505 (diff (abs (- level (length up-head) -1))))
4506 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4507 (replace-match up-head nil t)
4508 ;; Fixup tag positioning
4509 (and org-auto-align-tags (org-set-tags nil t))
4510 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4512 (defun org-demote ()
4513 "Demote the current heading lower down the tree.
4514 If the region is active in `transient-mark-mode', demote all headings
4515 in the region."
4516 (org-back-to-heading t)
4517 (let* ((level (save-match-data (funcall outline-level)))
4518 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4519 (diff (abs (- level (length down-head) -1))))
4520 (replace-match down-head nil t)
4521 ;; Fixup tag positioning
4522 (and org-auto-align-tags (org-set-tags nil t))
4523 (if org-adapt-indentation (org-fixup-indentation diff))))
4525 (defun org-map-tree (fun)
4526 "Call FUN for every heading underneath the current one."
4527 (org-back-to-heading)
4528 (let ((level (funcall outline-level)))
4529 (save-excursion
4530 (funcall fun)
4531 (while (and (progn
4532 (outline-next-heading)
4533 (> (funcall outline-level) level))
4534 (not (eobp)))
4535 (funcall fun)))))
4537 (defun org-map-region (fun beg end)
4538 "Call FUN for every heading between BEG and END."
4539 (let ((org-ignore-region t))
4540 (save-excursion
4541 (setq end (copy-marker end))
4542 (goto-char beg)
4543 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4544 (< (point) end))
4545 (funcall fun))
4546 (while (and (progn
4547 (outline-next-heading)
4548 (< (point) end))
4549 (not (eobp)))
4550 (funcall fun)))))
4552 (defun org-fixup-indentation (diff)
4553 "Change the indentation in the current entry by DIFF
4554 However, if any line in the current entry has no indentation, or if it
4555 would end up with no indentation after the change, nothing at all is done."
4556 (save-excursion
4557 (let ((end (save-excursion (outline-next-heading)
4558 (point-marker)))
4559 (prohibit (if (> diff 0)
4560 "^\\S-"
4561 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4562 col)
4563 (unless (save-excursion (end-of-line 1)
4564 (re-search-forward prohibit end t))
4565 (while (and (< (point) end)
4566 (re-search-forward "^[ \t]+" end t))
4567 (goto-char (match-end 0))
4568 (setq col (current-column))
4569 (if (< diff 0) (replace-match ""))
4570 (indent-to (+ diff col))))
4571 (move-marker end nil))))
4573 (defun org-convert-to-odd-levels ()
4574 "Convert an org-mode file with all levels allowed to one with odd levels.
4575 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4576 level 5 etc."
4577 (interactive)
4578 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4579 (let ((org-odd-levels-only nil) n)
4580 (save-excursion
4581 (goto-char (point-min))
4582 (while (re-search-forward "^\\*\\*+ " nil t)
4583 (setq n (- (length (match-string 0)) 2))
4584 (while (>= (setq n (1- n)) 0)
4585 (org-demote))
4586 (end-of-line 1))))))
4589 (defun org-convert-to-oddeven-levels ()
4590 "Convert an org-mode file with only odd levels to one with odd and even levels.
4591 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4592 section with an even level, conversion would destroy the structure of the file. An error
4593 is signaled in this case."
4594 (interactive)
4595 (goto-char (point-min))
4596 ;; First check if there are no even levels
4597 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4598 (org-show-context t)
4599 (error "Not all levels are odd in this file. Conversion not possible."))
4600 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4601 (let ((org-odd-levels-only nil) n)
4602 (save-excursion
4603 (goto-char (point-min))
4604 (while (re-search-forward "^\\*\\*+ " nil t)
4605 (setq n (/ (1- (length (match-string 0))) 2))
4606 (while (>= (setq n (1- n)) 0)
4607 (org-promote))
4608 (end-of-line 1))))))
4610 (defun org-tr-level (n)
4611 "Make N odd if required."
4612 (if org-odd-levels-only (1+ (/ n 2)) n))
4614 ;;; Vertical tree motion, cutting and pasting of subtrees
4616 (defun org-move-subtree-up (&optional arg)
4617 "Move the current subtree up past ARG headlines of the same level."
4618 (interactive "p")
4619 (org-move-subtree-down (- (prefix-numeric-value arg))))
4621 (defun org-move-subtree-down (&optional arg)
4622 "Move the current subtree down past ARG headlines of the same level."
4623 (interactive "p")
4624 (setq arg (prefix-numeric-value arg))
4625 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4626 'outline-get-last-sibling))
4627 (ins-point (make-marker))
4628 (cnt (abs arg))
4629 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4630 ;; Select the tree
4631 (org-back-to-heading)
4632 (setq beg0 (point))
4633 (save-excursion
4634 (setq ne-beg (org-back-over-empty-lines))
4635 (setq beg (point)))
4636 (save-match-data
4637 (save-excursion (outline-end-of-heading)
4638 (setq folded (org-invisible-p)))
4639 (outline-end-of-subtree))
4640 (outline-next-heading)
4641 (setq ne-end (org-back-over-empty-lines))
4642 (setq end (point))
4643 (goto-char beg0)
4644 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4645 ;; include less whitespace
4646 (save-excursion
4647 (goto-char beg)
4648 (forward-line (- ne-beg ne-end))
4649 (setq beg (point))))
4650 ;; Find insertion point, with error handling
4651 (while (> cnt 0)
4652 (or (and (funcall movfunc) (looking-at outline-regexp))
4653 (progn (goto-char beg0)
4654 (error "Cannot move past superior level or buffer limit")))
4655 (setq cnt (1- cnt)))
4656 (if (> arg 0)
4657 ;; Moving forward - still need to move over subtree
4658 (progn (org-end-of-subtree t t)
4659 (save-excursion
4660 (org-back-over-empty-lines)
4661 (or (bolp) (newline)))))
4662 (setq ne-ins (org-back-over-empty-lines))
4663 (move-marker ins-point (point))
4664 (setq txt (buffer-substring beg end))
4665 (delete-region beg end)
4666 (outline-flag-region (1- beg) beg nil)
4667 (outline-flag-region (1- (point)) (point) nil)
4668 (insert txt)
4669 (or (bolp) (insert "\n"))
4670 (setq ins-end (point))
4671 (goto-char ins-point)
4672 (org-skip-whitespace)
4673 (when (and (< arg 0)
4674 (org-first-sibling-p)
4675 (> ne-ins ne-beg))
4676 ;; Move whitespace back to beginning
4677 (save-excursion
4678 (goto-char ins-end)
4679 (let ((kill-whole-line t))
4680 (kill-line (- ne-ins ne-beg)) (point)))
4681 (insert (make-string (- ne-ins ne-beg) ?\n)))
4682 (move-marker ins-point nil)
4683 (org-compact-display-after-subtree-move)
4684 (unless folded
4685 (org-show-entry)
4686 (show-children)
4687 (org-cycle-hide-drawers 'children))))
4689 (defvar org-subtree-clip ""
4690 "Clipboard for cut and paste of subtrees.
4691 This is actually only a copy of the kill, because we use the normal kill
4692 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4694 (defvar org-subtree-clip-folded nil
4695 "Was the last copied subtree folded?
4696 This is used to fold the tree back after pasting.")
4698 (defun org-cut-subtree (&optional n)
4699 "Cut the current subtree into the clipboard.
4700 With prefix arg N, cut this many sequential subtrees.
4701 This is a short-hand for marking the subtree and then cutting it."
4702 (interactive "p")
4703 (org-copy-subtree n 'cut))
4705 (defun org-copy-subtree (&optional n cut)
4706 "Cut the current subtree into the clipboard.
4707 With prefix arg N, cut this many sequential subtrees.
4708 This is a short-hand for marking the subtree and then copying it.
4709 If CUT is non-nil, actually cut the subtree."
4710 (interactive "p")
4711 (let (beg end folded (beg0 (point)))
4712 (if (interactive-p)
4713 (org-back-to-heading nil) ; take what looks like a subtree
4714 (org-back-to-heading t)) ; take what is really there
4715 (org-back-over-empty-lines)
4716 (setq beg (point))
4717 (skip-chars-forward " \t\r\n")
4718 (save-match-data
4719 (save-excursion (outline-end-of-heading)
4720 (setq folded (org-invisible-p)))
4721 (condition-case nil
4722 (outline-forward-same-level (1- n))
4723 (error nil))
4724 (org-end-of-subtree t t))
4725 (org-back-over-empty-lines)
4726 (setq end (point))
4727 (goto-char beg0)
4728 (when (> end beg)
4729 (setq org-subtree-clip-folded folded)
4730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4731 (setq org-subtree-clip (current-kill 0))
4732 (message "%s: Subtree(s) with %d characters"
4733 (if cut "Cut" "Copied")
4734 (length org-subtree-clip)))))
4736 (defun org-paste-subtree (&optional level tree)
4737 "Paste the clipboard as a subtree, with modification of headline level.
4738 The entire subtree is promoted or demoted in order to match a new headline
4739 level. By default, the new level is derived from the visible headings
4740 before and after the insertion point, and taken to be the inferior headline
4741 level of the two. So if the previous visible heading is level 3 and the
4742 next is level 4 (or vice versa), level 4 will be used for insertion.
4743 This makes sure that the subtree remains an independent subtree and does
4744 not swallow low level entries.
4746 You can also force a different level, either by using a numeric prefix
4747 argument, or by inserting the heading marker by hand. For example, if the
4748 cursor is after \"*****\", then the tree will be shifted to level 5.
4750 If you want to insert the tree as is, just use \\[yank].
4752 If optional TREE is given, use this text instead of the kill ring."
4753 (interactive "P")
4754 (unless (org-kill-is-subtree-p tree)
4755 (error "%s"
4756 (substitute-command-keys
4757 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4758 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4759 (^re (concat "^\\(" outline-regexp "\\)"))
4760 (re (concat "\\(" outline-regexp "\\)"))
4761 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4763 (old-level (if (string-match ^re txt)
4764 (- (match-end 0) (match-beginning 0) 1)
4765 -1))
4766 (force-level (cond (level (prefix-numeric-value level))
4767 ((string-match
4768 ^re_ (buffer-substring (point-at-bol) (point)))
4769 (- (match-end 1) (match-beginning 1)))
4770 (t nil)))
4771 (previous-level (save-excursion
4772 (condition-case nil
4773 (progn
4774 (outline-previous-visible-heading 1)
4775 (if (looking-at re)
4776 (- (match-end 0) (match-beginning 0) 1)
4778 (error 1))))
4779 (next-level (save-excursion
4780 (condition-case nil
4781 (progn
4782 (or (looking-at outline-regexp)
4783 (outline-next-visible-heading 1))
4784 (if (looking-at re)
4785 (- (match-end 0) (match-beginning 0) 1)
4787 (error 1))))
4788 (new-level (or force-level (max previous-level next-level)))
4789 (shift (if (or (= old-level -1)
4790 (= new-level -1)
4791 (= old-level new-level))
4793 (- new-level old-level)))
4794 (delta (if (> shift 0) -1 1))
4795 (func (if (> shift 0) 'org-demote 'org-promote))
4796 (org-odd-levels-only nil)
4797 beg end)
4798 ;; Remove the forced level indicator
4799 (if force-level
4800 (delete-region (point-at-bol) (point)))
4801 ;; Paste
4802 (beginning-of-line 1)
4803 (org-back-over-empty-lines)
4804 (setq beg (point))
4805 (insert-before-markers txt)
4806 (unless (string-match "\n\\'" txt) (insert "\n"))
4807 (setq end (point))
4808 (goto-char beg)
4809 (skip-chars-forward " \t\n\r")
4810 (setq beg (point))
4811 ;; Shift if necessary
4812 (unless (= shift 0)
4813 (save-restriction
4814 (narrow-to-region beg end)
4815 (while (not (= shift 0))
4816 (org-map-region func (point-min) (point-max))
4817 (setq shift (+ delta shift)))
4818 (goto-char (point-min))))
4819 (when (interactive-p)
4820 (message "Clipboard pasted as level %d subtree" new-level))
4821 (if (and kill-ring
4822 (eq org-subtree-clip (current-kill 0))
4823 org-subtree-clip-folded)
4824 ;; The tree was folded before it was killed/copied
4825 (hide-subtree))))
4827 (defun org-kill-is-subtree-p (&optional txt)
4828 "Check if the current kill is an outline subtree, or a set of trees.
4829 Returns nil if kill does not start with a headline, or if the first
4830 headline level is not the largest headline level in the tree.
4831 So this will actually accept several entries of equal levels as well,
4832 which is OK for `org-paste-subtree'.
4833 If optional TXT is given, check this string instead of the current kill."
4834 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4835 (start-level (and kill
4836 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4837 org-outline-regexp "\\)")
4838 kill)
4839 (- (match-end 2) (match-beginning 2) 1)))
4840 (re (concat "^" org-outline-regexp))
4841 (start (1+ (match-beginning 2))))
4842 (if (not start-level)
4843 (progn
4844 nil) ;; does not even start with a heading
4845 (catch 'exit
4846 (while (setq start (string-match re kill (1+ start)))
4847 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4848 (throw 'exit nil)))
4849 t))))
4851 (defun org-narrow-to-subtree ()
4852 "Narrow buffer to the current subtree."
4853 (interactive)
4854 (save-excursion
4855 (save-match-data
4856 (narrow-to-region
4857 (progn (org-back-to-heading) (point))
4858 (progn (org-end-of-subtree t t) (point))))))
4861 ;;; Outline Sorting
4863 (defun org-sort (with-case)
4864 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4865 Optional argument WITH-CASE means sort case-sensitively."
4866 (interactive "P")
4867 (if (org-at-table-p)
4868 (org-call-with-arg 'org-table-sort-lines with-case)
4869 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4871 (defun org-sort-remove-invisible (s)
4872 (remove-text-properties 0 (length s) org-rm-props s)
4873 (while (string-match org-bracket-link-regexp s)
4874 (setq s (replace-match (if (match-end 2)
4875 (match-string 3 s)
4876 (match-string 1 s)) t t s)))
4879 (defvar org-priority-regexp) ; defined later in the file
4881 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4882 "Sort entries on a certain level of an outline tree.
4883 If there is an active region, the entries in the region are sorted.
4884 Else, if the cursor is before the first entry, sort the top-level items.
4885 Else, the children of the entry at point are sorted.
4887 Sorting can be alphabetically, numerically, and by date/time as given by
4888 the first time stamp in the entry. The command prompts for the sorting
4889 type unless it has been given to the function through the SORTING-TYPE
4890 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4891 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4892 called with point at the beginning of the record. It must return either
4893 a string or a number that should serve as the sorting key for that record.
4895 Comparing entries ignores case by default. However, with an optional argument
4896 WITH-CASE, the sorting considers case as well."
4897 (interactive "P")
4898 (let ((case-func (if with-case 'identity 'downcase))
4899 start beg end stars re re2
4900 txt what tmp plain-list-p)
4901 ;; Find beginning and end of region to sort
4902 (cond
4903 ((org-region-active-p)
4904 ;; we will sort the region
4905 (setq end (region-end)
4906 what "region")
4907 (goto-char (region-beginning))
4908 (if (not (org-on-heading-p)) (outline-next-heading))
4909 (setq start (point)))
4910 ((org-at-item-p)
4911 ;; we will sort this plain list
4912 (org-beginning-of-item-list) (setq start (point))
4913 (org-end-of-item-list) (setq end (point))
4914 (goto-char start)
4915 (setq plain-list-p t
4916 what "plain list"))
4917 ((or (org-on-heading-p)
4918 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4919 ;; we will sort the children of the current headline
4920 (org-back-to-heading)
4921 (setq start (point)
4922 end (progn (org-end-of-subtree t t)
4923 (org-back-over-empty-lines)
4924 (point))
4925 what "children")
4926 (goto-char start)
4927 (show-subtree)
4928 (outline-next-heading))
4930 ;; we will sort the top-level entries in this file
4931 (goto-char (point-min))
4932 (or (org-on-heading-p) (outline-next-heading))
4933 (setq start (point) end (point-max) what "top-level")
4934 (goto-char start)
4935 (show-all)))
4937 (setq beg (point))
4938 (if (>= beg end) (error "Nothing to sort"))
4940 (unless plain-list-p
4941 (looking-at "\\(\\*+\\)")
4942 (setq stars (match-string 1)
4943 re (concat "^" (regexp-quote stars) " +")
4944 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4945 txt (buffer-substring beg end))
4946 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4947 (if (and (not (equal stars "*")) (string-match re2 txt))
4948 (error "Region to sort contains a level above the first entry")))
4950 (unless sorting-type
4951 (message
4952 (if plain-list-p
4953 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4954 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
4955 what)
4956 (setq sorting-type (read-char-exclusive))
4958 (and (= (downcase sorting-type) ?f)
4959 (setq getkey-func
4960 (completing-read "Sort using function: "
4961 obarray 'fboundp t nil nil))
4962 (setq getkey-func (intern getkey-func)))
4964 (and (= (downcase sorting-type) ?r)
4965 (setq property
4966 (completing-read "Property: "
4967 (mapcar 'list (org-buffer-property-keys t))
4968 nil t))))
4970 (message "Sorting entries...")
4972 (save-restriction
4973 (narrow-to-region start end)
4975 (let ((dcst (downcase sorting-type))
4976 (now (current-time)))
4977 (sort-subr
4978 (/= dcst sorting-type)
4979 ;; This function moves to the beginning character of the "record" to
4980 ;; be sorted.
4981 (if plain-list-p
4982 (lambda nil
4983 (if (org-at-item-p) t (goto-char (point-max))))
4984 (lambda nil
4985 (if (re-search-forward re nil t)
4986 (goto-char (match-beginning 0))
4987 (goto-char (point-max)))))
4988 ;; This function moves to the last character of the "record" being
4989 ;; sorted.
4990 (if plain-list-p
4991 'org-end-of-item
4992 (lambda nil
4993 (save-match-data
4994 (condition-case nil
4995 (outline-forward-same-level 1)
4996 (error
4997 (goto-char (point-max)))))))
4999 ;; This function returns the value that gets sorted against.
5000 (if plain-list-p
5001 (lambda nil
5002 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5003 (cond
5004 ((= dcst ?n)
5005 (string-to-number (buffer-substring (match-end 0)
5006 (point-at-eol))))
5007 ((= dcst ?a)
5008 (buffer-substring (match-end 0) (point-at-eol)))
5009 ((= dcst ?t)
5010 (if (re-search-forward org-ts-regexp
5011 (point-at-eol) t)
5012 (org-time-string-to-time (match-string 0))
5013 now))
5014 ((= dcst ?f)
5015 (if getkey-func
5016 (progn
5017 (setq tmp (funcall getkey-func))
5018 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5019 tmp)
5020 (error "Invalid key function `%s'" getkey-func)))
5021 (t (error "Invalid sorting type `%c'" sorting-type)))))
5022 (lambda nil
5023 (cond
5024 ((= dcst ?n)
5025 (if (looking-at outline-regexp)
5026 (string-to-number (buffer-substring (match-end 0)
5027 (point-at-eol)))
5028 nil))
5029 ((= dcst ?a)
5030 (funcall case-func (buffer-substring (point-at-bol)
5031 (point-at-eol))))
5032 ((= dcst ?t)
5033 (if (re-search-forward org-ts-regexp
5034 (save-excursion
5035 (forward-line 2)
5036 (point)) t)
5037 (org-time-string-to-time (match-string 0))
5038 now))
5039 ((= dcst ?p)
5040 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5041 (string-to-char (match-string 2))
5042 org-default-priority))
5043 ((= dcst ?r)
5044 (or (org-entry-get nil property) ""))
5045 ((= dcst ?o)
5046 (if (looking-at org-complex-heading-regexp)
5047 (- 9999 (length (member (match-string 2)
5048 org-todo-keywords-1)))))
5049 ((= dcst ?f)
5050 (if getkey-func
5051 (progn
5052 (setq tmp (funcall getkey-func))
5053 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5054 tmp)
5055 (error "Invalid key function `%s'" getkey-func)))
5056 (t (error "Invalid sorting type `%c'" sorting-type)))))
5058 (cond
5059 ((= dcst ?a) 'string<)
5060 ((= dcst ?t) 'time-less-p)
5061 (t nil)))))
5062 (message "Sorting entries...done")))
5064 (defun org-do-sort (table what &optional with-case sorting-type)
5065 "Sort TABLE of WHAT according to SORTING-TYPE.
5066 The user will be prompted for the SORTING-TYPE if the call to this
5067 function does not specify it. WHAT is only for the prompt, to indicate
5068 what is being sorted. The sorting key will be extracted from
5069 the car of the elements of the table.
5070 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5071 (unless sorting-type
5072 (message
5073 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5074 what)
5075 (setq sorting-type (read-char-exclusive)))
5076 (let ((dcst (downcase sorting-type))
5077 extractfun comparefun)
5078 ;; Define the appropriate functions
5079 (cond
5080 ((= dcst ?n)
5081 (setq extractfun 'string-to-number
5082 comparefun (if (= dcst sorting-type) '< '>)))
5083 ((= dcst ?a)
5084 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5085 (lambda(x) (downcase (org-sort-remove-invisible x))))
5086 comparefun (if (= dcst sorting-type)
5087 'string<
5088 (lambda (a b) (and (not (string< a b))
5089 (not (string= a b)))))))
5090 ((= dcst ?t)
5091 (setq extractfun
5092 (lambda (x)
5093 (if (string-match org-ts-regexp x)
5094 (time-to-seconds
5095 (org-time-string-to-time (match-string 0 x)))
5097 comparefun (if (= dcst sorting-type) '< '>)))
5098 (t (error "Invalid sorting type `%c'" sorting-type)))
5100 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5101 table)
5102 (lambda (a b) (funcall comparefun (car a) (car b))))))
5104 ;;;; Plain list items, including checkboxes
5106 ;;; Plain list items
5108 (defun org-at-item-p ()
5109 "Is point in a line starting a hand-formatted item?"
5110 (let ((llt org-plain-list-ordered-item-terminator))
5111 (save-excursion
5112 (goto-char (point-at-bol))
5113 (looking-at
5114 (cond
5115 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5116 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5117 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5118 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5120 (defun org-in-item-p ()
5121 "It the cursor inside a plain list item.
5122 Does not have to be the first line."
5123 (save-excursion
5124 (condition-case nil
5125 (progn
5126 (org-beginning-of-item)
5127 (org-at-item-p)
5129 (error nil))))
5131 (defun org-insert-item (&optional checkbox)
5132 "Insert a new item at the current level.
5133 Return t when things worked, nil when we are not in an item."
5134 (when (save-excursion
5135 (condition-case nil
5136 (progn
5137 (org-beginning-of-item)
5138 (org-at-item-p)
5139 (if (org-invisible-p) (error "Invisible item"))
5141 (error nil)))
5142 (let* ((bul (match-string 0))
5143 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5144 (match-end 0)))
5145 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5146 pos)
5147 (cond
5148 ((and (org-at-item-p) (<= (point) eow))
5149 ;; before the bullet
5150 (beginning-of-line 1)
5151 (open-line (if blank 2 1)))
5152 ((<= (point) eow)
5153 (beginning-of-line 1))
5155 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5156 (end-of-line 1)
5157 (delete-horizontal-space))
5158 (newline (if blank 2 1))))
5159 (insert bul (if checkbox "[ ]" ""))
5160 (just-one-space)
5161 (setq pos (point))
5162 (end-of-line 1)
5163 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5164 (org-maybe-renumber-ordered-list)
5165 (and checkbox (org-update-checkbox-count-maybe))
5168 ;;; Checkboxes
5170 (defun org-at-item-checkbox-p ()
5171 "Is point at a line starting a plain-list item with a checklet?"
5172 (and (org-at-item-p)
5173 (save-excursion
5174 (goto-char (match-end 0))
5175 (skip-chars-forward " \t")
5176 (looking-at "\\[[- X]\\]"))))
5178 (defun org-toggle-checkbox (&optional arg)
5179 "Toggle the checkbox in the current line."
5180 (interactive "P")
5181 (catch 'exit
5182 (let (beg end status (firstnew 'unknown))
5183 (cond
5184 ((org-region-active-p)
5185 (setq beg (region-beginning) end (region-end)))
5186 ((org-on-heading-p)
5187 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5188 ((org-at-item-checkbox-p)
5189 (let ((pos (point)))
5190 (replace-match
5191 (cond (arg "[-]")
5192 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5193 (t "[ ]"))
5194 t t)
5195 (goto-char pos))
5196 (throw 'exit t))
5197 (t (error "Not at a checkbox or heading, and no active region")))
5198 (save-excursion
5199 (goto-char beg)
5200 (while (< (point) end)
5201 (when (org-at-item-checkbox-p)
5202 (setq status (equal (match-string 0) "[X]"))
5203 (when (eq firstnew 'unknown)
5204 (setq firstnew (not status)))
5205 (replace-match
5206 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5207 (beginning-of-line 2)))))
5208 (org-update-checkbox-count-maybe))
5210 (defun org-update-checkbox-count-maybe ()
5211 "Update checkbox statistics unless turned off by user."
5212 (when org-provide-checkbox-statistics
5213 (org-update-checkbox-count)))
5215 (defun org-update-checkbox-count (&optional all)
5216 "Update the checkbox statistics in the current section.
5217 This will find all statistic cookies like [57%] and [6/12] and update them
5218 with the current numbers. With optional prefix argument ALL, do this for
5219 the whole buffer."
5220 (interactive "P")
5221 (save-excursion
5222 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5223 (beg (condition-case nil
5224 (progn (outline-back-to-heading) (point))
5225 (error (point-min))))
5226 (end (move-marker (make-marker)
5227 (progn (outline-next-heading) (point))))
5228 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5229 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5230 (re-find (concat re "\\|" re-box))
5231 beg-cookie end-cookie is-percent c-on c-off lim
5232 eline curr-ind next-ind continue-from startsearch
5233 (cstat 0)
5235 (when all
5236 (goto-char (point-min))
5237 (outline-next-heading)
5238 (setq beg (point) end (point-max)))
5239 (goto-char end)
5240 ;; find each statistic cookie
5241 (while (re-search-backward re-find beg t)
5242 (setq beg-cookie (match-beginning 1)
5243 end-cookie (match-end 1)
5244 cstat (+ cstat (if end-cookie 1 0))
5245 startsearch (point-at-eol)
5246 continue-from (point-at-bol)
5247 is-percent (match-beginning 2)
5248 lim (cond
5249 ((org-on-heading-p) (outline-next-heading) (point))
5250 ((org-at-item-p) (org-end-of-item) (point))
5251 (t nil))
5252 c-on 0
5253 c-off 0)
5254 (when lim
5255 ;; find first checkbox for this cookie and gather
5256 ;; statistics from all that are at this indentation level
5257 (goto-char startsearch)
5258 (if (re-search-forward re-box lim t)
5259 (progn
5260 (org-beginning-of-item)
5261 (setq curr-ind (org-get-indentation))
5262 (setq next-ind curr-ind)
5263 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5264 (save-excursion (end-of-line) (setq eline (point)))
5265 (if (re-search-forward re-box eline t)
5266 (if (member (match-string 2) '("[ ]" "[-]"))
5267 (setq c-off (1+ c-off))
5268 (setq c-on (1+ c-on))
5271 (org-end-of-item)
5272 (setq next-ind (org-get-indentation))
5274 (goto-char continue-from)
5275 ;; update cookie
5276 (when end-cookie
5277 (delete-region beg-cookie end-cookie)
5278 (goto-char beg-cookie)
5279 (insert
5280 (if is-percent
5281 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5282 (format "[%d/%d]" c-on (+ c-on c-off)))))
5283 ;; update items checkbox if it has one
5284 (when (org-at-item-p)
5285 (org-beginning-of-item)
5286 (when (and (> (+ c-on c-off) 0)
5287 (re-search-forward re-box (point-at-eol) t))
5288 (setq beg-cookie (match-beginning 2)
5289 end-cookie (match-end 2))
5290 (delete-region beg-cookie end-cookie)
5291 (goto-char beg-cookie)
5292 (cond ((= c-off 0) (insert "[X]"))
5293 ((= c-on 0) (insert "[ ]"))
5294 (t (insert "[-]")))
5296 (goto-char continue-from))
5297 (when (interactive-p)
5298 (message "Checkbox satistics updated %s (%d places)"
5299 (if all "in entire file" "in current outline entry") cstat)))))
5301 (defun org-get-checkbox-statistics-face ()
5302 "Select the face for checkbox statistics.
5303 The face will be `org-done' when all relevant boxes are checked. Otherwise
5304 it will be `org-todo'."
5305 (if (match-end 1)
5306 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5307 (if (and (> (match-end 2) (match-beginning 2))
5308 (equal (match-string 2) (match-string 3)))
5309 'org-done
5310 'org-todo)))
5312 (defun org-get-indentation (&optional line)
5313 "Get the indentation of the current line, interpreting tabs.
5314 When LINE is given, assume it represents a line and compute its indentation."
5315 (if line
5316 (if (string-match "^ *" (org-remove-tabs line))
5317 (match-end 0))
5318 (save-excursion
5319 (beginning-of-line 1)
5320 (skip-chars-forward " \t")
5321 (current-column))))
5323 (defun org-remove-tabs (s &optional width)
5324 "Replace tabulators in S with spaces.
5325 Assumes that s is a single line, starting in column 0."
5326 (setq width (or width tab-width))
5327 (while (string-match "\t" s)
5328 (setq s (replace-match
5329 (make-string
5330 (- (* width (/ (+ (match-beginning 0) width) width))
5331 (match-beginning 0)) ?\ )
5332 t t s)))
5335 (defun org-fix-indentation (line ind)
5336 "Fix indentation in LINE.
5337 IND is a cons cell with target and minimum indentation.
5338 If the current indenation in LINE is smaller than the minimum,
5339 leave it alone. If it is larger than ind, set it to the target."
5340 (let* ((l (org-remove-tabs line))
5341 (i (org-get-indentation l))
5342 (i1 (car ind)) (i2 (cdr ind)))
5343 (if (>= i i2) (setq l (substring line i2)))
5344 (if (> i1 0)
5345 (concat (make-string i1 ?\ ) l)
5346 l)))
5348 (defun org-beginning-of-item ()
5349 "Go to the beginning of the current hand-formatted item.
5350 If the cursor is not in an item, throw an error."
5351 (interactive)
5352 (let ((pos (point))
5353 (limit (save-excursion
5354 (condition-case nil
5355 (progn
5356 (org-back-to-heading)
5357 (beginning-of-line 2) (point))
5358 (error (point-min)))))
5359 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5360 ind ind1)
5361 (if (org-at-item-p)
5362 (beginning-of-line 1)
5363 (beginning-of-line 1)
5364 (skip-chars-forward " \t")
5365 (setq ind (current-column))
5366 (if (catch 'exit
5367 (while t
5368 (beginning-of-line 0)
5369 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5371 (if (looking-at "[ \t]*$")
5372 (setq ind1 ind-empty)
5373 (skip-chars-forward " \t")
5374 (setq ind1 (current-column)))
5375 (if (< ind1 ind)
5376 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5378 (goto-char pos)
5379 (error "Not in an item")))))
5381 (defun org-end-of-item ()
5382 "Go to the end of the current hand-formatted item.
5383 If the cursor is not in an item, throw an error."
5384 (interactive)
5385 (let* ((pos (point))
5386 ind1
5387 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5388 (limit (save-excursion (outline-next-heading) (point)))
5389 (ind (save-excursion
5390 (org-beginning-of-item)
5391 (skip-chars-forward " \t")
5392 (current-column)))
5393 (end (catch 'exit
5394 (while t
5395 (beginning-of-line 2)
5396 (if (eobp) (throw 'exit (point)))
5397 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5398 (if (looking-at "[ \t]*$")
5399 (setq ind1 ind-empty)
5400 (skip-chars-forward " \t")
5401 (setq ind1 (current-column)))
5402 (if (<= ind1 ind)
5403 (throw 'exit (point-at-bol)))))))
5404 (if end
5405 (goto-char end)
5406 (goto-char pos)
5407 (error "Not in an item"))))
5409 (defun org-next-item ()
5410 "Move to the beginning of the next item in the current plain list.
5411 Error if not at a plain list, or if this is the last item in the list."
5412 (interactive)
5413 (let (ind ind1 (pos (point)))
5414 (org-beginning-of-item)
5415 (setq ind (org-get-indentation))
5416 (org-end-of-item)
5417 (setq ind1 (org-get-indentation))
5418 (unless (and (org-at-item-p) (= ind ind1))
5419 (goto-char pos)
5420 (error "On last item"))))
5422 (defun org-previous-item ()
5423 "Move to the beginning of the previous item in the current plain list.
5424 Error if not at a plain list, or if this is the first item in the list."
5425 (interactive)
5426 (let (beg ind ind1 (pos (point)))
5427 (org-beginning-of-item)
5428 (setq beg (point))
5429 (setq ind (org-get-indentation))
5430 (goto-char beg)
5431 (catch 'exit
5432 (while t
5433 (beginning-of-line 0)
5434 (if (looking-at "[ \t]*$")
5436 (if (<= (setq ind1 (org-get-indentation)) ind)
5437 (throw 'exit t)))))
5438 (condition-case nil
5439 (if (or (not (org-at-item-p))
5440 (< ind1 (1- ind)))
5441 (error "")
5442 (org-beginning-of-item))
5443 (error (goto-char pos)
5444 (error "On first item")))))
5446 (defun org-first-list-item-p ()
5447 "Is this heading the item in a plain list?"
5448 (unless (org-at-item-p)
5449 (error "Not at a plain list item"))
5450 (org-beginning-of-item)
5451 (= (point) (save-excursion (org-beginning-of-item-list))))
5453 (defun org-move-item-down ()
5454 "Move the plain list item at point down, i.e. swap with following item.
5455 Subitems (items with larger indentation) are considered part of the item,
5456 so this really moves item trees."
5457 (interactive)
5458 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5459 (org-beginning-of-item)
5460 (setq beg0 (point))
5461 (save-excursion
5462 (setq ne-beg (org-back-over-empty-lines))
5463 (setq beg (point)))
5464 (goto-char beg0)
5465 (setq ind (org-get-indentation))
5466 (org-end-of-item)
5467 (setq end0 (point))
5468 (setq ind1 (org-get-indentation))
5469 (setq ne-end (org-back-over-empty-lines))
5470 (setq end (point))
5471 (goto-char beg0)
5472 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5473 ;; include less whitespace
5474 (save-excursion
5475 (goto-char beg)
5476 (forward-line (- ne-beg ne-end))
5477 (setq beg (point))))
5478 (goto-char end0)
5479 (if (and (org-at-item-p) (= ind ind1))
5480 (progn
5481 (org-end-of-item)
5482 (org-back-over-empty-lines)
5483 (setq txt (buffer-substring beg end))
5484 (save-excursion
5485 (delete-region beg end))
5486 (setq pos (point))
5487 (insert txt)
5488 (goto-char pos) (org-skip-whitespace)
5489 (org-maybe-renumber-ordered-list))
5490 (goto-char pos)
5491 (error "Cannot move this item further down"))))
5493 (defun org-move-item-up (arg)
5494 "Move the plain list item at point up, i.e. swap with previous item.
5495 Subitems (items with larger indentation) are considered part of the item,
5496 so this really moves item trees."
5497 (interactive "p")
5498 (let (beg beg0 end ind ind1 (pos (point)) txt
5499 ne-beg ne-ins ins-end)
5500 (org-beginning-of-item)
5501 (setq beg0 (point))
5502 (setq ind (org-get-indentation))
5503 (save-excursion
5504 (setq ne-beg (org-back-over-empty-lines))
5505 (setq beg (point)))
5506 (goto-char beg0)
5507 (org-end-of-item)
5508 (setq end (point))
5509 (goto-char beg0)
5510 (catch 'exit
5511 (while t
5512 (beginning-of-line 0)
5513 (if (looking-at "[ \t]*$")
5514 (if org-empty-line-terminates-plain-lists
5515 (progn
5516 (goto-char pos)
5517 (error "Cannot move this item further up"))
5518 nil)
5519 (if (<= (setq ind1 (org-get-indentation)) ind)
5520 (throw 'exit t)))))
5521 (condition-case nil
5522 (org-beginning-of-item)
5523 (error (goto-char beg)
5524 (error "Cannot move this item further up")))
5525 (setq ind1 (org-get-indentation))
5526 (if (and (org-at-item-p) (= ind ind1))
5527 (progn
5528 (setq ne-ins (org-back-over-empty-lines))
5529 (setq txt (buffer-substring beg end))
5530 (save-excursion
5531 (delete-region beg end))
5532 (setq pos (point))
5533 (insert txt)
5534 (setq ins-end (point))
5535 (goto-char pos) (org-skip-whitespace)
5537 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5538 ;; Move whitespace back to beginning
5539 (save-excursion
5540 (goto-char ins-end)
5541 (let ((kill-whole-line t))
5542 (kill-line (- ne-ins ne-beg)) (point)))
5543 (insert (make-string (- ne-ins ne-beg) ?\n)))
5545 (org-maybe-renumber-ordered-list))
5546 (goto-char pos)
5547 (error "Cannot move this item further up"))))
5549 (defun org-maybe-renumber-ordered-list ()
5550 "Renumber the ordered list at point if setup allows it.
5551 This tests the user option `org-auto-renumber-ordered-lists' before
5552 doing the renumbering."
5553 (interactive)
5554 (when (and org-auto-renumber-ordered-lists
5555 (org-at-item-p))
5556 (if (match-beginning 3)
5557 (org-renumber-ordered-list 1)
5558 (org-fix-bullet-type))))
5560 (defun org-maybe-renumber-ordered-list-safe ()
5561 (condition-case nil
5562 (save-excursion
5563 (org-maybe-renumber-ordered-list))
5564 (error nil)))
5566 (defun org-cycle-list-bullet (&optional which)
5567 "Cycle through the different itemize/enumerate bullets.
5568 This cycle the entire list level through the sequence:
5570 `-' -> `+' -> `*' -> `1.' -> `1)'
5572 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5573 0 meand `-', 1 means `+' etc."
5574 (interactive "P")
5575 (org-preserve-lc
5576 (org-beginning-of-item-list)
5577 (org-at-item-p)
5578 (beginning-of-line 1)
5579 (let ((current (match-string 0))
5580 (prevp (eq which 'previous))
5581 new)
5582 (setq new (cond
5583 ((and (numberp which)
5584 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5585 ((string-match "-" current) (if prevp "1)" "+"))
5586 ((string-match "\\+" current)
5587 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5588 ((string-match "\\*" current) (if prevp "+" "1."))
5589 ((string-match "\\." current) (if prevp "*" "1)"))
5590 ((string-match ")" current) (if prevp "1." "-"))
5591 (t (error "This should not happen"))))
5592 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5593 (org-fix-bullet-type)
5594 (org-maybe-renumber-ordered-list))))
5596 (defun org-get-string-indentation (s)
5597 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5598 (let ((n -1) (i 0) (w tab-width) c)
5599 (catch 'exit
5600 (while (< (setq n (1+ n)) (length s))
5601 (setq c (aref s n))
5602 (cond ((= c ?\ ) (setq i (1+ i)))
5603 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5604 (t (throw 'exit t)))))
5607 (defun org-renumber-ordered-list (arg)
5608 "Renumber an ordered plain list.
5609 Cursor needs to be in the first line of an item, the line that starts
5610 with something like \"1.\" or \"2)\"."
5611 (interactive "p")
5612 (unless (and (org-at-item-p)
5613 (match-beginning 3))
5614 (error "This is not an ordered list"))
5615 (let ((line (org-current-line))
5616 (col (current-column))
5617 (ind (org-get-string-indentation
5618 (buffer-substring (point-at-bol) (match-beginning 3))))
5619 ;; (term (substring (match-string 3) -1))
5620 ind1 (n (1- arg))
5621 fmt)
5622 ;; find where this list begins
5623 (org-beginning-of-item-list)
5624 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5625 (setq fmt (concat "%d" (match-string 1)))
5626 (beginning-of-line 0)
5627 ;; walk forward and replace these numbers
5628 (catch 'exit
5629 (while t
5630 (catch 'next
5631 (beginning-of-line 2)
5632 (if (eobp) (throw 'exit nil))
5633 (if (looking-at "[ \t]*$") (throw 'next nil))
5634 (skip-chars-forward " \t") (setq ind1 (current-column))
5635 (if (> ind1 ind) (throw 'next t))
5636 (if (< ind1 ind) (throw 'exit t))
5637 (if (not (org-at-item-p)) (throw 'exit nil))
5638 (delete-region (match-beginning 2) (match-end 2))
5639 (goto-char (match-beginning 2))
5640 (insert (format fmt (setq n (1+ n)))))))
5641 (goto-line line)
5642 (move-to-column col)))
5644 (defun org-fix-bullet-type ()
5645 "Make sure all items in this list have the same bullet as the firsst item."
5646 (interactive)
5647 (unless (org-at-item-p) (error "This is not a list"))
5648 (let ((line (org-current-line))
5649 (col (current-column))
5650 (ind (current-indentation))
5651 ind1 bullet)
5652 ;; find where this list begins
5653 (org-beginning-of-item-list)
5654 (beginning-of-line 1)
5655 ;; find out what the bullet type is
5656 (looking-at "[ \t]*\\(\\S-+\\)")
5657 (setq bullet (match-string 1))
5658 ;; walk forward and replace these numbers
5659 (beginning-of-line 0)
5660 (catch 'exit
5661 (while t
5662 (catch 'next
5663 (beginning-of-line 2)
5664 (if (eobp) (throw 'exit nil))
5665 (if (looking-at "[ \t]*$") (throw 'next nil))
5666 (skip-chars-forward " \t") (setq ind1 (current-column))
5667 (if (> ind1 ind) (throw 'next t))
5668 (if (< ind1 ind) (throw 'exit t))
5669 (if (not (org-at-item-p)) (throw 'exit nil))
5670 (skip-chars-forward " \t")
5671 (looking-at "\\S-+")
5672 (replace-match bullet))))
5673 (goto-line line)
5674 (move-to-column col)
5675 (if (string-match "[0-9]" bullet)
5676 (org-renumber-ordered-list 1))))
5678 (defun org-beginning-of-item-list ()
5679 "Go to the beginning of the current item list.
5680 I.e. to the first item in this list."
5681 (interactive)
5682 (org-beginning-of-item)
5683 (let ((pos (point-at-bol))
5684 (ind (org-get-indentation))
5685 ind1)
5686 ;; find where this list begins
5687 (catch 'exit
5688 (while t
5689 (catch 'next
5690 (beginning-of-line 0)
5691 (if (looking-at "[ \t]*$")
5692 (throw (if (bobp) 'exit 'next) t))
5693 (skip-chars-forward " \t") (setq ind1 (current-column))
5694 (if (or (< ind1 ind)
5695 (and (= ind1 ind)
5696 (not (org-at-item-p)))
5697 (bobp))
5698 (throw 'exit t)
5699 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5700 (goto-char pos)))
5703 (defun org-end-of-item-list ()
5704 "Go to the end of the current item list.
5705 I.e. to the text after the last item."
5706 (interactive)
5707 (org-beginning-of-item)
5708 (let ((pos (point-at-bol))
5709 (ind (org-get-indentation))
5710 ind1)
5711 ;; find where this list begins
5712 (catch 'exit
5713 (while t
5714 (catch 'next
5715 (beginning-of-line 2)
5716 (if (looking-at "[ \t]*$")
5717 (throw (if (eobp) 'exit 'next) t))
5718 (skip-chars-forward " \t") (setq ind1 (current-column))
5719 (if (or (< ind1 ind)
5720 (and (= ind1 ind)
5721 (not (org-at-item-p)))
5722 (eobp))
5723 (progn
5724 (setq pos (point-at-bol))
5725 (throw 'exit t))))))
5726 (goto-char pos)))
5729 (defvar org-last-indent-begin-marker (make-marker))
5730 (defvar org-last-indent-end-marker (make-marker))
5732 (defun org-outdent-item (arg)
5733 "Outdent a local list item."
5734 (interactive "p")
5735 (org-indent-item (- arg)))
5737 (defun org-indent-item (arg)
5738 "Indent a local list item."
5739 (interactive "p")
5740 (unless (org-at-item-p)
5741 (error "Not on an item"))
5742 (save-excursion
5743 (let (beg end ind ind1 tmp delta ind-down ind-up)
5744 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5745 (setq beg org-last-indent-begin-marker
5746 end org-last-indent-end-marker)
5747 (org-beginning-of-item)
5748 (setq beg (move-marker org-last-indent-begin-marker (point)))
5749 (org-end-of-item)
5750 (setq end (move-marker org-last-indent-end-marker (point))))
5751 (goto-char beg)
5752 (setq tmp (org-item-indent-positions)
5753 ind (car tmp)
5754 ind-down (nth 2 tmp)
5755 ind-up (nth 1 tmp)
5756 delta (if (> arg 0)
5757 (if ind-down (- ind-down ind) 2)
5758 (if ind-up (- ind-up ind) -2)))
5759 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5760 (while (< (point) end)
5761 (beginning-of-line 1)
5762 (skip-chars-forward " \t") (setq ind1 (current-column))
5763 (delete-region (point-at-bol) (point))
5764 (or (eolp) (indent-to-column (+ ind1 delta)))
5765 (beginning-of-line 2))))
5766 (org-fix-bullet-type)
5767 (org-maybe-renumber-ordered-list-safe)
5768 (save-excursion
5769 (beginning-of-line 0)
5770 (condition-case nil (org-beginning-of-item) (error nil))
5771 (org-maybe-renumber-ordered-list-safe)))
5773 (defun org-item-indent-positions ()
5774 "Return indentation for plain list items.
5775 This returns a list with three values: The current indentation, the
5776 parent indentation and the indentation a child should habe.
5777 Assumes cursor in item line."
5778 (let* ((bolpos (point-at-bol))
5779 (ind (org-get-indentation))
5780 ind-down ind-up pos)
5781 (save-excursion
5782 (org-beginning-of-item-list)
5783 (skip-chars-backward "\n\r \t")
5784 (when (org-in-item-p)
5785 (org-beginning-of-item)
5786 (setq ind-up (org-get-indentation))))
5787 (setq pos (point))
5788 (save-excursion
5789 (cond
5790 ((and (condition-case nil (progn (org-previous-item) t)
5791 (error nil))
5792 (or (forward-char 1) t)
5793 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5794 (setq ind-down (org-get-indentation)))
5795 ((and (goto-char pos)
5796 (org-at-item-p))
5797 (goto-char (match-end 0))
5798 (skip-chars-forward " \t")
5799 (setq ind-down (current-column)))))
5800 (list ind ind-up ind-down)))
5802 ;;; The orgstruct minor mode
5804 ;; Define a minor mode which can be used in other modes in order to
5805 ;; integrate the org-mode structure editing commands.
5807 ;; This is really a hack, because the org-mode structure commands use
5808 ;; keys which normally belong to the major mode. Here is how it
5809 ;; works: The minor mode defines all the keys necessary to operate the
5810 ;; structure commands, but wraps the commands into a function which
5811 ;; tests if the cursor is currently at a headline or a plain list
5812 ;; item. If that is the case, the structure command is used,
5813 ;; temporarily setting many Org-mode variables like regular
5814 ;; expressions for filling etc. However, when any of those keys is
5815 ;; used at a different location, function uses `key-binding' to look
5816 ;; up if the key has an associated command in another currently active
5817 ;; keymap (minor modes, major mode, global), and executes that
5818 ;; command. There might be problems if any of the keys is otherwise
5819 ;; used as a prefix key.
5821 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5822 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5823 ;; addresses this by checking explicitly for both bindings.
5825 (defvar orgstruct-mode-map (make-sparse-keymap)
5826 "Keymap for the minor `orgstruct-mode'.")
5828 (defvar org-local-vars nil
5829 "List of local variables, for use by `orgstruct-mode'")
5831 ;;;###autoload
5832 (define-minor-mode orgstruct-mode
5833 "Toggle the minor more `orgstruct-mode'.
5834 This mode is for using Org-mode structure commands in other modes.
5835 The following key behave as if Org-mode was active, if the cursor
5836 is on a headline, or on a plain list item (both in the definition
5837 of Org-mode).
5839 M-up Move entry/item up
5840 M-down Move entry/item down
5841 M-left Promote
5842 M-right Demote
5843 M-S-up Move entry/item up
5844 M-S-down Move entry/item down
5845 M-S-left Promote subtree
5846 M-S-right Demote subtree
5847 M-q Fill paragraph and items like in Org-mode
5848 C-c ^ Sort entries
5849 C-c - Cycle list bullet
5850 TAB Cycle item visibility
5851 M-RET Insert new heading/item
5852 S-M-RET Insert new TODO heading / Chekbox item
5853 C-c C-c Set tags / toggle checkbox"
5854 nil " OrgStruct" nil
5855 (org-load-modules-maybe)
5856 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5858 ;;;###autoload
5859 (defun turn-on-orgstruct ()
5860 "Unconditionally turn on `orgstruct-mode'."
5861 (orgstruct-mode 1))
5863 ;;;###autoload
5864 (defun turn-on-orgstruct++ ()
5865 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5866 In addition to setting orgstruct-mode, this also exports all indentation and
5867 autofilling variables from org-mode into the buffer. Note that turning
5868 off orgstruct-mode will *not* remove these additional settings."
5869 (orgstruct-mode 1)
5870 (let (var val)
5871 (mapc
5872 (lambda (x)
5873 (when (string-match
5874 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5875 (symbol-name (car x)))
5876 (setq var (car x) val (nth 1 x))
5877 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5878 org-local-vars)))
5880 (defun orgstruct-error ()
5881 "Error when there is no default binding for a structure key."
5882 (interactive)
5883 (error "This key has no function outside structure elements"))
5885 (defun orgstruct-setup ()
5886 "Setup orgstruct keymaps."
5887 (let ((nfunc 0)
5888 (bindings
5889 (list
5890 '([(meta up)] org-metaup)
5891 '([(meta down)] org-metadown)
5892 '([(meta left)] org-metaleft)
5893 '([(meta right)] org-metaright)
5894 '([(meta shift up)] org-shiftmetaup)
5895 '([(meta shift down)] org-shiftmetadown)
5896 '([(meta shift left)] org-shiftmetaleft)
5897 '([(meta shift right)] org-shiftmetaright)
5898 '([(shift up)] org-shiftup)
5899 '([(shift down)] org-shiftdown)
5900 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5901 '("\M-q" fill-paragraph)
5902 '("\C-c^" org-sort)
5903 '("\C-c-" org-cycle-list-bullet)))
5904 elt key fun cmd)
5905 (while (setq elt (pop bindings))
5906 (setq nfunc (1+ nfunc))
5907 (setq key (org-key (car elt))
5908 fun (nth 1 elt)
5909 cmd (orgstruct-make-binding fun nfunc key))
5910 (org-defkey orgstruct-mode-map key cmd))
5912 ;; Special treatment needed for TAB and RET
5913 (org-defkey orgstruct-mode-map [(tab)]
5914 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5915 (org-defkey orgstruct-mode-map "\C-i"
5916 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5918 (org-defkey orgstruct-mode-map "\M-\C-m"
5919 (orgstruct-make-binding 'org-insert-heading 105
5920 "\M-\C-m" [(meta return)]))
5921 (org-defkey orgstruct-mode-map [(meta return)]
5922 (orgstruct-make-binding 'org-insert-heading 106
5923 [(meta return)] "\M-\C-m"))
5925 (org-defkey orgstruct-mode-map [(shift meta return)]
5926 (orgstruct-make-binding 'org-insert-todo-heading 107
5927 [(meta return)] "\M-\C-m"))
5929 (unless org-local-vars
5930 (setq org-local-vars (org-get-local-variables)))
5934 (defun orgstruct-make-binding (fun n &rest keys)
5935 "Create a function for binding in the structure minor mode.
5936 FUN is the command to call inside a table. N is used to create a unique
5937 command name. KEYS are keys that should be checked in for a command
5938 to execute outside of tables."
5939 (eval
5940 (list 'defun
5941 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5942 '(arg)
5943 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5944 "Outside of structure, run the binding of `"
5945 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5946 "'.")
5947 '(interactive "p")
5948 (list 'if
5949 '(org-context-p 'headline 'item)
5950 (list 'org-run-like-in-org-mode (list 'quote fun))
5951 (list 'let '(orgstruct-mode)
5952 (list 'call-interactively
5953 (append '(or)
5954 (mapcar (lambda (k)
5955 (list 'key-binding k))
5956 keys)
5957 '('orgstruct-error))))))))
5959 (defun org-context-p (&rest contexts)
5960 "Check if local context is and of CONTEXTS.
5961 Possible values in the list of contexts are `table', `headline', and `item'."
5962 (let ((pos (point)))
5963 (goto-char (point-at-bol))
5964 (prog1 (or (and (memq 'table contexts)
5965 (looking-at "[ \t]*|"))
5966 (and (memq 'headline contexts)
5967 (looking-at "\\*+"))
5968 (and (memq 'item contexts)
5969 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5970 (goto-char pos))))
5972 (defun org-get-local-variables ()
5973 "Return a list of all local variables in an org-mode buffer."
5974 (let (varlist)
5975 (with-current-buffer (get-buffer-create "*Org tmp*")
5976 (erase-buffer)
5977 (org-mode)
5978 (setq varlist (buffer-local-variables)))
5979 (kill-buffer "*Org tmp*")
5980 (delq nil
5981 (mapcar
5982 (lambda (x)
5983 (setq x
5984 (if (symbolp x)
5985 (list x)
5986 (list (car x) (list 'quote (cdr x)))))
5987 (if (string-match
5988 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5989 (symbol-name (car x)))
5990 x nil))
5991 varlist))))
5993 ;;;###autoload
5994 (defun org-run-like-in-org-mode (cmd)
5995 (org-load-modules-maybe)
5996 (unless org-local-vars
5997 (setq org-local-vars (org-get-local-variables)))
5998 (eval (list 'let org-local-vars
5999 (list 'call-interactively (list 'quote cmd)))))
6001 ;;;; Archiving
6003 (defun org-get-category (&optional pos)
6004 "Get the category applying to position POS."
6005 (get-text-property (or pos (point)) 'org-category))
6007 (defun org-refresh-category-properties ()
6008 "Refresh category text properties in the buffer."
6009 (let ((def-cat (cond
6010 ((null org-category)
6011 (if buffer-file-name
6012 (file-name-sans-extension
6013 (file-name-nondirectory buffer-file-name))
6014 "???"))
6015 ((symbolp org-category) (symbol-name org-category))
6016 (t org-category)))
6017 beg end cat pos optionp)
6018 (org-unmodified
6019 (save-excursion
6020 (save-restriction
6021 (widen)
6022 (goto-char (point-min))
6023 (put-text-property (point) (point-max) 'org-category def-cat)
6024 (while (re-search-forward
6025 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6026 (setq pos (match-end 0)
6027 optionp (equal (char-after (match-beginning 0)) ?#)
6028 cat (org-trim (match-string 2)))
6029 (if optionp
6030 (setq beg (point-at-bol) end (point-max))
6031 (org-back-to-heading t)
6032 (setq beg (point) end (org-end-of-subtree t t)))
6033 (put-text-property beg end 'org-category cat)
6034 (goto-char pos)))))))
6037 ;;;; Link Stuff
6039 ;;; Link abbreviations
6041 (defun org-link-expand-abbrev (link)
6042 "Apply replacements as defined in `org-link-abbrev-alist."
6043 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6044 (let* ((key (match-string 1 link))
6045 (as (or (assoc key org-link-abbrev-alist-local)
6046 (assoc key org-link-abbrev-alist)))
6047 (tag (and (match-end 2) (match-string 3 link)))
6048 rpl)
6049 (if (not as)
6050 link
6051 (setq rpl (cdr as))
6052 (cond
6053 ((symbolp rpl) (funcall rpl tag))
6054 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6055 (t (concat rpl tag)))))
6056 link))
6058 ;;; Storing and inserting links
6060 (defvar org-insert-link-history nil
6061 "Minibuffer history for links inserted with `org-insert-link'.")
6063 (defvar org-stored-links nil
6064 "Contains the links stored with `org-store-link'.")
6066 (defvar org-store-link-plist nil
6067 "Plist with info about the most recently link created with `org-store-link'.")
6069 (defvar org-link-protocols nil
6070 "Link protocols added to Org-mode using `org-add-link-type'.")
6072 (defvar org-store-link-functions nil
6073 "List of functions that are called to create and store a link.
6074 Each function will be called in turn until one returns a non-nil
6075 value. Each function should check if it is responsible for creating
6076 this link (for example by looking at the major mode).
6077 If not, it must exit and return nil.
6078 If yes, it should return a non-nil value after a calling
6079 `org-store-link-props' with a list of properties and values.
6080 Special properties are:
6082 :type The link prefix. like \"http\". This must be given.
6083 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6084 This is obligatory as well.
6085 :description Optional default description for the second pair
6086 of brackets in an Org-mode link. The user can still change
6087 this when inserting this link into an Org-mode buffer.
6089 In addition to these, any additional properties can be specified
6090 and then used in remember templates.")
6092 (defun org-add-link-type (type &optional follow export)
6093 "Add TYPE to the list of `org-link-types'.
6094 Re-compute all regular expressions depending on `org-link-types'
6096 FOLLOW and EXPORT are two functions.
6098 FOLLOW should take the link path as the single argument and do whatever
6099 is necessary to follow the link, for example find a file or display
6100 a mail message.
6102 EXPORT should format the link path for export to one of the export formats.
6103 It should be a function accepting three arguments:
6105 path the path of the link, the text after the prefix (like \"http:\")
6106 desc the description of the link, if any, nil if there was no descripton
6107 format the export format, a symbol like `html' or `latex'.
6109 The function may use the FORMAT information to return different values
6110 depending on the format. The return value will be put literally into
6111 the exported file.
6112 Org-mode has a built-in default for exporting links. If you are happy with
6113 this default, there is no need to define an export function for the link
6114 type. For a simple example of an export function, see `org-bbdb.el'."
6115 (add-to-list 'org-link-types type t)
6116 (org-make-link-regexps)
6117 (if (assoc type org-link-protocols)
6118 (setcdr (assoc type org-link-protocols) (list follow export))
6119 (push (list type follow export) org-link-protocols)))
6122 ;;;###autoload
6123 (defun org-store-link (arg)
6124 "\\<org-mode-map>Store an org-link to the current location.
6125 This link is added to `org-stored-links' and can later be inserted
6126 into an org-buffer with \\[org-insert-link].
6128 For some link types, a prefix arg is interpreted:
6129 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6130 For file links, arg negates `org-context-in-file-links'."
6131 (interactive "P")
6132 (org-load-modules-maybe)
6133 (setq org-store-link-plist nil) ; reset
6134 (let (link cpltxt desc description search txt)
6135 (cond
6137 ((run-hook-with-args-until-success 'org-store-link-functions)
6138 (setq link (plist-get org-store-link-plist :link)
6139 desc (or (plist-get org-store-link-plist :description) link)))
6141 ((eq major-mode 'calendar-mode)
6142 (let ((cd (calendar-cursor-to-date)))
6143 (setq link
6144 (format-time-string
6145 (car org-time-stamp-formats)
6146 (apply 'encode-time
6147 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6148 nil nil nil))))
6149 (org-store-link-props :type "calendar" :date cd)))
6151 ((eq major-mode 'w3-mode)
6152 (setq cpltxt (url-view-url t)
6153 link (org-make-link cpltxt))
6154 (org-store-link-props :type "w3" :url (url-view-url t)))
6156 ((eq major-mode 'w3m-mode)
6157 (setq cpltxt (or w3m-current-title w3m-current-url)
6158 link (org-make-link w3m-current-url))
6159 (org-store-link-props :type "w3m" :url (url-view-url t)))
6161 ((setq search (run-hook-with-args-until-success
6162 'org-create-file-search-functions))
6163 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6164 "::" search))
6165 (setq cpltxt (or description link)))
6167 ((eq major-mode 'image-mode)
6168 (setq cpltxt (concat "file:"
6169 (abbreviate-file-name buffer-file-name))
6170 link (org-make-link cpltxt))
6171 (org-store-link-props :type "image" :file buffer-file-name))
6173 ((eq major-mode 'dired-mode)
6174 ;; link to the file in the current line
6175 (setq cpltxt (concat "file:"
6176 (abbreviate-file-name
6177 (expand-file-name
6178 (dired-get-filename nil t))))
6179 link (org-make-link cpltxt)))
6181 ((and buffer-file-name (org-mode-p))
6182 ;; Just link to current headline
6183 (setq cpltxt (concat "file:"
6184 (abbreviate-file-name buffer-file-name)))
6185 ;; Add a context search string
6186 (when (org-xor org-context-in-file-links arg)
6187 ;; Check if we are on a target
6188 (if (org-in-regexp "<<\\(.*?\\)>>")
6189 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6190 (setq txt (cond
6191 ((org-on-heading-p) nil)
6192 ((org-region-active-p)
6193 (buffer-substring (region-beginning) (region-end)))
6194 (t nil)))
6195 (when (or (null txt) (string-match "\\S-" txt))
6196 (setq cpltxt
6197 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6198 desc "NONE"))))
6199 (if (string-match "::\\'" cpltxt)
6200 (setq cpltxt (substring cpltxt 0 -2)))
6201 (setq link (org-make-link cpltxt)))
6203 ((buffer-file-name (buffer-base-buffer))
6204 ;; Just link to this file here.
6205 (setq cpltxt (concat "file:"
6206 (abbreviate-file-name
6207 (buffer-file-name (buffer-base-buffer)))))
6208 ;; Add a context string
6209 (when (org-xor org-context-in-file-links arg)
6210 (setq txt (if (org-region-active-p)
6211 (buffer-substring (region-beginning) (region-end))
6212 (buffer-substring (point-at-bol) (point-at-eol))))
6213 ;; Only use search option if there is some text.
6214 (when (string-match "\\S-" txt)
6215 (setq cpltxt
6216 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6217 desc "NONE")))
6218 (setq link (org-make-link cpltxt)))
6220 ((interactive-p)
6221 (error "Cannot link to a buffer which is not visiting a file"))
6223 (t (setq link nil)))
6225 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6226 (setq link (or link cpltxt)
6227 desc (or desc cpltxt))
6228 (if (equal desc "NONE") (setq desc nil))
6230 (if (and (interactive-p) link)
6231 (progn
6232 (setq org-stored-links
6233 (cons (list link desc) org-stored-links))
6234 (message "Stored: %s" (or desc link)))
6235 (and link (org-make-link-string link desc)))))
6237 (defun org-store-link-props (&rest plist)
6238 "Store link properties, extract names and addresses."
6239 (let (x adr)
6240 (when (setq x (plist-get plist :from))
6241 (setq adr (mail-extract-address-components x))
6242 (plist-put plist :fromname (car adr))
6243 (plist-put plist :fromaddress (nth 1 adr)))
6244 (when (setq x (plist-get plist :to))
6245 (setq adr (mail-extract-address-components x))
6246 (plist-put plist :toname (car adr))
6247 (plist-put plist :toaddress (nth 1 adr))))
6248 (let ((from (plist-get plist :from))
6249 (to (plist-get plist :to)))
6250 (when (and from to org-from-is-user-regexp)
6251 (plist-put plist :fromto
6252 (if (string-match org-from-is-user-regexp from)
6253 (concat "to %t")
6254 (concat "from %f")))))
6255 (setq org-store-link-plist plist))
6257 (defun org-add-link-props (&rest plist)
6258 "Add these properties to the link property list."
6259 (let (key value)
6260 (while plist
6261 (setq key (pop plist) value (pop plist))
6262 (setq org-store-link-plist
6263 (plist-put org-store-link-plist key value)))))
6265 (defun org-email-link-description (&optional fmt)
6266 "Return the description part of an email link.
6267 This takes information from `org-store-link-plist' and formats it
6268 according to FMT (default from `org-email-link-description-format')."
6269 (setq fmt (or fmt org-email-link-description-format))
6270 (let* ((p org-store-link-plist)
6271 (to (plist-get p :toaddress))
6272 (from (plist-get p :fromaddress))
6273 (table
6274 (list
6275 (cons "%c" (plist-get p :fromto))
6276 (cons "%F" (plist-get p :from))
6277 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6278 (cons "%T" (plist-get p :to))
6279 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6280 (cons "%s" (plist-get p :subject))
6281 (cons "%m" (plist-get p :message-id)))))
6282 (when (string-match "%c" fmt)
6283 ;; Check if the user wrote this message
6284 (if (and org-from-is-user-regexp from to
6285 (save-match-data (string-match org-from-is-user-regexp from)))
6286 (setq fmt (replace-match "to %t" t t fmt))
6287 (setq fmt (replace-match "from %f" t t fmt))))
6288 (org-replace-escapes fmt table)))
6290 (defun org-make-org-heading-search-string (&optional string heading)
6291 "Make search string for STRING or current headline."
6292 (interactive)
6293 (let ((s (or string (org-get-heading))))
6294 (unless (and string (not heading))
6295 ;; We are using a headline, clean up garbage in there.
6296 (if (string-match org-todo-regexp s)
6297 (setq s (replace-match "" t t s)))
6298 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6299 (setq s (replace-match "" t t s)))
6300 (setq s (org-trim s))
6301 (if (string-match (concat "^\\(" org-quote-string "\\|"
6302 org-comment-string "\\)") s)
6303 (setq s (replace-match "" t t s)))
6304 (while (string-match org-ts-regexp s)
6305 (setq s (replace-match "" t t s))))
6306 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6307 (setq s (replace-match " " t t s)))
6308 (or string (setq s (concat "*" s))) ; Add * for headlines
6309 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6311 (defun org-make-link (&rest strings)
6312 "Concatenate STRINGS."
6313 (apply 'concat strings))
6315 (defun org-make-link-string (link &optional description)
6316 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6317 (unless (string-match "\\S-" link)
6318 (error "Empty link"))
6319 (when (stringp description)
6320 ;; Remove brackets from the description, they are fatal.
6321 (while (string-match "\\[" description)
6322 (setq description (replace-match "{" t t description)))
6323 (while (string-match "\\]" description)
6324 (setq description (replace-match "}" t t description))))
6325 (when (equal (org-link-escape link) description)
6326 ;; No description needed, it is identical
6327 (setq description nil))
6328 (when (and (not description)
6329 (not (equal link (org-link-escape link))))
6330 (setq description link))
6331 (concat "[[" (org-link-escape link) "]"
6332 (if description (concat "[" description "]") "")
6333 "]"))
6335 (defconst org-link-escape-chars
6336 '((?\ . "%20")
6337 (?\[ . "%5B")
6338 (?\] . "%5D")
6339 (?\340 . "%E0") ; `a
6340 (?\342 . "%E2") ; ^a
6341 (?\347 . "%E7") ; ,c
6342 (?\350 . "%E8") ; `e
6343 (?\351 . "%E9") ; 'e
6344 (?\352 . "%EA") ; ^e
6345 (?\356 . "%EE") ; ^i
6346 (?\364 . "%F4") ; ^o
6347 (?\371 . "%F9") ; `u
6348 (?\373 . "%FB") ; ^u
6349 (?\; . "%3B")
6350 (?? . "%3F")
6351 (?= . "%3D")
6352 (?+ . "%2B")
6354 "Association list of escapes for some characters problematic in links.
6355 This is the list that is used for internal purposes.")
6357 (defconst org-link-escape-chars-browser
6358 '((?\ . "%20")) ; 32 for the SPC char
6359 "Association list of escapes for some characters problematic in links.
6360 This is the list that is used before handing over to the browser.")
6362 (defun org-link-escape (text &optional table)
6363 "Escape charaters in TEXT that are problematic for links."
6364 (setq table (or table org-link-escape-chars))
6365 (when text
6366 (let ((re (mapconcat (lambda (x) (regexp-quote
6367 (char-to-string (car x))))
6368 table "\\|")))
6369 (while (string-match re text)
6370 (setq text
6371 (replace-match
6372 (cdr (assoc (string-to-char (match-string 0 text))
6373 table))
6374 t t text)))
6375 text)))
6377 (defun org-link-unescape (text &optional table)
6378 "Reverse the action of `org-link-escape'."
6379 (setq table (or table org-link-escape-chars))
6380 (when text
6381 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6382 table "\\|")))
6383 (while (string-match re text)
6384 (setq text
6385 (replace-match
6386 (char-to-string (car (rassoc (match-string 0 text) table)))
6387 t t text)))
6388 text)))
6390 (defun org-xor (a b)
6391 "Exclusive or."
6392 (if a (not b) b))
6394 (defun org-get-header (header)
6395 "Find a header field in the current buffer."
6396 (save-excursion
6397 (goto-char (point-min))
6398 (let ((case-fold-search t) s)
6399 (cond
6400 ((eq header 'from)
6401 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6402 (setq s (match-string 1)))
6403 (while (string-match "\"" s)
6404 (setq s (replace-match "" t t s)))
6405 (if (string-match "[<(].*" s)
6406 (setq s (replace-match "" t t s))))
6407 ((eq header 'message-id)
6408 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6409 (setq s (match-string 1))))
6410 ((eq header 'subject)
6411 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6412 (setq s (match-string 1)))))
6413 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6414 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6415 s)))
6418 (defun org-fixup-message-id-for-http (s)
6419 "Replace special characters in a message id, so it can be used in an http query."
6420 (while (string-match "<" s)
6421 (setq s (replace-match "%3C" t t s)))
6422 (while (string-match ">" s)
6423 (setq s (replace-match "%3E" t t s)))
6424 (while (string-match "@" s)
6425 (setq s (replace-match "%40" t t s)))
6428 ;;;###autoload
6429 (defun org-insert-link-global ()
6430 "Insert a link like Org-mode does.
6431 This command can be called in any mode to insert a link in Org-mode syntax."
6432 (interactive)
6433 (org-load-modules-maybe)
6434 (org-run-like-in-org-mode 'org-insert-link))
6436 (defun org-insert-link (&optional complete-file link-location)
6437 "Insert a link. At the prompt, enter the link.
6439 Completion can be used to select a link previously stored with
6440 `org-store-link'. When the empty string is entered (i.e. if you just
6441 press RET at the prompt), the link defaults to the most recently
6442 stored link. As SPC triggers completion in the minibuffer, you need to
6443 use M-SPC or C-q SPC to force the insertion of a space character.
6445 You will also be prompted for a description, and if one is given, it will
6446 be displayed in the buffer instead of the link.
6448 If there is already a link at point, this command will allow you to edit link
6449 and description parts.
6451 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6452 be selected using completion. The path to the file will be relative to the
6453 current directory if the file is in the current directory or a subdirectory.
6454 Otherwise, the link will be the absolute path as completed in the minibuffer
6455 \(i.e. normally ~/path/to/file).
6457 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6458 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6459 of `org-keep-stored-link-after-insertion'.
6461 If `org-make-link-description-function' is non-nil, this function will be
6462 called with the link target, and the result will be the default
6463 link description.
6465 If the LINK-LOCATION parameter is non-nil, this value will be
6466 used as the link location instead of reading one interactively."
6467 (interactive "P")
6468 (let* ((wcf (current-window-configuration))
6469 (region (if (org-region-active-p)
6470 (buffer-substring (region-beginning) (region-end))))
6471 (remove (and region (list (region-beginning) (region-end))))
6472 (desc region)
6473 tmphist ; byte-compile incorrectly complains about this
6474 (link link-location)
6475 entry file)
6476 (cond
6477 (link-location) ; specified by arg, just use it.
6478 ((org-in-regexp org-bracket-link-regexp 1)
6479 ;; We do have a link at point, and we are going to edit it.
6480 (setq remove (list (match-beginning 0) (match-end 0)))
6481 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6482 (setq link (read-string "Link: "
6483 (org-link-unescape
6484 (org-match-string-no-properties 1)))))
6485 ((or (org-in-regexp org-angle-link-re)
6486 (org-in-regexp org-plain-link-re))
6487 ;; Convert to bracket link
6488 (setq remove (list (match-beginning 0) (match-end 0))
6489 link (read-string "Link: "
6490 (org-remove-angle-brackets (match-string 0)))))
6491 ((equal complete-file '(4))
6492 ;; Completing read for file names.
6493 (setq file (read-file-name "File: "))
6494 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6495 (pwd1 (file-name-as-directory (abbreviate-file-name
6496 (expand-file-name ".")))))
6497 (cond
6498 ((equal complete-file '(16))
6499 (setq link (org-make-link
6500 "file:"
6501 (abbreviate-file-name (expand-file-name file)))))
6502 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6503 (setq link (org-make-link "file:" (match-string 1 file))))
6504 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6505 (expand-file-name file))
6506 (setq link (org-make-link
6507 "file:" (match-string 1 (expand-file-name file)))))
6508 (t (setq link (org-make-link "file:" file))))))
6510 ;; Read link, with completion for stored links.
6511 (with-output-to-temp-buffer "*Org Links*"
6512 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6513 (when org-stored-links
6514 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6515 (princ (mapconcat
6516 (lambda (x)
6517 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6518 (reverse org-stored-links) "\n"))))
6519 (let ((cw (selected-window)))
6520 (select-window (get-buffer-window "*Org Links*"))
6521 (shrink-window-if-larger-than-buffer)
6522 (setq truncate-lines t)
6523 (select-window cw))
6524 ;; Fake a link history, containing the stored links.
6525 (setq tmphist (append (mapcar 'car org-stored-links)
6526 org-insert-link-history))
6527 (unwind-protect
6528 (setq link (org-completing-read
6529 "Link: "
6530 (append
6531 (mapcar (lambda (x) (list (concat (car x) ":")))
6532 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6533 (mapcar (lambda (x) (list (concat x ":")))
6534 org-link-types))
6535 nil nil nil
6536 'tmphist
6537 (or (car (car org-stored-links)))))
6538 (set-window-configuration wcf)
6539 (kill-buffer "*Org Links*"))
6540 (setq entry (assoc link org-stored-links))
6541 (or entry (push link org-insert-link-history))
6542 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6543 (not org-keep-stored-link-after-insertion))
6544 (setq org-stored-links (delq (assoc link org-stored-links)
6545 org-stored-links)))
6546 (setq desc (or desc (nth 1 entry)))))
6548 (if (string-match org-plain-link-re link)
6549 ;; URL-like link, normalize the use of angular brackets.
6550 (setq link (org-make-link (org-remove-angle-brackets link))))
6552 ;; Check if we are linking to the current file with a search option
6553 ;; If yes, simplify the link by using only the search option.
6554 (when (and buffer-file-name
6555 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6556 (let* ((path (match-string 1 link))
6557 (case-fold-search nil)
6558 (search (match-string 2 link)))
6559 (save-match-data
6560 (if (equal (file-truename buffer-file-name) (file-truename path))
6561 ;; We are linking to this same file, with a search option
6562 (setq link search)))))
6564 ;; Check if we can/should use a relative path. If yes, simplify the link
6565 (when (string-match "\\<file:\\(.*\\)" link)
6566 (let* ((path (match-string 1 link))
6567 (origpath path)
6568 (case-fold-search nil))
6569 (cond
6570 ((eq org-link-file-path-type 'absolute)
6571 (setq path (abbreviate-file-name (expand-file-name path))))
6572 ((eq org-link-file-path-type 'noabbrev)
6573 (setq path (expand-file-name path)))
6574 ((eq org-link-file-path-type 'relative)
6575 (setq path (file-relative-name path)))
6577 (save-match-data
6578 (if (string-match (concat "^" (regexp-quote
6579 (file-name-as-directory
6580 (expand-file-name "."))))
6581 (expand-file-name path))
6582 ;; We are linking a file with relative path name.
6583 (setq path (substring (expand-file-name path)
6584 (match-end 0)))))))
6585 (setq link (concat "file:" path))
6586 (if (equal desc origpath)
6587 (setq desc path))))
6589 (if org-make-link-description-function
6590 (setq desc (funcall org-make-link-description-function link desc)))
6592 (setq desc (read-string "Description: " desc))
6593 (unless (string-match "\\S-" desc) (setq desc nil))
6594 (if remove (apply 'delete-region remove))
6595 (insert (org-make-link-string link desc))))
6597 (defun org-completing-read (&rest args)
6598 (let ((minibuffer-local-completion-map
6599 (copy-keymap minibuffer-local-completion-map)))
6600 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6601 (apply 'completing-read args)))
6603 ;;; Opening/following a link
6605 (defvar org-link-search-failed nil)
6607 (defun org-next-link ()
6608 "Move forward to the next link.
6609 If the link is in hidden text, expose it."
6610 (interactive)
6611 (when (and org-link-search-failed (eq this-command last-command))
6612 (goto-char (point-min))
6613 (message "Link search wrapped back to beginning of buffer"))
6614 (setq org-link-search-failed nil)
6615 (let* ((pos (point))
6616 (ct (org-context))
6617 (a (assoc :link ct)))
6618 (if a (goto-char (nth 2 a)))
6619 (if (re-search-forward org-any-link-re nil t)
6620 (progn
6621 (goto-char (match-beginning 0))
6622 (if (org-invisible-p) (org-show-context)))
6623 (goto-char pos)
6624 (setq org-link-search-failed t)
6625 (error "No further link found"))))
6627 (defun org-previous-link ()
6628 "Move backward to the previous link.
6629 If the link is in hidden text, expose it."
6630 (interactive)
6631 (when (and org-link-search-failed (eq this-command last-command))
6632 (goto-char (point-max))
6633 (message "Link search wrapped back to end of buffer"))
6634 (setq org-link-search-failed nil)
6635 (let* ((pos (point))
6636 (ct (org-context))
6637 (a (assoc :link ct)))
6638 (if a (goto-char (nth 1 a)))
6639 (if (re-search-backward org-any-link-re nil t)
6640 (progn
6641 (goto-char (match-beginning 0))
6642 (if (org-invisible-p) (org-show-context)))
6643 (goto-char pos)
6644 (setq org-link-search-failed t)
6645 (error "No further link found"))))
6647 (defun org-find-file-at-mouse (ev)
6648 "Open file link or URL at mouse."
6649 (interactive "e")
6650 (mouse-set-point ev)
6651 (org-open-at-point 'in-emacs))
6653 (defun org-open-at-mouse (ev)
6654 "Open file link or URL at mouse."
6655 (interactive "e")
6656 (mouse-set-point ev)
6657 (org-open-at-point))
6659 (defvar org-window-config-before-follow-link nil
6660 "The window configuration before following a link.
6661 This is saved in case the need arises to restore it.")
6663 (defvar org-open-link-marker (make-marker)
6664 "Marker pointing to the location where `org-open-at-point; was called.")
6666 ;;;###autoload
6667 (defun org-open-at-point-global ()
6668 "Follow a link like Org-mode does.
6669 This command can be called in any mode to follow a link that has
6670 Org-mode syntax."
6671 (interactive)
6672 (org-run-like-in-org-mode 'org-open-at-point))
6674 ;;;###autoload
6675 (defun org-open-link-from-string (s &optional arg)
6676 "Open a link in the string S, as if it was in Org-mode."
6677 (interactive "sLink: \nP")
6678 (with-temp-buffer
6679 (let ((org-inhibit-startup t))
6680 (org-mode)
6681 (insert s)
6682 (goto-char (point-min))
6683 (org-open-at-point arg))))
6685 (defun org-open-at-point (&optional in-emacs)
6686 "Open link at or after point.
6687 If there is no link at point, this function will search forward up to
6688 the end of the current subtree.
6689 Normally, files will be opened by an appropriate application. If the
6690 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6691 (interactive "P")
6692 (org-load-modules-maybe)
6693 (move-marker org-open-link-marker (point))
6694 (setq org-window-config-before-follow-link (current-window-configuration))
6695 (org-remove-occur-highlights nil nil t)
6696 (if (org-at-timestamp-p t)
6697 (org-follow-timestamp-link)
6698 (let (type path link line search (pos (point)))
6699 (catch 'match
6700 (save-excursion
6701 (skip-chars-forward "^]\n\r")
6702 (when (org-in-regexp org-bracket-link-regexp)
6703 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6704 (while (string-match " *\n *" link)
6705 (setq link (replace-match " " t t link)))
6706 (setq link (org-link-expand-abbrev link))
6707 (if (string-match org-link-re-with-space2 link)
6708 (setq type (match-string 1 link) path (match-string 2 link))
6709 (setq type "thisfile" path link))
6710 (throw 'match t)))
6712 (when (get-text-property (point) 'org-linked-text)
6713 (setq type "thisfile"
6714 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6715 (1+ (point)) (point))
6716 path (buffer-substring
6717 (previous-single-property-change pos 'org-linked-text)
6718 (next-single-property-change pos 'org-linked-text)))
6719 (throw 'match t))
6721 (save-excursion
6722 (when (or (org-in-regexp org-angle-link-re)
6723 (org-in-regexp org-plain-link-re))
6724 (setq type (match-string 1) path (match-string 2))
6725 (throw 'match t)))
6726 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6727 (setq type "tree-match"
6728 path (match-string 1))
6729 (throw 'match t))
6730 (save-excursion
6731 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6732 (setq type "tags"
6733 path (match-string 1))
6734 (while (string-match ":" path)
6735 (setq path (replace-match "+" t t path)))
6736 (throw 'match t))))
6737 (unless path
6738 (error "No link found"))
6739 ;; Remove any trailing spaces in path
6740 (if (string-match " +\\'" path)
6741 (setq path (replace-match "" t t path)))
6743 (cond
6745 ((assoc type org-link-protocols)
6746 (funcall (nth 1 (assoc type org-link-protocols)) path))
6748 ((equal type "mailto")
6749 (let ((cmd (car org-link-mailto-program))
6750 (args (cdr org-link-mailto-program)) args1
6751 (address path) (subject "") a)
6752 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6753 (setq address (match-string 1 path)
6754 subject (org-link-escape (match-string 2 path))))
6755 (while args
6756 (cond
6757 ((not (stringp (car args))) (push (pop args) args1))
6758 (t (setq a (pop args))
6759 (if (string-match "%a" a)
6760 (setq a (replace-match address t t a)))
6761 (if (string-match "%s" a)
6762 (setq a (replace-match subject t t a)))
6763 (push a args1))))
6764 (apply cmd (nreverse args1))))
6766 ((member type '("http" "https" "ftp" "news"))
6767 (browse-url (concat type ":" (org-link-escape
6768 path org-link-escape-chars-browser))))
6770 ((member type '("message"))
6771 (browse-url (concat type ":" path)))
6773 ((string= type "tags")
6774 (org-tags-view in-emacs path))
6775 ((string= type "thisfile")
6776 (if in-emacs
6777 (switch-to-buffer-other-window
6778 (org-get-buffer-for-internal-link (current-buffer)))
6779 (org-mark-ring-push))
6780 (let ((cmd `(org-link-search
6781 ,path
6782 ,(cond ((equal in-emacs '(4)) 'occur)
6783 ((equal in-emacs '(16)) 'org-occur)
6784 (t nil))
6785 ,pos)))
6786 (condition-case nil (eval cmd)
6787 (error (progn (widen) (eval cmd))))))
6789 ((string= type "tree-match")
6790 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6792 ((string= type "file")
6793 (if (string-match "::\\([0-9]+\\)\\'" path)
6794 (setq line (string-to-number (match-string 1 path))
6795 path (substring path 0 (match-beginning 0)))
6796 (if (string-match "::\\(.+\\)\\'" path)
6797 (setq search (match-string 1 path)
6798 path (substring path 0 (match-beginning 0)))))
6799 (if (string-match "[*?{]" (file-name-nondirectory path))
6800 (dired path)
6801 (org-open-file path in-emacs line search)))
6803 ((string= type "news")
6804 (require 'org-gnus)
6805 (org-gnus-follow-link path))
6807 ((string= type "shell")
6808 (let ((cmd path))
6809 (if (or (not org-confirm-shell-link-function)
6810 (funcall org-confirm-shell-link-function
6811 (format "Execute \"%s\" in shell? "
6812 (org-add-props cmd nil
6813 'face 'org-warning))))
6814 (progn
6815 (message "Executing %s" cmd)
6816 (shell-command cmd))
6817 (error "Abort"))))
6819 ((string= type "elisp")
6820 (let ((cmd path))
6821 (if (or (not org-confirm-elisp-link-function)
6822 (funcall org-confirm-elisp-link-function
6823 (format "Execute \"%s\" as elisp? "
6824 (org-add-props cmd nil
6825 'face 'org-warning))))
6826 (message "%s => %s" cmd (eval (read cmd)))
6827 (error "Abort"))))
6830 (browse-url-at-point)))))
6831 (move-marker org-open-link-marker nil)
6832 (run-hook-with-args 'org-follow-link-hook))
6834 ;;;; Time estimates
6836 (defun org-get-effort (&optional pom)
6837 "Get the effort estimate for the current entry."
6838 (org-entry-get pom org-effort-property))
6840 ;;; File search
6842 (defvar org-create-file-search-functions nil
6843 "List of functions to construct the right search string for a file link.
6844 These functions are called in turn with point at the location to
6845 which the link should point.
6847 A function in the hook should first test if it would like to
6848 handle this file type, for example by checking the major-mode or
6849 the file extension. If it decides not to handle this file, it
6850 should just return nil to give other functions a chance. If it
6851 does handle the file, it must return the search string to be used
6852 when following the link. The search string will be part of the
6853 file link, given after a double colon, and `org-open-at-point'
6854 will automatically search for it. If special measures must be
6855 taken to make the search successful, another function should be
6856 added to the companion hook `org-execute-file-search-functions',
6857 which see.
6859 A function in this hook may also use `setq' to set the variable
6860 `description' to provide a suggestion for the descriptive text to
6861 be used for this link when it gets inserted into an Org-mode
6862 buffer with \\[org-insert-link].")
6864 (defvar org-execute-file-search-functions nil
6865 "List of functions to execute a file search triggered by a link.
6867 Functions added to this hook must accept a single argument, the
6868 search string that was part of the file link, the part after the
6869 double colon. The function must first check if it would like to
6870 handle this search, for example by checking the major-mode or the
6871 file extension. If it decides not to handle this search, it
6872 should just return nil to give other functions a chance. If it
6873 does handle the search, it must return a non-nil value to keep
6874 other functions from trying.
6876 Each function can access the current prefix argument through the
6877 variable `current-prefix-argument'. Note that a single prefix is
6878 used to force opening a link in Emacs, so it may be good to only
6879 use a numeric or double prefix to guide the search function.
6881 In case this is needed, a function in this hook can also restore
6882 the window configuration before `org-open-at-point' was called using:
6884 (set-window-configuration org-window-config-before-follow-link)")
6886 (defun org-link-search (s &optional type avoid-pos)
6887 "Search for a link search option.
6888 If S is surrounded by forward slashes, it is interpreted as a
6889 regular expression. In org-mode files, this will create an `org-occur'
6890 sparse tree. In ordinary files, `occur' will be used to list matches.
6891 If the current buffer is in `dired-mode', grep will be used to search
6892 in all files. If AVOID-POS is given, ignore matches near that position."
6893 (let ((case-fold-search t)
6894 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6895 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6896 (append '(("") (" ") ("\t") ("\n"))
6897 org-emphasis-alist)
6898 "\\|") "\\)"))
6899 (pos (point))
6900 (pre nil) (post nil)
6901 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6902 (cond
6903 ;; First check if there are any special
6904 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6905 ;; Now try the builtin stuff
6906 ((save-excursion
6907 (goto-char (point-min))
6908 (and
6909 (re-search-forward
6910 (concat "<<" (regexp-quote s0) ">>") nil t)
6911 (setq type 'dedicated
6912 pos (match-beginning 0))))
6913 ;; There is an exact target for this
6914 (goto-char pos))
6915 ((string-match "^/\\(.*\\)/$" s)
6916 ;; A regular expression
6917 (cond
6918 ((org-mode-p)
6919 (org-occur (match-string 1 s)))
6920 ;;((eq major-mode 'dired-mode)
6921 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6922 (t (org-do-occur (match-string 1 s)))))
6924 ;; A normal search strings
6925 (when (equal (string-to-char s) ?*)
6926 ;; Anchor on headlines, post may include tags.
6927 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6928 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6929 s (substring s 1)))
6930 (remove-text-properties
6931 0 (length s)
6932 '(face nil mouse-face nil keymap nil fontified nil) s)
6933 ;; Make a series of regular expressions to find a match
6934 (setq words (org-split-string s "[ \n\r\t]+")
6936 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6937 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6938 "\\)" markers)
6939 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6940 re2a (concat "[ \t\r\n]" re2a_)
6941 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6942 re4 (concat "[^a-zA-Z_]" re4_)
6944 re1 (concat pre re2 post)
6945 re3 (concat pre (if pre re4_ re4) post)
6946 re5 (concat pre ".*" re4)
6947 re2 (concat pre re2)
6948 re2a (concat pre (if pre re2a_ re2a))
6949 re4 (concat pre (if pre re4_ re4))
6950 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6951 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6952 re5 "\\)"
6954 (cond
6955 ((eq type 'org-occur) (org-occur reall))
6956 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6957 (t (goto-char (point-min))
6958 (setq type 'fuzzy)
6959 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6960 (org-search-not-self 1 re1 nil t)
6961 (org-search-not-self 1 re2 nil t)
6962 (org-search-not-self 1 re2a nil t)
6963 (org-search-not-self 1 re3 nil t)
6964 (org-search-not-self 1 re4 nil t)
6965 (org-search-not-self 1 re5 nil t)
6967 (goto-char (match-beginning 1))
6968 (goto-char pos)
6969 (error "No match")))))
6971 ;; Normal string-search
6972 (goto-char (point-min))
6973 (if (search-forward s nil t)
6974 (goto-char (match-beginning 0))
6975 (error "No match"))))
6976 (and (org-mode-p) (org-show-context 'link-search))
6977 type))
6979 (defun org-search-not-self (group &rest args)
6980 "Execute `re-search-forward', but only accept matches that do not
6981 enclose the position of `org-open-link-marker'."
6982 (let ((m org-open-link-marker))
6983 (catch 'exit
6984 (while (apply 're-search-forward args)
6985 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6986 (goto-char (match-end group))
6987 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6988 (> (match-beginning 0) (marker-position m))
6989 (< (match-end 0) (marker-position m)))
6990 (save-match-data
6991 (or (not (org-in-regexp
6992 org-bracket-link-analytic-regexp 1))
6993 (not (match-end 4)) ; no description
6994 (and (<= (match-beginning 4) (point))
6995 (>= (match-end 4) (point))))))
6996 (throw 'exit (point))))))))
6998 (defun org-get-buffer-for-internal-link (buffer)
6999 "Return a buffer to be used for displaying the link target of internal links."
7000 (cond
7001 ((not org-display-internal-link-with-indirect-buffer)
7002 buffer)
7003 ((string-match "(Clone)$" (buffer-name buffer))
7004 (message "Buffer is already a clone, not making another one")
7005 ;; we also do not modify visibility in this case
7006 buffer)
7007 (t ; make a new indirect buffer for displaying the link
7008 (let* ((bn (buffer-name buffer))
7009 (ibn (concat bn "(Clone)"))
7010 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7011 (with-current-buffer ib (org-overview))
7012 ib))))
7014 (defun org-do-occur (regexp &optional cleanup)
7015 "Call the Emacs command `occur'.
7016 If CLEANUP is non-nil, remove the printout of the regular expression
7017 in the *Occur* buffer. This is useful if the regex is long and not useful
7018 to read."
7019 (occur regexp)
7020 (when cleanup
7021 (let ((cwin (selected-window)) win beg end)
7022 (when (setq win (get-buffer-window "*Occur*"))
7023 (select-window win))
7024 (goto-char (point-min))
7025 (when (re-search-forward "match[a-z]+" nil t)
7026 (setq beg (match-end 0))
7027 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7028 (setq end (1- (match-beginning 0)))))
7029 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7030 (goto-char (point-min))
7031 (select-window cwin))))
7033 ;;; The mark ring for links jumps
7035 (defvar org-mark-ring nil
7036 "Mark ring for positions before jumps in Org-mode.")
7037 (defvar org-mark-ring-last-goto nil
7038 "Last position in the mark ring used to go back.")
7039 ;; Fill and close the ring
7040 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7041 (loop for i from 1 to org-mark-ring-length do
7042 (push (make-marker) org-mark-ring))
7043 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7044 org-mark-ring)
7046 (defun org-mark-ring-push (&optional pos buffer)
7047 "Put the current position or POS into the mark ring and rotate it."
7048 (interactive)
7049 (setq pos (or pos (point)))
7050 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7051 (move-marker (car org-mark-ring)
7052 (or pos (point))
7053 (or buffer (current-buffer)))
7054 (message "%s"
7055 (substitute-command-keys
7056 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7058 (defun org-mark-ring-goto (&optional n)
7059 "Jump to the previous position in the mark ring.
7060 With prefix arg N, jump back that many stored positions. When
7061 called several times in succession, walk through the entire ring.
7062 Org-mode commands jumping to a different position in the current file,
7063 or to another Org-mode file, automatically push the old position
7064 onto the ring."
7065 (interactive "p")
7066 (let (p m)
7067 (if (eq last-command this-command)
7068 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7069 (setq p org-mark-ring))
7070 (setq org-mark-ring-last-goto p)
7071 (setq m (car p))
7072 (switch-to-buffer (marker-buffer m))
7073 (goto-char m)
7074 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7076 (defun org-remove-angle-brackets (s)
7077 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7078 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7080 (defun org-add-angle-brackets (s)
7081 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7082 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7085 ;;; Following specific links
7087 (defun org-follow-timestamp-link ()
7088 (cond
7089 ((org-at-date-range-p t)
7090 (let ((org-agenda-start-on-weekday)
7091 (t1 (match-string 1))
7092 (t2 (match-string 2)))
7093 (setq t1 (time-to-days (org-time-string-to-time t1))
7094 t2 (time-to-days (org-time-string-to-time t2)))
7095 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7096 ((org-at-timestamp-p t)
7097 (org-agenda-list nil (time-to-days (org-time-string-to-time
7098 (substring (match-string 1) 0 10)))
7100 (t (error "This should not happen"))))
7103 ;;; Following file links
7104 (defvar org-wait nil)
7105 (defun org-open-file (path &optional in-emacs line search)
7106 "Open the file at PATH.
7107 First, this expands any special file name abbreviations. Then the
7108 configuration variable `org-file-apps' is checked if it contains an
7109 entry for this file type, and if yes, the corresponding command is launched.
7110 If no application is found, Emacs simply visits the file.
7111 With optional argument IN-EMACS, Emacs will visit the file.
7112 Optional LINE specifies a line to go to, optional SEARCH a string to
7113 search for. If LINE or SEARCH is given, the file will always be
7114 opened in Emacs.
7115 If the file does not exist, an error is thrown."
7116 (setq in-emacs (or in-emacs line search))
7117 (let* ((file (if (equal path "")
7118 buffer-file-name
7119 (substitute-in-file-name (expand-file-name path))))
7120 (apps (append org-file-apps (org-default-apps)))
7121 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7122 (dirp (if remp nil (file-directory-p file)))
7123 (dfile (downcase file))
7124 (old-buffer (current-buffer))
7125 (old-pos (point))
7126 (old-mode major-mode)
7127 ext cmd)
7128 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7129 (setq ext (match-string 1 dfile))
7130 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7131 (setq ext (match-string 1 dfile))))
7132 (if in-emacs
7133 (setq cmd 'emacs)
7134 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7135 (and dirp (cdr (assoc 'directory apps)))
7136 (cdr (assoc ext apps))
7137 (cdr (assoc t apps)))))
7138 (when (eq cmd 'mailcap)
7139 (require 'mailcap)
7140 (mailcap-parse-mailcaps)
7141 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7142 (command (mailcap-mime-info mime-type)))
7143 (if (stringp command)
7144 (setq cmd command)
7145 (setq cmd 'emacs))))
7146 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7147 (not (file-exists-p file))
7148 (not org-open-non-existing-files))
7149 (error "No such file: %s" file))
7150 (cond
7151 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7152 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7153 (while (string-match "['\"]%s['\"]" cmd)
7154 (setq cmd (replace-match "%s" t t cmd)))
7155 (while (string-match "%s" cmd)
7156 (setq cmd (replace-match
7157 (save-match-data (shell-quote-argument file))
7158 t t cmd)))
7159 (save-window-excursion
7160 (start-process-shell-command cmd nil cmd)
7161 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7163 ((or (stringp cmd)
7164 (eq cmd 'emacs))
7165 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7166 (widen)
7167 (if line (goto-line line)
7168 (if search (org-link-search search))))
7169 ((consp cmd)
7170 (eval cmd))
7171 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7172 (and (org-mode-p) (eq old-mode 'org-mode)
7173 (or (not (equal old-buffer (current-buffer)))
7174 (not (equal old-pos (point))))
7175 (org-mark-ring-push old-pos old-buffer))))
7177 (defun org-default-apps ()
7178 "Return the default applications for this operating system."
7179 (cond
7180 ((eq system-type 'darwin)
7181 org-file-apps-defaults-macosx)
7182 ((eq system-type 'windows-nt)
7183 org-file-apps-defaults-windowsnt)
7184 (t org-file-apps-defaults-gnu)))
7186 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7187 (defun org-file-remote-p (file)
7188 "Test whether FILE specifies a location on a remote system.
7189 Return non-nil if the location is indeed remote.
7191 For example, the filename \"/user@host:/foo\" specifies a location
7192 on the system \"/user@host:\"."
7193 (cond ((fboundp 'file-remote-p)
7194 (file-remote-p file))
7195 ((fboundp 'tramp-handle-file-remote-p)
7196 (tramp-handle-file-remote-p file))
7197 ((and (boundp 'ange-ftp-name-format)
7198 (string-match (car ange-ftp-name-format) file))
7200 (t nil)))
7203 ;;;; Refiling
7205 (defun org-get-org-file ()
7206 "Read a filename, with default directory `org-directory'."
7207 (let ((default (or org-default-notes-file remember-data-file)))
7208 (read-file-name (format "File name [%s]: " default)
7209 (file-name-as-directory org-directory)
7210 default)))
7212 (defun org-notes-order-reversed-p ()
7213 "Check if the current file should receive notes in reversed order."
7214 (cond
7215 ((not org-reverse-note-order) nil)
7216 ((eq t org-reverse-note-order) t)
7217 ((not (listp org-reverse-note-order)) nil)
7218 (t (catch 'exit
7219 (let ((all org-reverse-note-order)
7220 entry)
7221 (while (setq entry (pop all))
7222 (if (string-match (car entry) buffer-file-name)
7223 (throw 'exit (cdr entry))))
7224 nil)))))
7226 (defvar org-refile-target-table nil
7227 "The list of refile targets, created by `org-refile'.")
7229 (defvar org-agenda-new-buffers nil
7230 "Buffers created to visit agenda files.")
7232 (defun org-get-refile-targets (&optional default-buffer)
7233 "Produce a table with refile targets."
7234 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7235 targets txt re files f desc descre)
7236 (with-current-buffer (or default-buffer (current-buffer))
7237 (while (setq entry (pop entries))
7238 (setq files (car entry) desc (cdr entry))
7239 (cond
7240 ((null files) (setq files (list (current-buffer))))
7241 ((eq files 'org-agenda-files)
7242 (setq files (org-agenda-files 'unrestricted)))
7243 ((and (symbolp files) (fboundp files))
7244 (setq files (funcall files)))
7245 ((and (symbolp files) (boundp files))
7246 (setq files (symbol-value files))))
7247 (if (stringp files) (setq files (list files)))
7248 (cond
7249 ((eq (car desc) :tag)
7250 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7251 ((eq (car desc) :todo)
7252 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7253 ((eq (car desc) :regexp)
7254 (setq descre (cdr desc)))
7255 ((eq (car desc) :level)
7256 (setq descre (concat "^\\*\\{" (number-to-string
7257 (if org-odd-levels-only
7258 (1- (* 2 (cdr desc)))
7259 (cdr desc)))
7260 "\\}[ \t]")))
7261 ((eq (car desc) :maxlevel)
7262 (setq descre (concat "^\\*\\{1," (number-to-string
7263 (if org-odd-levels-only
7264 (1- (* 2 (cdr desc)))
7265 (cdr desc)))
7266 "\\}[ \t]")))
7267 (t (error "Bad refiling target description %s" desc)))
7268 (while (setq f (pop files))
7269 (save-excursion
7270 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7271 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7272 (save-excursion
7273 (save-restriction
7274 (widen)
7275 (goto-char (point-min))
7276 (while (re-search-forward descre nil t)
7277 (goto-char (point-at-bol))
7278 (when (looking-at org-complex-heading-regexp)
7279 (setq txt (match-string 4)
7280 re (concat "^" (regexp-quote
7281 (buffer-substring (match-beginning 1)
7282 (match-end 4)))))
7283 (if (match-end 5) (setq re (concat re "[ \t]+"
7284 (regexp-quote
7285 (match-string 5)))))
7286 (setq re (concat re "[ \t]*$"))
7287 (when org-refile-use-outline-path
7288 (setq txt (mapconcat 'identity
7289 (append
7290 (if (eq org-refile-use-outline-path 'file)
7291 (list (file-name-nondirectory
7292 (buffer-file-name (buffer-base-buffer))))
7293 (if (eq org-refile-use-outline-path 'full-file-path)
7294 (list (buffer-file-name (buffer-base-buffer)))))
7295 (org-get-outline-path)
7296 (list txt))
7297 "/")))
7298 (push (list txt f re (point)) targets))
7299 (goto-char (point-at-eol))))))))
7300 (nreverse targets))))
7302 (defun org-get-outline-path ()
7303 "Return the outline path to the current entry, as a list."
7304 (let (rtn)
7305 (save-excursion
7306 (while (org-up-heading-safe)
7307 (when (looking-at org-complex-heading-regexp)
7308 (push (org-match-string-no-properties 4) rtn)))
7309 rtn)))
7311 (defvar org-refile-history nil
7312 "History for refiling operations.")
7314 (defun org-refile (&optional goto default-buffer)
7315 "Move the entry at point to another heading.
7316 The list of target headings is compiled using the information in
7317 `org-refile-targets', which see. This list is created before each use
7318 and will therefore always be up-to-date.
7320 At the target location, the entry is filed as a subitem of the target heading.
7321 Depending on `org-reverse-note-order', the new subitem will either be the
7322 first of the last subitem.
7324 With prefix arg GOTO, the command will only visit the target location,
7325 not actually move anything.
7326 With a double prefix `C-c C-c', go to the location where the last refiling
7327 operation has put the subtree."
7328 (interactive "P")
7329 (let* ((cbuf (current-buffer))
7330 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7331 pos it nbuf file re level reversed)
7332 (if (equal goto '(16))
7333 (org-refile-goto-last-stored)
7334 (when (setq it (org-refile-get-location
7335 (if goto "Goto: " "Refile to: ") default-buffer))
7336 (setq file (nth 1 it)
7337 re (nth 2 it)
7338 pos (nth 3 it))
7339 (setq nbuf (or (find-buffer-visiting file)
7340 (find-file-noselect file)))
7341 (if goto
7342 (progn
7343 (switch-to-buffer nbuf)
7344 (goto-char pos)
7345 (org-show-context 'org-goto))
7346 (org-copy-special)
7347 (save-excursion
7348 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7349 (find-file-noselect file))))
7350 (setq reversed (org-notes-order-reversed-p))
7351 (save-excursion
7352 (save-restriction
7353 (widen)
7354 (goto-char pos)
7355 (looking-at outline-regexp)
7356 (setq level (org-get-valid-level (funcall outline-level) 1))
7357 (goto-char
7358 (if reversed
7359 (outline-next-heading)
7360 (or (save-excursion (outline-get-next-sibling))
7361 (org-end-of-subtree t t)
7362 (point-max))))
7363 (bookmark-set "org-refile-last-stored")
7364 (org-paste-subtree level))))
7365 (org-cut-special)
7366 (message "Entry refiled to \"%s\"" (car it)))))))
7368 (defun org-refile-goto-last-stored ()
7369 "Go to the location where the last refile was stored."
7370 (interactive)
7371 (bookmark-jump "org-refile-last-stored")
7372 (message "This is the location of the last refile"))
7374 (defun org-refile-get-location (&optional prompt default-buffer)
7375 "Prompt the user for a refile location, using PROMPT."
7376 (let ((org-refile-targets org-refile-targets)
7377 (org-refile-use-outline-path org-refile-use-outline-path))
7378 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7379 (unless org-refile-target-table
7380 (error "No refile targets"))
7381 (let* ((cbuf (current-buffer))
7382 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7383 (fname (and filename (file-truename filename)))
7384 (tbl (mapcar
7385 (lambda (x)
7386 (if (not (equal fname (file-truename (nth 1 x))))
7387 (cons (concat (car x) " (" (file-name-nondirectory
7388 (nth 1 x)) ")")
7389 (cdr x))
7391 org-refile-target-table))
7392 (completion-ignore-case t))
7393 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7394 tbl)))
7396 ;;;; Dynamic blocks
7398 (defun org-find-dblock (name)
7399 "Find the first dynamic block with name NAME in the buffer.
7400 If not found, stay at current position and return nil."
7401 (let (pos)
7402 (save-excursion
7403 (goto-char (point-min))
7404 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7405 nil t)
7406 (match-beginning 0))))
7407 (if pos (goto-char pos))
7408 pos))
7410 (defconst org-dblock-start-re
7411 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7412 "Matches the startline of a dynamic block, with parameters.")
7414 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7415 "Matches the end of a dyhamic block.")
7417 (defun org-create-dblock (plist)
7418 "Create a dynamic block section, with parameters taken from PLIST.
7419 PLIST must containe a :name entry which is used as name of the block."
7420 (unless (bolp) (newline))
7421 (let ((name (plist-get plist :name)))
7422 (insert "#+BEGIN: " name)
7423 (while plist
7424 (if (eq (car plist) :name)
7425 (setq plist (cddr plist))
7426 (insert " " (prin1-to-string (pop plist)))))
7427 (insert "\n\n#+END:\n")
7428 (beginning-of-line -2)))
7430 (defun org-prepare-dblock ()
7431 "Prepare dynamic block for refresh.
7432 This empties the block, puts the cursor at the insert position and returns
7433 the property list including an extra property :name with the block name."
7434 (unless (looking-at org-dblock-start-re)
7435 (error "Not at a dynamic block"))
7436 (let* ((begdel (1+ (match-end 0)))
7437 (name (org-no-properties (match-string 1)))
7438 (params (append (list :name name)
7439 (read (concat "(" (match-string 3) ")")))))
7440 (unless (re-search-forward org-dblock-end-re nil t)
7441 (error "Dynamic block not terminated"))
7442 (setq params
7443 (append params
7444 (list :content (buffer-substring
7445 begdel (match-beginning 0)))))
7446 (delete-region begdel (match-beginning 0))
7447 (goto-char begdel)
7448 (open-line 1)
7449 params))
7451 (defun org-map-dblocks (&optional command)
7452 "Apply COMMAND to all dynamic blocks in the current buffer.
7453 If COMMAND is not given, use `org-update-dblock'."
7454 (let ((cmd (or command 'org-update-dblock))
7455 pos)
7456 (save-excursion
7457 (goto-char (point-min))
7458 (while (re-search-forward org-dblock-start-re nil t)
7459 (goto-char (setq pos (match-beginning 0)))
7460 (condition-case nil
7461 (funcall cmd)
7462 (error (message "Error during update of dynamic block")))
7463 (goto-char pos)
7464 (unless (re-search-forward org-dblock-end-re nil t)
7465 (error "Dynamic block not terminated"))))))
7467 (defun org-dblock-update (&optional arg)
7468 "User command for updating dynamic blocks.
7469 Update the dynamic block at point. With prefix ARG, update all dynamic
7470 blocks in the buffer."
7471 (interactive "P")
7472 (if arg
7473 (org-update-all-dblocks)
7474 (or (looking-at org-dblock-start-re)
7475 (org-beginning-of-dblock))
7476 (org-update-dblock)))
7478 (defun org-update-dblock ()
7479 "Update the dynamic block at point
7480 This means to empty the block, parse for parameters and then call
7481 the correct writing function."
7482 (save-window-excursion
7483 (let* ((pos (point))
7484 (line (org-current-line))
7485 (params (org-prepare-dblock))
7486 (name (plist-get params :name))
7487 (cmd (intern (concat "org-dblock-write:" name))))
7488 (message "Updating dynamic block `%s' at line %d..." name line)
7489 (funcall cmd params)
7490 (message "Updating dynamic block `%s' at line %d...done" name line)
7491 (goto-char pos))))
7493 (defun org-beginning-of-dblock ()
7494 "Find the beginning of the dynamic block at point.
7495 Error if there is no scuh block at point."
7496 (let ((pos (point))
7497 beg)
7498 (end-of-line 1)
7499 (if (and (re-search-backward org-dblock-start-re nil t)
7500 (setq beg (match-beginning 0))
7501 (re-search-forward org-dblock-end-re nil t)
7502 (> (match-end 0) pos))
7503 (goto-char beg)
7504 (goto-char pos)
7505 (error "Not in a dynamic block"))))
7507 (defun org-update-all-dblocks ()
7508 "Update all dynamic blocks in the buffer.
7509 This function can be used in a hook."
7510 (when (org-mode-p)
7511 (org-map-dblocks 'org-update-dblock)))
7514 ;;;; Completion
7516 (defconst org-additional-option-like-keywords
7517 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7518 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7519 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7521 (defun org-complete (&optional arg)
7522 "Perform completion on word at point.
7523 At the beginning of a headline, this completes TODO keywords as given in
7524 `org-todo-keywords'.
7525 If the current word is preceded by a backslash, completes the TeX symbols
7526 that are supported for HTML support.
7527 If the current word is preceded by \"#+\", completes special words for
7528 setting file options.
7529 In the line after \"#+STARTUP:, complete valid keywords.\"
7530 At all other locations, this simply calls the value of
7531 `org-completion-fallback-command'."
7532 (interactive "P")
7533 (org-without-partial-completion
7534 (catch 'exit
7535 (let* ((end (point))
7536 (beg1 (save-excursion
7537 (skip-chars-backward (org-re "[:alnum:]_@"))
7538 (point)))
7539 (beg (save-excursion
7540 (skip-chars-backward "a-zA-Z0-9_:$")
7541 (point)))
7542 (confirm (lambda (x) (stringp (car x))))
7543 (searchhead (equal (char-before beg) ?*))
7544 (tag (and (equal (char-before beg1) ?:)
7545 (equal (char-after (point-at-bol)) ?*)))
7546 (prop (and (equal (char-before beg1) ?:)
7547 (not (equal (char-after (point-at-bol)) ?*))))
7548 (texp (equal (char-before beg) ?\\))
7549 (link (equal (char-before beg) ?\[))
7550 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7551 beg)
7552 "#+"))
7553 (startup (string-match "^#\\+STARTUP:.*"
7554 (buffer-substring (point-at-bol) (point))))
7555 (completion-ignore-case opt)
7556 (type nil)
7557 (tbl nil)
7558 (table (cond
7559 (opt
7560 (setq type :opt)
7561 (require 'org-exp)
7562 (append
7563 (mapcar
7564 (lambda (x)
7565 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7566 (cons (match-string 2 x) (match-string 1 x)))
7567 (org-split-string (org-get-current-options) "\n"))
7568 (mapcar 'list org-additional-option-like-keywords)))
7569 (startup
7570 (setq type :startup)
7571 org-startup-options)
7572 (link (append org-link-abbrev-alist-local
7573 org-link-abbrev-alist))
7574 (texp
7575 (setq type :tex)
7576 org-html-entities)
7577 ((string-match "\\`\\*+[ \t]+\\'"
7578 (buffer-substring (point-at-bol) beg))
7579 (setq type :todo)
7580 (mapcar 'list org-todo-keywords-1))
7581 (searchhead
7582 (setq type :searchhead)
7583 (save-excursion
7584 (goto-char (point-min))
7585 (while (re-search-forward org-todo-line-regexp nil t)
7586 (push (list
7587 (org-make-org-heading-search-string
7588 (match-string 3) t))
7589 tbl)))
7590 tbl)
7591 (tag (setq type :tag beg beg1)
7592 (or org-tag-alist (org-get-buffer-tags)))
7593 (prop (setq type :prop beg beg1)
7594 (mapcar 'list (org-buffer-property-keys nil t t)))
7595 (t (progn
7596 (call-interactively org-completion-fallback-command)
7597 (throw 'exit nil)))))
7598 (pattern (buffer-substring-no-properties beg end))
7599 (completion (try-completion pattern table confirm)))
7600 (cond ((eq completion t)
7601 (if (not (assoc (upcase pattern) table))
7602 (message "Already complete")
7603 (if (and (equal type :opt)
7604 (not (member (car (assoc (upcase pattern) table))
7605 org-additional-option-like-keywords)))
7606 (insert (substring (cdr (assoc (upcase pattern) table))
7607 (length pattern)))
7608 (if (memq type '(:tag :prop)) (insert ":")))))
7609 ((null completion)
7610 (message "Can't find completion for \"%s\"" pattern)
7611 (ding))
7612 ((not (string= pattern completion))
7613 (delete-region beg end)
7614 (if (string-match " +$" completion)
7615 (setq completion (replace-match "" t t completion)))
7616 (insert completion)
7617 (if (get-buffer-window "*Completions*")
7618 (delete-window (get-buffer-window "*Completions*")))
7619 (if (assoc completion table)
7620 (if (eq type :todo) (insert " ")
7621 (if (memq type '(:tag :prop)) (insert ":"))))
7622 (if (and (equal type :opt) (assoc completion table))
7623 (message "%s" (substitute-command-keys
7624 "Press \\[org-complete] again to insert example settings"))))
7626 (message "Making completion list...")
7627 (let ((list (sort (all-completions pattern table confirm)
7628 'string<)))
7629 (with-output-to-temp-buffer "*Completions*"
7630 (condition-case nil
7631 ;; Protection needed for XEmacs and emacs 21
7632 (display-completion-list list pattern)
7633 (error (display-completion-list list)))))
7634 (message "Making completion list...%s" "done")))))))
7636 ;;;; TODO, DEADLINE, Comments
7638 (defun org-toggle-comment ()
7639 "Change the COMMENT state of an entry."
7640 (interactive)
7641 (save-excursion
7642 (org-back-to-heading)
7643 (let (case-fold-search)
7644 (if (looking-at (concat outline-regexp
7645 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7646 (replace-match "" t t nil 1)
7647 (if (looking-at outline-regexp)
7648 (progn
7649 (goto-char (match-end 0))
7650 (insert org-comment-string " ")))))))
7652 (defvar org-last-todo-state-is-todo nil
7653 "This is non-nil when the last TODO state change led to a TODO state.
7654 If the last change removed the TODO tag or switched to DONE, then
7655 this is nil.")
7657 (defvar org-setting-tags nil) ; dynamically skiped
7659 (defun org-parse-local-options (string var)
7660 "Parse STRING for startup setting relevant for variable VAR."
7661 (let ((rtn (symbol-value var))
7662 e opts)
7663 (save-match-data
7664 (if (or (not string) (not (string-match "\\S-" string)))
7666 (setq opts (delq nil (mapcar (lambda (x)
7667 (setq e (assoc x org-startup-options))
7668 (if (eq (nth 1 e) var) e nil))
7669 (org-split-string string "[ \t]+"))))
7670 (if (not opts)
7672 (setq rtn nil)
7673 (while (setq e (pop opts))
7674 (if (not (nth 3 e))
7675 (setq rtn (nth 2 e))
7676 (if (not (listp rtn)) (setq rtn nil))
7677 (push (nth 2 e) rtn)))
7678 rtn)))))
7680 (defvar org-blocker-hook nil
7681 "Hook for functions that are allowed to block a state change.
7683 Each function gets as its single argument a property list, see
7684 `org-trigger-hook' for more information about this list.
7686 If any of the functions in this hook returns nil, the state change
7687 is blocked.")
7689 (defvar org-trigger-hook nil
7690 "Hook for functions that are triggered by a state change.
7692 Each function gets as its single argument a property list with at least
7693 the following elements:
7695 (:type type-of-change :position pos-at-entry-start
7696 :from old-state :to new-state)
7698 Depending on the type, more properties may be present.
7700 This mechanism is currently implemented for:
7702 TODO state changes
7703 ------------------
7704 :type todo-state-change
7705 :from previous state (keyword as a string), or nil
7706 :to new state (keyword as a string), or nil")
7709 (defun org-todo (&optional arg)
7710 "Change the TODO state of an item.
7711 The state of an item is given by a keyword at the start of the heading,
7712 like
7713 *** TODO Write paper
7714 *** DONE Call mom
7716 The different keywords are specified in the variable `org-todo-keywords'.
7717 By default the available states are \"TODO\" and \"DONE\".
7718 So for this example: when the item starts with TODO, it is changed to DONE.
7719 When it starts with DONE, the DONE is removed. And when neither TODO nor
7720 DONE are present, add TODO at the beginning of the heading.
7722 With C-u prefix arg, use completion to determine the new state.
7723 With numeric prefix arg, switch to that state.
7725 For calling through lisp, arg is also interpreted in the following way:
7726 'none -> empty state
7727 \"\"(empty string) -> switch to empty state
7728 'done -> switch to DONE
7729 'nextset -> switch to the next set of keywords
7730 'previousset -> switch to the previous set of keywords
7731 \"WAITING\" -> switch to the specified keyword, but only if it
7732 really is a member of `org-todo-keywords'."
7733 (interactive "P")
7734 (save-excursion
7735 (catch 'exit
7736 (org-back-to-heading)
7737 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7738 (or (looking-at (concat " +" org-todo-regexp " *"))
7739 (looking-at " *"))
7740 (let* ((match-data (match-data))
7741 (startpos (point-at-bol))
7742 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7743 (org-log-done org-log-done)
7744 (org-log-repeat org-log-repeat)
7745 (org-todo-log-states org-todo-log-states)
7746 (this (match-string 1))
7747 (hl-pos (match-beginning 0))
7748 (head (org-get-todo-sequence-head this))
7749 (ass (assoc head org-todo-kwd-alist))
7750 (interpret (nth 1 ass))
7751 (done-word (nth 3 ass))
7752 (final-done-word (nth 4 ass))
7753 (last-state (or this ""))
7754 (completion-ignore-case t)
7755 (member (member this org-todo-keywords-1))
7756 (tail (cdr member))
7757 (state (cond
7758 ((and org-todo-key-trigger
7759 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7760 (and (not arg) org-use-fast-todo-selection
7761 (not (eq org-use-fast-todo-selection 'prefix)))))
7762 ;; Use fast selection
7763 (org-fast-todo-selection))
7764 ((and (equal arg '(4))
7765 (or (not org-use-fast-todo-selection)
7766 (not org-todo-key-trigger)))
7767 ;; Read a state with completion
7768 (completing-read "State: " (mapcar (lambda(x) (list x))
7769 org-todo-keywords-1)
7770 nil t))
7771 ((eq arg 'right)
7772 (if this
7773 (if tail (car tail) nil)
7774 (car org-todo-keywords-1)))
7775 ((eq arg 'left)
7776 (if (equal member org-todo-keywords-1)
7778 (if this
7779 (nth (- (length org-todo-keywords-1) (length tail) 2)
7780 org-todo-keywords-1)
7781 (org-last org-todo-keywords-1))))
7782 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7783 (setq arg nil))) ; hack to fall back to cycling
7784 (arg
7785 ;; user or caller requests a specific state
7786 (cond
7787 ((equal arg "") nil)
7788 ((eq arg 'none) nil)
7789 ((eq arg 'done) (or done-word (car org-done-keywords)))
7790 ((eq arg 'nextset)
7791 (or (car (cdr (member head org-todo-heads)))
7792 (car org-todo-heads)))
7793 ((eq arg 'previousset)
7794 (let ((org-todo-heads (reverse org-todo-heads)))
7795 (or (car (cdr (member head org-todo-heads)))
7796 (car org-todo-heads))))
7797 ((car (member arg org-todo-keywords-1)))
7798 ((nth (1- (prefix-numeric-value arg))
7799 org-todo-keywords-1))))
7800 ((null member) (or head (car org-todo-keywords-1)))
7801 ((equal this final-done-word) nil) ;; -> make empty
7802 ((null tail) nil) ;; -> first entry
7803 ((eq interpret 'sequence)
7804 (car tail))
7805 ((memq interpret '(type priority))
7806 (if (eq this-command last-command)
7807 (car tail)
7808 (if (> (length tail) 0)
7809 (or done-word (car org-done-keywords))
7810 nil)))
7811 (t nil)))
7812 (next (if state (concat " " state " ") " "))
7813 (change-plist (list :type 'todo-state-change :from this :to state
7814 :position startpos))
7815 dolog now-done-p)
7816 (when org-blocker-hook
7817 (unless (save-excursion
7818 (save-match-data
7819 (run-hook-with-args-until-failure
7820 'org-blocker-hook change-plist)))
7821 (if (interactive-p)
7822 (error "TODO state change from %s to %s blocked" this state)
7823 ;; fail silently
7824 (message "TODO state change from %s to %s blocked" this state)
7825 (throw 'exit nil))))
7826 (store-match-data match-data)
7827 (replace-match next t t)
7828 (unless (pos-visible-in-window-p hl-pos)
7829 (message "TODO state changed to %s" (org-trim next)))
7830 (unless head
7831 (setq head (org-get-todo-sequence-head state)
7832 ass (assoc head org-todo-kwd-alist)
7833 interpret (nth 1 ass)
7834 done-word (nth 3 ass)
7835 final-done-word (nth 4 ass)))
7836 (when (memq arg '(nextset previousset))
7837 (message "Keyword-Set %d/%d: %s"
7838 (- (length org-todo-sets) -1
7839 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7840 (length org-todo-sets)
7841 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7842 (setq org-last-todo-state-is-todo
7843 (not (member state org-done-keywords)))
7844 (setq now-done-p (and (member state org-done-keywords)
7845 (not (member this org-done-keywords))))
7846 (and logging (org-local-logging logging))
7847 (when (and (or org-todo-log-states org-log-done)
7848 (not (memq arg '(nextset previousset))))
7849 ;; we need to look at recording a time and note
7850 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7851 (nth 2 (assoc this org-todo-log-states))))
7852 (when (and state
7853 (member state org-not-done-keywords)
7854 (not (member this org-not-done-keywords)))
7855 ;; This is now a todo state and was not one before
7856 ;; If there was a CLOSED time stamp, get rid of it.
7857 (org-add-planning-info nil nil 'closed))
7858 (when (and now-done-p org-log-done)
7859 ;; It is now done, and it was not done before
7860 (org-add-planning-info 'closed (org-current-time))
7861 (if (and (not dolog) (eq 'note org-log-done))
7862 (org-add-log-setup 'done state 'findpos 'note)))
7863 (when (and state dolog)
7864 ;; This is a non-nil state, and we need to log it
7865 (org-add-log-setup 'state state 'findpos dolog)))
7866 ;; Fixup tag positioning
7867 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7868 (run-hooks 'org-after-todo-state-change-hook)
7869 (if (and arg (not (member state org-done-keywords)))
7870 (setq head (org-get-todo-sequence-head state)))
7871 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7872 ;; Do we need to trigger a repeat?
7873 (when now-done-p (org-auto-repeat-maybe state))
7874 ;; Fixup cursor location if close to the keyword
7875 (if (and (outline-on-heading-p)
7876 (not (bolp))
7877 (save-excursion (beginning-of-line 1)
7878 (looking-at org-todo-line-regexp))
7879 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7880 (progn
7881 (goto-char (or (match-end 2) (match-end 1)))
7882 (just-one-space)))
7883 (when org-trigger-hook
7884 (save-excursion
7885 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7887 (defun org-local-logging (value)
7888 "Get logging settings from a property VALUE."
7889 (let* (words w a)
7890 ;; directly set the variables, they are already local.
7891 (setq org-log-done nil
7892 org-log-repeat nil
7893 org-todo-log-states nil)
7894 (setq words (org-split-string value))
7895 (while (setq w (pop words))
7896 (cond
7897 ((setq a (assoc w org-startup-options))
7898 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7899 (set (nth 1 a) (nth 2 a))))
7900 ((setq a (org-extract-log-state-settings w))
7901 (and (member (car a) org-todo-keywords-1)
7902 (push a org-todo-log-states)))))))
7904 (defun org-get-todo-sequence-head (kwd)
7905 "Return the head of the TODO sequence to which KWD belongs.
7906 If KWD is not set, check if there is a text property remembering the
7907 right sequence."
7908 (let (p)
7909 (cond
7910 ((not kwd)
7911 (or (get-text-property (point-at-bol) 'org-todo-head)
7912 (progn
7913 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7914 nil (point-at-eol)))
7915 (get-text-property p 'org-todo-head))))
7916 ((not (member kwd org-todo-keywords-1))
7917 (car org-todo-keywords-1))
7918 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7920 (defun org-fast-todo-selection ()
7921 "Fast TODO keyword selection with single keys.
7922 Returns the new TODO keyword, or nil if no state change should occur."
7923 (let* ((fulltable org-todo-key-alist)
7924 (done-keywords org-done-keywords) ;; needed for the faces.
7925 (maxlen (apply 'max (mapcar
7926 (lambda (x)
7927 (if (stringp (car x)) (string-width (car x)) 0))
7928 fulltable)))
7929 (expert nil)
7930 (fwidth (+ maxlen 3 1 3))
7931 (ncol (/ (- (window-width) 4) fwidth))
7932 tg cnt e c tbl
7933 groups ingroup)
7934 (save-window-excursion
7935 (if expert
7936 (set-buffer (get-buffer-create " *Org todo*"))
7937 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7938 (erase-buffer)
7939 (org-set-local 'org-done-keywords done-keywords)
7940 (setq tbl fulltable cnt 0)
7941 (while (setq e (pop tbl))
7942 (cond
7943 ((equal e '(:startgroup))
7944 (push '() groups) (setq ingroup t)
7945 (when (not (= cnt 0))
7946 (setq cnt 0)
7947 (insert "\n"))
7948 (insert "{ "))
7949 ((equal e '(:endgroup))
7950 (setq ingroup nil cnt 0)
7951 (insert "}\n"))
7953 (setq tg (car e) c (cdr e))
7954 (if ingroup (push tg (car groups)))
7955 (setq tg (org-add-props tg nil 'face
7956 (org-get-todo-face tg)))
7957 (if (and (= cnt 0) (not ingroup)) (insert " "))
7958 (insert "[" c "] " tg (make-string
7959 (- fwidth 4 (length tg)) ?\ ))
7960 (when (= (setq cnt (1+ cnt)) ncol)
7961 (insert "\n")
7962 (if ingroup (insert " "))
7963 (setq cnt 0)))))
7964 (insert "\n")
7965 (goto-char (point-min))
7966 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7967 (fit-window-to-buffer))
7968 (message "[a-z..]:Set [SPC]:clear")
7969 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7970 (cond
7971 ((or (= c ?\C-g)
7972 (and (= c ?q) (not (rassoc c fulltable))))
7973 (setq quit-flag t))
7974 ((= c ?\ ) nil)
7975 ((setq e (rassoc c fulltable) tg (car e))
7977 (t (setq quit-flag t))))))
7979 (defun org-entry-is-todo-p ()
7980 (member (org-get-todo-state) org-not-done-keywords))
7982 (defun org-entry-is-done-p ()
7983 (member (org-get-todo-state) org-done-keywords))
7985 (defun org-get-todo-state ()
7986 (save-excursion
7987 (org-back-to-heading t)
7988 (and (looking-at org-todo-line-regexp)
7989 (match-end 2)
7990 (match-string 2))))
7992 (defun org-at-date-range-p (&optional inactive-ok)
7993 "Is the cursor inside a date range?"
7994 (interactive)
7995 (save-excursion
7996 (catch 'exit
7997 (let ((pos (point)))
7998 (skip-chars-backward "^[<\r\n")
7999 (skip-chars-backward "<[")
8000 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8001 (>= (match-end 0) pos)
8002 (throw 'exit t))
8003 (skip-chars-backward "^<[\r\n")
8004 (skip-chars-backward "<[")
8005 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8006 (>= (match-end 0) pos)
8007 (throw 'exit t)))
8008 nil)))
8010 (defun org-get-repeat ()
8011 "Check if tere is a deadline/schedule with repeater in this entry."
8012 (save-match-data
8013 (save-excursion
8014 (org-back-to-heading t)
8015 (if (re-search-forward
8016 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8017 (match-string 1)))))
8019 (defvar org-last-changed-timestamp)
8020 (defvar org-log-post-message)
8021 (defvar org-log-note-purpose)
8022 (defvar org-log-note-how)
8023 (defun org-auto-repeat-maybe (done-word)
8024 "Check if the current headline contains a repeated deadline/schedule.
8025 If yes, set TODO state back to what it was and change the base date
8026 of repeating deadline/scheduled time stamps to new date.
8027 This function is run automatically after each state change to a DONE state."
8028 ;; last-state is dynamically scoped into this function
8029 (let* ((repeat (org-get-repeat))
8030 (aa (assoc last-state org-todo-kwd-alist))
8031 (interpret (nth 1 aa))
8032 (head (nth 2 aa))
8033 (whata '(("d" . day) ("m" . month) ("y" . year)))
8034 (msg "Entry repeats: ")
8035 (org-log-done nil)
8036 (org-todo-log-states nil)
8037 (nshiftmax 10) (nshift 0)
8038 re type n what ts mb0 time)
8039 (when repeat
8040 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8041 (org-todo (if (eq interpret 'type) last-state head))
8042 (when org-log-repeat
8043 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8044 (memq 'org-add-log-note post-command-hook))
8045 ;; OK, we are already setup for some record
8046 (if (eq org-log-repeat 'note)
8047 ;; make sure we take a note, not only a time stamp
8048 (setq org-log-note-how 'note))
8049 ;; Set up for taking a record
8050 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8051 'findpos org-log-repeat)))
8052 (org-back-to-heading t)
8053 (org-add-planning-info nil nil 'closed)
8054 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8055 org-deadline-time-regexp "\\)\\|\\("
8056 org-ts-regexp "\\)"))
8057 (while (re-search-forward
8058 re (save-excursion (outline-next-heading) (point)) t)
8059 (setq type (if (match-end 1) org-scheduled-string
8060 (if (match-end 3) org-deadline-string "Plain:"))
8061 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8062 mb0 (match-beginning 0))
8063 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8064 (setq n (string-to-number (match-string 2 ts))
8065 what (match-string 3 ts))
8066 (if (equal what "w") (setq n (* n 7) what "d"))
8067 ;; Preparation, see if we need to modify the start date for the change
8068 (when (match-end 1)
8069 (setq time (save-match-data (org-time-string-to-time ts)))
8070 (cond
8071 ((equal (match-string 1 ts) ".")
8072 ;; Shift starting date to today
8073 (org-timestamp-change
8074 (- (time-to-days (current-time)) (time-to-days time))
8075 'day))
8076 ((equal (match-string 1 ts) "+")
8077 (while (or (= nshift 0)
8078 (<= (time-to-days time) (time-to-days (current-time))))
8079 (when (= (incf nshift) nshiftmax)
8080 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8081 (error "Abort")))
8082 (org-timestamp-change n (cdr (assoc what whata)))
8083 (org-at-timestamp-p t)
8084 (setq ts (match-string 1))
8085 (setq time (save-match-data (org-time-string-to-time ts))))
8086 (org-timestamp-change (- n) (cdr (assoc what whata)))
8087 ;; rematch, so that we have everything in place for the real shift
8088 (org-at-timestamp-p t)
8089 (setq ts (match-string 1))
8090 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8091 (org-timestamp-change n (cdr (assoc what whata)))
8092 (setq msg (concat msg type org-last-changed-timestamp " "))))
8093 (setq org-log-post-message msg)
8094 (message "%s" msg))))
8096 (defun org-show-todo-tree (arg)
8097 "Make a compact tree which shows all headlines marked with TODO.
8098 The tree will show the lines where the regexp matches, and all higher
8099 headlines above the match.
8100 With a \\[universal-argument] prefix, also show the DONE entries.
8101 With a numeric prefix N, construct a sparse tree for the Nth element
8102 of `org-todo-keywords-1'."
8103 (interactive "P")
8104 (let ((case-fold-search nil)
8105 (kwd-re
8106 (cond ((null arg) org-not-done-regexp)
8107 ((equal arg '(4))
8108 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8109 (mapcar 'list org-todo-keywords-1))))
8110 (concat "\\("
8111 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8112 "\\)\\>")))
8113 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8114 (regexp-quote (nth (1- (prefix-numeric-value arg))
8115 org-todo-keywords-1)))
8116 (t (error "Invalid prefix argument: %s" arg)))))
8117 (message "%d TODO entries found"
8118 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8120 (defun org-deadline (&optional remove)
8121 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8122 With argument REMOVE, remove any deadline from the item."
8123 (interactive "P")
8124 (if remove
8125 (progn
8126 (org-remove-timestamp-with-keyword org-deadline-string)
8127 (message "Item no longer has a deadline."))
8128 (org-add-planning-info 'deadline nil 'closed)))
8130 (defun org-schedule (&optional remove)
8131 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8132 With argument REMOVE, remove any scheduling date from the item."
8133 (interactive "P")
8134 (if remove
8135 (progn
8136 (org-remove-timestamp-with-keyword org-scheduled-string)
8137 (message "Item is no longer scheduled."))
8138 (org-add-planning-info 'scheduled nil 'closed)))
8140 (defun org-remove-timestamp-with-keyword (keyword)
8141 "Remove all time stamps with KEYWORD in the current entry."
8142 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8143 beg)
8144 (save-excursion
8145 (org-back-to-heading t)
8146 (setq beg (point))
8147 (org-end-of-subtree t t)
8148 (while (re-search-backward re beg t)
8149 (replace-match "")
8150 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8151 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8153 (defun org-add-planning-info (what &optional time &rest remove)
8154 "Insert new timestamp with keyword in the line directly after the headline.
8155 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8156 If non is given, the user is prompted for a date.
8157 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8158 be removed."
8159 (interactive)
8160 (let (org-time-was-given org-end-time-was-given ts
8161 end default-time default-input)
8163 (when (and (not time) (memq what '(scheduled deadline)))
8164 ;; Try to get a default date/time from existing timestamp
8165 (save-excursion
8166 (org-back-to-heading t)
8167 (setq end (save-excursion (outline-next-heading) (point)))
8168 (when (re-search-forward (if (eq what 'scheduled)
8169 org-scheduled-time-regexp
8170 org-deadline-time-regexp)
8171 end t)
8172 (setq ts (match-string 1)
8173 default-time
8174 (apply 'encode-time (org-parse-time-string ts))
8175 default-input (and ts (org-get-compact-tod ts))))))
8176 (when what
8177 ;; If necessary, get the time from the user
8178 (setq time (or time (org-read-date nil 'to-time nil nil
8179 default-time default-input))))
8181 (when (and org-insert-labeled-timestamps-at-point
8182 (member what '(scheduled deadline)))
8183 (insert
8184 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8185 (org-insert-time-stamp time org-time-was-given
8186 nil nil nil (list org-end-time-was-given))
8187 (setq what nil))
8188 (save-excursion
8189 (save-restriction
8190 (let (col list elt ts buffer-invisibility-spec)
8191 (org-back-to-heading t)
8192 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8193 (goto-char (match-end 1))
8194 (setq col (current-column))
8195 (goto-char (match-end 0))
8196 (if (eobp) (insert "\n") (forward-char 1))
8197 (if (and (not (looking-at outline-regexp))
8198 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8199 "[^\r\n]*"))
8200 (not (equal (match-string 1) org-clock-string)))
8201 (narrow-to-region (match-beginning 0) (match-end 0))
8202 (insert-before-markers "\n")
8203 (backward-char 1)
8204 (narrow-to-region (point) (point))
8205 (indent-to-column col))
8206 ;; Check if we have to remove something.
8207 (setq list (cons what remove))
8208 (while list
8209 (setq elt (pop list))
8210 (goto-char (point-min))
8211 (when (or (and (eq elt 'scheduled)
8212 (re-search-forward org-scheduled-time-regexp nil t))
8213 (and (eq elt 'deadline)
8214 (re-search-forward org-deadline-time-regexp nil t))
8215 (and (eq elt 'closed)
8216 (re-search-forward org-closed-time-regexp nil t)))
8217 (replace-match "")
8218 (if (looking-at "--+<[^>]+>") (replace-match ""))
8219 (if (looking-at " +") (replace-match ""))))
8220 (goto-char (point-max))
8221 (when what
8222 (insert
8223 (if (not (equal (char-before) ?\ )) " " "")
8224 (cond ((eq what 'scheduled) org-scheduled-string)
8225 ((eq what 'deadline) org-deadline-string)
8226 ((eq what 'closed) org-closed-string))
8227 " ")
8228 (setq ts (org-insert-time-stamp
8229 time
8230 (or org-time-was-given
8231 (and (eq what 'closed) org-log-done-with-time))
8232 (eq what 'closed)
8233 nil nil (list org-end-time-was-given)))
8234 (end-of-line 1))
8235 (goto-char (point-min))
8236 (widen)
8237 (if (looking-at "[ \t]+\r?\n")
8238 (replace-match ""))
8239 ts)))))
8241 (defvar org-log-note-marker (make-marker))
8242 (defvar org-log-note-purpose nil)
8243 (defvar org-log-note-state nil)
8244 (defvar org-log-note-how nil)
8245 (defvar org-log-note-window-configuration nil)
8246 (defvar org-log-note-return-to (make-marker))
8247 (defvar org-log-post-message nil
8248 "Message to be displayed after a log note has been stored.
8249 The auto-repeater uses this.")
8251 (defun org-add-note ()
8252 "Add a note to the current entry.
8253 This is done in the same way as adding a state change note."
8254 (interactive)
8255 (org-add-log-setup 'note nil t nil))
8257 (defun org-add-log-setup (&optional purpose state findpos how)
8258 "Set up the post command hook to take a note.
8259 If this is about to TODO state change, the new state is expected in STATE.
8260 When FINDPOS is non-nil, find the correct position for the note in
8261 the current entry. If not, assume that it can be inserted at point."
8262 (save-excursion
8263 (when findpos
8264 (org-back-to-heading t)
8265 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8266 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8267 "[^\r\n]*\\)?"))
8268 (goto-char (match-end 0))
8269 (unless org-log-states-order-reversed
8270 (and (= (char-after) ?\n) (forward-char 1))
8271 (org-skip-over-state-notes)
8272 (skip-chars-backward " \t\n\r")))
8273 (move-marker org-log-note-marker (point))
8274 (setq org-log-note-purpose purpose
8275 org-log-note-state state
8276 org-log-note-how how)
8277 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8279 (defun org-skip-over-state-notes ()
8280 "Skip past the list of State notes in an entry."
8281 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8282 (while (looking-at "[ \t]*- State")
8283 (condition-case nil
8284 (org-next-item)
8285 (error (org-end-of-item)))))
8287 (defun org-add-log-note (&optional purpose)
8288 "Pop up a window for taking a note, and add this note later at point."
8289 (remove-hook 'post-command-hook 'org-add-log-note)
8290 (setq org-log-note-window-configuration (current-window-configuration))
8291 (delete-other-windows)
8292 (move-marker org-log-note-return-to (point))
8293 (switch-to-buffer (marker-buffer org-log-note-marker))
8294 (goto-char org-log-note-marker)
8295 (org-switch-to-buffer-other-window "*Org Note*")
8296 (erase-buffer)
8297 (if (memq org-log-note-how '(time state))
8298 (org-store-log-note)
8299 (let ((org-inhibit-startup t)) (org-mode))
8300 (insert (format "# Insert note for %s.
8301 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8302 (cond
8303 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8304 ((eq org-log-note-purpose 'done) "closed todo item")
8305 ((eq org-log-note-purpose 'state)
8306 (format "state change to \"%s\"" org-log-note-state))
8307 ((eq org-log-note-purpose 'note)
8308 "this entry")
8309 (t (error "This should not happen")))))
8310 (org-set-local 'org-finish-function 'org-store-log-note)))
8312 (defvar org-note-abort nil) ; dynamically scoped
8313 (defun org-store-log-note ()
8314 "Finish taking a log note, and insert it to where it belongs."
8315 (let ((txt (buffer-string))
8316 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8317 lines ind)
8318 (kill-buffer (current-buffer))
8319 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8320 (setq txt (replace-match "" t t txt)))
8321 (if (string-match "\\s-+\\'" txt)
8322 (setq txt (replace-match "" t t txt)))
8323 (setq lines (org-split-string txt "\n"))
8324 (when (and note (string-match "\\S-" note))
8325 (setq note
8326 (org-replace-escapes
8327 note
8328 (list (cons "%u" (user-login-name))
8329 (cons "%U" user-full-name)
8330 (cons "%t" (format-time-string
8331 (org-time-stamp-format 'long 'inactive)
8332 (current-time)))
8333 (cons "%s" (if org-log-note-state
8334 (concat "\"" org-log-note-state "\"")
8335 "")))))
8336 (if lines (setq note (concat note " \\\\")))
8337 (push note lines))
8338 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8339 (when lines
8340 (save-excursion
8341 (set-buffer (marker-buffer org-log-note-marker))
8342 (save-excursion
8343 (goto-char org-log-note-marker)
8344 (move-marker org-log-note-marker nil)
8345 (end-of-line 1)
8346 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8347 (indent-relative nil)
8348 (insert "- " (pop lines))
8349 (org-indent-line-function)
8350 (beginning-of-line 1)
8351 (looking-at "[ \t]*")
8352 (setq ind (concat (match-string 0) " "))
8353 (end-of-line 1)
8354 (while lines (insert "\n" ind (pop lines)))))))
8355 (set-window-configuration org-log-note-window-configuration)
8356 (with-current-buffer (marker-buffer org-log-note-return-to)
8357 (goto-char org-log-note-return-to))
8358 (move-marker org-log-note-return-to nil)
8359 (and org-log-post-message (message "%s" org-log-post-message)))
8361 (defun org-sparse-tree (&optional arg)
8362 "Create a sparse tree, prompt for the details.
8363 This command can create sparse trees. You first need to select the type
8364 of match used to create the tree:
8366 t Show entries with a specific TODO keyword.
8367 T Show entries selected by a tags match.
8368 p Enter a property name and its value (both with completion on existing
8369 names/values) and show entries with that property.
8370 r Show entries matching a regular expression
8371 d Show deadlines due within `org-deadline-warning-days'."
8372 (interactive "P")
8373 (let (ans kwd value)
8374 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8375 (setq ans (read-char-exclusive))
8376 (cond
8377 ((equal ans ?d)
8378 (call-interactively 'org-check-deadlines))
8379 ((equal ans ?b)
8380 (call-interactively 'org-check-before-date))
8381 ((equal ans ?t)
8382 (org-show-todo-tree '(4)))
8383 ((equal ans ?T)
8384 (call-interactively 'org-tags-sparse-tree))
8385 ((member ans '(?p ?P))
8386 (setq kwd (completing-read "Property: "
8387 (mapcar 'list (org-buffer-property-keys))))
8388 (setq value (completing-read "Value: "
8389 (mapcar 'list (org-property-values kwd))))
8390 (unless (string-match "\\`{.*}\\'" value)
8391 (setq value (concat "\"" value "\"")))
8392 (org-tags-sparse-tree arg (concat kwd "=" value)))
8393 ((member ans '(?r ?R ?/))
8394 (call-interactively 'org-occur))
8395 (t (error "No such sparse tree command \"%c\"" ans)))))
8397 (defvar org-occur-highlights nil
8398 "List of overlays used for occur matches.")
8399 (make-variable-buffer-local 'org-occur-highlights)
8400 (defvar org-occur-parameters nil
8401 "Parameters of the active org-occur calls.
8402 This is a list, each call to org-occur pushes as cons cell,
8403 containing the regular expression and the callback, onto the list.
8404 The list can contain several entries if `org-occur' has been called
8405 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8406 will only contain one set of parameters. When the highlights are
8407 removed (for example with `C-c C-c', or with the next edit (depending
8408 on `org-remove-highlights-with-change'), this variable is emptied
8409 as well.")
8410 (make-variable-buffer-local 'org-occur-parameters)
8412 (defun org-occur (regexp &optional keep-previous callback)
8413 "Make a compact tree which shows all matches of REGEXP.
8414 The tree will show the lines where the regexp matches, and all higher
8415 headlines above the match. It will also show the heading after the match,
8416 to make sure editing the matching entry is easy.
8417 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8418 call to `org-occur' will be kept, to allow stacking of calls to this
8419 command.
8420 If CALLBACK is non-nil, it is a function which is called to confirm
8421 that the match should indeed be shown."
8422 (interactive "sRegexp: \nP")
8423 (unless keep-previous
8424 (org-remove-occur-highlights nil nil t))
8425 (push (cons regexp callback) org-occur-parameters)
8426 (let ((cnt 0))
8427 (save-excursion
8428 (goto-char (point-min))
8429 (if (or (not keep-previous) ; do not want to keep
8430 (not org-occur-highlights)) ; no previous matches
8431 ;; hide everything
8432 (org-overview))
8433 (while (re-search-forward regexp nil t)
8434 (when (or (not callback)
8435 (save-match-data (funcall callback)))
8436 (setq cnt (1+ cnt))
8437 (when org-highlight-sparse-tree-matches
8438 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8439 (org-show-context 'occur-tree))))
8440 (when org-remove-highlights-with-change
8441 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8442 nil 'local))
8443 (unless org-sparse-tree-open-archived-trees
8444 (org-hide-archived-subtrees (point-min) (point-max)))
8445 (run-hooks 'org-occur-hook)
8446 (if (interactive-p)
8447 (message "%d match(es) for regexp %s" cnt regexp))
8448 cnt))
8450 (defun org-show-context (&optional key)
8451 "Make sure point and context and visible.
8452 How much context is shown depends upon the variables
8453 `org-show-hierarchy-above', `org-show-following-heading'. and
8454 `org-show-siblings'."
8455 (let ((heading-p (org-on-heading-p t))
8456 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8457 (following-p (org-get-alist-option org-show-following-heading key))
8458 (entry-p (org-get-alist-option org-show-entry-below key))
8459 (siblings-p (org-get-alist-option org-show-siblings key)))
8460 (catch 'exit
8461 ;; Show heading or entry text
8462 (if (and heading-p (not entry-p))
8463 (org-flag-heading nil) ; only show the heading
8464 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8465 (org-show-hidden-entry))) ; show entire entry
8466 (when following-p
8467 ;; Show next sibling, or heading below text
8468 (save-excursion
8469 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8470 (org-flag-heading nil))))
8471 (when siblings-p (org-show-siblings))
8472 (when hierarchy-p
8473 ;; show all higher headings, possibly with siblings
8474 (save-excursion
8475 (while (and (condition-case nil
8476 (progn (org-up-heading-all 1) t)
8477 (error nil))
8478 (not (bobp)))
8479 (org-flag-heading nil)
8480 (when siblings-p (org-show-siblings))))))))
8482 (defun org-reveal (&optional siblings)
8483 "Show current entry, hierarchy above it, and the following headline.
8484 This can be used to show a consistent set of context around locations
8485 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8486 not t for the search context.
8488 With optional argument SIBLINGS, on each level of the hierarchy all
8489 siblings are shown. This repairs the tree structure to what it would
8490 look like when opened with hierarchical calls to `org-cycle'."
8491 (interactive "P")
8492 (let ((org-show-hierarchy-above t)
8493 (org-show-following-heading t)
8494 (org-show-siblings (if siblings t org-show-siblings)))
8495 (org-show-context nil)))
8497 (defun org-highlight-new-match (beg end)
8498 "Highlight from BEG to END and mark the highlight is an occur headline."
8499 (let ((ov (org-make-overlay beg end)))
8500 (org-overlay-put ov 'face 'secondary-selection)
8501 (push ov org-occur-highlights)))
8503 (defun org-remove-occur-highlights (&optional beg end noremove)
8504 "Remove the occur highlights from the buffer.
8505 BEG and END are ignored. If NOREMOVE is nil, remove this function
8506 from the `before-change-functions' in the current buffer."
8507 (interactive)
8508 (unless org-inhibit-highlight-removal
8509 (mapc 'org-delete-overlay org-occur-highlights)
8510 (setq org-occur-highlights nil)
8511 (setq org-occur-parameters nil)
8512 (unless noremove
8513 (remove-hook 'before-change-functions
8514 'org-remove-occur-highlights 'local))))
8516 ;;;; Priorities
8518 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8519 "Regular expression matching the priority indicator.")
8521 (defvar org-remove-priority-next-time nil)
8523 (defun org-priority-up ()
8524 "Increase the priority of the current item."
8525 (interactive)
8526 (org-priority 'up))
8528 (defun org-priority-down ()
8529 "Decrease the priority of the current item."
8530 (interactive)
8531 (org-priority 'down))
8533 (defun org-priority (&optional action)
8534 "Change the priority of an item by ARG.
8535 ACTION can be `set', `up', `down', or a character."
8536 (interactive)
8537 (setq action (or action 'set))
8538 (let (current new news have remove)
8539 (save-excursion
8540 (org-back-to-heading)
8541 (if (looking-at org-priority-regexp)
8542 (setq current (string-to-char (match-string 2))
8543 have t)
8544 (setq current org-default-priority))
8545 (cond
8546 ((or (eq action 'set)
8547 (if (featurep 'xemacs) (characterp action) (integerp action)))
8548 (if (not (eq action 'set))
8549 (setq new action)
8550 (message "Priority %c-%c, SPC to remove: "
8551 org-highest-priority org-lowest-priority)
8552 (setq new (read-char-exclusive)))
8553 (if (and (= (upcase org-highest-priority) org-highest-priority)
8554 (= (upcase org-lowest-priority) org-lowest-priority))
8555 (setq new (upcase new)))
8556 (cond ((equal new ?\ ) (setq remove t))
8557 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8558 (error "Priority must be between `%c' and `%c'"
8559 org-highest-priority org-lowest-priority))))
8560 ((eq action 'up)
8561 (if (and (not have) (eq last-command this-command))
8562 (setq new org-lowest-priority)
8563 (setq new (if (and org-priority-start-cycle-with-default (not have))
8564 org-default-priority (1- current)))))
8565 ((eq action 'down)
8566 (if (and (not have) (eq last-command this-command))
8567 (setq new org-highest-priority)
8568 (setq new (if (and org-priority-start-cycle-with-default (not have))
8569 org-default-priority (1+ current)))))
8570 (t (error "Invalid action")))
8571 (if (or (< (upcase new) org-highest-priority)
8572 (> (upcase new) org-lowest-priority))
8573 (setq remove t))
8574 (setq news (format "%c" new))
8575 (if have
8576 (if remove
8577 (replace-match "" t t nil 1)
8578 (replace-match news t t nil 2))
8579 (if remove
8580 (error "No priority cookie found in line")
8581 (looking-at org-todo-line-regexp)
8582 (if (match-end 2)
8583 (progn
8584 (goto-char (match-end 2))
8585 (insert " [#" news "]"))
8586 (goto-char (match-beginning 3))
8587 (insert "[#" news "] ")))))
8588 (org-preserve-lc (org-set-tags nil 'align))
8589 (if remove
8590 (message "Priority removed")
8591 (message "Priority of current item set to %s" news))))
8594 (defun org-get-priority (s)
8595 "Find priority cookie and return priority."
8596 (save-match-data
8597 (if (not (string-match org-priority-regexp s))
8598 (* 1000 (- org-lowest-priority org-default-priority))
8599 (* 1000 (- org-lowest-priority
8600 (string-to-char (match-string 2 s)))))))
8602 ;;;; Tags
8604 (defun org-scan-tags (action matcher &optional todo-only)
8605 "Scan headline tags with inheritance and produce output ACTION.
8606 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8607 evaluated, testing if a given set of tags qualifies a headline for
8608 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8609 are included in the output."
8610 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8611 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8612 (org-re
8613 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8614 (props (list 'face nil
8615 'done-face 'org-done
8616 'undone-face nil
8617 'mouse-face 'highlight
8618 'org-not-done-regexp org-not-done-regexp
8619 'org-todo-regexp org-todo-regexp
8620 'keymap org-agenda-keymap
8621 'help-echo
8622 (format "mouse-2 or RET jump to org file %s"
8623 (abbreviate-file-name
8624 (or (buffer-file-name (buffer-base-buffer))
8625 (buffer-name (buffer-base-buffer)))))))
8626 (case-fold-search nil)
8627 lspos
8628 tags tags-list tags-alist (llast 0) rtn level category i txt
8629 todo marker entry priority)
8630 (save-excursion
8631 (goto-char (point-min))
8632 (when (eq action 'sparse-tree)
8633 (org-overview)
8634 (org-remove-occur-highlights))
8635 (while (re-search-forward re nil t)
8636 (catch :skip
8637 (setq todo (if (match-end 1) (match-string 2))
8638 tags (if (match-end 4) (match-string 4)))
8639 (goto-char (setq lspos (1+ (match-beginning 0))))
8640 (setq level (org-reduced-level (funcall outline-level))
8641 category (org-get-category))
8642 (setq i llast llast level)
8643 ;; remove tag lists from same and sublevels
8644 (while (>= i level)
8645 (when (setq entry (assoc i tags-alist))
8646 (setq tags-alist (delete entry tags-alist)))
8647 (setq i (1- i)))
8648 ;; add the next tags
8649 (when tags
8650 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8651 tags-alist
8652 (cons (cons level tags) tags-alist)))
8653 ;; compile tags for current headline
8654 (setq tags-list
8655 (if org-use-tag-inheritance
8656 (apply 'append (mapcar 'cdr tags-alist))
8657 tags))
8658 (when (and tags org-use-tag-inheritance
8659 (not (eq t org-use-tag-inheritance)))
8660 ;; selective inheritance, remove uninherited ones
8661 (setcdr (car tags-alist)
8662 (org-remove-uniherited-tags (cdar tags-alist))))
8663 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8664 (eval matcher)
8665 (or (not org-agenda-skip-archived-trees)
8666 (not (member org-archive-tag tags-list))))
8667 (and (eq action 'agenda) (org-agenda-skip))
8668 ;; list this headline
8670 (if (eq action 'sparse-tree)
8671 (progn
8672 (and org-highlight-sparse-tree-matches
8673 (org-get-heading) (match-end 0)
8674 (org-highlight-new-match
8675 (match-beginning 0) (match-beginning 1)))
8676 (org-show-context 'tags-tree))
8677 (setq txt (org-format-agenda-item
8679 (concat
8680 (if org-tags-match-list-sublevels
8681 (make-string (1- level) ?.) "")
8682 (org-get-heading))
8683 category tags-list)
8684 priority (org-get-priority txt))
8685 (goto-char lspos)
8686 (setq marker (org-agenda-new-marker))
8687 (org-add-props txt props
8688 'org-marker marker 'org-hd-marker marker 'org-category category
8689 'priority priority 'type "tagsmatch")
8690 (push txt rtn))
8691 ;; if we are to skip sublevels, jump to end of subtree
8692 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8693 (when (and (eq action 'sparse-tree)
8694 (not org-sparse-tree-open-archived-trees))
8695 (org-hide-archived-subtrees (point-min) (point-max)))
8696 (nreverse rtn)))
8698 (defun org-remove-uniherited-tags (tags)
8699 "Remove all tags that are not inherited from the list TAGS."
8700 (cond
8701 ((eq org-use-tag-inheritance t) tags)
8702 ((not org-use-tag-inheritance) nil)
8703 ((stringp org-use-tag-inheritance)
8704 (delq nil (mapcar
8705 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8706 tags)))
8707 ((listp org-use-tag-inheritance)
8708 (org-delete-all org-use-tag-inheritance tags))))
8710 (defvar todo-only) ;; dynamically scoped
8712 (defun org-tags-sparse-tree (&optional todo-only match)
8713 "Create a sparse tree according to tags string MATCH.
8714 MATCH can contain positive and negative selection of tags, like
8715 \"+WORK+URGENT-WITHBOSS\".
8716 If optional argument TODO_ONLY is non-nil, only select lines that are
8717 also TODO lines."
8718 (interactive "P")
8719 (org-prepare-agenda-buffers (list (current-buffer)))
8720 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8722 (defvar org-cached-props nil)
8723 (defun org-cached-entry-get (pom property)
8724 (if (or (eq t org-use-property-inheritance)
8725 (and (stringp org-use-property-inheritance)
8726 (string-match org-use-property-inheritance property))
8727 (and (listp org-use-property-inheritance)
8728 (member property org-use-property-inheritance)))
8729 ;; Caching is not possible, check it directly
8730 (org-entry-get pom property 'inherit)
8731 ;; Get all properties, so that we can do complicated checks easily
8732 (cdr (assoc property (or org-cached-props
8733 (setq org-cached-props
8734 (org-entry-properties pom)))))))
8736 (defun org-global-tags-completion-table (&optional files)
8737 "Return the list of all tags in all agenda buffer/files."
8738 (save-excursion
8739 (org-uniquify
8740 (delq nil
8741 (apply 'append
8742 (mapcar
8743 (lambda (file)
8744 (set-buffer (find-file-noselect file))
8745 (append (org-get-buffer-tags)
8746 (mapcar (lambda (x) (if (stringp (car-safe x))
8747 (list (car-safe x)) nil))
8748 org-tag-alist)))
8749 (if (and files (car files))
8750 files
8751 (org-agenda-files))))))))
8753 (defun org-make-tags-matcher (match)
8754 "Create the TAGS//TODO matcher form for the selection string MATCH."
8755 ;; todo-only is scoped dynamically into this function, and the function
8756 ;; may change it it the matcher asksk for it.
8757 (unless match
8758 ;; Get a new match request, with completion
8759 (let ((org-last-tags-completion-table
8760 (org-global-tags-completion-table)))
8761 (setq match (completing-read
8762 "Match: " 'org-tags-completion-function nil nil nil
8763 'org-tags-history))))
8765 ;; Parse the string and create a lisp form
8766 (let ((match0 match)
8767 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8768 minus tag mm
8769 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8770 orterms term orlist re-p str-p level-p level-op
8771 prop-p pn pv po cat-p gv)
8772 (if (string-match "/+" match)
8773 ;; match contains also a todo-matching request
8774 (progn
8775 (setq tagsmatch (substring match 0 (match-beginning 0))
8776 todomatch (substring match (match-end 0)))
8777 (if (string-match "^!" todomatch)
8778 (setq todo-only t todomatch (substring todomatch 1)))
8779 (if (string-match "^\\s-*$" todomatch)
8780 (setq todomatch nil)))
8781 ;; only matching tags
8782 (setq tagsmatch match todomatch nil))
8784 ;; Make the tags matcher
8785 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8786 (setq tagsmatcher t)
8787 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8788 (while (setq term (pop orterms))
8789 (while (and (equal (substring term -1) "\\") orterms)
8790 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8791 (while (string-match re term)
8792 (setq minus (and (match-end 1)
8793 (equal (match-string 1 term) "-"))
8794 tag (match-string 2 term)
8795 re-p (equal (string-to-char tag) ?{)
8796 level-p (match-end 4)
8797 prop-p (match-end 5)
8798 mm (cond
8799 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8800 (level-p
8801 (setq level-op (org-op-to-function (match-string 3 term)))
8802 `(,level-op level ,(string-to-number
8803 (match-string 4 term))))
8804 (prop-p
8805 (setq pn (match-string 5 term)
8806 po (match-string 6 term)
8807 pv (match-string 7 term)
8808 cat-p (equal pn "CATEGORY")
8809 re-p (equal (string-to-char pv) ?{)
8810 str-p (equal (string-to-char pv) ?\")
8811 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8812 (setq po (org-op-to-function po str-p))
8813 (if (equal pn "CATEGORY")
8814 (setq gv '(get-text-property (point) 'org-category))
8815 (setq gv `(org-cached-entry-get nil ,pn)))
8816 (if re-p
8817 `(string-match ,pv (or ,gv ""))
8818 (if str-p
8819 `(,po (or ,gv "") ,pv)
8820 `(,po (string-to-number (or ,gv ""))
8821 ,(string-to-number pv) ))))
8822 (t `(member ,(downcase tag) tags-list)))
8823 mm (if minus (list 'not mm) mm)
8824 term (substring term (match-end 0)))
8825 (push mm tagsmatcher))
8826 (push (if (> (length tagsmatcher) 1)
8827 (cons 'and tagsmatcher)
8828 (car tagsmatcher))
8829 orlist)
8830 (setq tagsmatcher nil))
8831 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8832 (setq tagsmatcher
8833 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8834 ;; Make the todo matcher
8835 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8836 (setq todomatcher t)
8837 (setq orterms (org-split-string todomatch "|") orlist nil)
8838 (while (setq term (pop orterms))
8839 (while (string-match re term)
8840 (setq minus (and (match-end 1)
8841 (equal (match-string 1 term) "-"))
8842 kwd (match-string 2 term)
8843 re-p (equal (string-to-char kwd) ?{)
8844 term (substring term (match-end 0))
8845 mm (if re-p
8846 `(string-match ,(substring kwd 1 -1) todo)
8847 (list 'equal 'todo kwd))
8848 mm (if minus (list 'not mm) mm))
8849 (push mm todomatcher))
8850 (push (if (> (length todomatcher) 1)
8851 (cons 'and todomatcher)
8852 (car todomatcher))
8853 orlist)
8854 (setq todomatcher nil))
8855 (setq todomatcher (if (> (length orlist) 1)
8856 (cons 'or orlist) (car orlist))))
8858 ;; Return the string and lisp forms of the matcher
8859 (setq matcher (if todomatcher
8860 (list 'and tagsmatcher todomatcher)
8861 tagsmatcher))
8862 (cons match0 matcher)))
8864 (defun org-op-to-function (op &optional stringp)
8865 (setq op
8866 (cond
8867 ((equal op "<" ) '(< string< ))
8868 ((equal op ">" ) '(> string> ))
8869 ((member op '("<=" "=<")) '(<= org-string<= ))
8870 ((member op '(">=" "=>")) '(>= org-string>= ))
8871 ((member op '("=" "==")) '(= string= ))
8872 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8873 (nth (if stringp 1 0) op))
8875 (defun org<> (a b) (not (= a b)))
8876 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8877 (defun org-string>= (a b) (or (string= a b) (string> a b)))
8878 (defun org-string<> (a b) (not (string= a b)))
8880 (defun org-match-any-p (re list)
8881 "Does re match any element of list?"
8882 (setq list (mapcar (lambda (x) (string-match re x)) list))
8883 (delq nil list))
8885 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8886 (defvar org-tags-overlay (org-make-overlay 1 1))
8887 (org-detach-overlay org-tags-overlay)
8889 (defun org-get-tags-at (&optional pos)
8890 "Get a list of all headline tags applicable at POS.
8891 POS defaults to point. If tags are inherited, the list contains
8892 the targets in the same sequence as the headlines appear, i.e.
8893 sthe tags of the current headline come last."
8894 (interactive)
8895 (let (tags ltags lastpos parent)
8896 (save-excursion
8897 (save-restriction
8898 (widen)
8899 (goto-char (or pos (point)))
8900 (save-match-data
8901 (condition-case nil
8902 (progn
8903 (org-back-to-heading t)
8904 (while (not (equal lastpos (point)))
8905 (setq lastpos (point))
8906 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8907 (setq ltags (org-split-string
8908 (org-match-string-no-properties 1) ":"))
8909 (setq tags (append (org-remove-uniherited-tags ltags)
8910 tags)))
8911 (or org-use-tag-inheritance (error ""))
8912 (org-up-heading-all 1)
8913 (setq parent t)))
8914 (error nil))))
8915 tags)))
8917 (defun org-toggle-tag (tag &optional onoff)
8918 "Toggle the tag TAG for the current line.
8919 If ONOFF is `on' or `off', don't toggle but set to this state."
8920 (unless (org-on-heading-p t) (error "Not on headling"))
8921 (let (res current)
8922 (save-excursion
8923 (beginning-of-line)
8924 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8925 (point-at-eol) t)
8926 (progn
8927 (setq current (match-string 1))
8928 (replace-match ""))
8929 (setq current ""))
8930 (setq current (nreverse (org-split-string current ":")))
8931 (cond
8932 ((eq onoff 'on)
8933 (setq res t)
8934 (or (member tag current) (push tag current)))
8935 ((eq onoff 'off)
8936 (or (not (member tag current)) (setq current (delete tag current))))
8937 (t (if (member tag current)
8938 (setq current (delete tag current))
8939 (setq res t)
8940 (push tag current))))
8941 (end-of-line 1)
8942 (if current
8943 (progn
8944 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8945 (org-set-tags nil t))
8946 (delete-horizontal-space))
8947 (run-hooks 'org-after-tags-change-hook))
8948 res))
8950 (defun org-align-tags-here (to-col)
8951 ;; Assumes that this is a headline
8952 (let ((pos (point)) (col (current-column)) tags)
8953 (beginning-of-line 1)
8954 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8955 (< pos (match-beginning 2)))
8956 (progn
8957 (setq tags (match-string 2))
8958 (goto-char (match-beginning 1))
8959 (insert " ")
8960 (delete-region (point) (1+ (match-end 0)))
8961 (backward-char 1)
8962 (move-to-column
8963 (max (1+ (current-column))
8964 (1+ col)
8965 (if (> to-col 0)
8966 to-col
8967 (- (abs to-col) (length tags))))
8969 (insert tags)
8970 (move-to-column (min (current-column) col) t))
8971 (goto-char pos))))
8973 (defun org-set-tags (&optional arg just-align)
8974 "Set the tags for the current headline.
8975 With prefix ARG, realign all tags in headings in the current buffer."
8976 (interactive "P")
8977 (let* ((re (concat "^" outline-regexp))
8978 (current (org-get-tags-string))
8979 (col (current-column))
8980 (org-setting-tags t)
8981 table current-tags inherited-tags ; computed below when needed
8982 tags p0 c0 c1 rpl)
8983 (if arg
8984 (save-excursion
8985 (goto-char (point-min))
8986 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8987 (while (re-search-forward re nil t)
8988 (org-set-tags nil t)
8989 (end-of-line 1)))
8990 (message "All tags realigned to column %d" org-tags-column))
8991 (if just-align
8992 (setq tags current)
8993 ;; Get a new set of tags from the user
8994 (save-excursion
8995 (setq table (or org-tag-alist (org-get-buffer-tags))
8996 org-last-tags-completion-table table
8997 current-tags (org-split-string current ":")
8998 inherited-tags (nreverse
8999 (nthcdr (length current-tags)
9000 (nreverse (org-get-tags-at))))
9001 tags
9002 (if (or (eq t org-use-fast-tag-selection)
9003 (and org-use-fast-tag-selection
9004 (delq nil (mapcar 'cdr table))))
9005 (org-fast-tag-selection
9006 current-tags inherited-tags table
9007 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9008 (let ((org-add-colon-after-tag-completion t))
9009 (org-trim
9010 (org-without-partial-completion
9011 (completing-read "Tags: " 'org-tags-completion-function
9012 nil nil current 'org-tags-history)))))))
9013 (while (string-match "[-+&]+" tags)
9014 ;; No boolean logic, just a list
9015 (setq tags (replace-match ":" t t tags))))
9017 (if (string-match "\\`[\t ]*\\'" tags)
9018 (setq tags "")
9019 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9020 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9022 ;; Insert new tags at the correct column
9023 (beginning-of-line 1)
9024 (cond
9025 ((and (equal current "") (equal tags "")))
9026 ((re-search-forward
9027 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9028 (point-at-eol) t)
9029 (if (equal tags "")
9030 (setq rpl "")
9031 (goto-char (match-beginning 0))
9032 (setq c0 (current-column) p0 (point)
9033 c1 (max (1+ c0) (if (> org-tags-column 0)
9034 org-tags-column
9035 (- (- org-tags-column) (length tags))))
9036 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9037 (replace-match rpl t t)
9038 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9039 tags)
9040 (t (error "Tags alignment failed")))
9041 (move-to-column col)
9042 (unless just-align
9043 (run-hooks 'org-after-tags-change-hook)))))
9045 (defun org-change-tag-in-region (beg end tag off)
9046 "Add or remove TAG for each entry in the region.
9047 This works in the agenda, and also in an org-mode buffer."
9048 (interactive
9049 (list (region-beginning) (region-end)
9050 (let ((org-last-tags-completion-table
9051 (if (org-mode-p)
9052 (org-get-buffer-tags)
9053 (org-global-tags-completion-table))))
9054 (completing-read
9055 "Tag: " 'org-tags-completion-function nil nil nil
9056 'org-tags-history))
9057 (progn
9058 (message "[s]et or [r]emove? ")
9059 (equal (read-char-exclusive) ?r))))
9060 (if (fboundp 'deactivate-mark) (deactivate-mark))
9061 (let ((agendap (equal major-mode 'org-agenda-mode))
9062 l1 l2 m buf pos newhead (cnt 0))
9063 (goto-char end)
9064 (setq l2 (1- (org-current-line)))
9065 (goto-char beg)
9066 (setq l1 (org-current-line))
9067 (loop for l from l1 to l2 do
9068 (goto-line l)
9069 (setq m (get-text-property (point) 'org-hd-marker))
9070 (when (or (and (org-mode-p) (org-on-heading-p))
9071 (and agendap m))
9072 (setq buf (if agendap (marker-buffer m) (current-buffer))
9073 pos (if agendap m (point)))
9074 (with-current-buffer buf
9075 (save-excursion
9076 (save-restriction
9077 (goto-char pos)
9078 (setq cnt (1+ cnt))
9079 (org-toggle-tag tag (if off 'off 'on))
9080 (setq newhead (org-get-heading)))))
9081 (and agendap (org-agenda-change-all-lines newhead m))))
9082 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9084 (defun org-tags-completion-function (string predicate &optional flag)
9085 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9086 (confirm (lambda (x) (stringp (car x)))))
9087 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9088 (setq s1 (match-string 1 string)
9089 s2 (match-string 2 string))
9090 (setq s1 "" s2 string))
9091 (cond
9092 ((eq flag nil)
9093 ;; try completion
9094 (setq rtn (try-completion s2 ctable confirm))
9095 (if (stringp rtn)
9096 (setq rtn
9097 (concat s1 s2 (substring rtn (length s2))
9098 (if (and org-add-colon-after-tag-completion
9099 (assoc rtn ctable))
9100 ":" ""))))
9101 rtn)
9102 ((eq flag t)
9103 ;; all-completions
9104 (all-completions s2 ctable confirm)
9106 ((eq flag 'lambda)
9107 ;; exact match?
9108 (assoc s2 ctable)))
9111 (defun org-fast-tag-insert (kwd tags face &optional end)
9112 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9113 (insert (format "%-12s" (concat kwd ":"))
9114 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9115 (or end "")))
9117 (defun org-fast-tag-show-exit (flag)
9118 (save-excursion
9119 (goto-line 3)
9120 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9121 (replace-match ""))
9122 (when flag
9123 (end-of-line 1)
9124 (move-to-column (- (window-width) 19) t)
9125 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9127 (defun org-set-current-tags-overlay (current prefix)
9128 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9129 (if (featurep 'xemacs)
9130 (org-overlay-display org-tags-overlay (concat prefix s)
9131 'secondary-selection)
9132 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9133 (org-overlay-display org-tags-overlay (concat prefix s)))))
9135 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9136 "Fast tag selection with single keys.
9137 CURRENT is the current list of tags in the headline, INHERITED is the
9138 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9139 possibly with grouping information. TODO-TABLE is a similar table with
9140 TODO keywords, should these have keys assigned to them.
9141 If the keys are nil, a-z are automatically assigned.
9142 Returns the new tags string, or nil to not change the current settings."
9143 (let* ((fulltable (append table todo-table))
9144 (maxlen (apply 'max (mapcar
9145 (lambda (x)
9146 (if (stringp (car x)) (string-width (car x)) 0))
9147 fulltable)))
9148 (buf (current-buffer))
9149 (expert (eq org-fast-tag-selection-single-key 'expert))
9150 (buffer-tags nil)
9151 (fwidth (+ maxlen 3 1 3))
9152 (ncol (/ (- (window-width) 4) fwidth))
9153 (i-face 'org-done)
9154 (c-face 'org-todo)
9155 tg cnt e c char c1 c2 ntable tbl rtn
9156 ov-start ov-end ov-prefix
9157 (exit-after-next org-fast-tag-selection-single-key)
9158 (done-keywords org-done-keywords)
9159 groups ingroup)
9160 (save-excursion
9161 (beginning-of-line 1)
9162 (if (looking-at
9163 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9164 (setq ov-start (match-beginning 1)
9165 ov-end (match-end 1)
9166 ov-prefix "")
9167 (setq ov-start (1- (point-at-eol))
9168 ov-end (1+ ov-start))
9169 (skip-chars-forward "^\n\r")
9170 (setq ov-prefix
9171 (concat
9172 (buffer-substring (1- (point)) (point))
9173 (if (> (current-column) org-tags-column)
9175 (make-string (- org-tags-column (current-column)) ?\ ))))))
9176 (org-move-overlay org-tags-overlay ov-start ov-end)
9177 (save-window-excursion
9178 (if expert
9179 (set-buffer (get-buffer-create " *Org tags*"))
9180 (delete-other-windows)
9181 (split-window-vertically)
9182 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9183 (erase-buffer)
9184 (org-set-local 'org-done-keywords done-keywords)
9185 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9186 (org-fast-tag-insert "Current" current c-face "\n\n")
9187 (org-fast-tag-show-exit exit-after-next)
9188 (org-set-current-tags-overlay current ov-prefix)
9189 (setq tbl fulltable char ?a cnt 0)
9190 (while (setq e (pop tbl))
9191 (cond
9192 ((equal e '(:startgroup))
9193 (push '() groups) (setq ingroup t)
9194 (when (not (= cnt 0))
9195 (setq cnt 0)
9196 (insert "\n"))
9197 (insert "{ "))
9198 ((equal e '(:endgroup))
9199 (setq ingroup nil cnt 0)
9200 (insert "}\n"))
9202 (setq tg (car e) c2 nil)
9203 (if (cdr e)
9204 (setq c (cdr e))
9205 ;; automatically assign a character.
9206 (setq c1 (string-to-char
9207 (downcase (substring
9208 tg (if (= (string-to-char tg) ?@) 1 0)))))
9209 (if (or (rassoc c1 ntable) (rassoc c1 table))
9210 (while (or (rassoc char ntable) (rassoc char table))
9211 (setq char (1+ char)))
9212 (setq c2 c1))
9213 (setq c (or c2 char)))
9214 (if ingroup (push tg (car groups)))
9215 (setq tg (org-add-props tg nil 'face
9216 (cond
9217 ((not (assoc tg table))
9218 (org-get-todo-face tg))
9219 ((member tg current) c-face)
9220 ((member tg inherited) i-face)
9221 (t nil))))
9222 (if (and (= cnt 0) (not ingroup)) (insert " "))
9223 (insert "[" c "] " tg (make-string
9224 (- fwidth 4 (length tg)) ?\ ))
9225 (push (cons tg c) ntable)
9226 (when (= (setq cnt (1+ cnt)) ncol)
9227 (insert "\n")
9228 (if ingroup (insert " "))
9229 (setq cnt 0)))))
9230 (setq ntable (nreverse ntable))
9231 (insert "\n")
9232 (goto-char (point-min))
9233 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9234 (fit-window-to-buffer))
9235 (setq rtn
9236 (catch 'exit
9237 (while t
9238 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9239 (if groups " [!] no groups" " [!]groups")
9240 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9241 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9242 (cond
9243 ((= c ?\r) (throw 'exit t))
9244 ((= c ?!)
9245 (setq groups (not groups))
9246 (goto-char (point-min))
9247 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9248 ((= c ?\C-c)
9249 (if (not expert)
9250 (org-fast-tag-show-exit
9251 (setq exit-after-next (not exit-after-next)))
9252 (setq expert nil)
9253 (delete-other-windows)
9254 (split-window-vertically)
9255 (org-switch-to-buffer-other-window " *Org tags*")
9256 (and (fboundp 'fit-window-to-buffer)
9257 (fit-window-to-buffer))))
9258 ((or (= c ?\C-g)
9259 (and (= c ?q) (not (rassoc c ntable))))
9260 (org-detach-overlay org-tags-overlay)
9261 (setq quit-flag t))
9262 ((= c ?\ )
9263 (setq current nil)
9264 (if exit-after-next (setq exit-after-next 'now)))
9265 ((= c ?\t)
9266 (condition-case nil
9267 (setq tg (completing-read
9268 "Tag: "
9269 (or buffer-tags
9270 (with-current-buffer buf
9271 (org-get-buffer-tags)))))
9272 (quit (setq tg "")))
9273 (when (string-match "\\S-" tg)
9274 (add-to-list 'buffer-tags (list tg))
9275 (if (member tg current)
9276 (setq current (delete tg current))
9277 (push tg current)))
9278 (if exit-after-next (setq exit-after-next 'now)))
9279 ((setq e (rassoc c todo-table) tg (car e))
9280 (with-current-buffer buf
9281 (save-excursion (org-todo tg)))
9282 (if exit-after-next (setq exit-after-next 'now)))
9283 ((setq e (rassoc c ntable) tg (car e))
9284 (if (member tg current)
9285 (setq current (delete tg current))
9286 (loop for g in groups do
9287 (if (member tg g)
9288 (mapc (lambda (x)
9289 (setq current (delete x current)))
9290 g)))
9291 (push tg current))
9292 (if exit-after-next (setq exit-after-next 'now))))
9294 ;; Create a sorted list
9295 (setq current
9296 (sort current
9297 (lambda (a b)
9298 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9299 (if (eq exit-after-next 'now) (throw 'exit t))
9300 (goto-char (point-min))
9301 (beginning-of-line 2)
9302 (delete-region (point) (point-at-eol))
9303 (org-fast-tag-insert "Current" current c-face)
9304 (org-set-current-tags-overlay current ov-prefix)
9305 (while (re-search-forward
9306 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9307 (setq tg (match-string 1))
9308 (add-text-properties
9309 (match-beginning 1) (match-end 1)
9310 (list 'face
9311 (cond
9312 ((member tg current) c-face)
9313 ((member tg inherited) i-face)
9314 (t (get-text-property (match-beginning 1) 'face))))))
9315 (goto-char (point-min)))))
9316 (org-detach-overlay org-tags-overlay)
9317 (if rtn
9318 (mapconcat 'identity current ":")
9319 nil))))
9321 (defun org-get-tags-string ()
9322 "Get the TAGS string in the current headline."
9323 (unless (org-on-heading-p t)
9324 (error "Not on a heading"))
9325 (save-excursion
9326 (beginning-of-line 1)
9327 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9328 (org-match-string-no-properties 1)
9329 "")))
9331 (defun org-get-tags ()
9332 "Get the list of tags specified in the current headline."
9333 (org-split-string (org-get-tags-string) ":"))
9335 (defun org-get-buffer-tags ()
9336 "Get a table of all tags used in the buffer, for completion."
9337 (let (tags)
9338 (save-excursion
9339 (goto-char (point-min))
9340 (while (re-search-forward
9341 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9342 (when (equal (char-after (point-at-bol 0)) ?*)
9343 (mapc (lambda (x) (add-to-list 'tags x))
9344 (org-split-string (org-match-string-no-properties 1) ":")))))
9345 (mapcar 'list tags)))
9348 ;;;; Properties
9350 ;;; Setting and retrieving properties
9352 (defconst org-special-properties
9353 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9354 "TIMESTAMP" "TIMESTAMP_IA")
9355 "The special properties valid in Org-mode.
9357 These are properties that are not defined in the property drawer,
9358 but in some other way.")
9360 (defconst org-default-properties
9361 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9362 "LOCATION" "LOGGING" "COLUMNS")
9363 "Some properties that are used by Org-mode for various purposes.
9364 Being in this list makes sure that they are offered for completion.")
9366 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9367 "Regular expression matching the first line of a property drawer.")
9369 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9370 "Regular expression matching the first line of a property drawer.")
9372 (defun org-property-action ()
9373 "Do an action on properties."
9374 (interactive)
9375 (let (c)
9376 (org-at-property-p)
9377 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9378 (setq c (read-char-exclusive))
9379 (cond
9380 ((equal c ?s)
9381 (call-interactively 'org-set-property))
9382 ((equal c ?d)
9383 (call-interactively 'org-delete-property))
9384 ((equal c ?D)
9385 (call-interactively 'org-delete-property-globally))
9386 ((equal c ?c)
9387 (call-interactively 'org-compute-property-at-point))
9388 (t (error "No such property action %c" c)))))
9390 (defun org-at-property-p ()
9391 "Is the cursor in a property line?"
9392 ;; FIXME: Does not check if we are actually in the drawer.
9393 ;; FIXME: also returns true on any drawers.....
9394 ;; This is used by C-c C-c for property action.
9395 (save-excursion
9396 (beginning-of-line 1)
9397 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9399 (defun org-get-property-block (&optional beg end force)
9400 "Return the (beg . end) range of the body of the property drawer.
9401 BEG and END can be beginning and end of subtree, if not given
9402 they will be found.
9403 If the drawer does not exist and FORCE is non-nil, create the drawer."
9404 (catch 'exit
9405 (save-excursion
9406 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9407 (end (or end (progn (outline-next-heading) (point)))))
9408 (goto-char beg)
9409 (if (re-search-forward org-property-start-re end t)
9410 (setq beg (1+ (match-end 0)))
9411 (if force
9412 (save-excursion
9413 (org-insert-property-drawer)
9414 (setq end (progn (outline-next-heading) (point))))
9415 (throw 'exit nil))
9416 (goto-char beg)
9417 (if (re-search-forward org-property-start-re end t)
9418 (setq beg (1+ (match-end 0)))))
9419 (if (re-search-forward org-property-end-re end t)
9420 (setq end (match-beginning 0))
9421 (or force (throw 'exit nil))
9422 (goto-char beg)
9423 (setq end beg)
9424 (org-indent-line-function)
9425 (insert ":END:\n"))
9426 (cons beg end)))))
9428 (defun org-entry-properties (&optional pom which)
9429 "Get all properties of the entry at point-or-marker POM.
9430 This includes the TODO keyword, the tags, time strings for deadline,
9431 scheduled, and clocking, and any additional properties defined in the
9432 entry. The return value is an alist, keys may occur multiple times
9433 if the property key was used several times.
9434 POM may also be nil, in which case the current entry is used.
9435 If WHICH is nil or `all', get all properties. If WHICH is
9436 `special' or `standard', only get that subclass."
9437 (setq which (or which 'all))
9438 (org-with-point-at pom
9439 (let ((clockstr (substring org-clock-string 0 -1))
9440 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9441 beg end range props sum-props key value string clocksum)
9442 (save-excursion
9443 (when (condition-case nil (org-back-to-heading t) (error nil))
9444 (setq beg (point))
9445 (setq sum-props (get-text-property (point) 'org-summaries))
9446 (setq clocksum (get-text-property (point) :org-clock-minutes))
9447 (outline-next-heading)
9448 (setq end (point))
9449 (when (memq which '(all special))
9450 ;; Get the special properties, like TODO and tags
9451 (goto-char beg)
9452 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9453 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9454 (when (looking-at org-priority-regexp)
9455 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9456 (when (and (setq value (org-get-tags-string))
9457 (string-match "\\S-" value))
9458 (push (cons "TAGS" value) props))
9459 (when (setq value (org-get-tags-at))
9460 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9461 props))
9462 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9463 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9464 string (if (equal key clockstr)
9465 (org-no-properties
9466 (org-trim
9467 (buffer-substring
9468 (match-beginning 3) (goto-char (point-at-eol)))))
9469 (substring (org-match-string-no-properties 3) 1 -1)))
9470 (unless key
9471 (if (= (char-after (match-beginning 3)) ?\[)
9472 (setq key "TIMESTAMP_IA")
9473 (setq key "TIMESTAMP")))
9474 (when (or (equal key clockstr) (not (assoc key props)))
9475 (push (cons key string) props)))
9479 (when (memq which '(all standard))
9480 ;; Get the standard properties, like :PORP: ...
9481 (setq range (org-get-property-block beg end))
9482 (when range
9483 (goto-char (car range))
9484 (while (re-search-forward
9485 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9486 (cdr range) t)
9487 (setq key (org-match-string-no-properties 1)
9488 value (org-trim (or (org-match-string-no-properties 2) "")))
9489 (unless (member key excluded)
9490 (push (cons key (or value "")) props)))))
9491 (if clocksum
9492 (push (cons "CLOCKSUM"
9493 (org-columns-number-to-string (/ (float clocksum) 60.)
9494 'add_times))
9495 props))
9496 (append sum-props (nreverse props)))))))
9498 (defun org-entry-get (pom property &optional inherit)
9499 "Get value of PROPERTY for entry at point-or-marker POM.
9500 If INHERIT is non-nil and the entry does not have the property,
9501 then also check higher levels of the hierarchy.
9502 If INHERIT is the symbol `selective', use inheritance only if the setting
9503 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9504 If the property is present but empty, the return value is the empty string.
9505 If the property is not present at all, nil is returned."
9506 (org-with-point-at pom
9507 (if (and inherit (if (eq inherit 'selective)
9508 (org-property-inherit-p property)
9510 (org-entry-get-with-inheritance property)
9511 (if (member property org-special-properties)
9512 ;; We need a special property. Use brute force, get all properties.
9513 (cdr (assoc property (org-entry-properties nil 'special)))
9514 (let ((range (org-get-property-block)))
9515 (if (and range
9516 (goto-char (car range))
9517 (re-search-forward
9518 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9519 (cdr range) t))
9520 ;; Found the property, return it.
9521 (if (match-end 1)
9522 (org-match-string-no-properties 1)
9523 "")))))))
9525 (defun org-property-or-variable-value (var &optional inherit)
9526 "Check if there is a property fixing the value of VAR.
9527 If yes, return this value. If not, return the current value of the variable."
9528 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9529 (if (and prop (stringp prop) (string-match "\\S-" prop))
9530 (read prop)
9531 (symbol-value var))))
9533 (defun org-entry-delete (pom property)
9534 "Delete the property PROPERTY from entry at point-or-marker POM."
9535 (org-with-point-at pom
9536 (if (member property org-special-properties)
9537 nil ; cannot delete these properties.
9538 (let ((range (org-get-property-block)))
9539 (if (and range
9540 (goto-char (car range))
9541 (re-search-forward
9542 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9543 (cdr range) t))
9544 (progn
9545 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9547 nil)))))
9549 ;; Multi-values properties are properties that contain multiple values
9550 ;; These values are assumed to be single words, separated by whitespace.
9551 (defun org-entry-add-to-multivalued-property (pom property value)
9552 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9553 (let* ((old (org-entry-get pom property))
9554 (values (and old (org-split-string old "[ \t]"))))
9555 (unless (member value values)
9556 (setq values (cons value values))
9557 (org-entry-put pom property
9558 (mapconcat 'identity values " ")))))
9560 (defun org-entry-remove-from-multivalued-property (pom property value)
9561 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9562 (let* ((old (org-entry-get pom property))
9563 (values (and old (org-split-string old "[ \t]"))))
9564 (when (member value values)
9565 (setq values (delete value values))
9566 (org-entry-put pom property
9567 (mapconcat 'identity values " ")))))
9569 (defun org-entry-member-in-multivalued-property (pom property value)
9570 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9571 (let* ((old (org-entry-get pom property))
9572 (values (and old (org-split-string old "[ \t]"))))
9573 (member value values)))
9575 (defvar org-entry-property-inherited-from (make-marker))
9577 (defun org-entry-get-with-inheritance (property)
9578 "Get entry property, and search higher levels if not present."
9579 (let (tmp)
9580 (save-excursion
9581 (save-restriction
9582 (widen)
9583 (catch 'ex
9584 (while t
9585 (when (setq tmp (org-entry-get nil property))
9586 (org-back-to-heading t)
9587 (move-marker org-entry-property-inherited-from (point))
9588 (throw 'ex tmp))
9589 (or (org-up-heading-safe) (throw 'ex nil)))))
9590 (or tmp (cdr (assoc property org-local-properties))
9591 (cdr (assoc property org-global-properties))))))
9593 (defun org-entry-put (pom property value)
9594 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9595 (org-with-point-at pom
9596 (org-back-to-heading t)
9597 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9598 range)
9599 (cond
9600 ((equal property "TODO")
9601 (when (and (stringp value) (string-match "\\S-" value)
9602 (not (member value org-todo-keywords-1)))
9603 (error "\"%s\" is not a valid TODO state" value))
9604 (if (or (not value)
9605 (not (string-match "\\S-" value)))
9606 (setq value 'none))
9607 (org-todo value)
9608 (org-set-tags nil 'align))
9609 ((equal property "PRIORITY")
9610 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9611 (string-to-char value) ?\ ))
9612 (org-set-tags nil 'align))
9613 ((equal property "SCHEDULED")
9614 (if (re-search-forward org-scheduled-time-regexp end t)
9615 (cond
9616 ((eq value 'earlier) (org-timestamp-change -1 'day))
9617 ((eq value 'later) (org-timestamp-change 1 'day))
9618 (t (call-interactively 'org-schedule)))
9619 (call-interactively 'org-schedule)))
9620 ((equal property "DEADLINE")
9621 (if (re-search-forward org-deadline-time-regexp end t)
9622 (cond
9623 ((eq value 'earlier) (org-timestamp-change -1 'day))
9624 ((eq value 'later) (org-timestamp-change 1 'day))
9625 (t (call-interactively 'org-deadline)))
9626 (call-interactively 'org-deadline)))
9627 ((member property org-special-properties)
9628 (error "The %s property can not yet be set with `org-entry-put'"
9629 property))
9630 (t ; a non-special property
9631 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9632 (setq range (org-get-property-block beg end 'force))
9633 (goto-char (car range))
9634 (if (re-search-forward
9635 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9636 (progn
9637 (delete-region (match-beginning 1) (match-end 1))
9638 (goto-char (match-beginning 1)))
9639 (goto-char (cdr range))
9640 (insert "\n")
9641 (backward-char 1)
9642 (org-indent-line-function)
9643 (insert ":" property ":"))
9644 (and value (insert " " value))
9645 (org-indent-line-function)))))))
9647 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9648 "Get all property keys in the current buffer.
9649 With INCLUDE-SPECIALS, also list the special properties that relect things
9650 like tags and TODO state.
9651 With INCLUDE-DEFAULTS, also include properties that has special meaning
9652 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9653 With INCLUDE-COLUMNS, also include property names given in COLUMN
9654 formats in the current buffer."
9655 (let (rtn range cfmt cols s p)
9656 (save-excursion
9657 (save-restriction
9658 (widen)
9659 (goto-char (point-min))
9660 (while (re-search-forward org-property-start-re nil t)
9661 (setq range (org-get-property-block))
9662 (goto-char (car range))
9663 (while (re-search-forward
9664 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9665 (cdr range) t)
9666 (add-to-list 'rtn (org-match-string-no-properties 1)))
9667 (outline-next-heading))))
9669 (when include-specials
9670 (setq rtn (append org-special-properties rtn)))
9672 (when include-defaults
9673 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9675 (when include-columns
9676 (save-excursion
9677 (save-restriction
9678 (widen)
9679 (goto-char (point-min))
9680 (while (re-search-forward
9681 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9682 nil t)
9683 (setq cfmt (match-string 2) s 0)
9684 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9685 cfmt s)
9686 (setq s (match-end 0)
9687 p (match-string 1 cfmt))
9688 (unless (or (equal p "ITEM")
9689 (member p org-special-properties))
9690 (add-to-list 'rtn (match-string 1 cfmt))))))))
9692 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9694 (defun org-property-values (key)
9695 "Return a list of all values of property KEY."
9696 (save-excursion
9697 (save-restriction
9698 (widen)
9699 (goto-char (point-min))
9700 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9701 values)
9702 (while (re-search-forward re nil t)
9703 (add-to-list 'values (org-trim (match-string 1))))
9704 (delete "" values)))))
9706 (defun org-insert-property-drawer ()
9707 "Insert a property drawer into the current entry."
9708 (interactive)
9709 (org-back-to-heading t)
9710 (looking-at outline-regexp)
9711 (let ((indent (- (match-end 0)(match-beginning 0)))
9712 (beg (point))
9713 (re (concat "^[ \t]*" org-keyword-time-regexp))
9714 end hiddenp)
9715 (outline-next-heading)
9716 (setq end (point))
9717 (goto-char beg)
9718 (while (re-search-forward re end t))
9719 (setq hiddenp (org-invisible-p))
9720 (end-of-line 1)
9721 (and (equal (char-after) ?\n) (forward-char 1))
9722 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9723 (beginning-of-line 2))
9724 (org-skip-over-state-notes)
9725 (skip-chars-backward " \t\n\r")
9726 (if (eq (char-before) ?*) (forward-char 1))
9727 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9728 (beginning-of-line 0)
9729 (indent-to-column indent)
9730 (beginning-of-line 2)
9731 (indent-to-column indent)
9732 (beginning-of-line 0)
9733 (if hiddenp
9734 (save-excursion
9735 (org-back-to-heading t)
9736 (hide-entry))
9737 (org-flag-drawer t))))
9739 (defun org-set-property (property value)
9740 "In the current entry, set PROPERTY to VALUE.
9741 When called interactively, this will prompt for a property name, offering
9742 completion on existing and default properties. And then it will prompt
9743 for a value, offering competion either on allowed values (via an inherited
9744 xxx_ALL property) or on existing values in other instances of this property
9745 in the current file."
9746 (interactive
9747 (let* ((prop (completing-read
9748 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9749 (cur (org-entry-get nil prop))
9750 (allowed (org-property-get-allowed-values nil prop 'table))
9751 (existing (mapcar 'list (org-property-values prop)))
9752 (val (if allowed
9753 (completing-read "Value: " allowed nil 'req-match)
9754 (completing-read
9755 (concat "Value" (if (and cur (string-match "\\S-" cur))
9756 (concat "[" cur "]") "")
9757 ": ")
9758 existing nil nil "" nil cur))))
9759 (list prop (if (equal val "") cur val))))
9760 (unless (equal (org-entry-get nil property) value)
9761 (org-entry-put nil property value)))
9763 (defun org-delete-property (property)
9764 "In the current entry, delete PROPERTY."
9765 (interactive
9766 (let* ((prop (completing-read
9767 "Property: " (org-entry-properties nil 'standard))))
9768 (list prop)))
9769 (message "Property %s %s" property
9770 (if (org-entry-delete nil property)
9771 "deleted"
9772 "was not present in the entry")))
9774 (defun org-delete-property-globally (property)
9775 "Remove PROPERTY globally, from all entries."
9776 (interactive
9777 (let* ((prop (completing-read
9778 "Globally remove property: "
9779 (mapcar 'list (org-buffer-property-keys)))))
9780 (list prop)))
9781 (save-excursion
9782 (save-restriction
9783 (widen)
9784 (goto-char (point-min))
9785 (let ((cnt 0))
9786 (while (re-search-forward
9787 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9788 nil t)
9789 (setq cnt (1+ cnt))
9790 (replace-match ""))
9791 (message "Property \"%s\" removed from %d entries" property cnt)))))
9793 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9795 (defun org-compute-property-at-point ()
9796 "Compute the property at point.
9797 This looks for an enclosing column format, extracts the operator and
9798 then applies it to the proerty in the column format's scope."
9799 (interactive)
9800 (unless (org-at-property-p)
9801 (error "Not at a property"))
9802 (let ((prop (org-match-string-no-properties 2)))
9803 (org-columns-get-format-and-top-level)
9804 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9805 (error "No operator defined for property %s" prop))
9806 (org-columns-compute prop)))
9808 (defun org-property-get-allowed-values (pom property &optional table)
9809 "Get allowed values for the property PROPERTY.
9810 When TABLE is non-nil, return an alist that can directly be used for
9811 completion."
9812 (let (vals)
9813 (cond
9814 ((equal property "TODO")
9815 (setq vals (org-with-point-at pom
9816 (append org-todo-keywords-1 '("")))))
9817 ((equal property "PRIORITY")
9818 (let ((n org-lowest-priority))
9819 (while (>= n org-highest-priority)
9820 (push (char-to-string n) vals)
9821 (setq n (1- n)))))
9822 ((member property org-special-properties))
9824 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9826 (when (and vals (string-match "\\S-" vals))
9827 (setq vals (car (read-from-string (concat "(" vals ")"))))
9828 (setq vals (mapcar (lambda (x)
9829 (cond ((stringp x) x)
9830 ((numberp x) (number-to-string x))
9831 ((symbolp x) (symbol-name x))
9832 (t "???")))
9833 vals)))))
9834 (if table (mapcar 'list vals) vals)))
9836 (defun org-property-previous-allowed-value (&optional previous)
9837 "Switch to the next allowed value for this property."
9838 (interactive)
9839 (org-property-next-allowed-value t))
9841 (defun org-property-next-allowed-value (&optional previous)
9842 "Switch to the next allowed value for this property."
9843 (interactive)
9844 (unless (org-at-property-p)
9845 (error "Not at a property"))
9846 (let* ((key (match-string 2))
9847 (value (match-string 3))
9848 (allowed (or (org-property-get-allowed-values (point) key)
9849 (and (member value '("[ ]" "[-]" "[X]"))
9850 '("[ ]" "[X]"))))
9851 nval)
9852 (unless allowed
9853 (error "Allowed values for this property have not been defined"))
9854 (if previous (setq allowed (reverse allowed)))
9855 (if (member value allowed)
9856 (setq nval (car (cdr (member value allowed)))))
9857 (setq nval (or nval (car allowed)))
9858 (if (equal nval value)
9859 (error "Only one allowed value for this property"))
9860 (org-at-property-p)
9861 (replace-match (concat " :" key ": " nval) t t)
9862 (org-indent-line-function)
9863 (beginning-of-line 1)
9864 (skip-chars-forward " \t")))
9866 (defun org-find-entry-with-id (ident)
9867 "Locate the entry that contains the ID property with exact value IDENT.
9868 IDENT can be a string, a symbol or a number, this function will search for
9869 the string representation of it.
9870 Return the position where this entry starts, or nil if there is no such entry."
9871 (let ((id (cond
9872 ((stringp ident) ident)
9873 ((symbol-name ident) (symbol-name ident))
9874 ((numberp ident) (number-to-string ident))
9875 (t (error "IDENT %s must be a string, symbol or number" ident))))
9876 (case-fold-search nil))
9877 (save-excursion
9878 (save-restriction
9879 (widen)
9880 (goto-char (point-min))
9881 (when (re-search-forward
9882 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9883 nil t)
9884 (org-back-to-heading)
9885 (point))))))
9887 ;;;; Timestamps
9889 (defvar org-last-changed-timestamp nil)
9890 (defvar org-time-was-given) ; dynamically scoped parameter
9891 (defvar org-end-time-was-given) ; dynamically scoped parameter
9892 (defvar org-ts-what) ; dynamically scoped parameter
9894 (defun org-time-stamp (arg)
9895 "Prompt for a date/time and insert a time stamp.
9896 If the user specifies a time like HH:MM, or if this command is called
9897 with a prefix argument, the time stamp will contain date and time.
9898 Otherwise, only the date will be included. All parts of a date not
9899 specified by the user will be filled in from the current date/time.
9900 So if you press just return without typing anything, the time stamp
9901 will represent the current date/time. If there is already a timestamp
9902 at the cursor, it will be modified."
9903 (interactive "P")
9904 (let* ((ts nil)
9905 (default-time
9906 ;; Default time is either today, or, when entering a range,
9907 ;; the range start.
9908 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9909 (save-excursion
9910 (re-search-backward
9911 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9912 (- (point) 20) t)))
9913 (apply 'encode-time (org-parse-time-string (match-string 1)))
9914 (current-time)))
9915 (default-input (and ts (org-get-compact-tod ts)))
9916 org-time-was-given org-end-time-was-given time)
9917 (cond
9918 ((and (org-at-timestamp-p)
9919 (eq last-command 'org-time-stamp)
9920 (eq this-command 'org-time-stamp))
9921 (insert "--")
9922 (setq time (let ((this-command this-command))
9923 (org-read-date arg 'totime nil nil default-time default-input)))
9924 (org-insert-time-stamp time (or org-time-was-given arg)))
9925 ((org-at-timestamp-p)
9926 (setq time (let ((this-command this-command))
9927 (org-read-date arg 'totime nil nil default-time default-input)))
9928 (when (org-at-timestamp-p) ; just to get the match data
9929 (replace-match "")
9930 (setq org-last-changed-timestamp
9931 (org-insert-time-stamp
9932 time (or org-time-was-given arg)
9933 nil nil nil (list org-end-time-was-given))))
9934 (message "Timestamp updated"))
9936 (setq time (let ((this-command this-command))
9937 (org-read-date arg 'totime nil nil default-time default-input)))
9938 (org-insert-time-stamp time (or org-time-was-given arg)
9939 nil nil nil (list org-end-time-was-given))))))
9941 ;; FIXME: can we use this for something else, like computing time differences?
9942 (defun org-get-compact-tod (s)
9943 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9944 (let* ((t1 (match-string 1 s))
9945 (h1 (string-to-number (match-string 2 s)))
9946 (m1 (string-to-number (match-string 3 s)))
9947 (t2 (and (match-end 4) (match-string 5 s)))
9948 (h2 (and t2 (string-to-number (match-string 6 s))))
9949 (m2 (and t2 (string-to-number (match-string 7 s))))
9950 dh dm)
9951 (if (not t2)
9953 (setq dh (- h2 h1) dm (- m2 m1))
9954 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9955 (concat t1 "+" (number-to-string dh)
9956 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9958 (defun org-time-stamp-inactive (&optional arg)
9959 "Insert an inactive time stamp.
9960 An inactive time stamp is enclosed in square brackets instead of angle
9961 brackets. It is inactive in the sense that it does not trigger agenda entries,
9962 does not link to the calendar and cannot be changed with the S-cursor keys.
9963 So these are more for recording a certain time/date."
9964 (interactive "P")
9965 (let (org-time-was-given org-end-time-was-given time)
9966 (setq time (org-read-date arg 'totime))
9967 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9968 nil nil (list org-end-time-was-given))))
9970 (defvar org-date-ovl (org-make-overlay 1 1))
9971 (org-overlay-put org-date-ovl 'face 'org-warning)
9972 (org-detach-overlay org-date-ovl)
9974 (defvar org-ans1) ; dynamically scoped parameter
9975 (defvar org-ans2) ; dynamically scoped parameter
9977 (defvar org-plain-time-of-day-regexp) ; defined below
9979 (defvar org-read-date-overlay nil)
9980 (defvar org-dcst nil) ; dynamically scoped
9982 (defun org-read-date (&optional with-time to-time from-string prompt
9983 default-time default-input)
9984 "Read a date, possibly a time, and make things smooth for the user.
9985 The prompt will suggest to enter an ISO date, but you can also enter anything
9986 which will at least partially be understood by `parse-time-string'.
9987 Unrecognized parts of the date will default to the current day, month, year,
9988 hour and minute. If this command is called to replace a timestamp at point,
9989 of to enter the second timestamp of a range, the default time is taken from the
9990 existing stamp. For example,
9991 3-2-5 --> 2003-02-05
9992 feb 15 --> currentyear-02-15
9993 sep 12 9 --> 2009-09-12
9994 12:45 --> today 12:45
9995 22 sept 0:34 --> currentyear-09-22 0:34
9996 12 --> currentyear-currentmonth-12
9997 Fri --> nearest Friday (today or later)
9998 etc.
10000 Furthermore you can specify a relative date by giving, as the *first* thing
10001 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10002 change in days weeks, months, years.
10003 With a single plus or minus, the date is relative to today. With a double
10004 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10005 +4d --> four days from today
10006 +4 --> same as above
10007 +2w --> two weeks from today
10008 ++5 --> five days from default date
10010 The function understands only English month and weekday abbreviations,
10011 but this can be configured with the variables `parse-time-months' and
10012 `parse-time-weekdays'.
10014 While prompting, a calendar is popped up - you can also select the
10015 date with the mouse (button 1). The calendar shows a period of three
10016 months. To scroll it to other months, use the keys `>' and `<'.
10017 If you don't like the calendar, turn it off with
10018 \(setq org-read-date-popup-calendar nil)
10020 With optional argument TO-TIME, the date will immediately be converted
10021 to an internal time.
10022 With an optional argument WITH-TIME, the prompt will suggest to also
10023 insert a time. Note that when WITH-TIME is not set, you can still
10024 enter a time, and this function will inform the calling routine about
10025 this change. The calling routine may then choose to change the format
10026 used to insert the time stamp into the buffer to include the time.
10027 With optional argument FROM-STRING, read from this string instead from
10028 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10029 the time/date that is used for everything that is not specified by the
10030 user."
10031 (require 'parse-time)
10032 (let* ((org-time-stamp-rounding-minutes
10033 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10034 (org-dcst org-display-custom-times)
10035 (ct (org-current-time))
10036 (def (or default-time ct))
10037 (defdecode (decode-time def))
10038 (dummy (progn
10039 (when (< (nth 2 defdecode) org-extend-today-until)
10040 (setcar (nthcdr 2 defdecode) -1)
10041 (setcar (nthcdr 1 defdecode) 59)
10042 (setq def (apply 'encode-time defdecode)
10043 defdecode (decode-time def)))))
10044 (calendar-move-hook nil)
10045 (calendar-view-diary-initially-flag nil)
10046 (view-diary-entries-initially nil)
10047 (calendar-view-holidays-initially-flag nil)
10048 (view-calendar-holidays-initially nil)
10049 (timestr (format-time-string
10050 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10051 (prompt (concat (if prompt (concat prompt " ") "")
10052 (format "Date+time [%s]: " timestr)))
10053 ans (org-ans0 "") org-ans1 org-ans2 final)
10055 (cond
10056 (from-string (setq ans from-string))
10057 (org-read-date-popup-calendar
10058 (save-excursion
10059 (save-window-excursion
10060 (calendar)
10061 (calendar-forward-day (- (time-to-days def)
10062 (calendar-absolute-from-gregorian
10063 (calendar-current-date))))
10064 (org-eval-in-calendar nil t)
10065 (let* ((old-map (current-local-map))
10066 (map (copy-keymap calendar-mode-map))
10067 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10068 (org-defkey map (kbd "RET") 'org-calendar-select)
10069 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10070 'org-calendar-select-mouse)
10071 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10072 'org-calendar-select-mouse)
10073 (org-defkey minibuffer-local-map [(meta shift left)]
10074 (lambda () (interactive)
10075 (org-eval-in-calendar '(calendar-backward-month 1))))
10076 (org-defkey minibuffer-local-map [(meta shift right)]
10077 (lambda () (interactive)
10078 (org-eval-in-calendar '(calendar-forward-month 1))))
10079 (org-defkey minibuffer-local-map [(meta shift up)]
10080 (lambda () (interactive)
10081 (org-eval-in-calendar '(calendar-backward-year 1))))
10082 (org-defkey minibuffer-local-map [(meta shift down)]
10083 (lambda () (interactive)
10084 (org-eval-in-calendar '(calendar-forward-year 1))))
10085 (org-defkey minibuffer-local-map [(shift up)]
10086 (lambda () (interactive)
10087 (org-eval-in-calendar '(calendar-backward-week 1))))
10088 (org-defkey minibuffer-local-map [(shift down)]
10089 (lambda () (interactive)
10090 (org-eval-in-calendar '(calendar-forward-week 1))))
10091 (org-defkey minibuffer-local-map [(shift left)]
10092 (lambda () (interactive)
10093 (org-eval-in-calendar '(calendar-backward-day 1))))
10094 (org-defkey minibuffer-local-map [(shift right)]
10095 (lambda () (interactive)
10096 (org-eval-in-calendar '(calendar-forward-day 1))))
10097 (org-defkey minibuffer-local-map ">"
10098 (lambda () (interactive)
10099 (org-eval-in-calendar '(scroll-calendar-left 1))))
10100 (org-defkey minibuffer-local-map "<"
10101 (lambda () (interactive)
10102 (org-eval-in-calendar '(scroll-calendar-right 1))))
10103 (unwind-protect
10104 (progn
10105 (use-local-map map)
10106 (add-hook 'post-command-hook 'org-read-date-display)
10107 (setq org-ans0 (read-string prompt default-input nil nil))
10108 ;; org-ans0: from prompt
10109 ;; org-ans1: from mouse click
10110 ;; org-ans2: from calendar motion
10111 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10112 (remove-hook 'post-command-hook 'org-read-date-display)
10113 (use-local-map old-map)
10114 (when org-read-date-overlay
10115 (org-delete-overlay org-read-date-overlay)
10116 (setq org-read-date-overlay nil)))))))
10118 (t ; Naked prompt only
10119 (unwind-protect
10120 (setq ans (read-string prompt default-input nil timestr))
10121 (when org-read-date-overlay
10122 (org-delete-overlay org-read-date-overlay)
10123 (setq org-read-date-overlay nil)))))
10125 (setq final (org-read-date-analyze ans def defdecode))
10127 (if to-time
10128 (apply 'encode-time final)
10129 (if (and (boundp 'org-time-was-given) org-time-was-given)
10130 (format "%04d-%02d-%02d %02d:%02d"
10131 (nth 5 final) (nth 4 final) (nth 3 final)
10132 (nth 2 final) (nth 1 final))
10133 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10134 (defvar def)
10135 (defvar defdecode)
10136 (defvar with-time)
10137 (defun org-read-date-display ()
10138 "Display the currrent date prompt interpretation in the minibuffer."
10139 (when org-read-date-display-live
10140 (when org-read-date-overlay
10141 (org-delete-overlay org-read-date-overlay))
10142 (let ((p (point)))
10143 (end-of-line 1)
10144 (while (not (equal (buffer-substring
10145 (max (point-min) (- (point) 4)) (point))
10146 " "))
10147 (insert " "))
10148 (goto-char p))
10149 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10150 " " (or org-ans1 org-ans2)))
10151 (org-end-time-was-given nil)
10152 (f (org-read-date-analyze ans def defdecode))
10153 (fmts (if org-dcst
10154 org-time-stamp-custom-formats
10155 org-time-stamp-formats))
10156 (fmt (if (or with-time
10157 (and (boundp 'org-time-was-given) org-time-was-given))
10158 (cdr fmts)
10159 (car fmts)))
10160 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10161 (when (and org-end-time-was-given
10162 (string-match org-plain-time-of-day-regexp txt))
10163 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10164 org-end-time-was-given
10165 (substring txt (match-end 0)))))
10166 (setq org-read-date-overlay
10167 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10168 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10170 (defun org-read-date-analyze (ans def defdecode)
10171 "Analyze the combined answer of the date prompt."
10172 ;; FIXME: cleanup and comment
10173 (let (delta deltan deltaw deltadef year month day
10174 hour minute second wday pm h2 m2 tl wday1
10175 iso-year iso-weekday iso-week iso-year iso-date)
10177 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10178 (setq ans (replace-match "" t t ans)
10179 deltan (car delta)
10180 deltaw (nth 1 delta)
10181 deltadef (nth 2 delta)))
10183 ;; Check if there is an iso week date in there
10184 ;; If yes, sore the info and ostpone interpreting it until the rest
10185 ;; of the parsing is done
10186 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10187 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10188 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10189 iso-week (string-to-number (match-string 2 ans)))
10190 (setq ans (replace-match "" t t ans)))
10192 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10193 (when (string-match
10194 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10195 (setq year (if (match-end 2)
10196 (string-to-number (match-string 2 ans))
10197 (string-to-number (format-time-string "%Y")))
10198 month (string-to-number (match-string 3 ans))
10199 day (string-to-number (match-string 4 ans)))
10200 (if (< year 100) (setq year (+ 2000 year)))
10201 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10202 t nil ans)))
10203 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10204 ;; If there is a time with am/pm, and *no* time without it, we convert
10205 ;; so that matching will be successful.
10206 (loop for i from 1 to 2 do ; twice, for end time as well
10207 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10208 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10209 (setq hour (string-to-number (match-string 1 ans))
10210 minute (if (match-end 3)
10211 (string-to-number (match-string 3 ans))
10213 pm (equal ?p
10214 (string-to-char (downcase (match-string 4 ans)))))
10215 (if (and (= hour 12) (not pm))
10216 (setq hour 0)
10217 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10218 (setq ans (replace-match (format "%02d:%02d" hour minute)
10219 t t ans))))
10221 ;; Check if a time range is given as a duration
10222 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10223 (setq hour (string-to-number (match-string 1 ans))
10224 h2 (+ hour (string-to-number (match-string 3 ans)))
10225 minute (string-to-number (match-string 2 ans))
10226 m2 (+ minute (if (match-end 5) (string-to-number
10227 (match-string 5 ans))0)))
10228 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10229 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10230 t t ans)))
10232 ;; Check if there is a time range
10233 (when (boundp 'org-end-time-was-given)
10234 (setq org-time-was-given nil)
10235 (when (and (string-match org-plain-time-of-day-regexp ans)
10236 (match-end 8))
10237 (setq org-end-time-was-given (match-string 8 ans))
10238 (setq ans (concat (substring ans 0 (match-beginning 7))
10239 (substring ans (match-end 7))))))
10241 (setq tl (parse-time-string ans)
10242 day (or (nth 3 tl) (nth 3 defdecode))
10243 month (or (nth 4 tl)
10244 (if (and org-read-date-prefer-future
10245 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10246 (1+ (nth 4 defdecode))
10247 (nth 4 defdecode)))
10248 year (or (nth 5 tl)
10249 (if (and org-read-date-prefer-future
10250 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10251 (1+ (nth 5 defdecode))
10252 (nth 5 defdecode)))
10253 hour (or (nth 2 tl) (nth 2 defdecode))
10254 minute (or (nth 1 tl) (nth 1 defdecode))
10255 second (or (nth 0 tl) 0)
10256 wday (nth 6 tl))
10258 ;; Special date definitions below
10259 (cond
10260 (iso-week
10261 ;; There was an iso week
10262 (setq year (or iso-year year)
10263 day (or iso-weekday wday 1)
10264 wday nil ; to make sure that the trigger below does not match
10265 iso-date (calendar-gregorian-from-absolute
10266 (calendar-absolute-from-iso
10267 (list iso-week day year))))
10268 ; FIXME: Should we also push ISO weeks into the future?
10269 ; (when (and org-read-date-prefer-future
10270 ; (not iso-year)
10271 ; (< (calendar-absolute-from-gregorian iso-date)
10272 ; (time-to-days (current-time))))
10273 ; (setq year (1+ year)
10274 ; iso-date (calendar-gregorian-from-absolute
10275 ; (calendar-absolute-from-iso
10276 ; (list iso-week day year)))))
10277 (setq month (car iso-date)
10278 year (nth 2 iso-date)
10279 day (nth 1 iso-date)))
10280 (deltan
10281 (unless deltadef
10282 (let ((now (decode-time (current-time))))
10283 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10284 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10285 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10286 ((equal deltaw "m") (setq month (+ month deltan)))
10287 ((equal deltaw "y") (setq year (+ year deltan)))))
10288 ((and wday (not (nth 3 tl)))
10289 ;; Weekday was given, but no day, so pick that day in the week
10290 ;; on or after the derived date.
10291 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10292 (unless (equal wday wday1)
10293 (setq day (+ day (% (- wday wday1 -7) 7))))))
10294 (if (and (boundp 'org-time-was-given)
10295 (nth 2 tl))
10296 (setq org-time-was-given t))
10297 (if (< year 100) (setq year (+ 2000 year)))
10298 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10299 (list second minute hour day month year)))
10301 (defvar parse-time-weekdays)
10303 (defun org-read-date-get-relative (s today default)
10304 "Check string S for special relative date string.
10305 TODAY and DEFAULT are internal times, for today and for a default.
10306 Return shift list (N what def-flag)
10307 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10308 N is the number of WHATs to shift.
10309 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10310 the DEFAULT date rather than TODAY."
10311 (when (string-match
10312 (concat
10313 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10314 "\\([0-9]+\\)?"
10315 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10316 "\\([ \t]\\|$\\)") s)
10317 (let* ((dir (if (match-end 1)
10318 (string-to-char (substring (match-string 1 s) -1))
10319 ?+))
10320 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10321 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10322 (what (if (match-end 3) (match-string 3 s) "d"))
10323 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10324 (date (if rel default today))
10325 (wday (nth 6 (decode-time date)))
10326 delta)
10327 (if wday1
10328 (progn
10329 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10330 (if (= dir ?-) (setq delta (- delta 7)))
10331 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10332 (list delta "d" rel))
10333 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10335 (defun org-eval-in-calendar (form &optional keepdate)
10336 "Eval FORM in the calendar window and return to current window.
10337 Also, store the cursor date in variable org-ans2."
10338 (let ((sw (selected-window)))
10339 (select-window (get-buffer-window "*Calendar*"))
10340 (eval form)
10341 (when (and (not keepdate) (calendar-cursor-to-date))
10342 (let* ((date (calendar-cursor-to-date))
10343 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10344 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10345 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10346 (select-window sw)))
10348 ; ;; Update the prompt to show new default date
10349 ; (save-excursion
10350 ; (goto-char (point-min))
10351 ; (when (and org-ans2
10352 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10353 ; (get-text-property (match-end 0) 'field))
10354 ; (let ((inhibit-read-only t))
10355 ; (replace-match (concat "[" org-ans2 "]") t t)
10356 ; (add-text-properties (point-min) (1+ (match-end 0))
10357 ; (text-properties-at (1+ (point-min)))))))))
10359 (defun org-calendar-select ()
10360 "Return to `org-read-date' with the date currently selected.
10361 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10362 (interactive)
10363 (when (calendar-cursor-to-date)
10364 (let* ((date (calendar-cursor-to-date))
10365 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10366 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10367 (if (active-minibuffer-window) (exit-minibuffer))))
10369 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10370 "Insert a date stamp for the date given by the internal TIME.
10371 WITH-HM means, use the stamp format that includes the time of the day.
10372 INACTIVE means use square brackets instead of angular ones, so that the
10373 stamp will not contribute to the agenda.
10374 PRE and POST are optional strings to be inserted before and after the
10375 stamp.
10376 The command returns the inserted time stamp."
10377 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10378 stamp)
10379 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10380 (insert-before-markers (or pre ""))
10381 (insert-before-markers (setq stamp (format-time-string fmt time)))
10382 (when (listp extra)
10383 (setq extra (car extra))
10384 (if (and (stringp extra)
10385 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10386 (setq extra (format "-%02d:%02d"
10387 (string-to-number (match-string 1 extra))
10388 (string-to-number (match-string 2 extra))))
10389 (setq extra nil)))
10390 (when extra
10391 (backward-char 1)
10392 (insert-before-markers extra)
10393 (forward-char 1))
10394 (insert-before-markers (or post ""))
10395 stamp))
10397 (defun org-toggle-time-stamp-overlays ()
10398 "Toggle the use of custom time stamp formats."
10399 (interactive)
10400 (setq org-display-custom-times (not org-display-custom-times))
10401 (unless org-display-custom-times
10402 (let ((p (point-min)) (bmp (buffer-modified-p)))
10403 (while (setq p (next-single-property-change p 'display))
10404 (if (and (get-text-property p 'display)
10405 (eq (get-text-property p 'face) 'org-date))
10406 (remove-text-properties
10407 p (setq p (next-single-property-change p 'display))
10408 '(display t))))
10409 (set-buffer-modified-p bmp)))
10410 (if (featurep 'xemacs)
10411 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10412 (org-restart-font-lock)
10413 (setq org-table-may-need-update t)
10414 (if org-display-custom-times
10415 (message "Time stamps are overlayed with custom format")
10416 (message "Time stamp overlays removed")))
10418 (defun org-display-custom-time (beg end)
10419 "Overlay modified time stamp format over timestamp between BED and END."
10420 (let* ((ts (buffer-substring beg end))
10421 t1 w1 with-hm tf time str w2 (off 0))
10422 (save-match-data
10423 (setq t1 (org-parse-time-string ts t))
10424 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10425 (setq off (- (match-end 0) (match-beginning 0)))))
10426 (setq end (- end off))
10427 (setq w1 (- end beg)
10428 with-hm (and (nth 1 t1) (nth 2 t1))
10429 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10430 time (org-fix-decoded-time t1)
10431 str (org-add-props
10432 (format-time-string
10433 (substring tf 1 -1) (apply 'encode-time time))
10434 nil 'mouse-face 'highlight)
10435 w2 (length str))
10436 (if (not (= w2 w1))
10437 (add-text-properties (1+ beg) (+ 2 beg)
10438 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10439 (if (featurep 'xemacs)
10440 (progn
10441 (put-text-property beg end 'invisible t)
10442 (put-text-property beg end 'end-glyph (make-glyph str)))
10443 (put-text-property beg end 'display str))))
10445 (defun org-translate-time (string)
10446 "Translate all timestamps in STRING to custom format.
10447 But do this only if the variable `org-display-custom-times' is set."
10448 (when org-display-custom-times
10449 (save-match-data
10450 (let* ((start 0)
10451 (re org-ts-regexp-both)
10452 t1 with-hm inactive tf time str beg end)
10453 (while (setq start (string-match re string start))
10454 (setq beg (match-beginning 0)
10455 end (match-end 0)
10456 t1 (save-match-data
10457 (org-parse-time-string (substring string beg end) t))
10458 with-hm (and (nth 1 t1) (nth 2 t1))
10459 inactive (equal (substring string beg (1+ beg)) "[")
10460 tf (funcall (if with-hm 'cdr 'car)
10461 org-time-stamp-custom-formats)
10462 time (org-fix-decoded-time t1)
10463 str (format-time-string
10464 (concat
10465 (if inactive "[" "<") (substring tf 1 -1)
10466 (if inactive "]" ">"))
10467 (apply 'encode-time time))
10468 string (replace-match str t t string)
10469 start (+ start (length str)))))))
10470 string)
10472 (defun org-fix-decoded-time (time)
10473 "Set 0 instead of nil for the first 6 elements of time.
10474 Don't touch the rest."
10475 (let ((n 0))
10476 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10478 (defun org-days-to-time (timestamp-string)
10479 "Difference between TIMESTAMP-STRING and now in days."
10480 (- (time-to-days (org-time-string-to-time timestamp-string))
10481 (time-to-days (current-time))))
10483 (defun org-deadline-close (timestamp-string &optional ndays)
10484 "Is the time in TIMESTAMP-STRING close to the current date?"
10485 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10486 (and (< (org-days-to-time timestamp-string) ndays)
10487 (not (org-entry-is-done-p))))
10489 (defun org-get-wdays (ts)
10490 "Get the deadline lead time appropriate for timestring TS."
10491 (cond
10492 ((<= org-deadline-warning-days 0)
10493 ;; 0 or negative, enforce this value no matter what
10494 (- org-deadline-warning-days))
10495 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10496 ;; lead time is specified.
10497 (floor (* (string-to-number (match-string 1 ts))
10498 (cdr (assoc (match-string 2 ts)
10499 '(("d" . 1) ("w" . 7)
10500 ("m" . 30.4) ("y" . 365.25)))))))
10501 ;; go for the default.
10502 (t org-deadline-warning-days)))
10504 (defun org-calendar-select-mouse (ev)
10505 "Return to `org-read-date' with the date currently selected.
10506 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10507 (interactive "e")
10508 (mouse-set-point ev)
10509 (when (calendar-cursor-to-date)
10510 (let* ((date (calendar-cursor-to-date))
10511 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10512 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10513 (if (active-minibuffer-window) (exit-minibuffer))))
10515 (defun org-check-deadlines (ndays)
10516 "Check if there are any deadlines due or past due.
10517 A deadline is considered due if it happens within `org-deadline-warning-days'
10518 days from today's date. If the deadline appears in an entry marked DONE,
10519 it is not shown. The prefix arg NDAYS can be used to test that many
10520 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10521 (interactive "P")
10522 (let* ((org-warn-days
10523 (cond
10524 ((equal ndays '(4)) 100000)
10525 (ndays (prefix-numeric-value ndays))
10526 (t (abs org-deadline-warning-days))))
10527 (case-fold-search nil)
10528 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10529 (callback
10530 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10532 (message "%d deadlines past-due or due within %d days"
10533 (org-occur regexp nil callback)
10534 org-warn-days)))
10536 (defun org-check-before-date (date)
10537 "Check if there are deadlines or scheduled entries before DATE."
10538 (interactive (list (org-read-date)))
10539 (let ((case-fold-search nil)
10540 (regexp (concat "\\<\\(" org-deadline-string
10541 "\\|" org-scheduled-string
10542 "\\) *<\\([^>]+\\)>"))
10543 (callback
10544 (lambda () (time-less-p
10545 (org-time-string-to-time (match-string 2))
10546 (org-time-string-to-time date)))))
10547 (message "%d entries before %s"
10548 (org-occur regexp nil callback) date)))
10550 (defun org-evaluate-time-range (&optional to-buffer)
10551 "Evaluate a time range by computing the difference between start and end.
10552 Normally the result is just printed in the echo area, but with prefix arg
10553 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10554 If the time range is actually in a table, the result is inserted into the
10555 next column.
10556 For time difference computation, a year is assumed to be exactly 365
10557 days in order to avoid rounding problems."
10558 (interactive "P")
10560 (org-clock-update-time-maybe)
10561 (save-excursion
10562 (unless (org-at-date-range-p t)
10563 (goto-char (point-at-bol))
10564 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10565 (if (not (org-at-date-range-p t))
10566 (error "Not at a time-stamp range, and none found in current line")))
10567 (let* ((ts1 (match-string 1))
10568 (ts2 (match-string 2))
10569 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10570 (match-end (match-end 0))
10571 (time1 (org-time-string-to-time ts1))
10572 (time2 (org-time-string-to-time ts2))
10573 (t1 (time-to-seconds time1))
10574 (t2 (time-to-seconds time2))
10575 (diff (abs (- t2 t1)))
10576 (negative (< (- t2 t1) 0))
10577 ;; (ys (floor (* 365 24 60 60)))
10578 (ds (* 24 60 60))
10579 (hs (* 60 60))
10580 (fy "%dy %dd %02d:%02d")
10581 (fy1 "%dy %dd")
10582 (fd "%dd %02d:%02d")
10583 (fd1 "%dd")
10584 (fh "%02d:%02d")
10585 y d h m align)
10586 (if havetime
10587 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10589 d (floor (/ diff ds)) diff (mod diff ds)
10590 h (floor (/ diff hs)) diff (mod diff hs)
10591 m (floor (/ diff 60)))
10592 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10594 d (floor (+ (/ diff ds) 0.5))
10595 h 0 m 0))
10596 (if (not to-buffer)
10597 (message "%s" (org-make-tdiff-string y d h m))
10598 (if (org-at-table-p)
10599 (progn
10600 (goto-char match-end)
10601 (setq align t)
10602 (and (looking-at " *|") (goto-char (match-end 0))))
10603 (goto-char match-end))
10604 (if (looking-at
10605 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10606 (replace-match ""))
10607 (if negative (insert " -"))
10608 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10609 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10610 (insert " " (format fh h m))))
10611 (if align (org-table-align))
10612 (message "Time difference inserted")))))
10614 (defun org-make-tdiff-string (y d h m)
10615 (let ((fmt "")
10616 (l nil))
10617 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10618 l (push y l)))
10619 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10620 l (push d l)))
10621 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10622 l (push h l)))
10623 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10624 l (push m l)))
10625 (apply 'format fmt (nreverse l))))
10627 (defun org-time-string-to-time (s)
10628 (apply 'encode-time (org-parse-time-string s)))
10630 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10631 "Convert a time stamp to an absolute day number.
10632 If there is a specifyer for a cyclic time stamp, get the closest date to
10633 DAYNR.
10634 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10635 (cond
10636 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10637 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10638 daynr
10639 (+ daynr 1000)))
10640 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10641 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10642 (time-to-days (current-time))) (match-string 0 s)
10643 prefer show-all))
10644 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10646 (defun org-days-to-iso-week (days)
10647 "Return the iso week number."
10648 (require 'cal-iso)
10649 (car (calendar-iso-from-absolute days)))
10651 (defun org-small-year-to-year (year)
10652 "Convert 2-digit years into 4-digit years.
10653 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10654 The year 2000 cannot be abbreviated. Any year lager than 99
10655 is retrned unchanged."
10656 (if (< year 38)
10657 (setq year (+ 2000 year))
10658 (if (< year 100)
10659 (setq year (+ 1900 year))))
10660 year)
10662 (defun org-time-from-absolute (d)
10663 "Return the time corresponding to date D.
10664 D may be an absolute day number, or a calendar-type list (month day year)."
10665 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10666 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10668 (defun org-calendar-holiday ()
10669 "List of holidays, for Diary display in Org-mode."
10670 (require 'holidays)
10671 (let ((hl (funcall
10672 (if (fboundp 'calendar-check-holidays)
10673 'calendar-check-holidays 'check-calendar-holidays) date)))
10674 (if hl (mapconcat 'identity hl "; "))))
10676 (defun org-diary-sexp-entry (sexp entry date)
10677 "Process a SEXP diary ENTRY for DATE."
10678 (require 'diary-lib)
10679 (let ((result (if calendar-debug-sexp
10680 (let ((stack-trace-on-error t))
10681 (eval (car (read-from-string sexp))))
10682 (condition-case nil
10683 (eval (car (read-from-string sexp)))
10684 (error
10685 (beep)
10686 (message "Bad sexp at line %d in %s: %s"
10687 (org-current-line)
10688 (buffer-file-name) sexp)
10689 (sleep-for 2))))))
10690 (cond ((stringp result) result)
10691 ((and (consp result)
10692 (stringp (cdr result))) (cdr result))
10693 (result entry)
10694 (t nil))))
10696 (defun org-diary-to-ical-string (frombuf)
10697 "Get iCalendar entries from diary entries in buffer FROMBUF.
10698 This uses the icalendar.el library."
10699 (let* ((tmpdir (if (featurep 'xemacs)
10700 (temp-directory)
10701 temporary-file-directory))
10702 (tmpfile (make-temp-name
10703 (expand-file-name "orgics" tmpdir)))
10704 buf rtn b e)
10705 (save-excursion
10706 (set-buffer frombuf)
10707 (icalendar-export-region (point-min) (point-max) tmpfile)
10708 (setq buf (find-buffer-visiting tmpfile))
10709 (set-buffer buf)
10710 (goto-char (point-min))
10711 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10712 (setq b (match-beginning 0)))
10713 (goto-char (point-max))
10714 (if (re-search-backward "^END:VEVENT" nil t)
10715 (setq e (match-end 0)))
10716 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10717 (kill-buffer buf)
10718 (kill-buffer frombuf)
10719 (delete-file tmpfile)
10720 rtn))
10722 (defun org-closest-date (start current change prefer show-all)
10723 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10724 When PREFER is `past' return a date that is either CURRENT or past.
10725 When PREFER is `future', return a date that is either CURRENT or future.
10726 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10727 ;; Make the proper lists from the dates
10728 (catch 'exit
10729 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10730 dn dw sday cday n1 n2
10731 d m y y1 y2 date1 date2 nmonths nm ny m2)
10733 (setq start (org-date-to-gregorian start)
10734 current (org-date-to-gregorian
10735 (if show-all
10736 current
10737 (time-to-days (current-time))))
10738 sday (calendar-absolute-from-gregorian start)
10739 cday (calendar-absolute-from-gregorian current))
10741 (if (<= cday sday) (throw 'exit sday))
10743 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10744 (setq dn (string-to-number (match-string 1 change))
10745 dw (cdr (assoc (match-string 2 change) a1)))
10746 (error "Invalid change specifyer: %s" change))
10747 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10748 (cond
10749 ((eq dw 'day)
10750 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10751 n2 (+ n1 dn)))
10752 ((eq dw 'year)
10753 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10754 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10755 (setq date1 (list m d y1)
10756 n1 (calendar-absolute-from-gregorian date1)
10757 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10758 n2 (calendar-absolute-from-gregorian date2)))
10759 ((eq dw 'month)
10760 ;; approx number of month between the tow dates
10761 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10762 ;; How often does dn fit in there?
10763 (setq d (nth 1 start) m (car start) y (nth 2 start)
10764 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10765 m (+ m nm)
10766 ny (floor (/ m 12))
10767 y (+ y ny)
10768 m (- m (* ny 12)))
10769 (while (> m 12) (setq m (- m 12) y (1+ y)))
10770 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10771 (setq m2 (+ m dn) y2 y)
10772 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10773 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10774 (while (< n2 cday)
10775 (setq n1 n2 m m2 y y2)
10776 (setq m2 (+ m dn) y2 y)
10777 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10778 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10780 (if show-all
10781 (cond
10782 ((eq prefer 'past) n1)
10783 ((eq prefer 'future) (if (= cday n1) n1 n2))
10784 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10785 (cond
10786 ((eq prefer 'past) n1)
10787 ((eq prefer 'future) (if (= cday n1) n1 n2))
10788 (t (if (= cday n1) n1 n2)))))))
10790 (defun org-date-to-gregorian (date)
10791 "Turn any specification of DATE into a gregorian date for the calendar."
10792 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10793 ((and (listp date) (= (length date) 3)) date)
10794 ((stringp date)
10795 (setq date (org-parse-time-string date))
10796 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10797 ((listp date)
10798 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10800 (defun org-parse-time-string (s &optional nodefault)
10801 "Parse the standard Org-mode time string.
10802 This should be a lot faster than the normal `parse-time-string'.
10803 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10804 hour and minute fields will be nil if not given."
10805 (if (string-match org-ts-regexp0 s)
10806 (list 0
10807 (if (or (match-beginning 8) (not nodefault))
10808 (string-to-number (or (match-string 8 s) "0")))
10809 (if (or (match-beginning 7) (not nodefault))
10810 (string-to-number (or (match-string 7 s) "0")))
10811 (string-to-number (match-string 4 s))
10812 (string-to-number (match-string 3 s))
10813 (string-to-number (match-string 2 s))
10814 nil nil nil)
10815 (make-list 9 0)))
10817 (defun org-timestamp-up (&optional arg)
10818 "Increase the date item at the cursor by one.
10819 If the cursor is on the year, change the year. If it is on the month or
10820 the day, change that.
10821 With prefix ARG, change by that many units."
10822 (interactive "p")
10823 (org-timestamp-change (prefix-numeric-value arg)))
10825 (defun org-timestamp-down (&optional arg)
10826 "Decrease the date item at the cursor by one.
10827 If the cursor is on the year, change the year. If it is on the month or
10828 the day, change that.
10829 With prefix ARG, change by that many units."
10830 (interactive "p")
10831 (org-timestamp-change (- (prefix-numeric-value arg))))
10833 (defun org-timestamp-up-day (&optional arg)
10834 "Increase the date in the time stamp by one day.
10835 With prefix ARG, change that many days."
10836 (interactive "p")
10837 (if (and (not (org-at-timestamp-p t))
10838 (org-on-heading-p))
10839 (org-todo 'up)
10840 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10842 (defun org-timestamp-down-day (&optional arg)
10843 "Decrease the date in the time stamp by one day.
10844 With prefix ARG, change that many days."
10845 (interactive "p")
10846 (if (and (not (org-at-timestamp-p t))
10847 (org-on-heading-p))
10848 (org-todo 'down)
10849 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10851 (defun org-at-timestamp-p (&optional inactive-ok)
10852 "Determine if the cursor is in or at a timestamp."
10853 (interactive)
10854 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10855 (pos (point))
10856 (ans (or (looking-at tsr)
10857 (save-excursion
10858 (skip-chars-backward "^[<\n\r\t")
10859 (if (> (point) (point-min)) (backward-char 1))
10860 (and (looking-at tsr)
10861 (> (- (match-end 0) pos) -1))))))
10862 (and ans
10863 (boundp 'org-ts-what)
10864 (setq org-ts-what
10865 (cond
10866 ((= pos (match-beginning 0)) 'bracket)
10867 ((= pos (1- (match-end 0))) 'bracket)
10868 ((org-pos-in-match-range pos 2) 'year)
10869 ((org-pos-in-match-range pos 3) 'month)
10870 ((org-pos-in-match-range pos 7) 'hour)
10871 ((org-pos-in-match-range pos 8) 'minute)
10872 ((or (org-pos-in-match-range pos 4)
10873 (org-pos-in-match-range pos 5)) 'day)
10874 ((and (> pos (or (match-end 8) (match-end 5)))
10875 (< pos (match-end 0)))
10876 (- pos (or (match-end 8) (match-end 5))))
10877 (t 'day))))
10878 ans))
10880 (defun org-toggle-timestamp-type ()
10881 "Toggle the type (<active> or [inactive]) of a time stamp."
10882 (interactive)
10883 (when (org-at-timestamp-p t)
10884 (save-excursion
10885 (goto-char (match-beginning 0))
10886 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10887 (goto-char (1- (match-end 0)))
10888 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10889 (message "Timestamp is now %sactive"
10890 (if (equal (char-before) ?>) "in" ""))))
10892 (defun org-timestamp-change (n &optional what)
10893 "Change the date in the time stamp at point.
10894 The date will be changed by N times WHAT. WHAT can be `day', `month',
10895 `year', `minute', `second'. If WHAT is not given, the cursor position
10896 in the timestamp determines what will be changed."
10897 (let ((pos (point))
10898 with-hm inactive
10899 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10900 org-ts-what
10901 extra rem
10902 ts time time0)
10903 (if (not (org-at-timestamp-p t))
10904 (error "Not at a timestamp"))
10905 (if (and (not what) (eq org-ts-what 'bracket))
10906 (org-toggle-timestamp-type)
10907 (if (and (not what) (not (eq org-ts-what 'day))
10908 org-display-custom-times
10909 (get-text-property (point) 'display)
10910 (not (get-text-property (1- (point)) 'display)))
10911 (setq org-ts-what 'day))
10912 (setq org-ts-what (or what org-ts-what)
10913 inactive (= (char-after (match-beginning 0)) ?\[)
10914 ts (match-string 0))
10915 (replace-match "")
10916 (if (string-match
10917 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10919 (setq extra (match-string 1 ts)))
10920 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10921 (setq with-hm t))
10922 (setq time0 (org-parse-time-string ts))
10923 (when (and (eq org-ts-what 'minute)
10924 (eq current-prefix-arg nil))
10925 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10926 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10927 (setcar (cdr time0) (+ (nth 1 time0)
10928 (if (> n 0) (- rem) (- dm rem))))))
10929 (setq time
10930 (encode-time (or (car time0) 0)
10931 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10932 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10933 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10934 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10935 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10936 (nthcdr 6 time0)))
10937 (when (integerp org-ts-what)
10938 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10939 (if (eq what 'calendar)
10940 (let ((cal-date (org-get-date-from-calendar)))
10941 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10942 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10943 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10944 (setcar time0 (or (car time0) 0))
10945 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10946 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10947 (setq time (apply 'encode-time time0))))
10948 (setq org-last-changed-timestamp
10949 (org-insert-time-stamp time with-hm inactive nil nil extra))
10950 (org-clock-update-time-maybe)
10951 (goto-char pos)
10952 ;; Try to recenter the calendar window, if any
10953 (if (and org-calendar-follow-timestamp-change
10954 (get-buffer-window "*Calendar*" t)
10955 (memq org-ts-what '(day month year)))
10956 (org-recenter-calendar (time-to-days time))))))
10958 (defun org-modify-ts-extra (s pos n dm)
10959 "Change the different parts of the lead-time and repeat fields in timestamp."
10960 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10961 ng h m new rem)
10962 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10963 (cond
10964 ((or (org-pos-in-match-range pos 2)
10965 (org-pos-in-match-range pos 3))
10966 (setq m (string-to-number (match-string 3 s))
10967 h (string-to-number (match-string 2 s)))
10968 (if (org-pos-in-match-range pos 2)
10969 (setq h (+ h n))
10970 (setq n (* dm (org-no-warnings (signum n))))
10971 (when (not (= 0 (setq rem (% m dm))))
10972 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10973 (setq m (+ m n)))
10974 (if (< m 0) (setq m (+ m 60) h (1- h)))
10975 (if (> m 59) (setq m (- m 60) h (1+ h)))
10976 (setq h (min 24 (max 0 h)))
10977 (setq ng 1 new (format "-%02d:%02d" h m)))
10978 ((org-pos-in-match-range pos 6)
10979 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10980 ((org-pos-in-match-range pos 5)
10981 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10983 ((org-pos-in-match-range pos 9)
10984 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10985 ((org-pos-in-match-range pos 8)
10986 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10988 (when ng
10989 (setq s (concat
10990 (substring s 0 (match-beginning ng))
10992 (substring s (match-end ng))))))
10995 (defun org-recenter-calendar (date)
10996 "If the calendar is visible, recenter it to DATE."
10997 (let* ((win (selected-window))
10998 (cwin (get-buffer-window "*Calendar*" t))
10999 (calendar-move-hook nil))
11000 (when cwin
11001 (select-window cwin)
11002 (calendar-goto-date (if (listp date) date
11003 (calendar-gregorian-from-absolute date)))
11004 (select-window win))))
11006 (defun org-goto-calendar (&optional arg)
11007 "Go to the Emacs calendar at the current date.
11008 If there is a time stamp in the current line, go to that date.
11009 A prefix ARG can be used to force the current date."
11010 (interactive "P")
11011 (let ((tsr org-ts-regexp) diff
11012 (calendar-move-hook nil)
11013 (calendar-view-holidays-initially-flag nil)
11014 (view-calendar-holidays-initially nil)
11015 (calendar-view-diary-initially-flag nil)
11016 (view-diary-entries-initially nil))
11017 (if (or (org-at-timestamp-p)
11018 (save-excursion
11019 (beginning-of-line 1)
11020 (looking-at (concat ".*" tsr))))
11021 (let ((d1 (time-to-days (current-time)))
11022 (d2 (time-to-days
11023 (org-time-string-to-time (match-string 1)))))
11024 (setq diff (- d2 d1))))
11025 (calendar)
11026 (calendar-goto-today)
11027 (if (and diff (not arg)) (calendar-forward-day diff))))
11029 (defun org-get-date-from-calendar ()
11030 "Return a list (month day year) of date at point in calendar."
11031 (with-current-buffer "*Calendar*"
11032 (save-match-data
11033 (calendar-cursor-to-date))))
11035 (defun org-date-from-calendar ()
11036 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11037 If there is already a time stamp at the cursor position, update it."
11038 (interactive)
11039 (if (org-at-timestamp-p t)
11040 (org-timestamp-change 0 'calendar)
11041 (let ((cal-date (org-get-date-from-calendar)))
11042 (org-insert-time-stamp
11043 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11045 (defun org-minutes-to-hh:mm-string (m)
11046 "Compute H:MM from a number of minutes."
11047 (let ((h (/ m 60)))
11048 (setq m (- m (* 60 h)))
11049 (format "%d:%02d" h m)))
11051 (defun org-hh:mm-string-to-minutes (s)
11052 "Convert a string H:MM to a number of minutes."
11053 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11054 (+ (* (string-to-number (match-string 1 s)) 60)
11055 (string-to-number (match-string 2 s)))
11058 ;;;; Agenda files
11060 ;;;###autoload
11061 (defun org-iswitchb (&optional arg)
11062 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11063 With a prefix argument, restrict available to files.
11064 With two prefix arguments, restrict available buffers to agenda files.
11066 Due to some yet unresolved reason, global function
11067 `iswitchb-mode' needs to be active for this function to work."
11068 (interactive "P")
11069 (require 'iswitchb)
11070 (let ((enabled iswitchb-mode) blist)
11071 (or enabled (iswitchb-mode 1))
11072 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11073 ((equal arg '(16)) (org-buffer-list 'agenda))
11074 (t (org-buffer-list))))
11075 (unwind-protect
11076 (let ((iswitchb-make-buflist-hook
11077 (lambda ()
11078 (setq iswitchb-temp-buflist
11079 (mapcar 'buffer-name blist)))))
11080 (switch-to-buffer
11081 (iswitchb-read-buffer
11082 "Switch-to: " nil t))
11083 (or enabled (iswitchb-mode -1))))))
11085 (defun org-buffer-list (&optional predicate tmp)
11086 "Return a list of Org buffers.
11087 PREDICATE can be either 'export, 'files or 'agenda.
11089 'export restrict the list to Export buffers.
11090 'files restrict the list to buffers visiting Org files.
11091 'agenda restrict the list to buffers visiting agenda files.
11093 If TMP is non-nil, don't include temporary buffers."
11094 (let (filter blist)
11095 (setq filter
11096 (cond ((eq predicate 'files) "\.org$")
11097 ((eq predicate 'export) "\*Org .*Export")
11098 (t "\*Org \\|\.org$")))
11099 (setq blist
11100 (mapcar
11101 (lambda(b)
11102 (let ((bname (buffer-name b))
11103 (bfile (buffer-file-name b)))
11104 (if (and (string-match filter bname)
11105 (if (eq predicate 'agenda)
11106 (member bfile
11107 (mapcar (lambda(f) (file-truename f))
11108 org-agenda-files)) t)
11109 (if tmp (not (string-match "tmp" bname)) t)) b)))
11110 (buffer-list)))
11111 (delete nil blist)))
11113 (defun org-agenda-files (&optional unrestricted ext)
11114 "Get the list of agenda files.
11115 Optional UNRESTRICTED means return the full list even if a restriction
11116 is currently in place.
11117 When EXT is non-nil, try to add all files that are created by adding EXT
11118 to the file nemes. Basically, this is a way to add the archive files
11119 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11120 a string, \"_archive\" will be used."
11121 (let ((files
11122 (cond
11123 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11124 ((stringp org-agenda-files) (org-read-agenda-file-list))
11125 ((listp org-agenda-files) org-agenda-files)
11126 (t (error "Invalid value of `org-agenda-files'")))))
11127 (setq files (apply 'append
11128 (mapcar (lambda (f)
11129 (if (file-directory-p f)
11130 (directory-files
11131 f t org-agenda-file-regexp)
11132 (list f)))
11133 files)))
11134 (when org-agenda-skip-unavailable-files
11135 (setq files (delq nil
11136 (mapcar (function
11137 (lambda (file)
11138 (and (file-readable-p file) file)))
11139 files))))
11140 (when ext
11141 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11142 ext "_archive"))
11143 (setq files (apply 'append
11144 (mapcar
11145 (lambda (f)
11146 (if (file-exists-p (concat f ext))
11147 (list f (concat f ext))
11148 (list f)))
11149 files))))
11150 files))
11152 (defun org-edit-agenda-file-list ()
11153 "Edit the list of agenda files.
11154 Depending on setup, this either uses customize to edit the variable
11155 `org-agenda-files', or it visits the file that is holding the list. In the
11156 latter case, the buffer is set up in a way that saving it automatically kills
11157 the buffer and restores the previous window configuration."
11158 (interactive)
11159 (if (stringp org-agenda-files)
11160 (let ((cw (current-window-configuration)))
11161 (find-file org-agenda-files)
11162 (org-set-local 'org-window-configuration cw)
11163 (org-add-hook 'after-save-hook
11164 (lambda ()
11165 (set-window-configuration
11166 (prog1 org-window-configuration
11167 (kill-buffer (current-buffer))))
11168 (org-install-agenda-files-menu)
11169 (message "New agenda file list installed"))
11170 nil 'local)
11171 (message "%s" (substitute-command-keys
11172 "Edit list and finish with \\[save-buffer]")))
11173 (customize-variable 'org-agenda-files)))
11175 (defun org-store-new-agenda-file-list (list)
11176 "Set new value for the agenda file list and save it correcly."
11177 (if (stringp org-agenda-files)
11178 (let ((f org-agenda-files) b)
11179 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11180 (with-temp-file f
11181 (insert (mapconcat 'identity list "\n") "\n")))
11182 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11183 (setq org-agenda-files list)
11184 (customize-save-variable 'org-agenda-files org-agenda-files))))
11186 (defun org-read-agenda-file-list ()
11187 "Read the list of agenda files from a file."
11188 (when (file-directory-p org-agenda-files)
11189 (error "`org-agenda-files' cannot be a single directory"))
11190 (when (stringp org-agenda-files)
11191 (with-temp-buffer
11192 (insert-file-contents org-agenda-files)
11193 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11196 ;;;###autoload
11197 (defun org-cycle-agenda-files ()
11198 "Cycle through the files in `org-agenda-files'.
11199 If the current buffer visits an agenda file, find the next one in the list.
11200 If the current buffer does not, find the first agenda file."
11201 (interactive)
11202 (let* ((fs (org-agenda-files t))
11203 (files (append fs (list (car fs))))
11204 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11205 file)
11206 (unless files (error "No agenda files"))
11207 (catch 'exit
11208 (while (setq file (pop files))
11209 (if (equal (file-truename file) tcf)
11210 (when (car files)
11211 (find-file (car files))
11212 (throw 'exit t))))
11213 (find-file (car fs)))
11214 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11216 (defun org-agenda-file-to-front (&optional to-end)
11217 "Move/add the current file to the top of the agenda file list.
11218 If the file is not present in the list, it is added to the front. If it is
11219 present, it is moved there. With optional argument TO-END, add/move to the
11220 end of the list."
11221 (interactive "P")
11222 (let ((org-agenda-skip-unavailable-files nil)
11223 (file-alist (mapcar (lambda (x)
11224 (cons (file-truename x) x))
11225 (org-agenda-files t)))
11226 (ctf (file-truename buffer-file-name))
11227 x had)
11228 (setq x (assoc ctf file-alist) had x)
11230 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11231 (if to-end
11232 (setq file-alist (append (delq x file-alist) (list x)))
11233 (setq file-alist (cons x (delq x file-alist))))
11234 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11235 (org-install-agenda-files-menu)
11236 (message "File %s to %s of agenda file list"
11237 (if had "moved" "added") (if to-end "end" "front"))))
11239 (defun org-remove-file (&optional file)
11240 "Remove current file from the list of files in variable `org-agenda-files'.
11241 These are the files which are being checked for agenda entries.
11242 Optional argument FILE means, use this file instead of the current."
11243 (interactive)
11244 (let* ((org-agenda-skip-unavailable-files nil)
11245 (file (or file buffer-file-name))
11246 (true-file (file-truename file))
11247 (afile (abbreviate-file-name file))
11248 (files (delq nil (mapcar
11249 (lambda (x)
11250 (if (equal true-file
11251 (file-truename x))
11252 nil x))
11253 (org-agenda-files t)))))
11254 (if (not (= (length files) (length (org-agenda-files t))))
11255 (progn
11256 (org-store-new-agenda-file-list files)
11257 (org-install-agenda-files-menu)
11258 (message "Removed file: %s" afile))
11259 (message "File was not in list: %s (not removed)" afile))))
11261 (defun org-file-menu-entry (file)
11262 (vector file (list 'find-file file) t))
11264 (defun org-check-agenda-file (file)
11265 "Make sure FILE exists. If not, ask user what to do."
11266 (when (not (file-exists-p file))
11267 (message "non-existent file %s. [R]emove from list or [A]bort?"
11268 (abbreviate-file-name file))
11269 (let ((r (downcase (read-char-exclusive))))
11270 (cond
11271 ((equal r ?r)
11272 (org-remove-file file)
11273 (throw 'nextfile t))
11274 (t (error "Abort"))))))
11276 (defun org-get-agenda-file-buffer (file)
11277 "Get a buffer visiting FILE. If the buffer needs to be created, add
11278 it to the list of buffers which might be released later."
11279 (let ((buf (org-find-base-buffer-visiting file)))
11280 (if buf
11281 buf ; just return it
11282 ;; Make a new buffer and remember it
11283 (setq buf (find-file-noselect file))
11284 (if buf (push buf org-agenda-new-buffers))
11285 buf)))
11287 (defun org-release-buffers (blist)
11288 "Release all buffers in list, asking the user for confirmation when needed.
11289 When a buffer is unmodified, it is just killed. When modified, it is saved
11290 \(if the user agrees) and then killed."
11291 (let (buf file)
11292 (while (setq buf (pop blist))
11293 (setq file (buffer-file-name buf))
11294 (when (and (buffer-modified-p buf)
11295 file
11296 (y-or-n-p (format "Save file %s? " file)))
11297 (with-current-buffer buf (save-buffer)))
11298 (kill-buffer buf))))
11300 (defun org-prepare-agenda-buffers (files)
11301 "Create buffers for all agenda files, protect archived trees and comments."
11302 (interactive)
11303 (let ((pa '(:org-archived t))
11304 (pc '(:org-comment t))
11305 (pall '(:org-archived t :org-comment t))
11306 (inhibit-read-only t)
11307 (rea (concat ":" org-archive-tag ":"))
11308 bmp file re)
11309 (save-excursion
11310 (save-restriction
11311 (while (setq file (pop files))
11312 (if (bufferp file)
11313 (set-buffer file)
11314 (org-check-agenda-file file)
11315 (set-buffer (org-get-agenda-file-buffer file)))
11316 (widen)
11317 (setq bmp (buffer-modified-p))
11318 (org-refresh-category-properties)
11319 (setq org-todo-keywords-for-agenda
11320 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11321 (setq org-done-keywords-for-agenda
11322 (append org-done-keywords-for-agenda org-done-keywords))
11323 (save-excursion
11324 (remove-text-properties (point-min) (point-max) pall)
11325 (when org-agenda-skip-archived-trees
11326 (goto-char (point-min))
11327 (while (re-search-forward rea nil t)
11328 (if (org-on-heading-p t)
11329 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11330 (goto-char (point-min))
11331 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11332 (while (re-search-forward re nil t)
11333 (add-text-properties
11334 (match-beginning 0) (org-end-of-subtree t) pc)))
11335 (set-buffer-modified-p bmp))))))
11337 ;;;; Embedded LaTeX
11339 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11340 "Keymap for the minor `org-cdlatex-mode'.")
11342 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11343 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11344 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11345 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11346 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11348 (defvar org-cdlatex-texmathp-advice-is-done nil
11349 "Flag remembering if we have applied the advice to texmathp already.")
11351 (define-minor-mode org-cdlatex-mode
11352 "Toggle the minor `org-cdlatex-mode'.
11353 This mode supports entering LaTeX environment and math in LaTeX fragments
11354 in Org-mode.
11355 \\{org-cdlatex-mode-map}"
11356 nil " OCDL" nil
11357 (when org-cdlatex-mode (require 'cdlatex))
11358 (unless org-cdlatex-texmathp-advice-is-done
11359 (setq org-cdlatex-texmathp-advice-is-done t)
11360 (defadvice texmathp (around org-math-always-on activate)
11361 "Always return t in org-mode buffers.
11362 This is because we want to insert math symbols without dollars even outside
11363 the LaTeX math segments. If Orgmode thinks that point is actually inside
11364 en embedded LaTeX fragement, let texmathp do its job.
11365 \\[org-cdlatex-mode-map]"
11366 (interactive)
11367 (let (p)
11368 (cond
11369 ((not (org-mode-p)) ad-do-it)
11370 ((eq this-command 'cdlatex-math-symbol)
11371 (setq ad-return-value t
11372 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11374 (let ((p (org-inside-LaTeX-fragment-p)))
11375 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11376 (setq ad-return-value t
11377 texmathp-why '("Org-mode embedded math" . 0))
11378 (if p ad-do-it)))))))))
11380 (defun turn-on-org-cdlatex ()
11381 "Unconditionally turn on `org-cdlatex-mode'."
11382 (org-cdlatex-mode 1))
11384 (defun org-inside-LaTeX-fragment-p ()
11385 "Test if point is inside a LaTeX fragment.
11386 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11387 sequence appearing also before point.
11388 Even though the matchers for math are configurable, this function assumes
11389 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11390 delimiters are skipped when they have been removed by customization.
11391 The return value is nil, or a cons cell with the delimiter and
11392 and the position of this delimiter.
11394 This function does a reasonably good job, but can locally be fooled by
11395 for example currency specifications. For example it will assume being in
11396 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11397 fragments that are properly closed, but during editing, we have to live
11398 with the uncertainty caused by missing closing delimiters. This function
11399 looks only before point, not after."
11400 (catch 'exit
11401 (let ((pos (point))
11402 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11403 (lim (progn
11404 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11405 (point)))
11406 dd-on str (start 0) m re)
11407 (goto-char pos)
11408 (when dodollar
11409 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11410 re (nth 1 (assoc "$" org-latex-regexps)))
11411 (while (string-match re str start)
11412 (cond
11413 ((= (match-end 0) (length str))
11414 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11415 ((= (match-end 0) (- (length str) 5))
11416 (throw 'exit nil))
11417 (t (setq start (match-end 0))))))
11418 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11419 (goto-char pos)
11420 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11421 (and (match-beginning 2) (throw 'exit nil))
11422 ;; count $$
11423 (while (re-search-backward "\\$\\$" lim t)
11424 (setq dd-on (not dd-on)))
11425 (goto-char pos)
11426 (if dd-on (cons "$$" m))))))
11429 (defun org-try-cdlatex-tab ()
11430 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11431 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11432 - inside a LaTeX fragment, or
11433 - after the first word in a line, where an abbreviation expansion could
11434 insert a LaTeX environment."
11435 (when org-cdlatex-mode
11436 (cond
11437 ((save-excursion
11438 (skip-chars-backward "a-zA-Z0-9*")
11439 (skip-chars-backward " \t")
11440 (bolp))
11441 (cdlatex-tab) t)
11442 ((org-inside-LaTeX-fragment-p)
11443 (cdlatex-tab) t)
11444 (t nil))))
11446 (defun org-cdlatex-underscore-caret (&optional arg)
11447 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11448 Revert to the normal definition outside of these fragments."
11449 (interactive "P")
11450 (if (org-inside-LaTeX-fragment-p)
11451 (call-interactively 'cdlatex-sub-superscript)
11452 (let (org-cdlatex-mode)
11453 (call-interactively (key-binding (vector last-input-event))))))
11455 (defun org-cdlatex-math-modify (&optional arg)
11456 "Execute `cdlatex-math-modify' in LaTeX fragments.
11457 Revert to the normal definition outside of these fragments."
11458 (interactive "P")
11459 (if (org-inside-LaTeX-fragment-p)
11460 (call-interactively 'cdlatex-math-modify)
11461 (let (org-cdlatex-mode)
11462 (call-interactively (key-binding (vector last-input-event))))))
11464 (defvar org-latex-fragment-image-overlays nil
11465 "List of overlays carrying the images of latex fragments.")
11466 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11468 (defun org-remove-latex-fragment-image-overlays ()
11469 "Remove all overlays with LaTeX fragment images in current buffer."
11470 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11471 (setq org-latex-fragment-image-overlays nil))
11473 (defun org-preview-latex-fragment (&optional subtree)
11474 "Preview the LaTeX fragment at point, or all locally or globally.
11475 If the cursor is in a LaTeX fragment, create the image and overlay
11476 it over the source code. If there is no fragment at point, display
11477 all fragments in the current text, from one headline to the next. With
11478 prefix SUBTREE, display all fragments in the current subtree. With a
11479 double prefix `C-u C-u', or when the cursor is before the first headline,
11480 display all fragments in the buffer.
11481 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11482 (interactive "P")
11483 (org-remove-latex-fragment-image-overlays)
11484 (save-excursion
11485 (save-restriction
11486 (let (beg end at msg)
11487 (cond
11488 ((or (equal subtree '(16))
11489 (not (save-excursion
11490 (re-search-backward (concat "^" outline-regexp) nil t))))
11491 (setq beg (point-min) end (point-max)
11492 msg "Creating images for buffer...%s"))
11493 ((equal subtree '(4))
11494 (org-back-to-heading)
11495 (setq beg (point) end (org-end-of-subtree t)
11496 msg "Creating images for subtree...%s"))
11498 (if (setq at (org-inside-LaTeX-fragment-p))
11499 (goto-char (max (point-min) (- (cdr at) 2)))
11500 (org-back-to-heading))
11501 (setq beg (point) end (progn (outline-next-heading) (point))
11502 msg (if at "Creating image...%s"
11503 "Creating images for entry...%s"))))
11504 (message msg "")
11505 (narrow-to-region beg end)
11506 (goto-char beg)
11507 (org-format-latex
11508 (concat "ltxpng/" (file-name-sans-extension
11509 (file-name-nondirectory
11510 buffer-file-name)))
11511 default-directory 'overlays msg at 'forbuffer)
11512 (message msg "done. Use `C-c C-c' to remove images.")))))
11514 (defvar org-latex-regexps
11515 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11516 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11517 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11518 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11519 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11520 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11521 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11522 "Regular expressions for matching embedded LaTeX.")
11524 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11525 "Replace LaTeX fragments with links to an image, and produce images."
11526 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11527 (let* ((prefixnodir (file-name-nondirectory prefix))
11528 (absprefix (expand-file-name prefix dir))
11529 (todir (file-name-directory absprefix))
11530 (opt org-format-latex-options)
11531 (matchers (plist-get opt :matchers))
11532 (re-list org-latex-regexps)
11533 (cnt 0) txt link beg end re e checkdir
11534 m n block linkfile movefile ov)
11535 ;; Check if there are old images files with this prefix, and remove them
11536 (when (file-directory-p todir)
11537 (mapc 'delete-file
11538 (directory-files
11539 todir 'full
11540 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11541 ;; Check the different regular expressions
11542 (while (setq e (pop re-list))
11543 (setq m (car e) re (nth 1 e) n (nth 2 e)
11544 block (if (nth 3 e) "\n\n" ""))
11545 (when (member m matchers)
11546 (goto-char (point-min))
11547 (while (re-search-forward re nil t)
11548 (when (or (not at) (equal (cdr at) (match-beginning n)))
11549 (setq txt (match-string n)
11550 beg (match-beginning n) end (match-end n)
11551 cnt (1+ cnt)
11552 linkfile (format "%s_%04d.png" prefix cnt)
11553 movefile (format "%s_%04d.png" absprefix cnt)
11554 link (concat block "[[file:" linkfile "]]" block))
11555 (if msg (message msg cnt))
11556 (goto-char beg)
11557 (unless checkdir ; make sure the directory exists
11558 (setq checkdir t)
11559 (or (file-directory-p todir) (make-directory todir)))
11560 (org-create-formula-image
11561 txt movefile opt forbuffer)
11562 (if overlays
11563 (progn
11564 (setq ov (org-make-overlay beg end))
11565 (if (featurep 'xemacs)
11566 (progn
11567 (org-overlay-put ov 'invisible t)
11568 (org-overlay-put
11569 ov 'end-glyph
11570 (make-glyph (vector 'png :file movefile))))
11571 (org-overlay-put
11572 ov 'display
11573 (list 'image :type 'png :file movefile :ascent 'center)))
11574 (push ov org-latex-fragment-image-overlays)
11575 (goto-char end))
11576 (delete-region beg end)
11577 (insert link))))))))
11579 ;; This function borrows from Ganesh Swami's latex2png.el
11580 (defun org-create-formula-image (string tofile options buffer)
11581 (let* ((tmpdir (if (featurep 'xemacs)
11582 (temp-directory)
11583 temporary-file-directory))
11584 (texfilebase (make-temp-name
11585 (expand-file-name "orgtex" tmpdir)))
11586 (texfile (concat texfilebase ".tex"))
11587 (dvifile (concat texfilebase ".dvi"))
11588 (pngfile (concat texfilebase ".png"))
11589 (fnh (if (featurep 'xemacs)
11590 (font-height (get-face-font 'default))
11591 (face-attribute 'default :height nil)))
11592 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11593 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11594 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11595 "Black"))
11596 (bg (or (plist-get options (if buffer :background :html-background))
11597 "Transparent")))
11598 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11599 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11600 (with-temp-file texfile
11601 (insert org-format-latex-header
11602 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11603 (let ((dir default-directory))
11604 (condition-case nil
11605 (progn
11606 (cd tmpdir)
11607 (call-process "latex" nil nil nil texfile))
11608 (error nil))
11609 (cd dir))
11610 (if (not (file-exists-p dvifile))
11611 (progn (message "Failed to create dvi file from %s" texfile) nil)
11612 (call-process "dvipng" nil nil nil
11613 "-E" "-fg" fg "-bg" bg
11614 "-D" dpi
11615 ;;"-x" scale "-y" scale
11616 "-T" "tight"
11617 "-o" pngfile
11618 dvifile)
11619 (if (not (file-exists-p pngfile))
11620 (progn (message "Failed to create png file from %s" texfile) nil)
11621 ;; Use the requested file name and clean up
11622 (copy-file pngfile tofile 'replace)
11623 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11624 (delete-file (concat texfilebase e)))
11625 pngfile))))
11627 (defun org-dvipng-color (attr)
11628 "Return an rgb color specification for dvipng."
11629 (apply 'format "rgb %s %s %s"
11630 (mapcar 'org-normalize-color
11631 (color-values (face-attribute 'default attr nil)))))
11633 (defun org-normalize-color (value)
11634 "Return string to be used as color value for an RGB component."
11635 (format "%g" (/ value 65535.0)))
11638 ;;;; Key bindings
11640 ;; Make `C-c C-x' a prefix key
11641 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11643 ;; TAB key with modifiers
11644 (org-defkey org-mode-map "\C-i" 'org-cycle)
11645 (org-defkey org-mode-map [(tab)] 'org-cycle)
11646 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11647 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11648 (org-defkey org-mode-map "\M-\t" 'org-complete)
11649 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11650 ;; The following line is necessary under Suse GNU/Linux
11651 (unless (featurep 'xemacs)
11652 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11653 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11654 (define-key org-mode-map [backtab] 'org-shifttab)
11656 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11657 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11658 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11660 ;; Cursor keys with modifiers
11661 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11662 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11663 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11664 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11666 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11667 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11668 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11669 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11671 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11672 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11673 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11674 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11676 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11677 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11679 ;;; Extra keys for tty access.
11680 ;; We only set them when really needed because otherwise the
11681 ;; menus don't show the simple keys
11683 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11684 (not window-system))
11685 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11686 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11687 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11688 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11689 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11690 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11691 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11692 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11693 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11694 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11695 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11696 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11697 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11698 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11699 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11700 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11701 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11702 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11703 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11704 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11705 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11706 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11708 ;; All the other keys
11710 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11711 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11712 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11713 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11714 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11715 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11716 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11717 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11718 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11719 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11720 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11721 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11722 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11723 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11724 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11725 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11726 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11727 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11728 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11729 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11730 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11731 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11732 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11733 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11734 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11735 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11736 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11737 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11738 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11739 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11740 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11741 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11742 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11743 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11744 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11745 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11746 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11747 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11748 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11749 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11750 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11751 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11752 (org-defkey org-mode-map "\C-c^" 'org-sort)
11753 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11754 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11755 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11756 (org-defkey org-mode-map "\C-m" 'org-return)
11757 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11758 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11759 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11760 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11761 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11762 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11763 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11764 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11765 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11766 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11767 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11768 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11769 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11770 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11771 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11772 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11774 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11775 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11776 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11777 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11779 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11780 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11781 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11782 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11783 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11784 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11785 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11786 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11787 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11788 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11789 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11790 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11792 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11794 (when (featurep 'xemacs)
11795 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11797 (defvar org-table-auto-blank-field) ; defined in org-table.el
11798 (defun org-self-insert-command (N)
11799 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11800 If the cursor is in a table looking at whitespace, the whitespace is
11801 overwritten, and the table is not marked as requiring realignment."
11802 (interactive "p")
11803 (if (and (org-table-p)
11804 (progn
11805 ;; check if we blank the field, and if that triggers align
11806 (and (featurep 'org-table) org-table-auto-blank-field
11807 (member last-command
11808 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11809 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11810 ;; got extra space, this field does not determine column width
11811 (let (org-table-may-need-update) (org-table-blank-field))
11812 ;; no extra space, this field may determine column width
11813 (org-table-blank-field)))
11815 (eq N 1)
11816 (looking-at "[^|\n]* |"))
11817 (let (org-table-may-need-update)
11818 (goto-char (1- (match-end 0)))
11819 (delete-backward-char 1)
11820 (goto-char (match-beginning 0))
11821 (self-insert-command N))
11822 (setq org-table-may-need-update t)
11823 (self-insert-command N)
11824 (org-fix-tags-on-the-fly)))
11826 (defun org-fix-tags-on-the-fly ()
11827 (when (and (equal (char-after (point-at-bol)) ?*)
11828 (org-on-heading-p))
11829 (org-align-tags-here org-tags-column)))
11831 (defun org-delete-backward-char (N)
11832 "Like `delete-backward-char', insert whitespace at field end in tables.
11833 When deleting backwards, in tables this function will insert whitespace in
11834 front of the next \"|\" separator, to keep the table aligned. The table will
11835 still be marked for re-alignment if the field did fill the entire column,
11836 because, in this case the deletion might narrow the column."
11837 (interactive "p")
11838 (if (and (org-table-p)
11839 (eq N 1)
11840 (string-match "|" (buffer-substring (point-at-bol) (point)))
11841 (looking-at ".*?|"))
11842 (let ((pos (point))
11843 (noalign (looking-at "[^|\n\r]* |"))
11844 (c org-table-may-need-update))
11845 (backward-delete-char N)
11846 (skip-chars-forward "^|")
11847 (insert " ")
11848 (goto-char (1- pos))
11849 ;; noalign: if there were two spaces at the end, this field
11850 ;; does not determine the width of the column.
11851 (if noalign (setq org-table-may-need-update c)))
11852 (backward-delete-char N)
11853 (org-fix-tags-on-the-fly)))
11855 (defun org-delete-char (N)
11856 "Like `delete-char', but insert whitespace at field end in tables.
11857 When deleting characters, in tables this function will insert whitespace in
11858 front of the next \"|\" separator, to keep the table aligned. The table will
11859 still be marked for re-alignment if the field did fill the entire column,
11860 because, in this case the deletion might narrow the column."
11861 (interactive "p")
11862 (if (and (org-table-p)
11863 (not (bolp))
11864 (not (= (char-after) ?|))
11865 (eq N 1))
11866 (if (looking-at ".*?|")
11867 (let ((pos (point))
11868 (noalign (looking-at "[^|\n\r]* |"))
11869 (c org-table-may-need-update))
11870 (replace-match (concat
11871 (substring (match-string 0) 1 -1)
11872 " |"))
11873 (goto-char pos)
11874 ;; noalign: if there were two spaces at the end, this field
11875 ;; does not determine the width of the column.
11876 (if noalign (setq org-table-may-need-update c)))
11877 (delete-char N))
11878 (delete-char N)
11879 (org-fix-tags-on-the-fly)))
11881 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11882 (put 'org-self-insert-command 'delete-selection t)
11883 (put 'orgtbl-self-insert-command 'delete-selection t)
11884 (put 'org-delete-char 'delete-selection 'supersede)
11885 (put 'org-delete-backward-char 'delete-selection 'supersede)
11887 ;; Make `flyspell-mode' delay after some commands
11888 (put 'org-self-insert-command 'flyspell-delayed t)
11889 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11890 (put 'org-delete-char 'flyspell-delayed t)
11891 (put 'org-delete-backward-char 'flyspell-delayed t)
11893 ;; Make pabbrev-mode expand after org-mode commands
11894 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11895 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11897 ;; How to do this: Measure non-white length of current string
11898 ;; If equal to column width, we should realign.
11900 (defun org-remap (map &rest commands)
11901 "In MAP, remap the functions given in COMMANDS.
11902 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11903 (let (new old)
11904 (while commands
11905 (setq old (pop commands) new (pop commands))
11906 (if (fboundp 'command-remapping)
11907 (org-defkey map (vector 'remap old) new)
11908 (substitute-key-definition old new map global-map)))))
11910 (when (eq org-enable-table-editor 'optimized)
11911 ;; If the user wants maximum table support, we need to hijack
11912 ;; some standard editing functions
11913 (org-remap org-mode-map
11914 'self-insert-command 'org-self-insert-command
11915 'delete-char 'org-delete-char
11916 'delete-backward-char 'org-delete-backward-char)
11917 (org-defkey org-mode-map "|" 'org-force-self-insert))
11919 (defun org-shiftcursor-error ()
11920 "Throw an error because Shift-Cursor command was applied in wrong context."
11921 (error "This command is active in special context like tables, headlines or timestamps"))
11923 (defun org-shifttab (&optional arg)
11924 "Global visibility cycling or move to previous table field.
11925 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11926 on context.
11927 See the individual commands for more information."
11928 (interactive "P")
11929 (cond
11930 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11931 (arg (message "Content view to level: ")
11932 (org-content (prefix-numeric-value arg))
11933 (setq org-cycle-global-status 'overview))
11934 (t (call-interactively 'org-global-cycle))))
11936 (defun org-shiftmetaleft ()
11937 "Promote subtree or delete table column.
11938 Calls `org-promote-subtree', `org-outdent-item',
11939 or `org-table-delete-column', depending on context.
11940 See the individual commands for more information."
11941 (interactive)
11942 (cond
11943 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11944 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11945 ((org-at-item-p) (call-interactively 'org-outdent-item))
11946 (t (org-shiftcursor-error))))
11948 (defun org-shiftmetaright ()
11949 "Demote subtree or insert table column.
11950 Calls `org-demote-subtree', `org-indent-item',
11951 or `org-table-insert-column', depending on context.
11952 See the individual commands for more information."
11953 (interactive)
11954 (cond
11955 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11956 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11957 ((org-at-item-p) (call-interactively 'org-indent-item))
11958 (t (org-shiftcursor-error))))
11960 (defun org-shiftmetaup (&optional arg)
11961 "Move subtree up or kill table row.
11962 Calls `org-move-subtree-up' or `org-table-kill-row' or
11963 `org-move-item-up' depending on context. See the individual commands
11964 for more information."
11965 (interactive "P")
11966 (cond
11967 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11968 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11969 ((org-at-item-p) (call-interactively 'org-move-item-up))
11970 (t (org-shiftcursor-error))))
11971 (defun org-shiftmetadown (&optional arg)
11972 "Move subtree down or insert table row.
11973 Calls `org-move-subtree-down' or `org-table-insert-row' or
11974 `org-move-item-down', depending on context. See the individual
11975 commands for more information."
11976 (interactive "P")
11977 (cond
11978 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11979 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11980 ((org-at-item-p) (call-interactively 'org-move-item-down))
11981 (t (org-shiftcursor-error))))
11983 (defun org-metaleft (&optional arg)
11984 "Promote heading or move table column to left.
11985 Calls `org-do-promote' or `org-table-move-column', depending on context.
11986 With no specific context, calls the Emacs default `backward-word'.
11987 See the individual commands for more information."
11988 (interactive "P")
11989 (cond
11990 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11991 ((or (org-on-heading-p) (org-region-active-p))
11992 (call-interactively 'org-do-promote))
11993 ((org-at-item-p) (call-interactively 'org-outdent-item))
11994 (t (call-interactively 'backward-word))))
11996 (defun org-metaright (&optional arg)
11997 "Demote subtree or move table column to right.
11998 Calls `org-do-demote' or `org-table-move-column', depending on context.
11999 With no specific context, calls the Emacs default `forward-word'.
12000 See the individual commands for more information."
12001 (interactive "P")
12002 (cond
12003 ((org-at-table-p) (call-interactively 'org-table-move-column))
12004 ((or (org-on-heading-p) (org-region-active-p))
12005 (call-interactively 'org-do-demote))
12006 ((org-at-item-p) (call-interactively 'org-indent-item))
12007 (t (call-interactively 'forward-word))))
12009 (defun org-metaup (&optional arg)
12010 "Move subtree up or move table row up.
12011 Calls `org-move-subtree-up' or `org-table-move-row' or
12012 `org-move-item-up', depending on context. See the individual commands
12013 for more information."
12014 (interactive "P")
12015 (cond
12016 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12017 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12018 ((org-at-item-p) (call-interactively 'org-move-item-up))
12019 (t (transpose-lines 1) (beginning-of-line -1))))
12021 (defun org-metadown (&optional arg)
12022 "Move subtree down or move table row down.
12023 Calls `org-move-subtree-down' or `org-table-move-row' or
12024 `org-move-item-down', depending on context. See the individual
12025 commands for more information."
12026 (interactive "P")
12027 (cond
12028 ((org-at-table-p) (call-interactively 'org-table-move-row))
12029 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12030 ((org-at-item-p) (call-interactively 'org-move-item-down))
12031 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12033 (defun org-shiftup (&optional arg)
12034 "Increase item in timestamp or increase priority of current headline.
12035 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12036 depending on context. See the individual commands for more information."
12037 (interactive "P")
12038 (cond
12039 ((org-at-timestamp-p t)
12040 (call-interactively (if org-edit-timestamp-down-means-later
12041 'org-timestamp-down 'org-timestamp-up)))
12042 ((org-on-heading-p) (call-interactively 'org-priority-up))
12043 ((org-at-item-p) (call-interactively 'org-previous-item))
12044 ((org-clocktable-try-shift 'up arg))
12045 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12047 (defun org-shiftdown (&optional arg)
12048 "Decrease item in timestamp or decrease priority of current headline.
12049 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12050 depending on context. See the individual commands for more information."
12051 (interactive "P")
12052 (cond
12053 ((org-at-timestamp-p t)
12054 (call-interactively (if org-edit-timestamp-down-means-later
12055 'org-timestamp-up 'org-timestamp-down)))
12056 ((org-on-heading-p) (call-interactively 'org-priority-down))
12057 ((org-clocktable-try-shift 'down arg))
12058 (t (call-interactively 'org-next-item))))
12060 (defun org-shiftright (&optional arg)
12061 "Next TODO keyword or timestamp one day later, depending on context."
12062 (interactive "P")
12063 (cond
12064 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12065 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12066 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12067 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12068 ((org-clocktable-try-shift 'right arg))
12069 (t (org-shiftcursor-error))))
12071 (defun org-shiftleft (&optional arg)
12072 "Previous TODO keyword or timestamp one day earlier, depending on context."
12073 (interactive "P")
12074 (cond
12075 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12076 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12077 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12078 ((org-at-property-p)
12079 (call-interactively 'org-property-previous-allowed-value))
12080 ((org-clocktable-try-shift 'left arg))
12081 (t (org-shiftcursor-error))))
12083 (defun org-shiftcontrolright ()
12084 "Switch to next TODO set."
12085 (interactive)
12086 (cond
12087 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12088 (t (org-shiftcursor-error))))
12090 (defun org-shiftcontrolleft ()
12091 "Switch to previous TODO set."
12092 (interactive)
12093 (cond
12094 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12095 (t (org-shiftcursor-error))))
12097 (defun org-ctrl-c-ret ()
12098 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12099 (interactive)
12100 (cond
12101 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12102 (t (call-interactively 'org-insert-heading))))
12104 (defun org-copy-special ()
12105 "Copy region in table or copy current subtree.
12106 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12107 See the individual commands for more information."
12108 (interactive)
12109 (call-interactively
12110 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12112 (defun org-cut-special ()
12113 "Cut region in table or cut current subtree.
12114 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12115 See the individual commands for more information."
12116 (interactive)
12117 (call-interactively
12118 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12120 (defun org-paste-special (arg)
12121 "Paste rectangular region into table, or past subtree relative to level.
12122 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12123 See the individual commands for more information."
12124 (interactive "P")
12125 (if (org-at-table-p)
12126 (org-table-paste-rectangle)
12127 (org-paste-subtree arg)))
12129 (defun org-ctrl-c-ctrl-c (&optional arg)
12130 "Set tags in headline, or update according to changed information at point.
12132 This command does many different things, depending on context:
12134 - If the cursor is in a headline, prompt for tags and insert them
12135 into the current line, aligned to `org-tags-column'. When called
12136 with prefix arg, realign all tags in the current buffer.
12138 - If the cursor is in one of the special #+KEYWORD lines, this
12139 triggers scanning the buffer for these lines and updating the
12140 information.
12142 - If the cursor is inside a table, realign the table. This command
12143 works even if the automatic table editor has been turned off.
12145 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12146 the entire table.
12148 - If the cursor is a the beginning of a dynamic block, update it.
12150 - If the cursor is inside a table created by the table.el package,
12151 activate that table.
12153 - If the current buffer is a remember buffer, close note and file it.
12154 with a prefix argument, file it without further interaction to the default
12155 location.
12157 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12158 links in this buffer.
12160 - If the cursor is on a numbered item in a plain list, renumber the
12161 ordered list.
12163 - If the cursor is on a checkbox, toggle it."
12164 (interactive "P")
12165 (let ((org-enable-table-editor t))
12166 (cond
12167 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12168 org-occur-highlights
12169 org-latex-fragment-image-overlays)
12170 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12171 (org-remove-occur-highlights)
12172 (org-remove-latex-fragment-image-overlays)
12173 (message "Temporary highlights/overlays removed from current buffer"))
12174 ((and (local-variable-p 'org-finish-function (current-buffer))
12175 (fboundp org-finish-function))
12176 (funcall org-finish-function))
12177 ((org-at-property-p)
12178 (call-interactively 'org-property-action))
12179 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12180 ((org-on-heading-p) (call-interactively 'org-set-tags))
12181 ((org-at-table.el-p)
12182 (require 'table)
12183 (beginning-of-line 1)
12184 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12185 (call-interactively 'table-recognize-table))
12186 ((org-at-table-p)
12187 (org-table-maybe-eval-formula)
12188 (if arg
12189 (call-interactively 'org-table-recalculate)
12190 (org-table-maybe-recalculate-line))
12191 (call-interactively 'org-table-align))
12192 ((org-at-item-checkbox-p)
12193 (call-interactively 'org-toggle-checkbox))
12194 ((org-at-item-p)
12195 (call-interactively 'org-maybe-renumber-ordered-list))
12196 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12197 ;; Dynamic block
12198 (beginning-of-line 1)
12199 (org-update-dblock))
12200 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12201 (cond
12202 ((equal (match-string 1) "TBLFM")
12203 ;; Recalculate the table before this line
12204 (save-excursion
12205 (beginning-of-line 1)
12206 (skip-chars-backward " \r\n\t")
12207 (if (org-at-table-p)
12208 (org-call-with-arg 'org-table-recalculate t))))
12210 (call-interactively 'org-mode-restart))))
12211 (t (error "C-c C-c can do nothing useful at this location.")))))
12213 (defun org-mode-restart ()
12214 "Restart Org-mode, to scan again for special lines.
12215 Also updates the keyword regular expressions."
12216 (interactive)
12217 (let ((org-inhibit-startup t)) (org-mode))
12218 (message "Org-mode restarted to refresh keyword and special line setup"))
12220 (defun org-kill-note-or-show-branches ()
12221 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12222 (interactive)
12223 (if (not org-finish-function)
12224 (call-interactively 'show-branches)
12225 (let ((org-note-abort t))
12226 (funcall org-finish-function))))
12228 (defun org-return (&optional indent)
12229 "Goto next table row or insert a newline.
12230 Calls `org-table-next-row' or `newline', depending on context.
12231 See the individual commands for more information."
12232 (interactive)
12233 (cond
12234 ((bobp) (if indent (newline-and-indent) (newline)))
12235 ((and (org-at-heading-p)
12236 (looking-at
12237 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12238 (org-show-entry)
12239 (end-of-line 1)
12240 (newline))
12241 ((org-at-table-p)
12242 (org-table-justify-field-maybe)
12243 (call-interactively 'org-table-next-row))
12244 (t (if indent (newline-and-indent) (newline)))))
12246 (defun org-return-indent ()
12247 "Goto next table row or insert a newline and indent.
12248 Calls `org-table-next-row' or `newline-and-indent', depending on
12249 context. See the individual commands for more information."
12250 (interactive)
12251 (org-return t))
12253 (defun org-ctrl-c-star ()
12254 "Compute table, or change heading status of lines.
12255 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12256 depending on context. This will also turn a plain list item or a normal
12257 line into a subheading."
12258 (interactive)
12259 (cond
12260 ((org-at-table-p)
12261 (call-interactively 'org-table-recalculate))
12262 ((org-region-active-p)
12263 ;; Convert all lines in region to list items
12264 (call-interactively 'org-toggle-region-headings))
12265 ((org-on-heading-p)
12266 (org-toggle-region-headings (point-at-bol)
12267 (min (1+ (point-at-eol)) (point-max))))
12268 ((org-at-item-p)
12269 ;; Convert to heading
12270 (let ((level (save-match-data
12271 (save-excursion
12272 (condition-case nil
12273 (progn
12274 (org-back-to-heading t)
12275 (funcall outline-level))
12276 (error 0))))))
12277 (replace-match
12278 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12279 (t (org-toggle-region-headings (point-at-bol)
12280 (min (1+ (point-at-eol)) (point-max))))))
12282 (defun org-ctrl-c-minus ()
12283 "Insert separator line in table or modify bullet status of line.
12284 Also turns a plain line or a region of lines into list items.
12285 Calls `org-table-insert-hline', `org-toggle-region-items', or
12286 `org-cycle-list-bullet', depending on context."
12287 (interactive)
12288 (cond
12289 ((org-at-table-p)
12290 (call-interactively 'org-table-insert-hline))
12291 ((org-on-heading-p)
12292 ;; Convert to item
12293 (save-excursion
12294 (beginning-of-line 1)
12295 (if (looking-at "\\*+ ")
12296 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12297 ((org-region-active-p)
12298 ;; Convert all lines in region to list items
12299 (call-interactively 'org-toggle-region-items))
12300 ((org-in-item-p)
12301 (call-interactively 'org-cycle-list-bullet))
12302 (t (org-toggle-region-items (point-at-bol)
12303 (min (1+ (point-at-eol)) (point-max))))))
12305 (defun org-toggle-region-items (beg end)
12306 "Convert all lines in region to list items.
12307 If the first line is already an item, convert all list items in the region
12308 to normal lines."
12309 (interactive "r")
12310 (let (l2 l)
12311 (save-excursion
12312 (goto-char end)
12313 (setq l2 (org-current-line))
12314 (goto-char beg)
12315 (beginning-of-line 1)
12316 (setq l (1- (org-current-line)))
12317 (if (org-at-item-p)
12318 ;; We already have items, de-itemize
12319 (while (< (setq l (1+ l)) l2)
12320 (when (org-at-item-p)
12321 (goto-char (match-beginning 2))
12322 (delete-region (match-beginning 2) (match-end 2))
12323 (and (looking-at "[ \t]+") (replace-match "")))
12324 (beginning-of-line 2))
12325 (while (< (setq l (1+ l)) l2)
12326 (unless (org-at-item-p)
12327 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12328 (replace-match "\\1- \\2")))
12329 (beginning-of-line 2))))))
12331 (defun org-toggle-region-headings (beg end)
12332 "Convert all lines in region to list items.
12333 If the first line is already an item, convert all list items in the region
12334 to normal lines."
12335 (interactive "r")
12336 (let (l2 l)
12337 (save-excursion
12338 (goto-char end)
12339 (setq l2 (org-current-line))
12340 (goto-char beg)
12341 (beginning-of-line 1)
12342 (setq l (1- (org-current-line)))
12343 (if (org-on-heading-p)
12344 ;; We already have headlines, de-star them
12345 (while (< (setq l (1+ l)) l2)
12346 (when (org-on-heading-p t)
12347 (and (looking-at outline-regexp) (replace-match "")))
12348 (beginning-of-line 2))
12349 (let* ((stars (save-excursion
12350 (re-search-backward org-complex-heading-regexp nil t)
12351 (or (match-string 1) "*")))
12352 (add-stars (if org-odd-levels-only "**" "*"))
12353 (rpl (concat stars add-stars " \\2")))
12354 (while (< (setq l (1+ l)) l2)
12355 (unless (org-on-heading-p)
12356 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12357 (replace-match rpl)))
12358 (beginning-of-line 2)))))))
12360 (defun org-meta-return (&optional arg)
12361 "Insert a new heading or wrap a region in a table.
12362 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12363 See the individual commands for more information."
12364 (interactive "P")
12365 (cond
12366 ((org-at-table-p)
12367 (call-interactively 'org-table-wrap-region))
12368 (t (call-interactively 'org-insert-heading))))
12370 ;;; Menu entries
12372 ;; Define the Org-mode menus
12373 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12374 '("Tbl"
12375 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12376 ["Next Field" org-cycle (org-at-table-p)]
12377 ["Previous Field" org-shifttab (org-at-table-p)]
12378 ["Next Row" org-return (org-at-table-p)]
12379 "--"
12380 ["Blank Field" org-table-blank-field (org-at-table-p)]
12381 ["Edit Field" org-table-edit-field (org-at-table-p)]
12382 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12383 "--"
12384 ("Column"
12385 ["Move Column Left" org-metaleft (org-at-table-p)]
12386 ["Move Column Right" org-metaright (org-at-table-p)]
12387 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12388 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12389 ("Row"
12390 ["Move Row Up" org-metaup (org-at-table-p)]
12391 ["Move Row Down" org-metadown (org-at-table-p)]
12392 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12393 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12394 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12395 "--"
12396 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12397 ("Rectangle"
12398 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12399 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12400 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12401 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12402 "--"
12403 ("Calculate"
12404 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12405 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12406 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12407 "--"
12408 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12409 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12410 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12411 "--"
12412 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12413 "--"
12414 ["Sum Column/Rectangle" org-table-sum
12415 (or (org-at-table-p) (org-region-active-p))]
12416 ["Which Column?" org-table-current-column (org-at-table-p)])
12417 ["Debug Formulas"
12418 org-table-toggle-formula-debugger
12419 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12420 ["Show Col/Row Numbers"
12421 org-table-toggle-coordinate-overlays
12422 :style toggle
12423 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12424 "--"
12425 ["Create" org-table-create (and (not (org-at-table-p))
12426 org-enable-table-editor)]
12427 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12428 ["Import from File" org-table-import (not (org-at-table-p))]
12429 ["Export to File" org-table-export (org-at-table-p)]
12430 "--"
12431 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12433 (easy-menu-define org-org-menu org-mode-map "Org menu"
12434 '("Org"
12435 ("Show/Hide"
12436 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12437 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12438 ["Sparse Tree..." org-sparse-tree t]
12439 ["Reveal Context" org-reveal t]
12440 ["Show All" show-all t]
12441 "--"
12442 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12443 "--"
12444 ["New Heading" org-insert-heading t]
12445 ("Navigate Headings"
12446 ["Up" outline-up-heading t]
12447 ["Next" outline-next-visible-heading t]
12448 ["Previous" outline-previous-visible-heading t]
12449 ["Next Same Level" outline-forward-same-level t]
12450 ["Previous Same Level" outline-backward-same-level t]
12451 "--"
12452 ["Jump" org-goto t])
12453 ("Edit Structure"
12454 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12455 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12456 "--"
12457 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12458 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12459 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12460 "--"
12461 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12462 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12463 ["Demote Heading" org-metaright (not (org-at-table-p))]
12464 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12465 "--"
12466 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12467 "--"
12468 ["Convert to odd levels" org-convert-to-odd-levels t]
12469 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12470 ("Editing"
12471 ["Emphasis..." org-emphasize t])
12472 ("Archive"
12473 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12474 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12475 ; :active t :keys "C-u C-c C-x C-a"]
12476 ["Sparse trees open ARCHIVE trees"
12477 (setq org-sparse-tree-open-archived-trees
12478 (not org-sparse-tree-open-archived-trees))
12479 :style toggle :selected org-sparse-tree-open-archived-trees]
12480 ["Cycling opens ARCHIVE trees"
12481 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12482 :style toggle :selected org-cycle-open-archived-trees]
12483 ["Agenda includes ARCHIVE trees"
12484 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12485 :style toggle :selected (not org-agenda-skip-archived-trees)]
12486 "--"
12487 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12488 ; ["Check and Move Children" (org-archive-subtree '(4))
12489 ; :active t :keys "C-u C-c C-x C-s"]
12491 "--"
12492 ("TODO Lists"
12493 ["TODO/DONE/-" org-todo t]
12494 ("Select keyword"
12495 ["Next keyword" org-shiftright (org-on-heading-p)]
12496 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12497 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12498 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12499 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12500 ["Show TODO Tree" org-show-todo-tree t]
12501 ["Global TODO list" org-todo-list t]
12502 "--"
12503 ["Set Priority" org-priority t]
12504 ["Priority Up" org-shiftup t]
12505 ["Priority Down" org-shiftdown t])
12506 ("TAGS and Properties"
12507 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12508 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12509 "--"
12510 ["Set property" 'org-set-property t]
12511 ["Column view of properties" org-columns t]
12512 ["Insert Column View DBlock" org-insert-columns-dblock t])
12513 ("Dates and Scheduling"
12514 ["Timestamp" org-time-stamp t]
12515 ["Timestamp (inactive)" org-time-stamp-inactive t]
12516 ("Change Date"
12517 ["1 Day Later" org-shiftright t]
12518 ["1 Day Earlier" org-shiftleft t]
12519 ["1 ... Later" org-shiftup t]
12520 ["1 ... Earlier" org-shiftdown t])
12521 ["Compute Time Range" org-evaluate-time-range t]
12522 ["Schedule Item" org-schedule t]
12523 ["Deadline" org-deadline t]
12524 "--"
12525 ["Custom time format" org-toggle-time-stamp-overlays
12526 :style radio :selected org-display-custom-times]
12527 "--"
12528 ["Goto Calendar" org-goto-calendar t]
12529 ["Date from Calendar" org-date-from-calendar t])
12530 ("Logging work"
12531 ["Clock in" org-clock-in t]
12532 ["Clock out" org-clock-out t]
12533 ["Clock cancel" org-clock-cancel t]
12534 ["Goto running clock" org-clock-goto t]
12535 ["Display times" org-clock-display t]
12536 ["Create clock table" org-clock-report t]
12537 "--"
12538 ["Record DONE time"
12539 (progn (setq org-log-done (not org-log-done))
12540 (message "Switching to %s will %s record a timestamp"
12541 (car org-done-keywords)
12542 (if org-log-done "automatically" "not")))
12543 :style toggle :selected org-log-done])
12544 "--"
12545 ["Agenda Command..." org-agenda t]
12546 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12547 ("File List for Agenda")
12548 ("Special views current file"
12549 ["TODO Tree" org-show-todo-tree t]
12550 ["Check Deadlines" org-check-deadlines t]
12551 ["Timeline" org-timeline t]
12552 ["Tags Tree" org-tags-sparse-tree t])
12553 "--"
12554 ("Hyperlinks"
12555 ["Store Link (Global)" org-store-link t]
12556 ["Insert Link" org-insert-link t]
12557 ["Follow Link" org-open-at-point t]
12558 "--"
12559 ["Next link" org-next-link t]
12560 ["Previous link" org-previous-link t]
12561 "--"
12562 ["Descriptive Links"
12563 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12564 :style radio
12565 :selected (member '(org-link) buffer-invisibility-spec)]
12566 ["Literal Links"
12567 (progn
12568 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12569 :style radio
12570 :selected (not (member '(org-link) buffer-invisibility-spec))])
12571 "--"
12572 ["Export/Publish..." org-export t]
12573 ("LaTeX"
12574 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12575 :selected org-cdlatex-mode]
12576 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12577 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12578 ["Modify math symbol" org-cdlatex-math-modify
12579 (org-inside-LaTeX-fragment-p)]
12580 ["Export LaTeX fragments as images"
12581 (if (featurep 'org-exp)
12582 (setq org-export-with-LaTeX-fragments
12583 (not org-export-with-LaTeX-fragments))
12584 (require 'org-exp))
12585 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12586 org-export-with-LaTeX-fragments)])
12587 "--"
12588 ("Documentation"
12589 ["Show Version" org-version t]
12590 ["Info Documentation" org-info t])
12591 ("Customize"
12592 ["Browse Org Group" org-customize t]
12593 "--"
12594 ["Expand This Menu" org-create-customize-menu
12595 (fboundp 'customize-menu-create)])
12596 "--"
12597 ["Refresh setup" org-mode-restart t]
12600 (defun org-info (&optional node)
12601 "Read documentation for Org-mode in the info system.
12602 With optional NODE, go directly to that node."
12603 (interactive)
12604 (info (format "(org)%s" (or node ""))))
12606 (defun org-install-agenda-files-menu ()
12607 (let ((bl (buffer-list)))
12608 (save-excursion
12609 (while bl
12610 (set-buffer (pop bl))
12611 (if (org-mode-p) (setq bl nil)))
12612 (when (org-mode-p)
12613 (easy-menu-change
12614 '("Org") "File List for Agenda"
12615 (append
12616 (list
12617 ["Edit File List" (org-edit-agenda-file-list) t]
12618 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12619 ["Remove Current File from List" org-remove-file t]
12620 ["Cycle through agenda files" org-cycle-agenda-files t]
12621 ["Occur in all agenda files" org-occur-in-agenda-files t]
12622 "--")
12623 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12625 ;;;; Documentation
12627 (defun org-require-autoloaded-modules ()
12628 (interactive)
12629 (mapc 'require
12630 '(org-agenda org-archive org-clock org-colview
12631 org-exp org-export-latex org-publish
12632 org-remember org-table)))
12634 (defun org-customize ()
12635 "Call the customize function with org as argument."
12636 (interactive)
12637 (org-load-modules-maybe)
12638 (org-require-autoloaded-modules)
12639 (customize-browse 'org))
12641 (defun org-create-customize-menu ()
12642 "Create a full customization menu for Org-mode, insert it into the menu."
12643 (interactive)
12644 (org-load-modules-maybe)
12645 (org-require-autoloaded-modules)
12646 (if (fboundp 'customize-menu-create)
12647 (progn
12648 (easy-menu-change
12649 '("Org") "Customize"
12650 `(["Browse Org group" org-customize t]
12651 "--"
12652 ,(customize-menu-create 'org)
12653 ["Set" Custom-set t]
12654 ["Save" Custom-save t]
12655 ["Reset to Current" Custom-reset-current t]
12656 ["Reset to Saved" Custom-reset-saved t]
12657 ["Reset to Standard Settings" Custom-reset-standard t]))
12658 (message "\"Org\"-menu now contains full customization menu"))
12659 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12661 ;;;; Miscellaneous stuff
12663 ;;; Generally useful functions
12665 (defun org-plist-delete (plist property)
12666 "Delete PROPERTY from PLIST.
12667 This is in contrast to merely setting it to 0."
12668 (let (p)
12669 (while plist
12670 (if (not (eq property (car plist)))
12671 (setq p (plist-put p (car plist) (nth 1 plist))))
12672 (setq plist (cddr plist)))
12675 (defun org-force-self-insert (N)
12676 "Needed to enforce self-insert under remapping."
12677 (interactive "p")
12678 (self-insert-command N))
12680 (defun org-string-width (s)
12681 "Compute width of string, ignoring invisible characters.
12682 This ignores character with invisibility property `org-link', and also
12683 characters with property `org-cwidth', because these will become invisible
12684 upon the next fontification round."
12685 (let (b l)
12686 (when (or (eq t buffer-invisibility-spec)
12687 (assq 'org-link buffer-invisibility-spec))
12688 (while (setq b (text-property-any 0 (length s)
12689 'invisible 'org-link s))
12690 (setq s (concat (substring s 0 b)
12691 (substring s (or (next-single-property-change
12692 b 'invisible s) (length s)))))))
12693 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12694 (setq s (concat (substring s 0 b)
12695 (substring s (or (next-single-property-change
12696 b 'org-cwidth s) (length s))))))
12697 (setq l (string-width s) b -1)
12698 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12699 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12703 (defun org-trim (s)
12704 "Remove whitespace at beginning and end of string."
12705 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12706 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12709 (defun org-wrap (string &optional width lines)
12710 "Wrap string to either a number of lines, or a width in characters.
12711 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12712 that costs. If there is a word longer than WIDTH, the text is actually
12713 wrapped to the length of that word.
12714 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12715 many lines, whatever width that takes.
12716 The return value is a list of lines, without newlines at the end."
12717 (let* ((words (org-split-string string "[ \t\n]+"))
12718 (maxword (apply 'max (mapcar 'org-string-width words)))
12719 w ll)
12720 (cond (width
12721 (org-do-wrap words (max maxword width)))
12722 (lines
12723 (setq w maxword)
12724 (setq ll (org-do-wrap words maxword))
12725 (if (<= (length ll) lines)
12727 (setq ll words)
12728 (while (> (length ll) lines)
12729 (setq w (1+ w))
12730 (setq ll (org-do-wrap words w)))
12731 ll))
12732 (t (error "Cannot wrap this")))))
12734 (defun org-do-wrap (words width)
12735 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12736 (let (lines line)
12737 (while words
12738 (setq line (pop words))
12739 (while (and words (< (+ (length line) (length (car words))) width))
12740 (setq line (concat line " " (pop words))))
12741 (setq lines (push line lines)))
12742 (nreverse lines)))
12744 (defun org-split-string (string &optional separators)
12745 "Splits STRING into substrings at SEPARATORS.
12746 No empty strings are returned if there are matches at the beginning
12747 and end of string."
12748 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12749 (start 0)
12750 notfirst
12751 (list nil))
12752 (while (and (string-match rexp string
12753 (if (and notfirst
12754 (= start (match-beginning 0))
12755 (< start (length string)))
12756 (1+ start) start))
12757 (< (match-beginning 0) (length string)))
12758 (setq notfirst t)
12759 (or (eq (match-beginning 0) 0)
12760 (and (eq (match-beginning 0) (match-end 0))
12761 (eq (match-beginning 0) start))
12762 (setq list
12763 (cons (substring string start (match-beginning 0))
12764 list)))
12765 (setq start (match-end 0)))
12766 (or (eq start (length string))
12767 (setq list
12768 (cons (substring string start)
12769 list)))
12770 (nreverse list)))
12772 (defun org-context ()
12773 "Return a list of contexts of the current cursor position.
12774 If several contexts apply, all are returned.
12775 Each context entry is a list with a symbol naming the context, and
12776 two positions indicating start and end of the context. Possible
12777 contexts are:
12779 :headline anywhere in a headline
12780 :headline-stars on the leading stars in a headline
12781 :todo-keyword on a TODO keyword (including DONE) in a headline
12782 :tags on the TAGS in a headline
12783 :priority on the priority cookie in a headline
12784 :item on the first line of a plain list item
12785 :item-bullet on the bullet/number of a plain list item
12786 :checkbox on the checkbox in a plain list item
12787 :table in an org-mode table
12788 :table-special on a special filed in a table
12789 :table-table in a table.el table
12790 :link on a hyperlink
12791 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12792 :target on a <<target>>
12793 :radio-target on a <<<radio-target>>>
12794 :latex-fragment on a LaTeX fragment
12795 :latex-preview on a LaTeX fragment with overlayed preview image
12797 This function expects the position to be visible because it uses font-lock
12798 faces as a help to recognize the following contexts: :table-special, :link,
12799 and :keyword."
12800 (let* ((f (get-text-property (point) 'face))
12801 (faces (if (listp f) f (list f)))
12802 (p (point)) clist o)
12803 ;; First the large context
12804 (cond
12805 ((org-on-heading-p t)
12806 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12807 (when (progn
12808 (beginning-of-line 1)
12809 (looking-at org-todo-line-tags-regexp))
12810 (push (org-point-in-group p 1 :headline-stars) clist)
12811 (push (org-point-in-group p 2 :todo-keyword) clist)
12812 (push (org-point-in-group p 4 :tags) clist))
12813 (goto-char p)
12814 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12815 (if (looking-at "\\[#[A-Z0-9]\\]")
12816 (push (org-point-in-group p 0 :priority) clist)))
12818 ((org-at-item-p)
12819 (push (org-point-in-group p 2 :item-bullet) clist)
12820 (push (list :item (point-at-bol)
12821 (save-excursion (org-end-of-item) (point)))
12822 clist)
12823 (and (org-at-item-checkbox-p)
12824 (push (org-point-in-group p 0 :checkbox) clist)))
12826 ((org-at-table-p)
12827 (push (list :table (org-table-begin) (org-table-end)) clist)
12828 (if (memq 'org-formula faces)
12829 (push (list :table-special
12830 (previous-single-property-change p 'face)
12831 (next-single-property-change p 'face)) clist)))
12832 ((org-at-table-p 'any)
12833 (push (list :table-table) clist)))
12834 (goto-char p)
12836 ;; Now the small context
12837 (cond
12838 ((org-at-timestamp-p)
12839 (push (org-point-in-group p 0 :timestamp) clist))
12840 ((memq 'org-link faces)
12841 (push (list :link
12842 (previous-single-property-change p 'face)
12843 (next-single-property-change p 'face)) clist))
12844 ((memq 'org-special-keyword faces)
12845 (push (list :keyword
12846 (previous-single-property-change p 'face)
12847 (next-single-property-change p 'face)) clist))
12848 ((org-on-target-p)
12849 (push (org-point-in-group p 0 :target) clist)
12850 (goto-char (1- (match-beginning 0)))
12851 (if (looking-at org-radio-target-regexp)
12852 (push (org-point-in-group p 0 :radio-target) clist))
12853 (goto-char p))
12854 ((setq o (car (delq nil
12855 (mapcar
12856 (lambda (x)
12857 (if (memq x org-latex-fragment-image-overlays) x))
12858 (org-overlays-at (point))))))
12859 (push (list :latex-fragment
12860 (org-overlay-start o) (org-overlay-end o)) clist)
12861 (push (list :latex-preview
12862 (org-overlay-start o) (org-overlay-end o)) clist))
12863 ((org-inside-LaTeX-fragment-p)
12864 ;; FIXME: positions wrong.
12865 (push (list :latex-fragment (point) (point)) clist)))
12867 (setq clist (nreverse (delq nil clist)))
12868 clist))
12870 ;; FIXME: Compare with at-regexp-p Do we need both?
12871 (defun org-in-regexp (re &optional nlines visually)
12872 "Check if point is inside a match of regexp.
12873 Normally only the current line is checked, but you can include NLINES extra
12874 lines both before and after point into the search.
12875 If VISUALLY is set, require that the cursor is not after the match but
12876 really on, so that the block visually is on the match."
12877 (catch 'exit
12878 (let ((pos (point))
12879 (eol (point-at-eol (+ 1 (or nlines 0))))
12880 (inc (if visually 1 0)))
12881 (save-excursion
12882 (beginning-of-line (- 1 (or nlines 0)))
12883 (while (re-search-forward re eol t)
12884 (if (and (<= (match-beginning 0) pos)
12885 (>= (+ inc (match-end 0)) pos))
12886 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12888 (defun org-at-regexp-p (regexp)
12889 "Is point inside a match of REGEXP in the current line?"
12890 (catch 'exit
12891 (save-excursion
12892 (let ((pos (point)) (end (point-at-eol)))
12893 (beginning-of-line 1)
12894 (while (re-search-forward regexp end t)
12895 (if (and (<= (match-beginning 0) pos)
12896 (>= (match-end 0) pos))
12897 (throw 'exit t)))
12898 nil))))
12900 (defun org-occur-in-agenda-files (regexp &optional nlines)
12901 "Call `multi-occur' with buffers for all agenda files."
12902 (interactive "sOrg-files matching: \np")
12903 (let* ((files (org-agenda-files))
12904 (tnames (mapcar 'file-truename files))
12905 (extra org-agenda-text-search-extra-files)
12907 (when (eq (car extra) 'agenda-archives)
12908 (setq extra (cdr extra))
12909 (setq files (org-add-archive-files files)))
12910 (while (setq f (pop extra))
12911 (unless (member (file-truename f) tnames)
12912 (add-to-list 'files f 'append)
12913 (add-to-list 'tnames (file-truename f) 'append)))
12914 (multi-occur
12915 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12916 regexp)))
12918 (if (boundp 'occur-mode-find-occurrence-hook)
12919 ;; Emacs 23
12920 (add-hook 'occur-mode-find-occurrence-hook
12921 (lambda ()
12922 (when (org-mode-p)
12923 (org-reveal))))
12924 ;; Emacs 22
12925 (defadvice occur-mode-goto-occurrence
12926 (after org-occur-reveal activate)
12927 (and (org-mode-p) (org-reveal)))
12928 (defadvice occur-mode-goto-occurrence-other-window
12929 (after org-occur-reveal activate)
12930 (and (org-mode-p) (org-reveal)))
12931 (defadvice occur-mode-display-occurrence
12932 (after org-occur-reveal activate)
12933 (when (org-mode-p)
12934 (let ((pos (occur-mode-find-occurrence)))
12935 (with-current-buffer (marker-buffer pos)
12936 (save-excursion
12937 (goto-char pos)
12938 (org-reveal)))))))
12940 (defun org-uniquify (list)
12941 "Remove duplicate elements from LIST."
12942 (let (res)
12943 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12944 res))
12946 (defun org-delete-all (elts list)
12947 "Remove all elements in ELTS from LIST."
12948 (while elts
12949 (setq list (delete (pop elts) list)))
12950 list)
12952 (defun org-back-over-empty-lines ()
12953 "Move backwards over witespace, to the beginning of the first empty line.
12954 Returns the number of empty lines passed."
12955 (let ((pos (point)))
12956 (skip-chars-backward " \t\n\r")
12957 (beginning-of-line 2)
12958 (goto-char (min (point) pos))
12959 (count-lines (point) pos)))
12961 (defun org-skip-whitespace ()
12962 (skip-chars-forward " \t\n\r"))
12964 (defun org-point-in-group (point group &optional context)
12965 "Check if POINT is in match-group GROUP.
12966 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12967 match. If the match group does ot exist or point is not inside it,
12968 return nil."
12969 (and (match-beginning group)
12970 (>= point (match-beginning group))
12971 (<= point (match-end group))
12972 (if context
12973 (list context (match-beginning group) (match-end group))
12974 t)))
12976 (defun org-switch-to-buffer-other-window (&rest args)
12977 "Switch to buffer in a second window on the current frame.
12978 In particular, do not allow pop-up frames."
12979 (let (pop-up-frames special-display-buffer-names special-display-regexps
12980 special-display-function)
12981 (apply 'switch-to-buffer-other-window args)))
12983 (defun org-combine-plists (&rest plists)
12984 "Create a single property list from all plists in PLISTS.
12985 The process starts by copying the first list, and then setting properties
12986 from the other lists. Settings in the last list are the most significant
12987 ones and overrule settings in the other lists."
12988 (let ((rtn (copy-sequence (pop plists)))
12989 p v ls)
12990 (while plists
12991 (setq ls (pop plists))
12992 (while ls
12993 (setq p (pop ls) v (pop ls))
12994 (setq rtn (plist-put rtn p v))))
12995 rtn))
12997 (defun org-move-line-down (arg)
12998 "Move the current line down. With prefix argument, move it past ARG lines."
12999 (interactive "p")
13000 (let ((col (current-column))
13001 beg end pos)
13002 (beginning-of-line 1) (setq beg (point))
13003 (beginning-of-line 2) (setq end (point))
13004 (beginning-of-line (+ 1 arg))
13005 (setq pos (move-marker (make-marker) (point)))
13006 (insert (delete-and-extract-region beg end))
13007 (goto-char pos)
13008 (move-to-column col)))
13010 (defun org-move-line-up (arg)
13011 "Move the current line up. 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 (- arg))
13018 (setq pos (move-marker (make-marker) (point)))
13019 (insert (delete-and-extract-region beg end))
13020 (goto-char pos)
13021 (move-to-column col)))
13023 (defun org-replace-escapes (string table)
13024 "Replace %-escapes in STRING with values in TABLE.
13025 TABLE is an association list with keys like \"%a\" and string values.
13026 The sequences in STRING may contain normal field width and padding information,
13027 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13028 so values can contain further %-escapes if they are define later in TABLE."
13029 (let ((case-fold-search nil)
13030 e re rpl)
13031 (while (setq e (pop table))
13032 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13033 (while (string-match re string)
13034 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13035 (cdr e)))
13036 (setq string (replace-match rpl t t string))))
13037 string))
13040 (defun org-sublist (list start end)
13041 "Return a section of LIST, from START to END.
13042 Counting starts at 1."
13043 (let (rtn (c start))
13044 (setq list (nthcdr (1- start) list))
13045 (while (and list (<= c end))
13046 (push (pop list) rtn)
13047 (setq c (1+ c)))
13048 (nreverse rtn)))
13050 (defun org-find-base-buffer-visiting (file)
13051 "Like `find-buffer-visiting' but alway return the base buffer and
13052 not an indirect buffer."
13053 (let ((buf (find-buffer-visiting file)))
13054 (if buf
13055 (or (buffer-base-buffer buf) buf)
13056 nil)))
13058 (defun org-image-file-name-regexp ()
13059 "Return regexp matching the file names of images."
13060 (if (fboundp 'image-file-name-regexp)
13061 (image-file-name-regexp)
13062 (let ((image-file-name-extensions
13063 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13064 "xbm" "xpm" "pbm" "pgm" "ppm")))
13065 (concat "\\."
13066 (regexp-opt (nconc (mapcar 'upcase
13067 image-file-name-extensions)
13068 image-file-name-extensions)
13070 "\\'"))))
13072 (defun org-file-image-p (file)
13073 "Return non-nil if FILE is an image."
13074 (save-match-data
13075 (string-match (org-image-file-name-regexp) file)))
13077 ;;; Paragraph filling stuff.
13078 ;; We want this to be just right, so use the full arsenal.
13080 (defun org-indent-line-function ()
13081 "Indent line like previous, but further if previous was headline or item."
13082 (interactive)
13083 (let* ((pos (point))
13084 (itemp (org-at-item-p))
13085 column bpos bcol tpos tcol bullet btype bullet-type)
13086 ;; Find the previous relevant line
13087 (beginning-of-line 1)
13088 (cond
13089 ((looking-at "#") (setq column 0))
13090 ((looking-at "\\*+ ") (setq column 0))
13092 (beginning-of-line 0)
13093 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13094 (beginning-of-line 0))
13095 (cond
13096 ((looking-at "\\*+[ \t]+")
13097 (goto-char (match-end 0))
13098 (setq column (current-column)))
13099 ((org-in-item-p)
13100 (org-beginning-of-item)
13101 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13102 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13103 (setq bpos (match-beginning 1) tpos (match-end 0)
13104 bcol (progn (goto-char bpos) (current-column))
13105 tcol (progn (goto-char tpos) (current-column))
13106 bullet (match-string 1)
13107 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13108 (if (not itemp)
13109 (setq column tcol)
13110 (goto-char pos)
13111 (beginning-of-line 1)
13112 (if (looking-at "\\S-")
13113 (progn
13114 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13115 (setq bullet (match-string 1)
13116 btype (if (string-match "[0-9]" bullet) "n" bullet))
13117 (setq column (if (equal btype bullet-type) bcol tcol)))
13118 (setq column (org-get-indentation)))))
13119 (t (setq column (org-get-indentation))))))
13120 (goto-char pos)
13121 (if (<= (current-column) (current-indentation))
13122 (indent-line-to column)
13123 (save-excursion (indent-line-to column)))
13124 (setq column (current-column))
13125 (beginning-of-line 1)
13126 (if (looking-at
13127 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13128 (replace-match (concat "\\1" (format org-property-format
13129 (match-string 2) (match-string 3)))
13130 t nil))
13131 (move-to-column column)))
13133 (defun org-set-autofill-regexps ()
13134 (interactive)
13135 ;; In the paragraph separator we include headlines, because filling
13136 ;; text in a line directly attached to a headline would otherwise
13137 ;; fill the headline as well.
13138 (org-set-local 'comment-start-skip "^#+[ \t]*")
13139 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13140 ;; The paragraph starter includes hand-formatted lists.
13141 (org-set-local 'paragraph-start
13142 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13143 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13144 ;; But only if the user has not turned off tables or fixed-width regions
13145 (org-set-local
13146 'auto-fill-inhibit-regexp
13147 (concat "\\*+ \\|#\\+"
13148 "\\|[ \t]*" org-keyword-time-regexp
13149 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13150 (concat
13151 "\\|[ \t]*["
13152 (if org-enable-table-editor "|" "")
13153 (if org-enable-fixed-width-editor ":" "")
13154 "]"))))
13155 ;; We use our own fill-paragraph function, to make sure that tables
13156 ;; and fixed-width regions are not wrapped. That function will pass
13157 ;; through to `fill-paragraph' when appropriate.
13158 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13159 ; Adaptive filling: To get full control, first make sure that
13160 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13161 (org-set-local 'adaptive-fill-regexp "\000")
13162 (org-set-local 'adaptive-fill-function
13163 'org-adaptive-fill-function)
13164 (org-set-local
13165 'align-mode-rules-list
13166 '((org-in-buffer-settings
13167 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13168 (modes . '(org-mode))))))
13170 (defun org-fill-paragraph (&optional justify)
13171 "Re-align a table, pass through to fill-paragraph if no table."
13172 (let ((table-p (org-at-table-p))
13173 (table.el-p (org-at-table.el-p)))
13174 (cond ((and (equal (char-after (point-at-bol)) ?*)
13175 (save-excursion (goto-char (point-at-bol))
13176 (looking-at outline-regexp)))
13177 t) ; skip headlines
13178 (table.el-p t) ; skip table.el tables
13179 (table-p (org-table-align) t) ; align org-mode tables
13180 (t nil)))) ; call paragraph-fill
13182 ;; For reference, this is the default value of adaptive-fill-regexp
13183 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13185 (defun org-adaptive-fill-function ()
13186 "Return a fill prefix for org-mode files.
13187 In particular, this makes sure hanging paragraphs for hand-formatted lists
13188 work correctly."
13189 (cond ((looking-at "#[ \t]+")
13190 (match-string 0))
13191 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13192 (save-excursion
13193 (goto-char (match-end 0))
13194 (make-string (current-column) ?\ )))
13195 (t nil)))
13197 ;;; Other stuff.
13199 (defun org-toggle-fixed-width-section (arg)
13200 "Toggle the fixed-width export.
13201 If there is no active region, the QUOTE keyword at the current headline is
13202 inserted or removed. When present, it causes the text between this headline
13203 and the next to be exported as fixed-width text, and unmodified.
13204 If there is an active region, this command adds or removes a colon as the
13205 first character of this line. If the first character of a line is a colon,
13206 this line is also exported in fixed-width font."
13207 (interactive "P")
13208 (let* ((cc 0)
13209 (regionp (org-region-active-p))
13210 (beg (if regionp (region-beginning) (point)))
13211 (end (if regionp (region-end)))
13212 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13213 (case-fold-search nil)
13214 (re "[ \t]*\\(:\\)")
13215 off)
13216 (if regionp
13217 (save-excursion
13218 (goto-char beg)
13219 (setq cc (current-column))
13220 (beginning-of-line 1)
13221 (setq off (looking-at re))
13222 (while (> nlines 0)
13223 (setq nlines (1- nlines))
13224 (beginning-of-line 1)
13225 (cond
13226 (arg
13227 (move-to-column cc t)
13228 (insert ":\n")
13229 (forward-line -1))
13230 ((and off (looking-at re))
13231 (replace-match "" t t nil 1))
13232 ((not off) (move-to-column cc t) (insert ":")))
13233 (forward-line 1)))
13234 (save-excursion
13235 (org-back-to-heading)
13236 (if (looking-at (concat outline-regexp
13237 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13238 (replace-match "" t t nil 1)
13239 (if (looking-at outline-regexp)
13240 (progn
13241 (goto-char (match-end 0))
13242 (insert org-quote-string " "))))))))
13244 ;;;; Functions extending outline functionality
13246 (defun org-beginning-of-line (&optional arg)
13247 "Go to the beginning of the current line. If that is invisible, continue
13248 to a visible line beginning. This makes the function of C-a more intuitive.
13249 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13250 first attempt, and only move to after the tags when the cursor is already
13251 beyond the end of the headline."
13252 (interactive "P")
13253 (let ((pos (point)))
13254 (beginning-of-line 1)
13255 (if (bobp)
13257 (backward-char 1)
13258 (if (org-invisible-p)
13259 (while (and (not (bobp)) (org-invisible-p))
13260 (backward-char 1)
13261 (beginning-of-line 1))
13262 (forward-char 1)))
13263 (when org-special-ctrl-a/e
13264 (cond
13265 ((and (looking-at org-todo-line-regexp)
13266 (= (char-after (match-end 1)) ?\ ))
13267 (goto-char
13268 (if (eq org-special-ctrl-a/e t)
13269 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13270 ((= pos (point)) (match-beginning 3))
13271 (t (point)))
13272 (cond ((> pos (point)) (point))
13273 ((not (eq last-command this-command)) (point))
13274 (t (match-beginning 3))))))
13275 ((org-at-item-p)
13276 (goto-char
13277 (if (eq org-special-ctrl-a/e t)
13278 (cond ((> pos (match-end 4)) (match-end 4))
13279 ((= pos (point)) (match-end 4))
13280 (t (point)))
13281 (cond ((> pos (point)) (point))
13282 ((not (eq last-command this-command)) (point))
13283 (t (match-end 4))))))))))
13285 (defun org-end-of-line (&optional arg)
13286 "Go to the end of the line.
13287 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13288 first attempt, and only move to after the tags when the cursor is already
13289 beyond the end of the headline."
13290 (interactive "P")
13291 (if (or (not org-special-ctrl-a/e)
13292 (not (org-on-heading-p)))
13293 (end-of-line arg)
13294 (let ((pos (point)))
13295 (beginning-of-line 1)
13296 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13297 (if (eq org-special-ctrl-a/e t)
13298 (if (or (< pos (match-beginning 1))
13299 (= pos (match-end 0)))
13300 (goto-char (match-beginning 1))
13301 (goto-char (match-end 0)))
13302 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13303 (goto-char (match-end 0))
13304 (goto-char (match-beginning 1))))
13305 (end-of-line arg)))))
13307 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13308 (define-key org-mode-map "\C-e" 'org-end-of-line)
13310 (defun org-kill-line (&optional arg)
13311 "Kill line, to tags or end of line."
13312 (interactive "P")
13313 (cond
13314 ((or (not org-special-ctrl-k)
13315 (bolp)
13316 (not (org-on-heading-p)))
13317 (call-interactively 'kill-line))
13318 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13319 (kill-region (point) (match-beginning 1))
13320 (org-set-tags nil t))
13321 (t (kill-region (point) (point-at-eol)))))
13323 (define-key org-mode-map "\C-k" 'org-kill-line)
13325 (defun org-invisible-p ()
13326 "Check if point is at a character currently not visible."
13327 ;; Early versions of noutline don't have `outline-invisible-p'.
13328 (if (fboundp 'outline-invisible-p)
13329 (outline-invisible-p)
13330 (get-char-property (point) 'invisible)))
13332 (defun org-invisible-p2 ()
13333 "Check if point is at a character currently not visible."
13334 (save-excursion
13335 (if (and (eolp) (not (bobp))) (backward-char 1))
13336 ;; Early versions of noutline don't have `outline-invisible-p'.
13337 (if (fboundp 'outline-invisible-p)
13338 (outline-invisible-p)
13339 (get-char-property (point) 'invisible))))
13341 (defalias 'org-back-to-heading 'outline-back-to-heading)
13342 (defalias 'org-on-heading-p 'outline-on-heading-p)
13343 (defalias 'org-at-heading-p 'outline-on-heading-p)
13344 (defun org-at-heading-or-item-p ()
13345 (or (org-on-heading-p) (org-at-item-p)))
13347 (defun org-on-target-p ()
13348 (or (org-in-regexp org-radio-target-regexp)
13349 (org-in-regexp org-target-regexp)))
13351 (defun org-up-heading-all (arg)
13352 "Move to the heading line of which the present line is a subheading.
13353 This function considers both visible and invisible heading lines.
13354 With argument, move up ARG levels."
13355 (if (fboundp 'outline-up-heading-all)
13356 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13357 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13359 (defun org-up-heading-safe ()
13360 "Move to the heading line of which the present line is a subheading.
13361 This version will not throw an error. It will return the level of the
13362 headline found, or nil if no higher level is found."
13363 (let ((pos (point)) start-level level
13364 (re (concat "^" outline-regexp)))
13365 (catch 'exit
13366 (outline-back-to-heading t)
13367 (setq start-level (funcall outline-level))
13368 (if (equal start-level 1) (throw 'exit nil))
13369 (while (re-search-backward re nil t)
13370 (setq level (funcall outline-level))
13371 (if (< level start-level) (throw 'exit level)))
13372 nil)))
13374 (defun org-first-sibling-p ()
13375 "Is this heading the first child of its parents?"
13376 (interactive)
13377 (let ((re (concat "^" outline-regexp))
13378 level l)
13379 (unless (org-at-heading-p t)
13380 (error "Not at a heading"))
13381 (setq level (funcall outline-level))
13382 (save-excursion
13383 (if (not (re-search-backward re nil t))
13385 (setq l (funcall outline-level))
13386 (< l level)))))
13388 (defun org-goto-sibling (&optional previous)
13389 "Goto the next sibling, even if it is invisible.
13390 When PREVIOUS is set, go to the previous sibling instead. Returns t
13391 when a sibling was found. When none is found, return nil and don't
13392 move point."
13393 (let ((fun (if previous 're-search-backward 're-search-forward))
13394 (pos (point))
13395 (re (concat "^" outline-regexp))
13396 level l)
13397 (when (condition-case nil (org-back-to-heading t) (error nil))
13398 (setq level (funcall outline-level))
13399 (catch 'exit
13400 (or previous (forward-char 1))
13401 (while (funcall fun re nil t)
13402 (setq l (funcall outline-level))
13403 (when (< l level) (goto-char pos) (throw 'exit nil))
13404 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13405 (goto-char pos)
13406 nil))))
13408 (defun org-show-siblings ()
13409 "Show all siblings of the current headline."
13410 (save-excursion
13411 (while (org-goto-sibling) (org-flag-heading nil)))
13412 (save-excursion
13413 (while (org-goto-sibling 'previous)
13414 (org-flag-heading nil))))
13416 (defun org-show-hidden-entry ()
13417 "Show an entry where even the heading is hidden."
13418 (save-excursion
13419 (org-show-entry)))
13421 (defun org-flag-heading (flag &optional entry)
13422 "Flag the current heading. FLAG non-nil means make invisible.
13423 When ENTRY is non-nil, show the entire entry."
13424 (save-excursion
13425 (org-back-to-heading t)
13426 ;; Check if we should show the entire entry
13427 (if entry
13428 (progn
13429 (org-show-entry)
13430 (save-excursion
13431 (and (outline-next-heading)
13432 (org-flag-heading nil))))
13433 (outline-flag-region (max (point-min) (1- (point)))
13434 (save-excursion (outline-end-of-heading) (point))
13435 flag))))
13437 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13438 ;; This is an exact copy of the original function, but it uses
13439 ;; `org-back-to-heading', to make it work also in invisible
13440 ;; trees. And is uses an invisible-OK argument.
13441 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13442 (org-back-to-heading invisible-OK)
13443 (let ((first t)
13444 (level (funcall outline-level)))
13445 (while (and (not (eobp))
13446 (or first (> (funcall outline-level) level)))
13447 (setq first nil)
13448 (outline-next-heading))
13449 (unless to-heading
13450 (if (memq (preceding-char) '(?\n ?\^M))
13451 (progn
13452 ;; Go to end of line before heading
13453 (forward-char -1)
13454 (if (memq (preceding-char) '(?\n ?\^M))
13455 ;; leave blank line before heading
13456 (forward-char -1))))))
13457 (point))
13459 (defun org-show-subtree ()
13460 "Show everything after this heading at deeper levels."
13461 (outline-flag-region
13462 (point)
13463 (save-excursion
13464 (outline-end-of-subtree) (outline-next-heading) (point))
13465 nil))
13467 (defun org-show-entry ()
13468 "Show the body directly following this heading.
13469 Show the heading too, if it is currently invisible."
13470 (interactive)
13471 (save-excursion
13472 (condition-case nil
13473 (progn
13474 (org-back-to-heading t)
13475 (outline-flag-region
13476 (max (point-min) (1- (point)))
13477 (save-excursion
13478 (re-search-forward
13479 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13480 (or (match-beginning 1) (point-max)))
13481 nil))
13482 (error nil))))
13484 (defun org-make-options-regexp (kwds)
13485 "Make a regular expression for keyword lines."
13486 (concat
13488 "#?[ \t]*\\+\\("
13489 (mapconcat 'regexp-quote kwds "\\|")
13490 "\\):[ \t]*"
13491 "\\(.+\\)"))
13493 ;; Make isearch reveal the necessary context
13494 (defun org-isearch-end ()
13495 "Reveal context after isearch exits."
13496 (when isearch-success ; only if search was successful
13497 (if (featurep 'xemacs)
13498 ;; Under XEmacs, the hook is run in the correct place,
13499 ;; we directly show the context.
13500 (org-show-context 'isearch)
13501 ;; In Emacs the hook runs *before* restoring the overlays.
13502 ;; So we have to use a one-time post-command-hook to do this.
13503 ;; (Emacs 22 has a special variable, see function `org-mode')
13504 (unless (and (boundp 'isearch-mode-end-hook-quit)
13505 isearch-mode-end-hook-quit)
13506 ;; Only when the isearch was not quitted.
13507 (org-add-hook 'post-command-hook 'org-isearch-post-command
13508 'append 'local)))))
13510 (defun org-isearch-post-command ()
13511 "Remove self from hook, and show context."
13512 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13513 (org-show-context 'isearch))
13516 ;;;; Integration with and fixes for other packages
13518 ;;; Imenu support
13520 (defvar org-imenu-markers nil
13521 "All markers currently used by Imenu.")
13522 (make-variable-buffer-local 'org-imenu-markers)
13524 (defun org-imenu-new-marker (&optional pos)
13525 "Return a new marker for use by Imenu, and remember the marker."
13526 (let ((m (make-marker)))
13527 (move-marker m (or pos (point)))
13528 (push m org-imenu-markers)
13531 (defun org-imenu-get-tree ()
13532 "Produce the index for Imenu."
13533 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13534 (setq org-imenu-markers nil)
13535 (let* ((n org-imenu-depth)
13536 (re (concat "^" outline-regexp))
13537 (subs (make-vector (1+ n) nil))
13538 (last-level 0)
13539 m tree level head)
13540 (save-excursion
13541 (save-restriction
13542 (widen)
13543 (goto-char (point-max))
13544 (while (re-search-backward re nil t)
13545 (setq level (org-reduced-level (funcall outline-level)))
13546 (when (<= level n)
13547 (looking-at org-complex-heading-regexp)
13548 (setq head (org-match-string-no-properties 4)
13549 m (org-imenu-new-marker))
13550 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13551 (if (>= level last-level)
13552 (push (cons head m) (aref subs level))
13553 (push (cons head (aref subs (1+ level))) (aref subs level))
13554 (loop for i from (1+ level) to n do (aset subs i nil)))
13555 (setq last-level level)))))
13556 (aref subs 1)))
13558 (eval-after-load "imenu"
13559 '(progn
13560 (add-hook 'imenu-after-jump-hook
13561 (lambda () (org-show-context 'org-goto)))))
13563 ;; Speedbar support
13565 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13566 "Overlay marking the agenda restriction line in speedbar.")
13567 (org-overlay-put org-speedbar-restriction-lock-overlay
13568 'face 'org-agenda-restriction-lock)
13569 (org-overlay-put org-speedbar-restriction-lock-overlay
13570 'help-echo "Agendas are currently limited to this item.")
13571 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13573 (defun org-speedbar-set-agenda-restriction ()
13574 "Restrict future agenda commands to the location at point in speedbar.
13575 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13576 (interactive)
13577 (require 'org-agenda)
13578 (let (p m tp np dir txt w)
13579 (cond
13580 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13581 'org-imenu t))
13582 (setq m (get-text-property p 'org-imenu-marker))
13583 (save-excursion
13584 (save-restriction
13585 (set-buffer (marker-buffer m))
13586 (goto-char m)
13587 (org-agenda-set-restriction-lock 'subtree))))
13588 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13589 'speedbar-function 'speedbar-find-file))
13590 (setq tp (previous-single-property-change
13591 (1+ p) 'speedbar-function)
13592 np (next-single-property-change
13593 tp 'speedbar-function)
13594 dir (speedbar-line-directory)
13595 txt (buffer-substring-no-properties (or tp (point-min))
13596 (or np (point-max))))
13597 (save-excursion
13598 (save-restriction
13599 (set-buffer (find-file-noselect
13600 (let ((default-directory dir))
13601 (expand-file-name txt))))
13602 (unless (org-mode-p)
13603 (error "Cannot restrict to non-Org-mode file"))
13604 (org-agenda-set-restriction-lock 'file))))
13605 (t (error "Don't know how to restrict Org-mode's agenda")))
13606 (org-move-overlay org-speedbar-restriction-lock-overlay
13607 (point-at-bol) (point-at-eol))
13608 (setq current-prefix-arg nil)
13609 (org-agenda-maybe-redo)))
13611 (eval-after-load "speedbar"
13612 '(progn
13613 (speedbar-add-supported-extension ".org")
13614 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13615 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13616 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13617 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13618 (add-hook 'speedbar-visiting-tag-hook
13619 (lambda () (org-show-context 'org-goto)))))
13622 ;;; Fixes and Hacks for problems with other packages
13624 ;; Make flyspell not check words in links, to not mess up our keymap
13625 (defun org-mode-flyspell-verify ()
13626 "Don't let flyspell put overlays at active buttons."
13627 (not (get-text-property (point) 'keymap)))
13629 ;; Make `bookmark-jump' show the jump location if it was hidden.
13630 (eval-after-load "bookmark"
13631 '(if (boundp 'bookmark-after-jump-hook)
13632 ;; We can use the hook
13633 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13634 ;; Hook not available, use advice
13635 (defadvice bookmark-jump (after org-make-visible activate)
13636 "Make the position visible."
13637 (org-bookmark-jump-unhide))))
13639 (defun org-bookmark-jump-unhide ()
13640 "Unhide the current position, to show the bookmark location."
13641 (and (org-mode-p)
13642 (or (org-invisible-p)
13643 (save-excursion (goto-char (max (point-min) (1- (point))))
13644 (org-invisible-p)))
13645 (org-show-context 'bookmark-jump)))
13647 ;; Make session.el ignore our circular variable
13648 (eval-after-load "session"
13649 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13651 ;;;; Experimental code
13653 (defun org-closed-in-range ()
13654 "Sparse tree of items closed in a certain time range.
13655 Still experimental, may disappear in the future."
13656 (interactive)
13657 ;; Get the time interval from the user.
13658 (let* ((time1 (time-to-seconds
13659 (org-read-date nil 'to-time nil "Starting date: ")))
13660 (time2 (time-to-seconds
13661 (org-read-date nil 'to-time nil "End date:")))
13662 ;; callback function
13663 (callback (lambda ()
13664 (let ((time
13665 (time-to-seconds
13666 (apply 'encode-time
13667 (org-parse-time-string
13668 (match-string 1))))))
13669 ;; check if time in interval
13670 (and (>= time time1) (<= time time2))))))
13671 ;; make tree, check each match with the callback
13672 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13675 ;;;; Finish up
13677 (provide 'org)
13679 (run-hooks 'org-load-hook)
13681 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13682 ;;; org.el ends here