Implement description lists.
[org-mode/org-tableheadings.git] / lisp / org.el
blobb8ca18909d65a95b576c89acebb75de8c5ba8bf2
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.02b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.02b"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C eval: Include command output as text" org-eval)
178 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
179 (const :tag "C id: Global id's for identifying entries" org-id)
180 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
181 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
182 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
183 (const :tag "C mew: Support for links to messages in Mew" org-mew)
184 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
185 (const :tag "C registry: A registry for Org links" org-registry)
186 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
187 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
188 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
189 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
190 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
193 (defgroup org-startup nil
194 "Options concerning startup of Org-mode."
195 :tag "Org Startup"
196 :group 'org)
198 (defcustom org-startup-folded t
199 "Non-nil means, entering Org-mode will switch to OVERVIEW.
200 This can also be configured on a per-file basis by adding one of
201 the following lines anywhere in the buffer:
203 #+STARTUP: fold
204 #+STARTUP: nofold
205 #+STARTUP: content"
206 :group 'org-startup
207 :type '(choice
208 (const :tag "nofold: show all" nil)
209 (const :tag "fold: overview" t)
210 (const :tag "content: all headlines" content)))
212 (defcustom org-startup-truncated t
213 "Non-nil means, entering Org-mode will set `truncate-lines'.
214 This is useful since some lines containing links can be very long and
215 uninteresting. Also tables look terrible when wrapped."
216 :group 'org-startup
217 :type 'boolean)
219 (defcustom org-startup-align-all-tables nil
220 "Non-nil means, align all tables when visiting a file.
221 This is useful when the column width in tables is forced with <N> cookies
222 in table fields. Such tables will look correct only after the first re-align.
223 This can also be configured on a per-file basis by adding one of
224 the following lines anywhere in the buffer:
225 #+STARTUP: align
226 #+STARTUP: noalign"
227 :group 'org-startup
228 :type 'boolean)
230 (defcustom org-insert-mode-line-in-empty-file nil
231 "Non-nil means insert the first line setting Org-mode in empty files.
232 When the function `org-mode' is called interactively in an empty file, this
233 normally means that the file name does not automatically trigger Org-mode.
234 To ensure that the file will always be in Org-mode in the future, a
235 line enforcing Org-mode will be inserted into the buffer, if this option
236 has been set."
237 :group 'org-startup
238 :type 'boolean)
240 (defcustom org-replace-disputed-keys nil
241 "Non-nil means use alternative key bindings for some keys.
242 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
243 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
244 If you want to use Org-mode together with one of these other modes,
245 or more generally if you would like to move some Org-mode commands to
246 other keys, set this variable and configure the keys with the variable
247 `org-disputed-keys'.
249 This option is only relevant at load-time of Org-mode, and must be set
250 *before* org.el is loaded. Changing it requires a restart of Emacs to
251 become effective."
252 :group 'org-startup
253 :type 'boolean)
255 (if (fboundp 'defvaralias)
256 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
258 (defcustom org-disputed-keys
259 '(([(shift up)] . [(meta p)])
260 ([(shift down)] . [(meta n)])
261 ([(shift left)] . [(meta -)])
262 ([(shift right)] . [(meta +)])
263 ([(control shift right)] . [(meta shift +)])
264 ([(control shift left)] . [(meta shift -)]))
265 "Keys for which Org-mode and other modes compete.
266 This is an alist, cars are the default keys, second element specifies
267 the alternative to use when `org-replace-disputed-keys' is t.
269 Keys can be specified in any syntax supported by `define-key'.
270 The value of this option takes effect only at Org-mode's startup,
271 therefore you'll have to restart Emacs to apply it after changing."
272 :group 'org-startup
273 :type 'alist)
275 (defun org-key (key)
276 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
277 Or return the original if not disputed."
278 (if org-replace-disputed-keys
279 (let* ((nkey (key-description key))
280 (x (org-find-if (lambda (x)
281 (equal (key-description (car x)) nkey))
282 org-disputed-keys)))
283 (if x (cdr x) key))
284 key))
286 (defun org-find-if (predicate seq)
287 (catch 'exit
288 (while seq
289 (if (funcall predicate (car seq))
290 (throw 'exit (car seq))
291 (pop seq)))))
293 (defun org-defkey (keymap key def)
294 "Define a key, possibly translated, as returned by `org-key'."
295 (define-key keymap (org-key key) def))
297 (defcustom org-ellipsis nil
298 "The ellipsis to use in the Org-mode outline.
299 When nil, just use the standard three dots. When a string, use that instead,
300 When a face, use the standart 3 dots, but with the specified face.
301 The change affects only Org-mode (which will then use its own display table).
302 Changing this requires executing `M-x org-mode' in a buffer to become
303 effective."
304 :group 'org-startup
305 :type '(choice (const :tag "Default" nil)
306 (face :tag "Face" :value org-warning)
307 (string :tag "String" :value "...#")))
309 (defvar org-display-table nil
310 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
312 (defgroup org-keywords nil
313 "Keywords in Org-mode."
314 :tag "Org Keywords"
315 :group 'org)
317 (defcustom org-deadline-string "DEADLINE:"
318 "String to mark deadline entries.
319 A deadline is this string, followed by a time stamp. Should be a word,
320 terminated by a colon. You can insert a schedule keyword and
321 a timestamp with \\[org-deadline].
322 Changes become only effective after restarting Emacs."
323 :group 'org-keywords
324 :type 'string)
326 (defcustom org-scheduled-string "SCHEDULED:"
327 "String to mark scheduled TODO entries.
328 A schedule is this string, followed by a time stamp. Should be a word,
329 terminated by a colon. You can insert a schedule keyword and
330 a timestamp with \\[org-schedule].
331 Changes become only effective after restarting Emacs."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-closed-string "CLOSED:"
336 "String used as the prefix for timestamps logging closing a TODO entry."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-clock-string "CLOCK:"
341 "String used as prefix for timestamps clocking work hours on an item."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-comment-string "COMMENT"
346 "Entries starting with this keyword will never be exported.
347 An entry can be toggled between COMMENT and normal with
348 \\[org-toggle-comment].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-quote-string "QUOTE"
354 "Entries starting with this keyword will be exported in fixed-width font.
355 Quoting applies only to the text in the entry following the headline, and does
356 not extend beyond the next headline, even if that is lower level.
357 An entry can be toggled between QUOTE and normal with
358 \\[org-toggle-fixed-width-section]."
359 :group 'org-keywords
360 :type 'string)
362 (defconst org-repeat-re
363 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
364 "Regular expression for specifying repeated events.
365 After a match, group 1 contains the repeat expression.")
367 (defgroup org-structure nil
368 "Options concerning the general structure of Org-mode files."
369 :tag "Org Structure"
370 :group 'org)
372 (defgroup org-reveal-location nil
373 "Options about how to make context of a location visible."
374 :tag "Org Reveal Location"
375 :group 'org-structure)
377 (defconst org-context-choice
378 '(choice
379 (const :tag "Always" t)
380 (const :tag "Never" nil)
381 (repeat :greedy t :tag "Individual contexts"
382 (cons
383 (choice :tag "Context"
384 (const agenda)
385 (const org-goto)
386 (const occur-tree)
387 (const tags-tree)
388 (const link-search)
389 (const mark-goto)
390 (const bookmark-jump)
391 (const isearch)
392 (const default))
393 (boolean))))
394 "Contexts for the reveal options.")
396 (defcustom org-show-hierarchy-above '((default . t))
397 "Non-nil means, show full hierarchy when revealing a location.
398 Org-mode often shows locations in an org-mode file which might have
399 been invisible before. When this is set, the hierarchy of headings
400 above the exposed location is shown.
401 Turning this off for example for sparse trees makes them very compact.
402 Instead of t, this can also be an alist specifying this option for different
403 contexts. Valid contexts are
404 agenda when exposing an entry from the agenda
405 org-goto when using the command `org-goto' on key C-c C-j
406 occur-tree when using the command `org-occur' on key C-c /
407 tags-tree when constructing a sparse tree based on tags matches
408 link-search when exposing search matches associated with a link
409 mark-goto when exposing the jump goal of a mark
410 bookmark-jump when exposing a bookmark location
411 isearch when exiting from an incremental search
412 default default for all contexts not set explicitly"
413 :group 'org-reveal-location
414 :type org-context-choice)
416 (defcustom org-show-following-heading '((default . nil))
417 "Non-nil means, show following heading when revealing a location.
418 Org-mode often shows locations in an org-mode file which might have
419 been invisible before. When this is set, the heading following the
420 match is shown.
421 Turning this off for example for sparse trees makes them very compact,
422 but makes it harder to edit the location of the match. In such a case,
423 use the command \\[org-reveal] to show more context.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. See `org-show-hierarchy-above' for valid contexts."
426 :group 'org-reveal-location
427 :type org-context-choice)
429 (defcustom org-show-siblings '((default . nil) (isearch t))
430 "Non-nil means, show all sibling heading when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the sibling of the current entry
433 heading are all made visible. If `org-show-hierarchy-above' is t,
434 the same happens on each level of the hierarchy above the current entry.
436 By default this is on for the isearch context, off for all other contexts.
437 Turning this off for example for sparse trees makes them very compact,
438 but makes it harder to edit the location of the match. In such a case,
439 use the command \\[org-reveal] to show more context.
440 Instead of t, this can also be an alist specifying this option for different
441 contexts. See `org-show-hierarchy-above' for valid contexts."
442 :group 'org-reveal-location
443 :type org-context-choice)
445 (defcustom org-show-entry-below '((default . nil))
446 "Non-nil means, show the entry below a headline when revealing a location.
447 Org-mode often shows locations in an org-mode file which might have
448 been invisible before. When this is set, the text below the headline that is
449 exposed is also shown.
451 By default this is off for all contexts.
452 Instead of t, this can also be an alist specifying this option for different
453 contexts. See `org-show-hierarchy-above' for valid contexts."
454 :group 'org-reveal-location
455 :type org-context-choice)
457 (defcustom org-indirect-buffer-display 'other-window
458 "How should indirect tree buffers be displayed?
459 This applies to indirect buffers created with the commands
460 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
461 Valid values are:
462 current-window Display in the current window
463 other-window Just display in another window.
464 dedicated-frame Create one new frame, and re-use it each time.
465 new-frame Make a new frame each time. Note that in this case
466 previously-made indirect buffers are kept, and you need to
467 kill these buffers yourself."
468 :group 'org-structure
469 :group 'org-agenda-windows
470 :type '(choice
471 (const :tag "In current window" current-window)
472 (const :tag "In current frame, other window" other-window)
473 (const :tag "Each time a new frame" new-frame)
474 (const :tag "One dedicated frame" dedicated-frame)))
476 (defgroup org-cycle nil
477 "Options concerning visibility cycling in Org-mode."
478 :tag "Org Cycle"
479 :group 'org-structure)
481 (defcustom org-drawers '("PROPERTIES" "CLOCK")
482 "Names of drawers. Drawers are not opened by cycling on the headline above.
483 Drawers only open with a TAB on the drawer line itself. A drawer looks like
484 this:
485 :DRAWERNAME:
486 .....
487 :END:
488 The drawer \"PROPERTIES\" is special for capturing properties through
489 the property API.
491 Drawers can be defined on the per-file basis with a line like:
493 #+DRAWERS: HIDDEN STATE PROPERTIES"
494 :group 'org-structure
495 :type '(repeat (string :tag "Drawer Name")))
497 (defcustom org-cycle-global-at-bob nil
498 "Cycle globally if cursor is at beginning of buffer and not at a headline.
499 This makes it possible to do global cycling without having to use S-TAB or
500 C-u TAB. For this special case to work, the first line of the buffer
501 must not be a headline - it may be empty ot some other text. When used in
502 this way, `org-cycle-hook' is disables temporarily, to make sure the
503 cursor stays at the beginning of the buffer.
504 When this option is nil, don't do anything special at the beginning
505 of the buffer."
506 :group 'org-cycle
507 :type 'boolean)
509 (defcustom org-cycle-emulate-tab t
510 "Where should `org-cycle' emulate TAB.
511 nil Never
512 white Only in completely white lines
513 whitestart Only at the beginning of lines, before the first non-white char
514 t Everywhere except in headlines
515 exc-hl-bol Everywhere except at the start of a headline
516 If TAB is used in a place where it does not emulate TAB, the current subtree
517 visibility is cycled."
518 :group 'org-cycle
519 :type '(choice (const :tag "Never" nil)
520 (const :tag "Only in completely white lines" white)
521 (const :tag "Before first char in a line" whitestart)
522 (const :tag "Everywhere except in headlines" t)
523 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
526 (defcustom org-cycle-separator-lines 2
527 "Number of empty lines needed to keep an empty line between collapsed trees.
528 If you leave an empty line between the end of a subtree and the following
529 headline, this empty line is hidden when the subtree is folded.
530 Org-mode will leave (exactly) one empty line visible if the number of
531 empty lines is equal or larger to the number given in this variable.
532 So the default 2 means, at least 2 empty lines after the end of a subtree
533 are needed to produce free space between a collapsed subtree and the
534 following headline.
536 Special case: when 0, never leave empty lines in collapsed view."
537 :group 'org-cycle
538 :type 'integer)
540 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
541 org-cycle-hide-drawers
542 org-cycle-show-empty-lines
543 org-optimize-window-after-visibility-change)
544 "Hook that is run after `org-cycle' has changed the buffer visibility.
545 The function(s) in this hook must accept a single argument which indicates
546 the new state that was set by the most recent `org-cycle' command. The
547 argument is a symbol. After a global state change, it can have the values
548 `overview', `content', or `all'. After a local state change, it can have
549 the values `folded', `children', or `subtree'."
550 :group 'org-cycle
551 :type 'hook)
553 (defgroup org-edit-structure nil
554 "Options concerning structure editing in Org-mode."
555 :tag "Org Edit Structure"
556 :group 'org-structure)
558 (defcustom org-odd-levels-only nil
559 "Non-nil means, skip even levels and only use odd levels for the outline.
560 This has the effect that two stars are being added/taken away in
561 promotion/demotion commands. It also influences how levels are
562 handled by the exporters.
563 Changing it requires restart of `font-lock-mode' to become effective
564 for fontification also in regions already fontified.
565 You may also set this on a per-file basis by adding one of the following
566 lines to the buffer:
568 #+STARTUP: odd
569 #+STARTUP: oddeven"
570 :group 'org-edit-structure
571 :group 'org-font-lock
572 :type 'boolean)
574 (defcustom org-adapt-indentation t
575 "Non-nil means, adapt indentation when promoting and demoting.
576 When this is set and the *entire* text in an entry is indented, the
577 indentation is increased by one space in a demotion command, and
578 decreased by one in a promotion command. If any line in the entry
579 body starts at column 0, indentation is not changed at all."
580 :group 'org-edit-structure
581 :type 'boolean)
583 (defcustom org-special-ctrl-a/e nil
584 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
585 When t, `C-a' will bring back the cursor to the beginning of the
586 headline text, i.e. after the stars and after a possible TODO keyword.
587 In an item, this will be the position after the bullet.
588 When the cursor is already at that position, another `C-a' will bring
589 it to the beginning of the line.
590 `C-e' will jump to the end of the headline, ignoring the presence of tags
591 in the headline. A second `C-e' will then jump to the true end of the
592 line, after any tags.
593 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
594 and only a directly following, identical keypress will bring the cursor
595 to the special positions."
596 :group 'org-edit-structure
597 :type '(choice
598 (const :tag "off" nil)
599 (const :tag "after bullet first" t)
600 (const :tag "border first" reversed)))
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
605 (defcustom org-special-ctrl-k nil
606 "Non-nil means `C-k' will behave specially in headlines.
607 When nil, `C-k' will call the default `kill-line' command.
608 When t, the following will happen while the cursor is in the headline:
610 - When the cursor is at the beginning of a headline, kill the entire
611 line and possible the folded subtree below the line.
612 - When in the middle of the headline text, kill the headline up to the tags.
613 - When after the headline text, kill the tags."
614 :group 'org-edit-structure
615 :type 'boolean)
617 (defcustom org-M-RET-may-split-line '((default . t))
618 "Non-nil means, M-RET will split the line at the cursor position.
619 When nil, it will go to the end of the line before making a
620 new line.
621 You may also set this option in a different way for different
622 contexts. Valid contexts are:
624 headline when creating a new headline
625 item when creating a new item
626 table in a table field
627 default the value to be used for all contexts not explicitly
628 customized"
629 :group 'org-structure
630 :group 'org-table
631 :type '(choice
632 (const :tag "Always" t)
633 (const :tag "Never" nil)
634 (repeat :greedy t :tag "Individual contexts"
635 (cons
636 (choice :tag "Context"
637 (const headline)
638 (const item)
639 (const table)
640 (const default))
641 (boolean)))))
644 (defcustom org-blank-before-new-entry '((heading . nil)
645 (plain-list-item . nil))
646 "Should `org-insert-heading' leave a blank line before new heading/item?
647 The value is an alist, with `heading' and `plain-list-item' as car,
648 and a boolean flag as cdr."
649 :group 'org-edit-structure
650 :type '(list
651 (cons (const heading) (boolean))
652 (cons (const plain-list-item) (boolean))))
654 (defcustom org-insert-heading-hook nil
655 "Hook being run after inserting a new heading."
656 :group 'org-edit-structure
657 :type 'hook)
659 (defcustom org-enable-fixed-width-editor t
660 "Non-nil means, lines starting with \":\" are treated as fixed-width.
661 This currently only means, they are never auto-wrapped.
662 When nil, such lines will be treated like ordinary lines.
663 See also the QUOTE keyword."
664 :group 'org-edit-structure
665 :type 'boolean)
667 (defcustom org-goto-auto-isearch t
668 "Non-nil means, typing characters in org-goto starts incremental search."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defgroup org-sparse-trees nil
673 "Options concerning sparse trees in Org-mode."
674 :tag "Org Sparse Trees"
675 :group 'org-structure)
677 (defcustom org-highlight-sparse-tree-matches t
678 "Non-nil means, highlight all matches that define a sparse tree.
679 The highlights will automatically disappear the next time the buffer is
680 changed by an edit command."
681 :group 'org-sparse-trees
682 :type 'boolean)
684 (defcustom org-remove-highlights-with-change t
685 "Non-nil means, any change to the buffer will remove temporary highlights.
686 Such highlights are created by `org-occur' and `org-clock-display'.
687 When nil, `C-c C-c needs to be used to get rid of the highlights.
688 The highlights created by `org-preview-latex-fragment' always need
689 `C-c C-c' to be removed."
690 :group 'org-sparse-trees
691 :group 'org-time
692 :type 'boolean)
695 (defcustom org-occur-hook '(org-first-headline-recenter)
696 "Hook that is run after `org-occur' has constructed a sparse tree.
697 This can be used to recenter the window to show as much of the structure
698 as possible."
699 :group 'org-sparse-trees
700 :type 'hook)
702 (defgroup org-plain-lists nil
703 "Options concerning plain lists in Org-mode."
704 :tag "Org Plain lists"
705 :group 'org-structure)
707 (defcustom org-cycle-include-plain-lists nil
708 "Non-nil means, include plain lists into visibility cycling.
709 This means that during cycling, plain list items will *temporarily* be
710 interpreted as outline headlines with a level given by 1000+i where i is the
711 indentation of the bullet. In all other operations, plain list items are
712 not seen as headlines. For example, you cannot assign a TODO keyword to
713 such an item."
714 :group 'org-plain-lists
715 :type 'boolean)
717 (defcustom org-plain-list-ordered-item-terminator t
718 "The character that makes a line with leading number an ordered list item.
719 Valid values are ?. and ?\). To get both terminators, use t. While
720 ?. may look nicer, it creates the danger that a line with leading
721 number may be incorrectly interpreted as an item. ?\) therefore is
722 the safe choice."
723 :group 'org-plain-lists
724 :type '(choice (const :tag "dot like in \"2.\"" ?.)
725 (const :tag "paren like in \"2)\"" ?\))
726 (const :tab "both" t)))
728 (defcustom org-empty-line-terminates-plain-lists nil
729 "Non-nil means, an empty line ends all plain list levels.
730 When nil, empty lines are part of the preceeding item."
731 :group 'org-plain-lists
732 :type 'boolean)
734 (defcustom org-auto-renumber-ordered-lists t
735 "Non-nil means, automatically renumber ordered plain lists.
736 Renumbering happens when the sequence have been changed with
737 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
738 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
739 :group 'org-plain-lists
740 :type 'boolean)
742 (defcustom org-provide-checkbox-statistics t
743 "Non-nil means, update checkbox statistics after insert and toggle.
744 When this is set, checkbox statistics is updated each time you either insert
745 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
746 with \\[org-ctrl-c-ctrl-c\\]."
747 :group 'org-plain-lists
748 :type 'boolean)
751 (defgroup org-imenu-and-speedbar nil
752 "Options concerning imenu and speedbar in Org-mode."
753 :tag "Org Imenu and Speedbar"
754 :group 'org-structure)
756 (defcustom org-imenu-depth 2
757 "The maximum level for Imenu access to Org-mode headlines.
758 This also applied for speedbar access."
759 :group 'org-imenu-and-speedbar
760 :type 'number)
762 (defgroup org-table nil
763 "Options concerning tables in Org-mode."
764 :tag "Org Table"
765 :group 'org)
767 (defcustom org-enable-table-editor 'optimized
768 "Non-nil means, lines starting with \"|\" are handled by the table editor.
769 When nil, such lines will be treated like ordinary lines.
771 When equal to the symbol `optimized', the table editor will be optimized to
772 do the following:
773 - Automatic overwrite mode in front of whitespace in table fields.
774 This makes the structure of the table stay in tact as long as the edited
775 field does not exceed the column width.
776 - Minimize the number of realigns. Normally, the table is aligned each time
777 TAB or RET are pressed to move to another field. With optimization this
778 happens only if changes to a field might have changed the column width.
779 Optimization requires replacing the functions `self-insert-command',
780 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
781 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
782 very good at guessing when a re-align will be necessary, but you can always
783 force one with \\[org-ctrl-c-ctrl-c].
785 If you would like to use the optimized version in Org-mode, but the
786 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
788 This variable can be used to turn on and off the table editor during a session,
789 but in order to toggle optimization, a restart is required.
791 See also the variable `org-table-auto-blank-field'."
792 :group 'org-table
793 :type '(choice
794 (const :tag "off" nil)
795 (const :tag "on" t)
796 (const :tag "on, optimized" optimized)))
798 (defcustom org-table-tab-recognizes-table.el t
799 "Non-nil means, TAB will automatically notice a table.el table.
800 When it sees such a table, it moves point into it and - if necessary -
801 calls `table-recognize-table'."
802 :group 'org-table-editing
803 :type 'boolean)
805 (defgroup org-link nil
806 "Options concerning links in Org-mode."
807 :tag "Org Link"
808 :group 'org)
810 (defvar org-link-abbrev-alist-local nil
811 "Buffer-local version of `org-link-abbrev-alist', which see.
812 The value of this is taken from the #+LINK lines.")
813 (make-variable-buffer-local 'org-link-abbrev-alist-local)
815 (defcustom org-link-abbrev-alist nil
816 "Alist of link abbreviations.
817 The car of each element is a string, to be replaced at the start of a link.
818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
819 links in Org-mode buffers can have an optional tag after a double colon, e.g.
821 [[linkkey:tag][description]]
823 If REPLACE is a string, the tag will simply be appended to create the link.
824 If the string contains \"%s\", the tag will be inserted there.
826 REPLACE may also be a function that will be called with the tag as the
827 only argument to create the link, which should be returned as a string.
829 See the manual for examples."
830 :group 'org-link
831 :type 'alist)
833 (defcustom org-descriptive-links t
834 "Non-nil means, hide link part and only show description of bracket links.
835 Bracket links are like [[link][descritpion]]. This variable sets the initial
836 state in new org-mode buffers. The setting can then be toggled on a
837 per-buffer basis from the Org->Hyperlinks menu."
838 :group 'org-link
839 :type 'boolean)
841 (defcustom org-link-file-path-type 'adaptive
842 "How the path name in file links should be stored.
843 Valid values are:
845 relative Relative to the current directory, i.e. the directory of the file
846 into which the link is being inserted.
847 absolute Absolute path, if possible with ~ for home directory.
848 noabbrev Absolute path, no abbreviation of home directory.
849 adaptive Use relative path for files in the current directory and sub-
850 directories of it. For other files, use an absolute path."
851 :group 'org-link
852 :type '(choice
853 (const relative)
854 (const absolute)
855 (const noabbrev)
856 (const adaptive)))
858 (defcustom org-activate-links '(bracket angle plain radio tag date)
859 "Types of links that should be activated in Org-mode files.
860 This is a list of symbols, each leading to the activation of a certain link
861 type. In principle, it does not hurt to turn on most link types - there may
862 be a small gain when turning off unused link types. The types are:
864 bracket The recommended [[link][description]] or [[link]] links with hiding.
865 angular Links in angular brackes that may contain whitespace like
866 <bbdb:Carsten Dominik>.
867 plain Plain links in normal text, no whitespace, like http://google.com.
868 radio Text that is matched by a radio target, see manual for details.
869 tag Tag settings in a headline (link to tag search).
870 date Time stamps (link to calendar).
872 Changing this variable requires a restart of Emacs to become effective."
873 :group 'org-link
874 :type '(set (const :tag "Double bracket links (new style)" bracket)
875 (const :tag "Angular bracket links (old style)" angular)
876 (const :tag "Plain text links" plain)
877 (const :tag "Radio target matches" radio)
878 (const :tag "Tags" tag)
879 (const :tag "Timestamps" date)))
881 (defcustom org-make-link-description-function nil
882 "Function to use to generate link descriptions from links. If
883 nil the link location will be used. This function must take two
884 parameters; the first is the link and the second the description
885 org-insert-link has generated, and should return the description
886 to use."
887 :group 'org-link
888 :type 'function)
890 (defgroup org-link-store nil
891 "Options concerning storing links in Org-mode."
892 :tag "Org Store Link"
893 :group 'org-link)
895 (defcustom org-email-link-description-format "Email %c: %.30s"
896 "Format of the description part of a link to an email or usenet message.
897 The following %-excapes will be replaced by corresponding information:
899 %F full \"From\" field
900 %f name, taken from \"From\" field, address if no name
901 %T full \"To\" field
902 %t first name in \"To\" field, address if no name
903 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
904 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
905 %s subject
906 %m message-id.
908 You may use normal field width specification between the % and the letter.
909 This is for example useful to limit the length of the subject.
911 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
912 :group 'org-link-store
913 :type 'string)
915 (defcustom org-from-is-user-regexp
916 (let (r1 r2)
917 (when (and user-mail-address (not (string= user-mail-address "")))
918 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
919 (when (and user-full-name (not (string= user-full-name "")))
920 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
921 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
922 "Regexp mached against the \"From:\" header of an email or usenet message.
923 It should match if the message is from the user him/herself."
924 :group 'org-link-store
925 :type 'regexp)
927 (defcustom org-context-in-file-links t
928 "Non-nil means, file links from `org-store-link' contain context.
929 A search string will be added to the file name with :: as separator and
930 used to find the context when the link is activated by the command
931 `org-open-at-point'.
932 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
933 negates this setting for the duration of the command."
934 :group 'org-link-store
935 :type 'boolean)
937 (defcustom org-keep-stored-link-after-insertion nil
938 "Non-nil means, keep link in list for entire session.
940 The command `org-store-link' adds a link pointing to the current
941 location to an internal list. These links accumulate during a session.
942 The command `org-insert-link' can be used to insert links into any
943 Org-mode file (offering completion for all stored links). When this
944 option is nil, every link which has been inserted once using \\[org-insert-link]
945 will be removed from the list, to make completing the unused links
946 more efficient."
947 :group 'org-link-store
948 :type 'boolean)
950 (defgroup org-link-follow nil
951 "Options concerning following links in Org-mode."
952 :tag "Org Follow Link"
953 :group 'org-link)
955 (defcustom org-follow-link-hook nil
956 "Hook that is run after a link has been followed."
957 :group 'org-link-follow
958 :type 'hook)
960 (defcustom org-tab-follows-link nil
961 "Non-nil means, on links TAB will follow the link.
962 Needs to be set before org.el is loaded."
963 :group 'org-link-follow
964 :type 'boolean)
966 (defcustom org-return-follows-link nil
967 "Non-nil means, on links RET will follow the link.
968 Needs to be set before org.el is loaded."
969 :group 'org-link-follow
970 :type 'boolean)
972 (defcustom org-mouse-1-follows-link
973 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
974 "Non-nil means, mouse-1 on a link will follow the link.
975 A longer mouse click will still set point. Does not work on XEmacs.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-mark-ring-length 4
981 "Number of different positions to be recorded in the ring
982 Changing this requires a restart of Emacs to work correctly."
983 :group 'org-link-follow
984 :type 'interger)
986 (defcustom org-link-frame-setup
987 '((vm . vm-visit-folder-other-frame)
988 (gnus . gnus-other-frame)
989 (file . find-file-other-window))
990 "Setup the frame configuration for following links.
991 When following a link with Emacs, it may often be useful to display
992 this link in another window or frame. This variable can be used to
993 set this up for the different types of links.
994 For VM, use any of
995 `vm-visit-folder'
996 `vm-visit-folder-other-frame'
997 For Gnus, use any of
998 `gnus'
999 `gnus-other-frame'
1000 For FILE, use any of
1001 `find-file'
1002 `find-file-other-window'
1003 `find-file-other-frame'
1004 For the calendar, use the variable `calendar-setup'.
1005 For BBDB, it is currently only possible to display the matches in
1006 another window."
1007 :group 'org-link-follow
1008 :type '(list
1009 (cons (const vm)
1010 (choice
1011 (const vm-visit-folder)
1012 (const vm-visit-folder-other-window)
1013 (const vm-visit-folder-other-frame)))
1014 (cons (const gnus)
1015 (choice
1016 (const gnus)
1017 (const gnus-other-frame)))
1018 (cons (const file)
1019 (choice
1020 (const find-file)
1021 (const find-file-other-window)
1022 (const find-file-other-frame)))))
1024 (defcustom org-display-internal-link-with-indirect-buffer nil
1025 "Non-nil means, use indirect buffer to display infile links.
1026 Activating internal links (from one location in a file to another location
1027 in the same file) normally just jumps to the location. When the link is
1028 activated with a C-u prefix (or with mouse-3), the link is displayed in
1029 another window. When this option is set, the other window actually displays
1030 an indirect buffer clone of the current buffer, to avoid any visibility
1031 changes to the current buffer."
1032 :group 'org-link-follow
1033 :type 'boolean)
1035 (defcustom org-open-non-existing-files nil
1036 "Non-nil means, `org-open-file' will open non-existing files.
1037 When nil, an error will be generated."
1038 :group 'org-link-follow
1039 :type 'boolean)
1041 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1042 "Function and arguments to call for following mailto links.
1043 This is a list with the first element being a lisp function, and the
1044 remaining elements being arguments to the function. In string arguments,
1045 %a will be replaced by the address, and %s will be replaced by the subject
1046 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1047 :group 'org-link-follow
1048 :type '(choice
1049 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1050 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1051 (const :tag "message-mail" (message-mail "%a" "%s"))
1052 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1054 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1055 "Non-nil means, ask for confirmation before executing shell links.
1056 Shell links can be dangerous: just think about a link
1058 [[shell:rm -rf ~/*][Google Search]]
1060 This link would show up in your Org-mode document as \"Google Search\",
1061 but really it would remove your entire home directory.
1062 Therefore we advise against setting this variable to nil.
1063 Just change it to `y-or-n-p' of you want to confirm with a
1064 single keystroke rather than having to type \"yes\"."
1065 :group 'org-link-follow
1066 :type '(choice
1067 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1068 (const :tag "with y-or-n (faster)" y-or-n-p)
1069 (const :tag "no confirmation (dangerous)" nil)))
1071 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1072 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1073 Elisp links can be dangerous: just think about a link
1075 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1077 This link would show up in your Org-mode document as \"Google Search\",
1078 but really it would remove your entire home directory.
1079 Therefore we advise against setting this variable to nil.
1080 Just change it to `y-or-n-p' of you want to confirm with a
1081 single keystroke rather than having to type \"yes\"."
1082 :group 'org-link-follow
1083 :type '(choice
1084 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1085 (const :tag "with y-or-n (faster)" y-or-n-p)
1086 (const :tag "no confirmation (dangerous)" nil)))
1088 (defconst org-file-apps-defaults-gnu
1089 '((remote . emacs)
1090 (t . mailcap))
1091 "Default file applications on a UNIX or GNU/Linux system.
1092 See `org-file-apps'.")
1094 (defconst org-file-apps-defaults-macosx
1095 '((remote . emacs)
1096 (t . "open %s")
1097 ("ps" . "gv %s")
1098 ("ps.gz" . "gv %s")
1099 ("eps" . "gv %s")
1100 ("eps.gz" . "gv %s")
1101 ("dvi" . "xdvi %s")
1102 ("fig" . "xfig %s"))
1103 "Default file applications on a MacOS X system.
1104 The system \"open\" is known as a default, but we use X11 applications
1105 for some files for which the OS does not have a good default.
1106 See `org-file-apps'.")
1108 (defconst org-file-apps-defaults-windowsnt
1109 (list
1110 '(remote . emacs)
1111 (cons t
1112 (list (if (featurep 'xemacs)
1113 'mswindows-shell-execute
1114 'w32-shell-execute)
1115 "open" 'file)))
1116 "Default file applications on a Windows NT system.
1117 The system \"open\" is used for most files.
1118 See `org-file-apps'.")
1120 (defcustom org-file-apps
1122 ("txt" . emacs)
1123 ("tex" . emacs)
1124 ("ltx" . emacs)
1125 ("org" . emacs)
1126 ("el" . emacs)
1127 ("bib" . emacs)
1129 "External applications for opening `file:path' items in a document.
1130 Org-mode uses system defaults for different file types, but
1131 you can use this variable to set the application for a given file
1132 extension. The entries in this list are cons cells where the car identifies
1133 files and the cdr the corresponding command. Possible values for the
1134 file identifier are
1135 \"ext\" A string identifying an extension
1136 `directory' Matches a directory
1137 `remote' Matches a remote file, accessible through tramp or efs.
1138 Remote files most likely should be visited through Emacs
1139 because external applications cannot handle such paths.
1140 t Default for all remaining files
1142 Possible values for the command are:
1143 `emacs' The file will be visited by the current Emacs process.
1144 `default' Use the default application for this file type.
1145 string A command to be executed by a shell; %s will be replaced
1146 by the path to the file.
1147 sexp A Lisp form which will be evaluated. The file path will
1148 be available in the Lisp variable `file'.
1149 For more examples, see the system specific constants
1150 `org-file-apps-defaults-macosx'
1151 `org-file-apps-defaults-windowsnt'
1152 `org-file-apps-defaults-gnu'."
1153 :group 'org-link-follow
1154 :type '(repeat
1155 (cons (choice :value ""
1156 (string :tag "Extension")
1157 (const :tag "Default for unrecognized files" t)
1158 (const :tag "Remote file" remote)
1159 (const :tag "Links to a directory" directory))
1160 (choice :value ""
1161 (const :tag "Visit with Emacs" emacs)
1162 (const :tag "Use system default" default)
1163 (string :tag "Command")
1164 (sexp :tag "Lisp form")))))
1166 (defgroup org-refile nil
1167 "Options concerning refiling entries in Org-mode."
1168 :tag "Org Remember"
1169 :group 'org)
1171 (defcustom org-directory "~/org"
1172 "Directory with org files.
1173 This directory will be used as default to prompt for org files.
1174 Used by the hooks for remember.el."
1175 :group 'org-refile
1176 :group 'org-remember
1177 :type 'directory)
1179 (defcustom org-default-notes-file "~/.notes"
1180 "Default target for storing notes.
1181 Used by the hooks for remember.el. This can be a string, or nil to mean
1182 the value of `remember-data-file'.
1183 You can set this on a per-template basis with the variable
1184 `org-remember-templates'."
1185 :group 'org-refile
1186 :group 'org-remember
1187 :type '(choice
1188 (const :tag "Default from remember-data-file" nil)
1189 file))
1191 (defcustom org-goto-interface 'outline
1192 "The default interface to be used for `org-goto'.
1193 Allowed vaues are:
1194 outline The interface shows an outline of the relevant file
1195 and the correct heading is found by moving through
1196 the outline or by searching with incremental search.
1197 outline-path-completion Headlines in the current buffer are offered via
1198 completion."
1199 :group 'org-refile
1200 :type '(choice
1201 (const :tag "Outline" outline)
1202 (const :tag "Outline-path-completion" outline-path-completion)))
1204 (defcustom org-reverse-note-order nil
1205 "Non-nil means, store new notes at the beginning of a file or entry.
1206 When nil, new notes will be filed to the end of a file or entry.
1207 This can also be a list with cons cells of regular expressions that
1208 are matched against file names, and values."
1209 :group 'org-remember
1210 :type '(choice
1211 (const :tag "Reverse always" t)
1212 (const :tag "Reverse never" nil)
1213 (repeat :tag "By file name regexp"
1214 (cons regexp boolean))))
1216 (defcustom org-refile-targets nil
1217 "Targets for refiling entries with \\[org-refile].
1218 This is list of cons cells. Each cell contains:
1219 - a specification of the files to be considered, either a list of files,
1220 or a symbol whose function or variable value will be used to retrieve
1221 a file name or a list of file names. Nil means, refile to a different
1222 heading in the current buffer.
1223 - A specification of how to find candidate refile targets. This may be
1224 any of
1225 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1226 This tag has to be present in all target headlines, inheritance will
1227 not be considered.
1228 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1229 todo keyword.
1230 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1231 headlines that are refiling targets.
1232 - a cons cell (:level . N). Any headline of level N is considered a target.
1233 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1234 :group 'org-remember
1235 :type '(repeat
1236 (cons
1237 (choice :value org-agenda-files
1238 (const :tag "All agenda files" org-agenda-files)
1239 (const :tag "Current buffer" nil)
1240 (function) (variable) (file))
1241 (choice :tag "Identify target headline by"
1242 (cons :tag "Specific tag" (const :tag) (string))
1243 (cons :tag "TODO keyword" (const :todo) (string))
1244 (cons :tag "Regular expression" (const :regexp) (regexp))
1245 (cons :tag "Level number" (const :level) (integer))
1246 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1248 (defcustom org-refile-use-outline-path nil
1249 "Non-nil means, provide refile targets as paths.
1250 So a level 3 headline will be available as level1/level2/level3.
1251 When the value is `file', also include the file name (without directory)
1252 into the path. When `full-file-path', include the full file path."
1253 :group 'org-remember
1254 :type '(choice
1255 (const :tag "Not" nil)
1256 (const :tag "Yes" t)
1257 (const :tag "Start with file name" file)
1258 (const :tag "Start with full file path" full-file-path)))
1260 (defgroup org-todo nil
1261 "Options concerning TODO items in Org-mode."
1262 :tag "Org TODO"
1263 :group 'org)
1265 (defgroup org-progress nil
1266 "Options concerning Progress logging in Org-mode."
1267 :tag "Org Progress"
1268 :group 'org-time)
1270 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1271 "List of TODO entry keyword sequences and their interpretation.
1272 \\<org-mode-map>This is a list of sequences.
1274 Each sequence starts with a symbol, either `sequence' or `type',
1275 indicating if the keywords should be interpreted as a sequence of
1276 action steps, or as different types of TODO items. The first
1277 keywords are states requiring action - these states will select a headline
1278 for inclusion into the global TODO list Org-mode produces. If one of
1279 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1280 signify that no further action is necessary. If \"|\" is not found,
1281 the last keyword is treated as the only DONE state of the sequence.
1283 The command \\[org-todo] cycles an entry through these states, and one
1284 additional state where no keyword is present. For details about this
1285 cycling, see the manual.
1287 TODO keywords and interpretation can also be set on a per-file basis with
1288 the special #+SEQ_TODO and #+TYP_TODO lines.
1290 Each keyword can optionally specify a character for fast state selection
1291 \(in combination with the variable `org-use-fast-todo-selection')
1292 and specifiers for state change logging, using the same syntax
1293 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1294 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1295 indicates to record a time stamp each time this state is selected.
1297 Each keyword may also specify if a timestamp or a note should be
1298 recorded when entering or leaving the state, by adding additional
1299 characters in the parenthesis after the keyword. This looks like this:
1300 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1301 record only the time of the state change. With X and Y being either
1302 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1303 Y when leaving the state if and only if the *target* state does not
1304 define X. You may omit any of the fast-selection key or X or /Y,
1305 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1307 For backward compatibility, this variable may also be just a list
1308 of keywords - in this case the interptetation (sequence or type) will be
1309 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1310 :group 'org-todo
1311 :group 'org-keywords
1312 :type '(choice
1313 (repeat :tag "Old syntax, just keywords"
1314 (string :tag "Keyword"))
1315 (repeat :tag "New syntax"
1316 (cons
1317 (choice
1318 :tag "Interpretation"
1319 (const :tag "Sequence (cycling hits every state)" sequence)
1320 (const :tag "Type (cycling directly to DONE)" type))
1321 (repeat
1322 (string :tag "Keyword"))))))
1324 (defvar org-todo-keywords-1 nil
1325 "All TODO and DONE keywords active in a buffer.")
1326 (make-variable-buffer-local 'org-todo-keywords-1)
1327 (defvar org-todo-keywords-for-agenda nil)
1328 (defvar org-done-keywords-for-agenda nil)
1329 (defvar org-agenda-contributing-files nil)
1330 (defvar org-not-done-keywords nil)
1331 (make-variable-buffer-local 'org-not-done-keywords)
1332 (defvar org-done-keywords nil)
1333 (make-variable-buffer-local 'org-done-keywords)
1334 (defvar org-todo-heads nil)
1335 (make-variable-buffer-local 'org-todo-heads)
1336 (defvar org-todo-sets nil)
1337 (make-variable-buffer-local 'org-todo-sets)
1338 (defvar org-todo-log-states nil)
1339 (make-variable-buffer-local 'org-todo-log-states)
1340 (defvar org-todo-kwd-alist nil)
1341 (make-variable-buffer-local 'org-todo-kwd-alist)
1342 (defvar org-todo-key-alist nil)
1343 (make-variable-buffer-local 'org-todo-key-alist)
1344 (defvar org-todo-key-trigger nil)
1345 (make-variable-buffer-local 'org-todo-key-trigger)
1347 (defcustom org-todo-interpretation 'sequence
1348 "Controls how TODO keywords are interpreted.
1349 This variable is in principle obsolete and is only used for
1350 backward compatibility, if the interpretation of todo keywords is
1351 not given already in `org-todo-keywords'. See that variable for
1352 more information."
1353 :group 'org-todo
1354 :group 'org-keywords
1355 :type '(choice (const sequence)
1356 (const type)))
1358 (defcustom org-use-fast-todo-selection 'prefix
1359 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1360 This variable describes if and under what circumstances the cycling
1361 mechanism for TODO keywords will be replaced by a single-key, direct
1362 selection scheme.
1364 When nil, fast selection is never used.
1366 When the symbol `prefix', it will be used when `org-todo' is called with
1367 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1368 in an agenda buffer.
1370 When t, fast selection is used by default. In this case, the prefix
1371 argument forces cycling instead.
1373 In all cases, the special interface is only used if access keys have actually
1374 been assigned by the user, i.e. if keywords in the configuration are followed
1375 by a letter in parenthesis, like TODO(t)."
1376 :group 'org-todo
1377 :type '(choice
1378 (const :tag "Never" nil)
1379 (const :tag "By default" t)
1380 (const :tag "Only with C-u C-c C-t" prefix)))
1382 (defcustom org-after-todo-state-change-hook nil
1383 "Hook which is run after the state of a TODO item was changed.
1384 The new state (a string with a TODO keyword, or nil) is available in the
1385 Lisp variable `state'."
1386 :group 'org-todo
1387 :type 'hook)
1389 (defcustom org-log-done nil
1390 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1391 When equal to the list (done), also prompt for a closing note.
1392 This can also be configured on a per-file basis by adding one of
1393 the following lines anywhere in the buffer:
1395 #+STARTUP: logdone
1396 #+STARTUP: lognotedone
1397 #+STARTUP: nologdone"
1398 :group 'org-todo
1399 :group 'org-progress
1400 :type '(choice
1401 (const :tag "No logging" nil)
1402 (const :tag "Record CLOSED timestamp" time)
1403 (const :tag "Record CLOSED timestamp with closing note." note)))
1405 ;; Normalize old uses of org-log-done.
1406 (cond
1407 ((eq org-log-done t) (setq org-log-done 'time))
1408 ((and (listp org-log-done) (memq 'done org-log-done))
1409 (setq org-log-done 'note)))
1411 (defcustom org-log-note-clock-out nil
1412 "Non-nil means, recored a note when clocking out of an item.
1413 This can also be configured on a per-file basis by adding one of
1414 the following lines anywhere in the buffer:
1416 #+STARTUP: lognoteclock-out
1417 #+STARTUP: nolognoteclock-out"
1418 :group 'org-todo
1419 :group 'org-progress
1420 :type 'boolean)
1422 (defcustom org-log-done-with-time t
1423 "Non-nil means, the CLOSED time stamp will contain date and time.
1424 When nil, only the date will be recorded."
1425 :group 'org-progress
1426 :type 'boolean)
1428 (defcustom org-log-note-headings
1429 '((done . "CLOSING NOTE %t")
1430 (state . "State %-12s %t")
1431 (note . "Note taken on %t")
1432 (clock-out . ""))
1433 "Headings for notes added to entries.
1434 The value is an alist, with the car being a symbol indicating the note
1435 context, and the cdr is the heading to be used. The heading may also be the
1436 empty string.
1437 %t in the heading will be replaced by a time stamp.
1438 %s will be replaced by the new TODO state, in double quotes.
1439 %u will be replaced by the user name.
1440 %U will be replaced by the full user name."
1441 :group 'org-todo
1442 :group 'org-progress
1443 :type '(list :greedy t
1444 (cons (const :tag "Heading when closing an item" done) string)
1445 (cons (const :tag
1446 "Heading when changing todo state (todo sequence only)"
1447 state) string)
1448 (cons (const :tag "Heading when just taking a note" note) string)
1449 (cons (const :tag "Heading when clocking out" clock-out) string)))
1451 (unless (assq 'note org-log-note-headings)
1452 (push '(note . "%t") org-log-note-headings))
1454 (defcustom org-log-states-order-reversed t
1455 "Non-nil means, the latest state change note will be directly after heading.
1456 When nil, the notes will be orderer according to time."
1457 :group 'org-todo
1458 :group 'org-progress
1459 :type 'boolean)
1461 (defcustom org-log-repeat 'time
1462 "Non-nil means, record moving through the DONE state when triggering repeat.
1463 An auto-repeating tasks is immediately switched back to TODO when marked
1464 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1465 the TODO keyword definition, or recording a closing note by setting
1466 `org-log-done', there will be no record of the task moving through DONE.
1467 This variable forces taking a note anyway. Possible values are:
1469 nil Don't force a record
1470 time Record a time stamp
1471 note Record a note
1473 This option can also be set with on a per-file-basis with
1475 #+STARTUP: logrepeat
1476 #+STARTUP: lognoterepeat
1477 #+STARTUP: nologrepeat
1479 You can have local logging settings for a subtree by setting the LOGGING
1480 property to one or more of these keywords."
1481 :group 'org-todo
1482 :group 'org-progress
1483 :type '(choice
1484 (const :tag "Don't force a record" nil)
1485 (const :tag "Force recording the DONE state" time)
1486 (const :tag "Force recording a note with the DONE state" note)))
1489 (defgroup org-priorities nil
1490 "Priorities in Org-mode."
1491 :tag "Org Priorities"
1492 :group 'org-todo)
1494 (defcustom org-highest-priority ?A
1495 "The highest priority of TODO items. A character like ?A, ?B etc.
1496 Must have a smaller ASCII number than `org-lowest-priority'."
1497 :group 'org-priorities
1498 :type 'character)
1500 (defcustom org-lowest-priority ?C
1501 "The lowest priority of TODO items. A character like ?A, ?B etc.
1502 Must have a larger ASCII number than `org-highest-priority'."
1503 :group 'org-priorities
1504 :type 'character)
1506 (defcustom org-default-priority ?B
1507 "The default priority of TODO items.
1508 This is the priority an item get if no explicit priority is given."
1509 :group 'org-priorities
1510 :type 'character)
1512 (defcustom org-priority-start-cycle-with-default t
1513 "Non-nil means, start with default priority when starting to cycle.
1514 When this is nil, the first step in the cycle will be (depending on the
1515 command used) one higher or lower that the default priority."
1516 :group 'org-priorities
1517 :type 'boolean)
1519 (defgroup org-time nil
1520 "Options concerning time stamps and deadlines in Org-mode."
1521 :tag "Org Time"
1522 :group 'org)
1524 (defcustom org-insert-labeled-timestamps-at-point nil
1525 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1526 When nil, these labeled time stamps are forces into the second line of an
1527 entry, just after the headline. When scheduling from the global TODO list,
1528 the time stamp will always be forced into the second line."
1529 :group 'org-time
1530 :type 'boolean)
1532 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1533 "Formats for `format-time-string' which are used for time stamps.
1534 It is not recommended to change this constant.")
1536 (defcustom org-time-stamp-rounding-minutes '(0 5)
1537 "Number of minutes to round time stamps to.
1538 These are two values, the first applies when first creating a time stamp.
1539 The second applies when changing it with the commands `S-up' and `S-down'.
1540 When changing the time stamp, this means that it will change in steps
1541 of N minutes, as given by the second value.
1543 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1544 numbers should be factors of 60, so for example 5, 10, 15.
1546 When this is larger than 1, you can still force an exact time-stamp by using
1547 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1548 and by using a prefix arg to `S-up/down' to specify the exact number
1549 of minutes to shift."
1550 :group 'org-time
1551 :get '(lambda (var) ; Make sure all entries have 5 elements
1552 (if (integerp (default-value var))
1553 (list (default-value var) 5)
1554 (default-value var)))
1555 :type '(list
1556 (integer :tag "when inserting times")
1557 (integer :tag "when modifying times")))
1559 ;; Normalize old customizations of this variable.
1560 (when (integerp org-time-stamp-rounding-minutes)
1561 (setq org-time-stamp-rounding-minutes
1562 (list org-time-stamp-rounding-minutes
1563 org-time-stamp-rounding-minutes)))
1565 (defcustom org-display-custom-times nil
1566 "Non-nil means, overlay custom formats over all time stamps.
1567 The formats are defined through the variable `org-time-stamp-custom-formats'.
1568 To turn this on on a per-file basis, insert anywhere in the file:
1569 #+STARTUP: customtime"
1570 :group 'org-time
1571 :set 'set-default
1572 :type 'sexp)
1573 (make-variable-buffer-local 'org-display-custom-times)
1575 (defcustom org-time-stamp-custom-formats
1576 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1577 "Custom formats for time stamps. See `format-time-string' for the syntax.
1578 These are overlayed over the default ISO format if the variable
1579 `org-display-custom-times' is set. Time like %H:%M should be at the
1580 end of the second format."
1581 :group 'org-time
1582 :type 'sexp)
1584 (defun org-time-stamp-format (&optional long inactive)
1585 "Get the right format for a time string."
1586 (let ((f (if long (cdr org-time-stamp-formats)
1587 (car org-time-stamp-formats))))
1588 (if inactive
1589 (concat "[" (substring f 1 -1) "]")
1590 f)))
1592 (defcustom org-deadline-warning-days 14
1593 "No. of days before expiration during which a deadline becomes active.
1594 This variable governs the display in sparse trees and in the agenda.
1595 When 0 or negative, it means use this number (the absolute value of it)
1596 even if a deadline has a different individual lead time specified."
1597 :group 'org-time
1598 :group 'org-agenda-daily/weekly
1599 :type 'number)
1601 (defcustom org-read-date-prefer-future t
1602 "Non-nil means, assume future for incomplete date input from user.
1603 This affects the following situations:
1604 1. The user gives a day, but no month.
1605 For example, if today is the 15th, and you enter \"3\", Org-mode will
1606 read this as the third of *next* month. However, if you enter \"17\",
1607 it will be considered as *this* month.
1608 2. The user gives a month but not a year.
1609 For example, if it is april and you enter \"feb 2\", this will be read
1610 as feb 2, *next* year. \"May 5\", however, will be this year.
1612 Currently this does not work for ISO week specifications.
1614 When this option is nil, the current month and year will always be used
1615 as defaults."
1616 :group 'org-time
1617 :type 'boolean)
1619 (defcustom org-read-date-display-live t
1620 "Non-nil means, display current interpretation of date prompt live.
1621 This display will be in an overlay, in the minibuffer."
1622 :group 'org-time
1623 :type 'boolean)
1625 (defcustom org-read-date-popup-calendar t
1626 "Non-nil means, pop up a calendar when prompting for a date.
1627 In the calendar, the date can be selected with mouse-1. However, the
1628 minibuffer will also be active, and you can simply enter the date as well.
1629 When nil, only the minibuffer will be available."
1630 :group 'org-time
1631 :type 'boolean)
1632 (if (fboundp 'defvaralias)
1633 (defvaralias 'org-popup-calendar-for-date-prompt
1634 'org-read-date-popup-calendar))
1636 (defcustom org-extend-today-until 0
1637 "The hour when your day really ends.
1638 This has influence for the following applications:
1639 - When switching the agenda to \"today\". It it is still earlier than
1640 the time given here, the day recognized as TODAY is actually yesterday.
1641 - When a date is read from the user and it is still before the time given
1642 here, the current date and time will be assumed to be yesterday, 23:59.
1644 FIXME:
1645 IMPORTANT: This is still a very experimental feature, it may disappear
1646 again or it may be extended to mean more things."
1647 :group 'org-time
1648 :type 'number)
1650 (defcustom org-edit-timestamp-down-means-later nil
1651 "Non-nil means, S-down will increase the time in a time stamp.
1652 When nil, S-up will increase."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-calendar-follow-timestamp-change t
1657 "Non-nil means, make the calendar window follow timestamp changes.
1658 When a timestamp is modified and the calendar window is visible, it will be
1659 moved to the new date."
1660 :group 'org-time
1661 :type 'boolean)
1663 (defgroup org-tags nil
1664 "Options concerning tags in Org-mode."
1665 :tag "Org Tags"
1666 :group 'org)
1668 (defcustom org-tag-alist nil
1669 "List of tags allowed in Org-mode files.
1670 When this list is nil, Org-mode will base TAG input on what is already in the
1671 buffer.
1672 The value of this variable is an alist, the car of each entry must be a
1673 keyword as a string, the cdr may be a character that is used to select
1674 that tag through the fast-tag-selection interface.
1675 See the manual for details."
1676 :group 'org-tags
1677 :type '(repeat
1678 (choice
1679 (cons (string :tag "Tag name")
1680 (character :tag "Access char"))
1681 (const :tag "Start radio group" (:startgroup))
1682 (const :tag "End radio group" (:endgroup)))))
1684 (defcustom org-use-fast-tag-selection 'auto
1685 "Non-nil means, use fast tag selection scheme.
1686 This is a special interface to select and deselect tags with single keys.
1687 When nil, fast selection is never used.
1688 When the symbol `auto', fast selection is used if and only if selection
1689 characters for tags have been configured, either through the variable
1690 `org-tag-alist' or through a #+TAGS line in the buffer.
1691 When t, fast selection is always used and selection keys are assigned
1692 automatically if necessary."
1693 :group 'org-tags
1694 :type '(choice
1695 (const :tag "Always" t)
1696 (const :tag "Never" nil)
1697 (const :tag "When selection characters are configured" 'auto)))
1699 (defcustom org-fast-tag-selection-single-key nil
1700 "Non-nil means, fast tag selection exits after first change.
1701 When nil, you have to press RET to exit it.
1702 During fast tag selection, you can toggle this flag with `C-c'.
1703 This variable can also have the value `expert'. In this case, the window
1704 displaying the tags menu is not even shown, until you press C-c again."
1705 :group 'org-tags
1706 :type '(choice
1707 (const :tag "No" nil)
1708 (const :tag "Yes" t)
1709 (const :tag "Expert" expert)))
1711 (defvar org-fast-tag-selection-include-todo nil
1712 "Non-nil means, fast tags selection interface will also offer TODO states.
1713 This is an undocumented feature, you should not rely on it.")
1715 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1716 "The column to which tags should be indented in a headline.
1717 If this number is positive, it specifies the column. If it is negative,
1718 it means that the tags should be flushright to that column. For example,
1719 -80 works well for a normal 80 character screen."
1720 :group 'org-tags
1721 :type 'integer)
1723 (defcustom org-auto-align-tags t
1724 "Non-nil means, realign tags after pro/demotion of TODO state change.
1725 These operations change the length of a headline and therefore shift
1726 the tags around. With this options turned on, after each such operation
1727 the tags are again aligned to `org-tags-column'."
1728 :group 'org-tags
1729 :type 'boolean)
1731 (defcustom org-use-tag-inheritance t
1732 "Non-nil means, tags in levels apply also for sublevels.
1733 When nil, only the tags directly given in a specific line apply there.
1734 If you turn off this option, you very likely want to turn on the
1735 companion option `org-tags-match-list-sublevels'.
1737 This may also be a list of tags that should be inherited, or a regexp that
1738 matches tags that should be inherited."
1739 :group 'org-tags
1740 :type '(choice
1741 (const :tag "Not" nil)
1742 (const :tag "Always" t)
1743 (repeat :tag "Specific tags" (string :tag "Tag"))
1744 (regexp :tag "Tags matched by regexp")))
1746 (defun org-tag-inherit-p (tag)
1747 "Check if TAG is one that should be inherited."
1748 (cond
1749 ((eq org-use-tag-inheritance t) t)
1750 ((not org-use-tag-inheritance) nil)
1751 ((stringp org-use-tag-inheritance)
1752 (string-match org-use-tag-inheritance tag))
1753 ((listp org-use-tag-inheritance)
1754 (member tag org-use-tag-inheritance))
1755 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1757 (defcustom org-tags-match-list-sublevels nil
1758 "Non-nil means list also sublevels of headlines matching tag search.
1759 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1760 the sublevels of a headline matching a tag search often also match
1761 the same search. Listing all of them can create very long lists.
1762 Setting this variable to nil causes subtrees of a match to be skipped.
1763 This option is off by default, because inheritance in on. If you turn
1764 inheritance off, you very likely want to turn this option on.
1766 As a special case, if the tag search is restricted to TODO items, the
1767 value of this variable is ignored and sublevels are always checked, to
1768 make sure all corresponding TODO items find their way into the list."
1769 :group 'org-tags
1770 :type 'boolean)
1772 (defvar org-tags-history nil
1773 "History of minibuffer reads for tags.")
1774 (defvar org-last-tags-completion-table nil
1775 "The last used completion table for tags.")
1776 (defvar org-after-tags-change-hook nil
1777 "Hook that is run after the tags in a line have changed.")
1779 (defgroup org-properties nil
1780 "Options concerning properties in Org-mode."
1781 :tag "Org Properties"
1782 :group 'org)
1784 (defcustom org-property-format "%-10s %s"
1785 "How property key/value pairs should be formatted by `indent-line'.
1786 When `indent-line' hits a property definition, it will format the line
1787 according to this format, mainly to make sure that the values are
1788 lined-up with respect to each other."
1789 :group 'org-properties
1790 :type 'string)
1792 (defcustom org-use-property-inheritance nil
1793 "Non-nil means, properties apply also for sublevels.
1795 This setting is chiefly used during property searches. Turning it on can
1796 cause significant overhead when doing a search, which is why it is not
1797 on by default.
1799 When nil, only the properties directly given in the current entry count.
1800 When t, every property is inherited. The value may also be a list of
1801 properties that should have inheritance, or a regular expression matching
1802 properties that should be inherited.
1804 However, note that some special properties use inheritance under special
1805 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1806 and the properties ending in \"_ALL\" when they are used as descriptor
1807 for valid values of a property.
1809 Note for programmers:
1810 When querying an entry with `org-entry-get', you can control if inheritance
1811 should be used. By default, `org-entry-get' looks only at the local
1812 properties. You can request inheritance by setting the inherit argument
1813 to t (to force inheritance) or to `selective' (to respect the setting
1814 in this variable)."
1815 :group 'org-properties
1816 :type '(choice
1817 (const :tag "Not" nil)
1818 (const :tag "Always" t)
1819 (repeat :tag "Specific properties" (string :tag "Property"))
1820 (regexp :tag "Properties matched by regexp")))
1822 (defun org-property-inherit-p (property)
1823 "Check if PROPERTY is one that should be inherited."
1824 (cond
1825 ((eq org-use-property-inheritance t) t)
1826 ((not org-use-property-inheritance) nil)
1827 ((stringp org-use-property-inheritance)
1828 (string-match org-use-property-inheritance property))
1829 ((listp org-use-property-inheritance)
1830 (member property org-use-property-inheritance))
1831 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1833 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1834 "The default column format, if no other format has been defined.
1835 This variable can be set on the per-file basis by inserting a line
1837 #+COLUMNS: %25ITEM ....."
1838 :group 'org-properties
1839 :type 'string)
1841 (defcustom org-effort-property "Effort"
1842 "The property that is being used to keep track of effort estimates.
1843 Effort estimates given in this property need to have the format H:MM."
1844 :group 'org-properties
1845 :group 'org-progress
1846 :type '(string :tag "Property"))
1848 (defcustom org-global-properties nil
1849 "List of property/value pairs that can be inherited by any entry.
1850 You can set buffer-local values for this by adding lines like
1852 #+PROPERTY: NAME VALUE"
1853 :group 'org-properties
1854 :type '(repeat
1855 (cons (string :tag "Property")
1856 (string :tag "Value"))))
1858 (defvar org-local-properties nil
1859 "List of property/value pairs that can be inherited by any entry.
1860 Valid for the current buffer.
1861 This variable is populated from #+PROPERTY lines.")
1863 (defgroup org-agenda nil
1864 "Options concerning agenda views in Org-mode."
1865 :tag "Org Agenda"
1866 :group 'org)
1868 (defvar org-category nil
1869 "Variable used by org files to set a category for agenda display.
1870 Such files should use a file variable to set it, for example
1872 # -*- mode: org; org-category: \"ELisp\"
1874 or contain a special line
1876 #+CATEGORY: ELisp
1878 If the file does not specify a category, then file's base name
1879 is used instead.")
1880 (make-variable-buffer-local 'org-category)
1882 (defcustom org-agenda-files nil
1883 "The files to be used for agenda display.
1884 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1885 \\[org-remove-file]. You can also use customize to edit the list.
1887 If an entry is a directory, all files in that directory that are matched by
1888 `org-agenda-file-regexp' will be part of the file list.
1890 If the value of the variable is not a list but a single file name, then
1891 the list of agenda files is actually stored and maintained in that file, one
1892 agenda file per line."
1893 :group 'org-agenda
1894 :type '(choice
1895 (repeat :tag "List of files and directories" file)
1896 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1898 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1899 "Regular expression to match files for `org-agenda-files'.
1900 If any element in the list in that variable contains a directory instead
1901 of a normal file, all files in that directory that are matched by this
1902 regular expression will be included."
1903 :group 'org-agenda
1904 :type 'regexp)
1906 (defcustom org-agenda-text-search-extra-files nil
1907 "List of extra files to be searched by text search commands.
1908 These files will be search in addition to the agenda files by the
1909 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1910 Note that these files will only be searched for text search commands,
1911 not for the other agenda views like todo lists, tag searches or the weekly
1912 agenda. This variable is intended to list notes and possibly archive files
1913 that should also be searched by these two commands.
1914 In fact, if the first element in the list is the symbol `agenda-archives',
1915 than all archive files of all agenda files will be added to the search
1916 scope."
1917 :group 'org-agenda
1918 :type '(set :greedy t
1919 (const :tag "Agenda Archives" agenda-archives)
1920 (repeat :inline t (file))))
1922 (if (fboundp 'defvaralias)
1923 (defvaralias 'org-agenda-multi-occur-extra-files
1924 'org-agenda-text-search-extra-files))
1926 (defcustom org-agenda-skip-unavailable-files nil
1927 "t means to just skip non-reachable files in `org-agenda-files'.
1928 Nil means to remove them, after a query, from the list."
1929 :group 'org-agenda
1930 :type 'boolean)
1932 (defcustom org-calendar-to-agenda-key [?c]
1933 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1934 The command `org-calendar-goto-agenda' will be bound to this key. The
1935 default is the character `c' because then `c' can be used to switch back and
1936 forth between agenda and calendar."
1937 :group 'org-agenda
1938 :type 'sexp)
1940 (eval-after-load "calendar"
1941 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1942 'org-calendar-goto-agenda))
1944 (defgroup org-latex nil
1945 "Options for embedding LaTeX code into Org-mode."
1946 :tag "Org LaTeX"
1947 :group 'org)
1949 (defcustom org-format-latex-options
1950 '(:foreground default :background default :scale 1.0
1951 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1952 :matchers ("begin" "$" "$$" "\\(" "\\["))
1953 "Options for creating images from LaTeX fragments.
1954 This is a property list with the following properties:
1955 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1956 `default' means use the forground of the default face.
1957 :background the background color, or \"Transparent\".
1958 `default' means use the background of the default face.
1959 :scale a scaling factor for the size of the images
1960 :html-foreground, :html-background, :html-scale
1961 The same numbers for HTML export.
1962 :matchers a list indicating which matchers should be used to
1963 find LaTeX fragments. Valid members of this list are:
1964 \"begin\" find environments
1965 \"$\" find math expressions surrounded by $...$
1966 \"$$\" find math expressions surrounded by $$....$$
1967 \"\\(\" find math expressions surrounded by \\(...\\)
1968 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1969 :group 'org-latex
1970 :type 'plist)
1972 (defcustom org-format-latex-header "\\documentclass{article}
1973 \\usepackage{fullpage} % do not remove
1974 \\usepackage{amssymb}
1975 \\usepackage[usenames]{color}
1976 \\usepackage{amsmath}
1977 \\usepackage{latexsym}
1978 \\usepackage[mathscr]{eucal}
1979 \\pagestyle{empty} % do not remove"
1980 "The document header used for processing LaTeX fragments."
1981 :group 'org-latex
1982 :type 'string)
1985 (defgroup org-font-lock nil
1986 "Font-lock settings for highlighting in Org-mode."
1987 :tag "Org Font Lock"
1988 :group 'org)
1990 (defcustom org-level-color-stars-only nil
1991 "Non-nil means fontify only the stars in each headline.
1992 When nil, the entire headline is fontified.
1993 Changing it requires restart of `font-lock-mode' to become effective
1994 also in regions already fontified."
1995 :group 'org-font-lock
1996 :type 'boolean)
1998 (defcustom org-hide-leading-stars nil
1999 "Non-nil means, hide the first N-1 stars in a headline.
2000 This works by using the face `org-hide' for these stars. This
2001 face is white for a light background, and black for a dark
2002 background. You may have to customize the face `org-hide' to
2003 make this work.
2004 Changing it requires restart of `font-lock-mode' to become effective
2005 also in regions already fontified.
2006 You may also set this on a per-file basis by adding one of the following
2007 lines to the buffer:
2009 #+STARTUP: hidestars
2010 #+STARTUP: showstars"
2011 :group 'org-font-lock
2012 :type 'boolean)
2014 (defcustom org-fontify-done-headline nil
2015 "Non-nil means, change the face of a headline if it is marked DONE.
2016 Normally, only the TODO/DONE keyword indicates the state of a headline.
2017 When this is non-nil, the headline after the keyword is set to the
2018 `org-headline-done' as an additional indication."
2019 :group 'org-font-lock
2020 :type 'boolean)
2022 (defcustom org-fontify-emphasized-text t
2023 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2024 Changing this variable requires a restart of Emacs to take effect."
2025 :group 'org-font-lock
2026 :type 'boolean)
2028 (defcustom org-highlight-latex-fragments-and-specials nil
2029 "Non-nil means, fontify what is treated specially by the exporters."
2030 :group 'org-font-lock
2031 :type 'boolean)
2033 (defcustom org-hide-emphasis-markers nil
2034 "Non-nil mean font-lock should hide the emphasis marker characters."
2035 :group 'org-font-lock
2036 :type 'boolean)
2038 (defvar org-emph-re nil
2039 "Regular expression for matching emphasis.")
2040 (defvar org-verbatim-re nil
2041 "Regular expression for matching verbatim text.")
2042 (defvar org-emphasis-regexp-components) ; defined just below
2043 (defvar org-emphasis-alist) ; defined just below
2044 (defun org-set-emph-re (var val)
2045 "Set variable and compute the emphasis regular expression."
2046 (set var val)
2047 (when (and (boundp 'org-emphasis-alist)
2048 (boundp 'org-emphasis-regexp-components)
2049 org-emphasis-alist org-emphasis-regexp-components)
2050 (let* ((e org-emphasis-regexp-components)
2051 (pre (car e))
2052 (post (nth 1 e))
2053 (border (nth 2 e))
2054 (body (nth 3 e))
2055 (nl (nth 4 e))
2056 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2057 (body1 (concat body "*?"))
2058 (markers (mapconcat 'car org-emphasis-alist ""))
2059 (vmarkers (mapconcat
2060 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2061 org-emphasis-alist "")))
2062 ;; make sure special characters appear at the right position in the class
2063 (if (string-match "\\^" markers)
2064 (setq markers (concat (replace-match "" t t markers) "^")))
2065 (if (string-match "-" markers)
2066 (setq markers (concat (replace-match "" t t markers) "-")))
2067 (if (string-match "\\^" vmarkers)
2068 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2069 (if (string-match "-" vmarkers)
2070 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2071 (if (> nl 0)
2072 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2073 (int-to-string nl) "\\}")))
2074 ;; Make the regexp
2075 (setq org-emph-re
2076 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2077 "\\("
2078 "\\([" markers "]\\)"
2079 "\\("
2080 "[^" border "]\\|"
2081 "[^" border (if (and nil stacked) markers) "]"
2082 body1
2083 "[^" border (if (and nil stacked) markers) "]"
2084 "\\)"
2085 "\\3\\)"
2086 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2087 (setq org-verbatim-re
2088 (concat "\\([" pre "]\\|^\\)"
2089 "\\("
2090 "\\([" vmarkers "]\\)"
2091 "\\("
2092 "[^" border "]\\|"
2093 "[^" border "]"
2094 body1
2095 "[^" border "]"
2096 "\\)"
2097 "\\3\\)"
2098 "\\([" post "]\\|$\\)")))))
2100 (defcustom org-emphasis-regexp-components
2101 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2102 "Components used to build the regular expression for emphasis.
2103 This is a list with 6 entries. Terminology: In an emphasis string
2104 like \" *strong word* \", we call the initial space PREMATCH, the final
2105 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2106 and \"trong wor\" is the body. The different components in this variable
2107 specify what is allowed/forbidden in each part:
2109 pre Chars allowed as prematch. Beginning of line will be allowed too.
2110 post Chars allowed as postmatch. End of line will be allowed too.
2111 border The chars *forbidden* as border characters.
2112 body-regexp A regexp like \".\" to match a body character. Don't use
2113 non-shy groups here, and don't allow newline here.
2114 newline The maximum number of newlines allowed in an emphasis exp.
2116 Use customize to modify this, or restart Emacs after changing it."
2117 :group 'org-font-lock
2118 :set 'org-set-emph-re
2119 :type '(list
2120 (sexp :tag "Allowed chars in pre ")
2121 (sexp :tag "Allowed chars in post ")
2122 (sexp :tag "Forbidden chars in border ")
2123 (sexp :tag "Regexp for body ")
2124 (integer :tag "number of newlines allowed")
2125 (option (boolean :tag "Stacking (DISABLED) "))))
2127 (defcustom org-emphasis-alist
2128 `(("*" bold "<b>" "</b>")
2129 ("/" italic "<i>" "</i>")
2130 ("_" underline "<u>" "</u>")
2131 ("=" org-code "<code>" "</code>" verbatim)
2132 ("~" org-verbatim "" "" verbatim)
2133 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2134 "<del>" "</del>")
2136 "Special syntax for emphasized text.
2137 Text starting and ending with a special character will be emphasized, for
2138 example *bold*, _underlined_ and /italic/. This variable sets the marker
2139 characters, the face to be used by font-lock for highlighting in Org-mode
2140 Emacs buffers, and the HTML tags to be used for this.
2141 Use customize to modify this, or restart Emacs after changing it."
2142 :group 'org-font-lock
2143 :set 'org-set-emph-re
2144 :type '(repeat
2145 (list
2146 (string :tag "Marker character")
2147 (choice
2148 (face :tag "Font-lock-face")
2149 (plist :tag "Face property list"))
2150 (string :tag "HTML start tag")
2151 (string :tag "HTML end tag")
2152 (option (const verbatim)))))
2154 ;;; Miscellaneous options
2156 (defgroup org-completion nil
2157 "Completion in Org-mode."
2158 :tag "Org Completion"
2159 :group 'org)
2161 (defcustom org-completion-fallback-command 'hippie-expand
2162 "The expansion command called by \\[org-complete] in normal context.
2163 Normal means, no org-mode-specific context."
2164 :group 'org-completion
2165 :type 'function)
2167 ;;; Functions and variables from ther packages
2168 ;; Declared here to avoid compiler warnings
2170 ;; XEmacs only
2171 (defvar outline-mode-menu-heading)
2172 (defvar outline-mode-menu-show)
2173 (defvar outline-mode-menu-hide)
2174 (defvar zmacs-regions) ; XEmacs regions
2176 ;; Emacs only
2177 (defvar mark-active)
2179 ;; Various packages
2180 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2181 (declare-function calendar-forward-day "cal-move" (arg))
2182 (declare-function calendar-goto-date "cal-move" (date))
2183 (declare-function calendar-goto-today "cal-move" ())
2184 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2185 (defvar calc-embedded-close-formula)
2186 (defvar calc-embedded-open-formula)
2187 (declare-function cdlatex-tab "ext:cdlatex" ())
2188 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2189 (defvar font-lock-unfontify-region-function)
2190 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2191 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2192 (defvar iswitchb-temp-buflist)
2193 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2194 (declare-function org-agenda-skip "org-agenda" ())
2195 (declare-function org-format-agenda-item "org-agenda"
2196 (extra txt &optional category tags dotime noprefix remove-re))
2197 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2198 (declare-function org-agenda-change-all-lines "org-agenda"
2199 (newhead hdmarker &optional fixface))
2200 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2201 (declare-function org-agenda-maybe-redo "org-agenda" ())
2202 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2203 (beg end))
2204 (declare-function parse-time-string "parse-time" (string))
2205 (declare-function remember "remember" (&optional initial))
2206 (declare-function remember-buffer-desc "remember" ())
2207 (declare-function remember-finalize "remember" ())
2208 (defvar remember-save-after-remembering)
2209 (defvar remember-data-file)
2210 (defvar remember-register)
2211 (defvar remember-buffer)
2212 (defvar remember-handler-functions)
2213 (defvar remember-annotation-functions)
2214 (defvar texmathp-why)
2215 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2216 (declare-function table--at-cell-p "table" (position &optional object at-column))
2218 (defvar w3m-current-url)
2219 (defvar w3m-current-title)
2221 (defvar org-latex-regexps)
2223 ;;; Autoload and prepare some org modules
2225 ;; Some table stuff that needs to be defined here, because it is used
2226 ;; by the functions setting up org-mode or checking for table context.
2228 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2229 "Detects an org-type or table-type table.")
2230 (defconst org-table-line-regexp "^[ \t]*|"
2231 "Detects an org-type table line.")
2232 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2233 "Detects an org-type table line.")
2234 (defconst org-table-hline-regexp "^[ \t]*|-"
2235 "Detects an org-type table hline.")
2236 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2237 "Detects a table-type table hline.")
2238 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2239 "Searching from within a table (any type) this finds the first line
2240 outside the table.")
2242 ;; Autoload the functions in org-table.el that are needed by functions here.
2244 (eval-and-compile
2245 (org-autoload "org-table"
2246 '(org-table-align org-table-begin org-table-blank-field
2247 org-table-convert org-table-convert-region org-table-copy-down
2248 org-table-copy-region org-table-create
2249 org-table-create-or-convert-from-region
2250 org-table-create-with-table.el org-table-current-dline
2251 org-table-cut-region org-table-delete-column org-table-edit-field
2252 org-table-edit-formulas org-table-end org-table-eval-formula
2253 org-table-export org-table-field-info
2254 org-table-get-stored-formulas org-table-goto-column
2255 org-table-hline-and-move org-table-import org-table-insert-column
2256 org-table-insert-hline org-table-insert-row org-table-iterate
2257 org-table-justify-field-maybe org-table-kill-row
2258 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2259 org-table-move-column org-table-move-column-left
2260 org-table-move-column-right org-table-move-row
2261 org-table-move-row-down org-table-move-row-up
2262 org-table-next-field org-table-next-row org-table-paste-rectangle
2263 org-table-previous-field org-table-recalculate
2264 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2265 org-table-toggle-coordinate-overlays
2266 org-table-toggle-formula-debugger org-table-wrap-region
2267 orgtbl-mode turn-on-orgtbl)))
2269 (defun org-at-table-p (&optional table-type)
2270 "Return t if the cursor is inside an org-type table.
2271 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2272 (if org-enable-table-editor
2273 (save-excursion
2274 (beginning-of-line 1)
2275 (looking-at (if table-type org-table-any-line-regexp
2276 org-table-line-regexp)))
2277 nil))
2278 (defsubst org-table-p () (org-at-table-p))
2280 (defun org-at-table.el-p ()
2281 "Return t if and only if we are at a table.el table."
2282 (and (org-at-table-p 'any)
2283 (save-excursion
2284 (goto-char (org-table-begin 'any))
2285 (looking-at org-table1-hline-regexp))))
2286 (defun org-table-recognize-table.el ()
2287 "If there is a table.el table nearby, recognize it and move into it."
2288 (if org-table-tab-recognizes-table.el
2289 (if (org-at-table.el-p)
2290 (progn
2291 (beginning-of-line 1)
2292 (if (looking-at org-table-dataline-regexp)
2294 (if (looking-at org-table1-hline-regexp)
2295 (progn
2296 (beginning-of-line 2)
2297 (if (looking-at org-table-any-border-regexp)
2298 (beginning-of-line -1)))))
2299 (if (re-search-forward "|" (org-table-end t) t)
2300 (progn
2301 (require 'table)
2302 (if (table--at-cell-p (point))
2304 (message "recognizing table.el table...")
2305 (table-recognize-table)
2306 (message "recognizing table.el table...done")))
2307 (error "This should not happen..."))
2309 nil)
2310 nil))
2312 (defun org-at-table-hline-p ()
2313 "Return t if the cursor is inside a hline in a table."
2314 (if org-enable-table-editor
2315 (save-excursion
2316 (beginning-of-line 1)
2317 (looking-at org-table-hline-regexp))
2318 nil))
2320 (defvar org-table-clean-did-remove-column nil)
2322 (defun org-table-map-tables (function)
2323 "Apply FUNCTION to the start of all tables in the buffer."
2324 (save-excursion
2325 (save-restriction
2326 (widen)
2327 (goto-char (point-min))
2328 (while (re-search-forward org-table-any-line-regexp nil t)
2329 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2330 (beginning-of-line 1)
2331 (if (looking-at org-table-line-regexp)
2332 (save-excursion (funcall function)))
2333 (re-search-forward org-table-any-border-regexp nil 1))))
2334 (message "Mapping tables: done"))
2336 ;; Declare and autoload functions from org-exp.el
2338 (declare-function org-default-export-plist "org-exp")
2339 (declare-function org-infile-export-plist "org-exp")
2340 (declare-function org-get-current-options "org-exp")
2341 (eval-and-compile
2342 (org-autoload "org-exp"
2343 '(org-export org-export-as-ascii org-export-visible
2344 org-insert-export-options-template org-export-as-html-and-open
2345 org-export-as-html-batch org-export-as-html-to-buffer
2346 org-replace-region-by-html org-export-region-as-html
2347 org-export-as-html org-export-icalendar-this-file
2348 org-export-icalendar-all-agenda-files
2349 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2351 ;; Declare and autoload functions from org-exp.el
2353 (eval-and-compile
2354 (org-autoload "org-exp"
2355 '(org-agenda org-agenda-list org-search-view
2356 org-todo-list org-tags-view org-agenda-list-stuck-projects
2357 org-diary org-agenda-to-appt)))
2359 ;; Autoload org-remember
2361 (eval-and-compile
2362 (org-autoload "org-remember"
2363 '(org-remember-insinuate org-remember-annotation
2364 org-remember-apply-template org-remember org-remember-handler)))
2366 ;; Autoload org-clock.el
2369 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2370 (beg end))
2371 (defvar org-clock-marker (make-marker)
2372 "Marker recording the last clock-in.")
2374 (eval-and-compile
2375 (org-autoload
2376 "org-clock"
2377 '(org-clock-in org-clock-out org-clock-cancel
2378 org-clock-goto org-clock-sum org-clock-display
2379 org-remove-clock-overlays org-clock-report
2380 org-clocktable-shift org-dblock-write:clocktable
2381 org-get-clocktable)))
2383 (defun org-clock-update-time-maybe ()
2384 "If this is a CLOCK line, update it and return t.
2385 Otherwise, return nil."
2386 (interactive)
2387 (save-excursion
2388 (beginning-of-line 1)
2389 (skip-chars-forward " \t")
2390 (when (looking-at org-clock-string)
2391 (let ((re (concat "[ \t]*" org-clock-string
2392 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2393 "\\([ \t]*=>.*\\)?"))
2394 ts te h m s)
2395 (if (not (looking-at re))
2397 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2398 (end-of-line 1)
2399 (setq ts (match-string 1)
2400 te (match-string 2))
2401 (setq s (- (time-to-seconds
2402 (apply 'encode-time (org-parse-time-string te)))
2403 (time-to-seconds
2404 (apply 'encode-time (org-parse-time-string ts))))
2405 h (floor (/ s 3600))
2406 s (- s (* 3600 h))
2407 m (floor (/ s 60))
2408 s (- s (* 60 s)))
2409 (insert " => " (format "%2d:%02d" h m))
2410 t)))))
2412 (defun org-check-running-clock ()
2413 "Check if the current buffer contains the running clock.
2414 If yes, offer to stop it and to save the buffer with the changes."
2415 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2416 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2417 (buffer-name))))
2418 (org-clock-out)
2419 (when (y-or-n-p "Save changed buffer?")
2420 (save-buffer))))
2422 (defun org-clocktable-try-shift (dir n)
2423 "Check if this line starts a clock table, if yes, shift the time block."
2424 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2425 (org-clocktable-shift dir n)))
2427 ;; Autoload archiving code
2428 ;; The stuff that is needed for cycling and tags has to be defined here.
2430 (defgroup org-archive nil
2431 "Options concerning archiving in Org-mode."
2432 :tag "Org Archive"
2433 :group 'org-structure)
2435 (defcustom org-archive-location "%s_archive::"
2436 "The location where subtrees should be archived.
2438 Otherwise, the value of this variable is a string, consisting of two
2439 parts, separated by a double-colon.
2441 The first part is a file name - when omitted, archiving happens in the same
2442 file. %s will be replaced by the current file name (without directory part).
2443 Archiving to a different file is useful to keep archived entries from
2444 contributing to the Org-mode Agenda.
2446 The part after the double colon is a headline. The archived entries will be
2447 filed under that headline. When omitted, the subtrees are simply filed away
2448 at the end of the file, as top-level entries.
2450 Here are a few examples:
2451 \"%s_archive::\"
2452 If the current file is Projects.org, archive in file
2453 Projects.org_archive, as top-level trees. This is the default.
2455 \"::* Archived Tasks\"
2456 Archive in the current file, under the top-level headline
2457 \"* Archived Tasks\".
2459 \"~/org/archive.org::\"
2460 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2462 \"basement::** Finished Tasks\"
2463 Archive in file ./basement (relative path), as level 3 trees
2464 below the level 2 heading \"** Finished Tasks\".
2466 You may set this option on a per-file basis by adding to the buffer a
2467 line like
2469 #+ARCHIVE: basement::** Finished Tasks
2471 You may also define it locally for a subtree by setting an ARCHIVE property
2472 in the entry. If such a property is found in an entry, or anywhere up
2473 the hierarchy, it will be used."
2474 :group 'org-archive
2475 :type 'string)
2477 (defcustom org-archive-tag "ARCHIVE"
2478 "The tag that marks a subtree as archived.
2479 An archived subtree does not open during visibility cycling, and does
2480 not contribute to the agenda listings.
2481 After changing this, font-lock must be restarted in the relevant buffers to
2482 get the proper fontification."
2483 :group 'org-archive
2484 :group 'org-keywords
2485 :type 'string)
2487 (defcustom org-agenda-skip-archived-trees t
2488 "Non-nil means, the agenda will skip any items located in archived trees.
2489 An archived tree is a tree marked with the tag ARCHIVE."
2490 :group 'org-archive
2491 :group 'org-agenda-skip
2492 :type 'boolean)
2494 (defcustom org-cycle-open-archived-trees nil
2495 "Non-nil means, `org-cycle' will open archived trees.
2496 An archived tree is a tree marked with the tag ARCHIVE.
2497 When nil, archived trees will stay folded. You can still open them with
2498 normal outline commands like `show-all', but not with the cycling commands."
2499 :group 'org-archive
2500 :group 'org-cycle
2501 :type 'boolean)
2503 (defcustom org-sparse-tree-open-archived-trees nil
2504 "Non-nil means sparse tree construction shows matches in archived trees.
2505 When nil, matches in these trees are highlighted, but the trees are kept in
2506 collapsed state."
2507 :group 'org-archive
2508 :group 'org-sparse-trees
2509 :type 'boolean)
2511 (defun org-cycle-hide-archived-subtrees (state)
2512 "Re-hide all archived subtrees after a visibility state change."
2513 (when (and (not org-cycle-open-archived-trees)
2514 (not (memq state '(overview folded))))
2515 (save-excursion
2516 (let* ((globalp (memq state '(contents all)))
2517 (beg (if globalp (point-min) (point)))
2518 (end (if globalp (point-max) (org-end-of-subtree t))))
2519 (org-hide-archived-subtrees beg end)
2520 (goto-char beg)
2521 (if (looking-at (concat ".*:" org-archive-tag ":"))
2522 (message "%s" (substitute-command-keys
2523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2525 (defun org-force-cycle-archived ()
2526 "Cycle subtree even if it is archived."
2527 (interactive)
2528 (setq this-command 'org-cycle)
2529 (let ((org-cycle-open-archived-trees t))
2530 (call-interactively 'org-cycle)))
2532 (defun org-hide-archived-subtrees (beg end)
2533 "Re-hide all archived subtrees after a visibility state change."
2534 (save-excursion
2535 (let* ((re (concat ":" org-archive-tag ":")))
2536 (goto-char beg)
2537 (while (re-search-forward re end t)
2538 (and (org-on-heading-p) (hide-subtree))
2539 (org-end-of-subtree t)))))
2541 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2543 (eval-and-compile
2544 (org-autoload "org-archive"
2545 '(org-add-archive-files org-archive-subtree
2546 org-archive-to-archive-sibling org-toggle-archive-tag)))
2548 ;; Autoload Column View Code
2550 (declare-function org-columns-number-to-string "org-colview")
2551 (declare-function org-columns-get-format-and-top-level "org-colview")
2552 (declare-function org-columns-compute "org-colview")
2554 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2555 '(org-columns-number-to-string org-columns-get-format-and-top-level
2556 org-columns-compute org-agenda-columns org-columns-remove-overlays
2557 org-columns org-insert-columns-dblock))
2559 ;;; Variables for pre-computed regular expressions, all buffer local
2561 (defvar org-drawer-regexp nil
2562 "Matches first line of a hidden block.")
2563 (make-variable-buffer-local 'org-drawer-regexp)
2564 (defvar org-todo-regexp nil
2565 "Matches any of the TODO state keywords.")
2566 (make-variable-buffer-local 'org-todo-regexp)
2567 (defvar org-not-done-regexp nil
2568 "Matches any of the TODO state keywords except the last one.")
2569 (make-variable-buffer-local 'org-not-done-regexp)
2570 (defvar org-todo-line-regexp nil
2571 "Matches a headline and puts TODO state into group 2 if present.")
2572 (make-variable-buffer-local 'org-todo-line-regexp)
2573 (defvar org-complex-heading-regexp nil
2574 "Matches a headline and puts everything into groups:
2575 group 1: the stars
2576 group 2: The todo keyword, maybe
2577 group 3: Priority cookie
2578 group 4: True headline
2579 group 5: Tags")
2580 (make-variable-buffer-local 'org-complex-heading-regexp)
2581 (defvar org-todo-line-tags-regexp nil
2582 "Matches a headline and puts TODO state into group 2 if present.
2583 Also put tags into group 4 if tags are present.")
2584 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2585 (defvar org-nl-done-regexp nil
2586 "Matches newline followed by a headline with the DONE keyword.")
2587 (make-variable-buffer-local 'org-nl-done-regexp)
2588 (defvar org-looking-at-done-regexp nil
2589 "Matches the DONE keyword a point.")
2590 (make-variable-buffer-local 'org-looking-at-done-regexp)
2591 (defvar org-ds-keyword-length 12
2592 "Maximum length of the Deadline and SCHEDULED keywords.")
2593 (make-variable-buffer-local 'org-ds-keyword-length)
2594 (defvar org-deadline-regexp nil
2595 "Matches the DEADLINE keyword.")
2596 (make-variable-buffer-local 'org-deadline-regexp)
2597 (defvar org-deadline-time-regexp nil
2598 "Matches the DEADLINE keyword together with a time stamp.")
2599 (make-variable-buffer-local 'org-deadline-time-regexp)
2600 (defvar org-deadline-line-regexp nil
2601 "Matches the DEADLINE keyword and the rest of the line.")
2602 (make-variable-buffer-local 'org-deadline-line-regexp)
2603 (defvar org-scheduled-regexp nil
2604 "Matches the SCHEDULED keyword.")
2605 (make-variable-buffer-local 'org-scheduled-regexp)
2606 (defvar org-scheduled-time-regexp nil
2607 "Matches the SCHEDULED keyword together with a time stamp.")
2608 (make-variable-buffer-local 'org-scheduled-time-regexp)
2609 (defvar org-closed-time-regexp nil
2610 "Matches the CLOSED keyword together with a time stamp.")
2611 (make-variable-buffer-local 'org-closed-time-regexp)
2613 (defvar org-keyword-time-regexp nil
2614 "Matches any of the 4 keywords, together with the time stamp.")
2615 (make-variable-buffer-local 'org-keyword-time-regexp)
2616 (defvar org-keyword-time-not-clock-regexp nil
2617 "Matches any of the 3 keywords, together with the time stamp.")
2618 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2619 (defvar org-maybe-keyword-time-regexp nil
2620 "Matches a timestamp, possibly preceeded by a keyword.")
2621 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2622 (defvar org-planning-or-clock-line-re nil
2623 "Matches a line with planning or clock info.")
2624 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2626 (defconst org-plain-time-of-day-regexp
2627 (concat
2628 "\\(\\<[012]?[0-9]"
2629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2630 "\\(--?"
2631 "\\(\\<[012]?[0-9]"
2632 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2633 "\\)?")
2634 "Regular expression to match a plain time or time range.
2635 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2636 groups carry important information:
2637 0 the full match
2638 1 the first time, range or not
2639 8 the second time, if it is a range.")
2641 (defconst org-plain-time-extension-regexp
2642 (concat
2643 "\\(\\<[012]?[0-9]"
2644 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2645 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2646 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2647 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2648 groups carry important information:
2649 0 the full match
2650 7 hours of duration
2651 9 minutes of duration")
2653 (defconst org-stamp-time-of-day-regexp
2654 (concat
2655 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2656 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2657 "\\(--?"
2658 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2659 "Regular expression to match a timestamp time or time range.
2660 After a match, the following groups carry important information:
2661 0 the full match
2662 1 date plus weekday, for backreferencing to make sure both times on same day
2663 2 the first time, range or not
2664 4 the second time, if it is a range.")
2666 (defconst org-startup-options
2667 '(("fold" org-startup-folded t)
2668 ("overview" org-startup-folded t)
2669 ("nofold" org-startup-folded nil)
2670 ("showall" org-startup-folded nil)
2671 ("content" org-startup-folded content)
2672 ("hidestars" org-hide-leading-stars t)
2673 ("showstars" org-hide-leading-stars nil)
2674 ("odd" org-odd-levels-only t)
2675 ("oddeven" org-odd-levels-only nil)
2676 ("align" org-startup-align-all-tables t)
2677 ("noalign" org-startup-align-all-tables nil)
2678 ("customtime" org-display-custom-times t)
2679 ("logdone" org-log-done time)
2680 ("lognotedone" org-log-done note)
2681 ("nologdone" org-log-done nil)
2682 ("lognoteclock-out" org-log-note-clock-out t)
2683 ("nolognoteclock-out" org-log-note-clock-out nil)
2684 ("logrepeat" org-log-repeat state)
2685 ("lognoterepeat" org-log-repeat note)
2686 ("nologrepeat" org-log-repeat nil)
2687 ("constcgs" constants-unit-system cgs)
2688 ("constSI" constants-unit-system SI))
2689 "Variable associated with STARTUP options for org-mode.
2690 Each element is a list of three items: The startup options as written
2691 in the #+STARTUP line, the corresponding variable, and the value to
2692 set this variable to if the option is found. An optional forth element PUSH
2693 means to push this value onto the list in the variable.")
2695 (defun org-set-regexps-and-options ()
2696 "Precompute regular expressions for current buffer."
2697 (when (org-mode-p)
2698 (org-set-local 'org-todo-kwd-alist nil)
2699 (org-set-local 'org-todo-key-alist nil)
2700 (org-set-local 'org-todo-key-trigger nil)
2701 (org-set-local 'org-todo-keywords-1 nil)
2702 (org-set-local 'org-done-keywords nil)
2703 (org-set-local 'org-todo-heads nil)
2704 (org-set-local 'org-todo-sets nil)
2705 (org-set-local 'org-todo-log-states nil)
2706 (let ((re (org-make-options-regexp
2707 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2708 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2709 "CONSTANTS" "PROPERTY" "DRAWERS")))
2710 (splitre "[ \t]+")
2711 kwds kws0 kwsa key log value cat arch tags const links hw dws
2712 tail sep kws1 prio props drawers)
2713 (save-excursion
2714 (save-restriction
2715 (widen)
2716 (goto-char (point-min))
2717 (while (re-search-forward re nil t)
2718 (setq key (match-string 1) value (org-match-string-no-properties 2))
2719 (cond
2720 ((equal key "CATEGORY")
2721 (if (string-match "[ \t]+$" value)
2722 (setq value (replace-match "" t t value)))
2723 (setq cat value))
2724 ((member key '("SEQ_TODO" "TODO"))
2725 (push (cons 'sequence (org-split-string value splitre)) kwds))
2726 ((equal key "TYP_TODO")
2727 (push (cons 'type (org-split-string value splitre)) kwds))
2728 ((equal key "TAGS")
2729 (setq tags (append tags (org-split-string value splitre))))
2730 ((equal key "COLUMNS")
2731 (org-set-local 'org-columns-default-format value))
2732 ((equal key "LINK")
2733 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2734 (push (cons (match-string 1 value)
2735 (org-trim (match-string 2 value)))
2736 links)))
2737 ((equal key "PRIORITIES")
2738 (setq prio (org-split-string value " +")))
2739 ((equal key "PROPERTY")
2740 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2741 (push (cons (match-string 1 value) (match-string 2 value))
2742 props)))
2743 ((equal key "DRAWERS")
2744 (setq drawers (org-split-string value splitre)))
2745 ((equal key "CONSTANTS")
2746 (setq const (append const (org-split-string value splitre))))
2747 ((equal key "STARTUP")
2748 (let ((opts (org-split-string value splitre))
2749 l var val)
2750 (while (setq l (pop opts))
2751 (when (setq l (assoc l org-startup-options))
2752 (setq var (nth 1 l) val (nth 2 l))
2753 (if (not (nth 3 l))
2754 (set (make-local-variable var) val)
2755 (if (not (listp (symbol-value var)))
2756 (set (make-local-variable var) nil))
2757 (set (make-local-variable var) (symbol-value var))
2758 (add-to-list var val))))))
2759 ((equal key "ARCHIVE")
2760 (string-match " *$" value)
2761 (setq arch (replace-match "" t t value))
2762 (remove-text-properties 0 (length arch)
2763 '(face t fontified t) arch)))
2765 (when cat
2766 (org-set-local 'org-category (intern cat))
2767 (push (cons "CATEGORY" cat) props))
2768 (when prio
2769 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2770 (setq prio (mapcar 'string-to-char prio))
2771 (org-set-local 'org-highest-priority (nth 0 prio))
2772 (org-set-local 'org-lowest-priority (nth 1 prio))
2773 (org-set-local 'org-default-priority (nth 2 prio)))
2774 (and props (org-set-local 'org-local-properties (nreverse props)))
2775 (and drawers (org-set-local 'org-drawers drawers))
2776 (and arch (org-set-local 'org-archive-location arch))
2777 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2778 ;; Process the TODO keywords
2779 (unless kwds
2780 ;; Use the global values as if they had been given locally.
2781 (setq kwds (default-value 'org-todo-keywords))
2782 (if (stringp (car kwds))
2783 (setq kwds (list (cons org-todo-interpretation
2784 (default-value 'org-todo-keywords)))))
2785 (setq kwds (reverse kwds)))
2786 (setq kwds (nreverse kwds))
2787 (let (inter kws kw)
2788 (while (setq kws (pop kwds))
2789 (setq inter (pop kws) sep (member "|" kws)
2790 kws0 (delete "|" (copy-sequence kws))
2791 kwsa nil
2792 kws1 (mapcar
2793 (lambda (x)
2794 ;; 1 2
2795 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2796 (progn
2797 (setq kw (match-string 1 x)
2798 key (and (match-end 2) (match-string 2 x))
2799 log (org-extract-log-state-settings x))
2800 (push (cons kw (and key (string-to-char key))) kwsa)
2801 (and log (push log org-todo-log-states))
2803 (error "Invalid TODO keyword %s" x)))
2804 kws0)
2805 kwsa (if kwsa (append '((:startgroup))
2806 (nreverse kwsa)
2807 '((:endgroup))))
2808 hw (car kws1)
2809 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2810 tail (list inter hw (car dws) (org-last dws)))
2811 (add-to-list 'org-todo-heads hw 'append)
2812 (push kws1 org-todo-sets)
2813 (setq org-done-keywords (append org-done-keywords dws nil))
2814 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2815 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2816 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2817 (setq org-todo-sets (nreverse org-todo-sets)
2818 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2819 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2820 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2821 ;; Process the constants
2822 (when const
2823 (let (e cst)
2824 (while (setq e (pop const))
2825 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2826 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2827 (setq org-table-formula-constants-local cst)))
2829 ;; Process the tags.
2830 (when tags
2831 (let (e tgs)
2832 (while (setq e (pop tags))
2833 (cond
2834 ((equal e "{") (push '(:startgroup) tgs))
2835 ((equal e "}") (push '(:endgroup) tgs))
2836 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2837 (push (cons (match-string 1 e)
2838 (string-to-char (match-string 2 e)))
2839 tgs))
2840 (t (push (list e) tgs))))
2841 (org-set-local 'org-tag-alist nil)
2842 (while (setq e (pop tgs))
2843 (or (and (stringp (car e))
2844 (assoc (car e) org-tag-alist))
2845 (push e org-tag-alist))))))
2847 ;; Compute the regular expressions and other local variables
2848 (if (not org-done-keywords)
2849 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2850 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2851 (length org-scheduled-string)
2852 (length org-clock-string)
2853 (length org-closed-string)))
2854 org-drawer-regexp
2855 (concat "^[ \t]*:\\("
2856 (mapconcat 'regexp-quote org-drawers "\\|")
2857 "\\):[ \t]*$")
2858 org-not-done-keywords
2859 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2860 org-todo-regexp
2861 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2862 "\\|") "\\)\\>")
2863 org-not-done-regexp
2864 (concat "\\<\\("
2865 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2866 "\\)\\>")
2867 org-todo-line-regexp
2868 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2869 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2870 "\\)\\>\\)?[ \t]*\\(.*\\)")
2871 org-complex-heading-regexp
2872 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2873 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2874 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2875 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2876 org-nl-done-regexp
2877 (concat "\n\\*+[ \t]+"
2878 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2879 "\\)" "\\>")
2880 org-todo-line-tags-regexp
2881 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2882 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2883 (org-re
2884 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2885 org-looking-at-done-regexp
2886 (concat "^" "\\(?:"
2887 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2888 "\\>")
2889 org-deadline-regexp (concat "\\<" org-deadline-string)
2890 org-deadline-time-regexp
2891 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2892 org-deadline-line-regexp
2893 (concat "\\<\\(" org-deadline-string "\\).*")
2894 org-scheduled-regexp
2895 (concat "\\<" org-scheduled-string)
2896 org-scheduled-time-regexp
2897 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2898 org-closed-time-regexp
2899 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2900 org-keyword-time-regexp
2901 (concat "\\<\\(" org-scheduled-string
2902 "\\|" org-deadline-string
2903 "\\|" org-closed-string
2904 "\\|" org-clock-string "\\)"
2905 " *[[<]\\([^]>]+\\)[]>]")
2906 org-keyword-time-not-clock-regexp
2907 (concat "\\<\\(" org-scheduled-string
2908 "\\|" org-deadline-string
2909 "\\|" org-closed-string
2910 "\\)"
2911 " *[[<]\\([^]>]+\\)[]>]")
2912 org-maybe-keyword-time-regexp
2913 (concat "\\(\\<\\(" org-scheduled-string
2914 "\\|" org-deadline-string
2915 "\\|" org-closed-string
2916 "\\|" org-clock-string "\\)\\)?"
2917 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2918 org-planning-or-clock-line-re
2919 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2920 "\\|" org-deadline-string
2921 "\\|" org-closed-string "\\|" org-clock-string
2922 "\\)\\>\\)")
2924 (org-compute-latex-and-specials-regexp)
2925 (org-set-font-lock-defaults)))
2927 (defun org-extract-log-state-settings (x)
2928 "Extract the log state setting from a TODO keyword string.
2929 This will extract info from a string like \"WAIT(w@/!)\"."
2930 (let (kw key log1 log2)
2931 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2932 (setq kw (match-string 1 x)
2933 key (and (match-end 2) (match-string 2 x))
2934 log1 (and (match-end 3) (match-string 3 x))
2935 log2 (and (match-end 4) (match-string 4 x)))
2936 (and (or log1 log2)
2937 (list kw
2938 (and log1 (if (equal log1 "!") 'time 'note))
2939 (and log2 (if (equal log2 "!") 'time 'note)))))))
2941 (defun org-remove-keyword-keys (list)
2942 "Remove a pair of parenthesis at the end of each string in LIST."
2943 (mapcar (lambda (x)
2944 (if (string-match "(.*)$" x)
2945 (substring x 0 (match-beginning 0))
2947 list))
2949 ;; FIXME: this could be done much better, using second characters etc.
2950 (defun org-assign-fast-keys (alist)
2951 "Assign fast keys to a keyword-key alist.
2952 Respect keys that are already there."
2953 (let (new e k c c1 c2 (char ?a))
2954 (while (setq e (pop alist))
2955 (cond
2956 ((equal e '(:startgroup)) (push e new))
2957 ((equal e '(:endgroup)) (push e new))
2959 (setq k (car e) c2 nil)
2960 (if (cdr e)
2961 (setq c (cdr e))
2962 ;; automatically assign a character.
2963 (setq c1 (string-to-char
2964 (downcase (substring
2965 k (if (= (string-to-char k) ?@) 1 0)))))
2966 (if (or (rassoc c1 new) (rassoc c1 alist))
2967 (while (or (rassoc char new) (rassoc char alist))
2968 (setq char (1+ char)))
2969 (setq c2 c1))
2970 (setq c (or c2 char)))
2971 (push (cons k c) new))))
2972 (nreverse new)))
2974 ;;; Some variables used in various places
2976 (defvar org-window-configuration nil
2977 "Used in various places to store a window configuration.")
2978 (defvar org-finish-function nil
2979 "Function to be called when `C-c C-c' is used.
2980 This is for getting out of special buffers like remember.")
2983 ;; FIXME: Occasionally check by commenting these, to make sure
2984 ;; no other functions uses these, forgetting to let-bind them.
2985 (defvar entry)
2986 (defvar state)
2987 (defvar last-state)
2988 (defvar date)
2989 (defvar description)
2991 ;; Defined somewhere in this file, but used before definition.
2992 (defvar org-html-entities)
2993 (defvar org-struct-menu)
2994 (defvar org-org-menu)
2995 (defvar org-tbl-menu)
2996 (defvar org-agenda-keymap)
2998 ;;;; Define the Org-mode
3000 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3001 (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."))
3004 ;; We use a before-change function to check if a table might need
3005 ;; an update.
3006 (defvar org-table-may-need-update t
3007 "Indicates that a table might need an update.
3008 This variable is set by `org-before-change-function'.
3009 `org-table-align' sets it back to nil.")
3010 (defun org-before-change-function (beg end)
3011 "Every change indicates that a table might need an update."
3012 (setq org-table-may-need-update t))
3013 (defvar org-mode-map)
3014 (defvar org-mode-hook nil)
3015 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3016 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3017 (defvar org-table-buffer-is-an nil)
3018 (defconst org-outline-regexp "\\*+ ")
3020 ;;;###autoload
3021 (define-derived-mode org-mode outline-mode "Org"
3022 "Outline-based notes management and organizer, alias
3023 \"Carsten's outline-mode for keeping track of everything.\"
3025 Org-mode develops organizational tasks around a NOTES file which
3026 contains information about projects as plain text. Org-mode is
3027 implemented on top of outline-mode, which is ideal to keep the content
3028 of large files well structured. It supports ToDo items, deadlines and
3029 time stamps, which magically appear in the diary listing of the Emacs
3030 calendar. Tables are easily created with a built-in table editor.
3031 Plain text URL-like links connect to websites, emails (VM), Usenet
3032 messages (Gnus), BBDB entries, and any files related to the project.
3033 For printing and sharing of notes, an Org-mode file (or a part of it)
3034 can be exported as a structured ASCII or HTML file.
3036 The following commands are available:
3038 \\{org-mode-map}"
3040 ;; Get rid of Outline menus, they are not needed
3041 ;; Need to do this here because define-derived-mode sets up
3042 ;; the keymap so late. Still, it is a waste to call this each time
3043 ;; we switch another buffer into org-mode.
3044 (if (featurep 'xemacs)
3045 (when (boundp 'outline-mode-menu-heading)
3046 ;; Assume this is Greg's port, it used easymenu
3047 (easy-menu-remove outline-mode-menu-heading)
3048 (easy-menu-remove outline-mode-menu-show)
3049 (easy-menu-remove outline-mode-menu-hide))
3050 (define-key org-mode-map [menu-bar headings] 'undefined)
3051 (define-key org-mode-map [menu-bar hide] 'undefined)
3052 (define-key org-mode-map [menu-bar show] 'undefined))
3054 (org-load-modules-maybe)
3055 (easy-menu-add org-org-menu)
3056 (easy-menu-add org-tbl-menu)
3057 (org-install-agenda-files-menu)
3058 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3059 (org-add-to-invisibility-spec '(org-cwidth))
3060 (when (featurep 'xemacs)
3061 (org-set-local 'line-move-ignore-invisible t))
3062 (org-set-local 'outline-regexp org-outline-regexp)
3063 (org-set-local 'outline-level 'org-outline-level)
3064 (when (and org-ellipsis
3065 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3066 (fboundp 'make-glyph-code))
3067 (unless org-display-table
3068 (setq org-display-table (make-display-table)))
3069 (set-display-table-slot
3070 org-display-table 4
3071 (vconcat (mapcar
3072 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3073 org-ellipsis)))
3074 (if (stringp org-ellipsis) org-ellipsis "..."))))
3075 (setq buffer-display-table org-display-table))
3076 (org-set-regexps-and-options)
3077 ;; Calc embedded
3078 (org-set-local 'calc-embedded-open-mode "# ")
3079 (modify-syntax-entry ?# "<")
3080 (modify-syntax-entry ?@ "w")
3081 (if org-startup-truncated (setq truncate-lines t))
3082 (org-set-local 'font-lock-unfontify-region-function
3083 'org-unfontify-region)
3084 ;; Activate before-change-function
3085 (org-set-local 'org-table-may-need-update t)
3086 (org-add-hook 'before-change-functions 'org-before-change-function nil
3087 'local)
3088 ;; Check for running clock before killing a buffer
3089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3090 ;; Paragraphs and auto-filling
3091 (org-set-autofill-regexps)
3092 (setq indent-line-function 'org-indent-line-function)
3093 (org-update-radio-target-regexp)
3095 ;; Comment characters
3096 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3097 (org-set-local 'comment-padding " ")
3099 ;; Align options lines
3100 (org-set-local
3101 'align-mode-rules-list
3102 '((org-in-buffer-settings
3103 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3104 (modes . '(org-mode)))))
3106 ;; Imenu
3107 (org-set-local 'imenu-create-index-function
3108 'org-imenu-get-tree)
3110 ;; Make isearch reveal context
3111 (if (or (featurep 'xemacs)
3112 (not (boundp 'outline-isearch-open-invisible-function)))
3113 ;; Emacs 21 and XEmacs make use of the hook
3114 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3115 ;; Emacs 22 deals with this through a special variable
3116 (org-set-local 'outline-isearch-open-invisible-function
3117 (lambda (&rest ignore) (org-show-context 'isearch))))
3119 ;; If empty file that did not turn on org-mode automatically, make it to.
3120 (if (and org-insert-mode-line-in-empty-file
3121 (interactive-p)
3122 (= (point-min) (point-max)))
3123 (insert "# -*- mode: org -*-\n\n"))
3125 (unless org-inhibit-startup
3126 (when org-startup-align-all-tables
3127 (let ((bmp (buffer-modified-p)))
3128 (org-table-map-tables 'org-table-align)
3129 (set-buffer-modified-p bmp)))
3130 (org-cycle-hide-drawers 'all)
3131 (cond
3132 ((eq org-startup-folded t)
3133 (org-cycle '(4)))
3134 ((eq org-startup-folded 'content)
3135 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3136 (org-cycle '(4)) (org-cycle '(4)))))))
3138 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3140 (defun org-current-time ()
3141 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3142 (if (> (car org-time-stamp-rounding-minutes) 1)
3143 (let ((r (car org-time-stamp-rounding-minutes))
3144 (time (decode-time)))
3145 (apply 'encode-time
3146 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3147 (nthcdr 2 time))))
3148 (current-time)))
3150 ;;;; Font-Lock stuff, including the activators
3152 (defvar org-mouse-map (make-sparse-keymap))
3153 (org-defkey org-mouse-map
3154 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3155 (org-defkey org-mouse-map
3156 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3157 (when org-mouse-1-follows-link
3158 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3159 (when org-tab-follows-link
3160 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3161 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3162 (when org-return-follows-link
3163 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3164 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3166 (require 'font-lock)
3168 (defconst org-non-link-chars "]\t\n\r<>")
3169 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3170 "shell" "elisp"))
3171 (defvar org-link-types-re nil
3172 "Matches a link that has a url-like prefix like \"http:\"")
3173 (defvar org-link-re-with-space nil
3174 "Matches a link with spaces, optional angular brackets around it.")
3175 (defvar org-link-re-with-space2 nil
3176 "Matches a link with spaces, optional angular brackets around it.")
3177 (defvar org-angle-link-re nil
3178 "Matches link with angular brackets, spaces are allowed.")
3179 (defvar org-plain-link-re nil
3180 "Matches plain link, without spaces.")
3181 (defvar org-bracket-link-regexp nil
3182 "Matches a link in double brackets.")
3183 (defvar org-bracket-link-analytic-regexp nil
3184 "Regular expression used to analyze links.
3185 Here is what the match groups contain after a match:
3186 1: http:
3187 2: http
3188 3: path
3189 4: [desc]
3190 5: desc")
3191 (defvar org-any-link-re nil
3192 "Regular expression matching any link.")
3194 (defun org-make-link-regexps ()
3195 "Update the link regular expressions.
3196 This should be called after the variable `org-link-types' has changed."
3197 (setq org-link-types-re
3198 (concat
3199 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3200 org-link-re-with-space
3201 (concat
3202 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3203 "\\([^" org-non-link-chars " ]"
3204 "[^" org-non-link-chars "]*"
3205 "[^" org-non-link-chars " ]\\)>?")
3206 org-link-re-with-space2
3207 (concat
3208 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3209 "\\([^" org-non-link-chars " ]"
3210 "[^]\t\n\r]*"
3211 "[^" org-non-link-chars " ]\\)>?")
3212 org-angle-link-re
3213 (concat
3214 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3215 "\\([^" org-non-link-chars " ]"
3216 "[^" org-non-link-chars "]*"
3217 "\\)>")
3218 org-plain-link-re
3219 (concat
3220 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3221 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3222 org-bracket-link-regexp
3223 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3224 org-bracket-link-analytic-regexp
3225 (concat
3226 "\\[\\["
3227 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3228 "\\([^]]+\\)"
3229 "\\]"
3230 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3231 "\\]")
3232 org-any-link-re
3233 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3234 org-angle-link-re "\\)\\|\\("
3235 org-plain-link-re "\\)")))
3237 (org-make-link-regexps)
3239 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3240 "Regular expression for fast time stamp matching.")
3241 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3242 "Regular expression for fast time stamp matching.")
3243 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3244 "Regular expression matching time strings for analysis.
3245 This one does not require the space after the date, so it can be used
3246 on a string that terminates immediately after the date.")
3247 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3248 "Regular expression matching time strings for analysis.")
3249 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3250 "Regular expression matching time stamps, with groups.")
3251 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3252 "Regular expression matching time stamps (also [..]), with groups.")
3253 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3254 "Regular expression matching a time stamp range.")
3255 (defconst org-tr-regexp-both
3256 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3257 "Regular expression matching a time stamp range.")
3258 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3259 org-ts-regexp "\\)?")
3260 "Regular expression matching a time stamp or time stamp range.")
3261 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3262 org-ts-regexp-both "\\)?")
3263 "Regular expression matching a time stamp or time stamp range.
3264 The time stamps may be either active or inactive.")
3266 (defvar org-emph-face nil)
3268 (defun org-do-emphasis-faces (limit)
3269 "Run through the buffer and add overlays to links."
3270 (let (rtn)
3271 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3272 (if (not (= (char-after (match-beginning 3))
3273 (char-after (match-beginning 4))))
3274 (progn
3275 (setq rtn t)
3276 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3277 'face
3278 (nth 1 (assoc (match-string 3)
3279 org-emphasis-alist)))
3280 (add-text-properties (match-beginning 2) (match-end 2)
3281 '(font-lock-multiline t))
3282 (when org-hide-emphasis-markers
3283 (add-text-properties (match-end 4) (match-beginning 5)
3284 '(invisible org-link))
3285 (add-text-properties (match-beginning 3) (match-end 3)
3286 '(invisible org-link)))))
3287 (backward-char 1))
3288 rtn))
3290 (defun org-emphasize (&optional char)
3291 "Insert or change an emphasis, i.e. a font like bold or italic.
3292 If there is an active region, change that region to a new emphasis.
3293 If there is no region, just insert the marker characters and position
3294 the cursor between them.
3295 CHAR should be either the marker character, or the first character of the
3296 HTML tag associated with that emphasis. If CHAR is a space, the means
3297 to remove the emphasis of the selected region.
3298 If char is not given (for example in an interactive call) it
3299 will be prompted for."
3300 (interactive)
3301 (let ((eal org-emphasis-alist) e det
3302 (erc org-emphasis-regexp-components)
3303 (prompt "")
3304 (string "") beg end move tag c s)
3305 (if (org-region-active-p)
3306 (setq beg (region-beginning) end (region-end)
3307 string (buffer-substring beg end))
3308 (setq move t))
3310 (while (setq e (pop eal))
3311 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3312 c (aref tag 0))
3313 (push (cons c (string-to-char (car e))) det)
3314 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3315 (substring tag 1)))))
3316 (unless char
3317 (message "%s" (concat "Emphasis marker or tag:" prompt))
3318 (setq char (read-char-exclusive)))
3319 (setq char (or (cdr (assoc char det)) char))
3320 (if (equal char ?\ )
3321 (setq s "" move nil)
3322 (unless (assoc (char-to-string char) org-emphasis-alist)
3323 (error "No such emphasis marker: \"%c\"" char))
3324 (setq s (char-to-string char)))
3325 (while (and (> (length string) 1)
3326 (equal (substring string 0 1) (substring string -1))
3327 (assoc (substring string 0 1) org-emphasis-alist))
3328 (setq string (substring string 1 -1)))
3329 (setq string (concat s string s))
3330 (if beg (delete-region beg end))
3331 (unless (or (bolp)
3332 (string-match (concat "[" (nth 0 erc) "\n]")
3333 (char-to-string (char-before (point)))))
3334 (insert " "))
3335 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3336 (char-to-string (char-after (point))))
3337 (insert " ") (backward-char 1))
3338 (insert string)
3339 (and move (backward-char 1))))
3341 (defconst org-nonsticky-props
3342 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3345 (defun org-activate-plain-links (limit)
3346 "Run through the buffer and add overlays to links."
3347 (catch 'exit
3348 (let (f)
3349 (while (re-search-forward org-plain-link-re limit t)
3350 (setq f (get-text-property (match-beginning 0) 'face))
3351 (if (or (eq f 'org-tag)
3352 (and (listp f) (memq 'org-tag f)))
3354 (add-text-properties (match-beginning 0) (match-end 0)
3355 (list 'mouse-face 'highlight
3356 'rear-nonsticky org-nonsticky-props
3357 'keymap org-mouse-map
3359 (throw 'exit t))))))
3361 (defun org-activate-code (limit)
3362 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3363 (unless (get-text-property (match-beginning 1) 'face)
3364 (remove-text-properties (match-beginning 0) (match-end 0)
3365 '(display t invisible t intangible t))
3366 t)))
3368 (defun org-activate-angle-links (limit)
3369 "Run through the buffer and add overlays to links."
3370 (if (re-search-forward org-angle-link-re limit t)
3371 (progn
3372 (add-text-properties (match-beginning 0) (match-end 0)
3373 (list 'mouse-face 'highlight
3374 'rear-nonsticky org-nonsticky-props
3375 'keymap org-mouse-map
3377 t)))
3379 (defun org-activate-bracket-links (limit)
3380 "Run through the buffer and add overlays to bracketed links."
3381 (if (re-search-forward org-bracket-link-regexp limit t)
3382 (let* ((help (concat "LINK: "
3383 (org-match-string-no-properties 1)))
3384 ;; FIXME: above we should remove the escapes.
3385 ;; but that requires another match, protecting match data,
3386 ;; a lot of overhead for font-lock.
3387 (ip (org-maybe-intangible
3388 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3389 'keymap org-mouse-map 'mouse-face 'highlight
3390 'font-lock-multiline t 'help-echo help)))
3391 (vp (list 'rear-nonsticky org-nonsticky-props
3392 'keymap org-mouse-map 'mouse-face 'highlight
3393 ' font-lock-multiline t 'help-echo help)))
3394 ;; We need to remove the invisible property here. Table narrowing
3395 ;; may have made some of this invisible.
3396 (remove-text-properties (match-beginning 0) (match-end 0)
3397 '(invisible nil))
3398 (if (match-end 3)
3399 (progn
3400 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3401 (add-text-properties (match-beginning 3) (match-end 3) vp)
3402 (add-text-properties (match-end 3) (match-end 0) ip))
3403 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3404 (add-text-properties (match-beginning 1) (match-end 1) vp)
3405 (add-text-properties (match-end 1) (match-end 0) ip))
3406 t)))
3408 (defun org-activate-dates (limit)
3409 "Run through the buffer and add overlays to dates."
3410 (if (re-search-forward org-tsr-regexp-both limit t)
3411 (progn
3412 (add-text-properties (match-beginning 0) (match-end 0)
3413 (list 'mouse-face 'highlight
3414 'rear-nonsticky org-nonsticky-props
3415 'keymap org-mouse-map))
3416 (when org-display-custom-times
3417 (if (match-end 3)
3418 (org-display-custom-time (match-beginning 3) (match-end 3)))
3419 (org-display-custom-time (match-beginning 1) (match-end 1)))
3420 t)))
3422 (defvar org-target-link-regexp nil
3423 "Regular expression matching radio targets in plain text.")
3424 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3425 "Regular expression matching a link target.")
3426 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3427 "Regular expression matching a radio target.")
3428 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3429 "Regular expression matching any target.")
3431 (defun org-activate-target-links (limit)
3432 "Run through the buffer and add overlays to target matches."
3433 (when org-target-link-regexp
3434 (let ((case-fold-search t))
3435 (if (re-search-forward org-target-link-regexp limit t)
3436 (progn
3437 (add-text-properties (match-beginning 0) (match-end 0)
3438 (list 'mouse-face 'highlight
3439 'rear-nonsticky org-nonsticky-props
3440 'keymap org-mouse-map
3441 'help-echo "Radio target link"
3442 'org-linked-text t))
3443 t)))))
3445 (defun org-update-radio-target-regexp ()
3446 "Find all radio targets in this file and update the regular expression."
3447 (interactive)
3448 (when (memq 'radio org-activate-links)
3449 (setq org-target-link-regexp
3450 (org-make-target-link-regexp (org-all-targets 'radio)))
3451 (org-restart-font-lock)))
3453 (defun org-hide-wide-columns (limit)
3454 (let (s e)
3455 (setq s (text-property-any (point) (or limit (point-max))
3456 'org-cwidth t))
3457 (when s
3458 (setq e (next-single-property-change s 'org-cwidth))
3459 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3460 (goto-char e)
3461 t)))
3463 (defvar org-latex-and-specials-regexp nil
3464 "Regular expression for highlighting export special stuff.")
3465 (defvar org-match-substring-regexp)
3466 (defvar org-match-substring-with-braces-regexp)
3467 (defvar org-export-html-special-string-regexps)
3469 (defun org-compute-latex-and-specials-regexp ()
3470 "Compute regular expression for stuff treated specially by exporters."
3471 (if (not org-highlight-latex-fragments-and-specials)
3472 (org-set-local 'org-latex-and-specials-regexp nil)
3473 (require 'org-exp)
3474 (let*
3475 ((matchers (plist-get org-format-latex-options :matchers))
3476 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3477 org-latex-regexps)))
3478 (options (org-combine-plists (org-default-export-plist)
3479 (org-infile-export-plist)))
3480 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3481 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3482 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3483 (org-export-html-expand (plist-get options :expand-quoted-html))
3484 (org-export-with-special-strings (plist-get options :special-strings))
3485 (re-sub
3486 (cond
3487 ((equal org-export-with-sub-superscripts '{})
3488 (list org-match-substring-with-braces-regexp))
3489 (org-export-with-sub-superscripts
3490 (list org-match-substring-regexp))
3491 (t nil)))
3492 (re-latex
3493 (if org-export-with-LaTeX-fragments
3494 (mapcar (lambda (x) (nth 1 x)) latexs)))
3495 (re-macros
3496 (if org-export-with-TeX-macros
3497 (list (concat "\\\\"
3498 (regexp-opt
3499 (append (mapcar 'car org-html-entities)
3500 (if (boundp 'org-latex-entities)
3501 org-latex-entities nil))
3502 'words))) ; FIXME
3504 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3505 (re-special (if org-export-with-special-strings
3506 (mapcar (lambda (x) (car x))
3507 org-export-html-special-string-regexps)))
3508 (re-rest
3509 (delq nil
3510 (list
3511 (if org-export-html-expand "@<[^>\n]+>")
3512 ))))
3513 (org-set-local
3514 'org-latex-and-specials-regexp
3515 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3516 re-rest) "\\|")))))
3518 (defun org-do-latex-and-special-faces (limit)
3519 "Run through the buffer and add overlays to links."
3520 (when org-latex-and-specials-regexp
3521 (let (rtn d)
3522 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3523 limit t))
3524 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3525 'face))
3526 '(org-code org-verbatim underline)))
3527 (progn
3528 (setq rtn t
3529 d (cond ((member (char-after (1+ (match-beginning 0)))
3530 '(?_ ?^)) 1)
3531 (t 0)))
3532 (font-lock-prepend-text-property
3533 (+ d (match-beginning 0)) (match-end 0)
3534 'face 'org-latex-and-export-specials)
3535 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3536 '(font-lock-multiline t)))))
3537 rtn)))
3539 (defun org-restart-font-lock ()
3540 "Restart font-lock-mode, to force refontification."
3541 (when (and (boundp 'font-lock-mode) font-lock-mode)
3542 (font-lock-mode -1)
3543 (font-lock-mode 1)))
3545 (defun org-all-targets (&optional radio)
3546 "Return a list of all targets in this file.
3547 With optional argument RADIO, only find radio targets."
3548 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3549 rtn)
3550 (save-excursion
3551 (goto-char (point-min))
3552 (while (re-search-forward re nil t)
3553 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3554 rtn)))
3556 (defun org-make-target-link-regexp (targets)
3557 "Make regular expression matching all strings in TARGETS.
3558 The regular expression finds the targets also if there is a line break
3559 between words."
3560 (and targets
3561 (concat
3562 "\\<\\("
3563 (mapconcat
3564 (lambda (x)
3565 (while (string-match " +" x)
3566 (setq x (replace-match "\\s-+" t t x)))
3568 targets
3569 "\\|")
3570 "\\)\\>")))
3572 (defun org-activate-tags (limit)
3573 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3574 (progn
3575 (add-text-properties (match-beginning 1) (match-end 1)
3576 (list 'mouse-face 'highlight
3577 'rear-nonsticky org-nonsticky-props
3578 'keymap org-mouse-map))
3579 t)))
3581 (defun org-outline-level ()
3582 (save-excursion
3583 (looking-at outline-regexp)
3584 (if (match-beginning 1)
3585 (+ (org-get-string-indentation (match-string 1)) 1000)
3586 (1- (- (match-end 0) (match-beginning 0))))))
3588 (defvar org-font-lock-keywords nil)
3590 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3591 "Regular expression matching a property line.")
3593 (defvar org-font-lock-hook nil
3594 "Functions to be called for special font loch stuff.")
3596 (defun org-font-lock-hook (limit)
3597 (run-hook-with-args 'org-font-lock-hook limit))
3599 (defun org-set-font-lock-defaults ()
3600 (let* ((em org-fontify-emphasized-text)
3601 (lk org-activate-links)
3602 (org-font-lock-extra-keywords
3603 (list
3604 ;; Call the hook
3605 '(org-font-lock-hook)
3606 ;; Headlines
3607 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3608 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3609 ;; Table lines
3610 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3611 (1 'org-table t))
3612 ;; Table internals
3613 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3614 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3615 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3616 ;; Drawers
3617 (list org-drawer-regexp '(0 'org-special-keyword t))
3618 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3619 ;; Properties
3620 (list org-property-re
3621 '(1 'org-special-keyword t)
3622 '(3 'org-property-value t))
3623 (if org-format-transports-properties-p
3624 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3625 ;; Links
3626 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3627 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3628 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3629 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3630 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3631 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3632 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3633 '(org-hide-wide-columns (0 nil append))
3634 ;; TODO lines
3635 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3636 '(1 (org-get-todo-face 1) t))
3637 ;; DONE
3638 (if org-fontify-done-headline
3639 (list (concat "^[*]+ +\\<\\("
3640 (mapconcat 'regexp-quote org-done-keywords "\\|")
3641 "\\)\\(.*\\)")
3642 '(2 'org-headline-done t))
3643 nil)
3644 ;; Priorities
3645 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3646 ;; Special keywords
3647 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3648 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3649 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3650 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3651 ;; Emphasis
3652 (if em
3653 (if (featurep 'xemacs)
3654 '(org-do-emphasis-faces (0 nil append))
3655 '(org-do-emphasis-faces)))
3656 ;; Checkboxes
3657 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3658 2 'bold prepend)
3659 (if org-provide-checkbox-statistics
3660 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3661 (0 (org-get-checkbox-statistics-face) t)))
3662 ;; Description list items
3663 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3664 2 'bold prepend)
3665 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3666 '(1 'org-archived prepend))
3667 ;; Specials
3668 '(org-do-latex-and-special-faces)
3669 ;; Code
3670 '(org-activate-code (1 'org-code t))
3671 ;; COMMENT
3672 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3673 "\\|" org-quote-string "\\)\\>")
3674 '(1 'org-special-keyword t))
3675 '("^#.*" (0 'font-lock-comment-face t))
3677 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3678 ;; Now set the full font-lock-keywords
3679 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3680 (org-set-local 'font-lock-defaults
3681 '(org-font-lock-keywords t nil nil backward-paragraph))
3682 (kill-local-variable 'font-lock-keywords) nil))
3684 (defvar org-m nil)
3685 (defvar org-l nil)
3686 (defvar org-f nil)
3687 (defun org-get-level-face (n)
3688 "Get the right face for match N in font-lock matching of healdines."
3689 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3690 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3691 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3692 (cond
3693 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3694 ((eq n 2) org-f)
3695 (t (if org-level-color-stars-only nil org-f))))
3697 (defun org-get-todo-face (kwd)
3698 "Get the right face for a TODO keyword KWD.
3699 If KWD is a number, get the corresponding match group."
3700 (if (numberp kwd) (setq kwd (match-string kwd)))
3701 (or (cdr (assoc kwd org-todo-keyword-faces))
3702 (and (member kwd org-done-keywords) 'org-done)
3703 'org-todo))
3705 (defun org-unfontify-region (beg end &optional maybe_loudly)
3706 "Remove fontification and activation overlays from links."
3707 (font-lock-default-unfontify-region beg end)
3708 (let* ((buffer-undo-list t)
3709 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3710 (inhibit-modification-hooks t)
3711 deactivate-mark buffer-file-name buffer-file-truename)
3712 (remove-text-properties beg end
3713 '(mouse-face t keymap t org-linked-text t
3714 invisible t intangible t))))
3716 ;;;; Visibility cycling, including org-goto and indirect buffer
3718 ;;; Cycling
3720 (defvar org-cycle-global-status nil)
3721 (make-variable-buffer-local 'org-cycle-global-status)
3722 (defvar org-cycle-subtree-status nil)
3723 (make-variable-buffer-local 'org-cycle-subtree-status)
3725 ;;;###autoload
3726 (defun org-cycle (&optional arg)
3727 "Visibility cycling for Org-mode.
3729 - When this function is called with a prefix argument, rotate the entire
3730 buffer through 3 states (global cycling)
3731 1. OVERVIEW: Show only top-level headlines.
3732 2. CONTENTS: Show all headlines of all levels, but no body text.
3733 3. SHOW ALL: Show everything.
3735 - When point is at the beginning of a headline, rotate the subtree started
3736 by this line through 3 different states (local cycling)
3737 1. FOLDED: Only the main headline is shown.
3738 2. CHILDREN: The main headline and the direct children are shown.
3739 From this state, you can move to one of the children
3740 and zoom in further.
3741 3. SUBTREE: Show the entire subtree, including body text.
3743 - When there is a numeric prefix, go up to a heading with level ARG, do
3744 a `show-subtree' and return to the previous cursor position. If ARG
3745 is negative, go up that many levels.
3747 - When point is not at the beginning of a headline, execute
3748 `indent-relative', like TAB normally does. See the option
3749 `org-cycle-emulate-tab' for details.
3751 - Special case: if point is at the beginning of the buffer and there is
3752 no headline in line 1, this function will act as if called with prefix arg.
3753 But only if also the variable `org-cycle-global-at-bob' is t."
3754 (interactive "P")
3755 (org-load-modules-maybe)
3756 (let* ((outline-regexp
3757 (if (and (org-mode-p) org-cycle-include-plain-lists)
3758 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3759 outline-regexp))
3760 (bob-special (and org-cycle-global-at-bob (bobp)
3761 (not (looking-at outline-regexp))))
3762 (org-cycle-hook
3763 (if bob-special
3764 (delq 'org-optimize-window-after-visibility-change
3765 (copy-sequence org-cycle-hook))
3766 org-cycle-hook))
3767 (pos (point)))
3769 (if (or bob-special (equal arg '(4)))
3770 ;; special case: use global cycling
3771 (setq arg t))
3773 (cond
3775 ((org-at-table-p 'any)
3776 ;; Enter the table or move to the next field in the table
3777 (or (org-table-recognize-table.el)
3778 (progn
3779 (if arg (org-table-edit-field t)
3780 (org-table-justify-field-maybe)
3781 (call-interactively 'org-table-next-field)))))
3783 ((eq arg t) ;; Global cycling
3785 (cond
3786 ((and (eq last-command this-command)
3787 (eq org-cycle-global-status 'overview))
3788 ;; We just created the overview - now do table of contents
3789 ;; This can be slow in very large buffers, so indicate action
3790 (message "CONTENTS...")
3791 (org-content)
3792 (message "CONTENTS...done")
3793 (setq org-cycle-global-status 'contents)
3794 (run-hook-with-args 'org-cycle-hook 'contents))
3796 ((and (eq last-command this-command)
3797 (eq org-cycle-global-status 'contents))
3798 ;; We just showed the table of contents - now show everything
3799 (show-all)
3800 (message "SHOW ALL")
3801 (setq org-cycle-global-status 'all)
3802 (run-hook-with-args 'org-cycle-hook 'all))
3805 ;; Default action: go to overview
3806 (org-overview)
3807 (message "OVERVIEW")
3808 (setq org-cycle-global-status 'overview)
3809 (run-hook-with-args 'org-cycle-hook 'overview))))
3811 ((and org-drawers org-drawer-regexp
3812 (save-excursion
3813 (beginning-of-line 1)
3814 (looking-at org-drawer-regexp)))
3815 ;; Toggle block visibility
3816 (org-flag-drawer
3817 (not (get-char-property (match-end 0) 'invisible))))
3819 ((integerp arg)
3820 ;; Show-subtree, ARG levels up from here.
3821 (save-excursion
3822 (org-back-to-heading)
3823 (outline-up-heading (if (< arg 0) (- arg)
3824 (- (funcall outline-level) arg)))
3825 (org-show-subtree)))
3827 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3828 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3829 ;; At a heading: rotate between three different views
3830 (org-back-to-heading)
3831 (let ((goal-column 0) eoh eol eos)
3832 ;; First, some boundaries
3833 (save-excursion
3834 (org-back-to-heading)
3835 (save-excursion
3836 (beginning-of-line 2)
3837 (while (and (not (eobp)) ;; this is like `next-line'
3838 (get-char-property (1- (point)) 'invisible))
3839 (beginning-of-line 2)) (setq eol (point)))
3840 (outline-end-of-heading) (setq eoh (point))
3841 (org-end-of-subtree t)
3842 (unless (eobp)
3843 (skip-chars-forward " \t\n")
3844 (beginning-of-line 1) ; in case this is an item
3846 (setq eos (1- (point))))
3847 ;; Find out what to do next and set `this-command'
3848 (cond
3849 ((= eos eoh)
3850 ;; Nothing is hidden behind this heading
3851 (message "EMPTY ENTRY")
3852 (setq org-cycle-subtree-status nil)
3853 (save-excursion
3854 (goto-char eos)
3855 (outline-next-heading)
3856 (if (org-invisible-p) (org-flag-heading nil))))
3857 ((or (>= eol eos)
3858 (not (string-match "\\S-" (buffer-substring eol eos))))
3859 ;; Entire subtree is hidden in one line: open it
3860 (org-show-entry)
3861 (show-children)
3862 (message "CHILDREN")
3863 (save-excursion
3864 (goto-char eos)
3865 (outline-next-heading)
3866 (if (org-invisible-p) (org-flag-heading nil)))
3867 (setq org-cycle-subtree-status 'children)
3868 (run-hook-with-args 'org-cycle-hook 'children))
3869 ((and (eq last-command this-command)
3870 (eq org-cycle-subtree-status 'children))
3871 ;; We just showed the children, now show everything.
3872 (org-show-subtree)
3873 (message "SUBTREE")
3874 (setq org-cycle-subtree-status 'subtree)
3875 (run-hook-with-args 'org-cycle-hook 'subtree))
3877 ;; Default action: hide the subtree.
3878 (hide-subtree)
3879 (message "FOLDED")
3880 (setq org-cycle-subtree-status 'folded)
3881 (run-hook-with-args 'org-cycle-hook 'folded)))))
3883 ;; TAB emulation
3884 (buffer-read-only (org-back-to-heading))
3886 ((org-try-cdlatex-tab))
3888 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3889 (or (not (bolp))
3890 (not (looking-at outline-regexp))))
3891 (call-interactively (global-key-binding "\t")))
3893 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3894 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3895 (or (and (eq org-cycle-emulate-tab 'white)
3896 (= (match-end 0) (point-at-eol)))
3897 (and (eq org-cycle-emulate-tab 'whitestart)
3898 (>= (match-end 0) pos))))
3900 (eq org-cycle-emulate-tab t))
3901 (call-interactively (global-key-binding "\t")))
3903 (t (save-excursion
3904 (org-back-to-heading)
3905 (org-cycle))))))
3907 ;;;###autoload
3908 (defun org-global-cycle (&optional arg)
3909 "Cycle the global visibility. For details see `org-cycle'."
3910 (interactive "P")
3911 (let ((org-cycle-include-plain-lists
3912 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3913 (if (integerp arg)
3914 (progn
3915 (show-all)
3916 (hide-sublevels arg)
3917 (setq org-cycle-global-status 'contents))
3918 (org-cycle '(4)))))
3920 (defun org-overview ()
3921 "Switch to overview mode, shoing only top-level headlines.
3922 Really, this shows all headlines with level equal or greater than the level
3923 of the first headline in the buffer. This is important, because if the
3924 first headline is not level one, then (hide-sublevels 1) gives confusing
3925 results."
3926 (interactive)
3927 (let ((level (save-excursion
3928 (goto-char (point-min))
3929 (if (re-search-forward (concat "^" outline-regexp) nil t)
3930 (progn
3931 (goto-char (match-beginning 0))
3932 (funcall outline-level))))))
3933 (and level (hide-sublevels level))))
3935 (defun org-content (&optional arg)
3936 "Show all headlines in the buffer, like a table of contents.
3937 With numerical argument N, show content up to level N."
3938 (interactive "P")
3939 (save-excursion
3940 ;; Visit all headings and show their offspring
3941 (and (integerp arg) (org-overview))
3942 (goto-char (point-max))
3943 (catch 'exit
3944 (while (and (progn (condition-case nil
3945 (outline-previous-visible-heading 1)
3946 (error (goto-char (point-min))))
3948 (looking-at outline-regexp))
3949 (if (integerp arg)
3950 (show-children (1- arg))
3951 (show-branches))
3952 (if (bobp) (throw 'exit nil))))))
3955 (defun org-optimize-window-after-visibility-change (state)
3956 "Adjust the window after a change in outline visibility.
3957 This function is the default value of the hook `org-cycle-hook'."
3958 (when (get-buffer-window (current-buffer))
3959 (cond
3960 ; ((eq state 'overview) (org-first-headline-recenter 1))
3961 ; ((eq state 'overview) (org-beginning-of-line))
3962 ((eq state 'content) nil)
3963 ((eq state 'all) nil)
3964 ((eq state 'folded) nil)
3965 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3966 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3968 (defun org-compact-display-after-subtree-move ()
3969 (let (beg end)
3970 (save-excursion
3971 (if (org-up-heading-safe)
3972 (progn
3973 (hide-subtree)
3974 (show-entry)
3975 (show-children)
3976 (org-cycle-show-empty-lines 'children)
3977 (org-cycle-hide-drawers 'children))
3978 (org-overview)))))
3980 (defun org-cycle-show-empty-lines (state)
3981 "Show empty lines above all visible headlines.
3982 The region to be covered depends on STATE when called through
3983 `org-cycle-hook'. Lisp program can use t for STATE to get the
3984 entire buffer covered. Note that an empty line is only shown if there
3985 are at least `org-cycle-separator-lines' empty lines before the headeline."
3986 (when (> org-cycle-separator-lines 0)
3987 (save-excursion
3988 (let* ((n org-cycle-separator-lines)
3989 (re (cond
3990 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3991 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3992 (t (let ((ns (number-to-string (- n 2))))
3993 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3994 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3995 beg end)
3996 (cond
3997 ((memq state '(overview contents t))
3998 (setq beg (point-min) end (point-max)))
3999 ((memq state '(children folded))
4000 (setq beg (point) end (progn (org-end-of-subtree t t)
4001 (beginning-of-line 2)
4002 (point)))))
4003 (when beg
4004 (goto-char beg)
4005 (while (re-search-forward re end t)
4006 (if (not (get-char-property (match-end 1) 'invisible))
4007 (outline-flag-region
4008 (match-beginning 1) (match-end 1) nil)))))))
4009 ;; Never hide empty lines at the end of the file.
4010 (save-excursion
4011 (goto-char (point-max))
4012 (outline-previous-heading)
4013 (outline-end-of-heading)
4014 (if (and (looking-at "[ \t\n]+")
4015 (= (match-end 0) (point-max)))
4016 (outline-flag-region (point) (match-end 0) nil))))
4018 (defun org-cycle-hide-drawers (state)
4019 "Re-hide all drawers after a visibility state change."
4020 (when (and (org-mode-p)
4021 (not (memq state '(overview folded))))
4022 (save-excursion
4023 (let* ((globalp (memq state '(contents all)))
4024 (beg (if globalp (point-min) (point)))
4025 (end (if globalp (point-max) (org-end-of-subtree t))))
4026 (goto-char beg)
4027 (while (re-search-forward org-drawer-regexp end t)
4028 (org-flag-drawer t))))))
4030 (defun org-flag-drawer (flag)
4031 (save-excursion
4032 (beginning-of-line 1)
4033 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4034 (let ((b (match-end 0))
4035 (outline-regexp org-outline-regexp))
4036 (if (re-search-forward
4037 "^[ \t]*:END:"
4038 (save-excursion (outline-next-heading) (point)) t)
4039 (outline-flag-region b (point-at-eol) flag)
4040 (error ":END: line missing"))))))
4042 (defun org-subtree-end-visible-p ()
4043 "Is the end of the current subtree visible?"
4044 (pos-visible-in-window-p
4045 (save-excursion (org-end-of-subtree t) (point))))
4047 (defun org-first-headline-recenter (&optional N)
4048 "Move cursor to the first headline and recenter the headline.
4049 Optional argument N means, put the headline into the Nth line of the window."
4050 (goto-char (point-min))
4051 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4052 (beginning-of-line)
4053 (recenter (prefix-numeric-value N))))
4055 ;;; Org-goto
4057 (defvar org-goto-window-configuration nil)
4058 (defvar org-goto-marker nil)
4059 (defvar org-goto-map
4060 (let ((map (make-sparse-keymap)))
4061 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4062 (while (setq cmd (pop cmds))
4063 (substitute-key-definition cmd cmd map global-map)))
4064 (suppress-keymap map)
4065 (org-defkey map "\C-m" 'org-goto-ret)
4066 (org-defkey map [(return)] 'org-goto-ret)
4067 (org-defkey map [(left)] 'org-goto-left)
4068 (org-defkey map [(right)] 'org-goto-right)
4069 (org-defkey map [(control ?g)] 'org-goto-quit)
4070 (org-defkey map "\C-i" 'org-cycle)
4071 (org-defkey map [(tab)] 'org-cycle)
4072 (org-defkey map [(down)] 'outline-next-visible-heading)
4073 (org-defkey map [(up)] 'outline-previous-visible-heading)
4074 (if org-goto-auto-isearch
4075 (if (fboundp 'define-key-after)
4076 (define-key-after map [t] 'org-goto-local-auto-isearch)
4077 nil)
4078 (org-defkey map "q" 'org-goto-quit)
4079 (org-defkey map "n" 'outline-next-visible-heading)
4080 (org-defkey map "p" 'outline-previous-visible-heading)
4081 (org-defkey map "f" 'outline-forward-same-level)
4082 (org-defkey map "b" 'outline-backward-same-level)
4083 (org-defkey map "u" 'outline-up-heading))
4084 (org-defkey map "/" 'org-occur)
4085 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4086 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4087 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4088 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4089 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4090 map))
4092 (defconst org-goto-help
4093 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4094 RET=jump to location [Q]uit and return to previous location
4095 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4097 (defvar org-goto-start-pos) ; dynamically scoped parameter
4099 (defun org-goto (&optional alternative-interface)
4100 "Look up a different location in the current file, keeping current visibility.
4102 When you want look-up or go to a different location in a document, the
4103 fastest way is often to fold the entire buffer and then dive into the tree.
4104 This method has the disadvantage, that the previous location will be folded,
4105 which may not be what you want.
4107 This command works around this by showing a copy of the current buffer
4108 in an indirect buffer, in overview mode. You can dive into the tree in
4109 that copy, use org-occur and incremental search to find a location.
4110 When pressing RET or `Q', the command returns to the original buffer in
4111 which the visibility is still unchanged. After RET is will also jump to
4112 the location selected in the indirect buffer and expose the
4113 the headline hierarchy above."
4114 (interactive "P")
4115 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4116 (org-refile-use-outline-path t)
4117 (interface
4118 (if (not alternative-interface)
4119 org-goto-interface
4120 (if (eq org-goto-interface 'outline)
4121 'outline-path-completion
4122 'outline)))
4123 (org-goto-start-pos (point))
4124 (selected-point
4125 (if (eq interface 'outline)
4126 (car (org-get-location (current-buffer) org-goto-help))
4127 (nth 3 (org-refile-get-location "Goto: ")))))
4128 (if selected-point
4129 (progn
4130 (org-mark-ring-push org-goto-start-pos)
4131 (goto-char selected-point)
4132 (if (or (org-invisible-p) (org-invisible-p2))
4133 (org-show-context 'org-goto)))
4134 (message "Quit"))))
4136 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4137 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4138 (defvar org-goto-local-auto-isearch-map) ; defined below
4140 (defun org-get-location (buf help)
4141 "Let the user select a location in the Org-mode buffer BUF.
4142 This function uses a recursive edit. It returns the selected position
4143 or nil."
4144 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4145 (isearch-hide-immediately nil)
4146 (isearch-search-fun-function
4147 (lambda () 'org-goto-local-search-forward-headings))
4148 (org-goto-selected-point org-goto-exit-command))
4149 (save-excursion
4150 (save-window-excursion
4151 (delete-other-windows)
4152 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4153 (switch-to-buffer
4154 (condition-case nil
4155 (make-indirect-buffer (current-buffer) "*org-goto*")
4156 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4157 (with-output-to-temp-buffer "*Help*"
4158 (princ help))
4159 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4160 (setq buffer-read-only nil)
4161 (let ((org-startup-truncated t)
4162 (org-startup-folded nil)
4163 (org-startup-align-all-tables nil))
4164 (org-mode)
4165 (org-overview))
4166 (setq buffer-read-only t)
4167 (if (and (boundp 'org-goto-start-pos)
4168 (integer-or-marker-p org-goto-start-pos))
4169 (let ((org-show-hierarchy-above t)
4170 (org-show-siblings t)
4171 (org-show-following-heading t))
4172 (goto-char org-goto-start-pos)
4173 (and (org-invisible-p) (org-show-context)))
4174 (goto-char (point-min)))
4175 (org-beginning-of-line)
4176 (message "Select location and press RET")
4177 (use-local-map org-goto-map)
4178 (recursive-edit)
4180 (kill-buffer "*org-goto*")
4181 (cons org-goto-selected-point org-goto-exit-command)))
4183 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4184 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4185 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4186 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4188 (defun org-goto-local-search-forward-headings (string bound noerror)
4189 "Search and make sure that anu matches are in headlines."
4190 (catch 'return
4191 (while (search-forward string bound noerror)
4192 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4193 (and (member :headline context)
4194 (not (member :tags context))))
4195 (throw 'return (point))))))
4197 (defun org-goto-local-auto-isearch ()
4198 "Start isearch."
4199 (interactive)
4200 (goto-char (point-min))
4201 (let ((keys (this-command-keys)))
4202 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4203 (isearch-mode t)
4204 (isearch-process-search-char (string-to-char keys)))))
4206 (defun org-goto-ret (&optional arg)
4207 "Finish `org-goto' by going to the new location."
4208 (interactive "P")
4209 (setq org-goto-selected-point (point)
4210 org-goto-exit-command 'return)
4211 (throw 'exit nil))
4213 (defun org-goto-left ()
4214 "Finish `org-goto' by going to the new location."
4215 (interactive)
4216 (if (org-on-heading-p)
4217 (progn
4218 (beginning-of-line 1)
4219 (setq org-goto-selected-point (point)
4220 org-goto-exit-command 'left)
4221 (throw 'exit nil))
4222 (error "Not on a heading")))
4224 (defun org-goto-right ()
4225 "Finish `org-goto' by going to the new location."
4226 (interactive)
4227 (if (org-on-heading-p)
4228 (progn
4229 (setq org-goto-selected-point (point)
4230 org-goto-exit-command 'right)
4231 (throw 'exit nil))
4232 (error "Not on a heading")))
4234 (defun org-goto-quit ()
4235 "Finish `org-goto' without cursor motion."
4236 (interactive)
4237 (setq org-goto-selected-point nil)
4238 (setq org-goto-exit-command 'quit)
4239 (throw 'exit nil))
4241 ;;; Indirect buffer display of subtrees
4243 (defvar org-indirect-dedicated-frame nil
4244 "This is the frame being used for indirect tree display.")
4245 (defvar org-last-indirect-buffer nil)
4247 (defun org-tree-to-indirect-buffer (&optional arg)
4248 "Create indirect buffer and narrow it to current subtree.
4249 With numerical prefix ARG, go up to this level and then take that tree.
4250 If ARG is negative, go up that many levels.
4251 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4252 indirect buffer previously made with this command, to avoid proliferation of
4253 indirect buffers. However, when you call the command with a `C-u' prefix, or
4254 when `org-indirect-buffer-display' is `new-frame', the last buffer
4255 is kept so that you can work with several indirect buffers at the same time.
4256 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4257 requests that a new frame be made for the new buffer, so that the dedicated
4258 frame is not changed."
4259 (interactive "P")
4260 (let ((cbuf (current-buffer))
4261 (cwin (selected-window))
4262 (pos (point))
4263 beg end level heading ibuf)
4264 (save-excursion
4265 (org-back-to-heading t)
4266 (when (numberp arg)
4267 (setq level (org-outline-level))
4268 (if (< arg 0) (setq arg (+ level arg)))
4269 (while (> (setq level (org-outline-level)) arg)
4270 (outline-up-heading 1 t)))
4271 (setq beg (point)
4272 heading (org-get-heading))
4273 (org-end-of-subtree t) (setq end (point)))
4274 (if (and (buffer-live-p org-last-indirect-buffer)
4275 (not (eq org-indirect-buffer-display 'new-frame))
4276 (not arg))
4277 (kill-buffer org-last-indirect-buffer))
4278 (setq ibuf (org-get-indirect-buffer cbuf)
4279 org-last-indirect-buffer ibuf)
4280 (cond
4281 ((or (eq org-indirect-buffer-display 'new-frame)
4282 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4283 (select-frame (make-frame))
4284 (delete-other-windows)
4285 (switch-to-buffer ibuf)
4286 (org-set-frame-title heading))
4287 ((eq org-indirect-buffer-display 'dedicated-frame)
4288 (raise-frame
4289 (select-frame (or (and org-indirect-dedicated-frame
4290 (frame-live-p org-indirect-dedicated-frame)
4291 org-indirect-dedicated-frame)
4292 (setq org-indirect-dedicated-frame (make-frame)))))
4293 (delete-other-windows)
4294 (switch-to-buffer ibuf)
4295 (org-set-frame-title (concat "Indirect: " heading)))
4296 ((eq org-indirect-buffer-display 'current-window)
4297 (switch-to-buffer ibuf))
4298 ((eq org-indirect-buffer-display 'other-window)
4299 (pop-to-buffer ibuf))
4300 (t (error "Invalid value.")))
4301 (if (featurep 'xemacs)
4302 (save-excursion (org-mode) (turn-on-font-lock)))
4303 (narrow-to-region beg end)
4304 (show-all)
4305 (goto-char pos)
4306 (and (window-live-p cwin) (select-window cwin))))
4308 (defun org-get-indirect-buffer (&optional buffer)
4309 (setq buffer (or buffer (current-buffer)))
4310 (let ((n 1) (base (buffer-name buffer)) bname)
4311 (while (buffer-live-p
4312 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4313 (setq n (1+ n)))
4314 (condition-case nil
4315 (make-indirect-buffer buffer bname 'clone)
4316 (error (make-indirect-buffer buffer bname)))))
4318 (defun org-set-frame-title (title)
4319 "Set the title of the current frame to the string TITLE."
4320 ;; FIXME: how to name a single frame in XEmacs???
4321 (unless (featurep 'xemacs)
4322 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4324 ;;;; Structure editing
4326 ;;; Inserting headlines
4328 (defun org-insert-heading (&optional force-heading)
4329 "Insert a new heading or item with same depth at point.
4330 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4331 If point is at the beginning of a headline, insert a sibling before the
4332 current headline. If point is not at the beginning, do not split the line,
4333 but create the new hedline after the current line."
4334 (interactive "P")
4335 (if (= (buffer-size) 0)
4336 (insert "\n* ")
4337 (when (or force-heading (not (org-insert-item)))
4338 (let* ((head (save-excursion
4339 (condition-case nil
4340 (progn
4341 (org-back-to-heading)
4342 (match-string 0))
4343 (error "*"))))
4344 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4345 pos)
4346 (cond
4347 ((and (org-on-heading-p) (bolp)
4348 (or (bobp)
4349 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4350 ;; insert before the current line
4351 (open-line (if blank 2 1)))
4352 ((and (bolp)
4353 (or (bobp)
4354 (save-excursion
4355 (backward-char 1) (not (org-invisible-p)))))
4356 ;; insert right here
4357 nil)
4359 ;; in the middle of the line
4360 (org-show-entry)
4361 (let ((split
4362 (org-get-alist-option org-M-RET-may-split-line 'headline))
4363 tags pos)
4364 (if (org-on-heading-p)
4365 (progn
4366 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4367 (setq tags (and (match-end 2) (match-string 2)))
4368 (and (match-end 1)
4369 (delete-region (match-beginning 1) (match-end 1)))
4370 (setq pos (point-at-bol))
4371 (or split (end-of-line 1))
4372 (delete-horizontal-space)
4373 (newline (if blank 2 1))
4374 (when tags
4375 (save-excursion
4376 (goto-char pos)
4377 (end-of-line 1)
4378 (insert " " tags)
4379 (org-set-tags nil 'align))))
4380 (or split (end-of-line 1))
4381 (newline (if blank 2 1))))))
4382 (insert head) (just-one-space)
4383 (setq pos (point))
4384 (end-of-line 1)
4385 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4386 (run-hooks 'org-insert-heading-hook)))))
4388 (defun org-get-heading (&optional no-tags)
4389 "Return the heading of the current entry, without the stars."
4390 (save-excursion
4391 (org-back-to-heading t)
4392 (if (looking-at
4393 (if no-tags
4394 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4395 "\\*+[ \t]+\\([^\r\n]*\\)"))
4396 (match-string 1) "")))
4398 (defun org-insert-heading-after-current ()
4399 "Insert a new heading with same level as current, after current subtree."
4400 (interactive)
4401 (org-back-to-heading)
4402 (org-insert-heading)
4403 (org-move-subtree-down)
4404 (end-of-line 1))
4406 (defun org-insert-todo-heading (arg)
4407 "Insert a new heading with the same level and TODO state as current heading.
4408 If the heading has no TODO state, or if the state is DONE, use the first
4409 state (TODO by default). Also with prefix arg, force first state."
4410 (interactive "P")
4411 (when (not (org-insert-item 'checkbox))
4412 (org-insert-heading)
4413 (save-excursion
4414 (org-back-to-heading)
4415 (outline-previous-heading)
4416 (looking-at org-todo-line-regexp))
4417 (if (or arg
4418 (not (match-beginning 2))
4419 (member (match-string 2) org-done-keywords))
4420 (insert (car org-todo-keywords-1) " ")
4421 (insert (match-string 2) " "))))
4423 (defun org-insert-subheading (arg)
4424 "Insert a new subheading and demote it.
4425 Works for outline headings and for plain lists alike."
4426 (interactive "P")
4427 (org-insert-heading arg)
4428 (cond
4429 ((org-on-heading-p) (org-do-demote))
4430 ((org-at-item-p) (org-indent-item 1))))
4432 (defun org-insert-todo-subheading (arg)
4433 "Insert a new subheading with TODO keyword or checkbox and demote it.
4434 Works for outline headings and for plain lists alike."
4435 (interactive "P")
4436 (org-insert-todo-heading arg)
4437 (cond
4438 ((org-on-heading-p) (org-do-demote))
4439 ((org-at-item-p) (org-indent-item 1))))
4441 ;;; Promotion and Demotion
4443 (defun org-promote-subtree ()
4444 "Promote the entire subtree.
4445 See also `org-promote'."
4446 (interactive)
4447 (save-excursion
4448 (org-map-tree 'org-promote))
4449 (org-fix-position-after-promote))
4451 (defun org-demote-subtree ()
4452 "Demote the entire subtree. See `org-demote'.
4453 See also `org-promote'."
4454 (interactive)
4455 (save-excursion
4456 (org-map-tree 'org-demote))
4457 (org-fix-position-after-promote))
4460 (defun org-do-promote ()
4461 "Promote the current heading higher up the tree.
4462 If the region is active in `transient-mark-mode', promote all headings
4463 in the region."
4464 (interactive)
4465 (save-excursion
4466 (if (org-region-active-p)
4467 (org-map-region 'org-promote (region-beginning) (region-end))
4468 (org-promote)))
4469 (org-fix-position-after-promote))
4471 (defun org-do-demote ()
4472 "Demote the current heading lower down the tree.
4473 If the region is active in `transient-mark-mode', demote all headings
4474 in the region."
4475 (interactive)
4476 (save-excursion
4477 (if (org-region-active-p)
4478 (org-map-region 'org-demote (region-beginning) (region-end))
4479 (org-demote)))
4480 (org-fix-position-after-promote))
4482 (defun org-fix-position-after-promote ()
4483 "Make sure that after pro/demotion cursor position is right."
4484 (let ((pos (point)))
4485 (when (save-excursion
4486 (beginning-of-line 1)
4487 (looking-at org-todo-line-regexp)
4488 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4489 (cond ((eobp) (insert " "))
4490 ((eolp) (insert " "))
4491 ((equal (char-after) ?\ ) (forward-char 1))))))
4493 (defun org-reduced-level (l)
4494 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4496 (defun org-get-valid-level (level &optional change)
4497 "Rectify a level change under the influence of `org-odd-levels-only'
4498 LEVEL is a current level, CHANGE is by how much the level should be
4499 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4500 even level numbers will become the next higher odd number."
4501 (if org-odd-levels-only
4502 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4503 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4504 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4505 (max 1 (+ level change))))
4507 (if (boundp 'define-obsolete-function-alias)
4508 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4509 (define-obsolete-function-alias 'org-get-legal-level
4510 'org-get-valid-level)
4511 (define-obsolete-function-alias 'org-get-legal-level
4512 'org-get-valid-level "23.1")))
4514 (defun org-promote ()
4515 "Promote the current heading higher up the tree.
4516 If the region is active in `transient-mark-mode', promote all headings
4517 in the region."
4518 (org-back-to-heading t)
4519 (let* ((level (save-match-data (funcall outline-level)))
4520 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4521 (diff (abs (- level (length up-head) -1))))
4522 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4523 (replace-match up-head nil t)
4524 ;; Fixup tag positioning
4525 (and org-auto-align-tags (org-set-tags nil t))
4526 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4528 (defun org-demote ()
4529 "Demote the current heading lower down the tree.
4530 If the region is active in `transient-mark-mode', demote all headings
4531 in the region."
4532 (org-back-to-heading t)
4533 (let* ((level (save-match-data (funcall outline-level)))
4534 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4535 (diff (abs (- level (length down-head) -1))))
4536 (replace-match down-head nil t)
4537 ;; Fixup tag positioning
4538 (and org-auto-align-tags (org-set-tags nil t))
4539 (if org-adapt-indentation (org-fixup-indentation diff))))
4541 (defun org-map-tree (fun)
4542 "Call FUN for every heading underneath the current one."
4543 (org-back-to-heading)
4544 (let ((level (funcall outline-level)))
4545 (save-excursion
4546 (funcall fun)
4547 (while (and (progn
4548 (outline-next-heading)
4549 (> (funcall outline-level) level))
4550 (not (eobp)))
4551 (funcall fun)))))
4553 (defun org-map-region (fun beg end)
4554 "Call FUN for every heading between BEG and END."
4555 (let ((org-ignore-region t))
4556 (save-excursion
4557 (setq end (copy-marker end))
4558 (goto-char beg)
4559 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4560 (< (point) end))
4561 (funcall fun))
4562 (while (and (progn
4563 (outline-next-heading)
4564 (< (point) end))
4565 (not (eobp)))
4566 (funcall fun)))))
4568 (defun org-fixup-indentation (diff)
4569 "Change the indentation in the current entry by DIFF
4570 However, if any line in the current entry has no indentation, or if it
4571 would end up with no indentation after the change, nothing at all is done."
4572 (save-excursion
4573 (let ((end (save-excursion (outline-next-heading)
4574 (point-marker)))
4575 (prohibit (if (> diff 0)
4576 "^\\S-"
4577 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4578 col)
4579 (unless (save-excursion (end-of-line 1)
4580 (re-search-forward prohibit end t))
4581 (while (and (< (point) end)
4582 (re-search-forward "^[ \t]+" end t))
4583 (goto-char (match-end 0))
4584 (setq col (current-column))
4585 (if (< diff 0) (replace-match ""))
4586 (indent-to (+ diff col))))
4587 (move-marker end nil))))
4589 (defun org-convert-to-odd-levels ()
4590 "Convert an org-mode file with all levels allowed to one with odd levels.
4591 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4592 level 5 etc."
4593 (interactive)
4594 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4595 (let ((org-odd-levels-only nil) n)
4596 (save-excursion
4597 (goto-char (point-min))
4598 (while (re-search-forward "^\\*\\*+ " nil t)
4599 (setq n (- (length (match-string 0)) 2))
4600 (while (>= (setq n (1- n)) 0)
4601 (org-demote))
4602 (end-of-line 1))))))
4605 (defun org-convert-to-oddeven-levels ()
4606 "Convert an org-mode file with only odd levels to one with odd and even levels.
4607 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4608 section with an even level, conversion would destroy the structure of the file. An error
4609 is signaled in this case."
4610 (interactive)
4611 (goto-char (point-min))
4612 ;; First check if there are no even levels
4613 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4614 (org-show-context t)
4615 (error "Not all levels are odd in this file. Conversion not possible."))
4616 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4617 (let ((org-odd-levels-only nil) n)
4618 (save-excursion
4619 (goto-char (point-min))
4620 (while (re-search-forward "^\\*\\*+ " nil t)
4621 (setq n (/ (1- (length (match-string 0))) 2))
4622 (while (>= (setq n (1- n)) 0)
4623 (org-promote))
4624 (end-of-line 1))))))
4626 (defun org-tr-level (n)
4627 "Make N odd if required."
4628 (if org-odd-levels-only (1+ (/ n 2)) n))
4630 ;;; Vertical tree motion, cutting and pasting of subtrees
4632 (defun org-move-subtree-up (&optional arg)
4633 "Move the current subtree up past ARG headlines of the same level."
4634 (interactive "p")
4635 (org-move-subtree-down (- (prefix-numeric-value arg))))
4637 (defun org-move-subtree-down (&optional arg)
4638 "Move the current subtree down past ARG headlines of the same level."
4639 (interactive "p")
4640 (setq arg (prefix-numeric-value arg))
4641 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4642 'outline-get-last-sibling))
4643 (ins-point (make-marker))
4644 (cnt (abs arg))
4645 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4646 ;; Select the tree
4647 (org-back-to-heading)
4648 (setq beg0 (point))
4649 (save-excursion
4650 (setq ne-beg (org-back-over-empty-lines))
4651 (setq beg (point)))
4652 (save-match-data
4653 (save-excursion (outline-end-of-heading)
4654 (setq folded (org-invisible-p)))
4655 (outline-end-of-subtree))
4656 (outline-next-heading)
4657 (setq ne-end (org-back-over-empty-lines))
4658 (setq end (point))
4659 (goto-char beg0)
4660 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4661 ;; include less whitespace
4662 (save-excursion
4663 (goto-char beg)
4664 (forward-line (- ne-beg ne-end))
4665 (setq beg (point))))
4666 ;; Find insertion point, with error handling
4667 (while (> cnt 0)
4668 (or (and (funcall movfunc) (looking-at outline-regexp))
4669 (progn (goto-char beg0)
4670 (error "Cannot move past superior level or buffer limit")))
4671 (setq cnt (1- cnt)))
4672 (if (> arg 0)
4673 ;; Moving forward - still need to move over subtree
4674 (progn (org-end-of-subtree t t)
4675 (save-excursion
4676 (org-back-over-empty-lines)
4677 (or (bolp) (newline)))))
4678 (setq ne-ins (org-back-over-empty-lines))
4679 (move-marker ins-point (point))
4680 (setq txt (buffer-substring beg end))
4681 (org-save-markers-in-region beg end)
4682 (delete-region beg end)
4683 (outline-flag-region (1- beg) beg nil)
4684 (outline-flag-region (1- (point)) (point) nil)
4685 (let ((bbb (point)))
4686 (insert-before-markers txt)
4687 (org-reinstall-markers-in-region bbb)
4688 (move-marker ins-point bbb))
4689 (or (bolp) (insert "\n"))
4690 (setq ins-end (point))
4691 (goto-char ins-point)
4692 (org-skip-whitespace)
4693 (when (and (< arg 0)
4694 (org-first-sibling-p)
4695 (> ne-ins ne-beg))
4696 ;; Move whitespace back to beginning
4697 (save-excursion
4698 (goto-char ins-end)
4699 (let ((kill-whole-line t))
4700 (kill-line (- ne-ins ne-beg)) (point)))
4701 (insert (make-string (- ne-ins ne-beg) ?\n)))
4702 (move-marker ins-point nil)
4703 (org-compact-display-after-subtree-move)
4704 (unless folded
4705 (org-show-entry)
4706 (show-children)
4707 (org-cycle-hide-drawers 'children))))
4709 (defvar org-subtree-clip ""
4710 "Clipboard for cut and paste of subtrees.
4711 This is actually only a copy of the kill, because we use the normal kill
4712 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4714 (defvar org-subtree-clip-folded nil
4715 "Was the last copied subtree folded?
4716 This is used to fold the tree back after pasting.")
4718 (defun org-cut-subtree (&optional n)
4719 "Cut the current subtree into the clipboard.
4720 With prefix arg N, cut this many sequential subtrees.
4721 This is a short-hand for marking the subtree and then cutting it."
4722 (interactive "p")
4723 (org-copy-subtree n 'cut))
4725 (defun org-copy-subtree (&optional n cut force-store-markers)
4726 "Cut the current subtree into the clipboard.
4727 With prefix arg N, cut this many sequential subtrees.
4728 This is a short-hand for marking the subtree and then copying it.
4729 If CUT is non-nil, actually cut the subtree.
4730 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4731 of some markers in the region, even if CUT is non-nil. This is
4732 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4733 (interactive "p")
4734 (let (beg end folded (beg0 (point)))
4735 (if (interactive-p)
4736 (org-back-to-heading nil) ; take what looks like a subtree
4737 (org-back-to-heading t)) ; take what is really there
4738 (org-back-over-empty-lines)
4739 (setq beg (point))
4740 (skip-chars-forward " \t\r\n")
4741 (save-match-data
4742 (save-excursion (outline-end-of-heading)
4743 (setq folded (org-invisible-p)))
4744 (condition-case nil
4745 (outline-forward-same-level (1- n))
4746 (error nil))
4747 (org-end-of-subtree t t))
4748 (org-back-over-empty-lines)
4749 (setq end (point))
4750 (goto-char beg0)
4751 (when (> end beg)
4752 (setq org-subtree-clip-folded folded)
4753 (when (or cut force-store-markers)
4754 (org-save-markers-in-region beg end))
4755 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4756 (setq org-subtree-clip (current-kill 0))
4757 (message "%s: Subtree(s) with %d characters"
4758 (if cut "Cut" "Copied")
4759 (length org-subtree-clip)))))
4761 (defun org-paste-subtree (&optional level tree)
4762 "Paste the clipboard as a subtree, with modification of headline level.
4763 The entire subtree is promoted or demoted in order to match a new headline
4764 level. By default, the new level is derived from the visible headings
4765 before and after the insertion point, and taken to be the inferior headline
4766 level of the two. So if the previous visible heading is level 3 and the
4767 next is level 4 (or vice versa), level 4 will be used for insertion.
4768 This makes sure that the subtree remains an independent subtree and does
4769 not swallow low level entries.
4771 You can also force a different level, either by using a numeric prefix
4772 argument, or by inserting the heading marker by hand. For example, if the
4773 cursor is after \"*****\", then the tree will be shifted to level 5.
4775 If you want to insert the tree as is, just use \\[yank].
4777 If optional TREE is given, use this text instead of the kill ring."
4778 (interactive "P")
4779 (unless (org-kill-is-subtree-p tree)
4780 (error "%s"
4781 (substitute-command-keys
4782 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4783 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4784 (^re (concat "^\\(" outline-regexp "\\)"))
4785 (re (concat "\\(" outline-regexp "\\)"))
4786 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4788 (old-level (if (string-match ^re txt)
4789 (- (match-end 0) (match-beginning 0) 1)
4790 -1))
4791 (force-level (cond (level (prefix-numeric-value level))
4792 ((string-match
4793 ^re_ (buffer-substring (point-at-bol) (point)))
4794 (- (match-end 1) (match-beginning 1)))
4795 (t nil)))
4796 (previous-level (save-excursion
4797 (condition-case nil
4798 (progn
4799 (outline-previous-visible-heading 1)
4800 (if (looking-at re)
4801 (- (match-end 0) (match-beginning 0) 1)
4803 (error 1))))
4804 (next-level (save-excursion
4805 (condition-case nil
4806 (progn
4807 (or (looking-at outline-regexp)
4808 (outline-next-visible-heading 1))
4809 (if (looking-at re)
4810 (- (match-end 0) (match-beginning 0) 1)
4812 (error 1))))
4813 (new-level (or force-level (max previous-level next-level)))
4814 (shift (if (or (= old-level -1)
4815 (= new-level -1)
4816 (= old-level new-level))
4818 (- new-level old-level)))
4819 (delta (if (> shift 0) -1 1))
4820 (func (if (> shift 0) 'org-demote 'org-promote))
4821 (org-odd-levels-only nil)
4822 beg end)
4823 ;; Remove the forced level indicator
4824 (if force-level
4825 (delete-region (point-at-bol) (point)))
4826 ;; Paste
4827 (beginning-of-line 1)
4828 (org-back-over-empty-lines)
4829 (setq beg (point))
4830 (insert-before-markers txt)
4831 (unless (string-match "\n\\'" txt) (insert "\n"))
4832 (org-reinstall-markers-in-region beg)
4833 (setq end (point))
4834 (goto-char beg)
4835 (skip-chars-forward " \t\n\r")
4836 (setq beg (point))
4837 ;; Shift if necessary
4838 (unless (= shift 0)
4839 (save-restriction
4840 (narrow-to-region beg end)
4841 (while (not (= shift 0))
4842 (org-map-region func (point-min) (point-max))
4843 (setq shift (+ delta shift)))
4844 (goto-char (point-min))))
4845 (when (interactive-p)
4846 (message "Clipboard pasted as level %d subtree" new-level))
4847 (if (and kill-ring
4848 (eq org-subtree-clip (current-kill 0))
4849 org-subtree-clip-folded)
4850 ;; The tree was folded before it was killed/copied
4851 (hide-subtree))))
4853 (defun org-kill-is-subtree-p (&optional txt)
4854 "Check if the current kill is an outline subtree, or a set of trees.
4855 Returns nil if kill does not start with a headline, or if the first
4856 headline level is not the largest headline level in the tree.
4857 So this will actually accept several entries of equal levels as well,
4858 which is OK for `org-paste-subtree'.
4859 If optional TXT is given, check this string instead of the current kill."
4860 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4861 (start-level (and kill
4862 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4863 org-outline-regexp "\\)")
4864 kill)
4865 (- (match-end 2) (match-beginning 2) 1)))
4866 (re (concat "^" org-outline-regexp))
4867 (start (1+ (match-beginning 2))))
4868 (if (not start-level)
4869 (progn
4870 nil) ;; does not even start with a heading
4871 (catch 'exit
4872 (while (setq start (string-match re kill (1+ start)))
4873 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4874 (throw 'exit nil)))
4875 t))))
4877 (defvar org-markers-to-move nil
4878 "Markers that should be moved with a cut-and-paste operation.
4879 Those markers are stored together with their positions relative to
4880 the start of the region.")
4882 (defun org-save-markers-in-region (beg end)
4883 "Check markers in region.
4884 If these markers are between BEG and END, record their position relative
4885 to BEG, so that after moving the block of text, we can put the markers back
4886 into place.
4887 This function gets called just before an entry or tree gets cut from the
4888 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4889 called immediately, to move the markers with the entries."
4890 (setq org-markers-to-move nil)
4891 (when (featurep 'org-clock)
4892 (org-clock-save-markers-for-cut-and-paste beg end))
4893 (when (featurep 'org-agenda)
4894 (org-agenda-save-markers-for-cut-and-paste beg end)))
4896 (defun org-check-and-save-marker (marker beg end)
4897 "Check if MARKER is between BEG and END.
4898 If yes, remember the marker and the distance to BEG."
4899 (when (and (marker-buffer marker)
4900 (equal (marker-buffer marker) (current-buffer)))
4901 (if (and (>= marker beg) (< marker end))
4902 (push (cons marker (- marker beg)) org-markers-to-move))))
4904 (defun org-reinstall-markers-in-region (beg)
4905 "Move all remembered markers to their position relative to BEG."
4906 (mapc (lambda (x)
4907 (move-marker (car x) (+ beg (cdr x))))
4908 org-markers-to-move)
4909 (setq org-markers-to-move nil))
4911 (defun org-narrow-to-subtree ()
4912 "Narrow buffer to the current subtree."
4913 (interactive)
4914 (save-excursion
4915 (save-match-data
4916 (narrow-to-region
4917 (progn (org-back-to-heading) (point))
4918 (progn (org-end-of-subtree t t) (point))))))
4921 ;;; Outline Sorting
4923 (defun org-sort (with-case)
4924 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4925 Optional argument WITH-CASE means sort case-sensitively."
4926 (interactive "P")
4927 (if (org-at-table-p)
4928 (org-call-with-arg 'org-table-sort-lines with-case)
4929 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4931 (defun org-sort-remove-invisible (s)
4932 (remove-text-properties 0 (length s) org-rm-props s)
4933 (while (string-match org-bracket-link-regexp s)
4934 (setq s (replace-match (if (match-end 2)
4935 (match-string 3 s)
4936 (match-string 1 s)) t t s)))
4939 (defvar org-priority-regexp) ; defined later in the file
4941 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4942 "Sort entries on a certain level of an outline tree.
4943 If there is an active region, the entries in the region are sorted.
4944 Else, if the cursor is before the first entry, sort the top-level items.
4945 Else, the children of the entry at point are sorted.
4947 Sorting can be alphabetically, numerically, and by date/time as given by
4948 the first time stamp in the entry. The command prompts for the sorting
4949 type unless it has been given to the function through the SORTING-TYPE
4950 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4951 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4952 called with point at the beginning of the record. It must return either
4953 a string or a number that should serve as the sorting key for that record.
4955 Comparing entries ignores case by default. However, with an optional argument
4956 WITH-CASE, the sorting considers case as well."
4957 (interactive "P")
4958 (let ((case-func (if with-case 'identity 'downcase))
4959 start beg end stars re re2
4960 txt what tmp plain-list-p)
4961 ;; Find beginning and end of region to sort
4962 (cond
4963 ((org-region-active-p)
4964 ;; we will sort the region
4965 (setq end (region-end)
4966 what "region")
4967 (goto-char (region-beginning))
4968 (if (not (org-on-heading-p)) (outline-next-heading))
4969 (setq start (point)))
4970 ((org-at-item-p)
4971 ;; we will sort this plain list
4972 (org-beginning-of-item-list) (setq start (point))
4973 (org-end-of-item-list) (setq end (point))
4974 (goto-char start)
4975 (setq plain-list-p t
4976 what "plain list"))
4977 ((or (org-on-heading-p)
4978 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4979 ;; we will sort the children of the current headline
4980 (org-back-to-heading)
4981 (setq start (point)
4982 end (progn (org-end-of-subtree t t)
4983 (org-back-over-empty-lines)
4984 (point))
4985 what "children")
4986 (goto-char start)
4987 (show-subtree)
4988 (outline-next-heading))
4990 ;; we will sort the top-level entries in this file
4991 (goto-char (point-min))
4992 (or (org-on-heading-p) (outline-next-heading))
4993 (setq start (point) end (point-max) what "top-level")
4994 (goto-char start)
4995 (show-all)))
4997 (setq beg (point))
4998 (if (>= beg end) (error "Nothing to sort"))
5000 (unless plain-list-p
5001 (looking-at "\\(\\*+\\)")
5002 (setq stars (match-string 1)
5003 re (concat "^" (regexp-quote stars) " +")
5004 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5005 txt (buffer-substring beg end))
5006 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5007 (if (and (not (equal stars "*")) (string-match re2 txt))
5008 (error "Region to sort contains a level above the first entry")))
5010 (unless sorting-type
5011 (message
5012 (if plain-list-p
5013 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5014 "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:")
5015 what)
5016 (setq sorting-type (read-char-exclusive))
5018 (and (= (downcase sorting-type) ?f)
5019 (setq getkey-func
5020 (completing-read "Sort using function: "
5021 obarray 'fboundp t nil nil))
5022 (setq getkey-func (intern getkey-func)))
5024 (and (= (downcase sorting-type) ?r)
5025 (setq property
5026 (completing-read "Property: "
5027 (mapcar 'list (org-buffer-property-keys t))
5028 nil t))))
5030 (message "Sorting entries...")
5032 (save-restriction
5033 (narrow-to-region start end)
5035 (let ((dcst (downcase sorting-type))
5036 (now (current-time)))
5037 (sort-subr
5038 (/= dcst sorting-type)
5039 ;; This function moves to the beginning character of the "record" to
5040 ;; be sorted.
5041 (if plain-list-p
5042 (lambda nil
5043 (if (org-at-item-p) t (goto-char (point-max))))
5044 (lambda nil
5045 (if (re-search-forward re nil t)
5046 (goto-char (match-beginning 0))
5047 (goto-char (point-max)))))
5048 ;; This function moves to the last character of the "record" being
5049 ;; sorted.
5050 (if plain-list-p
5051 'org-end-of-item
5052 (lambda nil
5053 (save-match-data
5054 (condition-case nil
5055 (outline-forward-same-level 1)
5056 (error
5057 (goto-char (point-max)))))))
5059 ;; This function returns the value that gets sorted against.
5060 (if plain-list-p
5061 (lambda nil
5062 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5063 (cond
5064 ((= dcst ?n)
5065 (string-to-number (buffer-substring (match-end 0)
5066 (point-at-eol))))
5067 ((= dcst ?a)
5068 (buffer-substring (match-end 0) (point-at-eol)))
5069 ((= dcst ?t)
5070 (if (re-search-forward org-ts-regexp
5071 (point-at-eol) t)
5072 (org-time-string-to-time (match-string 0))
5073 now))
5074 ((= dcst ?f)
5075 (if getkey-func
5076 (progn
5077 (setq tmp (funcall getkey-func))
5078 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5079 tmp)
5080 (error "Invalid key function `%s'" getkey-func)))
5081 (t (error "Invalid sorting type `%c'" sorting-type)))))
5082 (lambda nil
5083 (cond
5084 ((= dcst ?n)
5085 (if (looking-at outline-regexp)
5086 (string-to-number (buffer-substring (match-end 0)
5087 (point-at-eol)))
5088 nil))
5089 ((= dcst ?a)
5090 (funcall case-func (buffer-substring (point-at-bol)
5091 (point-at-eol))))
5092 ((= dcst ?t)
5093 (if (re-search-forward org-ts-regexp
5094 (save-excursion
5095 (forward-line 2)
5096 (point)) t)
5097 (org-time-string-to-time (match-string 0))
5098 now))
5099 ((= dcst ?p)
5100 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5101 (string-to-char (match-string 2))
5102 org-default-priority))
5103 ((= dcst ?r)
5104 (or (org-entry-get nil property) ""))
5105 ((= dcst ?o)
5106 (if (looking-at org-complex-heading-regexp)
5107 (- 9999 (length (member (match-string 2)
5108 org-todo-keywords-1)))))
5109 ((= dcst ?f)
5110 (if getkey-func
5111 (progn
5112 (setq tmp (funcall getkey-func))
5113 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5114 tmp)
5115 (error "Invalid key function `%s'" getkey-func)))
5116 (t (error "Invalid sorting type `%c'" sorting-type)))))
5118 (cond
5119 ((= dcst ?a) 'string<)
5120 ((= dcst ?t) 'time-less-p)
5121 (t nil)))))
5122 (message "Sorting entries...done")))
5124 (defun org-do-sort (table what &optional with-case sorting-type)
5125 "Sort TABLE of WHAT according to SORTING-TYPE.
5126 The user will be prompted for the SORTING-TYPE if the call to this
5127 function does not specify it. WHAT is only for the prompt, to indicate
5128 what is being sorted. The sorting key will be extracted from
5129 the car of the elements of the table.
5130 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5131 (unless sorting-type
5132 (message
5133 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5134 what)
5135 (setq sorting-type (read-char-exclusive)))
5136 (let ((dcst (downcase sorting-type))
5137 extractfun comparefun)
5138 ;; Define the appropriate functions
5139 (cond
5140 ((= dcst ?n)
5141 (setq extractfun 'string-to-number
5142 comparefun (if (= dcst sorting-type) '< '>)))
5143 ((= dcst ?a)
5144 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5145 (lambda(x) (downcase (org-sort-remove-invisible x))))
5146 comparefun (if (= dcst sorting-type)
5147 'string<
5148 (lambda (a b) (and (not (string< a b))
5149 (not (string= a b)))))))
5150 ((= dcst ?t)
5151 (setq extractfun
5152 (lambda (x)
5153 (if (string-match org-ts-regexp x)
5154 (time-to-seconds
5155 (org-time-string-to-time (match-string 0 x)))
5157 comparefun (if (= dcst sorting-type) '< '>)))
5158 (t (error "Invalid sorting type `%c'" sorting-type)))
5160 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5161 table)
5162 (lambda (a b) (funcall comparefun (car a) (car b))))))
5164 ;;;; Plain list items, including checkboxes
5166 ;;; Plain list items
5168 (defun org-at-item-p ()
5169 "Is point in a line starting a hand-formatted item?"
5170 (let ((llt org-plain-list-ordered-item-terminator))
5171 (save-excursion
5172 (goto-char (point-at-bol))
5173 (looking-at
5174 (cond
5175 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5176 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5177 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5178 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5180 (defun org-in-item-p ()
5181 "It the cursor inside a plain list item.
5182 Does not have to be the first line."
5183 (save-excursion
5184 (condition-case nil
5185 (progn
5186 (org-beginning-of-item)
5187 (org-at-item-p)
5189 (error nil))))
5191 (defun org-insert-item (&optional checkbox)
5192 "Insert a new item at the current level.
5193 Return t when things worked, nil when we are not in an item."
5194 (when (save-excursion
5195 (condition-case nil
5196 (progn
5197 (org-beginning-of-item)
5198 (org-at-item-p)
5199 (if (org-invisible-p) (error "Invisible item"))
5201 (error nil)))
5202 (let* ((bul (match-string 0))
5203 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5204 (match-end 0)))
5205 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5206 pos)
5207 (cond
5208 ((and (org-at-item-p) (<= (point) eow))
5209 ;; before the bullet
5210 (beginning-of-line 1)
5211 (open-line (if blank 2 1)))
5212 ((<= (point) eow)
5213 (beginning-of-line 1))
5215 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5216 (end-of-line 1)
5217 (delete-horizontal-space))
5218 (newline (if blank 2 1))))
5219 (insert bul (if checkbox "[ ]" ""))
5220 (just-one-space)
5221 (setq pos (point))
5222 (end-of-line 1)
5223 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5224 (org-maybe-renumber-ordered-list)
5225 (and checkbox (org-update-checkbox-count-maybe))
5228 ;;; Checkboxes
5230 (defun org-at-item-checkbox-p ()
5231 "Is point at a line starting a plain-list item with a checklet?"
5232 (and (org-at-item-p)
5233 (save-excursion
5234 (goto-char (match-end 0))
5235 (skip-chars-forward " \t")
5236 (looking-at "\\[[- X]\\]"))))
5238 (defun org-toggle-checkbox (&optional arg)
5239 "Toggle the checkbox in the current line."
5240 (interactive "P")
5241 (catch 'exit
5242 (let (beg end status (firstnew 'unknown))
5243 (cond
5244 ((org-region-active-p)
5245 (setq beg (region-beginning) end (region-end)))
5246 ((org-on-heading-p)
5247 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5248 ((org-at-item-checkbox-p)
5249 (let ((pos (point)))
5250 (replace-match
5251 (cond (arg "[-]")
5252 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5253 (t "[ ]"))
5254 t t)
5255 (goto-char pos))
5256 (throw 'exit t))
5257 (t (error "Not at a checkbox or heading, and no active region")))
5258 (save-excursion
5259 (goto-char beg)
5260 (while (< (point) end)
5261 (when (org-at-item-checkbox-p)
5262 (setq status (equal (match-string 0) "[X]"))
5263 (when (eq firstnew 'unknown)
5264 (setq firstnew (not status)))
5265 (replace-match
5266 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5267 (beginning-of-line 2)))))
5268 (org-update-checkbox-count-maybe))
5270 (defun org-update-checkbox-count-maybe ()
5271 "Update checkbox statistics unless turned off by user."
5272 (when org-provide-checkbox-statistics
5273 (org-update-checkbox-count)))
5275 (defun org-update-checkbox-count (&optional all)
5276 "Update the checkbox statistics in the current section.
5277 This will find all statistic cookies like [57%] and [6/12] and update them
5278 with the current numbers. With optional prefix argument ALL, do this for
5279 the whole buffer."
5280 (interactive "P")
5281 (save-excursion
5282 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5283 (beg (condition-case nil
5284 (progn (outline-back-to-heading) (point))
5285 (error (point-min))))
5286 (end (move-marker (make-marker)
5287 (progn (outline-next-heading) (point))))
5288 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5289 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5290 (re-find (concat re "\\|" re-box))
5291 beg-cookie end-cookie is-percent c-on c-off lim
5292 eline curr-ind next-ind continue-from startsearch
5293 (cstat 0)
5295 (when all
5296 (goto-char (point-min))
5297 (outline-next-heading)
5298 (setq beg (point) end (point-max)))
5299 (goto-char end)
5300 ;; find each statistic cookie
5301 (while (re-search-backward re-find beg t)
5302 (setq beg-cookie (match-beginning 1)
5303 end-cookie (match-end 1)
5304 cstat (+ cstat (if end-cookie 1 0))
5305 startsearch (point-at-eol)
5306 continue-from (point-at-bol)
5307 is-percent (match-beginning 2)
5308 lim (cond
5309 ((org-on-heading-p) (outline-next-heading) (point))
5310 ((org-at-item-p) (org-end-of-item) (point))
5311 (t nil))
5312 c-on 0
5313 c-off 0)
5314 (when lim
5315 ;; find first checkbox for this cookie and gather
5316 ;; statistics from all that are at this indentation level
5317 (goto-char startsearch)
5318 (if (re-search-forward re-box lim t)
5319 (progn
5320 (org-beginning-of-item)
5321 (setq curr-ind (org-get-indentation))
5322 (setq next-ind curr-ind)
5323 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5324 (save-excursion (end-of-line) (setq eline (point)))
5325 (if (re-search-forward re-box eline t)
5326 (if (member (match-string 2) '("[ ]" "[-]"))
5327 (setq c-off (1+ c-off))
5328 (setq c-on (1+ c-on))
5331 (org-end-of-item)
5332 (setq next-ind (org-get-indentation))
5334 (goto-char continue-from)
5335 ;; update cookie
5336 (when end-cookie
5337 (delete-region beg-cookie end-cookie)
5338 (goto-char beg-cookie)
5339 (insert
5340 (if is-percent
5341 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5342 (format "[%d/%d]" c-on (+ c-on c-off)))))
5343 ;; update items checkbox if it has one
5344 (when (org-at-item-p)
5345 (org-beginning-of-item)
5346 (when (and (> (+ c-on c-off) 0)
5347 (re-search-forward re-box (point-at-eol) t))
5348 (setq beg-cookie (match-beginning 2)
5349 end-cookie (match-end 2))
5350 (delete-region beg-cookie end-cookie)
5351 (goto-char beg-cookie)
5352 (cond ((= c-off 0) (insert "[X]"))
5353 ((= c-on 0) (insert "[ ]"))
5354 (t (insert "[-]")))
5356 (goto-char continue-from))
5357 (when (interactive-p)
5358 (message "Checkbox satistics updated %s (%d places)"
5359 (if all "in entire file" "in current outline entry") cstat)))))
5361 (defun org-get-checkbox-statistics-face ()
5362 "Select the face for checkbox statistics.
5363 The face will be `org-done' when all relevant boxes are checked. Otherwise
5364 it will be `org-todo'."
5365 (if (match-end 1)
5366 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5367 (if (and (> (match-end 2) (match-beginning 2))
5368 (equal (match-string 2) (match-string 3)))
5369 'org-done
5370 'org-todo)))
5372 (defun org-get-indentation (&optional line)
5373 "Get the indentation of the current line, interpreting tabs.
5374 When LINE is given, assume it represents a line and compute its indentation."
5375 (if line
5376 (if (string-match "^ *" (org-remove-tabs line))
5377 (match-end 0))
5378 (save-excursion
5379 (beginning-of-line 1)
5380 (skip-chars-forward " \t")
5381 (current-column))))
5383 (defun org-remove-tabs (s &optional width)
5384 "Replace tabulators in S with spaces.
5385 Assumes that s is a single line, starting in column 0."
5386 (setq width (or width tab-width))
5387 (while (string-match "\t" s)
5388 (setq s (replace-match
5389 (make-string
5390 (- (* width (/ (+ (match-beginning 0) width) width))
5391 (match-beginning 0)) ?\ )
5392 t t s)))
5395 (defun org-fix-indentation (line ind)
5396 "Fix indentation in LINE.
5397 IND is a cons cell with target and minimum indentation.
5398 If the current indenation in LINE is smaller than the minimum,
5399 leave it alone. If it is larger than ind, set it to the target."
5400 (let* ((l (org-remove-tabs line))
5401 (i (org-get-indentation l))
5402 (i1 (car ind)) (i2 (cdr ind)))
5403 (if (>= i i2) (setq l (substring line i2)))
5404 (if (> i1 0)
5405 (concat (make-string i1 ?\ ) l)
5406 l)))
5408 (defun org-beginning-of-item ()
5409 "Go to the beginning of the current hand-formatted item.
5410 If the cursor is not in an item, throw an error."
5411 (interactive)
5412 (let ((pos (point))
5413 (limit (save-excursion
5414 (condition-case nil
5415 (progn
5416 (org-back-to-heading)
5417 (beginning-of-line 2) (point))
5418 (error (point-min)))))
5419 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5420 ind ind1)
5421 (if (org-at-item-p)
5422 (beginning-of-line 1)
5423 (beginning-of-line 1)
5424 (skip-chars-forward " \t")
5425 (setq ind (current-column))
5426 (if (catch 'exit
5427 (while t
5428 (beginning-of-line 0)
5429 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5431 (if (looking-at "[ \t]*$")
5432 (setq ind1 ind-empty)
5433 (skip-chars-forward " \t")
5434 (setq ind1 (current-column)))
5435 (if (< ind1 ind)
5436 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5438 (goto-char pos)
5439 (error "Not in an item")))))
5441 (defun org-end-of-item ()
5442 "Go to the end of the current hand-formatted item.
5443 If the cursor is not in an item, throw an error."
5444 (interactive)
5445 (let* ((pos (point))
5446 ind1
5447 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5448 (limit (save-excursion (outline-next-heading) (point)))
5449 (ind (save-excursion
5450 (org-beginning-of-item)
5451 (skip-chars-forward " \t")
5452 (current-column)))
5453 (end (catch 'exit
5454 (while t
5455 (beginning-of-line 2)
5456 (if (eobp) (throw 'exit (point)))
5457 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5458 (if (looking-at "[ \t]*$")
5459 (setq ind1 ind-empty)
5460 (skip-chars-forward " \t")
5461 (setq ind1 (current-column)))
5462 (if (<= ind1 ind)
5463 (throw 'exit (point-at-bol)))))))
5464 (if end
5465 (goto-char end)
5466 (goto-char pos)
5467 (error "Not in an item"))))
5469 (defun org-next-item ()
5470 "Move to the beginning of the next item in the current plain list.
5471 Error if not at a plain list, or if this is the last item in the list."
5472 (interactive)
5473 (let (ind ind1 (pos (point)))
5474 (org-beginning-of-item)
5475 (setq ind (org-get-indentation))
5476 (org-end-of-item)
5477 (setq ind1 (org-get-indentation))
5478 (unless (and (org-at-item-p) (= ind ind1))
5479 (goto-char pos)
5480 (error "On last item"))))
5482 (defun org-previous-item ()
5483 "Move to the beginning of the previous item in the current plain list.
5484 Error if not at a plain list, or if this is the first item in the list."
5485 (interactive)
5486 (let (beg ind ind1 (pos (point)))
5487 (org-beginning-of-item)
5488 (setq beg (point))
5489 (setq ind (org-get-indentation))
5490 (goto-char beg)
5491 (catch 'exit
5492 (while t
5493 (beginning-of-line 0)
5494 (if (looking-at "[ \t]*$")
5496 (if (<= (setq ind1 (org-get-indentation)) ind)
5497 (throw 'exit t)))))
5498 (condition-case nil
5499 (if (or (not (org-at-item-p))
5500 (< ind1 (1- ind)))
5501 (error "")
5502 (org-beginning-of-item))
5503 (error (goto-char pos)
5504 (error "On first item")))))
5506 (defun org-first-list-item-p ()
5507 "Is this heading the item in a plain list?"
5508 (unless (org-at-item-p)
5509 (error "Not at a plain list item"))
5510 (org-beginning-of-item)
5511 (= (point) (save-excursion (org-beginning-of-item-list))))
5513 (defun org-move-item-down ()
5514 "Move the plain list item at point down, i.e. swap with following item.
5515 Subitems (items with larger indentation) are considered part of the item,
5516 so this really moves item trees."
5517 (interactive)
5518 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5519 (org-beginning-of-item)
5520 (setq beg0 (point))
5521 (save-excursion
5522 (setq ne-beg (org-back-over-empty-lines))
5523 (setq beg (point)))
5524 (goto-char beg0)
5525 (setq ind (org-get-indentation))
5526 (org-end-of-item)
5527 (setq end0 (point))
5528 (setq ind1 (org-get-indentation))
5529 (setq ne-end (org-back-over-empty-lines))
5530 (setq end (point))
5531 (goto-char beg0)
5532 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5533 ;; include less whitespace
5534 (save-excursion
5535 (goto-char beg)
5536 (forward-line (- ne-beg ne-end))
5537 (setq beg (point))))
5538 (goto-char end0)
5539 (if (and (org-at-item-p) (= ind ind1))
5540 (progn
5541 (org-end-of-item)
5542 (org-back-over-empty-lines)
5543 (setq txt (buffer-substring beg end))
5544 (save-excursion
5545 (delete-region beg end))
5546 (setq pos (point))
5547 (insert txt)
5548 (goto-char pos) (org-skip-whitespace)
5549 (org-maybe-renumber-ordered-list))
5550 (goto-char pos)
5551 (error "Cannot move this item further down"))))
5553 (defun org-move-item-up (arg)
5554 "Move the plain list item at point up, i.e. swap with previous item.
5555 Subitems (items with larger indentation) are considered part of the item,
5556 so this really moves item trees."
5557 (interactive "p")
5558 (let (beg beg0 end ind ind1 (pos (point)) txt
5559 ne-beg ne-ins ins-end)
5560 (org-beginning-of-item)
5561 (setq beg0 (point))
5562 (setq ind (org-get-indentation))
5563 (save-excursion
5564 (setq ne-beg (org-back-over-empty-lines))
5565 (setq beg (point)))
5566 (goto-char beg0)
5567 (org-end-of-item)
5568 (setq end (point))
5569 (goto-char beg0)
5570 (catch 'exit
5571 (while t
5572 (beginning-of-line 0)
5573 (if (looking-at "[ \t]*$")
5574 (if org-empty-line-terminates-plain-lists
5575 (progn
5576 (goto-char pos)
5577 (error "Cannot move this item further up"))
5578 nil)
5579 (if (<= (setq ind1 (org-get-indentation)) ind)
5580 (throw 'exit t)))))
5581 (condition-case nil
5582 (org-beginning-of-item)
5583 (error (goto-char beg)
5584 (error "Cannot move this item further up")))
5585 (setq ind1 (org-get-indentation))
5586 (if (and (org-at-item-p) (= ind ind1))
5587 (progn
5588 (setq ne-ins (org-back-over-empty-lines))
5589 (setq txt (buffer-substring beg end))
5590 (save-excursion
5591 (delete-region beg end))
5592 (setq pos (point))
5593 (insert txt)
5594 (setq ins-end (point))
5595 (goto-char pos) (org-skip-whitespace)
5597 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5598 ;; Move whitespace back to beginning
5599 (save-excursion
5600 (goto-char ins-end)
5601 (let ((kill-whole-line t))
5602 (kill-line (- ne-ins ne-beg)) (point)))
5603 (insert (make-string (- ne-ins ne-beg) ?\n)))
5605 (org-maybe-renumber-ordered-list))
5606 (goto-char pos)
5607 (error "Cannot move this item further up"))))
5609 (defun org-maybe-renumber-ordered-list ()
5610 "Renumber the ordered list at point if setup allows it.
5611 This tests the user option `org-auto-renumber-ordered-lists' before
5612 doing the renumbering."
5613 (interactive)
5614 (when (and org-auto-renumber-ordered-lists
5615 (org-at-item-p))
5616 (if (match-beginning 3)
5617 (org-renumber-ordered-list 1)
5618 (org-fix-bullet-type))))
5620 (defun org-maybe-renumber-ordered-list-safe ()
5621 (condition-case nil
5622 (save-excursion
5623 (org-maybe-renumber-ordered-list))
5624 (error nil)))
5626 (defun org-cycle-list-bullet (&optional which)
5627 "Cycle through the different itemize/enumerate bullets.
5628 This cycle the entire list level through the sequence:
5630 `-' -> `+' -> `*' -> `1.' -> `1)'
5632 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5633 0 meand `-', 1 means `+' etc."
5634 (interactive "P")
5635 (org-preserve-lc
5636 (org-beginning-of-item-list)
5637 (org-at-item-p)
5638 (beginning-of-line 1)
5639 (let ((current (match-string 0))
5640 (prevp (eq which 'previous))
5641 new)
5642 (setq new (cond
5643 ((and (numberp which)
5644 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5645 ((string-match "-" current) (if prevp "1)" "+"))
5646 ((string-match "\\+" current)
5647 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5648 ((string-match "\\*" current) (if prevp "+" "1."))
5649 ((string-match "\\." current) (if prevp "*" "1)"))
5650 ((string-match ")" current) (if prevp "1." "-"))
5651 (t (error "This should not happen"))))
5652 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5653 (org-fix-bullet-type)
5654 (org-maybe-renumber-ordered-list))))
5656 (defun org-get-string-indentation (s)
5657 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5658 (let ((n -1) (i 0) (w tab-width) c)
5659 (catch 'exit
5660 (while (< (setq n (1+ n)) (length s))
5661 (setq c (aref s n))
5662 (cond ((= c ?\ ) (setq i (1+ i)))
5663 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5664 (t (throw 'exit t)))))
5667 (defun org-renumber-ordered-list (arg)
5668 "Renumber an ordered plain list.
5669 Cursor needs to be in the first line of an item, the line that starts
5670 with something like \"1.\" or \"2)\"."
5671 (interactive "p")
5672 (unless (and (org-at-item-p)
5673 (match-beginning 3))
5674 (error "This is not an ordered list"))
5675 (let ((line (org-current-line))
5676 (col (current-column))
5677 (ind (org-get-string-indentation
5678 (buffer-substring (point-at-bol) (match-beginning 3))))
5679 ;; (term (substring (match-string 3) -1))
5680 ind1 (n (1- arg))
5681 fmt)
5682 ;; find where this list begins
5683 (org-beginning-of-item-list)
5684 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5685 (setq fmt (concat "%d" (match-string 1)))
5686 (beginning-of-line 0)
5687 ;; walk forward and replace these numbers
5688 (catch 'exit
5689 (while t
5690 (catch 'next
5691 (beginning-of-line 2)
5692 (if (eobp) (throw 'exit nil))
5693 (if (looking-at "[ \t]*$") (throw 'next nil))
5694 (skip-chars-forward " \t") (setq ind1 (current-column))
5695 (if (> ind1 ind) (throw 'next t))
5696 (if (< ind1 ind) (throw 'exit t))
5697 (if (not (org-at-item-p)) (throw 'exit nil))
5698 (delete-region (match-beginning 2) (match-end 2))
5699 (goto-char (match-beginning 2))
5700 (insert (format fmt (setq n (1+ n)))))))
5701 (goto-line line)
5702 (org-move-to-column col)))
5704 (defun org-fix-bullet-type ()
5705 "Make sure all items in this list have the same bullet as the firsst item."
5706 (interactive)
5707 (unless (org-at-item-p) (error "This is not a list"))
5708 (let ((line (org-current-line))
5709 (col (current-column))
5710 (ind (current-indentation))
5711 ind1 bullet)
5712 ;; find where this list begins
5713 (org-beginning-of-item-list)
5714 (beginning-of-line 1)
5715 ;; find out what the bullet type is
5716 (looking-at "[ \t]*\\(\\S-+\\)")
5717 (setq bullet (match-string 1))
5718 ;; walk forward and replace these numbers
5719 (beginning-of-line 0)
5720 (catch 'exit
5721 (while t
5722 (catch 'next
5723 (beginning-of-line 2)
5724 (if (eobp) (throw 'exit nil))
5725 (if (looking-at "[ \t]*$") (throw 'next nil))
5726 (skip-chars-forward " \t") (setq ind1 (current-column))
5727 (if (> ind1 ind) (throw 'next t))
5728 (if (< ind1 ind) (throw 'exit t))
5729 (if (not (org-at-item-p)) (throw 'exit nil))
5730 (skip-chars-forward " \t")
5731 (looking-at "\\S-+")
5732 (replace-match bullet))))
5733 (goto-line line)
5734 (org-move-to-column col)
5735 (if (string-match "[0-9]" bullet)
5736 (org-renumber-ordered-list 1))))
5738 (defun org-beginning-of-item-list ()
5739 "Go to the beginning of the current item list.
5740 I.e. to the first item in this list."
5741 (interactive)
5742 (org-beginning-of-item)
5743 (let ((pos (point-at-bol))
5744 (ind (org-get-indentation))
5745 ind1)
5746 ;; find where this list begins
5747 (catch 'exit
5748 (while t
5749 (catch 'next
5750 (beginning-of-line 0)
5751 (if (looking-at "[ \t]*$")
5752 (throw (if (bobp) 'exit 'next) t))
5753 (skip-chars-forward " \t") (setq ind1 (current-column))
5754 (if (or (< ind1 ind)
5755 (and (= ind1 ind)
5756 (not (org-at-item-p)))
5757 (bobp))
5758 (throw 'exit t)
5759 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5760 (goto-char pos)))
5763 (defun org-end-of-item-list ()
5764 "Go to the end of the current item list.
5765 I.e. to the text after the last item."
5766 (interactive)
5767 (org-beginning-of-item)
5768 (let ((pos (point-at-bol))
5769 (ind (org-get-indentation))
5770 ind1)
5771 ;; find where this list begins
5772 (catch 'exit
5773 (while t
5774 (catch 'next
5775 (beginning-of-line 2)
5776 (if (looking-at "[ \t]*$")
5777 (throw (if (eobp) 'exit 'next) t))
5778 (skip-chars-forward " \t") (setq ind1 (current-column))
5779 (if (or (< ind1 ind)
5780 (and (= ind1 ind)
5781 (not (org-at-item-p)))
5782 (eobp))
5783 (progn
5784 (setq pos (point-at-bol))
5785 (throw 'exit t))))))
5786 (goto-char pos)))
5789 (defvar org-last-indent-begin-marker (make-marker))
5790 (defvar org-last-indent-end-marker (make-marker))
5792 (defun org-outdent-item (arg)
5793 "Outdent a local list item."
5794 (interactive "p")
5795 (org-indent-item (- arg)))
5797 (defun org-indent-item (arg)
5798 "Indent a local list item."
5799 (interactive "p")
5800 (unless (org-at-item-p)
5801 (error "Not on an item"))
5802 (save-excursion
5803 (let (beg end ind ind1 tmp delta ind-down ind-up)
5804 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5805 (setq beg org-last-indent-begin-marker
5806 end org-last-indent-end-marker)
5807 (org-beginning-of-item)
5808 (setq beg (move-marker org-last-indent-begin-marker (point)))
5809 (org-end-of-item)
5810 (setq end (move-marker org-last-indent-end-marker (point))))
5811 (goto-char beg)
5812 (setq tmp (org-item-indent-positions)
5813 ind (car tmp)
5814 ind-down (nth 2 tmp)
5815 ind-up (nth 1 tmp)
5816 delta (if (> arg 0)
5817 (if ind-down (- ind-down ind) 2)
5818 (if ind-up (- ind-up ind) -2)))
5819 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5820 (while (< (point) end)
5821 (beginning-of-line 1)
5822 (skip-chars-forward " \t") (setq ind1 (current-column))
5823 (delete-region (point-at-bol) (point))
5824 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5825 (beginning-of-line 2))))
5826 (org-fix-bullet-type)
5827 (org-maybe-renumber-ordered-list-safe)
5828 (save-excursion
5829 (beginning-of-line 0)
5830 (condition-case nil (org-beginning-of-item) (error nil))
5831 (org-maybe-renumber-ordered-list-safe)))
5833 (defun org-item-indent-positions ()
5834 "Return indentation for plain list items.
5835 This returns a list with three values: The current indentation, the
5836 parent indentation and the indentation a child should habe.
5837 Assumes cursor in item line."
5838 (let* ((bolpos (point-at-bol))
5839 (ind (org-get-indentation))
5840 ind-down ind-up pos)
5841 (save-excursion
5842 (org-beginning-of-item-list)
5843 (skip-chars-backward "\n\r \t")
5844 (when (org-in-item-p)
5845 (org-beginning-of-item)
5846 (setq ind-up (org-get-indentation))))
5847 (setq pos (point))
5848 (save-excursion
5849 (cond
5850 ((and (condition-case nil (progn (org-previous-item) t)
5851 (error nil))
5852 (or (forward-char 1) t)
5853 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5854 (setq ind-down (org-get-indentation)))
5855 ((and (goto-char pos)
5856 (org-at-item-p))
5857 (goto-char (match-end 0))
5858 (skip-chars-forward " \t")
5859 (setq ind-down (current-column)))))
5860 (list ind ind-up ind-down)))
5862 ;;; The orgstruct minor mode
5864 ;; Define a minor mode which can be used in other modes in order to
5865 ;; integrate the org-mode structure editing commands.
5867 ;; This is really a hack, because the org-mode structure commands use
5868 ;; keys which normally belong to the major mode. Here is how it
5869 ;; works: The minor mode defines all the keys necessary to operate the
5870 ;; structure commands, but wraps the commands into a function which
5871 ;; tests if the cursor is currently at a headline or a plain list
5872 ;; item. If that is the case, the structure command is used,
5873 ;; temporarily setting many Org-mode variables like regular
5874 ;; expressions for filling etc. However, when any of those keys is
5875 ;; used at a different location, function uses `key-binding' to look
5876 ;; up if the key has an associated command in another currently active
5877 ;; keymap (minor modes, major mode, global), and executes that
5878 ;; command. There might be problems if any of the keys is otherwise
5879 ;; used as a prefix key.
5881 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5882 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5883 ;; addresses this by checking explicitly for both bindings.
5885 (defvar orgstruct-mode-map (make-sparse-keymap)
5886 "Keymap for the minor `orgstruct-mode'.")
5888 (defvar org-local-vars nil
5889 "List of local variables, for use by `orgstruct-mode'")
5891 ;;;###autoload
5892 (define-minor-mode orgstruct-mode
5893 "Toggle the minor more `orgstruct-mode'.
5894 This mode is for using Org-mode structure commands in other modes.
5895 The following key behave as if Org-mode was active, if the cursor
5896 is on a headline, or on a plain list item (both in the definition
5897 of Org-mode).
5899 M-up Move entry/item up
5900 M-down Move entry/item down
5901 M-left Promote
5902 M-right Demote
5903 M-S-up Move entry/item up
5904 M-S-down Move entry/item down
5905 M-S-left Promote subtree
5906 M-S-right Demote subtree
5907 M-q Fill paragraph and items like in Org-mode
5908 C-c ^ Sort entries
5909 C-c - Cycle list bullet
5910 TAB Cycle item visibility
5911 M-RET Insert new heading/item
5912 S-M-RET Insert new TODO heading / Chekbox item
5913 C-c C-c Set tags / toggle checkbox"
5914 nil " OrgStruct" nil
5915 (org-load-modules-maybe)
5916 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5918 ;;;###autoload
5919 (defun turn-on-orgstruct ()
5920 "Unconditionally turn on `orgstruct-mode'."
5921 (orgstruct-mode 1))
5923 ;;;###autoload
5924 (defun turn-on-orgstruct++ ()
5925 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5926 In addition to setting orgstruct-mode, this also exports all indentation and
5927 autofilling variables from org-mode into the buffer. Note that turning
5928 off orgstruct-mode will *not* remove these additional settings."
5929 (orgstruct-mode 1)
5930 (let (var val)
5931 (mapc
5932 (lambda (x)
5933 (when (string-match
5934 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5935 (symbol-name (car x)))
5936 (setq var (car x) val (nth 1 x))
5937 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5938 org-local-vars)))
5940 (defun orgstruct-error ()
5941 "Error when there is no default binding for a structure key."
5942 (interactive)
5943 (error "This key has no function outside structure elements"))
5945 (defun orgstruct-setup ()
5946 "Setup orgstruct keymaps."
5947 (let ((nfunc 0)
5948 (bindings
5949 (list
5950 '([(meta up)] org-metaup)
5951 '([(meta down)] org-metadown)
5952 '([(meta left)] org-metaleft)
5953 '([(meta right)] org-metaright)
5954 '([(meta shift up)] org-shiftmetaup)
5955 '([(meta shift down)] org-shiftmetadown)
5956 '([(meta shift left)] org-shiftmetaleft)
5957 '([(meta shift right)] org-shiftmetaright)
5958 '([(shift up)] org-shiftup)
5959 '([(shift down)] org-shiftdown)
5960 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5961 '("\M-q" fill-paragraph)
5962 '("\C-c^" org-sort)
5963 '("\C-c-" org-cycle-list-bullet)))
5964 elt key fun cmd)
5965 (while (setq elt (pop bindings))
5966 (setq nfunc (1+ nfunc))
5967 (setq key (org-key (car elt))
5968 fun (nth 1 elt)
5969 cmd (orgstruct-make-binding fun nfunc key))
5970 (org-defkey orgstruct-mode-map key cmd))
5972 ;; Special treatment needed for TAB and RET
5973 (org-defkey orgstruct-mode-map [(tab)]
5974 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5975 (org-defkey orgstruct-mode-map "\C-i"
5976 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5978 (org-defkey orgstruct-mode-map "\M-\C-m"
5979 (orgstruct-make-binding 'org-insert-heading 105
5980 "\M-\C-m" [(meta return)]))
5981 (org-defkey orgstruct-mode-map [(meta return)]
5982 (orgstruct-make-binding 'org-insert-heading 106
5983 [(meta return)] "\M-\C-m"))
5985 (org-defkey orgstruct-mode-map [(shift meta return)]
5986 (orgstruct-make-binding 'org-insert-todo-heading 107
5987 [(meta return)] "\M-\C-m"))
5989 (unless org-local-vars
5990 (setq org-local-vars (org-get-local-variables)))
5994 (defun orgstruct-make-binding (fun n &rest keys)
5995 "Create a function for binding in the structure minor mode.
5996 FUN is the command to call inside a table. N is used to create a unique
5997 command name. KEYS are keys that should be checked in for a command
5998 to execute outside of tables."
5999 (eval
6000 (list 'defun
6001 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6002 '(arg)
6003 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6004 "Outside of structure, run the binding of `"
6005 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6006 "'.")
6007 '(interactive "p")
6008 (list 'if
6009 '(org-context-p 'headline 'item)
6010 (list 'org-run-like-in-org-mode (list 'quote fun))
6011 (list 'let '(orgstruct-mode)
6012 (list 'call-interactively
6013 (append '(or)
6014 (mapcar (lambda (k)
6015 (list 'key-binding k))
6016 keys)
6017 '('orgstruct-error))))))))
6019 (defun org-context-p (&rest contexts)
6020 "Check if local context is and of CONTEXTS.
6021 Possible values in the list of contexts are `table', `headline', and `item'."
6022 (let ((pos (point)))
6023 (goto-char (point-at-bol))
6024 (prog1 (or (and (memq 'table contexts)
6025 (looking-at "[ \t]*|"))
6026 (and (memq 'headline contexts)
6027 (looking-at "\\*+"))
6028 (and (memq 'item contexts)
6029 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6030 (goto-char pos))))
6032 (defun org-get-local-variables ()
6033 "Return a list of all local variables in an org-mode buffer."
6034 (let (varlist)
6035 (with-current-buffer (get-buffer-create "*Org tmp*")
6036 (erase-buffer)
6037 (org-mode)
6038 (setq varlist (buffer-local-variables)))
6039 (kill-buffer "*Org tmp*")
6040 (delq nil
6041 (mapcar
6042 (lambda (x)
6043 (setq x
6044 (if (symbolp x)
6045 (list x)
6046 (list (car x) (list 'quote (cdr x)))))
6047 (if (string-match
6048 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6049 (symbol-name (car x)))
6050 x nil))
6051 varlist))))
6053 ;;;###autoload
6054 (defun org-run-like-in-org-mode (cmd)
6055 (org-load-modules-maybe)
6056 (unless org-local-vars
6057 (setq org-local-vars (org-get-local-variables)))
6058 (eval (list 'let org-local-vars
6059 (list 'call-interactively (list 'quote cmd)))))
6061 ;;;; Archiving
6063 (defun org-get-category (&optional pos)
6064 "Get the category applying to position POS."
6065 (get-text-property (or pos (point)) 'org-category))
6067 (defun org-refresh-category-properties ()
6068 "Refresh category text properties in the buffer."
6069 (let ((def-cat (cond
6070 ((null org-category)
6071 (if buffer-file-name
6072 (file-name-sans-extension
6073 (file-name-nondirectory buffer-file-name))
6074 "???"))
6075 ((symbolp org-category) (symbol-name org-category))
6076 (t org-category)))
6077 beg end cat pos optionp)
6078 (org-unmodified
6079 (save-excursion
6080 (save-restriction
6081 (widen)
6082 (goto-char (point-min))
6083 (put-text-property (point) (point-max) 'org-category def-cat)
6084 (while (re-search-forward
6085 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6086 (setq pos (match-end 0)
6087 optionp (equal (char-after (match-beginning 0)) ?#)
6088 cat (org-trim (match-string 2)))
6089 (if optionp
6090 (setq beg (point-at-bol) end (point-max))
6091 (org-back-to-heading t)
6092 (setq beg (point) end (org-end-of-subtree t t)))
6093 (put-text-property beg end 'org-category cat)
6094 (goto-char pos)))))))
6097 ;;;; Link Stuff
6099 ;;; Link abbreviations
6101 (defun org-link-expand-abbrev (link)
6102 "Apply replacements as defined in `org-link-abbrev-alist."
6103 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6104 (let* ((key (match-string 1 link))
6105 (as (or (assoc key org-link-abbrev-alist-local)
6106 (assoc key org-link-abbrev-alist)))
6107 (tag (and (match-end 2) (match-string 3 link)))
6108 rpl)
6109 (if (not as)
6110 link
6111 (setq rpl (cdr as))
6112 (cond
6113 ((symbolp rpl) (funcall rpl tag))
6114 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6115 (t (concat rpl tag)))))
6116 link))
6118 ;;; Storing and inserting links
6120 (defvar org-insert-link-history nil
6121 "Minibuffer history for links inserted with `org-insert-link'.")
6123 (defvar org-stored-links nil
6124 "Contains the links stored with `org-store-link'.")
6126 (defvar org-store-link-plist nil
6127 "Plist with info about the most recently link created with `org-store-link'.")
6129 (defvar org-link-protocols nil
6130 "Link protocols added to Org-mode using `org-add-link-type'.")
6132 (defvar org-store-link-functions nil
6133 "List of functions that are called to create and store a link.
6134 Each function will be called in turn until one returns a non-nil
6135 value. Each function should check if it is responsible for creating
6136 this link (for example by looking at the major mode).
6137 If not, it must exit and return nil.
6138 If yes, it should return a non-nil value after a calling
6139 `org-store-link-props' with a list of properties and values.
6140 Special properties are:
6142 :type The link prefix. like \"http\". This must be given.
6143 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6144 This is obligatory as well.
6145 :description Optional default description for the second pair
6146 of brackets in an Org-mode link. The user can still change
6147 this when inserting this link into an Org-mode buffer.
6149 In addition to these, any additional properties can be specified
6150 and then used in remember templates.")
6152 (defun org-add-link-type (type &optional follow export)
6153 "Add TYPE to the list of `org-link-types'.
6154 Re-compute all regular expressions depending on `org-link-types'
6156 FOLLOW and EXPORT are two functions.
6158 FOLLOW should take the link path as the single argument and do whatever
6159 is necessary to follow the link, for example find a file or display
6160 a mail message.
6162 EXPORT should format the link path for export to one of the export formats.
6163 It should be a function accepting three arguments:
6165 path the path of the link, the text after the prefix (like \"http:\")
6166 desc the description of the link, if any, nil if there was no descripton
6167 format the export format, a symbol like `html' or `latex'.
6169 The function may use the FORMAT information to return different values
6170 depending on the format. The return value will be put literally into
6171 the exported file.
6172 Org-mode has a built-in default for exporting links. If you are happy with
6173 this default, there is no need to define an export function for the link
6174 type. For a simple example of an export function, see `org-bbdb.el'."
6175 (add-to-list 'org-link-types type t)
6176 (org-make-link-regexps)
6177 (if (assoc type org-link-protocols)
6178 (setcdr (assoc type org-link-protocols) (list follow export))
6179 (push (list type follow export) org-link-protocols)))
6182 ;;;###autoload
6183 (defun org-store-link (arg)
6184 "\\<org-mode-map>Store an org-link to the current location.
6185 This link is added to `org-stored-links' and can later be inserted
6186 into an org-buffer with \\[org-insert-link].
6188 For some link types, a prefix arg is interpreted:
6189 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6190 For file links, arg negates `org-context-in-file-links'."
6191 (interactive "P")
6192 (org-load-modules-maybe)
6193 (setq org-store-link-plist nil) ; reset
6194 (let (link cpltxt desc description search txt)
6195 (cond
6197 ((run-hook-with-args-until-success 'org-store-link-functions)
6198 (setq link (plist-get org-store-link-plist :link)
6199 desc (or (plist-get org-store-link-plist :description) link)))
6201 ((eq major-mode 'calendar-mode)
6202 (let ((cd (calendar-cursor-to-date)))
6203 (setq link
6204 (format-time-string
6205 (car org-time-stamp-formats)
6206 (apply 'encode-time
6207 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6208 nil nil nil))))
6209 (org-store-link-props :type "calendar" :date cd)))
6211 ((eq major-mode 'w3-mode)
6212 (setq cpltxt (url-view-url t)
6213 link (org-make-link cpltxt))
6214 (org-store-link-props :type "w3" :url (url-view-url t)))
6216 ((eq major-mode 'w3m-mode)
6217 (setq cpltxt (or w3m-current-title w3m-current-url)
6218 link (org-make-link w3m-current-url))
6219 (org-store-link-props :type "w3m" :url (url-view-url t)))
6221 ((setq search (run-hook-with-args-until-success
6222 'org-create-file-search-functions))
6223 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6224 "::" search))
6225 (setq cpltxt (or description link)))
6227 ((eq major-mode 'image-mode)
6228 (setq cpltxt (concat "file:"
6229 (abbreviate-file-name buffer-file-name))
6230 link (org-make-link cpltxt))
6231 (org-store-link-props :type "image" :file buffer-file-name))
6233 ((eq major-mode 'dired-mode)
6234 ;; link to the file in the current line
6235 (setq cpltxt (concat "file:"
6236 (abbreviate-file-name
6237 (expand-file-name
6238 (dired-get-filename nil t))))
6239 link (org-make-link cpltxt)))
6241 ((and buffer-file-name (org-mode-p))
6242 ;; Just link to current headline
6243 (setq cpltxt (concat "file:"
6244 (abbreviate-file-name buffer-file-name)))
6245 ;; Add a context search string
6246 (when (org-xor org-context-in-file-links arg)
6247 ;; Check if we are on a target
6248 (if (org-in-regexp "<<\\(.*?\\)>>")
6249 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6250 (setq txt (cond
6251 ((org-on-heading-p) nil)
6252 ((org-region-active-p)
6253 (buffer-substring (region-beginning) (region-end)))
6254 (t nil)))
6255 (when (or (null txt) (string-match "\\S-" txt))
6256 (setq cpltxt
6257 (concat cpltxt "::"
6258 (condition-case nil
6259 (org-make-org-heading-search-string txt)
6260 (error "")))
6261 desc "NONE"))))
6262 (if (string-match "::\\'" cpltxt)
6263 (setq cpltxt (substring cpltxt 0 -2)))
6264 (setq link (org-make-link cpltxt)))
6266 ((buffer-file-name (buffer-base-buffer))
6267 ;; Just link to this file here.
6268 (setq cpltxt (concat "file:"
6269 (abbreviate-file-name
6270 (buffer-file-name (buffer-base-buffer)))))
6271 ;; Add a context string
6272 (when (org-xor org-context-in-file-links arg)
6273 (setq txt (if (org-region-active-p)
6274 (buffer-substring (region-beginning) (region-end))
6275 (buffer-substring (point-at-bol) (point-at-eol))))
6276 ;; Only use search option if there is some text.
6277 (when (string-match "\\S-" txt)
6278 (setq cpltxt
6279 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6280 desc "NONE")))
6281 (setq link (org-make-link cpltxt)))
6283 ((interactive-p)
6284 (error "Cannot link to a buffer which is not visiting a file"))
6286 (t (setq link nil)))
6288 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6289 (setq link (or link cpltxt)
6290 desc (or desc cpltxt))
6291 (if (equal desc "NONE") (setq desc nil))
6293 (if (and (interactive-p) link)
6294 (progn
6295 (setq org-stored-links
6296 (cons (list link desc) org-stored-links))
6297 (message "Stored: %s" (or desc link)))
6298 (and link (org-make-link-string link desc)))))
6300 (defun org-store-link-props (&rest plist)
6301 "Store link properties, extract names and addresses."
6302 (let (x adr)
6303 (when (setq x (plist-get plist :from))
6304 (setq adr (mail-extract-address-components x))
6305 (plist-put plist :fromname (car adr))
6306 (plist-put plist :fromaddress (nth 1 adr)))
6307 (when (setq x (plist-get plist :to))
6308 (setq adr (mail-extract-address-components x))
6309 (plist-put plist :toname (car adr))
6310 (plist-put plist :toaddress (nth 1 adr))))
6311 (let ((from (plist-get plist :from))
6312 (to (plist-get plist :to)))
6313 (when (and from to org-from-is-user-regexp)
6314 (plist-put plist :fromto
6315 (if (string-match org-from-is-user-regexp from)
6316 (concat "to %t")
6317 (concat "from %f")))))
6318 (setq org-store-link-plist plist))
6320 (defun org-add-link-props (&rest plist)
6321 "Add these properties to the link property list."
6322 (let (key value)
6323 (while plist
6324 (setq key (pop plist) value (pop plist))
6325 (setq org-store-link-plist
6326 (plist-put org-store-link-plist key value)))))
6328 (defun org-email-link-description (&optional fmt)
6329 "Return the description part of an email link.
6330 This takes information from `org-store-link-plist' and formats it
6331 according to FMT (default from `org-email-link-description-format')."
6332 (setq fmt (or fmt org-email-link-description-format))
6333 (let* ((p org-store-link-plist)
6334 (to (plist-get p :toaddress))
6335 (from (plist-get p :fromaddress))
6336 (table
6337 (list
6338 (cons "%c" (plist-get p :fromto))
6339 (cons "%F" (plist-get p :from))
6340 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6341 (cons "%T" (plist-get p :to))
6342 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6343 (cons "%s" (plist-get p :subject))
6344 (cons "%m" (plist-get p :message-id)))))
6345 (when (string-match "%c" fmt)
6346 ;; Check if the user wrote this message
6347 (if (and org-from-is-user-regexp from to
6348 (save-match-data (string-match org-from-is-user-regexp from)))
6349 (setq fmt (replace-match "to %t" t t fmt))
6350 (setq fmt (replace-match "from %f" t t fmt))))
6351 (org-replace-escapes fmt table)))
6353 (defun org-make-org-heading-search-string (&optional string heading)
6354 "Make search string for STRING or current headline."
6355 (interactive)
6356 (let ((s (or string (org-get-heading))))
6357 (unless (and string (not heading))
6358 ;; We are using a headline, clean up garbage in there.
6359 (if (string-match org-todo-regexp s)
6360 (setq s (replace-match "" t t s)))
6361 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6362 (setq s (replace-match "" t t s)))
6363 (setq s (org-trim s))
6364 (if (string-match (concat "^\\(" org-quote-string "\\|"
6365 org-comment-string "\\)") s)
6366 (setq s (replace-match "" t t s)))
6367 (while (string-match org-ts-regexp s)
6368 (setq s (replace-match "" t t s))))
6369 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6370 (setq s (replace-match " " t t s)))
6371 (or string (setq s (concat "*" s))) ; Add * for headlines
6372 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6374 (defun org-make-link (&rest strings)
6375 "Concatenate STRINGS."
6376 (apply 'concat strings))
6378 (defun org-make-link-string (link &optional description)
6379 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6380 (unless (string-match "\\S-" link)
6381 (error "Empty link"))
6382 (when (stringp description)
6383 ;; Remove brackets from the description, they are fatal.
6384 (while (string-match "\\[" description)
6385 (setq description (replace-match "{" t t description)))
6386 (while (string-match "\\]" description)
6387 (setq description (replace-match "}" t t description))))
6388 (when (equal (org-link-escape link) description)
6389 ;; No description needed, it is identical
6390 (setq description nil))
6391 (when (and (not description)
6392 (not (equal link (org-link-escape link))))
6393 (setq description link))
6394 (concat "[[" (org-link-escape link) "]"
6395 (if description (concat "[" description "]") "")
6396 "]"))
6398 (defconst org-link-escape-chars
6399 '((?\ . "%20")
6400 (?\[ . "%5B")
6401 (?\] . "%5D")
6402 (?\340 . "%E0") ; `a
6403 (?\342 . "%E2") ; ^a
6404 (?\347 . "%E7") ; ,c
6405 (?\350 . "%E8") ; `e
6406 (?\351 . "%E9") ; 'e
6407 (?\352 . "%EA") ; ^e
6408 (?\356 . "%EE") ; ^i
6409 (?\364 . "%F4") ; ^o
6410 (?\371 . "%F9") ; `u
6411 (?\373 . "%FB") ; ^u
6412 (?\; . "%3B")
6413 (?? . "%3F")
6414 (?= . "%3D")
6415 (?+ . "%2B")
6417 "Association list of escapes for some characters problematic in links.
6418 This is the list that is used for internal purposes.")
6420 (defconst org-link-escape-chars-browser
6421 '((?\ . "%20")) ; 32 for the SPC char
6422 "Association list of escapes for some characters problematic in links.
6423 This is the list that is used before handing over to the browser.")
6425 (defun org-link-escape (text &optional table)
6426 "Escape charaters in TEXT that are problematic for links."
6427 (setq table (or table org-link-escape-chars))
6428 (when text
6429 (let ((re (mapconcat (lambda (x) (regexp-quote
6430 (char-to-string (car x))))
6431 table "\\|")))
6432 (while (string-match re text)
6433 (setq text
6434 (replace-match
6435 (cdr (assoc (string-to-char (match-string 0 text))
6436 table))
6437 t t text)))
6438 text)))
6440 (defun org-link-unescape (text &optional table)
6441 "Reverse the action of `org-link-escape'."
6442 (setq table (or table org-link-escape-chars))
6443 (when text
6444 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6445 table "\\|")))
6446 (while (string-match re text)
6447 (setq text
6448 (replace-match
6449 (char-to-string (car (rassoc (match-string 0 text) table)))
6450 t t text)))
6451 text)))
6453 (defun org-xor (a b)
6454 "Exclusive or."
6455 (if a (not b) b))
6457 (defun org-get-header (header)
6458 "Find a header field in the current buffer."
6459 (save-excursion
6460 (goto-char (point-min))
6461 (let ((case-fold-search t) s)
6462 (cond
6463 ((eq header 'from)
6464 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6465 (setq s (match-string 1)))
6466 (while (string-match "\"" s)
6467 (setq s (replace-match "" t t s)))
6468 (if (string-match "[<(].*" s)
6469 (setq s (replace-match "" t t s))))
6470 ((eq header 'message-id)
6471 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6472 (setq s (match-string 1))))
6473 ((eq header 'subject)
6474 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6475 (setq s (match-string 1)))))
6476 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6477 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6478 s)))
6481 (defun org-fixup-message-id-for-http (s)
6482 "Replace special characters in a message id, so it can be used in an http query."
6483 (while (string-match "<" s)
6484 (setq s (replace-match "%3C" t t s)))
6485 (while (string-match ">" s)
6486 (setq s (replace-match "%3E" t t s)))
6487 (while (string-match "@" s)
6488 (setq s (replace-match "%40" t t s)))
6491 ;;;###autoload
6492 (defun org-insert-link-global ()
6493 "Insert a link like Org-mode does.
6494 This command can be called in any mode to insert a link in Org-mode syntax."
6495 (interactive)
6496 (org-load-modules-maybe)
6497 (org-run-like-in-org-mode 'org-insert-link))
6499 (defun org-insert-link (&optional complete-file link-location)
6500 "Insert a link. At the prompt, enter the link.
6502 Completion can be used to select a link previously stored with
6503 `org-store-link'. When the empty string is entered (i.e. if you just
6504 press RET at the prompt), the link defaults to the most recently
6505 stored link. As SPC triggers completion in the minibuffer, you need to
6506 use M-SPC or C-q SPC to force the insertion of a space character.
6508 You will also be prompted for a description, and if one is given, it will
6509 be displayed in the buffer instead of the link.
6511 If there is already a link at point, this command will allow you to edit link
6512 and description parts.
6514 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6515 be selected using completion. The path to the file will be relative to the
6516 current directory if the file is in the current directory or a subdirectory.
6517 Otherwise, the link will be the absolute path as completed in the minibuffer
6518 \(i.e. normally ~/path/to/file).
6520 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6521 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6522 of `org-keep-stored-link-after-insertion'.
6524 If `org-make-link-description-function' is non-nil, this function will be
6525 called with the link target, and the result will be the default
6526 link description.
6528 If the LINK-LOCATION parameter is non-nil, this value will be
6529 used as the link location instead of reading one interactively."
6530 (interactive "P")
6531 (let* ((wcf (current-window-configuration))
6532 (region (if (org-region-active-p)
6533 (buffer-substring (region-beginning) (region-end))))
6534 (remove (and region (list (region-beginning) (region-end))))
6535 (desc region)
6536 tmphist ; byte-compile incorrectly complains about this
6537 (link link-location)
6538 entry file)
6539 (cond
6540 (link-location) ; specified by arg, just use it.
6541 ((org-in-regexp org-bracket-link-regexp 1)
6542 ;; We do have a link at point, and we are going to edit it.
6543 (setq remove (list (match-beginning 0) (match-end 0)))
6544 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6545 (setq link (read-string "Link: "
6546 (org-link-unescape
6547 (org-match-string-no-properties 1)))))
6548 ((or (org-in-regexp org-angle-link-re)
6549 (org-in-regexp org-plain-link-re))
6550 ;; Convert to bracket link
6551 (setq remove (list (match-beginning 0) (match-end 0))
6552 link (read-string "Link: "
6553 (org-remove-angle-brackets (match-string 0)))))
6554 ((equal complete-file '(4))
6555 ;; Completing read for file names.
6556 (setq file (read-file-name "File: "))
6557 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6558 (pwd1 (file-name-as-directory (abbreviate-file-name
6559 (expand-file-name ".")))))
6560 (cond
6561 ((equal complete-file '(16))
6562 (setq link (org-make-link
6563 "file:"
6564 (abbreviate-file-name (expand-file-name file)))))
6565 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6566 (setq link (org-make-link "file:" (match-string 1 file))))
6567 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6568 (expand-file-name file))
6569 (setq link (org-make-link
6570 "file:" (match-string 1 (expand-file-name file)))))
6571 (t (setq link (org-make-link "file:" file))))))
6573 ;; Read link, with completion for stored links.
6574 (with-output-to-temp-buffer "*Org Links*"
6575 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6576 (when org-stored-links
6577 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6578 (princ (mapconcat
6579 (lambda (x)
6580 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6581 (reverse org-stored-links) "\n"))))
6582 (let ((cw (selected-window)))
6583 (select-window (get-buffer-window "*Org Links*"))
6584 (shrink-window-if-larger-than-buffer)
6585 (setq truncate-lines t)
6586 (select-window cw))
6587 ;; Fake a link history, containing the stored links.
6588 (setq tmphist (append (mapcar 'car org-stored-links)
6589 org-insert-link-history))
6590 (unwind-protect
6591 (setq link (org-completing-read
6592 "Link: "
6593 (append
6594 (mapcar (lambda (x) (list (concat (car x) ":")))
6595 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6596 (mapcar (lambda (x) (list (concat x ":")))
6597 org-link-types))
6598 nil nil nil
6599 'tmphist
6600 (or (car (car org-stored-links)))))
6601 (set-window-configuration wcf)
6602 (kill-buffer "*Org Links*"))
6603 (setq entry (assoc link org-stored-links))
6604 (or entry (push link org-insert-link-history))
6605 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6606 (not org-keep-stored-link-after-insertion))
6607 (setq org-stored-links (delq (assoc link org-stored-links)
6608 org-stored-links)))
6609 (setq desc (or desc (nth 1 entry)))))
6611 (if (string-match org-plain-link-re link)
6612 ;; URL-like link, normalize the use of angular brackets.
6613 (setq link (org-make-link (org-remove-angle-brackets link))))
6615 ;; Check if we are linking to the current file with a search option
6616 ;; If yes, simplify the link by using only the search option.
6617 (when (and buffer-file-name
6618 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6619 (let* ((path (match-string 1 link))
6620 (case-fold-search nil)
6621 (search (match-string 2 link)))
6622 (save-match-data
6623 (if (equal (file-truename buffer-file-name) (file-truename path))
6624 ;; We are linking to this same file, with a search option
6625 (setq link search)))))
6627 ;; Check if we can/should use a relative path. If yes, simplify the link
6628 (when (string-match "\\<file:\\(.*\\)" link)
6629 (let* ((path (match-string 1 link))
6630 (origpath path)
6631 (case-fold-search nil))
6632 (cond
6633 ((eq org-link-file-path-type 'absolute)
6634 (setq path (abbreviate-file-name (expand-file-name path))))
6635 ((eq org-link-file-path-type 'noabbrev)
6636 (setq path (expand-file-name path)))
6637 ((eq org-link-file-path-type 'relative)
6638 (setq path (file-relative-name path)))
6640 (save-match-data
6641 (if (string-match (concat "^" (regexp-quote
6642 (file-name-as-directory
6643 (expand-file-name "."))))
6644 (expand-file-name path))
6645 ;; We are linking a file with relative path name.
6646 (setq path (substring (expand-file-name path)
6647 (match-end 0)))))))
6648 (setq link (concat "file:" path))
6649 (if (equal desc origpath)
6650 (setq desc path))))
6652 (if org-make-link-description-function
6653 (setq desc (funcall org-make-link-description-function link desc)))
6655 (setq desc (read-string "Description: " desc))
6656 (unless (string-match "\\S-" desc) (setq desc nil))
6657 (if remove (apply 'delete-region remove))
6658 (insert (org-make-link-string link desc))))
6660 (defun org-completing-read (&rest args)
6661 (let ((minibuffer-local-completion-map
6662 (copy-keymap minibuffer-local-completion-map)))
6663 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6664 (apply 'completing-read args)))
6666 ;;; Opening/following a link
6668 (defvar org-link-search-failed nil)
6670 (defun org-next-link ()
6671 "Move forward to the next link.
6672 If the link is in hidden text, expose it."
6673 (interactive)
6674 (when (and org-link-search-failed (eq this-command last-command))
6675 (goto-char (point-min))
6676 (message "Link search wrapped back to beginning of buffer"))
6677 (setq org-link-search-failed nil)
6678 (let* ((pos (point))
6679 (ct (org-context))
6680 (a (assoc :link ct)))
6681 (if a (goto-char (nth 2 a)))
6682 (if (re-search-forward org-any-link-re nil t)
6683 (progn
6684 (goto-char (match-beginning 0))
6685 (if (org-invisible-p) (org-show-context)))
6686 (goto-char pos)
6687 (setq org-link-search-failed t)
6688 (error "No further link found"))))
6690 (defun org-previous-link ()
6691 "Move backward to the previous link.
6692 If the link is in hidden text, expose it."
6693 (interactive)
6694 (when (and org-link-search-failed (eq this-command last-command))
6695 (goto-char (point-max))
6696 (message "Link search wrapped back to end of buffer"))
6697 (setq org-link-search-failed nil)
6698 (let* ((pos (point))
6699 (ct (org-context))
6700 (a (assoc :link ct)))
6701 (if a (goto-char (nth 1 a)))
6702 (if (re-search-backward org-any-link-re nil t)
6703 (progn
6704 (goto-char (match-beginning 0))
6705 (if (org-invisible-p) (org-show-context)))
6706 (goto-char pos)
6707 (setq org-link-search-failed t)
6708 (error "No further link found"))))
6710 (defun org-find-file-at-mouse (ev)
6711 "Open file link or URL at mouse."
6712 (interactive "e")
6713 (mouse-set-point ev)
6714 (org-open-at-point 'in-emacs))
6716 (defun org-open-at-mouse (ev)
6717 "Open file link or URL at mouse."
6718 (interactive "e")
6719 (mouse-set-point ev)
6720 (org-open-at-point))
6722 (defvar org-window-config-before-follow-link nil
6723 "The window configuration before following a link.
6724 This is saved in case the need arises to restore it.")
6726 (defvar org-open-link-marker (make-marker)
6727 "Marker pointing to the location where `org-open-at-point; was called.")
6729 ;;;###autoload
6730 (defun org-open-at-point-global ()
6731 "Follow a link like Org-mode does.
6732 This command can be called in any mode to follow a link that has
6733 Org-mode syntax."
6734 (interactive)
6735 (org-run-like-in-org-mode 'org-open-at-point))
6737 ;;;###autoload
6738 (defun org-open-link-from-string (s &optional arg)
6739 "Open a link in the string S, as if it was in Org-mode."
6740 (interactive "sLink: \nP")
6741 (with-temp-buffer
6742 (let ((org-inhibit-startup t))
6743 (org-mode)
6744 (insert s)
6745 (goto-char (point-min))
6746 (org-open-at-point arg))))
6748 (defun org-open-at-point (&optional in-emacs)
6749 "Open link at or after point.
6750 If there is no link at point, this function will search forward up to
6751 the end of the current subtree.
6752 Normally, files will be opened by an appropriate application. If the
6753 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6754 (interactive "P")
6755 (org-load-modules-maybe)
6756 (move-marker org-open-link-marker (point))
6757 (setq org-window-config-before-follow-link (current-window-configuration))
6758 (org-remove-occur-highlights nil nil t)
6759 (if (org-at-timestamp-p t)
6760 (org-follow-timestamp-link)
6761 (let (type path link line search (pos (point)))
6762 (catch 'match
6763 (save-excursion
6764 (skip-chars-forward "^]\n\r")
6765 (when (org-in-regexp org-bracket-link-regexp)
6766 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6767 (while (string-match " *\n *" link)
6768 (setq link (replace-match " " t t link)))
6769 (setq link (org-link-expand-abbrev link))
6770 (if (string-match org-link-re-with-space2 link)
6771 (setq type (match-string 1 link) path (match-string 2 link))
6772 (setq type "thisfile" path link))
6773 (throw 'match t)))
6775 (when (get-text-property (point) 'org-linked-text)
6776 (setq type "thisfile"
6777 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6778 (1+ (point)) (point))
6779 path (buffer-substring
6780 (previous-single-property-change pos 'org-linked-text)
6781 (next-single-property-change pos 'org-linked-text)))
6782 (throw 'match t))
6784 (save-excursion
6785 (when (or (org-in-regexp org-angle-link-re)
6786 (org-in-regexp org-plain-link-re))
6787 (setq type (match-string 1) path (match-string 2))
6788 (throw 'match t)))
6789 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6790 (setq type "tree-match"
6791 path (match-string 1))
6792 (throw 'match t))
6793 (save-excursion
6794 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6795 (setq type "tags"
6796 path (match-string 1))
6797 (while (string-match ":" path)
6798 (setq path (replace-match "+" t t path)))
6799 (throw 'match t))))
6800 (unless path
6801 (error "No link found"))
6802 ;; Remove any trailing spaces in path
6803 (if (string-match " +\\'" path)
6804 (setq path (replace-match "" t t path)))
6806 (cond
6808 ((assoc type org-link-protocols)
6809 (funcall (nth 1 (assoc type org-link-protocols)) path))
6811 ((equal type "mailto")
6812 (let ((cmd (car org-link-mailto-program))
6813 (args (cdr org-link-mailto-program)) args1
6814 (address path) (subject "") a)
6815 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6816 (setq address (match-string 1 path)
6817 subject (org-link-escape (match-string 2 path))))
6818 (while args
6819 (cond
6820 ((not (stringp (car args))) (push (pop args) args1))
6821 (t (setq a (pop args))
6822 (if (string-match "%a" a)
6823 (setq a (replace-match address t t a)))
6824 (if (string-match "%s" a)
6825 (setq a (replace-match subject t t a)))
6826 (push a args1))))
6827 (apply cmd (nreverse args1))))
6829 ((member type '("http" "https" "ftp" "news"))
6830 (browse-url (concat type ":" (org-link-escape
6831 path org-link-escape-chars-browser))))
6833 ((member type '("message"))
6834 (browse-url (concat type ":" path)))
6836 ((string= type "tags")
6837 (org-tags-view in-emacs path))
6838 ((string= type "thisfile")
6839 (if in-emacs
6840 (switch-to-buffer-other-window
6841 (org-get-buffer-for-internal-link (current-buffer)))
6842 (org-mark-ring-push))
6843 (let ((cmd `(org-link-search
6844 ,path
6845 ,(cond ((equal in-emacs '(4)) 'occur)
6846 ((equal in-emacs '(16)) 'org-occur)
6847 (t nil))
6848 ,pos)))
6849 (condition-case nil (eval cmd)
6850 (error (progn (widen) (eval cmd))))))
6852 ((string= type "tree-match")
6853 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6855 ((string= type "file")
6856 (if (string-match "::\\([0-9]+\\)\\'" path)
6857 (setq line (string-to-number (match-string 1 path))
6858 path (substring path 0 (match-beginning 0)))
6859 (if (string-match "::\\(.+\\)\\'" path)
6860 (setq search (match-string 1 path)
6861 path (substring path 0 (match-beginning 0)))))
6862 (if (string-match "[*?{]" (file-name-nondirectory path))
6863 (dired path)
6864 (org-open-file path in-emacs line search)))
6866 ((string= type "news")
6867 (require 'org-gnus)
6868 (org-gnus-follow-link path))
6870 ((string= type "shell")
6871 (let ((cmd path))
6872 (if (or (not org-confirm-shell-link-function)
6873 (funcall org-confirm-shell-link-function
6874 (format "Execute \"%s\" in shell? "
6875 (org-add-props cmd nil
6876 'face 'org-warning))))
6877 (progn
6878 (message "Executing %s" cmd)
6879 (shell-command cmd))
6880 (error "Abort"))))
6882 ((string= type "elisp")
6883 (let ((cmd path))
6884 (if (or (not org-confirm-elisp-link-function)
6885 (funcall org-confirm-elisp-link-function
6886 (format "Execute \"%s\" as elisp? "
6887 (org-add-props cmd nil
6888 'face 'org-warning))))
6889 (message "%s => %s" cmd (eval (read cmd)))
6890 (error "Abort"))))
6893 (browse-url-at-point)))))
6894 (move-marker org-open-link-marker nil)
6895 (run-hook-with-args 'org-follow-link-hook))
6897 ;;;; Time estimates
6899 (defun org-get-effort (&optional pom)
6900 "Get the effort estimate for the current entry."
6901 (org-entry-get pom org-effort-property))
6903 ;;; File search
6905 (defvar org-create-file-search-functions nil
6906 "List of functions to construct the right search string for a file link.
6907 These functions are called in turn with point at the location to
6908 which the link should point.
6910 A function in the hook should first test if it would like to
6911 handle this file type, for example by checking the major-mode or
6912 the file extension. If it decides not to handle this file, it
6913 should just return nil to give other functions a chance. If it
6914 does handle the file, it must return the search string to be used
6915 when following the link. The search string will be part of the
6916 file link, given after a double colon, and `org-open-at-point'
6917 will automatically search for it. If special measures must be
6918 taken to make the search successful, another function should be
6919 added to the companion hook `org-execute-file-search-functions',
6920 which see.
6922 A function in this hook may also use `setq' to set the variable
6923 `description' to provide a suggestion for the descriptive text to
6924 be used for this link when it gets inserted into an Org-mode
6925 buffer with \\[org-insert-link].")
6927 (defvar org-execute-file-search-functions nil
6928 "List of functions to execute a file search triggered by a link.
6930 Functions added to this hook must accept a single argument, the
6931 search string that was part of the file link, the part after the
6932 double colon. The function must first check if it would like to
6933 handle this search, for example by checking the major-mode or the
6934 file extension. If it decides not to handle this search, it
6935 should just return nil to give other functions a chance. If it
6936 does handle the search, it must return a non-nil value to keep
6937 other functions from trying.
6939 Each function can access the current prefix argument through the
6940 variable `current-prefix-argument'. Note that a single prefix is
6941 used to force opening a link in Emacs, so it may be good to only
6942 use a numeric or double prefix to guide the search function.
6944 In case this is needed, a function in this hook can also restore
6945 the window configuration before `org-open-at-point' was called using:
6947 (set-window-configuration org-window-config-before-follow-link)")
6949 (defun org-link-search (s &optional type avoid-pos)
6950 "Search for a link search option.
6951 If S is surrounded by forward slashes, it is interpreted as a
6952 regular expression. In org-mode files, this will create an `org-occur'
6953 sparse tree. In ordinary files, `occur' will be used to list matches.
6954 If the current buffer is in `dired-mode', grep will be used to search
6955 in all files. If AVOID-POS is given, ignore matches near that position."
6956 (let ((case-fold-search t)
6957 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6958 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6959 (append '(("") (" ") ("\t") ("\n"))
6960 org-emphasis-alist)
6961 "\\|") "\\)"))
6962 (pos (point))
6963 (pre nil) (post nil)
6964 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6965 (cond
6966 ;; First check if there are any special
6967 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6968 ;; Now try the builtin stuff
6969 ((save-excursion
6970 (goto-char (point-min))
6971 (and
6972 (re-search-forward
6973 (concat "<<" (regexp-quote s0) ">>") nil t)
6974 (setq type 'dedicated
6975 pos (match-beginning 0))))
6976 ;; There is an exact target for this
6977 (goto-char pos))
6978 ((string-match "^/\\(.*\\)/$" s)
6979 ;; A regular expression
6980 (cond
6981 ((org-mode-p)
6982 (org-occur (match-string 1 s)))
6983 ;;((eq major-mode 'dired-mode)
6984 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6985 (t (org-do-occur (match-string 1 s)))))
6987 ;; A normal search strings
6988 (when (equal (string-to-char s) ?*)
6989 ;; Anchor on headlines, post may include tags.
6990 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6991 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6992 s (substring s 1)))
6993 (remove-text-properties
6994 0 (length s)
6995 '(face nil mouse-face nil keymap nil fontified nil) s)
6996 ;; Make a series of regular expressions to find a match
6997 (setq words (org-split-string s "[ \n\r\t]+")
6999 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7000 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7001 "\\)" markers)
7002 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7003 re2a (concat "[ \t\r\n]" re2a_)
7004 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7005 re4 (concat "[^a-zA-Z_]" re4_)
7007 re1 (concat pre re2 post)
7008 re3 (concat pre (if pre re4_ re4) post)
7009 re5 (concat pre ".*" re4)
7010 re2 (concat pre re2)
7011 re2a (concat pre (if pre re2a_ re2a))
7012 re4 (concat pre (if pre re4_ re4))
7013 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7014 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7015 re5 "\\)"
7017 (cond
7018 ((eq type 'org-occur) (org-occur reall))
7019 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7020 (t (goto-char (point-min))
7021 (setq type 'fuzzy)
7022 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7023 (org-search-not-self 1 re1 nil t)
7024 (org-search-not-self 1 re2 nil t)
7025 (org-search-not-self 1 re2a nil t)
7026 (org-search-not-self 1 re3 nil t)
7027 (org-search-not-self 1 re4 nil t)
7028 (org-search-not-self 1 re5 nil t)
7030 (goto-char (match-beginning 1))
7031 (goto-char pos)
7032 (error "No match")))))
7034 ;; Normal string-search
7035 (goto-char (point-min))
7036 (if (search-forward s nil t)
7037 (goto-char (match-beginning 0))
7038 (error "No match"))))
7039 (and (org-mode-p) (org-show-context 'link-search))
7040 type))
7042 (defun org-search-not-self (group &rest args)
7043 "Execute `re-search-forward', but only accept matches that do not
7044 enclose the position of `org-open-link-marker'."
7045 (let ((m org-open-link-marker))
7046 (catch 'exit
7047 (while (apply 're-search-forward args)
7048 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7049 (goto-char (match-end group))
7050 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7051 (> (match-beginning 0) (marker-position m))
7052 (< (match-end 0) (marker-position m)))
7053 (save-match-data
7054 (or (not (org-in-regexp
7055 org-bracket-link-analytic-regexp 1))
7056 (not (match-end 4)) ; no description
7057 (and (<= (match-beginning 4) (point))
7058 (>= (match-end 4) (point))))))
7059 (throw 'exit (point))))))))
7061 (defun org-get-buffer-for-internal-link (buffer)
7062 "Return a buffer to be used for displaying the link target of internal links."
7063 (cond
7064 ((not org-display-internal-link-with-indirect-buffer)
7065 buffer)
7066 ((string-match "(Clone)$" (buffer-name buffer))
7067 (message "Buffer is already a clone, not making another one")
7068 ;; we also do not modify visibility in this case
7069 buffer)
7070 (t ; make a new indirect buffer for displaying the link
7071 (let* ((bn (buffer-name buffer))
7072 (ibn (concat bn "(Clone)"))
7073 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7074 (with-current-buffer ib (org-overview))
7075 ib))))
7077 (defun org-do-occur (regexp &optional cleanup)
7078 "Call the Emacs command `occur'.
7079 If CLEANUP is non-nil, remove the printout of the regular expression
7080 in the *Occur* buffer. This is useful if the regex is long and not useful
7081 to read."
7082 (occur regexp)
7083 (when cleanup
7084 (let ((cwin (selected-window)) win beg end)
7085 (when (setq win (get-buffer-window "*Occur*"))
7086 (select-window win))
7087 (goto-char (point-min))
7088 (when (re-search-forward "match[a-z]+" nil t)
7089 (setq beg (match-end 0))
7090 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7091 (setq end (1- (match-beginning 0)))))
7092 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7093 (goto-char (point-min))
7094 (select-window cwin))))
7096 ;;; The mark ring for links jumps
7098 (defvar org-mark-ring nil
7099 "Mark ring for positions before jumps in Org-mode.")
7100 (defvar org-mark-ring-last-goto nil
7101 "Last position in the mark ring used to go back.")
7102 ;; Fill and close the ring
7103 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7104 (loop for i from 1 to org-mark-ring-length do
7105 (push (make-marker) org-mark-ring))
7106 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7107 org-mark-ring)
7109 (defun org-mark-ring-push (&optional pos buffer)
7110 "Put the current position or POS into the mark ring and rotate it."
7111 (interactive)
7112 (setq pos (or pos (point)))
7113 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7114 (move-marker (car org-mark-ring)
7115 (or pos (point))
7116 (or buffer (current-buffer)))
7117 (message "%s"
7118 (substitute-command-keys
7119 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7121 (defun org-mark-ring-goto (&optional n)
7122 "Jump to the previous position in the mark ring.
7123 With prefix arg N, jump back that many stored positions. When
7124 called several times in succession, walk through the entire ring.
7125 Org-mode commands jumping to a different position in the current file,
7126 or to another Org-mode file, automatically push the old position
7127 onto the ring."
7128 (interactive "p")
7129 (let (p m)
7130 (if (eq last-command this-command)
7131 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7132 (setq p org-mark-ring))
7133 (setq org-mark-ring-last-goto p)
7134 (setq m (car p))
7135 (switch-to-buffer (marker-buffer m))
7136 (goto-char m)
7137 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7139 (defun org-remove-angle-brackets (s)
7140 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7141 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7143 (defun org-add-angle-brackets (s)
7144 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7145 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7148 ;;; Following specific links
7150 (defun org-follow-timestamp-link ()
7151 (cond
7152 ((org-at-date-range-p t)
7153 (let ((org-agenda-start-on-weekday)
7154 (t1 (match-string 1))
7155 (t2 (match-string 2)))
7156 (setq t1 (time-to-days (org-time-string-to-time t1))
7157 t2 (time-to-days (org-time-string-to-time t2)))
7158 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7159 ((org-at-timestamp-p t)
7160 (org-agenda-list nil (time-to-days (org-time-string-to-time
7161 (substring (match-string 1) 0 10)))
7163 (t (error "This should not happen"))))
7166 ;;; Following file links
7167 (defvar org-wait nil)
7168 (defun org-open-file (path &optional in-emacs line search)
7169 "Open the file at PATH.
7170 First, this expands any special file name abbreviations. Then the
7171 configuration variable `org-file-apps' is checked if it contains an
7172 entry for this file type, and if yes, the corresponding command is launched.
7173 If no application is found, Emacs simply visits the file.
7174 With optional argument IN-EMACS, Emacs will visit the file.
7175 Optional LINE specifies a line to go to, optional SEARCH a string to
7176 search for. If LINE or SEARCH is given, the file will always be
7177 opened in Emacs.
7178 If the file does not exist, an error is thrown."
7179 (setq in-emacs (or in-emacs line search))
7180 (let* ((file (if (equal path "")
7181 buffer-file-name
7182 (substitute-in-file-name (expand-file-name path))))
7183 (apps (append org-file-apps (org-default-apps)))
7184 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7185 (dirp (if remp nil (file-directory-p file)))
7186 (dfile (downcase file))
7187 (old-buffer (current-buffer))
7188 (old-pos (point))
7189 (old-mode major-mode)
7190 ext cmd)
7191 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7192 (setq ext (match-string 1 dfile))
7193 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7194 (setq ext (match-string 1 dfile))))
7195 (if in-emacs
7196 (setq cmd 'emacs)
7197 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7198 (and dirp (cdr (assoc 'directory apps)))
7199 (cdr (assoc ext apps))
7200 (cdr (assoc t apps)))))
7201 (when (eq cmd 'mailcap)
7202 (require 'mailcap)
7203 (mailcap-parse-mailcaps)
7204 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7205 (command (mailcap-mime-info mime-type)))
7206 (if (stringp command)
7207 (setq cmd command)
7208 (setq cmd 'emacs))))
7209 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7210 (not (file-exists-p file))
7211 (not org-open-non-existing-files))
7212 (error "No such file: %s" file))
7213 (cond
7214 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7215 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7216 (while (string-match "['\"]%s['\"]" cmd)
7217 (setq cmd (replace-match "%s" t t cmd)))
7218 (while (string-match "%s" cmd)
7219 (setq cmd (replace-match
7220 (save-match-data (shell-quote-argument file))
7221 t t cmd)))
7222 (save-window-excursion
7223 (start-process-shell-command cmd nil cmd)
7224 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7226 ((or (stringp cmd)
7227 (eq cmd 'emacs))
7228 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7229 (widen)
7230 (if line (goto-line line)
7231 (if search (org-link-search search))))
7232 ((consp cmd)
7233 (eval cmd))
7234 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7235 (and (org-mode-p) (eq old-mode 'org-mode)
7236 (or (not (equal old-buffer (current-buffer)))
7237 (not (equal old-pos (point))))
7238 (org-mark-ring-push old-pos old-buffer))))
7240 (defun org-default-apps ()
7241 "Return the default applications for this operating system."
7242 (cond
7243 ((eq system-type 'darwin)
7244 org-file-apps-defaults-macosx)
7245 ((eq system-type 'windows-nt)
7246 org-file-apps-defaults-windowsnt)
7247 (t org-file-apps-defaults-gnu)))
7249 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7250 (defun org-file-remote-p (file)
7251 "Test whether FILE specifies a location on a remote system.
7252 Return non-nil if the location is indeed remote.
7254 For example, the filename \"/user@host:/foo\" specifies a location
7255 on the system \"/user@host:\"."
7256 (cond ((fboundp 'file-remote-p)
7257 (file-remote-p file))
7258 ((fboundp 'tramp-handle-file-remote-p)
7259 (tramp-handle-file-remote-p file))
7260 ((and (boundp 'ange-ftp-name-format)
7261 (string-match (car ange-ftp-name-format) file))
7263 (t nil)))
7266 ;;;; Refiling
7268 (defun org-get-org-file ()
7269 "Read a filename, with default directory `org-directory'."
7270 (let ((default (or org-default-notes-file remember-data-file)))
7271 (read-file-name (format "File name [%s]: " default)
7272 (file-name-as-directory org-directory)
7273 default)))
7275 (defun org-notes-order-reversed-p ()
7276 "Check if the current file should receive notes in reversed order."
7277 (cond
7278 ((not org-reverse-note-order) nil)
7279 ((eq t org-reverse-note-order) t)
7280 ((not (listp org-reverse-note-order)) nil)
7281 (t (catch 'exit
7282 (let ((all org-reverse-note-order)
7283 entry)
7284 (while (setq entry (pop all))
7285 (if (string-match (car entry) buffer-file-name)
7286 (throw 'exit (cdr entry))))
7287 nil)))))
7289 (defvar org-refile-target-table nil
7290 "The list of refile targets, created by `org-refile'.")
7292 (defvar org-agenda-new-buffers nil
7293 "Buffers created to visit agenda files.")
7295 (defun org-get-refile-targets (&optional default-buffer)
7296 "Produce a table with refile targets."
7297 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7298 targets txt re files f desc descre)
7299 (with-current-buffer (or default-buffer (current-buffer))
7300 (while (setq entry (pop entries))
7301 (setq files (car entry) desc (cdr entry))
7302 (cond
7303 ((null files) (setq files (list (current-buffer))))
7304 ((eq files 'org-agenda-files)
7305 (setq files (org-agenda-files 'unrestricted)))
7306 ((and (symbolp files) (fboundp files))
7307 (setq files (funcall files)))
7308 ((and (symbolp files) (boundp files))
7309 (setq files (symbol-value files))))
7310 (if (stringp files) (setq files (list files)))
7311 (cond
7312 ((eq (car desc) :tag)
7313 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7314 ((eq (car desc) :todo)
7315 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7316 ((eq (car desc) :regexp)
7317 (setq descre (cdr desc)))
7318 ((eq (car desc) :level)
7319 (setq descre (concat "^\\*\\{" (number-to-string
7320 (if org-odd-levels-only
7321 (1- (* 2 (cdr desc)))
7322 (cdr desc)))
7323 "\\}[ \t]")))
7324 ((eq (car desc) :maxlevel)
7325 (setq descre (concat "^\\*\\{1," (number-to-string
7326 (if org-odd-levels-only
7327 (1- (* 2 (cdr desc)))
7328 (cdr desc)))
7329 "\\}[ \t]")))
7330 (t (error "Bad refiling target description %s" desc)))
7331 (while (setq f (pop files))
7332 (save-excursion
7333 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7334 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7335 (save-excursion
7336 (save-restriction
7337 (widen)
7338 (goto-char (point-min))
7339 (while (re-search-forward descre nil t)
7340 (goto-char (point-at-bol))
7341 (when (looking-at org-complex-heading-regexp)
7342 (setq txt (match-string 4)
7343 re (concat "^" (regexp-quote
7344 (buffer-substring (match-beginning 1)
7345 (match-end 4)))))
7346 (if (match-end 5) (setq re (concat re "[ \t]+"
7347 (regexp-quote
7348 (match-string 5)))))
7349 (setq re (concat re "[ \t]*$"))
7350 (when org-refile-use-outline-path
7351 (setq txt (mapconcat 'identity
7352 (append
7353 (if (eq org-refile-use-outline-path 'file)
7354 (list (file-name-nondirectory
7355 (buffer-file-name (buffer-base-buffer))))
7356 (if (eq org-refile-use-outline-path 'full-file-path)
7357 (list (buffer-file-name (buffer-base-buffer)))))
7358 (org-get-outline-path)
7359 (list txt))
7360 "/")))
7361 (push (list txt f re (point)) targets))
7362 (goto-char (point-at-eol))))))))
7363 (nreverse targets))))
7365 (defun org-get-outline-path ()
7366 "Return the outline path to the current entry, as a list."
7367 (let (rtn)
7368 (save-excursion
7369 (while (org-up-heading-safe)
7370 (when (looking-at org-complex-heading-regexp)
7371 (push (org-match-string-no-properties 4) rtn)))
7372 rtn)))
7374 (defvar org-refile-history nil
7375 "History for refiling operations.")
7377 (defun org-refile (&optional goto default-buffer)
7378 "Move the entry at point to another heading.
7379 The list of target headings is compiled using the information in
7380 `org-refile-targets', which see. This list is created before each use
7381 and will therefore always be up-to-date.
7383 At the target location, the entry is filed as a subitem of the target heading.
7384 Depending on `org-reverse-note-order', the new subitem will either be the
7385 first of the last subitem.
7387 With prefix arg GOTO, the command will only visit the target location,
7388 not actually move anything.
7389 With a double prefix `C-c C-c', go to the location where the last refiling
7390 operation has put the subtree."
7391 (interactive "P")
7392 (let* ((cbuf (current-buffer))
7393 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7394 pos it nbuf file re level reversed)
7395 (if (equal goto '(16))
7396 (org-refile-goto-last-stored)
7397 (when (setq it (org-refile-get-location
7398 (if goto "Goto: " "Refile to: ") default-buffer))
7399 (setq file (nth 1 it)
7400 re (nth 2 it)
7401 pos (nth 3 it))
7402 (setq nbuf (or (find-buffer-visiting file)
7403 (find-file-noselect file)))
7404 (if goto
7405 (progn
7406 (switch-to-buffer nbuf)
7407 (goto-char pos)
7408 (org-show-context 'org-goto))
7409 (org-copy-subtree 1 nil t)
7410 (save-excursion
7411 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7412 (find-file-noselect file))))
7413 (setq reversed (org-notes-order-reversed-p))
7414 (save-excursion
7415 (save-restriction
7416 (widen)
7417 (goto-char pos)
7418 (looking-at outline-regexp)
7419 (setq level (org-get-valid-level (funcall outline-level) 1))
7420 (goto-char
7421 (if reversed
7422 (outline-next-heading)
7423 (or (save-excursion (outline-get-next-sibling))
7424 (org-end-of-subtree t t)
7425 (point-max))))
7426 (bookmark-set "org-refile-last-stored")
7427 (org-paste-subtree level))))
7428 (org-cut-subtree)
7429 (setq org-markers-to-move nil)
7430 (message "Entry refiled to \"%s\"" (car it)))))))
7432 (defun org-refile-goto-last-stored ()
7433 "Go to the location where the last refile was stored."
7434 (interactive)
7435 (bookmark-jump "org-refile-last-stored")
7436 (message "This is the location of the last refile"))
7438 (defun org-refile-get-location (&optional prompt default-buffer)
7439 "Prompt the user for a refile location, using PROMPT."
7440 (let ((org-refile-targets org-refile-targets)
7441 (org-refile-use-outline-path org-refile-use-outline-path))
7442 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7443 (unless org-refile-target-table
7444 (error "No refile targets"))
7445 (let* ((cbuf (current-buffer))
7446 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7447 (fname (and filename (file-truename filename)))
7448 (tbl (mapcar
7449 (lambda (x)
7450 (if (not (equal fname (file-truename (nth 1 x))))
7451 (cons (concat (car x) " (" (file-name-nondirectory
7452 (nth 1 x)) ")")
7453 (cdr x))
7455 org-refile-target-table))
7456 (completion-ignore-case t))
7457 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7458 tbl)))
7460 ;;;; Dynamic blocks
7462 (defun org-find-dblock (name)
7463 "Find the first dynamic block with name NAME in the buffer.
7464 If not found, stay at current position and return nil."
7465 (let (pos)
7466 (save-excursion
7467 (goto-char (point-min))
7468 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7469 nil t)
7470 (match-beginning 0))))
7471 (if pos (goto-char pos))
7472 pos))
7474 (defconst org-dblock-start-re
7475 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7476 "Matches the startline of a dynamic block, with parameters.")
7478 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7479 "Matches the end of a dyhamic block.")
7481 (defun org-create-dblock (plist)
7482 "Create a dynamic block section, with parameters taken from PLIST.
7483 PLIST must containe a :name entry which is used as name of the block."
7484 (unless (bolp) (newline))
7485 (let ((name (plist-get plist :name)))
7486 (insert "#+BEGIN: " name)
7487 (while plist
7488 (if (eq (car plist) :name)
7489 (setq plist (cddr plist))
7490 (insert " " (prin1-to-string (pop plist)))))
7491 (insert "\n\n#+END:\n")
7492 (beginning-of-line -2)))
7494 (defun org-prepare-dblock ()
7495 "Prepare dynamic block for refresh.
7496 This empties the block, puts the cursor at the insert position and returns
7497 the property list including an extra property :name with the block name."
7498 (unless (looking-at org-dblock-start-re)
7499 (error "Not at a dynamic block"))
7500 (let* ((begdel (1+ (match-end 0)))
7501 (name (org-no-properties (match-string 1)))
7502 (params (append (list :name name)
7503 (read (concat "(" (match-string 3) ")")))))
7504 (unless (re-search-forward org-dblock-end-re nil t)
7505 (error "Dynamic block not terminated"))
7506 (setq params
7507 (append params
7508 (list :content (buffer-substring
7509 begdel (match-beginning 0)))))
7510 (delete-region begdel (match-beginning 0))
7511 (goto-char begdel)
7512 (open-line 1)
7513 params))
7515 (defun org-map-dblocks (&optional command)
7516 "Apply COMMAND to all dynamic blocks in the current buffer.
7517 If COMMAND is not given, use `org-update-dblock'."
7518 (let ((cmd (or command 'org-update-dblock))
7519 pos)
7520 (save-excursion
7521 (goto-char (point-min))
7522 (while (re-search-forward org-dblock-start-re nil t)
7523 (goto-char (setq pos (match-beginning 0)))
7524 (condition-case nil
7525 (funcall cmd)
7526 (error (message "Error during update of dynamic block")))
7527 (goto-char pos)
7528 (unless (re-search-forward org-dblock-end-re nil t)
7529 (error "Dynamic block not terminated"))))))
7531 (defun org-dblock-update (&optional arg)
7532 "User command for updating dynamic blocks.
7533 Update the dynamic block at point. With prefix ARG, update all dynamic
7534 blocks in the buffer."
7535 (interactive "P")
7536 (if arg
7537 (org-update-all-dblocks)
7538 (or (looking-at org-dblock-start-re)
7539 (org-beginning-of-dblock))
7540 (org-update-dblock)))
7542 (defun org-update-dblock ()
7543 "Update the dynamic block at point
7544 This means to empty the block, parse for parameters and then call
7545 the correct writing function."
7546 (save-window-excursion
7547 (let* ((pos (point))
7548 (line (org-current-line))
7549 (params (org-prepare-dblock))
7550 (name (plist-get params :name))
7551 (cmd (intern (concat "org-dblock-write:" name))))
7552 (message "Updating dynamic block `%s' at line %d..." name line)
7553 (funcall cmd params)
7554 (message "Updating dynamic block `%s' at line %d...done" name line)
7555 (goto-char pos))))
7557 (defun org-beginning-of-dblock ()
7558 "Find the beginning of the dynamic block at point.
7559 Error if there is no scuh block at point."
7560 (let ((pos (point))
7561 beg)
7562 (end-of-line 1)
7563 (if (and (re-search-backward org-dblock-start-re nil t)
7564 (setq beg (match-beginning 0))
7565 (re-search-forward org-dblock-end-re nil t)
7566 (> (match-end 0) pos))
7567 (goto-char beg)
7568 (goto-char pos)
7569 (error "Not in a dynamic block"))))
7571 (defun org-update-all-dblocks ()
7572 "Update all dynamic blocks in the buffer.
7573 This function can be used in a hook."
7574 (when (org-mode-p)
7575 (org-map-dblocks 'org-update-dblock)))
7578 ;;;; Completion
7580 (defconst org-additional-option-like-keywords
7581 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7582 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7583 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7585 (defun org-complete (&optional arg)
7586 "Perform completion on word at point.
7587 At the beginning of a headline, this completes TODO keywords as given in
7588 `org-todo-keywords'.
7589 If the current word is preceded by a backslash, completes the TeX symbols
7590 that are supported for HTML support.
7591 If the current word is preceded by \"#+\", completes special words for
7592 setting file options.
7593 In the line after \"#+STARTUP:, complete valid keywords.\"
7594 At all other locations, this simply calls the value of
7595 `org-completion-fallback-command'."
7596 (interactive "P")
7597 (org-without-partial-completion
7598 (catch 'exit
7599 (let* ((end (point))
7600 (beg1 (save-excursion
7601 (skip-chars-backward (org-re "[:alnum:]_@"))
7602 (point)))
7603 (beg (save-excursion
7604 (skip-chars-backward "a-zA-Z0-9_:$")
7605 (point)))
7606 (confirm (lambda (x) (stringp (car x))))
7607 (searchhead (equal (char-before beg) ?*))
7608 (tag (and (equal (char-before beg1) ?:)
7609 (equal (char-after (point-at-bol)) ?*)))
7610 (prop (and (equal (char-before beg1) ?:)
7611 (not (equal (char-after (point-at-bol)) ?*))))
7612 (texp (equal (char-before beg) ?\\))
7613 (link (equal (char-before beg) ?\[))
7614 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7615 beg)
7616 "#+"))
7617 (startup (string-match "^#\\+STARTUP:.*"
7618 (buffer-substring (point-at-bol) (point))))
7619 (completion-ignore-case opt)
7620 (type nil)
7621 (tbl nil)
7622 (table (cond
7623 (opt
7624 (setq type :opt)
7625 (require 'org-exp)
7626 (append
7627 (mapcar
7628 (lambda (x)
7629 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7630 (cons (match-string 2 x) (match-string 1 x)))
7631 (org-split-string (org-get-current-options) "\n"))
7632 (mapcar 'list org-additional-option-like-keywords)))
7633 (startup
7634 (setq type :startup)
7635 org-startup-options)
7636 (link (append org-link-abbrev-alist-local
7637 org-link-abbrev-alist))
7638 (texp
7639 (setq type :tex)
7640 org-html-entities)
7641 ((string-match "\\`\\*+[ \t]+\\'"
7642 (buffer-substring (point-at-bol) beg))
7643 (setq type :todo)
7644 (mapcar 'list org-todo-keywords-1))
7645 (searchhead
7646 (setq type :searchhead)
7647 (save-excursion
7648 (goto-char (point-min))
7649 (while (re-search-forward org-todo-line-regexp nil t)
7650 (push (list
7651 (org-make-org-heading-search-string
7652 (match-string 3) t))
7653 tbl)))
7654 tbl)
7655 (tag (setq type :tag beg beg1)
7656 (or org-tag-alist (org-get-buffer-tags)))
7657 (prop (setq type :prop beg beg1)
7658 (mapcar 'list (org-buffer-property-keys nil t t)))
7659 (t (progn
7660 (call-interactively org-completion-fallback-command)
7661 (throw 'exit nil)))))
7662 (pattern (buffer-substring-no-properties beg end))
7663 (completion (try-completion pattern table confirm)))
7664 (cond ((eq completion t)
7665 (if (not (assoc (upcase pattern) table))
7666 (message "Already complete")
7667 (if (and (equal type :opt)
7668 (not (member (car (assoc (upcase pattern) table))
7669 org-additional-option-like-keywords)))
7670 (insert (substring (cdr (assoc (upcase pattern) table))
7671 (length pattern)))
7672 (if (memq type '(:tag :prop)) (insert ":")))))
7673 ((null completion)
7674 (message "Can't find completion for \"%s\"" pattern)
7675 (ding))
7676 ((not (string= pattern completion))
7677 (delete-region beg end)
7678 (if (string-match " +$" completion)
7679 (setq completion (replace-match "" t t completion)))
7680 (insert completion)
7681 (if (get-buffer-window "*Completions*")
7682 (delete-window (get-buffer-window "*Completions*")))
7683 (if (assoc completion table)
7684 (if (eq type :todo) (insert " ")
7685 (if (memq type '(:tag :prop)) (insert ":"))))
7686 (if (and (equal type :opt) (assoc completion table))
7687 (message "%s" (substitute-command-keys
7688 "Press \\[org-complete] again to insert example settings"))))
7690 (message "Making completion list...")
7691 (let ((list (sort (all-completions pattern table confirm)
7692 'string<)))
7693 (with-output-to-temp-buffer "*Completions*"
7694 (condition-case nil
7695 ;; Protection needed for XEmacs and emacs 21
7696 (display-completion-list list pattern)
7697 (error (display-completion-list list)))))
7698 (message "Making completion list...%s" "done")))))))
7700 ;;;; TODO, DEADLINE, Comments
7702 (defun org-toggle-comment ()
7703 "Change the COMMENT state of an entry."
7704 (interactive)
7705 (save-excursion
7706 (org-back-to-heading)
7707 (let (case-fold-search)
7708 (if (looking-at (concat outline-regexp
7709 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7710 (replace-match "" t t nil 1)
7711 (if (looking-at outline-regexp)
7712 (progn
7713 (goto-char (match-end 0))
7714 (insert org-comment-string " ")))))))
7716 (defvar org-last-todo-state-is-todo nil
7717 "This is non-nil when the last TODO state change led to a TODO state.
7718 If the last change removed the TODO tag or switched to DONE, then
7719 this is nil.")
7721 (defvar org-setting-tags nil) ; dynamically skiped
7723 (defun org-parse-local-options (string var)
7724 "Parse STRING for startup setting relevant for variable VAR."
7725 (let ((rtn (symbol-value var))
7726 e opts)
7727 (save-match-data
7728 (if (or (not string) (not (string-match "\\S-" string)))
7730 (setq opts (delq nil (mapcar (lambda (x)
7731 (setq e (assoc x org-startup-options))
7732 (if (eq (nth 1 e) var) e nil))
7733 (org-split-string string "[ \t]+"))))
7734 (if (not opts)
7736 (setq rtn nil)
7737 (while (setq e (pop opts))
7738 (if (not (nth 3 e))
7739 (setq rtn (nth 2 e))
7740 (if (not (listp rtn)) (setq rtn nil))
7741 (push (nth 2 e) rtn)))
7742 rtn)))))
7744 (defvar org-blocker-hook nil
7745 "Hook for functions that are allowed to block a state change.
7747 Each function gets as its single argument a property list, see
7748 `org-trigger-hook' for more information about this list.
7750 If any of the functions in this hook returns nil, the state change
7751 is blocked.")
7753 (defvar org-trigger-hook nil
7754 "Hook for functions that are triggered by a state change.
7756 Each function gets as its single argument a property list with at least
7757 the following elements:
7759 (:type type-of-change :position pos-at-entry-start
7760 :from old-state :to new-state)
7762 Depending on the type, more properties may be present.
7764 This mechanism is currently implemented for:
7766 TODO state changes
7767 ------------------
7768 :type todo-state-change
7769 :from previous state (keyword as a string), or nil
7770 :to new state (keyword as a string), or nil")
7773 (defun org-todo (&optional arg)
7774 "Change the TODO state of an item.
7775 The state of an item is given by a keyword at the start of the heading,
7776 like
7777 *** TODO Write paper
7778 *** DONE Call mom
7780 The different keywords are specified in the variable `org-todo-keywords'.
7781 By default the available states are \"TODO\" and \"DONE\".
7782 So for this example: when the item starts with TODO, it is changed to DONE.
7783 When it starts with DONE, the DONE is removed. And when neither TODO nor
7784 DONE are present, add TODO at the beginning of the heading.
7786 With C-u prefix arg, use completion to determine the new state.
7787 With numeric prefix arg, switch to that state.
7789 For calling through lisp, arg is also interpreted in the following way:
7790 'none -> empty state
7791 \"\"(empty string) -> switch to empty state
7792 'done -> switch to DONE
7793 'nextset -> switch to the next set of keywords
7794 'previousset -> switch to the previous set of keywords
7795 \"WAITING\" -> switch to the specified keyword, but only if it
7796 really is a member of `org-todo-keywords'."
7797 (interactive "P")
7798 (save-excursion
7799 (catch 'exit
7800 (org-back-to-heading)
7801 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7802 (or (looking-at (concat " +" org-todo-regexp " *"))
7803 (looking-at " *"))
7804 (let* ((match-data (match-data))
7805 (startpos (point-at-bol))
7806 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7807 (org-log-done org-log-done)
7808 (org-log-repeat org-log-repeat)
7809 (org-todo-log-states org-todo-log-states)
7810 (this (match-string 1))
7811 (hl-pos (match-beginning 0))
7812 (head (org-get-todo-sequence-head this))
7813 (ass (assoc head org-todo-kwd-alist))
7814 (interpret (nth 1 ass))
7815 (done-word (nth 3 ass))
7816 (final-done-word (nth 4 ass))
7817 (last-state (or this ""))
7818 (completion-ignore-case t)
7819 (member (member this org-todo-keywords-1))
7820 (tail (cdr member))
7821 (state (cond
7822 ((and org-todo-key-trigger
7823 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7824 (and (not arg) org-use-fast-todo-selection
7825 (not (eq org-use-fast-todo-selection 'prefix)))))
7826 ;; Use fast selection
7827 (org-fast-todo-selection))
7828 ((and (equal arg '(4))
7829 (or (not org-use-fast-todo-selection)
7830 (not org-todo-key-trigger)))
7831 ;; Read a state with completion
7832 (completing-read "State: " (mapcar (lambda(x) (list x))
7833 org-todo-keywords-1)
7834 nil t))
7835 ((eq arg 'right)
7836 (if this
7837 (if tail (car tail) nil)
7838 (car org-todo-keywords-1)))
7839 ((eq arg 'left)
7840 (if (equal member org-todo-keywords-1)
7842 (if this
7843 (nth (- (length org-todo-keywords-1) (length tail) 2)
7844 org-todo-keywords-1)
7845 (org-last org-todo-keywords-1))))
7846 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7847 (setq arg nil))) ; hack to fall back to cycling
7848 (arg
7849 ;; user or caller requests a specific state
7850 (cond
7851 ((equal arg "") nil)
7852 ((eq arg 'none) nil)
7853 ((eq arg 'done) (or done-word (car org-done-keywords)))
7854 ((eq arg 'nextset)
7855 (or (car (cdr (member head org-todo-heads)))
7856 (car org-todo-heads)))
7857 ((eq arg 'previousset)
7858 (let ((org-todo-heads (reverse org-todo-heads)))
7859 (or (car (cdr (member head org-todo-heads)))
7860 (car org-todo-heads))))
7861 ((car (member arg org-todo-keywords-1)))
7862 ((nth (1- (prefix-numeric-value arg))
7863 org-todo-keywords-1))))
7864 ((null member) (or head (car org-todo-keywords-1)))
7865 ((equal this final-done-word) nil) ;; -> make empty
7866 ((null tail) nil) ;; -> first entry
7867 ((eq interpret 'sequence)
7868 (car tail))
7869 ((memq interpret '(type priority))
7870 (if (eq this-command last-command)
7871 (car tail)
7872 (if (> (length tail) 0)
7873 (or done-word (car org-done-keywords))
7874 nil)))
7875 (t nil)))
7876 (next (if state (concat " " state " ") " "))
7877 (change-plist (list :type 'todo-state-change :from this :to state
7878 :position startpos))
7879 dolog now-done-p)
7880 (when org-blocker-hook
7881 (unless (save-excursion
7882 (save-match-data
7883 (run-hook-with-args-until-failure
7884 'org-blocker-hook change-plist)))
7885 (if (interactive-p)
7886 (error "TODO state change from %s to %s blocked" this state)
7887 ;; fail silently
7888 (message "TODO state change from %s to %s blocked" this state)
7889 (throw 'exit nil))))
7890 (store-match-data match-data)
7891 (replace-match next t t)
7892 (unless (pos-visible-in-window-p hl-pos)
7893 (message "TODO state changed to %s" (org-trim next)))
7894 (unless head
7895 (setq head (org-get-todo-sequence-head state)
7896 ass (assoc head org-todo-kwd-alist)
7897 interpret (nth 1 ass)
7898 done-word (nth 3 ass)
7899 final-done-word (nth 4 ass)))
7900 (when (memq arg '(nextset previousset))
7901 (message "Keyword-Set %d/%d: %s"
7902 (- (length org-todo-sets) -1
7903 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7904 (length org-todo-sets)
7905 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7906 (setq org-last-todo-state-is-todo
7907 (not (member state org-done-keywords)))
7908 (setq now-done-p (and (member state org-done-keywords)
7909 (not (member this org-done-keywords))))
7910 (and logging (org-local-logging logging))
7911 (when (and (or org-todo-log-states org-log-done)
7912 (not (memq arg '(nextset previousset))))
7913 ;; we need to look at recording a time and note
7914 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7915 (nth 2 (assoc this org-todo-log-states))))
7916 (when (and state
7917 (member state org-not-done-keywords)
7918 (not (member this org-not-done-keywords)))
7919 ;; This is now a todo state and was not one before
7920 ;; If there was a CLOSED time stamp, get rid of it.
7921 (org-add-planning-info nil nil 'closed))
7922 (when (and now-done-p org-log-done)
7923 ;; It is now done, and it was not done before
7924 (org-add-planning-info 'closed (org-current-time))
7925 (if (and (not dolog) (eq 'note org-log-done))
7926 (org-add-log-setup 'done state 'findpos 'note)))
7927 (when (and state dolog)
7928 ;; This is a non-nil state, and we need to log it
7929 (org-add-log-setup 'state state 'findpos dolog)))
7930 ;; Fixup tag positioning
7931 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7932 (run-hooks 'org-after-todo-state-change-hook)
7933 (if (and arg (not (member state org-done-keywords)))
7934 (setq head (org-get-todo-sequence-head state)))
7935 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7936 ;; Do we need to trigger a repeat?
7937 (when now-done-p (org-auto-repeat-maybe state))
7938 ;; Fixup cursor location if close to the keyword
7939 (if (and (outline-on-heading-p)
7940 (not (bolp))
7941 (save-excursion (beginning-of-line 1)
7942 (looking-at org-todo-line-regexp))
7943 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7944 (progn
7945 (goto-char (or (match-end 2) (match-end 1)))
7946 (just-one-space)))
7947 (when org-trigger-hook
7948 (save-excursion
7949 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7951 (defun org-local-logging (value)
7952 "Get logging settings from a property VALUE."
7953 (let* (words w a)
7954 ;; directly set the variables, they are already local.
7955 (setq org-log-done nil
7956 org-log-repeat nil
7957 org-todo-log-states nil)
7958 (setq words (org-split-string value))
7959 (while (setq w (pop words))
7960 (cond
7961 ((setq a (assoc w org-startup-options))
7962 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7963 (set (nth 1 a) (nth 2 a))))
7964 ((setq a (org-extract-log-state-settings w))
7965 (and (member (car a) org-todo-keywords-1)
7966 (push a org-todo-log-states)))))))
7968 (defun org-get-todo-sequence-head (kwd)
7969 "Return the head of the TODO sequence to which KWD belongs.
7970 If KWD is not set, check if there is a text property remembering the
7971 right sequence."
7972 (let (p)
7973 (cond
7974 ((not kwd)
7975 (or (get-text-property (point-at-bol) 'org-todo-head)
7976 (progn
7977 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7978 nil (point-at-eol)))
7979 (get-text-property p 'org-todo-head))))
7980 ((not (member kwd org-todo-keywords-1))
7981 (car org-todo-keywords-1))
7982 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7984 (defun org-fast-todo-selection ()
7985 "Fast TODO keyword selection with single keys.
7986 Returns the new TODO keyword, or nil if no state change should occur."
7987 (let* ((fulltable org-todo-key-alist)
7988 (done-keywords org-done-keywords) ;; needed for the faces.
7989 (maxlen (apply 'max (mapcar
7990 (lambda (x)
7991 (if (stringp (car x)) (string-width (car x)) 0))
7992 fulltable)))
7993 (expert nil)
7994 (fwidth (+ maxlen 3 1 3))
7995 (ncol (/ (- (window-width) 4) fwidth))
7996 tg cnt e c tbl
7997 groups ingroup)
7998 (save-window-excursion
7999 (if expert
8000 (set-buffer (get-buffer-create " *Org todo*"))
8001 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8002 (erase-buffer)
8003 (org-set-local 'org-done-keywords done-keywords)
8004 (setq tbl fulltable cnt 0)
8005 (while (setq e (pop tbl))
8006 (cond
8007 ((equal e '(:startgroup))
8008 (push '() groups) (setq ingroup t)
8009 (when (not (= cnt 0))
8010 (setq cnt 0)
8011 (insert "\n"))
8012 (insert "{ "))
8013 ((equal e '(:endgroup))
8014 (setq ingroup nil cnt 0)
8015 (insert "}\n"))
8017 (setq tg (car e) c (cdr e))
8018 (if ingroup (push tg (car groups)))
8019 (setq tg (org-add-props tg nil 'face
8020 (org-get-todo-face tg)))
8021 (if (and (= cnt 0) (not ingroup)) (insert " "))
8022 (insert "[" c "] " tg (make-string
8023 (- fwidth 4 (length tg)) ?\ ))
8024 (when (= (setq cnt (1+ cnt)) ncol)
8025 (insert "\n")
8026 (if ingroup (insert " "))
8027 (setq cnt 0)))))
8028 (insert "\n")
8029 (goto-char (point-min))
8030 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8031 (fit-window-to-buffer))
8032 (message "[a-z..]:Set [SPC]:clear")
8033 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8034 (cond
8035 ((or (= c ?\C-g)
8036 (and (= c ?q) (not (rassoc c fulltable))))
8037 (setq quit-flag t))
8038 ((= c ?\ ) nil)
8039 ((setq e (rassoc c fulltable) tg (car e))
8041 (t (setq quit-flag t))))))
8043 (defun org-entry-is-todo-p ()
8044 (member (org-get-todo-state) org-not-done-keywords))
8046 (defun org-entry-is-done-p ()
8047 (member (org-get-todo-state) org-done-keywords))
8049 (defun org-get-todo-state ()
8050 (save-excursion
8051 (org-back-to-heading t)
8052 (and (looking-at org-todo-line-regexp)
8053 (match-end 2)
8054 (match-string 2))))
8056 (defun org-at-date-range-p (&optional inactive-ok)
8057 "Is the cursor inside a date range?"
8058 (interactive)
8059 (save-excursion
8060 (catch 'exit
8061 (let ((pos (point)))
8062 (skip-chars-backward "^[<\r\n")
8063 (skip-chars-backward "<[")
8064 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8065 (>= (match-end 0) pos)
8066 (throw 'exit t))
8067 (skip-chars-backward "^<[\r\n")
8068 (skip-chars-backward "<[")
8069 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8070 (>= (match-end 0) pos)
8071 (throw 'exit t)))
8072 nil)))
8074 (defun org-get-repeat ()
8075 "Check if tere is a deadline/schedule with repeater in this entry."
8076 (save-match-data
8077 (save-excursion
8078 (org-back-to-heading t)
8079 (if (re-search-forward
8080 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8081 (match-string 1)))))
8083 (defvar org-last-changed-timestamp)
8084 (defvar org-log-post-message)
8085 (defvar org-log-note-purpose)
8086 (defvar org-log-note-how)
8087 (defun org-auto-repeat-maybe (done-word)
8088 "Check if the current headline contains a repeated deadline/schedule.
8089 If yes, set TODO state back to what it was and change the base date
8090 of repeating deadline/scheduled time stamps to new date.
8091 This function is run automatically after each state change to a DONE state."
8092 ;; last-state is dynamically scoped into this function
8093 (let* ((repeat (org-get-repeat))
8094 (aa (assoc last-state org-todo-kwd-alist))
8095 (interpret (nth 1 aa))
8096 (head (nth 2 aa))
8097 (whata '(("d" . day) ("m" . month) ("y" . year)))
8098 (msg "Entry repeats: ")
8099 (org-log-done nil)
8100 (org-todo-log-states nil)
8101 (nshiftmax 10) (nshift 0)
8102 re type n what ts mb0 time)
8103 (when repeat
8104 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8105 (org-todo (if (eq interpret 'type) last-state head))
8106 (when org-log-repeat
8107 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8108 (memq 'org-add-log-note post-command-hook))
8109 ;; OK, we are already setup for some record
8110 (if (eq org-log-repeat 'note)
8111 ;; make sure we take a note, not only a time stamp
8112 (setq org-log-note-how 'note))
8113 ;; Set up for taking a record
8114 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8115 'findpos org-log-repeat)))
8116 (org-back-to-heading t)
8117 (org-add-planning-info nil nil 'closed)
8118 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8119 org-deadline-time-regexp "\\)\\|\\("
8120 org-ts-regexp "\\)"))
8121 (while (re-search-forward
8122 re (save-excursion (outline-next-heading) (point)) t)
8123 (setq type (if (match-end 1) org-scheduled-string
8124 (if (match-end 3) org-deadline-string "Plain:"))
8125 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8126 mb0 (match-beginning 0))
8127 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8128 (setq n (string-to-number (match-string 2 ts))
8129 what (match-string 3 ts))
8130 (if (equal what "w") (setq n (* n 7) what "d"))
8131 ;; Preparation, see if we need to modify the start date for the change
8132 (when (match-end 1)
8133 (setq time (save-match-data (org-time-string-to-time ts)))
8134 (cond
8135 ((equal (match-string 1 ts) ".")
8136 ;; Shift starting date to today
8137 (org-timestamp-change
8138 (- (time-to-days (current-time)) (time-to-days time))
8139 'day))
8140 ((equal (match-string 1 ts) "+")
8141 (while (or (= nshift 0)
8142 (<= (time-to-days time) (time-to-days (current-time))))
8143 (when (= (incf nshift) nshiftmax)
8144 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8145 (error "Abort")))
8146 (org-timestamp-change n (cdr (assoc what whata)))
8147 (org-at-timestamp-p t)
8148 (setq ts (match-string 1))
8149 (setq time (save-match-data (org-time-string-to-time ts))))
8150 (org-timestamp-change (- n) (cdr (assoc what whata)))
8151 ;; rematch, so that we have everything in place for the real shift
8152 (org-at-timestamp-p t)
8153 (setq ts (match-string 1))
8154 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8155 (org-timestamp-change n (cdr (assoc what whata)))
8156 (setq msg (concat msg type org-last-changed-timestamp " "))))
8157 (setq org-log-post-message msg)
8158 (message "%s" msg))))
8160 (defun org-show-todo-tree (arg)
8161 "Make a compact tree which shows all headlines marked with TODO.
8162 The tree will show the lines where the regexp matches, and all higher
8163 headlines above the match.
8164 With a \\[universal-argument] prefix, also show the DONE entries.
8165 With a numeric prefix N, construct a sparse tree for the Nth element
8166 of `org-todo-keywords-1'."
8167 (interactive "P")
8168 (let ((case-fold-search nil)
8169 (kwd-re
8170 (cond ((null arg) org-not-done-regexp)
8171 ((equal arg '(4))
8172 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8173 (mapcar 'list org-todo-keywords-1))))
8174 (concat "\\("
8175 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8176 "\\)\\>")))
8177 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8178 (regexp-quote (nth (1- (prefix-numeric-value arg))
8179 org-todo-keywords-1)))
8180 (t (error "Invalid prefix argument: %s" arg)))))
8181 (message "%d TODO entries found"
8182 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8184 (defun org-deadline (&optional remove)
8185 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8186 With argument REMOVE, remove any deadline from the item."
8187 (interactive "P")
8188 (if remove
8189 (progn
8190 (org-remove-timestamp-with-keyword org-deadline-string)
8191 (message "Item no longer has a deadline."))
8192 (org-add-planning-info 'deadline nil 'closed)))
8194 (defun org-schedule (&optional remove)
8195 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8196 With argument REMOVE, remove any scheduling date from the item."
8197 (interactive "P")
8198 (if remove
8199 (progn
8200 (org-remove-timestamp-with-keyword org-scheduled-string)
8201 (message "Item is no longer scheduled."))
8202 (org-add-planning-info 'scheduled nil 'closed)))
8204 (defun org-remove-timestamp-with-keyword (keyword)
8205 "Remove all time stamps with KEYWORD in the current entry."
8206 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8207 beg)
8208 (save-excursion
8209 (org-back-to-heading t)
8210 (setq beg (point))
8211 (org-end-of-subtree t t)
8212 (while (re-search-backward re beg t)
8213 (replace-match "")
8214 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8215 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8217 (defun org-add-planning-info (what &optional time &rest remove)
8218 "Insert new timestamp with keyword in the line directly after the headline.
8219 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8220 If non is given, the user is prompted for a date.
8221 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8222 be removed."
8223 (interactive)
8224 (let (org-time-was-given org-end-time-was-given ts
8225 end default-time default-input)
8227 (when (and (not time) (memq what '(scheduled deadline)))
8228 ;; Try to get a default date/time from existing timestamp
8229 (save-excursion
8230 (org-back-to-heading t)
8231 (setq end (save-excursion (outline-next-heading) (point)))
8232 (when (re-search-forward (if (eq what 'scheduled)
8233 org-scheduled-time-regexp
8234 org-deadline-time-regexp)
8235 end t)
8236 (setq ts (match-string 1)
8237 default-time
8238 (apply 'encode-time (org-parse-time-string ts))
8239 default-input (and ts (org-get-compact-tod ts))))))
8240 (when what
8241 ;; If necessary, get the time from the user
8242 (setq time (or time (org-read-date nil 'to-time nil nil
8243 default-time default-input))))
8245 (when (and org-insert-labeled-timestamps-at-point
8246 (member what '(scheduled deadline)))
8247 (insert
8248 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8249 (org-insert-time-stamp time org-time-was-given
8250 nil nil nil (list org-end-time-was-given))
8251 (setq what nil))
8252 (save-excursion
8253 (save-restriction
8254 (let (col list elt ts buffer-invisibility-spec)
8255 (org-back-to-heading t)
8256 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8257 (goto-char (match-end 1))
8258 (setq col (current-column))
8259 (goto-char (match-end 0))
8260 (if (eobp) (insert "\n") (forward-char 1))
8261 (if (and (not (looking-at outline-regexp))
8262 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8263 "[^\r\n]*"))
8264 (not (equal (match-string 1) org-clock-string)))
8265 (narrow-to-region (match-beginning 0) (match-end 0))
8266 (insert-before-markers "\n")
8267 (backward-char 1)
8268 (narrow-to-region (point) (point))
8269 (org-indent-to-column col))
8270 ;; Check if we have to remove something.
8271 (setq list (cons what remove))
8272 (while list
8273 (setq elt (pop list))
8274 (goto-char (point-min))
8275 (when (or (and (eq elt 'scheduled)
8276 (re-search-forward org-scheduled-time-regexp nil t))
8277 (and (eq elt 'deadline)
8278 (re-search-forward org-deadline-time-regexp nil t))
8279 (and (eq elt 'closed)
8280 (re-search-forward org-closed-time-regexp nil t)))
8281 (replace-match "")
8282 (if (looking-at "--+<[^>]+>") (replace-match ""))
8283 (if (looking-at " +") (replace-match ""))))
8284 (goto-char (point-max))
8285 (when what
8286 (insert
8287 (if (not (equal (char-before) ?\ )) " " "")
8288 (cond ((eq what 'scheduled) org-scheduled-string)
8289 ((eq what 'deadline) org-deadline-string)
8290 ((eq what 'closed) org-closed-string))
8291 " ")
8292 (setq ts (org-insert-time-stamp
8293 time
8294 (or org-time-was-given
8295 (and (eq what 'closed) org-log-done-with-time))
8296 (eq what 'closed)
8297 nil nil (list org-end-time-was-given)))
8298 (end-of-line 1))
8299 (goto-char (point-min))
8300 (widen)
8301 (if (and (looking-at "[ \t]+\n")
8302 (equal (char-before) ?\n))
8303 (backward-delete-char 1))
8304 ts)))))
8306 (defvar org-log-note-marker (make-marker))
8307 (defvar org-log-note-purpose nil)
8308 (defvar org-log-note-state nil)
8309 (defvar org-log-note-how nil)
8310 (defvar org-log-note-window-configuration nil)
8311 (defvar org-log-note-return-to (make-marker))
8312 (defvar org-log-post-message nil
8313 "Message to be displayed after a log note has been stored.
8314 The auto-repeater uses this.")
8316 (defun org-add-note ()
8317 "Add a note to the current entry.
8318 This is done in the same way as adding a state change note."
8319 (interactive)
8320 (org-add-log-setup 'note nil t nil))
8322 (defun org-add-log-setup (&optional purpose state findpos how)
8323 "Set up the post command hook to take a note.
8324 If this is about to TODO state change, the new state is expected in STATE.
8325 When FINDPOS is non-nil, find the correct position for the note in
8326 the current entry. If not, assume that it can be inserted at point."
8327 (save-excursion
8328 (when findpos
8329 (org-back-to-heading t)
8330 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8331 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8332 "[^\r\n]*\\)?"))
8333 (goto-char (match-end 0))
8334 (unless org-log-states-order-reversed
8335 (and (= (char-after) ?\n) (forward-char 1))
8336 (org-skip-over-state-notes)
8337 (skip-chars-backward " \t\n\r")))
8338 (move-marker org-log-note-marker (point))
8339 (setq org-log-note-purpose purpose
8340 org-log-note-state state
8341 org-log-note-how how)
8342 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8344 (defun org-skip-over-state-notes ()
8345 "Skip past the list of State notes in an entry."
8346 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8347 (while (looking-at "[ \t]*- State")
8348 (condition-case nil
8349 (org-next-item)
8350 (error (org-end-of-item)))))
8352 (defun org-add-log-note (&optional purpose)
8353 "Pop up a window for taking a note, and add this note later at point."
8354 (remove-hook 'post-command-hook 'org-add-log-note)
8355 (setq org-log-note-window-configuration (current-window-configuration))
8356 (delete-other-windows)
8357 (move-marker org-log-note-return-to (point))
8358 (switch-to-buffer (marker-buffer org-log-note-marker))
8359 (goto-char org-log-note-marker)
8360 (org-switch-to-buffer-other-window "*Org Note*")
8361 (erase-buffer)
8362 (if (memq org-log-note-how '(time state))
8363 (org-store-log-note)
8364 (let ((org-inhibit-startup t)) (org-mode))
8365 (insert (format "# Insert note for %s.
8366 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8367 (cond
8368 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8369 ((eq org-log-note-purpose 'done) "closed todo item")
8370 ((eq org-log-note-purpose 'state)
8371 (format "state change to \"%s\"" org-log-note-state))
8372 ((eq org-log-note-purpose 'note)
8373 "this entry")
8374 (t (error "This should not happen")))))
8375 (org-set-local 'org-finish-function 'org-store-log-note)))
8377 (defvar org-note-abort nil) ; dynamically scoped
8378 (defun org-store-log-note ()
8379 "Finish taking a log note, and insert it to where it belongs."
8380 (let ((txt (buffer-string))
8381 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8382 lines ind)
8383 (kill-buffer (current-buffer))
8384 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8385 (setq txt (replace-match "" t t txt)))
8386 (if (string-match "\\s-+\\'" txt)
8387 (setq txt (replace-match "" t t txt)))
8388 (setq lines (org-split-string txt "\n"))
8389 (when (and note (string-match "\\S-" note))
8390 (setq note
8391 (org-replace-escapes
8392 note
8393 (list (cons "%u" (user-login-name))
8394 (cons "%U" user-full-name)
8395 (cons "%t" (format-time-string
8396 (org-time-stamp-format 'long 'inactive)
8397 (current-time)))
8398 (cons "%s" (if org-log-note-state
8399 (concat "\"" org-log-note-state "\"")
8400 "")))))
8401 (if lines (setq note (concat note " \\\\")))
8402 (push note lines))
8403 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8404 (when lines
8405 (save-excursion
8406 (set-buffer (marker-buffer org-log-note-marker))
8407 (save-excursion
8408 (goto-char org-log-note-marker)
8409 (move-marker org-log-note-marker nil)
8410 (end-of-line 1)
8411 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8412 (indent-relative nil)
8413 (insert "- " (pop lines))
8414 (org-indent-line-function)
8415 (beginning-of-line 1)
8416 (looking-at "[ \t]*")
8417 (setq ind (concat (match-string 0) " "))
8418 (end-of-line 1)
8419 (while lines (insert "\n" ind (pop lines)))))))
8420 (set-window-configuration org-log-note-window-configuration)
8421 (with-current-buffer (marker-buffer org-log-note-return-to)
8422 (goto-char org-log-note-return-to))
8423 (move-marker org-log-note-return-to nil)
8424 (and org-log-post-message (message "%s" org-log-post-message)))
8426 (defun org-sparse-tree (&optional arg)
8427 "Create a sparse tree, prompt for the details.
8428 This command can create sparse trees. You first need to select the type
8429 of match used to create the tree:
8431 t Show entries with a specific TODO keyword.
8432 T Show entries selected by a tags match.
8433 p Enter a property name and its value (both with completion on existing
8434 names/values) and show entries with that property.
8435 r Show entries matching a regular expression
8436 d Show deadlines due within `org-deadline-warning-days'."
8437 (interactive "P")
8438 (let (ans kwd value)
8439 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8440 (setq ans (read-char-exclusive))
8441 (cond
8442 ((equal ans ?d)
8443 (call-interactively 'org-check-deadlines))
8444 ((equal ans ?b)
8445 (call-interactively 'org-check-before-date))
8446 ((equal ans ?t)
8447 (org-show-todo-tree '(4)))
8448 ((equal ans ?T)
8449 (call-interactively 'org-tags-sparse-tree))
8450 ((member ans '(?p ?P))
8451 (setq kwd (completing-read "Property: "
8452 (mapcar 'list (org-buffer-property-keys))))
8453 (setq value (completing-read "Value: "
8454 (mapcar 'list (org-property-values kwd))))
8455 (unless (string-match "\\`{.*}\\'" value)
8456 (setq value (concat "\"" value "\"")))
8457 (org-tags-sparse-tree arg (concat kwd "=" value)))
8458 ((member ans '(?r ?R ?/))
8459 (call-interactively 'org-occur))
8460 (t (error "No such sparse tree command \"%c\"" ans)))))
8462 (defvar org-occur-highlights nil
8463 "List of overlays used for occur matches.")
8464 (make-variable-buffer-local 'org-occur-highlights)
8465 (defvar org-occur-parameters nil
8466 "Parameters of the active org-occur calls.
8467 This is a list, each call to org-occur pushes as cons cell,
8468 containing the regular expression and the callback, onto the list.
8469 The list can contain several entries if `org-occur' has been called
8470 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8471 will only contain one set of parameters. When the highlights are
8472 removed (for example with `C-c C-c', or with the next edit (depending
8473 on `org-remove-highlights-with-change'), this variable is emptied
8474 as well.")
8475 (make-variable-buffer-local 'org-occur-parameters)
8477 (defun org-occur (regexp &optional keep-previous callback)
8478 "Make a compact tree which shows all matches of REGEXP.
8479 The tree will show the lines where the regexp matches, and all higher
8480 headlines above the match. It will also show the heading after the match,
8481 to make sure editing the matching entry is easy.
8482 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8483 call to `org-occur' will be kept, to allow stacking of calls to this
8484 command.
8485 If CALLBACK is non-nil, it is a function which is called to confirm
8486 that the match should indeed be shown."
8487 (interactive "sRegexp: \nP")
8488 (unless keep-previous
8489 (org-remove-occur-highlights nil nil t))
8490 (push (cons regexp callback) org-occur-parameters)
8491 (let ((cnt 0))
8492 (save-excursion
8493 (goto-char (point-min))
8494 (if (or (not keep-previous) ; do not want to keep
8495 (not org-occur-highlights)) ; no previous matches
8496 ;; hide everything
8497 (org-overview))
8498 (while (re-search-forward regexp nil t)
8499 (when (or (not callback)
8500 (save-match-data (funcall callback)))
8501 (setq cnt (1+ cnt))
8502 (when org-highlight-sparse-tree-matches
8503 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8504 (org-show-context 'occur-tree))))
8505 (when org-remove-highlights-with-change
8506 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8507 nil 'local))
8508 (unless org-sparse-tree-open-archived-trees
8509 (org-hide-archived-subtrees (point-min) (point-max)))
8510 (run-hooks 'org-occur-hook)
8511 (if (interactive-p)
8512 (message "%d match(es) for regexp %s" cnt regexp))
8513 cnt))
8515 (defun org-show-context (&optional key)
8516 "Make sure point and context and visible.
8517 How much context is shown depends upon the variables
8518 `org-show-hierarchy-above', `org-show-following-heading'. and
8519 `org-show-siblings'."
8520 (let ((heading-p (org-on-heading-p t))
8521 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8522 (following-p (org-get-alist-option org-show-following-heading key))
8523 (entry-p (org-get-alist-option org-show-entry-below key))
8524 (siblings-p (org-get-alist-option org-show-siblings key)))
8525 (catch 'exit
8526 ;; Show heading or entry text
8527 (if (and heading-p (not entry-p))
8528 (org-flag-heading nil) ; only show the heading
8529 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8530 (org-show-hidden-entry))) ; show entire entry
8531 (when following-p
8532 ;; Show next sibling, or heading below text
8533 (save-excursion
8534 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8535 (org-flag-heading nil))))
8536 (when siblings-p (org-show-siblings))
8537 (when hierarchy-p
8538 ;; show all higher headings, possibly with siblings
8539 (save-excursion
8540 (while (and (condition-case nil
8541 (progn (org-up-heading-all 1) t)
8542 (error nil))
8543 (not (bobp)))
8544 (org-flag-heading nil)
8545 (when siblings-p (org-show-siblings))))))))
8547 (defun org-reveal (&optional siblings)
8548 "Show current entry, hierarchy above it, and the following headline.
8549 This can be used to show a consistent set of context around locations
8550 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8551 not t for the search context.
8553 With optional argument SIBLINGS, on each level of the hierarchy all
8554 siblings are shown. This repairs the tree structure to what it would
8555 look like when opened with hierarchical calls to `org-cycle'."
8556 (interactive "P")
8557 (let ((org-show-hierarchy-above t)
8558 (org-show-following-heading t)
8559 (org-show-siblings (if siblings t org-show-siblings)))
8560 (org-show-context nil)))
8562 (defun org-highlight-new-match (beg end)
8563 "Highlight from BEG to END and mark the highlight is an occur headline."
8564 (let ((ov (org-make-overlay beg end)))
8565 (org-overlay-put ov 'face 'secondary-selection)
8566 (push ov org-occur-highlights)))
8568 (defun org-remove-occur-highlights (&optional beg end noremove)
8569 "Remove the occur highlights from the buffer.
8570 BEG and END are ignored. If NOREMOVE is nil, remove this function
8571 from the `before-change-functions' in the current buffer."
8572 (interactive)
8573 (unless org-inhibit-highlight-removal
8574 (mapc 'org-delete-overlay org-occur-highlights)
8575 (setq org-occur-highlights nil)
8576 (setq org-occur-parameters nil)
8577 (unless noremove
8578 (remove-hook 'before-change-functions
8579 'org-remove-occur-highlights 'local))))
8581 ;;;; Priorities
8583 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8584 "Regular expression matching the priority indicator.")
8586 (defvar org-remove-priority-next-time nil)
8588 (defun org-priority-up ()
8589 "Increase the priority of the current item."
8590 (interactive)
8591 (org-priority 'up))
8593 (defun org-priority-down ()
8594 "Decrease the priority of the current item."
8595 (interactive)
8596 (org-priority 'down))
8598 (defun org-priority (&optional action)
8599 "Change the priority of an item by ARG.
8600 ACTION can be `set', `up', `down', or a character."
8601 (interactive)
8602 (setq action (or action 'set))
8603 (let (current new news have remove)
8604 (save-excursion
8605 (org-back-to-heading)
8606 (if (looking-at org-priority-regexp)
8607 (setq current (string-to-char (match-string 2))
8608 have t)
8609 (setq current org-default-priority))
8610 (cond
8611 ((or (eq action 'set)
8612 (if (featurep 'xemacs) (characterp action) (integerp action)))
8613 (if (not (eq action 'set))
8614 (setq new action)
8615 (message "Priority %c-%c, SPC to remove: "
8616 org-highest-priority org-lowest-priority)
8617 (setq new (read-char-exclusive)))
8618 (if (and (= (upcase org-highest-priority) org-highest-priority)
8619 (= (upcase org-lowest-priority) org-lowest-priority))
8620 (setq new (upcase new)))
8621 (cond ((equal new ?\ ) (setq remove t))
8622 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8623 (error "Priority must be between `%c' and `%c'"
8624 org-highest-priority org-lowest-priority))))
8625 ((eq action 'up)
8626 (if (and (not have) (eq last-command this-command))
8627 (setq new org-lowest-priority)
8628 (setq new (if (and org-priority-start-cycle-with-default (not have))
8629 org-default-priority (1- current)))))
8630 ((eq action 'down)
8631 (if (and (not have) (eq last-command this-command))
8632 (setq new org-highest-priority)
8633 (setq new (if (and org-priority-start-cycle-with-default (not have))
8634 org-default-priority (1+ current)))))
8635 (t (error "Invalid action")))
8636 (if (or (< (upcase new) org-highest-priority)
8637 (> (upcase new) org-lowest-priority))
8638 (setq remove t))
8639 (setq news (format "%c" new))
8640 (if have
8641 (if remove
8642 (replace-match "" t t nil 1)
8643 (replace-match news t t nil 2))
8644 (if remove
8645 (error "No priority cookie found in line")
8646 (looking-at org-todo-line-regexp)
8647 (if (match-end 2)
8648 (progn
8649 (goto-char (match-end 2))
8650 (insert " [#" news "]"))
8651 (goto-char (match-beginning 3))
8652 (insert "[#" news "] ")))))
8653 (org-preserve-lc (org-set-tags nil 'align))
8654 (if remove
8655 (message "Priority removed")
8656 (message "Priority of current item set to %s" news))))
8659 (defun org-get-priority (s)
8660 "Find priority cookie and return priority."
8661 (save-match-data
8662 (if (not (string-match org-priority-regexp s))
8663 (* 1000 (- org-lowest-priority org-default-priority))
8664 (* 1000 (- org-lowest-priority
8665 (string-to-char (match-string 2 s)))))))
8667 ;;;; Tags
8669 (defun org-scan-tags (action matcher &optional todo-only)
8670 "Scan headline tags with inheritance and produce output ACTION.
8671 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8672 evaluated, testing if a given set of tags qualifies a headline for
8673 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8674 are included in the output."
8675 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8676 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8677 (org-re
8678 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8679 (props (list 'face nil
8680 'done-face 'org-done
8681 'undone-face nil
8682 'mouse-face 'highlight
8683 'org-not-done-regexp org-not-done-regexp
8684 'org-todo-regexp org-todo-regexp
8685 'keymap org-agenda-keymap
8686 'help-echo
8687 (format "mouse-2 or RET jump to org file %s"
8688 (abbreviate-file-name
8689 (or (buffer-file-name (buffer-base-buffer))
8690 (buffer-name (buffer-base-buffer)))))))
8691 (case-fold-search nil)
8692 lspos
8693 tags tags-list tags-alist (llast 0) rtn level category i txt
8694 todo marker entry priority)
8695 (save-excursion
8696 (goto-char (point-min))
8697 (when (eq action 'sparse-tree)
8698 (org-overview)
8699 (org-remove-occur-highlights))
8700 (while (re-search-forward re nil t)
8701 (catch :skip
8702 (setq todo (if (match-end 1) (match-string 2))
8703 tags (if (match-end 4) (match-string 4)))
8704 (goto-char (setq lspos (1+ (match-beginning 0))))
8705 (setq level (org-reduced-level (funcall outline-level))
8706 category (org-get-category))
8707 (setq i llast llast level)
8708 ;; remove tag lists from same and sublevels
8709 (while (>= i level)
8710 (when (setq entry (assoc i tags-alist))
8711 (setq tags-alist (delete entry tags-alist)))
8712 (setq i (1- i)))
8713 ;; add the next tags
8714 (when tags
8715 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8716 tags-alist
8717 (cons (cons level tags) tags-alist)))
8718 ;; compile tags for current headline
8719 (setq tags-list
8720 (if org-use-tag-inheritance
8721 (apply 'append (mapcar 'cdr tags-alist))
8722 tags))
8723 (when (and tags org-use-tag-inheritance
8724 (not (eq t org-use-tag-inheritance)))
8725 ;; selective inheritance, remove uninherited ones
8726 (setcdr (car tags-alist)
8727 (org-remove-uniherited-tags (cdar tags-alist))))
8728 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8729 (eval matcher)
8730 (or (not org-agenda-skip-archived-trees)
8731 (not (member org-archive-tag tags-list))))
8732 (and (eq action 'agenda) (org-agenda-skip))
8733 ;; list this headline
8735 (if (eq action 'sparse-tree)
8736 (progn
8737 (and org-highlight-sparse-tree-matches
8738 (org-get-heading) (match-end 0)
8739 (org-highlight-new-match
8740 (match-beginning 0) (match-beginning 1)))
8741 (org-show-context 'tags-tree))
8742 (setq txt (org-format-agenda-item
8744 (concat
8745 (if org-tags-match-list-sublevels
8746 (make-string (1- level) ?.) "")
8747 (org-get-heading))
8748 category tags-list)
8749 priority (org-get-priority txt))
8750 (goto-char lspos)
8751 (setq marker (org-agenda-new-marker))
8752 (org-add-props txt props
8753 'org-marker marker 'org-hd-marker marker 'org-category category
8754 'priority priority 'type "tagsmatch")
8755 (push txt rtn))
8756 ;; if we are to skip sublevels, jump to end of subtree
8757 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8758 (when (and (eq action 'sparse-tree)
8759 (not org-sparse-tree-open-archived-trees))
8760 (org-hide-archived-subtrees (point-min) (point-max)))
8761 (nreverse rtn)))
8763 (defun org-remove-uniherited-tags (tags)
8764 "Remove all tags that are not inherited from the list TAGS."
8765 (cond
8766 ((eq org-use-tag-inheritance t) tags)
8767 ((not org-use-tag-inheritance) nil)
8768 ((stringp org-use-tag-inheritance)
8769 (delq nil (mapcar
8770 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8771 tags)))
8772 ((listp org-use-tag-inheritance)
8773 (org-delete-all org-use-tag-inheritance tags))))
8775 (defvar todo-only) ;; dynamically scoped
8777 (defun org-tags-sparse-tree (&optional todo-only match)
8778 "Create a sparse tree according to tags string MATCH.
8779 MATCH can contain positive and negative selection of tags, like
8780 \"+WORK+URGENT-WITHBOSS\".
8781 If optional argument TODO_ONLY is non-nil, only select lines that are
8782 also TODO lines."
8783 (interactive "P")
8784 (org-prepare-agenda-buffers (list (current-buffer)))
8785 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8787 (defvar org-cached-props nil)
8788 (defun org-cached-entry-get (pom property)
8789 (if (or (eq t org-use-property-inheritance)
8790 (and (stringp org-use-property-inheritance)
8791 (string-match org-use-property-inheritance property))
8792 (and (listp org-use-property-inheritance)
8793 (member property org-use-property-inheritance)))
8794 ;; Caching is not possible, check it directly
8795 (org-entry-get pom property 'inherit)
8796 ;; Get all properties, so that we can do complicated checks easily
8797 (cdr (assoc property (or org-cached-props
8798 (setq org-cached-props
8799 (org-entry-properties pom)))))))
8801 (defun org-global-tags-completion-table (&optional files)
8802 "Return the list of all tags in all agenda buffer/files."
8803 (save-excursion
8804 (org-uniquify
8805 (delq nil
8806 (apply 'append
8807 (mapcar
8808 (lambda (file)
8809 (set-buffer (find-file-noselect file))
8810 (append (org-get-buffer-tags)
8811 (mapcar (lambda (x) (if (stringp (car-safe x))
8812 (list (car-safe x)) nil))
8813 org-tag-alist)))
8814 (if (and files (car files))
8815 files
8816 (org-agenda-files))))))))
8818 (defun org-make-tags-matcher (match)
8819 "Create the TAGS//TODO matcher form for the selection string MATCH."
8820 ;; todo-only is scoped dynamically into this function, and the function
8821 ;; may change it it the matcher asksk for it.
8822 (unless match
8823 ;; Get a new match request, with completion
8824 (let ((org-last-tags-completion-table
8825 (org-global-tags-completion-table)))
8826 (setq match (completing-read
8827 "Match: " 'org-tags-completion-function nil nil nil
8828 'org-tags-history))))
8830 ;; Parse the string and create a lisp form
8831 (let ((match0 match)
8832 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8833 minus tag mm
8834 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8835 orterms term orlist re-p str-p level-p level-op
8836 prop-p pn pv po cat-p gv)
8837 (if (string-match "/+" match)
8838 ;; match contains also a todo-matching request
8839 (progn
8840 (setq tagsmatch (substring match 0 (match-beginning 0))
8841 todomatch (substring match (match-end 0)))
8842 (if (string-match "^!" todomatch)
8843 (setq todo-only t todomatch (substring todomatch 1)))
8844 (if (string-match "^\\s-*$" todomatch)
8845 (setq todomatch nil)))
8846 ;; only matching tags
8847 (setq tagsmatch match todomatch nil))
8849 ;; Make the tags matcher
8850 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8851 (setq tagsmatcher t)
8852 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8853 (while (setq term (pop orterms))
8854 (while (and (equal (substring term -1) "\\") orterms)
8855 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8856 (while (string-match re term)
8857 (setq minus (and (match-end 1)
8858 (equal (match-string 1 term) "-"))
8859 tag (match-string 2 term)
8860 re-p (equal (string-to-char tag) ?{)
8861 level-p (match-end 4)
8862 prop-p (match-end 5)
8863 mm (cond
8864 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8865 (level-p
8866 (setq level-op (org-op-to-function (match-string 3 term)))
8867 `(,level-op level ,(string-to-number
8868 (match-string 4 term))))
8869 (prop-p
8870 (setq pn (match-string 5 term)
8871 po (match-string 6 term)
8872 pv (match-string 7 term)
8873 cat-p (equal pn "CATEGORY")
8874 re-p (equal (string-to-char pv) ?{)
8875 str-p (equal (string-to-char pv) ?\")
8876 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8877 (setq po (org-op-to-function po str-p))
8878 (if (equal pn "CATEGORY")
8879 (setq gv '(get-text-property (point) 'org-category))
8880 (setq gv `(org-cached-entry-get nil ,pn)))
8881 (if re-p
8882 (if (eq po 'org<>)
8883 `(not (string-match ,pv (or ,gv "")))
8884 `(string-match ,pv (or ,gv "")))
8885 (if str-p
8886 `(,po (or ,gv "") ,pv)
8887 `(,po (string-to-number (or ,gv ""))
8888 ,(string-to-number pv) ))))
8889 (t `(member ,(downcase tag) tags-list)))
8890 mm (if minus (list 'not mm) mm)
8891 term (substring term (match-end 0)))
8892 (push mm tagsmatcher))
8893 (push (if (> (length tagsmatcher) 1)
8894 (cons 'and tagsmatcher)
8895 (car tagsmatcher))
8896 orlist)
8897 (setq tagsmatcher nil))
8898 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8899 (setq tagsmatcher
8900 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8901 ;; Make the todo matcher
8902 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8903 (setq todomatcher t)
8904 (setq orterms (org-split-string todomatch "|") orlist nil)
8905 (while (setq term (pop orterms))
8906 (while (string-match re term)
8907 (setq minus (and (match-end 1)
8908 (equal (match-string 1 term) "-"))
8909 kwd (match-string 2 term)
8910 re-p (equal (string-to-char kwd) ?{)
8911 term (substring term (match-end 0))
8912 mm (if re-p
8913 `(string-match ,(substring kwd 1 -1) todo)
8914 (list 'equal 'todo kwd))
8915 mm (if minus (list 'not mm) mm))
8916 (push mm todomatcher))
8917 (push (if (> (length todomatcher) 1)
8918 (cons 'and todomatcher)
8919 (car todomatcher))
8920 orlist)
8921 (setq todomatcher nil))
8922 (setq todomatcher (if (> (length orlist) 1)
8923 (cons 'or orlist) (car orlist))))
8925 ;; Return the string and lisp forms of the matcher
8926 (setq matcher (if todomatcher
8927 (list 'and tagsmatcher todomatcher)
8928 tagsmatcher))
8929 (cons match0 matcher)))
8931 (defun org-op-to-function (op &optional stringp)
8932 (setq op
8933 (cond
8934 ((equal op "<" ) '(< string< ))
8935 ((equal op ">" ) '(> org-string> ))
8936 ((member op '("<=" "=<")) '(<= org-string<= ))
8937 ((member op '(">=" "=>")) '(>= org-string>= ))
8938 ((member op '("=" "==")) '(= string= ))
8939 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8940 (nth (if stringp 1 0) op))
8942 (defun org<> (a b) (not (= a b)))
8943 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8944 (defun org-string>= (a b) (not (string< a b)))
8945 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8946 (defun org-string<> (a b) (not (string= a b)))
8948 (defun org-match-any-p (re list)
8949 "Does re match any element of list?"
8950 (setq list (mapcar (lambda (x) (string-match re x)) list))
8951 (delq nil list))
8953 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8954 (defvar org-tags-overlay (org-make-overlay 1 1))
8955 (org-detach-overlay org-tags-overlay)
8957 (defun org-get-tags-at (&optional pos)
8958 "Get a list of all headline tags applicable at POS.
8959 POS defaults to point. If tags are inherited, the list contains
8960 the targets in the same sequence as the headlines appear, i.e.
8961 sthe tags of the current headline come last."
8962 (interactive)
8963 (let (tags ltags lastpos parent)
8964 (save-excursion
8965 (save-restriction
8966 (widen)
8967 (goto-char (or pos (point)))
8968 (save-match-data
8969 (condition-case nil
8970 (progn
8971 (org-back-to-heading t)
8972 (while (not (equal lastpos (point)))
8973 (setq lastpos (point))
8974 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8975 (setq ltags (org-split-string
8976 (org-match-string-no-properties 1) ":"))
8977 (setq tags (append (org-remove-uniherited-tags ltags)
8978 tags)))
8979 (or org-use-tag-inheritance (error ""))
8980 (org-up-heading-all 1)
8981 (setq parent t)))
8982 (error nil))))
8983 tags)))
8985 (defun org-toggle-tag (tag &optional onoff)
8986 "Toggle the tag TAG for the current line.
8987 If ONOFF is `on' or `off', don't toggle but set to this state."
8988 (unless (org-on-heading-p t) (error "Not on headling"))
8989 (let (res current)
8990 (save-excursion
8991 (beginning-of-line)
8992 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8993 (point-at-eol) t)
8994 (progn
8995 (setq current (match-string 1))
8996 (replace-match ""))
8997 (setq current ""))
8998 (setq current (nreverse (org-split-string current ":")))
8999 (cond
9000 ((eq onoff 'on)
9001 (setq res t)
9002 (or (member tag current) (push tag current)))
9003 ((eq onoff 'off)
9004 (or (not (member tag current)) (setq current (delete tag current))))
9005 (t (if (member tag current)
9006 (setq current (delete tag current))
9007 (setq res t)
9008 (push tag current))))
9009 (end-of-line 1)
9010 (if current
9011 (progn
9012 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9013 (org-set-tags nil t))
9014 (delete-horizontal-space))
9015 (run-hooks 'org-after-tags-change-hook))
9016 res))
9018 (defun org-align-tags-here (to-col)
9019 ;; Assumes that this is a headline
9020 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9021 (beginning-of-line 1)
9022 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9023 (< pos (match-beginning 2)))
9024 (progn
9025 (setq tags-l (- (match-end 2) (match-beginning 2)))
9026 (goto-char (match-beginning 1))
9027 (insert " ")
9028 (delete-region (point) (1+ (match-beginning 2)))
9029 (setq ncol (max (1+ (current-column))
9030 (1+ col)
9031 (if (> to-col 0)
9032 to-col
9033 (- (abs to-col) tags-l))))
9034 (setq p (point))
9035 (insert (make-string (- ncol (current-column)) ?\ ))
9036 (setq ncol (current-column))
9037 (tabify p (point-at-eol))
9038 (org-move-to-column (min ncol col) t))
9039 (goto-char pos))))
9041 (defun org-set-tags (&optional arg just-align)
9042 "Set the tags for the current headline.
9043 With prefix ARG, realign all tags in headings in the current buffer."
9044 (interactive "P")
9045 (let* ((re (concat "^" outline-regexp))
9046 (current (org-get-tags-string))
9047 (col (current-column))
9048 (org-setting-tags t)
9049 table current-tags inherited-tags ; computed below when needed
9050 tags p0 c0 c1 rpl)
9051 (if arg
9052 (save-excursion
9053 (goto-char (point-min))
9054 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9055 (while (re-search-forward re nil t)
9056 (org-set-tags nil t)
9057 (end-of-line 1)))
9058 (message "All tags realigned to column %d" org-tags-column))
9059 (if just-align
9060 (setq tags current)
9061 ;; Get a new set of tags from the user
9062 (save-excursion
9063 (setq table (or org-tag-alist (org-get-buffer-tags))
9064 org-last-tags-completion-table table
9065 current-tags (org-split-string current ":")
9066 inherited-tags (nreverse
9067 (nthcdr (length current-tags)
9068 (nreverse (org-get-tags-at))))
9069 tags
9070 (if (or (eq t org-use-fast-tag-selection)
9071 (and org-use-fast-tag-selection
9072 (delq nil (mapcar 'cdr table))))
9073 (org-fast-tag-selection
9074 current-tags inherited-tags table
9075 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9076 (let ((org-add-colon-after-tag-completion t))
9077 (org-trim
9078 (org-without-partial-completion
9079 (completing-read "Tags: " 'org-tags-completion-function
9080 nil nil current 'org-tags-history)))))))
9081 (while (string-match "[-+&]+" tags)
9082 ;; No boolean logic, just a list
9083 (setq tags (replace-match ":" t t tags))))
9085 (if (string-match "\\`[\t ]*\\'" tags)
9086 (setq tags "")
9087 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9088 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9090 ;; Insert new tags at the correct column
9091 (beginning-of-line 1)
9092 (cond
9093 ((and (equal current "") (equal tags "")))
9094 ((re-search-forward
9095 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9096 (point-at-eol) t)
9097 (if (equal tags "")
9098 (setq rpl "")
9099 (goto-char (match-beginning 0))
9100 (setq c0 (current-column) p0 (point)
9101 c1 (max (1+ c0) (if (> org-tags-column 0)
9102 org-tags-column
9103 (- (- org-tags-column) (length tags))))
9104 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9105 (replace-match rpl t t)
9106 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9107 tags)
9108 (t (error "Tags alignment failed")))
9109 (org-move-to-column col)
9110 (unless just-align
9111 (run-hooks 'org-after-tags-change-hook)))))
9113 (defun org-change-tag-in-region (beg end tag off)
9114 "Add or remove TAG for each entry in the region.
9115 This works in the agenda, and also in an org-mode buffer."
9116 (interactive
9117 (list (region-beginning) (region-end)
9118 (let ((org-last-tags-completion-table
9119 (if (org-mode-p)
9120 (org-get-buffer-tags)
9121 (org-global-tags-completion-table))))
9122 (completing-read
9123 "Tag: " 'org-tags-completion-function nil nil nil
9124 'org-tags-history))
9125 (progn
9126 (message "[s]et or [r]emove? ")
9127 (equal (read-char-exclusive) ?r))))
9128 (if (fboundp 'deactivate-mark) (deactivate-mark))
9129 (let ((agendap (equal major-mode 'org-agenda-mode))
9130 l1 l2 m buf pos newhead (cnt 0))
9131 (goto-char end)
9132 (setq l2 (1- (org-current-line)))
9133 (goto-char beg)
9134 (setq l1 (org-current-line))
9135 (loop for l from l1 to l2 do
9136 (goto-line l)
9137 (setq m (get-text-property (point) 'org-hd-marker))
9138 (when (or (and (org-mode-p) (org-on-heading-p))
9139 (and agendap m))
9140 (setq buf (if agendap (marker-buffer m) (current-buffer))
9141 pos (if agendap m (point)))
9142 (with-current-buffer buf
9143 (save-excursion
9144 (save-restriction
9145 (goto-char pos)
9146 (setq cnt (1+ cnt))
9147 (org-toggle-tag tag (if off 'off 'on))
9148 (setq newhead (org-get-heading)))))
9149 (and agendap (org-agenda-change-all-lines newhead m))))
9150 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9152 (defun org-tags-completion-function (string predicate &optional flag)
9153 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9154 (confirm (lambda (x) (stringp (car x)))))
9155 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9156 (setq s1 (match-string 1 string)
9157 s2 (match-string 2 string))
9158 (setq s1 "" s2 string))
9159 (cond
9160 ((eq flag nil)
9161 ;; try completion
9162 (setq rtn (try-completion s2 ctable confirm))
9163 (if (stringp rtn)
9164 (setq rtn
9165 (concat s1 s2 (substring rtn (length s2))
9166 (if (and org-add-colon-after-tag-completion
9167 (assoc rtn ctable))
9168 ":" ""))))
9169 rtn)
9170 ((eq flag t)
9171 ;; all-completions
9172 (all-completions s2 ctable confirm)
9174 ((eq flag 'lambda)
9175 ;; exact match?
9176 (assoc s2 ctable)))
9179 (defun org-fast-tag-insert (kwd tags face &optional end)
9180 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9181 (insert (format "%-12s" (concat kwd ":"))
9182 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9183 (or end "")))
9185 (defun org-fast-tag-show-exit (flag)
9186 (save-excursion
9187 (goto-line 3)
9188 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9189 (replace-match ""))
9190 (when flag
9191 (end-of-line 1)
9192 (org-move-to-column (- (window-width) 19) t)
9193 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9195 (defun org-set-current-tags-overlay (current prefix)
9196 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9197 (if (featurep 'xemacs)
9198 (org-overlay-display org-tags-overlay (concat prefix s)
9199 'secondary-selection)
9200 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9201 (org-overlay-display org-tags-overlay (concat prefix s)))))
9203 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9204 "Fast tag selection with single keys.
9205 CURRENT is the current list of tags in the headline, INHERITED is the
9206 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9207 possibly with grouping information. TODO-TABLE is a similar table with
9208 TODO keywords, should these have keys assigned to them.
9209 If the keys are nil, a-z are automatically assigned.
9210 Returns the new tags string, or nil to not change the current settings."
9211 (let* ((fulltable (append table todo-table))
9212 (maxlen (apply 'max (mapcar
9213 (lambda (x)
9214 (if (stringp (car x)) (string-width (car x)) 0))
9215 fulltable)))
9216 (buf (current-buffer))
9217 (expert (eq org-fast-tag-selection-single-key 'expert))
9218 (buffer-tags nil)
9219 (fwidth (+ maxlen 3 1 3))
9220 (ncol (/ (- (window-width) 4) fwidth))
9221 (i-face 'org-done)
9222 (c-face 'org-todo)
9223 tg cnt e c char c1 c2 ntable tbl rtn
9224 ov-start ov-end ov-prefix
9225 (exit-after-next org-fast-tag-selection-single-key)
9226 (done-keywords org-done-keywords)
9227 groups ingroup)
9228 (save-excursion
9229 (beginning-of-line 1)
9230 (if (looking-at
9231 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9232 (setq ov-start (match-beginning 1)
9233 ov-end (match-end 1)
9234 ov-prefix "")
9235 (setq ov-start (1- (point-at-eol))
9236 ov-end (1+ ov-start))
9237 (skip-chars-forward "^\n\r")
9238 (setq ov-prefix
9239 (concat
9240 (buffer-substring (1- (point)) (point))
9241 (if (> (current-column) org-tags-column)
9243 (make-string (- org-tags-column (current-column)) ?\ ))))))
9244 (org-move-overlay org-tags-overlay ov-start ov-end)
9245 (save-window-excursion
9246 (if expert
9247 (set-buffer (get-buffer-create " *Org tags*"))
9248 (delete-other-windows)
9249 (split-window-vertically)
9250 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9251 (erase-buffer)
9252 (org-set-local 'org-done-keywords done-keywords)
9253 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9254 (org-fast-tag-insert "Current" current c-face "\n\n")
9255 (org-fast-tag-show-exit exit-after-next)
9256 (org-set-current-tags-overlay current ov-prefix)
9257 (setq tbl fulltable char ?a cnt 0)
9258 (while (setq e (pop tbl))
9259 (cond
9260 ((equal e '(:startgroup))
9261 (push '() groups) (setq ingroup t)
9262 (when (not (= cnt 0))
9263 (setq cnt 0)
9264 (insert "\n"))
9265 (insert "{ "))
9266 ((equal e '(:endgroup))
9267 (setq ingroup nil cnt 0)
9268 (insert "}\n"))
9270 (setq tg (car e) c2 nil)
9271 (if (cdr e)
9272 (setq c (cdr e))
9273 ;; automatically assign a character.
9274 (setq c1 (string-to-char
9275 (downcase (substring
9276 tg (if (= (string-to-char tg) ?@) 1 0)))))
9277 (if (or (rassoc c1 ntable) (rassoc c1 table))
9278 (while (or (rassoc char ntable) (rassoc char table))
9279 (setq char (1+ char)))
9280 (setq c2 c1))
9281 (setq c (or c2 char)))
9282 (if ingroup (push tg (car groups)))
9283 (setq tg (org-add-props tg nil 'face
9284 (cond
9285 ((not (assoc tg table))
9286 (org-get-todo-face tg))
9287 ((member tg current) c-face)
9288 ((member tg inherited) i-face)
9289 (t nil))))
9290 (if (and (= cnt 0) (not ingroup)) (insert " "))
9291 (insert "[" c "] " tg (make-string
9292 (- fwidth 4 (length tg)) ?\ ))
9293 (push (cons tg c) ntable)
9294 (when (= (setq cnt (1+ cnt)) ncol)
9295 (insert "\n")
9296 (if ingroup (insert " "))
9297 (setq cnt 0)))))
9298 (setq ntable (nreverse ntable))
9299 (insert "\n")
9300 (goto-char (point-min))
9301 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9302 (fit-window-to-buffer))
9303 (setq rtn
9304 (catch 'exit
9305 (while t
9306 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9307 (if groups " [!] no groups" " [!]groups")
9308 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9309 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9310 (cond
9311 ((= c ?\r) (throw 'exit t))
9312 ((= c ?!)
9313 (setq groups (not groups))
9314 (goto-char (point-min))
9315 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9316 ((= c ?\C-c)
9317 (if (not expert)
9318 (org-fast-tag-show-exit
9319 (setq exit-after-next (not exit-after-next)))
9320 (setq expert nil)
9321 (delete-other-windows)
9322 (split-window-vertically)
9323 (org-switch-to-buffer-other-window " *Org tags*")
9324 (and (fboundp 'fit-window-to-buffer)
9325 (fit-window-to-buffer))))
9326 ((or (= c ?\C-g)
9327 (and (= c ?q) (not (rassoc c ntable))))
9328 (org-detach-overlay org-tags-overlay)
9329 (setq quit-flag t))
9330 ((= c ?\ )
9331 (setq current nil)
9332 (if exit-after-next (setq exit-after-next 'now)))
9333 ((= c ?\t)
9334 (condition-case nil
9335 (setq tg (completing-read
9336 "Tag: "
9337 (or buffer-tags
9338 (with-current-buffer buf
9339 (org-get-buffer-tags)))))
9340 (quit (setq tg "")))
9341 (when (string-match "\\S-" tg)
9342 (add-to-list 'buffer-tags (list tg))
9343 (if (member tg current)
9344 (setq current (delete tg current))
9345 (push tg current)))
9346 (if exit-after-next (setq exit-after-next 'now)))
9347 ((setq e (rassoc c todo-table) tg (car e))
9348 (with-current-buffer buf
9349 (save-excursion (org-todo tg)))
9350 (if exit-after-next (setq exit-after-next 'now)))
9351 ((setq e (rassoc c ntable) tg (car e))
9352 (if (member tg current)
9353 (setq current (delete tg current))
9354 (loop for g in groups do
9355 (if (member tg g)
9356 (mapc (lambda (x)
9357 (setq current (delete x current)))
9358 g)))
9359 (push tg current))
9360 (if exit-after-next (setq exit-after-next 'now))))
9362 ;; Create a sorted list
9363 (setq current
9364 (sort current
9365 (lambda (a b)
9366 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9367 (if (eq exit-after-next 'now) (throw 'exit t))
9368 (goto-char (point-min))
9369 (beginning-of-line 2)
9370 (delete-region (point) (point-at-eol))
9371 (org-fast-tag-insert "Current" current c-face)
9372 (org-set-current-tags-overlay current ov-prefix)
9373 (while (re-search-forward
9374 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9375 (setq tg (match-string 1))
9376 (add-text-properties
9377 (match-beginning 1) (match-end 1)
9378 (list 'face
9379 (cond
9380 ((member tg current) c-face)
9381 ((member tg inherited) i-face)
9382 (t (get-text-property (match-beginning 1) 'face))))))
9383 (goto-char (point-min)))))
9384 (org-detach-overlay org-tags-overlay)
9385 (if rtn
9386 (mapconcat 'identity current ":")
9387 nil))))
9389 (defun org-get-tags-string ()
9390 "Get the TAGS string in the current headline."
9391 (unless (org-on-heading-p t)
9392 (error "Not on a heading"))
9393 (save-excursion
9394 (beginning-of-line 1)
9395 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9396 (org-match-string-no-properties 1)
9397 "")))
9399 (defun org-get-tags ()
9400 "Get the list of tags specified in the current headline."
9401 (org-split-string (org-get-tags-string) ":"))
9403 (defun org-get-buffer-tags ()
9404 "Get a table of all tags used in the buffer, for completion."
9405 (let (tags)
9406 (save-excursion
9407 (goto-char (point-min))
9408 (while (re-search-forward
9409 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9410 (when (equal (char-after (point-at-bol 0)) ?*)
9411 (mapc (lambda (x) (add-to-list 'tags x))
9412 (org-split-string (org-match-string-no-properties 1) ":")))))
9413 (mapcar 'list tags)))
9416 ;;;; Properties
9418 ;;; Setting and retrieving properties
9420 (defconst org-special-properties
9421 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9422 "TIMESTAMP" "TIMESTAMP_IA")
9423 "The special properties valid in Org-mode.
9425 These are properties that are not defined in the property drawer,
9426 but in some other way.")
9428 (defconst org-default-properties
9429 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9430 "LOCATION" "LOGGING" "COLUMNS")
9431 "Some properties that are used by Org-mode for various purposes.
9432 Being in this list makes sure that they are offered for completion.")
9434 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9435 "Regular expression matching the first line of a property drawer.")
9437 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9438 "Regular expression matching the first line of a property drawer.")
9440 (defun org-property-action ()
9441 "Do an action on properties."
9442 (interactive)
9443 (let (c)
9444 (org-at-property-p)
9445 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9446 (setq c (read-char-exclusive))
9447 (cond
9448 ((equal c ?s)
9449 (call-interactively 'org-set-property))
9450 ((equal c ?d)
9451 (call-interactively 'org-delete-property))
9452 ((equal c ?D)
9453 (call-interactively 'org-delete-property-globally))
9454 ((equal c ?c)
9455 (call-interactively 'org-compute-property-at-point))
9456 (t (error "No such property action %c" c)))))
9458 (defun org-at-property-p ()
9459 "Is the cursor in a property line?"
9460 ;; FIXME: Does not check if we are actually in the drawer.
9461 ;; FIXME: also returns true on any drawers.....
9462 ;; This is used by C-c C-c for property action.
9463 (save-excursion
9464 (beginning-of-line 1)
9465 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9467 (defun org-get-property-block (&optional beg end force)
9468 "Return the (beg . end) range of the body of the property drawer.
9469 BEG and END can be beginning and end of subtree, if not given
9470 they will be found.
9471 If the drawer does not exist and FORCE is non-nil, create the drawer."
9472 (catch 'exit
9473 (save-excursion
9474 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9475 (end (or end (progn (outline-next-heading) (point)))))
9476 (goto-char beg)
9477 (if (re-search-forward org-property-start-re end t)
9478 (setq beg (1+ (match-end 0)))
9479 (if force
9480 (save-excursion
9481 (org-insert-property-drawer)
9482 (setq end (progn (outline-next-heading) (point))))
9483 (throw 'exit nil))
9484 (goto-char beg)
9485 (if (re-search-forward org-property-start-re end t)
9486 (setq beg (1+ (match-end 0)))))
9487 (if (re-search-forward org-property-end-re end t)
9488 (setq end (match-beginning 0))
9489 (or force (throw 'exit nil))
9490 (goto-char beg)
9491 (setq end beg)
9492 (org-indent-line-function)
9493 (insert ":END:\n"))
9494 (cons beg end)))))
9496 (defun org-entry-properties (&optional pom which)
9497 "Get all properties of the entry at point-or-marker POM.
9498 This includes the TODO keyword, the tags, time strings for deadline,
9499 scheduled, and clocking, and any additional properties defined in the
9500 entry. The return value is an alist, keys may occur multiple times
9501 if the property key was used several times.
9502 POM may also be nil, in which case the current entry is used.
9503 If WHICH is nil or `all', get all properties. If WHICH is
9504 `special' or `standard', only get that subclass."
9505 (setq which (or which 'all))
9506 (org-with-point-at pom
9507 (let ((clockstr (substring org-clock-string 0 -1))
9508 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9509 beg end range props sum-props key value string clocksum)
9510 (save-excursion
9511 (when (condition-case nil (org-back-to-heading t) (error nil))
9512 (setq beg (point))
9513 (setq sum-props (get-text-property (point) 'org-summaries))
9514 (setq clocksum (get-text-property (point) :org-clock-minutes))
9515 (outline-next-heading)
9516 (setq end (point))
9517 (when (memq which '(all special))
9518 ;; Get the special properties, like TODO and tags
9519 (goto-char beg)
9520 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9521 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9522 (when (looking-at org-priority-regexp)
9523 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9524 (when (and (setq value (org-get-tags-string))
9525 (string-match "\\S-" value))
9526 (push (cons "TAGS" value) props))
9527 (when (setq value (org-get-tags-at))
9528 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9529 props))
9530 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9531 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9532 string (if (equal key clockstr)
9533 (org-no-properties
9534 (org-trim
9535 (buffer-substring
9536 (match-beginning 3) (goto-char (point-at-eol)))))
9537 (substring (org-match-string-no-properties 3) 1 -1)))
9538 (unless key
9539 (if (= (char-after (match-beginning 3)) ?\[)
9540 (setq key "TIMESTAMP_IA")
9541 (setq key "TIMESTAMP")))
9542 (when (or (equal key clockstr) (not (assoc key props)))
9543 (push (cons key string) props)))
9547 (when (memq which '(all standard))
9548 ;; Get the standard properties, like :PORP: ...
9549 (setq range (org-get-property-block beg end))
9550 (when range
9551 (goto-char (car range))
9552 (while (re-search-forward
9553 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9554 (cdr range) t)
9555 (setq key (org-match-string-no-properties 1)
9556 value (org-trim (or (org-match-string-no-properties 2) "")))
9557 (unless (member key excluded)
9558 (push (cons key (or value "")) props)))))
9559 (if clocksum
9560 (push (cons "CLOCKSUM"
9561 (org-columns-number-to-string (/ (float clocksum) 60.)
9562 'add_times))
9563 props))
9564 (append sum-props (nreverse props)))))))
9566 (defun org-entry-get (pom property &optional inherit)
9567 "Get value of PROPERTY for entry at point-or-marker POM.
9568 If INHERIT is non-nil and the entry does not have the property,
9569 then also check higher levels of the hierarchy.
9570 If INHERIT is the symbol `selective', use inheritance only if the setting
9571 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9572 If the property is present but empty, the return value is the empty string.
9573 If the property is not present at all, nil is returned."
9574 (org-with-point-at pom
9575 (if (and inherit (if (eq inherit 'selective)
9576 (org-property-inherit-p property)
9578 (org-entry-get-with-inheritance property)
9579 (if (member property org-special-properties)
9580 ;; We need a special property. Use brute force, get all properties.
9581 (cdr (assoc property (org-entry-properties nil 'special)))
9582 (let ((range (org-get-property-block)))
9583 (if (and range
9584 (goto-char (car range))
9585 (re-search-forward
9586 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9587 (cdr range) t))
9588 ;; Found the property, return it.
9589 (if (match-end 1)
9590 (org-match-string-no-properties 1)
9591 "")))))))
9593 (defun org-property-or-variable-value (var &optional inherit)
9594 "Check if there is a property fixing the value of VAR.
9595 If yes, return this value. If not, return the current value of the variable."
9596 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9597 (if (and prop (stringp prop) (string-match "\\S-" prop))
9598 (read prop)
9599 (symbol-value var))))
9601 (defun org-entry-delete (pom property)
9602 "Delete the property PROPERTY from entry at point-or-marker POM."
9603 (org-with-point-at pom
9604 (if (member property org-special-properties)
9605 nil ; cannot delete these properties.
9606 (let ((range (org-get-property-block)))
9607 (if (and range
9608 (goto-char (car range))
9609 (re-search-forward
9610 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9611 (cdr range) t))
9612 (progn
9613 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9615 nil)))))
9617 ;; Multi-values properties are properties that contain multiple values
9618 ;; These values are assumed to be single words, separated by whitespace.
9619 (defun org-entry-add-to-multivalued-property (pom property value)
9620 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9621 (let* ((old (org-entry-get pom property))
9622 (values (and old (org-split-string old "[ \t]"))))
9623 (unless (member value values)
9624 (setq values (cons value values))
9625 (org-entry-put pom property
9626 (mapconcat 'identity values " ")))))
9628 (defun org-entry-remove-from-multivalued-property (pom property value)
9629 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9630 (let* ((old (org-entry-get pom property))
9631 (values (and old (org-split-string old "[ \t]"))))
9632 (when (member value values)
9633 (setq values (delete value values))
9634 (org-entry-put pom property
9635 (mapconcat 'identity values " ")))))
9637 (defun org-entry-member-in-multivalued-property (pom property value)
9638 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9639 (let* ((old (org-entry-get pom property))
9640 (values (and old (org-split-string old "[ \t]"))))
9641 (member value values)))
9643 (defvar org-entry-property-inherited-from (make-marker))
9645 (defun org-entry-get-with-inheritance (property)
9646 "Get entry property, and search higher levels if not present."
9647 (let (tmp)
9648 (save-excursion
9649 (save-restriction
9650 (widen)
9651 (catch 'ex
9652 (while t
9653 (when (setq tmp (org-entry-get nil property))
9654 (org-back-to-heading t)
9655 (move-marker org-entry-property-inherited-from (point))
9656 (throw 'ex tmp))
9657 (or (org-up-heading-safe) (throw 'ex nil)))))
9658 (or tmp (cdr (assoc property org-local-properties))
9659 (cdr (assoc property org-global-properties))))))
9661 (defun org-entry-put (pom property value)
9662 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9663 (org-with-point-at pom
9664 (org-back-to-heading t)
9665 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9666 range)
9667 (cond
9668 ((equal property "TODO")
9669 (when (and (stringp value) (string-match "\\S-" value)
9670 (not (member value org-todo-keywords-1)))
9671 (error "\"%s\" is not a valid TODO state" value))
9672 (if (or (not value)
9673 (not (string-match "\\S-" value)))
9674 (setq value 'none))
9675 (org-todo value)
9676 (org-set-tags nil 'align))
9677 ((equal property "PRIORITY")
9678 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9679 (string-to-char value) ?\ ))
9680 (org-set-tags nil 'align))
9681 ((equal property "SCHEDULED")
9682 (if (re-search-forward org-scheduled-time-regexp end t)
9683 (cond
9684 ((eq value 'earlier) (org-timestamp-change -1 'day))
9685 ((eq value 'later) (org-timestamp-change 1 'day))
9686 (t (call-interactively 'org-schedule)))
9687 (call-interactively 'org-schedule)))
9688 ((equal property "DEADLINE")
9689 (if (re-search-forward org-deadline-time-regexp end t)
9690 (cond
9691 ((eq value 'earlier) (org-timestamp-change -1 'day))
9692 ((eq value 'later) (org-timestamp-change 1 'day))
9693 (t (call-interactively 'org-deadline)))
9694 (call-interactively 'org-deadline)))
9695 ((member property org-special-properties)
9696 (error "The %s property can not yet be set with `org-entry-put'"
9697 property))
9698 (t ; a non-special property
9699 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9700 (setq range (org-get-property-block beg end 'force))
9701 (goto-char (car range))
9702 (if (re-search-forward
9703 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9704 (progn
9705 (delete-region (match-beginning 1) (match-end 1))
9706 (goto-char (match-beginning 1)))
9707 (goto-char (cdr range))
9708 (insert "\n")
9709 (backward-char 1)
9710 (org-indent-line-function)
9711 (insert ":" property ":"))
9712 (and value (insert " " value))
9713 (org-indent-line-function)))))))
9715 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9716 "Get all property keys in the current buffer.
9717 With INCLUDE-SPECIALS, also list the special properties that relect things
9718 like tags and TODO state.
9719 With INCLUDE-DEFAULTS, also include properties that has special meaning
9720 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9721 With INCLUDE-COLUMNS, also include property names given in COLUMN
9722 formats in the current buffer."
9723 (let (rtn range cfmt cols s p)
9724 (save-excursion
9725 (save-restriction
9726 (widen)
9727 (goto-char (point-min))
9728 (while (re-search-forward org-property-start-re nil t)
9729 (setq range (org-get-property-block))
9730 (goto-char (car range))
9731 (while (re-search-forward
9732 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9733 (cdr range) t)
9734 (add-to-list 'rtn (org-match-string-no-properties 1)))
9735 (outline-next-heading))))
9737 (when include-specials
9738 (setq rtn (append org-special-properties rtn)))
9740 (when include-defaults
9741 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9743 (when include-columns
9744 (save-excursion
9745 (save-restriction
9746 (widen)
9747 (goto-char (point-min))
9748 (while (re-search-forward
9749 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9750 nil t)
9751 (setq cfmt (match-string 2) s 0)
9752 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9753 cfmt s)
9754 (setq s (match-end 0)
9755 p (match-string 1 cfmt))
9756 (unless (or (equal p "ITEM")
9757 (member p org-special-properties))
9758 (add-to-list 'rtn (match-string 1 cfmt))))))))
9760 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9762 (defun org-property-values (key)
9763 "Return a list of all values of property KEY."
9764 (save-excursion
9765 (save-restriction
9766 (widen)
9767 (goto-char (point-min))
9768 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9769 values)
9770 (while (re-search-forward re nil t)
9771 (add-to-list 'values (org-trim (match-string 1))))
9772 (delete "" values)))))
9774 (defun org-insert-property-drawer ()
9775 "Insert a property drawer into the current entry."
9776 (interactive)
9777 (org-back-to-heading t)
9778 (looking-at outline-regexp)
9779 (let ((indent (- (match-end 0)(match-beginning 0)))
9780 (beg (point))
9781 (re (concat "^[ \t]*" org-keyword-time-regexp))
9782 end hiddenp)
9783 (outline-next-heading)
9784 (setq end (point))
9785 (goto-char beg)
9786 (while (re-search-forward re end t))
9787 (setq hiddenp (org-invisible-p))
9788 (end-of-line 1)
9789 (and (equal (char-after) ?\n) (forward-char 1))
9790 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9791 (beginning-of-line 2))
9792 (org-skip-over-state-notes)
9793 (skip-chars-backward " \t\n\r")
9794 (if (eq (char-before) ?*) (forward-char 1))
9795 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9796 (beginning-of-line 0)
9797 (org-indent-to-column indent)
9798 (beginning-of-line 2)
9799 (org-indent-to-column indent)
9800 (beginning-of-line 0)
9801 (if hiddenp
9802 (save-excursion
9803 (org-back-to-heading t)
9804 (hide-entry))
9805 (org-flag-drawer t))))
9807 (defun org-set-property (property value)
9808 "In the current entry, set PROPERTY to VALUE.
9809 When called interactively, this will prompt for a property name, offering
9810 completion on existing and default properties. And then it will prompt
9811 for a value, offering competion either on allowed values (via an inherited
9812 xxx_ALL property) or on existing values in other instances of this property
9813 in the current file."
9814 (interactive
9815 (let* ((prop (completing-read
9816 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9817 (cur (org-entry-get nil prop))
9818 (allowed (org-property-get-allowed-values nil prop 'table))
9819 (existing (mapcar 'list (org-property-values prop)))
9820 (val (if allowed
9821 (completing-read "Value: " allowed nil 'req-match)
9822 (completing-read
9823 (concat "Value" (if (and cur (string-match "\\S-" cur))
9824 (concat "[" cur "]") "")
9825 ": ")
9826 existing nil nil "" nil cur))))
9827 (list prop (if (equal val "") cur val))))
9828 (unless (equal (org-entry-get nil property) value)
9829 (org-entry-put nil property value)))
9831 (defun org-delete-property (property)
9832 "In the current entry, delete PROPERTY."
9833 (interactive
9834 (let* ((prop (completing-read
9835 "Property: " (org-entry-properties nil 'standard))))
9836 (list prop)))
9837 (message "Property %s %s" property
9838 (if (org-entry-delete nil property)
9839 "deleted"
9840 "was not present in the entry")))
9842 (defun org-delete-property-globally (property)
9843 "Remove PROPERTY globally, from all entries."
9844 (interactive
9845 (let* ((prop (completing-read
9846 "Globally remove property: "
9847 (mapcar 'list (org-buffer-property-keys)))))
9848 (list prop)))
9849 (save-excursion
9850 (save-restriction
9851 (widen)
9852 (goto-char (point-min))
9853 (let ((cnt 0))
9854 (while (re-search-forward
9855 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9856 nil t)
9857 (setq cnt (1+ cnt))
9858 (replace-match ""))
9859 (message "Property \"%s\" removed from %d entries" property cnt)))))
9861 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9863 (defun org-compute-property-at-point ()
9864 "Compute the property at point.
9865 This looks for an enclosing column format, extracts the operator and
9866 then applies it to the proerty in the column format's scope."
9867 (interactive)
9868 (unless (org-at-property-p)
9869 (error "Not at a property"))
9870 (let ((prop (org-match-string-no-properties 2)))
9871 (org-columns-get-format-and-top-level)
9872 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9873 (error "No operator defined for property %s" prop))
9874 (org-columns-compute prop)))
9876 (defun org-property-get-allowed-values (pom property &optional table)
9877 "Get allowed values for the property PROPERTY.
9878 When TABLE is non-nil, return an alist that can directly be used for
9879 completion."
9880 (let (vals)
9881 (cond
9882 ((equal property "TODO")
9883 (setq vals (org-with-point-at pom
9884 (append org-todo-keywords-1 '("")))))
9885 ((equal property "PRIORITY")
9886 (let ((n org-lowest-priority))
9887 (while (>= n org-highest-priority)
9888 (push (char-to-string n) vals)
9889 (setq n (1- n)))))
9890 ((member property org-special-properties))
9892 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9894 (when (and vals (string-match "\\S-" vals))
9895 (setq vals (car (read-from-string (concat "(" vals ")"))))
9896 (setq vals (mapcar (lambda (x)
9897 (cond ((stringp x) x)
9898 ((numberp x) (number-to-string x))
9899 ((symbolp x) (symbol-name x))
9900 (t "???")))
9901 vals)))))
9902 (if table (mapcar 'list vals) vals)))
9904 (defun org-property-previous-allowed-value (&optional previous)
9905 "Switch to the next allowed value for this property."
9906 (interactive)
9907 (org-property-next-allowed-value t))
9909 (defun org-property-next-allowed-value (&optional previous)
9910 "Switch to the next allowed value for this property."
9911 (interactive)
9912 (unless (org-at-property-p)
9913 (error "Not at a property"))
9914 (let* ((key (match-string 2))
9915 (value (match-string 3))
9916 (allowed (or (org-property-get-allowed-values (point) key)
9917 (and (member value '("[ ]" "[-]" "[X]"))
9918 '("[ ]" "[X]"))))
9919 nval)
9920 (unless allowed
9921 (error "Allowed values for this property have not been defined"))
9922 (if previous (setq allowed (reverse allowed)))
9923 (if (member value allowed)
9924 (setq nval (car (cdr (member value allowed)))))
9925 (setq nval (or nval (car allowed)))
9926 (if (equal nval value)
9927 (error "Only one allowed value for this property"))
9928 (org-at-property-p)
9929 (replace-match (concat " :" key ": " nval) t t)
9930 (org-indent-line-function)
9931 (beginning-of-line 1)
9932 (skip-chars-forward " \t")))
9934 (defun org-find-entry-with-id (ident)
9935 "Locate the entry that contains the ID property with exact value IDENT.
9936 IDENT can be a string, a symbol or a number, this function will search for
9937 the string representation of it.
9938 Return the position where this entry starts, or nil if there is no such entry."
9939 (let ((id (cond
9940 ((stringp ident) ident)
9941 ((symbol-name ident) (symbol-name ident))
9942 ((numberp ident) (number-to-string ident))
9943 (t (error "IDENT %s must be a string, symbol or number" ident))))
9944 (case-fold-search nil))
9945 (save-excursion
9946 (save-restriction
9947 (widen)
9948 (goto-char (point-min))
9949 (when (re-search-forward
9950 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9951 nil t)
9952 (org-back-to-heading)
9953 (point))))))
9955 ;;;; Timestamps
9957 (defvar org-last-changed-timestamp nil)
9958 (defvar org-time-was-given) ; dynamically scoped parameter
9959 (defvar org-end-time-was-given) ; dynamically scoped parameter
9960 (defvar org-ts-what) ; dynamically scoped parameter
9962 (defun org-time-stamp (arg)
9963 "Prompt for a date/time and insert a time stamp.
9964 If the user specifies a time like HH:MM, or if this command is called
9965 with a prefix argument, the time stamp will contain date and time.
9966 Otherwise, only the date will be included. All parts of a date not
9967 specified by the user will be filled in from the current date/time.
9968 So if you press just return without typing anything, the time stamp
9969 will represent the current date/time. If there is already a timestamp
9970 at the cursor, it will be modified."
9971 (interactive "P")
9972 (let* ((ts nil)
9973 (default-time
9974 ;; Default time is either today, or, when entering a range,
9975 ;; the range start.
9976 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9977 (save-excursion
9978 (re-search-backward
9979 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9980 (- (point) 20) t)))
9981 (apply 'encode-time (org-parse-time-string (match-string 1)))
9982 (current-time)))
9983 (default-input (and ts (org-get-compact-tod ts)))
9984 org-time-was-given org-end-time-was-given time)
9985 (cond
9986 ((and (org-at-timestamp-p)
9987 (eq last-command 'org-time-stamp)
9988 (eq this-command 'org-time-stamp))
9989 (insert "--")
9990 (setq time (let ((this-command this-command))
9991 (org-read-date arg 'totime nil nil default-time default-input)))
9992 (org-insert-time-stamp time (or org-time-was-given arg)))
9993 ((org-at-timestamp-p)
9994 (setq time (let ((this-command this-command))
9995 (org-read-date arg 'totime nil nil default-time default-input)))
9996 (when (org-at-timestamp-p) ; just to get the match data
9997 (replace-match "")
9998 (setq org-last-changed-timestamp
9999 (org-insert-time-stamp
10000 time (or org-time-was-given arg)
10001 nil nil nil (list org-end-time-was-given))))
10002 (message "Timestamp updated"))
10004 (setq time (let ((this-command this-command))
10005 (org-read-date arg 'totime nil nil default-time default-input)))
10006 (org-insert-time-stamp time (or org-time-was-given arg)
10007 nil nil nil (list org-end-time-was-given))))))
10009 ;; FIXME: can we use this for something else, like computing time differences?
10010 (defun org-get-compact-tod (s)
10011 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10012 (let* ((t1 (match-string 1 s))
10013 (h1 (string-to-number (match-string 2 s)))
10014 (m1 (string-to-number (match-string 3 s)))
10015 (t2 (and (match-end 4) (match-string 5 s)))
10016 (h2 (and t2 (string-to-number (match-string 6 s))))
10017 (m2 (and t2 (string-to-number (match-string 7 s))))
10018 dh dm)
10019 (if (not t2)
10021 (setq dh (- h2 h1) dm (- m2 m1))
10022 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10023 (concat t1 "+" (number-to-string dh)
10024 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10026 (defun org-time-stamp-inactive (&optional arg)
10027 "Insert an inactive time stamp.
10028 An inactive time stamp is enclosed in square brackets instead of angle
10029 brackets. It is inactive in the sense that it does not trigger agenda entries,
10030 does not link to the calendar and cannot be changed with the S-cursor keys.
10031 So these are more for recording a certain time/date."
10032 (interactive "P")
10033 (let (org-time-was-given org-end-time-was-given time)
10034 (setq time (org-read-date arg 'totime))
10035 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10036 nil nil (list org-end-time-was-given))))
10038 (defvar org-date-ovl (org-make-overlay 1 1))
10039 (org-overlay-put org-date-ovl 'face 'org-warning)
10040 (org-detach-overlay org-date-ovl)
10042 (defvar org-ans1) ; dynamically scoped parameter
10043 (defvar org-ans2) ; dynamically scoped parameter
10045 (defvar org-plain-time-of-day-regexp) ; defined below
10047 (defvar org-read-date-overlay nil)
10048 (defvar org-dcst nil) ; dynamically scoped
10050 (defun org-read-date (&optional with-time to-time from-string prompt
10051 default-time default-input)
10052 "Read a date, possibly a time, and make things smooth for the user.
10053 The prompt will suggest to enter an ISO date, but you can also enter anything
10054 which will at least partially be understood by `parse-time-string'.
10055 Unrecognized parts of the date will default to the current day, month, year,
10056 hour and minute. If this command is called to replace a timestamp at point,
10057 of to enter the second timestamp of a range, the default time is taken from the
10058 existing stamp. For example,
10059 3-2-5 --> 2003-02-05
10060 feb 15 --> currentyear-02-15
10061 sep 12 9 --> 2009-09-12
10062 12:45 --> today 12:45
10063 22 sept 0:34 --> currentyear-09-22 0:34
10064 12 --> currentyear-currentmonth-12
10065 Fri --> nearest Friday (today or later)
10066 etc.
10068 Furthermore you can specify a relative date by giving, as the *first* thing
10069 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10070 change in days weeks, months, years.
10071 With a single plus or minus, the date is relative to today. With a double
10072 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10073 +4d --> four days from today
10074 +4 --> same as above
10075 +2w --> two weeks from today
10076 ++5 --> five days from default date
10078 The function understands only English month and weekday abbreviations,
10079 but this can be configured with the variables `parse-time-months' and
10080 `parse-time-weekdays'.
10082 While prompting, a calendar is popped up - you can also select the
10083 date with the mouse (button 1). The calendar shows a period of three
10084 months. To scroll it to other months, use the keys `>' and `<'.
10085 If you don't like the calendar, turn it off with
10086 \(setq org-read-date-popup-calendar nil)
10088 With optional argument TO-TIME, the date will immediately be converted
10089 to an internal time.
10090 With an optional argument WITH-TIME, the prompt will suggest to also
10091 insert a time. Note that when WITH-TIME is not set, you can still
10092 enter a time, and this function will inform the calling routine about
10093 this change. The calling routine may then choose to change the format
10094 used to insert the time stamp into the buffer to include the time.
10095 With optional argument FROM-STRING, read from this string instead from
10096 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10097 the time/date that is used for everything that is not specified by the
10098 user."
10099 (require 'parse-time)
10100 (let* ((org-time-stamp-rounding-minutes
10101 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10102 (org-dcst org-display-custom-times)
10103 (ct (org-current-time))
10104 (def (or default-time ct))
10105 (defdecode (decode-time def))
10106 (dummy (progn
10107 (when (< (nth 2 defdecode) org-extend-today-until)
10108 (setcar (nthcdr 2 defdecode) -1)
10109 (setcar (nthcdr 1 defdecode) 59)
10110 (setq def (apply 'encode-time defdecode)
10111 defdecode (decode-time def)))))
10112 (calendar-move-hook nil)
10113 (calendar-view-diary-initially-flag nil)
10114 (view-diary-entries-initially nil)
10115 (calendar-view-holidays-initially-flag nil)
10116 (view-calendar-holidays-initially nil)
10117 (timestr (format-time-string
10118 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10119 (prompt (concat (if prompt (concat prompt " ") "")
10120 (format "Date+time [%s]: " timestr)))
10121 ans (org-ans0 "") org-ans1 org-ans2 final)
10123 (cond
10124 (from-string (setq ans from-string))
10125 (org-read-date-popup-calendar
10126 (save-excursion
10127 (save-window-excursion
10128 (calendar)
10129 (calendar-forward-day (- (time-to-days def)
10130 (calendar-absolute-from-gregorian
10131 (calendar-current-date))))
10132 (org-eval-in-calendar nil t)
10133 (let* ((old-map (current-local-map))
10134 (map (copy-keymap calendar-mode-map))
10135 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10136 (org-defkey map (kbd "RET") 'org-calendar-select)
10137 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10138 'org-calendar-select-mouse)
10139 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10140 'org-calendar-select-mouse)
10141 (org-defkey minibuffer-local-map [(meta shift left)]
10142 (lambda () (interactive)
10143 (org-eval-in-calendar '(calendar-backward-month 1))))
10144 (org-defkey minibuffer-local-map [(meta shift right)]
10145 (lambda () (interactive)
10146 (org-eval-in-calendar '(calendar-forward-month 1))))
10147 (org-defkey minibuffer-local-map [(meta shift up)]
10148 (lambda () (interactive)
10149 (org-eval-in-calendar '(calendar-backward-year 1))))
10150 (org-defkey minibuffer-local-map [(meta shift down)]
10151 (lambda () (interactive)
10152 (org-eval-in-calendar '(calendar-forward-year 1))))
10153 (org-defkey minibuffer-local-map [(shift up)]
10154 (lambda () (interactive)
10155 (org-eval-in-calendar '(calendar-backward-week 1))))
10156 (org-defkey minibuffer-local-map [(shift down)]
10157 (lambda () (interactive)
10158 (org-eval-in-calendar '(calendar-forward-week 1))))
10159 (org-defkey minibuffer-local-map [(shift left)]
10160 (lambda () (interactive)
10161 (org-eval-in-calendar '(calendar-backward-day 1))))
10162 (org-defkey minibuffer-local-map [(shift right)]
10163 (lambda () (interactive)
10164 (org-eval-in-calendar '(calendar-forward-day 1))))
10165 (org-defkey minibuffer-local-map ">"
10166 (lambda () (interactive)
10167 (org-eval-in-calendar '(scroll-calendar-left 1))))
10168 (org-defkey minibuffer-local-map "<"
10169 (lambda () (interactive)
10170 (org-eval-in-calendar '(scroll-calendar-right 1))))
10171 (unwind-protect
10172 (progn
10173 (use-local-map map)
10174 (add-hook 'post-command-hook 'org-read-date-display)
10175 (setq org-ans0 (read-string prompt default-input nil nil))
10176 ;; org-ans0: from prompt
10177 ;; org-ans1: from mouse click
10178 ;; org-ans2: from calendar motion
10179 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10180 (remove-hook 'post-command-hook 'org-read-date-display)
10181 (use-local-map old-map)
10182 (when org-read-date-overlay
10183 (org-delete-overlay org-read-date-overlay)
10184 (setq org-read-date-overlay nil)))))))
10186 (t ; Naked prompt only
10187 (unwind-protect
10188 (setq ans (read-string prompt default-input nil timestr))
10189 (when org-read-date-overlay
10190 (org-delete-overlay org-read-date-overlay)
10191 (setq org-read-date-overlay nil)))))
10193 (setq final (org-read-date-analyze ans def defdecode))
10195 (if to-time
10196 (apply 'encode-time final)
10197 (if (and (boundp 'org-time-was-given) org-time-was-given)
10198 (format "%04d-%02d-%02d %02d:%02d"
10199 (nth 5 final) (nth 4 final) (nth 3 final)
10200 (nth 2 final) (nth 1 final))
10201 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10202 (defvar def)
10203 (defvar defdecode)
10204 (defvar with-time)
10205 (defun org-read-date-display ()
10206 "Display the currrent date prompt interpretation in the minibuffer."
10207 (when org-read-date-display-live
10208 (when org-read-date-overlay
10209 (org-delete-overlay org-read-date-overlay))
10210 (let ((p (point)))
10211 (end-of-line 1)
10212 (while (not (equal (buffer-substring
10213 (max (point-min) (- (point) 4)) (point))
10214 " "))
10215 (insert " "))
10216 (goto-char p))
10217 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10218 " " (or org-ans1 org-ans2)))
10219 (org-end-time-was-given nil)
10220 (f (org-read-date-analyze ans def defdecode))
10221 (fmts (if org-dcst
10222 org-time-stamp-custom-formats
10223 org-time-stamp-formats))
10224 (fmt (if (or with-time
10225 (and (boundp 'org-time-was-given) org-time-was-given))
10226 (cdr fmts)
10227 (car fmts)))
10228 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10229 (when (and org-end-time-was-given
10230 (string-match org-plain-time-of-day-regexp txt))
10231 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10232 org-end-time-was-given
10233 (substring txt (match-end 0)))))
10234 (setq org-read-date-overlay
10235 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10236 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10238 (defun org-read-date-analyze (ans def defdecode)
10239 "Analyze the combined answer of the date prompt."
10240 ;; FIXME: cleanup and comment
10241 (let (delta deltan deltaw deltadef year month day
10242 hour minute second wday pm h2 m2 tl wday1
10243 iso-year iso-weekday iso-week iso-year iso-date)
10245 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10246 (setq ans "+0"))
10248 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10249 (setq ans (replace-match "" t t ans)
10250 deltan (car delta)
10251 deltaw (nth 1 delta)
10252 deltadef (nth 2 delta)))
10254 ;; Check if there is an iso week date in there
10255 ;; If yes, sore the info and ostpone interpreting it until the rest
10256 ;; of the parsing is done
10257 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10258 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10259 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10260 iso-week (string-to-number (match-string 2 ans)))
10261 (setq ans (replace-match "" t t ans)))
10263 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10264 (when (string-match
10265 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10266 (setq year (if (match-end 2)
10267 (string-to-number (match-string 2 ans))
10268 (string-to-number (format-time-string "%Y")))
10269 month (string-to-number (match-string 3 ans))
10270 day (string-to-number (match-string 4 ans)))
10271 (if (< year 100) (setq year (+ 2000 year)))
10272 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10273 t nil ans)))
10274 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10275 ;; If there is a time with am/pm, and *no* time without it, we convert
10276 ;; so that matching will be successful.
10277 (loop for i from 1 to 2 do ; twice, for end time as well
10278 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10279 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10280 (setq hour (string-to-number (match-string 1 ans))
10281 minute (if (match-end 3)
10282 (string-to-number (match-string 3 ans))
10284 pm (equal ?p
10285 (string-to-char (downcase (match-string 4 ans)))))
10286 (if (and (= hour 12) (not pm))
10287 (setq hour 0)
10288 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10289 (setq ans (replace-match (format "%02d:%02d" hour minute)
10290 t t ans))))
10292 ;; Check if a time range is given as a duration
10293 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10294 (setq hour (string-to-number (match-string 1 ans))
10295 h2 (+ hour (string-to-number (match-string 3 ans)))
10296 minute (string-to-number (match-string 2 ans))
10297 m2 (+ minute (if (match-end 5) (string-to-number
10298 (match-string 5 ans))0)))
10299 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10300 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10301 t t ans)))
10303 ;; Check if there is a time range
10304 (when (boundp 'org-end-time-was-given)
10305 (setq org-time-was-given nil)
10306 (when (and (string-match org-plain-time-of-day-regexp ans)
10307 (match-end 8))
10308 (setq org-end-time-was-given (match-string 8 ans))
10309 (setq ans (concat (substring ans 0 (match-beginning 7))
10310 (substring ans (match-end 7))))))
10312 (setq tl (parse-time-string ans)
10313 day (or (nth 3 tl) (nth 3 defdecode))
10314 month (or (nth 4 tl)
10315 (if (and org-read-date-prefer-future
10316 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10317 (1+ (nth 4 defdecode))
10318 (nth 4 defdecode)))
10319 year (or (nth 5 tl)
10320 (if (and org-read-date-prefer-future
10321 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10322 (1+ (nth 5 defdecode))
10323 (nth 5 defdecode)))
10324 hour (or (nth 2 tl) (nth 2 defdecode))
10325 minute (or (nth 1 tl) (nth 1 defdecode))
10326 second (or (nth 0 tl) 0)
10327 wday (nth 6 tl))
10329 ;; Special date definitions below
10330 (cond
10331 (iso-week
10332 ;; There was an iso week
10333 (setq year (or iso-year year)
10334 day (or iso-weekday wday 1)
10335 wday nil ; to make sure that the trigger below does not match
10336 iso-date (calendar-gregorian-from-absolute
10337 (calendar-absolute-from-iso
10338 (list iso-week day year))))
10339 ; FIXME: Should we also push ISO weeks into the future?
10340 ; (when (and org-read-date-prefer-future
10341 ; (not iso-year)
10342 ; (< (calendar-absolute-from-gregorian iso-date)
10343 ; (time-to-days (current-time))))
10344 ; (setq year (1+ year)
10345 ; iso-date (calendar-gregorian-from-absolute
10346 ; (calendar-absolute-from-iso
10347 ; (list iso-week day year)))))
10348 (setq month (car iso-date)
10349 year (nth 2 iso-date)
10350 day (nth 1 iso-date)))
10351 (deltan
10352 (unless deltadef
10353 (let ((now (decode-time (current-time))))
10354 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10355 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10356 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10357 ((equal deltaw "m") (setq month (+ month deltan)))
10358 ((equal deltaw "y") (setq year (+ year deltan)))))
10359 ((and wday (not (nth 3 tl)))
10360 ;; Weekday was given, but no day, so pick that day in the week
10361 ;; on or after the derived date.
10362 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10363 (unless (equal wday wday1)
10364 (setq day (+ day (% (- wday wday1 -7) 7))))))
10365 (if (and (boundp 'org-time-was-given)
10366 (nth 2 tl))
10367 (setq org-time-was-given t))
10368 (if (< year 100) (setq year (+ 2000 year)))
10369 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10370 (list second minute hour day month year)))
10372 (defvar parse-time-weekdays)
10374 (defun org-read-date-get-relative (s today default)
10375 "Check string S for special relative date string.
10376 TODAY and DEFAULT are internal times, for today and for a default.
10377 Return shift list (N what def-flag)
10378 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10379 N is the number of WHATs to shift.
10380 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10381 the DEFAULT date rather than TODAY."
10382 (when (string-match
10383 (concat
10384 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10385 "\\([0-9]+\\)?"
10386 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10387 "\\([ \t]\\|$\\)") s)
10388 (let* ((dir (if (match-end 1)
10389 (string-to-char (substring (match-string 1 s) -1))
10390 ?+))
10391 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10392 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10393 (what (if (match-end 3) (match-string 3 s) "d"))
10394 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10395 (date (if rel default today))
10396 (wday (nth 6 (decode-time date)))
10397 delta)
10398 (if wday1
10399 (progn
10400 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10401 (if (= dir ?-) (setq delta (- delta 7)))
10402 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10403 (list delta "d" rel))
10404 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10406 (defun org-eval-in-calendar (form &optional keepdate)
10407 "Eval FORM in the calendar window and return to current window.
10408 Also, store the cursor date in variable org-ans2."
10409 (let ((sw (selected-window)))
10410 (select-window (get-buffer-window "*Calendar*"))
10411 (eval form)
10412 (when (and (not keepdate) (calendar-cursor-to-date))
10413 (let* ((date (calendar-cursor-to-date))
10414 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10415 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10416 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10417 (select-window sw)))
10419 ; ;; Update the prompt to show new default date
10420 ; (save-excursion
10421 ; (goto-char (point-min))
10422 ; (when (and org-ans2
10423 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10424 ; (get-text-property (match-end 0) 'field))
10425 ; (let ((inhibit-read-only t))
10426 ; (replace-match (concat "[" org-ans2 "]") t t)
10427 ; (add-text-properties (point-min) (1+ (match-end 0))
10428 ; (text-properties-at (1+ (point-min)))))))))
10430 (defun org-calendar-select ()
10431 "Return to `org-read-date' with the date currently selected.
10432 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10433 (interactive)
10434 (when (calendar-cursor-to-date)
10435 (let* ((date (calendar-cursor-to-date))
10436 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10437 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10438 (if (active-minibuffer-window) (exit-minibuffer))))
10440 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10441 "Insert a date stamp for the date given by the internal TIME.
10442 WITH-HM means, use the stamp format that includes the time of the day.
10443 INACTIVE means use square brackets instead of angular ones, so that the
10444 stamp will not contribute to the agenda.
10445 PRE and POST are optional strings to be inserted before and after the
10446 stamp.
10447 The command returns the inserted time stamp."
10448 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10449 stamp)
10450 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10451 (insert-before-markers (or pre ""))
10452 (insert-before-markers (setq stamp (format-time-string fmt time)))
10453 (when (listp extra)
10454 (setq extra (car extra))
10455 (if (and (stringp extra)
10456 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10457 (setq extra (format "-%02d:%02d"
10458 (string-to-number (match-string 1 extra))
10459 (string-to-number (match-string 2 extra))))
10460 (setq extra nil)))
10461 (when extra
10462 (backward-char 1)
10463 (insert-before-markers extra)
10464 (forward-char 1))
10465 (insert-before-markers (or post ""))
10466 stamp))
10468 (defun org-toggle-time-stamp-overlays ()
10469 "Toggle the use of custom time stamp formats."
10470 (interactive)
10471 (setq org-display-custom-times (not org-display-custom-times))
10472 (unless org-display-custom-times
10473 (let ((p (point-min)) (bmp (buffer-modified-p)))
10474 (while (setq p (next-single-property-change p 'display))
10475 (if (and (get-text-property p 'display)
10476 (eq (get-text-property p 'face) 'org-date))
10477 (remove-text-properties
10478 p (setq p (next-single-property-change p 'display))
10479 '(display t))))
10480 (set-buffer-modified-p bmp)))
10481 (if (featurep 'xemacs)
10482 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10483 (org-restart-font-lock)
10484 (setq org-table-may-need-update t)
10485 (if org-display-custom-times
10486 (message "Time stamps are overlayed with custom format")
10487 (message "Time stamp overlays removed")))
10489 (defun org-display-custom-time (beg end)
10490 "Overlay modified time stamp format over timestamp between BEG and END."
10491 (let* ((ts (buffer-substring beg end))
10492 t1 w1 with-hm tf time str w2 (off 0))
10493 (save-match-data
10494 (setq t1 (org-parse-time-string ts t))
10495 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10496 (setq off (- (match-end 0) (match-beginning 0)))))
10497 (setq end (- end off))
10498 (setq w1 (- end beg)
10499 with-hm (and (nth 1 t1) (nth 2 t1))
10500 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10501 time (org-fix-decoded-time t1)
10502 str (org-add-props
10503 (format-time-string
10504 (substring tf 1 -1) (apply 'encode-time time))
10505 nil 'mouse-face 'highlight)
10506 w2 (length str))
10507 (if (not (= w2 w1))
10508 (add-text-properties (1+ beg) (+ 2 beg)
10509 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10510 (if (featurep 'xemacs)
10511 (progn
10512 (put-text-property beg end 'invisible t)
10513 (put-text-property beg end 'end-glyph (make-glyph str)))
10514 (put-text-property beg end 'display str))))
10516 (defun org-translate-time (string)
10517 "Translate all timestamps in STRING to custom format.
10518 But do this only if the variable `org-display-custom-times' is set."
10519 (when org-display-custom-times
10520 (save-match-data
10521 (let* ((start 0)
10522 (re org-ts-regexp-both)
10523 t1 with-hm inactive tf time str beg end)
10524 (while (setq start (string-match re string start))
10525 (setq beg (match-beginning 0)
10526 end (match-end 0)
10527 t1 (save-match-data
10528 (org-parse-time-string (substring string beg end) t))
10529 with-hm (and (nth 1 t1) (nth 2 t1))
10530 inactive (equal (substring string beg (1+ beg)) "[")
10531 tf (funcall (if with-hm 'cdr 'car)
10532 org-time-stamp-custom-formats)
10533 time (org-fix-decoded-time t1)
10534 str (format-time-string
10535 (concat
10536 (if inactive "[" "<") (substring tf 1 -1)
10537 (if inactive "]" ">"))
10538 (apply 'encode-time time))
10539 string (replace-match str t t string)
10540 start (+ start (length str)))))))
10541 string)
10543 (defun org-fix-decoded-time (time)
10544 "Set 0 instead of nil for the first 6 elements of time.
10545 Don't touch the rest."
10546 (let ((n 0))
10547 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10549 (defun org-days-to-time (timestamp-string)
10550 "Difference between TIMESTAMP-STRING and now in days."
10551 (- (time-to-days (org-time-string-to-time timestamp-string))
10552 (time-to-days (current-time))))
10554 (defun org-deadline-close (timestamp-string &optional ndays)
10555 "Is the time in TIMESTAMP-STRING close to the current date?"
10556 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10557 (and (< (org-days-to-time timestamp-string) ndays)
10558 (not (org-entry-is-done-p))))
10560 (defun org-get-wdays (ts)
10561 "Get the deadline lead time appropriate for timestring TS."
10562 (cond
10563 ((<= org-deadline-warning-days 0)
10564 ;; 0 or negative, enforce this value no matter what
10565 (- org-deadline-warning-days))
10566 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10567 ;; lead time is specified.
10568 (floor (* (string-to-number (match-string 1 ts))
10569 (cdr (assoc (match-string 2 ts)
10570 '(("d" . 1) ("w" . 7)
10571 ("m" . 30.4) ("y" . 365.25)))))))
10572 ;; go for the default.
10573 (t org-deadline-warning-days)))
10575 (defun org-calendar-select-mouse (ev)
10576 "Return to `org-read-date' with the date currently selected.
10577 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10578 (interactive "e")
10579 (mouse-set-point ev)
10580 (when (calendar-cursor-to-date)
10581 (let* ((date (calendar-cursor-to-date))
10582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10583 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10584 (if (active-minibuffer-window) (exit-minibuffer))))
10586 (defun org-check-deadlines (ndays)
10587 "Check if there are any deadlines due or past due.
10588 A deadline is considered due if it happens within `org-deadline-warning-days'
10589 days from today's date. If the deadline appears in an entry marked DONE,
10590 it is not shown. The prefix arg NDAYS can be used to test that many
10591 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10592 (interactive "P")
10593 (let* ((org-warn-days
10594 (cond
10595 ((equal ndays '(4)) 100000)
10596 (ndays (prefix-numeric-value ndays))
10597 (t (abs org-deadline-warning-days))))
10598 (case-fold-search nil)
10599 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10600 (callback
10601 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10603 (message "%d deadlines past-due or due within %d days"
10604 (org-occur regexp nil callback)
10605 org-warn-days)))
10607 (defun org-check-before-date (date)
10608 "Check if there are deadlines or scheduled entries before DATE."
10609 (interactive (list (org-read-date)))
10610 (let ((case-fold-search nil)
10611 (regexp (concat "\\<\\(" org-deadline-string
10612 "\\|" org-scheduled-string
10613 "\\) *<\\([^>]+\\)>"))
10614 (callback
10615 (lambda () (time-less-p
10616 (org-time-string-to-time (match-string 2))
10617 (org-time-string-to-time date)))))
10618 (message "%d entries before %s"
10619 (org-occur regexp nil callback) date)))
10621 (defun org-evaluate-time-range (&optional to-buffer)
10622 "Evaluate a time range by computing the difference between start and end.
10623 Normally the result is just printed in the echo area, but with prefix arg
10624 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10625 If the time range is actually in a table, the result is inserted into the
10626 next column.
10627 For time difference computation, a year is assumed to be exactly 365
10628 days in order to avoid rounding problems."
10629 (interactive "P")
10631 (org-clock-update-time-maybe)
10632 (save-excursion
10633 (unless (org-at-date-range-p t)
10634 (goto-char (point-at-bol))
10635 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10636 (if (not (org-at-date-range-p t))
10637 (error "Not at a time-stamp range, and none found in current line")))
10638 (let* ((ts1 (match-string 1))
10639 (ts2 (match-string 2))
10640 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10641 (match-end (match-end 0))
10642 (time1 (org-time-string-to-time ts1))
10643 (time2 (org-time-string-to-time ts2))
10644 (t1 (time-to-seconds time1))
10645 (t2 (time-to-seconds time2))
10646 (diff (abs (- t2 t1)))
10647 (negative (< (- t2 t1) 0))
10648 ;; (ys (floor (* 365 24 60 60)))
10649 (ds (* 24 60 60))
10650 (hs (* 60 60))
10651 (fy "%dy %dd %02d:%02d")
10652 (fy1 "%dy %dd")
10653 (fd "%dd %02d:%02d")
10654 (fd1 "%dd")
10655 (fh "%02d:%02d")
10656 y d h m align)
10657 (if havetime
10658 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10660 d (floor (/ diff ds)) diff (mod diff ds)
10661 h (floor (/ diff hs)) diff (mod diff hs)
10662 m (floor (/ diff 60)))
10663 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10665 d (floor (+ (/ diff ds) 0.5))
10666 h 0 m 0))
10667 (if (not to-buffer)
10668 (message "%s" (org-make-tdiff-string y d h m))
10669 (if (org-at-table-p)
10670 (progn
10671 (goto-char match-end)
10672 (setq align t)
10673 (and (looking-at " *|") (goto-char (match-end 0))))
10674 (goto-char match-end))
10675 (if (looking-at
10676 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10677 (replace-match ""))
10678 (if negative (insert " -"))
10679 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10680 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10681 (insert " " (format fh h m))))
10682 (if align (org-table-align))
10683 (message "Time difference inserted")))))
10685 (defun org-make-tdiff-string (y d h m)
10686 (let ((fmt "")
10687 (l nil))
10688 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10689 l (push y l)))
10690 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10691 l (push d l)))
10692 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10693 l (push h l)))
10694 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10695 l (push m l)))
10696 (apply 'format fmt (nreverse l))))
10698 (defun org-time-string-to-time (s)
10699 (apply 'encode-time (org-parse-time-string s)))
10701 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10702 "Convert a time stamp to an absolute day number.
10703 If there is a specifyer for a cyclic time stamp, get the closest date to
10704 DAYNR.
10705 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10706 (cond
10707 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10708 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10709 daynr
10710 (+ daynr 1000)))
10711 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10712 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10713 (time-to-days (current-time))) (match-string 0 s)
10714 prefer show-all))
10715 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10717 (defun org-days-to-iso-week (days)
10718 "Return the iso week number."
10719 (require 'cal-iso)
10720 (car (calendar-iso-from-absolute days)))
10722 (defun org-small-year-to-year (year)
10723 "Convert 2-digit years into 4-digit years.
10724 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10725 The year 2000 cannot be abbreviated. Any year lager than 99
10726 is retrned unchanged."
10727 (if (< year 38)
10728 (setq year (+ 2000 year))
10729 (if (< year 100)
10730 (setq year (+ 1900 year))))
10731 year)
10733 (defun org-time-from-absolute (d)
10734 "Return the time corresponding to date D.
10735 D may be an absolute day number, or a calendar-type list (month day year)."
10736 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10737 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10739 (defun org-calendar-holiday ()
10740 "List of holidays, for Diary display in Org-mode."
10741 (require 'holidays)
10742 (let ((hl (funcall
10743 (if (fboundp 'calendar-check-holidays)
10744 'calendar-check-holidays 'check-calendar-holidays) date)))
10745 (if hl (mapconcat 'identity hl "; "))))
10747 (defun org-diary-sexp-entry (sexp entry date)
10748 "Process a SEXP diary ENTRY for DATE."
10749 (require 'diary-lib)
10750 (let ((result (if calendar-debug-sexp
10751 (let ((stack-trace-on-error t))
10752 (eval (car (read-from-string sexp))))
10753 (condition-case nil
10754 (eval (car (read-from-string sexp)))
10755 (error
10756 (beep)
10757 (message "Bad sexp at line %d in %s: %s"
10758 (org-current-line)
10759 (buffer-file-name) sexp)
10760 (sleep-for 2))))))
10761 (cond ((stringp result) result)
10762 ((and (consp result)
10763 (stringp (cdr result))) (cdr result))
10764 (result entry)
10765 (t nil))))
10767 (defun org-diary-to-ical-string (frombuf)
10768 "Get iCalendar entries from diary entries in buffer FROMBUF.
10769 This uses the icalendar.el library."
10770 (let* ((tmpdir (if (featurep 'xemacs)
10771 (temp-directory)
10772 temporary-file-directory))
10773 (tmpfile (make-temp-name
10774 (expand-file-name "orgics" tmpdir)))
10775 buf rtn b e)
10776 (save-excursion
10777 (set-buffer frombuf)
10778 (icalendar-export-region (point-min) (point-max) tmpfile)
10779 (setq buf (find-buffer-visiting tmpfile))
10780 (set-buffer buf)
10781 (goto-char (point-min))
10782 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10783 (setq b (match-beginning 0)))
10784 (goto-char (point-max))
10785 (if (re-search-backward "^END:VEVENT" nil t)
10786 (setq e (match-end 0)))
10787 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10788 (kill-buffer buf)
10789 (kill-buffer frombuf)
10790 (delete-file tmpfile)
10791 rtn))
10793 (defun org-closest-date (start current change prefer show-all)
10794 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10795 When PREFER is `past' return a date that is either CURRENT or past.
10796 When PREFER is `future', return a date that is either CURRENT or future.
10797 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10798 ;; Make the proper lists from the dates
10799 (catch 'exit
10800 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10801 dn dw sday cday n1 n2
10802 d m y y1 y2 date1 date2 nmonths nm ny m2)
10804 (setq start (org-date-to-gregorian start)
10805 current (org-date-to-gregorian
10806 (if show-all
10807 current
10808 (time-to-days (current-time))))
10809 sday (calendar-absolute-from-gregorian start)
10810 cday (calendar-absolute-from-gregorian current))
10812 (if (<= cday sday) (throw 'exit sday))
10814 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10815 (setq dn (string-to-number (match-string 1 change))
10816 dw (cdr (assoc (match-string 2 change) a1)))
10817 (error "Invalid change specifyer: %s" change))
10818 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10819 (cond
10820 ((eq dw 'day)
10821 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10822 n2 (+ n1 dn)))
10823 ((eq dw 'year)
10824 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10825 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10826 (setq date1 (list m d y1)
10827 n1 (calendar-absolute-from-gregorian date1)
10828 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10829 n2 (calendar-absolute-from-gregorian date2)))
10830 ((eq dw 'month)
10831 ;; approx number of month between the tow dates
10832 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10833 ;; How often does dn fit in there?
10834 (setq d (nth 1 start) m (car start) y (nth 2 start)
10835 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10836 m (+ m nm)
10837 ny (floor (/ m 12))
10838 y (+ y ny)
10839 m (- m (* ny 12)))
10840 (while (> m 12) (setq m (- m 12) y (1+ y)))
10841 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10842 (setq m2 (+ m dn) y2 y)
10843 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10844 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10845 (while (< n2 cday)
10846 (setq n1 n2 m m2 y y2)
10847 (setq m2 (+ m dn) y2 y)
10848 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10849 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10851 (if show-all
10852 (cond
10853 ((eq prefer 'past) n1)
10854 ((eq prefer 'future) (if (= cday n1) n1 n2))
10855 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10856 (cond
10857 ((eq prefer 'past) n1)
10858 ((eq prefer 'future) (if (= cday n1) n1 n2))
10859 (t (if (= cday n1) n1 n2)))))))
10861 (defun org-date-to-gregorian (date)
10862 "Turn any specification of DATE into a gregorian date for the calendar."
10863 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10864 ((and (listp date) (= (length date) 3)) date)
10865 ((stringp date)
10866 (setq date (org-parse-time-string date))
10867 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10868 ((listp date)
10869 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10871 (defun org-parse-time-string (s &optional nodefault)
10872 "Parse the standard Org-mode time string.
10873 This should be a lot faster than the normal `parse-time-string'.
10874 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10875 hour and minute fields will be nil if not given."
10876 (if (string-match org-ts-regexp0 s)
10877 (list 0
10878 (if (or (match-beginning 8) (not nodefault))
10879 (string-to-number (or (match-string 8 s) "0")))
10880 (if (or (match-beginning 7) (not nodefault))
10881 (string-to-number (or (match-string 7 s) "0")))
10882 (string-to-number (match-string 4 s))
10883 (string-to-number (match-string 3 s))
10884 (string-to-number (match-string 2 s))
10885 nil nil nil)
10886 (make-list 9 0)))
10888 (defun org-timestamp-up (&optional arg)
10889 "Increase the date item at the cursor by one.
10890 If the cursor is on the year, change the year. If it is on the month or
10891 the day, change that.
10892 With prefix ARG, change by that many units."
10893 (interactive "p")
10894 (org-timestamp-change (prefix-numeric-value arg)))
10896 (defun org-timestamp-down (&optional arg)
10897 "Decrease the date item at the cursor by one.
10898 If the cursor is on the year, change the year. If it is on the month or
10899 the day, change that.
10900 With prefix ARG, change by that many units."
10901 (interactive "p")
10902 (org-timestamp-change (- (prefix-numeric-value arg))))
10904 (defun org-timestamp-up-day (&optional arg)
10905 "Increase the date in the time stamp by one day.
10906 With prefix ARG, change that many days."
10907 (interactive "p")
10908 (if (and (not (org-at-timestamp-p t))
10909 (org-on-heading-p))
10910 (org-todo 'up)
10911 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10913 (defun org-timestamp-down-day (&optional arg)
10914 "Decrease the date in the time stamp by one day.
10915 With prefix ARG, change that many days."
10916 (interactive "p")
10917 (if (and (not (org-at-timestamp-p t))
10918 (org-on-heading-p))
10919 (org-todo 'down)
10920 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10922 (defun org-at-timestamp-p (&optional inactive-ok)
10923 "Determine if the cursor is in or at a timestamp."
10924 (interactive)
10925 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10926 (pos (point))
10927 (ans (or (looking-at tsr)
10928 (save-excursion
10929 (skip-chars-backward "^[<\n\r\t")
10930 (if (> (point) (point-min)) (backward-char 1))
10931 (and (looking-at tsr)
10932 (> (- (match-end 0) pos) -1))))))
10933 (and ans
10934 (boundp 'org-ts-what)
10935 (setq org-ts-what
10936 (cond
10937 ((= pos (match-beginning 0)) 'bracket)
10938 ((= pos (1- (match-end 0))) 'bracket)
10939 ((org-pos-in-match-range pos 2) 'year)
10940 ((org-pos-in-match-range pos 3) 'month)
10941 ((org-pos-in-match-range pos 7) 'hour)
10942 ((org-pos-in-match-range pos 8) 'minute)
10943 ((or (org-pos-in-match-range pos 4)
10944 (org-pos-in-match-range pos 5)) 'day)
10945 ((and (> pos (or (match-end 8) (match-end 5)))
10946 (< pos (match-end 0)))
10947 (- pos (or (match-end 8) (match-end 5))))
10948 (t 'day))))
10949 ans))
10951 (defun org-toggle-timestamp-type ()
10952 "Toggle the type (<active> or [inactive]) of a time stamp."
10953 (interactive)
10954 (when (org-at-timestamp-p t)
10955 (save-excursion
10956 (goto-char (match-beginning 0))
10957 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10958 (goto-char (1- (match-end 0)))
10959 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10960 (message "Timestamp is now %sactive"
10961 (if (equal (char-before) ?>) "in" ""))))
10963 (defun org-timestamp-change (n &optional what)
10964 "Change the date in the time stamp at point.
10965 The date will be changed by N times WHAT. WHAT can be `day', `month',
10966 `year', `minute', `second'. If WHAT is not given, the cursor position
10967 in the timestamp determines what will be changed."
10968 (let ((pos (point))
10969 with-hm inactive
10970 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10971 org-ts-what
10972 extra rem
10973 ts time time0)
10974 (if (not (org-at-timestamp-p t))
10975 (error "Not at a timestamp"))
10976 (if (and (not what) (eq org-ts-what 'bracket))
10977 (org-toggle-timestamp-type)
10978 (if (and (not what) (not (eq org-ts-what 'day))
10979 org-display-custom-times
10980 (get-text-property (point) 'display)
10981 (not (get-text-property (1- (point)) 'display)))
10982 (setq org-ts-what 'day))
10983 (setq org-ts-what (or what org-ts-what)
10984 inactive (= (char-after (match-beginning 0)) ?\[)
10985 ts (match-string 0))
10986 (replace-match "")
10987 (if (string-match
10988 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10990 (setq extra (match-string 1 ts)))
10991 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10992 (setq with-hm t))
10993 (setq time0 (org-parse-time-string ts))
10994 (when (and (eq org-ts-what 'minute)
10995 (eq current-prefix-arg nil))
10996 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10997 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10998 (setcar (cdr time0) (+ (nth 1 time0)
10999 (if (> n 0) (- rem) (- dm rem))))))
11000 (setq time
11001 (encode-time (or (car time0) 0)
11002 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11003 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11004 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11005 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11006 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11007 (nthcdr 6 time0)))
11008 (when (integerp org-ts-what)
11009 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11010 (if (eq what 'calendar)
11011 (let ((cal-date (org-get-date-from-calendar)))
11012 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11013 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11014 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11015 (setcar time0 (or (car time0) 0))
11016 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11017 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11018 (setq time (apply 'encode-time time0))))
11019 (setq org-last-changed-timestamp
11020 (org-insert-time-stamp time with-hm inactive nil nil extra))
11021 (org-clock-update-time-maybe)
11022 (goto-char pos)
11023 ;; Try to recenter the calendar window, if any
11024 (if (and org-calendar-follow-timestamp-change
11025 (get-buffer-window "*Calendar*" t)
11026 (memq org-ts-what '(day month year)))
11027 (org-recenter-calendar (time-to-days time))))))
11029 (defun org-modify-ts-extra (s pos n dm)
11030 "Change the different parts of the lead-time and repeat fields in timestamp."
11031 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11032 ng h m new rem)
11033 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11034 (cond
11035 ((or (org-pos-in-match-range pos 2)
11036 (org-pos-in-match-range pos 3))
11037 (setq m (string-to-number (match-string 3 s))
11038 h (string-to-number (match-string 2 s)))
11039 (if (org-pos-in-match-range pos 2)
11040 (setq h (+ h n))
11041 (setq n (* dm (org-no-warnings (signum n))))
11042 (when (not (= 0 (setq rem (% m dm))))
11043 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11044 (setq m (+ m n)))
11045 (if (< m 0) (setq m (+ m 60) h (1- h)))
11046 (if (> m 59) (setq m (- m 60) h (1+ h)))
11047 (setq h (min 24 (max 0 h)))
11048 (setq ng 1 new (format "-%02d:%02d" h m)))
11049 ((org-pos-in-match-range pos 6)
11050 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11051 ((org-pos-in-match-range pos 5)
11052 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11054 ((org-pos-in-match-range pos 9)
11055 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11056 ((org-pos-in-match-range pos 8)
11057 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11059 (when ng
11060 (setq s (concat
11061 (substring s 0 (match-beginning ng))
11063 (substring s (match-end ng))))))
11066 (defun org-recenter-calendar (date)
11067 "If the calendar is visible, recenter it to DATE."
11068 (let* ((win (selected-window))
11069 (cwin (get-buffer-window "*Calendar*" t))
11070 (calendar-move-hook nil))
11071 (when cwin
11072 (select-window cwin)
11073 (calendar-goto-date (if (listp date) date
11074 (calendar-gregorian-from-absolute date)))
11075 (select-window win))))
11077 (defun org-goto-calendar (&optional arg)
11078 "Go to the Emacs calendar at the current date.
11079 If there is a time stamp in the current line, go to that date.
11080 A prefix ARG can be used to force the current date."
11081 (interactive "P")
11082 (let ((tsr org-ts-regexp) diff
11083 (calendar-move-hook nil)
11084 (calendar-view-holidays-initially-flag nil)
11085 (view-calendar-holidays-initially nil)
11086 (calendar-view-diary-initially-flag nil)
11087 (view-diary-entries-initially nil))
11088 (if (or (org-at-timestamp-p)
11089 (save-excursion
11090 (beginning-of-line 1)
11091 (looking-at (concat ".*" tsr))))
11092 (let ((d1 (time-to-days (current-time)))
11093 (d2 (time-to-days
11094 (org-time-string-to-time (match-string 1)))))
11095 (setq diff (- d2 d1))))
11096 (calendar)
11097 (calendar-goto-today)
11098 (if (and diff (not arg)) (calendar-forward-day diff))))
11100 (defun org-get-date-from-calendar ()
11101 "Return a list (month day year) of date at point in calendar."
11102 (with-current-buffer "*Calendar*"
11103 (save-match-data
11104 (calendar-cursor-to-date))))
11106 (defun org-date-from-calendar ()
11107 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11108 If there is already a time stamp at the cursor position, update it."
11109 (interactive)
11110 (if (org-at-timestamp-p t)
11111 (org-timestamp-change 0 'calendar)
11112 (let ((cal-date (org-get-date-from-calendar)))
11113 (org-insert-time-stamp
11114 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11116 (defun org-minutes-to-hh:mm-string (m)
11117 "Compute H:MM from a number of minutes."
11118 (let ((h (/ m 60)))
11119 (setq m (- m (* 60 h)))
11120 (format "%d:%02d" h m)))
11122 (defun org-hh:mm-string-to-minutes (s)
11123 "Convert a string H:MM to a number of minutes."
11124 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11125 (+ (* (string-to-number (match-string 1 s)) 60)
11126 (string-to-number (match-string 2 s)))
11129 ;;;; Agenda files
11131 ;;;###autoload
11132 (defun org-iswitchb (&optional arg)
11133 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11134 With a prefix argument, restrict available to files.
11135 With two prefix arguments, restrict available buffers to agenda files.
11137 Due to some yet unresolved reason, global function
11138 `iswitchb-mode' needs to be active for this function to work."
11139 (interactive "P")
11140 (require 'iswitchb)
11141 (let ((enabled iswitchb-mode) blist)
11142 (or enabled (iswitchb-mode 1))
11143 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11144 ((equal arg '(16)) (org-buffer-list 'agenda))
11145 (t (org-buffer-list))))
11146 (unwind-protect
11147 (let ((iswitchb-make-buflist-hook
11148 (lambda ()
11149 (setq iswitchb-temp-buflist
11150 (mapcar 'buffer-name blist)))))
11151 (switch-to-buffer
11152 (iswitchb-read-buffer
11153 "Switch-to: " nil t))
11154 (or enabled (iswitchb-mode -1))))))
11156 (defun org-buffer-list (&optional predicate tmp)
11157 "Return a list of Org buffers.
11158 PREDICATE can be either 'export, 'files or 'agenda.
11160 'export restrict the list to Export buffers.
11161 'files restrict the list to buffers visiting Org files.
11162 'agenda restrict the list to buffers visiting agenda files.
11164 If TMP is non-nil, don't include temporary buffers."
11165 (let (filter blist)
11166 (setq filter
11167 (cond ((eq predicate 'files) "\.org$")
11168 ((eq predicate 'export) "\*Org .*Export")
11169 (t "\*Org \\|\.org$")))
11170 (setq blist
11171 (mapcar
11172 (lambda(b)
11173 (let ((bname (buffer-name b))
11174 (bfile (buffer-file-name b)))
11175 (if (and (string-match filter bname)
11176 (if (eq predicate 'agenda)
11177 (member bfile
11178 (mapcar (lambda(f) (file-truename f))
11179 org-agenda-files)) t)
11180 (if tmp (not (string-match "tmp" bname)) t)) b)))
11181 (buffer-list)))
11182 (delete nil blist)))
11184 (defun org-agenda-files (&optional unrestricted ext)
11185 "Get the list of agenda files.
11186 Optional UNRESTRICTED means return the full list even if a restriction
11187 is currently in place.
11188 When EXT is non-nil, try to add all files that are created by adding EXT
11189 to the file nemes. Basically, this is a way to add the archive files
11190 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11191 a string, \"_archive\" will be used."
11192 (let ((files
11193 (cond
11194 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11195 ((stringp org-agenda-files) (org-read-agenda-file-list))
11196 ((listp org-agenda-files) org-agenda-files)
11197 (t (error "Invalid value of `org-agenda-files'")))))
11198 (setq files (apply 'append
11199 (mapcar (lambda (f)
11200 (if (file-directory-p f)
11201 (directory-files
11202 f t org-agenda-file-regexp)
11203 (list f)))
11204 files)))
11205 (when org-agenda-skip-unavailable-files
11206 (setq files (delq nil
11207 (mapcar (function
11208 (lambda (file)
11209 (and (file-readable-p file) file)))
11210 files))))
11211 (when ext
11212 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11213 ext "_archive"))
11214 (setq files (apply 'append
11215 (mapcar
11216 (lambda (f)
11217 (if (file-exists-p (concat f ext))
11218 (list f (concat f ext))
11219 (list f)))
11220 files))))
11221 files))
11223 (defun org-edit-agenda-file-list ()
11224 "Edit the list of agenda files.
11225 Depending on setup, this either uses customize to edit the variable
11226 `org-agenda-files', or it visits the file that is holding the list. In the
11227 latter case, the buffer is set up in a way that saving it automatically kills
11228 the buffer and restores the previous window configuration."
11229 (interactive)
11230 (if (stringp org-agenda-files)
11231 (let ((cw (current-window-configuration)))
11232 (find-file org-agenda-files)
11233 (org-set-local 'org-window-configuration cw)
11234 (org-add-hook 'after-save-hook
11235 (lambda ()
11236 (set-window-configuration
11237 (prog1 org-window-configuration
11238 (kill-buffer (current-buffer))))
11239 (org-install-agenda-files-menu)
11240 (message "New agenda file list installed"))
11241 nil 'local)
11242 (message "%s" (substitute-command-keys
11243 "Edit list and finish with \\[save-buffer]")))
11244 (customize-variable 'org-agenda-files)))
11246 (defun org-store-new-agenda-file-list (list)
11247 "Set new value for the agenda file list and save it correcly."
11248 (if (stringp org-agenda-files)
11249 (let ((f org-agenda-files) b)
11250 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11251 (with-temp-file f
11252 (insert (mapconcat 'identity list "\n") "\n")))
11253 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11254 (setq org-agenda-files list)
11255 (customize-save-variable 'org-agenda-files org-agenda-files))))
11257 (defun org-read-agenda-file-list ()
11258 "Read the list of agenda files from a file."
11259 (when (file-directory-p org-agenda-files)
11260 (error "`org-agenda-files' cannot be a single directory"))
11261 (when (stringp org-agenda-files)
11262 (with-temp-buffer
11263 (insert-file-contents org-agenda-files)
11264 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11267 ;;;###autoload
11268 (defun org-cycle-agenda-files ()
11269 "Cycle through the files in `org-agenda-files'.
11270 If the current buffer visits an agenda file, find the next one in the list.
11271 If the current buffer does not, find the first agenda file."
11272 (interactive)
11273 (let* ((fs (org-agenda-files t))
11274 (files (append fs (list (car fs))))
11275 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11276 file)
11277 (unless files (error "No agenda files"))
11278 (catch 'exit
11279 (while (setq file (pop files))
11280 (if (equal (file-truename file) tcf)
11281 (when (car files)
11282 (find-file (car files))
11283 (throw 'exit t))))
11284 (find-file (car fs)))
11285 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11287 (defun org-agenda-file-to-front (&optional to-end)
11288 "Move/add the current file to the top of the agenda file list.
11289 If the file is not present in the list, it is added to the front. If it is
11290 present, it is moved there. With optional argument TO-END, add/move to the
11291 end of the list."
11292 (interactive "P")
11293 (let ((org-agenda-skip-unavailable-files nil)
11294 (file-alist (mapcar (lambda (x)
11295 (cons (file-truename x) x))
11296 (org-agenda-files t)))
11297 (ctf (file-truename buffer-file-name))
11298 x had)
11299 (setq x (assoc ctf file-alist) had x)
11301 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11302 (if to-end
11303 (setq file-alist (append (delq x file-alist) (list x)))
11304 (setq file-alist (cons x (delq x file-alist))))
11305 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11306 (org-install-agenda-files-menu)
11307 (message "File %s to %s of agenda file list"
11308 (if had "moved" "added") (if to-end "end" "front"))))
11310 (defun org-remove-file (&optional file)
11311 "Remove current file from the list of files in variable `org-agenda-files'.
11312 These are the files which are being checked for agenda entries.
11313 Optional argument FILE means, use this file instead of the current."
11314 (interactive)
11315 (let* ((org-agenda-skip-unavailable-files nil)
11316 (file (or file buffer-file-name))
11317 (true-file (file-truename file))
11318 (afile (abbreviate-file-name file))
11319 (files (delq nil (mapcar
11320 (lambda (x)
11321 (if (equal true-file
11322 (file-truename x))
11323 nil x))
11324 (org-agenda-files t)))))
11325 (if (not (= (length files) (length (org-agenda-files t))))
11326 (progn
11327 (org-store-new-agenda-file-list files)
11328 (org-install-agenda-files-menu)
11329 (message "Removed file: %s" afile))
11330 (message "File was not in list: %s (not removed)" afile))))
11332 (defun org-file-menu-entry (file)
11333 (vector file (list 'find-file file) t))
11335 (defun org-check-agenda-file (file)
11336 "Make sure FILE exists. If not, ask user what to do."
11337 (when (not (file-exists-p file))
11338 (message "non-existent file %s. [R]emove from list or [A]bort?"
11339 (abbreviate-file-name file))
11340 (let ((r (downcase (read-char-exclusive))))
11341 (cond
11342 ((equal r ?r)
11343 (org-remove-file file)
11344 (throw 'nextfile t))
11345 (t (error "Abort"))))))
11347 (defun org-get-agenda-file-buffer (file)
11348 "Get a buffer visiting FILE. If the buffer needs to be created, add
11349 it to the list of buffers which might be released later."
11350 (let ((buf (org-find-base-buffer-visiting file)))
11351 (if buf
11352 buf ; just return it
11353 ;; Make a new buffer and remember it
11354 (setq buf (find-file-noselect file))
11355 (if buf (push buf org-agenda-new-buffers))
11356 buf)))
11358 (defun org-release-buffers (blist)
11359 "Release all buffers in list, asking the user for confirmation when needed.
11360 When a buffer is unmodified, it is just killed. When modified, it is saved
11361 \(if the user agrees) and then killed."
11362 (let (buf file)
11363 (while (setq buf (pop blist))
11364 (setq file (buffer-file-name buf))
11365 (when (and (buffer-modified-p buf)
11366 file
11367 (y-or-n-p (format "Save file %s? " file)))
11368 (with-current-buffer buf (save-buffer)))
11369 (kill-buffer buf))))
11371 (defun org-prepare-agenda-buffers (files)
11372 "Create buffers for all agenda files, protect archived trees and comments."
11373 (interactive)
11374 (let ((pa '(:org-archived t))
11375 (pc '(:org-comment t))
11376 (pall '(:org-archived t :org-comment t))
11377 (inhibit-read-only t)
11378 (rea (concat ":" org-archive-tag ":"))
11379 bmp file re)
11380 (save-excursion
11381 (save-restriction
11382 (while (setq file (pop files))
11383 (if (bufferp file)
11384 (set-buffer file)
11385 (org-check-agenda-file file)
11386 (set-buffer (org-get-agenda-file-buffer file)))
11387 (widen)
11388 (setq bmp (buffer-modified-p))
11389 (org-refresh-category-properties)
11390 (setq org-todo-keywords-for-agenda
11391 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11392 (setq org-done-keywords-for-agenda
11393 (append org-done-keywords-for-agenda org-done-keywords))
11394 (save-excursion
11395 (remove-text-properties (point-min) (point-max) pall)
11396 (when org-agenda-skip-archived-trees
11397 (goto-char (point-min))
11398 (while (re-search-forward rea nil t)
11399 (if (org-on-heading-p t)
11400 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11401 (goto-char (point-min))
11402 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11403 (while (re-search-forward re nil t)
11404 (add-text-properties
11405 (match-beginning 0) (org-end-of-subtree t) pc)))
11406 (set-buffer-modified-p bmp))))))
11408 ;;;; Embedded LaTeX
11410 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11411 "Keymap for the minor `org-cdlatex-mode'.")
11413 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11414 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11415 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11416 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11417 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11419 (defvar org-cdlatex-texmathp-advice-is-done nil
11420 "Flag remembering if we have applied the advice to texmathp already.")
11422 (define-minor-mode org-cdlatex-mode
11423 "Toggle the minor `org-cdlatex-mode'.
11424 This mode supports entering LaTeX environment and math in LaTeX fragments
11425 in Org-mode.
11426 \\{org-cdlatex-mode-map}"
11427 nil " OCDL" nil
11428 (when org-cdlatex-mode (require 'cdlatex))
11429 (unless org-cdlatex-texmathp-advice-is-done
11430 (setq org-cdlatex-texmathp-advice-is-done t)
11431 (defadvice texmathp (around org-math-always-on activate)
11432 "Always return t in org-mode buffers.
11433 This is because we want to insert math symbols without dollars even outside
11434 the LaTeX math segments. If Orgmode thinks that point is actually inside
11435 en embedded LaTeX fragement, let texmathp do its job.
11436 \\[org-cdlatex-mode-map]"
11437 (interactive)
11438 (let (p)
11439 (cond
11440 ((not (org-mode-p)) ad-do-it)
11441 ((eq this-command 'cdlatex-math-symbol)
11442 (setq ad-return-value t
11443 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11445 (let ((p (org-inside-LaTeX-fragment-p)))
11446 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11447 (setq ad-return-value t
11448 texmathp-why '("Org-mode embedded math" . 0))
11449 (if p ad-do-it)))))))))
11451 (defun turn-on-org-cdlatex ()
11452 "Unconditionally turn on `org-cdlatex-mode'."
11453 (org-cdlatex-mode 1))
11455 (defun org-inside-LaTeX-fragment-p ()
11456 "Test if point is inside a LaTeX fragment.
11457 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11458 sequence appearing also before point.
11459 Even though the matchers for math are configurable, this function assumes
11460 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11461 delimiters are skipped when they have been removed by customization.
11462 The return value is nil, or a cons cell with the delimiter and
11463 and the position of this delimiter.
11465 This function does a reasonably good job, but can locally be fooled by
11466 for example currency specifications. For example it will assume being in
11467 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11468 fragments that are properly closed, but during editing, we have to live
11469 with the uncertainty caused by missing closing delimiters. This function
11470 looks only before point, not after."
11471 (catch 'exit
11472 (let ((pos (point))
11473 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11474 (lim (progn
11475 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11476 (point)))
11477 dd-on str (start 0) m re)
11478 (goto-char pos)
11479 (when dodollar
11480 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11481 re (nth 1 (assoc "$" org-latex-regexps)))
11482 (while (string-match re str start)
11483 (cond
11484 ((= (match-end 0) (length str))
11485 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11486 ((= (match-end 0) (- (length str) 5))
11487 (throw 'exit nil))
11488 (t (setq start (match-end 0))))))
11489 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11490 (goto-char pos)
11491 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11492 (and (match-beginning 2) (throw 'exit nil))
11493 ;; count $$
11494 (while (re-search-backward "\\$\\$" lim t)
11495 (setq dd-on (not dd-on)))
11496 (goto-char pos)
11497 (if dd-on (cons "$$" m))))))
11500 (defun org-try-cdlatex-tab ()
11501 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11502 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11503 - inside a LaTeX fragment, or
11504 - after the first word in a line, where an abbreviation expansion could
11505 insert a LaTeX environment."
11506 (when org-cdlatex-mode
11507 (cond
11508 ((save-excursion
11509 (skip-chars-backward "a-zA-Z0-9*")
11510 (skip-chars-backward " \t")
11511 (bolp))
11512 (cdlatex-tab) t)
11513 ((org-inside-LaTeX-fragment-p)
11514 (cdlatex-tab) t)
11515 (t nil))))
11517 (defun org-cdlatex-underscore-caret (&optional arg)
11518 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11519 Revert to the normal definition outside of these fragments."
11520 (interactive "P")
11521 (if (org-inside-LaTeX-fragment-p)
11522 (call-interactively 'cdlatex-sub-superscript)
11523 (let (org-cdlatex-mode)
11524 (call-interactively (key-binding (vector last-input-event))))))
11526 (defun org-cdlatex-math-modify (&optional arg)
11527 "Execute `cdlatex-math-modify' in LaTeX fragments.
11528 Revert to the normal definition outside of these fragments."
11529 (interactive "P")
11530 (if (org-inside-LaTeX-fragment-p)
11531 (call-interactively 'cdlatex-math-modify)
11532 (let (org-cdlatex-mode)
11533 (call-interactively (key-binding (vector last-input-event))))))
11535 (defvar org-latex-fragment-image-overlays nil
11536 "List of overlays carrying the images of latex fragments.")
11537 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11539 (defun org-remove-latex-fragment-image-overlays ()
11540 "Remove all overlays with LaTeX fragment images in current buffer."
11541 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11542 (setq org-latex-fragment-image-overlays nil))
11544 (defun org-preview-latex-fragment (&optional subtree)
11545 "Preview the LaTeX fragment at point, or all locally or globally.
11546 If the cursor is in a LaTeX fragment, create the image and overlay
11547 it over the source code. If there is no fragment at point, display
11548 all fragments in the current text, from one headline to the next. With
11549 prefix SUBTREE, display all fragments in the current subtree. With a
11550 double prefix `C-u C-u', or when the cursor is before the first headline,
11551 display all fragments in the buffer.
11552 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11553 (interactive "P")
11554 (org-remove-latex-fragment-image-overlays)
11555 (save-excursion
11556 (save-restriction
11557 (let (beg end at msg)
11558 (cond
11559 ((or (equal subtree '(16))
11560 (not (save-excursion
11561 (re-search-backward (concat "^" outline-regexp) nil t))))
11562 (setq beg (point-min) end (point-max)
11563 msg "Creating images for buffer...%s"))
11564 ((equal subtree '(4))
11565 (org-back-to-heading)
11566 (setq beg (point) end (org-end-of-subtree t)
11567 msg "Creating images for subtree...%s"))
11569 (if (setq at (org-inside-LaTeX-fragment-p))
11570 (goto-char (max (point-min) (- (cdr at) 2)))
11571 (org-back-to-heading))
11572 (setq beg (point) end (progn (outline-next-heading) (point))
11573 msg (if at "Creating image...%s"
11574 "Creating images for entry...%s"))))
11575 (message msg "")
11576 (narrow-to-region beg end)
11577 (goto-char beg)
11578 (org-format-latex
11579 (concat "ltxpng/" (file-name-sans-extension
11580 (file-name-nondirectory
11581 buffer-file-name)))
11582 default-directory 'overlays msg at 'forbuffer)
11583 (message msg "done. Use `C-c C-c' to remove images.")))))
11585 (defvar org-latex-regexps
11586 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11587 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11588 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11589 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11590 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11591 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11592 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11593 "Regular expressions for matching embedded LaTeX.")
11595 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11596 "Replace LaTeX fragments with links to an image, and produce images."
11597 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11598 (let* ((prefixnodir (file-name-nondirectory prefix))
11599 (absprefix (expand-file-name prefix dir))
11600 (todir (file-name-directory absprefix))
11601 (opt org-format-latex-options)
11602 (matchers (plist-get opt :matchers))
11603 (re-list org-latex-regexps)
11604 (cnt 0) txt link beg end re e checkdir
11605 m n block linkfile movefile ov)
11606 ;; Check if there are old images files with this prefix, and remove them
11607 (when (file-directory-p todir)
11608 (mapc 'delete-file
11609 (directory-files
11610 todir 'full
11611 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11612 ;; Check the different regular expressions
11613 (while (setq e (pop re-list))
11614 (setq m (car e) re (nth 1 e) n (nth 2 e)
11615 block (if (nth 3 e) "\n\n" ""))
11616 (when (member m matchers)
11617 (goto-char (point-min))
11618 (while (re-search-forward re nil t)
11619 (when (or (not at) (equal (cdr at) (match-beginning n)))
11620 (setq txt (match-string n)
11621 beg (match-beginning n) end (match-end n)
11622 cnt (1+ cnt)
11623 linkfile (format "%s_%04d.png" prefix cnt)
11624 movefile (format "%s_%04d.png" absprefix cnt)
11625 link (concat block "[[file:" linkfile "]]" block))
11626 (if msg (message msg cnt))
11627 (goto-char beg)
11628 (unless checkdir ; make sure the directory exists
11629 (setq checkdir t)
11630 (or (file-directory-p todir) (make-directory todir)))
11631 (org-create-formula-image
11632 txt movefile opt forbuffer)
11633 (if overlays
11634 (progn
11635 (setq ov (org-make-overlay beg end))
11636 (if (featurep 'xemacs)
11637 (progn
11638 (org-overlay-put ov 'invisible t)
11639 (org-overlay-put
11640 ov 'end-glyph
11641 (make-glyph (vector 'png :file movefile))))
11642 (org-overlay-put
11643 ov 'display
11644 (list 'image :type 'png :file movefile :ascent 'center)))
11645 (push ov org-latex-fragment-image-overlays)
11646 (goto-char end))
11647 (delete-region beg end)
11648 (insert link))))))))
11650 ;; This function borrows from Ganesh Swami's latex2png.el
11651 (defun org-create-formula-image (string tofile options buffer)
11652 (let* ((tmpdir (if (featurep 'xemacs)
11653 (temp-directory)
11654 temporary-file-directory))
11655 (texfilebase (make-temp-name
11656 (expand-file-name "orgtex" tmpdir)))
11657 (texfile (concat texfilebase ".tex"))
11658 (dvifile (concat texfilebase ".dvi"))
11659 (pngfile (concat texfilebase ".png"))
11660 (fnh (if (featurep 'xemacs)
11661 (font-height (get-face-font 'default))
11662 (face-attribute 'default :height nil)))
11663 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11664 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11665 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11666 "Black"))
11667 (bg (or (plist-get options (if buffer :background :html-background))
11668 "Transparent")))
11669 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11670 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11671 (with-temp-file texfile
11672 (insert org-format-latex-header
11673 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11674 (let ((dir default-directory))
11675 (condition-case nil
11676 (progn
11677 (cd tmpdir)
11678 (call-process "latex" nil nil nil texfile))
11679 (error nil))
11680 (cd dir))
11681 (if (not (file-exists-p dvifile))
11682 (progn (message "Failed to create dvi file from %s" texfile) nil)
11683 (call-process "dvipng" nil nil nil
11684 "-E" "-fg" fg "-bg" bg
11685 "-D" dpi
11686 ;;"-x" scale "-y" scale
11687 "-T" "tight"
11688 "-o" pngfile
11689 dvifile)
11690 (if (not (file-exists-p pngfile))
11691 (progn (message "Failed to create png file from %s" texfile) nil)
11692 ;; Use the requested file name and clean up
11693 (copy-file pngfile tofile 'replace)
11694 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11695 (delete-file (concat texfilebase e)))
11696 pngfile))))
11698 (defun org-dvipng-color (attr)
11699 "Return an rgb color specification for dvipng."
11700 (apply 'format "rgb %s %s %s"
11701 (mapcar 'org-normalize-color
11702 (color-values (face-attribute 'default attr nil)))))
11704 (defun org-normalize-color (value)
11705 "Return string to be used as color value for an RGB component."
11706 (format "%g" (/ value 65535.0)))
11709 ;;;; Key bindings
11711 ;; Make `C-c C-x' a prefix key
11712 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11714 ;; TAB key with modifiers
11715 (org-defkey org-mode-map "\C-i" 'org-cycle)
11716 (org-defkey org-mode-map [(tab)] 'org-cycle)
11717 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11718 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11719 (org-defkey org-mode-map "\M-\t" 'org-complete)
11720 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11721 ;; The following line is necessary under Suse GNU/Linux
11722 (unless (featurep 'xemacs)
11723 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11724 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11725 (define-key org-mode-map [backtab] 'org-shifttab)
11727 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11728 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11729 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11731 ;; Cursor keys with modifiers
11732 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11733 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11734 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11735 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11737 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11738 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11739 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11740 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11742 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11743 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11744 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11745 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11747 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11748 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11750 ;;; Extra keys for tty access.
11751 ;; We only set them when really needed because otherwise the
11752 ;; menus don't show the simple keys
11754 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11755 (not window-system))
11756 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11757 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11758 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11759 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11760 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11761 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11762 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11763 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11764 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11765 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11766 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11767 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11768 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11769 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11770 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11771 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11772 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11773 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11774 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11775 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11776 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11777 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11779 ;; All the other keys
11781 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11782 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11783 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11784 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11785 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11786 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11787 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11788 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11789 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11790 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11791 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11792 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11793 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11794 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11795 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11796 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11797 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11798 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11799 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11800 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11801 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11802 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11803 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11804 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11805 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11806 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11807 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11808 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11809 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11810 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11811 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11812 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11813 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11814 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11815 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11816 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11817 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11818 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11819 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11820 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11821 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11822 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11823 (org-defkey org-mode-map "\C-c^" 'org-sort)
11824 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11825 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11826 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11827 (org-defkey org-mode-map "\C-m" 'org-return)
11828 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11829 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11830 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11831 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11832 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11833 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11834 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11835 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11836 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11837 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11838 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11839 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11840 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11841 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11842 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11843 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11845 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11846 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11847 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11848 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11850 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11851 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11852 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11853 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11854 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11855 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11856 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11857 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11858 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11859 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11860 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11861 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11863 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11865 (when (featurep 'xemacs)
11866 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11868 (defvar org-table-auto-blank-field) ; defined in org-table.el
11869 (defun org-self-insert-command (N)
11870 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11871 If the cursor is in a table looking at whitespace, the whitespace is
11872 overwritten, and the table is not marked as requiring realignment."
11873 (interactive "p")
11874 (if (and (org-table-p)
11875 (progn
11876 ;; check if we blank the field, and if that triggers align
11877 (and (featurep 'org-table) org-table-auto-blank-field
11878 (member last-command
11879 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11880 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11881 ;; got extra space, this field does not determine column width
11882 (let (org-table-may-need-update) (org-table-blank-field))
11883 ;; no extra space, this field may determine column width
11884 (org-table-blank-field)))
11886 (eq N 1)
11887 (looking-at "[^|\n]* |"))
11888 (let (org-table-may-need-update)
11889 (goto-char (1- (match-end 0)))
11890 (delete-backward-char 1)
11891 (goto-char (match-beginning 0))
11892 (self-insert-command N))
11893 (setq org-table-may-need-update t)
11894 (self-insert-command N)
11895 (org-fix-tags-on-the-fly)))
11897 (defun org-fix-tags-on-the-fly ()
11898 (when (and (equal (char-after (point-at-bol)) ?*)
11899 (org-on-heading-p))
11900 (org-align-tags-here org-tags-column)))
11902 (defun org-delete-backward-char (N)
11903 "Like `delete-backward-char', insert whitespace at field end in tables.
11904 When deleting backwards, in tables this function will insert whitespace in
11905 front of the next \"|\" separator, to keep the table aligned. The table will
11906 still be marked for re-alignment if the field did fill the entire column,
11907 because, in this case the deletion might narrow the column."
11908 (interactive "p")
11909 (if (and (org-table-p)
11910 (eq N 1)
11911 (string-match "|" (buffer-substring (point-at-bol) (point)))
11912 (looking-at ".*?|"))
11913 (let ((pos (point))
11914 (noalign (looking-at "[^|\n\r]* |"))
11915 (c org-table-may-need-update))
11916 (backward-delete-char N)
11917 (skip-chars-forward "^|")
11918 (insert " ")
11919 (goto-char (1- pos))
11920 ;; noalign: if there were two spaces at the end, this field
11921 ;; does not determine the width of the column.
11922 (if noalign (setq org-table-may-need-update c)))
11923 (backward-delete-char N)
11924 (org-fix-tags-on-the-fly)))
11926 (defun org-delete-char (N)
11927 "Like `delete-char', but insert whitespace at field end in tables.
11928 When deleting characters, in tables this function will insert whitespace in
11929 front of the next \"|\" separator, to keep the table aligned. The table will
11930 still be marked for re-alignment if the field did fill the entire column,
11931 because, in this case the deletion might narrow the column."
11932 (interactive "p")
11933 (if (and (org-table-p)
11934 (not (bolp))
11935 (not (= (char-after) ?|))
11936 (eq N 1))
11937 (if (looking-at ".*?|")
11938 (let ((pos (point))
11939 (noalign (looking-at "[^|\n\r]* |"))
11940 (c org-table-may-need-update))
11941 (replace-match (concat
11942 (substring (match-string 0) 1 -1)
11943 " |"))
11944 (goto-char pos)
11945 ;; noalign: if there were two spaces at the end, this field
11946 ;; does not determine the width of the column.
11947 (if noalign (setq org-table-may-need-update c)))
11948 (delete-char N))
11949 (delete-char N)
11950 (org-fix-tags-on-the-fly)))
11952 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11953 (put 'org-self-insert-command 'delete-selection t)
11954 (put 'orgtbl-self-insert-command 'delete-selection t)
11955 (put 'org-delete-char 'delete-selection 'supersede)
11956 (put 'org-delete-backward-char 'delete-selection 'supersede)
11958 ;; Make `flyspell-mode' delay after some commands
11959 (put 'org-self-insert-command 'flyspell-delayed t)
11960 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11961 (put 'org-delete-char 'flyspell-delayed t)
11962 (put 'org-delete-backward-char 'flyspell-delayed t)
11964 ;; Make pabbrev-mode expand after org-mode commands
11965 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11966 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11968 ;; How to do this: Measure non-white length of current string
11969 ;; If equal to column width, we should realign.
11971 (defun org-remap (map &rest commands)
11972 "In MAP, remap the functions given in COMMANDS.
11973 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11974 (let (new old)
11975 (while commands
11976 (setq old (pop commands) new (pop commands))
11977 (if (fboundp 'command-remapping)
11978 (org-defkey map (vector 'remap old) new)
11979 (substitute-key-definition old new map global-map)))))
11981 (when (eq org-enable-table-editor 'optimized)
11982 ;; If the user wants maximum table support, we need to hijack
11983 ;; some standard editing functions
11984 (org-remap org-mode-map
11985 'self-insert-command 'org-self-insert-command
11986 'delete-char 'org-delete-char
11987 'delete-backward-char 'org-delete-backward-char)
11988 (org-defkey org-mode-map "|" 'org-force-self-insert))
11990 (defun org-shiftcursor-error ()
11991 "Throw an error because Shift-Cursor command was applied in wrong context."
11992 (error "This command is active in special context like tables, headlines or timestamps"))
11994 (defun org-shifttab (&optional arg)
11995 "Global visibility cycling or move to previous table field.
11996 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11997 on context.
11998 See the individual commands for more information."
11999 (interactive "P")
12000 (cond
12001 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12002 (arg (message "Content view to level: ")
12003 (org-content (prefix-numeric-value arg))
12004 (setq org-cycle-global-status 'overview))
12005 (t (call-interactively 'org-global-cycle))))
12007 (defun org-shiftmetaleft ()
12008 "Promote subtree or delete table column.
12009 Calls `org-promote-subtree', `org-outdent-item',
12010 or `org-table-delete-column', depending on context.
12011 See the individual commands for more information."
12012 (interactive)
12013 (cond
12014 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12015 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12016 ((org-at-item-p) (call-interactively 'org-outdent-item))
12017 (t (org-shiftcursor-error))))
12019 (defun org-shiftmetaright ()
12020 "Demote subtree or insert table column.
12021 Calls `org-demote-subtree', `org-indent-item',
12022 or `org-table-insert-column', depending on context.
12023 See the individual commands for more information."
12024 (interactive)
12025 (cond
12026 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12027 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12028 ((org-at-item-p) (call-interactively 'org-indent-item))
12029 (t (org-shiftcursor-error))))
12031 (defun org-shiftmetaup (&optional arg)
12032 "Move subtree up or kill table row.
12033 Calls `org-move-subtree-up' or `org-table-kill-row' or
12034 `org-move-item-up' depending on context. See the individual commands
12035 for more information."
12036 (interactive "P")
12037 (cond
12038 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12039 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12040 ((org-at-item-p) (call-interactively 'org-move-item-up))
12041 (t (org-shiftcursor-error))))
12042 (defun org-shiftmetadown (&optional arg)
12043 "Move subtree down or insert table row.
12044 Calls `org-move-subtree-down' or `org-table-insert-row' or
12045 `org-move-item-down', depending on context. See the individual
12046 commands for more information."
12047 (interactive "P")
12048 (cond
12049 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12050 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12051 ((org-at-item-p) (call-interactively 'org-move-item-down))
12052 (t (org-shiftcursor-error))))
12054 (defun org-metaleft (&optional arg)
12055 "Promote heading or move table column to left.
12056 Calls `org-do-promote' or `org-table-move-column', depending on context.
12057 With no specific context, calls the Emacs default `backward-word'.
12058 See the individual commands for more information."
12059 (interactive "P")
12060 (cond
12061 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12062 ((or (org-on-heading-p) (org-region-active-p))
12063 (call-interactively 'org-do-promote))
12064 ((org-at-item-p) (call-interactively 'org-outdent-item))
12065 (t (call-interactively 'backward-word))))
12067 (defun org-metaright (&optional arg)
12068 "Demote subtree or move table column to right.
12069 Calls `org-do-demote' or `org-table-move-column', depending on context.
12070 With no specific context, calls the Emacs default `forward-word'.
12071 See the individual commands for more information."
12072 (interactive "P")
12073 (cond
12074 ((org-at-table-p) (call-interactively 'org-table-move-column))
12075 ((or (org-on-heading-p) (org-region-active-p))
12076 (call-interactively 'org-do-demote))
12077 ((org-at-item-p) (call-interactively 'org-indent-item))
12078 (t (call-interactively 'forward-word))))
12080 (defun org-metaup (&optional arg)
12081 "Move subtree up or move table row up.
12082 Calls `org-move-subtree-up' or `org-table-move-row' or
12083 `org-move-item-up', depending on context. See the individual commands
12084 for more information."
12085 (interactive "P")
12086 (cond
12087 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12088 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12089 ((org-at-item-p) (call-interactively 'org-move-item-up))
12090 (t (transpose-lines 1) (beginning-of-line -1))))
12092 (defun org-metadown (&optional arg)
12093 "Move subtree down or move table row down.
12094 Calls `org-move-subtree-down' or `org-table-move-row' or
12095 `org-move-item-down', depending on context. See the individual
12096 commands for more information."
12097 (interactive "P")
12098 (cond
12099 ((org-at-table-p) (call-interactively 'org-table-move-row))
12100 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12101 ((org-at-item-p) (call-interactively 'org-move-item-down))
12102 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12104 (defun org-shiftup (&optional arg)
12105 "Increase item in timestamp or increase priority of current headline.
12106 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12107 depending on context. See the individual commands for more information."
12108 (interactive "P")
12109 (cond
12110 ((org-at-timestamp-p t)
12111 (call-interactively (if org-edit-timestamp-down-means-later
12112 'org-timestamp-down 'org-timestamp-up)))
12113 ((org-on-heading-p) (call-interactively 'org-priority-up))
12114 ((org-at-item-p) (call-interactively 'org-previous-item))
12115 ((org-clocktable-try-shift 'up arg))
12116 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12118 (defun org-shiftdown (&optional arg)
12119 "Decrease item in timestamp or decrease priority of current headline.
12120 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12121 depending on context. See the individual commands for more information."
12122 (interactive "P")
12123 (cond
12124 ((org-at-timestamp-p t)
12125 (call-interactively (if org-edit-timestamp-down-means-later
12126 'org-timestamp-up 'org-timestamp-down)))
12127 ((org-on-heading-p) (call-interactively 'org-priority-down))
12128 ((org-clocktable-try-shift 'down arg))
12129 (t (call-interactively 'org-next-item))))
12131 (defun org-shiftright (&optional arg)
12132 "Next TODO keyword or timestamp one day later, depending on context."
12133 (interactive "P")
12134 (cond
12135 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12136 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12137 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12138 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12139 ((org-clocktable-try-shift 'right arg))
12140 (t (org-shiftcursor-error))))
12142 (defun org-shiftleft (&optional arg)
12143 "Previous TODO keyword or timestamp one day earlier, depending on context."
12144 (interactive "P")
12145 (cond
12146 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12147 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12148 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12149 ((org-at-property-p)
12150 (call-interactively 'org-property-previous-allowed-value))
12151 ((org-clocktable-try-shift 'left arg))
12152 (t (org-shiftcursor-error))))
12154 (defun org-shiftcontrolright ()
12155 "Switch to next TODO set."
12156 (interactive)
12157 (cond
12158 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12159 (t (org-shiftcursor-error))))
12161 (defun org-shiftcontrolleft ()
12162 "Switch to previous TODO set."
12163 (interactive)
12164 (cond
12165 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12166 (t (org-shiftcursor-error))))
12168 (defun org-ctrl-c-ret ()
12169 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12170 (interactive)
12171 (cond
12172 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12173 (t (call-interactively 'org-insert-heading))))
12175 (defun org-copy-special ()
12176 "Copy region in table or copy current subtree.
12177 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12178 See the individual commands for more information."
12179 (interactive)
12180 (call-interactively
12181 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12183 (defun org-cut-special ()
12184 "Cut region in table or cut current subtree.
12185 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12186 See the individual commands for more information."
12187 (interactive)
12188 (call-interactively
12189 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12191 (defun org-paste-special (arg)
12192 "Paste rectangular region into table, or past subtree relative to level.
12193 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12194 See the individual commands for more information."
12195 (interactive "P")
12196 (if (org-at-table-p)
12197 (org-table-paste-rectangle)
12198 (org-paste-subtree arg)))
12200 (defun org-ctrl-c-ctrl-c (&optional arg)
12201 "Set tags in headline, or update according to changed information at point.
12203 This command does many different things, depending on context:
12205 - If the cursor is in a headline, prompt for tags and insert them
12206 into the current line, aligned to `org-tags-column'. When called
12207 with prefix arg, realign all tags in the current buffer.
12209 - If the cursor is in one of the special #+KEYWORD lines, this
12210 triggers scanning the buffer for these lines and updating the
12211 information.
12213 - If the cursor is inside a table, realign the table. This command
12214 works even if the automatic table editor has been turned off.
12216 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12217 the entire table.
12219 - If the cursor is a the beginning of a dynamic block, update it.
12221 - If the cursor is inside a table created by the table.el package,
12222 activate that table.
12224 - If the current buffer is a remember buffer, close note and file it.
12225 with a prefix argument, file it without further interaction to the default
12226 location.
12228 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12229 links in this buffer.
12231 - If the cursor is on a numbered item in a plain list, renumber the
12232 ordered list.
12234 - If the cursor is on a checkbox, toggle it."
12235 (interactive "P")
12236 (let ((org-enable-table-editor t))
12237 (cond
12238 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12239 org-occur-highlights
12240 org-latex-fragment-image-overlays)
12241 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12242 (org-remove-occur-highlights)
12243 (org-remove-latex-fragment-image-overlays)
12244 (message "Temporary highlights/overlays removed from current buffer"))
12245 ((and (local-variable-p 'org-finish-function (current-buffer))
12246 (fboundp org-finish-function))
12247 (funcall org-finish-function))
12248 ((org-at-property-p)
12249 (call-interactively 'org-property-action))
12250 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12251 ((org-on-heading-p) (call-interactively 'org-set-tags))
12252 ((org-at-table.el-p)
12253 (require 'table)
12254 (beginning-of-line 1)
12255 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12256 (call-interactively 'table-recognize-table))
12257 ((org-at-table-p)
12258 (org-table-maybe-eval-formula)
12259 (if arg
12260 (call-interactively 'org-table-recalculate)
12261 (org-table-maybe-recalculate-line))
12262 (call-interactively 'org-table-align))
12263 ((org-at-item-checkbox-p)
12264 (call-interactively 'org-toggle-checkbox))
12265 ((org-at-item-p)
12266 (call-interactively 'org-maybe-renumber-ordered-list))
12267 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12268 ;; Dynamic block
12269 (beginning-of-line 1)
12270 (org-update-dblock))
12271 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12272 (cond
12273 ((equal (match-string 1) "TBLFM")
12274 ;; Recalculate the table before this line
12275 (save-excursion
12276 (beginning-of-line 1)
12277 (skip-chars-backward " \r\n\t")
12278 (if (org-at-table-p)
12279 (org-call-with-arg 'org-table-recalculate t))))
12281 (call-interactively 'org-mode-restart))))
12282 (t (error "C-c C-c can do nothing useful at this location.")))))
12284 (defun org-mode-restart ()
12285 "Restart Org-mode, to scan again for special lines.
12286 Also updates the keyword regular expressions."
12287 (interactive)
12288 (let ((org-inhibit-startup t)) (org-mode))
12289 (message "Org-mode restarted to refresh keyword and special line setup"))
12291 (defun org-kill-note-or-show-branches ()
12292 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12293 (interactive)
12294 (if (not org-finish-function)
12295 (call-interactively 'show-branches)
12296 (let ((org-note-abort t))
12297 (funcall org-finish-function))))
12299 (defun org-return (&optional indent)
12300 "Goto next table row or insert a newline.
12301 Calls `org-table-next-row' or `newline', depending on context.
12302 See the individual commands for more information."
12303 (interactive)
12304 (cond
12305 ((bobp) (if indent (newline-and-indent) (newline)))
12306 ((and (org-at-heading-p)
12307 (looking-at
12308 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12309 (org-show-entry)
12310 (end-of-line 1)
12311 (newline))
12312 ((org-at-table-p)
12313 (org-table-justify-field-maybe)
12314 (call-interactively 'org-table-next-row))
12315 (t (if indent (newline-and-indent) (newline)))))
12317 (defun org-return-indent ()
12318 "Goto next table row or insert a newline and indent.
12319 Calls `org-table-next-row' or `newline-and-indent', depending on
12320 context. See the individual commands for more information."
12321 (interactive)
12322 (org-return t))
12324 (defun org-ctrl-c-star ()
12325 "Compute table, or change heading status of lines.
12326 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12327 depending on context. This will also turn a plain list item or a normal
12328 line into a subheading."
12329 (interactive)
12330 (cond
12331 ((org-at-table-p)
12332 (call-interactively 'org-table-recalculate))
12333 ((org-region-active-p)
12334 ;; Convert all lines in region to list items
12335 (call-interactively 'org-toggle-region-headings))
12336 ((org-on-heading-p)
12337 (org-toggle-region-headings (point-at-bol)
12338 (min (1+ (point-at-eol)) (point-max))))
12339 ((org-at-item-p)
12340 ;; Convert to heading
12341 (let ((level (save-match-data
12342 (save-excursion
12343 (condition-case nil
12344 (progn
12345 (org-back-to-heading t)
12346 (funcall outline-level))
12347 (error 0))))))
12348 (replace-match
12349 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12350 (t (org-toggle-region-headings (point-at-bol)
12351 (min (1+ (point-at-eol)) (point-max))))))
12353 (defun org-ctrl-c-minus ()
12354 "Insert separator line in table or modify bullet status of line.
12355 Also turns a plain line or a region of lines into list items.
12356 Calls `org-table-insert-hline', `org-toggle-region-items', or
12357 `org-cycle-list-bullet', depending on context."
12358 (interactive)
12359 (cond
12360 ((org-at-table-p)
12361 (call-interactively 'org-table-insert-hline))
12362 ((org-on-heading-p)
12363 ;; Convert to item
12364 (save-excursion
12365 (beginning-of-line 1)
12366 (if (looking-at "\\*+ ")
12367 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12368 ((org-region-active-p)
12369 ;; Convert all lines in region to list items
12370 (call-interactively 'org-toggle-region-items))
12371 ((org-in-item-p)
12372 (call-interactively 'org-cycle-list-bullet))
12373 (t (org-toggle-region-items (point-at-bol)
12374 (min (1+ (point-at-eol)) (point-max))))))
12376 (defun org-toggle-region-items (beg end)
12377 "Convert all lines in region to list items.
12378 If the first line is already an item, convert all list items in the region
12379 to normal lines."
12380 (interactive "r")
12381 (let (l2 l)
12382 (save-excursion
12383 (goto-char end)
12384 (setq l2 (org-current-line))
12385 (goto-char beg)
12386 (beginning-of-line 1)
12387 (setq l (1- (org-current-line)))
12388 (if (org-at-item-p)
12389 ;; We already have items, de-itemize
12390 (while (< (setq l (1+ l)) l2)
12391 (when (org-at-item-p)
12392 (goto-char (match-beginning 2))
12393 (delete-region (match-beginning 2) (match-end 2))
12394 (and (looking-at "[ \t]+") (replace-match "")))
12395 (beginning-of-line 2))
12396 (while (< (setq l (1+ l)) l2)
12397 (unless (org-at-item-p)
12398 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12399 (replace-match "\\1- \\2")))
12400 (beginning-of-line 2))))))
12402 (defun org-toggle-region-headings (beg end)
12403 "Convert all lines in region to list items.
12404 If the first line is already an item, convert all list items in the region
12405 to normal lines."
12406 (interactive "r")
12407 (let (l2 l)
12408 (save-excursion
12409 (goto-char end)
12410 (setq l2 (org-current-line))
12411 (goto-char beg)
12412 (beginning-of-line 1)
12413 (setq l (1- (org-current-line)))
12414 (if (org-on-heading-p)
12415 ;; We already have headlines, de-star them
12416 (while (< (setq l (1+ l)) l2)
12417 (when (org-on-heading-p t)
12418 (and (looking-at outline-regexp) (replace-match "")))
12419 (beginning-of-line 2))
12420 (let* ((stars (save-excursion
12421 (re-search-backward org-complex-heading-regexp nil t)
12422 (or (match-string 1) "*")))
12423 (add-stars (if org-odd-levels-only "**" "*"))
12424 (rpl (concat stars add-stars " \\2")))
12425 (while (< (setq l (1+ l)) l2)
12426 (unless (org-on-heading-p)
12427 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12428 (replace-match rpl)))
12429 (beginning-of-line 2)))))))
12431 (defun org-meta-return (&optional arg)
12432 "Insert a new heading or wrap a region in a table.
12433 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12434 See the individual commands for more information."
12435 (interactive "P")
12436 (cond
12437 ((org-at-table-p)
12438 (call-interactively 'org-table-wrap-region))
12439 (t (call-interactively 'org-insert-heading))))
12441 ;;; Menu entries
12443 ;; Define the Org-mode menus
12444 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12445 '("Tbl"
12446 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12447 ["Next Field" org-cycle (org-at-table-p)]
12448 ["Previous Field" org-shifttab (org-at-table-p)]
12449 ["Next Row" org-return (org-at-table-p)]
12450 "--"
12451 ["Blank Field" org-table-blank-field (org-at-table-p)]
12452 ["Edit Field" org-table-edit-field (org-at-table-p)]
12453 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12454 "--"
12455 ("Column"
12456 ["Move Column Left" org-metaleft (org-at-table-p)]
12457 ["Move Column Right" org-metaright (org-at-table-p)]
12458 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12459 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12460 ("Row"
12461 ["Move Row Up" org-metaup (org-at-table-p)]
12462 ["Move Row Down" org-metadown (org-at-table-p)]
12463 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12464 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12465 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12466 "--"
12467 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12468 ("Rectangle"
12469 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12470 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12471 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12472 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12473 "--"
12474 ("Calculate"
12475 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12476 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12477 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12478 "--"
12479 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12480 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12481 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12482 "--"
12483 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12484 "--"
12485 ["Sum Column/Rectangle" org-table-sum
12486 (or (org-at-table-p) (org-region-active-p))]
12487 ["Which Column?" org-table-current-column (org-at-table-p)])
12488 ["Debug Formulas"
12489 org-table-toggle-formula-debugger
12490 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12491 ["Show Col/Row Numbers"
12492 org-table-toggle-coordinate-overlays
12493 :style toggle
12494 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12495 "--"
12496 ["Create" org-table-create (and (not (org-at-table-p))
12497 org-enable-table-editor)]
12498 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12499 ["Import from File" org-table-import (not (org-at-table-p))]
12500 ["Export to File" org-table-export (org-at-table-p)]
12501 "--"
12502 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12504 (easy-menu-define org-org-menu org-mode-map "Org menu"
12505 '("Org"
12506 ("Show/Hide"
12507 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12508 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12509 ["Sparse Tree..." org-sparse-tree t]
12510 ["Reveal Context" org-reveal t]
12511 ["Show All" show-all t]
12512 "--"
12513 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12514 "--"
12515 ["New Heading" org-insert-heading t]
12516 ("Navigate Headings"
12517 ["Up" outline-up-heading t]
12518 ["Next" outline-next-visible-heading t]
12519 ["Previous" outline-previous-visible-heading t]
12520 ["Next Same Level" outline-forward-same-level t]
12521 ["Previous Same Level" outline-backward-same-level t]
12522 "--"
12523 ["Jump" org-goto t])
12524 ("Edit Structure"
12525 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12526 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12527 "--"
12528 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12529 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12530 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12531 "--"
12532 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12533 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12534 ["Demote Heading" org-metaright (not (org-at-table-p))]
12535 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12536 "--"
12537 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12538 "--"
12539 ["Convert to odd levels" org-convert-to-odd-levels t]
12540 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12541 ("Editing"
12542 ["Emphasis..." org-emphasize t])
12543 ("Archive"
12544 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12545 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12546 ; :active t :keys "C-u C-c C-x C-a"]
12547 ["Sparse trees open ARCHIVE trees"
12548 (setq org-sparse-tree-open-archived-trees
12549 (not org-sparse-tree-open-archived-trees))
12550 :style toggle :selected org-sparse-tree-open-archived-trees]
12551 ["Cycling opens ARCHIVE trees"
12552 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12553 :style toggle :selected org-cycle-open-archived-trees]
12554 ["Agenda includes ARCHIVE trees"
12555 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12556 :style toggle :selected (not org-agenda-skip-archived-trees)]
12557 "--"
12558 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12559 ; ["Check and Move Children" (org-archive-subtree '(4))
12560 ; :active t :keys "C-u C-c C-x C-s"]
12562 "--"
12563 ("TODO Lists"
12564 ["TODO/DONE/-" org-todo t]
12565 ("Select keyword"
12566 ["Next keyword" org-shiftright (org-on-heading-p)]
12567 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12568 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12569 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12570 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12571 ["Show TODO Tree" org-show-todo-tree t]
12572 ["Global TODO list" org-todo-list t]
12573 "--"
12574 ["Set Priority" org-priority t]
12575 ["Priority Up" org-shiftup t]
12576 ["Priority Down" org-shiftdown t])
12577 ("TAGS and Properties"
12578 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12579 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12580 "--"
12581 ["Set property" 'org-set-property t]
12582 ["Column view of properties" org-columns t]
12583 ["Insert Column View DBlock" org-insert-columns-dblock t])
12584 ("Dates and Scheduling"
12585 ["Timestamp" org-time-stamp t]
12586 ["Timestamp (inactive)" org-time-stamp-inactive t]
12587 ("Change Date"
12588 ["1 Day Later" org-shiftright t]
12589 ["1 Day Earlier" org-shiftleft t]
12590 ["1 ... Later" org-shiftup t]
12591 ["1 ... Earlier" org-shiftdown t])
12592 ["Compute Time Range" org-evaluate-time-range t]
12593 ["Schedule Item" org-schedule t]
12594 ["Deadline" org-deadline t]
12595 "--"
12596 ["Custom time format" org-toggle-time-stamp-overlays
12597 :style radio :selected org-display-custom-times]
12598 "--"
12599 ["Goto Calendar" org-goto-calendar t]
12600 ["Date from Calendar" org-date-from-calendar t])
12601 ("Logging work"
12602 ["Clock in" org-clock-in t]
12603 ["Clock out" org-clock-out t]
12604 ["Clock cancel" org-clock-cancel t]
12605 ["Goto running clock" org-clock-goto t]
12606 ["Display times" org-clock-display t]
12607 ["Create clock table" org-clock-report t]
12608 "--"
12609 ["Record DONE time"
12610 (progn (setq org-log-done (not org-log-done))
12611 (message "Switching to %s will %s record a timestamp"
12612 (car org-done-keywords)
12613 (if org-log-done "automatically" "not")))
12614 :style toggle :selected org-log-done])
12615 "--"
12616 ["Agenda Command..." org-agenda t]
12617 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12618 ("File List for Agenda")
12619 ("Special views current file"
12620 ["TODO Tree" org-show-todo-tree t]
12621 ["Check Deadlines" org-check-deadlines t]
12622 ["Timeline" org-timeline t]
12623 ["Tags Tree" org-tags-sparse-tree t])
12624 "--"
12625 ("Hyperlinks"
12626 ["Store Link (Global)" org-store-link t]
12627 ["Insert Link" org-insert-link t]
12628 ["Follow Link" org-open-at-point t]
12629 "--"
12630 ["Next link" org-next-link t]
12631 ["Previous link" org-previous-link t]
12632 "--"
12633 ["Descriptive Links"
12634 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12635 :style radio
12636 :selected (member '(org-link) buffer-invisibility-spec)]
12637 ["Literal Links"
12638 (progn
12639 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12640 :style radio
12641 :selected (not (member '(org-link) buffer-invisibility-spec))])
12642 "--"
12643 ["Export/Publish..." org-export t]
12644 ("LaTeX"
12645 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12646 :selected org-cdlatex-mode]
12647 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12648 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12649 ["Modify math symbol" org-cdlatex-math-modify
12650 (org-inside-LaTeX-fragment-p)]
12651 ["Export LaTeX fragments as images"
12652 (if (featurep 'org-exp)
12653 (setq org-export-with-LaTeX-fragments
12654 (not org-export-with-LaTeX-fragments))
12655 (require 'org-exp))
12656 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12657 org-export-with-LaTeX-fragments)])
12658 "--"
12659 ("Documentation"
12660 ["Show Version" org-version t]
12661 ["Info Documentation" org-info t])
12662 ("Customize"
12663 ["Browse Org Group" org-customize t]
12664 "--"
12665 ["Expand This Menu" org-create-customize-menu
12666 (fboundp 'customize-menu-create)])
12667 "--"
12668 ["Refresh setup" org-mode-restart t]
12671 (defun org-info (&optional node)
12672 "Read documentation for Org-mode in the info system.
12673 With optional NODE, go directly to that node."
12674 (interactive)
12675 (info (format "(org)%s" (or node ""))))
12677 (defun org-install-agenda-files-menu ()
12678 (let ((bl (buffer-list)))
12679 (save-excursion
12680 (while bl
12681 (set-buffer (pop bl))
12682 (if (org-mode-p) (setq bl nil)))
12683 (when (org-mode-p)
12684 (easy-menu-change
12685 '("Org") "File List for Agenda"
12686 (append
12687 (list
12688 ["Edit File List" (org-edit-agenda-file-list) t]
12689 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12690 ["Remove Current File from List" org-remove-file t]
12691 ["Cycle through agenda files" org-cycle-agenda-files t]
12692 ["Occur in all agenda files" org-occur-in-agenda-files t]
12693 "--")
12694 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12696 ;;;; Documentation
12698 (defun org-require-autoloaded-modules ()
12699 (interactive)
12700 (mapc 'require
12701 '(org-agenda org-archive org-clock org-colview
12702 org-exp org-export-latex org-publish
12703 org-remember org-table)))
12705 (defun org-customize ()
12706 "Call the customize function with org as argument."
12707 (interactive)
12708 (org-load-modules-maybe)
12709 (org-require-autoloaded-modules)
12710 (customize-browse 'org))
12712 (defun org-create-customize-menu ()
12713 "Create a full customization menu for Org-mode, insert it into the menu."
12714 (interactive)
12715 (org-load-modules-maybe)
12716 (org-require-autoloaded-modules)
12717 (if (fboundp 'customize-menu-create)
12718 (progn
12719 (easy-menu-change
12720 '("Org") "Customize"
12721 `(["Browse Org group" org-customize t]
12722 "--"
12723 ,(customize-menu-create 'org)
12724 ["Set" Custom-set t]
12725 ["Save" Custom-save t]
12726 ["Reset to Current" Custom-reset-current t]
12727 ["Reset to Saved" Custom-reset-saved t]
12728 ["Reset to Standard Settings" Custom-reset-standard t]))
12729 (message "\"Org\"-menu now contains full customization menu"))
12730 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12732 ;;;; Miscellaneous stuff
12734 ;;; Generally useful functions
12736 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12737 "Display the given MESSAGE as a warning."
12738 (if (fboundp 'display-warning)
12739 (display-warning 'org message
12740 (if (featurep 'xemacs)
12741 'warning
12742 :warning))
12743 (let ((buf (get-buffer-create "*Org warnings*")))
12744 (with-current-buffer buf
12745 (goto-char (point-max))
12746 (insert "Warning (Org): " message)
12747 (unless (bolp)
12748 (newline)))
12749 (display-buffer buf)
12750 (sit-for 0))))
12752 (defun org-plist-delete (plist property)
12753 "Delete PROPERTY from PLIST.
12754 This is in contrast to merely setting it to 0."
12755 (let (p)
12756 (while plist
12757 (if (not (eq property (car plist)))
12758 (setq p (plist-put p (car plist) (nth 1 plist))))
12759 (setq plist (cddr plist)))
12762 (defun org-force-self-insert (N)
12763 "Needed to enforce self-insert under remapping."
12764 (interactive "p")
12765 (self-insert-command N))
12767 (defun org-string-width (s)
12768 "Compute width of string, ignoring invisible characters.
12769 This ignores character with invisibility property `org-link', and also
12770 characters with property `org-cwidth', because these will become invisible
12771 upon the next fontification round."
12772 (let (b l)
12773 (when (or (eq t buffer-invisibility-spec)
12774 (assq 'org-link buffer-invisibility-spec))
12775 (while (setq b (text-property-any 0 (length s)
12776 'invisible 'org-link s))
12777 (setq s (concat (substring s 0 b)
12778 (substring s (or (next-single-property-change
12779 b 'invisible s) (length s)))))))
12780 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12781 (setq s (concat (substring s 0 b)
12782 (substring s (or (next-single-property-change
12783 b 'org-cwidth s) (length s))))))
12784 (setq l (string-width s) b -1)
12785 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12786 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12789 (defun org-base-buffer (buffer)
12790 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12791 (if (not buffer)
12792 buffer
12793 (or (buffer-base-buffer buffer)
12794 buffer)))
12796 (defun org-trim (s)
12797 "Remove whitespace at beginning and end of string."
12798 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12799 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12802 (defun org-wrap (string &optional width lines)
12803 "Wrap string to either a number of lines, or a width in characters.
12804 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12805 that costs. If there is a word longer than WIDTH, the text is actually
12806 wrapped to the length of that word.
12807 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12808 many lines, whatever width that takes.
12809 The return value is a list of lines, without newlines at the end."
12810 (let* ((words (org-split-string string "[ \t\n]+"))
12811 (maxword (apply 'max (mapcar 'org-string-width words)))
12812 w ll)
12813 (cond (width
12814 (org-do-wrap words (max maxword width)))
12815 (lines
12816 (setq w maxword)
12817 (setq ll (org-do-wrap words maxword))
12818 (if (<= (length ll) lines)
12820 (setq ll words)
12821 (while (> (length ll) lines)
12822 (setq w (1+ w))
12823 (setq ll (org-do-wrap words w)))
12824 ll))
12825 (t (error "Cannot wrap this")))))
12827 (defun org-do-wrap (words width)
12828 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12829 (let (lines line)
12830 (while words
12831 (setq line (pop words))
12832 (while (and words (< (+ (length line) (length (car words))) width))
12833 (setq line (concat line " " (pop words))))
12834 (setq lines (push line lines)))
12835 (nreverse lines)))
12837 (defun org-split-string (string &optional separators)
12838 "Splits STRING into substrings at SEPARATORS.
12839 No empty strings are returned if there are matches at the beginning
12840 and end of string."
12841 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12842 (start 0)
12843 notfirst
12844 (list nil))
12845 (while (and (string-match rexp string
12846 (if (and notfirst
12847 (= start (match-beginning 0))
12848 (< start (length string)))
12849 (1+ start) start))
12850 (< (match-beginning 0) (length string)))
12851 (setq notfirst t)
12852 (or (eq (match-beginning 0) 0)
12853 (and (eq (match-beginning 0) (match-end 0))
12854 (eq (match-beginning 0) start))
12855 (setq list
12856 (cons (substring string start (match-beginning 0))
12857 list)))
12858 (setq start (match-end 0)))
12859 (or (eq start (length string))
12860 (setq list
12861 (cons (substring string start)
12862 list)))
12863 (nreverse list)))
12865 (defun org-context ()
12866 "Return a list of contexts of the current cursor position.
12867 If several contexts apply, all are returned.
12868 Each context entry is a list with a symbol naming the context, and
12869 two positions indicating start and end of the context. Possible
12870 contexts are:
12872 :headline anywhere in a headline
12873 :headline-stars on the leading stars in a headline
12874 :todo-keyword on a TODO keyword (including DONE) in a headline
12875 :tags on the TAGS in a headline
12876 :priority on the priority cookie in a headline
12877 :item on the first line of a plain list item
12878 :item-bullet on the bullet/number of a plain list item
12879 :checkbox on the checkbox in a plain list item
12880 :table in an org-mode table
12881 :table-special on a special filed in a table
12882 :table-table in a table.el table
12883 :link on a hyperlink
12884 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12885 :target on a <<target>>
12886 :radio-target on a <<<radio-target>>>
12887 :latex-fragment on a LaTeX fragment
12888 :latex-preview on a LaTeX fragment with overlayed preview image
12890 This function expects the position to be visible because it uses font-lock
12891 faces as a help to recognize the following contexts: :table-special, :link,
12892 and :keyword."
12893 (let* ((f (get-text-property (point) 'face))
12894 (faces (if (listp f) f (list f)))
12895 (p (point)) clist o)
12896 ;; First the large context
12897 (cond
12898 ((org-on-heading-p t)
12899 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12900 (when (progn
12901 (beginning-of-line 1)
12902 (looking-at org-todo-line-tags-regexp))
12903 (push (org-point-in-group p 1 :headline-stars) clist)
12904 (push (org-point-in-group p 2 :todo-keyword) clist)
12905 (push (org-point-in-group p 4 :tags) clist))
12906 (goto-char p)
12907 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12908 (if (looking-at "\\[#[A-Z0-9]\\]")
12909 (push (org-point-in-group p 0 :priority) clist)))
12911 ((org-at-item-p)
12912 (push (org-point-in-group p 2 :item-bullet) clist)
12913 (push (list :item (point-at-bol)
12914 (save-excursion (org-end-of-item) (point)))
12915 clist)
12916 (and (org-at-item-checkbox-p)
12917 (push (org-point-in-group p 0 :checkbox) clist)))
12919 ((org-at-table-p)
12920 (push (list :table (org-table-begin) (org-table-end)) clist)
12921 (if (memq 'org-formula faces)
12922 (push (list :table-special
12923 (previous-single-property-change p 'face)
12924 (next-single-property-change p 'face)) clist)))
12925 ((org-at-table-p 'any)
12926 (push (list :table-table) clist)))
12927 (goto-char p)
12929 ;; Now the small context
12930 (cond
12931 ((org-at-timestamp-p)
12932 (push (org-point-in-group p 0 :timestamp) clist))
12933 ((memq 'org-link faces)
12934 (push (list :link
12935 (previous-single-property-change p 'face)
12936 (next-single-property-change p 'face)) clist))
12937 ((memq 'org-special-keyword faces)
12938 (push (list :keyword
12939 (previous-single-property-change p 'face)
12940 (next-single-property-change p 'face)) clist))
12941 ((org-on-target-p)
12942 (push (org-point-in-group p 0 :target) clist)
12943 (goto-char (1- (match-beginning 0)))
12944 (if (looking-at org-radio-target-regexp)
12945 (push (org-point-in-group p 0 :radio-target) clist))
12946 (goto-char p))
12947 ((setq o (car (delq nil
12948 (mapcar
12949 (lambda (x)
12950 (if (memq x org-latex-fragment-image-overlays) x))
12951 (org-overlays-at (point))))))
12952 (push (list :latex-fragment
12953 (org-overlay-start o) (org-overlay-end o)) clist)
12954 (push (list :latex-preview
12955 (org-overlay-start o) (org-overlay-end o)) clist))
12956 ((org-inside-LaTeX-fragment-p)
12957 ;; FIXME: positions wrong.
12958 (push (list :latex-fragment (point) (point)) clist)))
12960 (setq clist (nreverse (delq nil clist)))
12961 clist))
12963 ;; FIXME: Compare with at-regexp-p Do we need both?
12964 (defun org-in-regexp (re &optional nlines visually)
12965 "Check if point is inside a match of regexp.
12966 Normally only the current line is checked, but you can include NLINES extra
12967 lines both before and after point into the search.
12968 If VISUALLY is set, require that the cursor is not after the match but
12969 really on, so that the block visually is on the match."
12970 (catch 'exit
12971 (let ((pos (point))
12972 (eol (point-at-eol (+ 1 (or nlines 0))))
12973 (inc (if visually 1 0)))
12974 (save-excursion
12975 (beginning-of-line (- 1 (or nlines 0)))
12976 (while (re-search-forward re eol t)
12977 (if (and (<= (match-beginning 0) pos)
12978 (>= (+ inc (match-end 0)) pos))
12979 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12981 (defun org-at-regexp-p (regexp)
12982 "Is point inside a match of REGEXP in the current line?"
12983 (catch 'exit
12984 (save-excursion
12985 (let ((pos (point)) (end (point-at-eol)))
12986 (beginning-of-line 1)
12987 (while (re-search-forward regexp end t)
12988 (if (and (<= (match-beginning 0) pos)
12989 (>= (match-end 0) pos))
12990 (throw 'exit t)))
12991 nil))))
12993 (defun org-occur-in-agenda-files (regexp &optional nlines)
12994 "Call `multi-occur' with buffers for all agenda files."
12995 (interactive "sOrg-files matching: \np")
12996 (let* ((files (org-agenda-files))
12997 (tnames (mapcar 'file-truename files))
12998 (extra org-agenda-text-search-extra-files)
13000 (when (eq (car extra) 'agenda-archives)
13001 (setq extra (cdr extra))
13002 (setq files (org-add-archive-files files)))
13003 (while (setq f (pop extra))
13004 (unless (member (file-truename f) tnames)
13005 (add-to-list 'files f 'append)
13006 (add-to-list 'tnames (file-truename f) 'append)))
13007 (multi-occur
13008 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13009 regexp)))
13011 (if (boundp 'occur-mode-find-occurrence-hook)
13012 ;; Emacs 23
13013 (add-hook 'occur-mode-find-occurrence-hook
13014 (lambda ()
13015 (when (org-mode-p)
13016 (org-reveal))))
13017 ;; Emacs 22
13018 (defadvice occur-mode-goto-occurrence
13019 (after org-occur-reveal activate)
13020 (and (org-mode-p) (org-reveal)))
13021 (defadvice occur-mode-goto-occurrence-other-window
13022 (after org-occur-reveal activate)
13023 (and (org-mode-p) (org-reveal)))
13024 (defadvice occur-mode-display-occurrence
13025 (after org-occur-reveal activate)
13026 (when (org-mode-p)
13027 (let ((pos (occur-mode-find-occurrence)))
13028 (with-current-buffer (marker-buffer pos)
13029 (save-excursion
13030 (goto-char pos)
13031 (org-reveal)))))))
13033 (defun org-uniquify (list)
13034 "Remove duplicate elements from LIST."
13035 (let (res)
13036 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13037 res))
13039 (defun org-delete-all (elts list)
13040 "Remove all elements in ELTS from LIST."
13041 (while elts
13042 (setq list (delete (pop elts) list)))
13043 list)
13045 (defun org-back-over-empty-lines ()
13046 "Move backwards over witespace, to the beginning of the first empty line.
13047 Returns the number of empty lines passed."
13048 (let ((pos (point)))
13049 (skip-chars-backward " \t\n\r")
13050 (beginning-of-line 2)
13051 (goto-char (min (point) pos))
13052 (count-lines (point) pos)))
13054 (defun org-skip-whitespace ()
13055 (skip-chars-forward " \t\n\r"))
13057 (defun org-point-in-group (point group &optional context)
13058 "Check if POINT is in match-group GROUP.
13059 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13060 match. If the match group does ot exist or point is not inside it,
13061 return nil."
13062 (and (match-beginning group)
13063 (>= point (match-beginning group))
13064 (<= point (match-end group))
13065 (if context
13066 (list context (match-beginning group) (match-end group))
13067 t)))
13069 (defun org-switch-to-buffer-other-window (&rest args)
13070 "Switch to buffer in a second window on the current frame.
13071 In particular, do not allow pop-up frames."
13072 (let (pop-up-frames special-display-buffer-names special-display-regexps
13073 special-display-function)
13074 (apply 'switch-to-buffer-other-window args)))
13076 (defun org-combine-plists (&rest plists)
13077 "Create a single property list from all plists in PLISTS.
13078 The process starts by copying the first list, and then setting properties
13079 from the other lists. Settings in the last list are the most significant
13080 ones and overrule settings in the other lists."
13081 (let ((rtn (copy-sequence (pop plists)))
13082 p v ls)
13083 (while plists
13084 (setq ls (pop plists))
13085 (while ls
13086 (setq p (pop ls) v (pop ls))
13087 (setq rtn (plist-put rtn p v))))
13088 rtn))
13090 (defun org-move-line-down (arg)
13091 "Move the current line down. With prefix argument, move it past ARG lines."
13092 (interactive "p")
13093 (let ((col (current-column))
13094 beg end pos)
13095 (beginning-of-line 1) (setq beg (point))
13096 (beginning-of-line 2) (setq end (point))
13097 (beginning-of-line (+ 1 arg))
13098 (setq pos (move-marker (make-marker) (point)))
13099 (insert (delete-and-extract-region beg end))
13100 (goto-char pos)
13101 (org-move-to-column col)))
13103 (defun org-move-line-up (arg)
13104 "Move the current line up. With prefix argument, move it past ARG lines."
13105 (interactive "p")
13106 (let ((col (current-column))
13107 beg end pos)
13108 (beginning-of-line 1) (setq beg (point))
13109 (beginning-of-line 2) (setq end (point))
13110 (beginning-of-line (- arg))
13111 (setq pos (move-marker (make-marker) (point)))
13112 (insert (delete-and-extract-region beg end))
13113 (goto-char pos)
13114 (org-move-to-column col)))
13116 (defun org-replace-escapes (string table)
13117 "Replace %-escapes in STRING with values in TABLE.
13118 TABLE is an association list with keys like \"%a\" and string values.
13119 The sequences in STRING may contain normal field width and padding information,
13120 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13121 so values can contain further %-escapes if they are define later in TABLE."
13122 (let ((case-fold-search nil)
13123 e re rpl)
13124 (while (setq e (pop table))
13125 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13126 (while (string-match re string)
13127 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13128 (cdr e)))
13129 (setq string (replace-match rpl t t string))))
13130 string))
13133 (defun org-sublist (list start end)
13134 "Return a section of LIST, from START to END.
13135 Counting starts at 1."
13136 (let (rtn (c start))
13137 (setq list (nthcdr (1- start) list))
13138 (while (and list (<= c end))
13139 (push (pop list) rtn)
13140 (setq c (1+ c)))
13141 (nreverse rtn)))
13143 (defun org-find-base-buffer-visiting (file)
13144 "Like `find-buffer-visiting' but alway return the base buffer and
13145 not an indirect buffer."
13146 (let ((buf (find-buffer-visiting file)))
13147 (if buf
13148 (or (buffer-base-buffer buf) buf)
13149 nil)))
13151 (defun org-image-file-name-regexp ()
13152 "Return regexp matching the file names of images."
13153 (if (fboundp 'image-file-name-regexp)
13154 (image-file-name-regexp)
13155 (let ((image-file-name-extensions
13156 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13157 "xbm" "xpm" "pbm" "pgm" "ppm")))
13158 (concat "\\."
13159 (regexp-opt (nconc (mapcar 'upcase
13160 image-file-name-extensions)
13161 image-file-name-extensions)
13163 "\\'"))))
13165 (defun org-file-image-p (file)
13166 "Return non-nil if FILE is an image."
13167 (save-match-data
13168 (string-match (org-image-file-name-regexp) file)))
13170 ;;; Paragraph filling stuff.
13171 ;; We want this to be just right, so use the full arsenal.
13173 (defun org-indent-line-function ()
13174 "Indent line like previous, but further if previous was headline or item."
13175 (interactive)
13176 (let* ((pos (point))
13177 (itemp (org-at-item-p))
13178 column bpos bcol tpos tcol bullet btype bullet-type)
13179 ;; Find the previous relevant line
13180 (beginning-of-line 1)
13181 (cond
13182 ((looking-at "#") (setq column 0))
13183 ((looking-at "\\*+ ") (setq column 0))
13185 (beginning-of-line 0)
13186 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13187 (beginning-of-line 0))
13188 (cond
13189 ((looking-at "\\*+[ \t]+")
13190 (goto-char (match-end 0))
13191 (setq column (current-column)))
13192 ((org-in-item-p)
13193 (org-beginning-of-item)
13194 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13195 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13196 (setq bpos (match-beginning 1) tpos (match-end 0)
13197 bcol (progn (goto-char bpos) (current-column))
13198 tcol (progn (goto-char tpos) (current-column))
13199 bullet (match-string 1)
13200 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13201 (if (not itemp)
13202 (setq column tcol)
13203 (goto-char pos)
13204 (beginning-of-line 1)
13205 (if (looking-at "\\S-")
13206 (progn
13207 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13208 (setq bullet (match-string 1)
13209 btype (if (string-match "[0-9]" bullet) "n" bullet))
13210 (setq column (if (equal btype bullet-type) bcol tcol)))
13211 (setq column (org-get-indentation)))))
13212 (t (setq column (org-get-indentation))))))
13213 (goto-char pos)
13214 (if (<= (current-column) (current-indentation))
13215 (org-indent-line-to column)
13216 (save-excursion (org-indent-line-to column)))
13217 (setq column (current-column))
13218 (beginning-of-line 1)
13219 (if (looking-at
13220 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13221 (replace-match (concat "\\1" (format org-property-format
13222 (match-string 2) (match-string 3)))
13223 t nil))
13224 (org-move-to-column column)))
13226 (defun org-set-autofill-regexps ()
13227 (interactive)
13228 ;; In the paragraph separator we include headlines, because filling
13229 ;; text in a line directly attached to a headline would otherwise
13230 ;; fill the headline as well.
13231 (org-set-local 'comment-start-skip "^#+[ \t]*")
13232 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13233 ;; The paragraph starter includes hand-formatted lists.
13234 (org-set-local 'paragraph-start
13235 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13236 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13237 ;; But only if the user has not turned off tables or fixed-width regions
13238 (org-set-local
13239 'auto-fill-inhibit-regexp
13240 (concat "\\*+ \\|#\\+"
13241 "\\|[ \t]*" org-keyword-time-regexp
13242 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13243 (concat
13244 "\\|[ \t]*["
13245 (if org-enable-table-editor "|" "")
13246 (if org-enable-fixed-width-editor ":" "")
13247 "]"))))
13248 ;; We use our own fill-paragraph function, to make sure that tables
13249 ;; and fixed-width regions are not wrapped. That function will pass
13250 ;; through to `fill-paragraph' when appropriate.
13251 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13252 ; Adaptive filling: To get full control, first make sure that
13253 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13254 (org-set-local 'adaptive-fill-regexp "\000")
13255 (org-set-local 'adaptive-fill-function
13256 'org-adaptive-fill-function)
13257 (org-set-local
13258 'align-mode-rules-list
13259 '((org-in-buffer-settings
13260 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13261 (modes . '(org-mode))))))
13263 (defun org-fill-paragraph (&optional justify)
13264 "Re-align a table, pass through to fill-paragraph if no table."
13265 (let ((table-p (org-at-table-p))
13266 (table.el-p (org-at-table.el-p)))
13267 (cond ((and (equal (char-after (point-at-bol)) ?*)
13268 (save-excursion (goto-char (point-at-bol))
13269 (looking-at outline-regexp)))
13270 t) ; skip headlines
13271 (table.el-p t) ; skip table.el tables
13272 (table-p (org-table-align) t) ; align org-mode tables
13273 (t nil)))) ; call paragraph-fill
13275 ;; For reference, this is the default value of adaptive-fill-regexp
13276 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13278 (defun org-adaptive-fill-function ()
13279 "Return a fill prefix for org-mode files.
13280 In particular, this makes sure hanging paragraphs for hand-formatted lists
13281 work correctly."
13282 (cond ((looking-at "#[ \t]+")
13283 (match-string 0))
13284 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13285 (save-excursion
13286 (goto-char (match-end 0))
13287 (make-string (current-column) ?\ )))
13288 (t nil)))
13290 ;;; Other stuff.
13292 (defun org-toggle-fixed-width-section (arg)
13293 "Toggle the fixed-width export.
13294 If there is no active region, the QUOTE keyword at the current headline is
13295 inserted or removed. When present, it causes the text between this headline
13296 and the next to be exported as fixed-width text, and unmodified.
13297 If there is an active region, this command adds or removes a colon as the
13298 first character of this line. If the first character of a line is a colon,
13299 this line is also exported in fixed-width font."
13300 (interactive "P")
13301 (let* ((cc 0)
13302 (regionp (org-region-active-p))
13303 (beg (if regionp (region-beginning) (point)))
13304 (end (if regionp (region-end)))
13305 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13306 (case-fold-search nil)
13307 (re "[ \t]*\\(:\\)")
13308 off)
13309 (if regionp
13310 (save-excursion
13311 (goto-char beg)
13312 (setq cc (current-column))
13313 (beginning-of-line 1)
13314 (setq off (looking-at re))
13315 (while (> nlines 0)
13316 (setq nlines (1- nlines))
13317 (beginning-of-line 1)
13318 (cond
13319 (arg
13320 (org-move-to-column cc t)
13321 (insert ":\n")
13322 (forward-line -1))
13323 ((and off (looking-at re))
13324 (replace-match "" t t nil 1))
13325 ((not off) (org-move-to-column cc t) (insert ":")))
13326 (forward-line 1)))
13327 (save-excursion
13328 (org-back-to-heading)
13329 (if (looking-at (concat outline-regexp
13330 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13331 (replace-match "" t t nil 1)
13332 (if (looking-at outline-regexp)
13333 (progn
13334 (goto-char (match-end 0))
13335 (insert org-quote-string " "))))))))
13337 ;;;; Functions extending outline functionality
13339 (defun org-beginning-of-line (&optional arg)
13340 "Go to the beginning of the current line. If that is invisible, continue
13341 to a visible line beginning. This makes the function of C-a more intuitive.
13342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13343 first attempt, and only move to after the tags when the cursor is already
13344 beyond the end of the headline."
13345 (interactive "P")
13346 (let ((pos (point)))
13347 (beginning-of-line 1)
13348 (if (bobp)
13350 (backward-char 1)
13351 (if (org-invisible-p)
13352 (while (and (not (bobp)) (org-invisible-p))
13353 (backward-char 1)
13354 (beginning-of-line 1))
13355 (forward-char 1)))
13356 (when org-special-ctrl-a/e
13357 (cond
13358 ((and (looking-at org-todo-line-regexp)
13359 (= (char-after (match-end 1)) ?\ ))
13360 (goto-char
13361 (if (eq org-special-ctrl-a/e t)
13362 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13363 ((= pos (point)) (match-beginning 3))
13364 (t (point)))
13365 (cond ((> pos (point)) (point))
13366 ((not (eq last-command this-command)) (point))
13367 (t (match-beginning 3))))))
13368 ((org-at-item-p)
13369 (goto-char
13370 (if (eq org-special-ctrl-a/e t)
13371 (cond ((> pos (match-end 4)) (match-end 4))
13372 ((= pos (point)) (match-end 4))
13373 (t (point)))
13374 (cond ((> pos (point)) (point))
13375 ((not (eq last-command this-command)) (point))
13376 (t (match-end 4))))))))))
13378 (defun org-end-of-line (&optional arg)
13379 "Go to the end of the line.
13380 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13381 first attempt, and only move to after the tags when the cursor is already
13382 beyond the end of the headline."
13383 (interactive "P")
13384 (if (or (not org-special-ctrl-a/e)
13385 (not (org-on-heading-p)))
13386 (end-of-line arg)
13387 (let ((pos (point)))
13388 (beginning-of-line 1)
13389 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13390 (if (eq org-special-ctrl-a/e t)
13391 (if (or (< pos (match-beginning 1))
13392 (= pos (match-end 0)))
13393 (goto-char (match-beginning 1))
13394 (goto-char (match-end 0)))
13395 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13396 (goto-char (match-end 0))
13397 (goto-char (match-beginning 1))))
13398 (end-of-line arg)))))
13400 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13401 (define-key org-mode-map "\C-e" 'org-end-of-line)
13403 (defun org-kill-line (&optional arg)
13404 "Kill line, to tags or end of line."
13405 (interactive "P")
13406 (cond
13407 ((or (not org-special-ctrl-k)
13408 (bolp)
13409 (not (org-on-heading-p)))
13410 (call-interactively 'kill-line))
13411 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13412 (kill-region (point) (match-beginning 1))
13413 (org-set-tags nil t))
13414 (t (kill-region (point) (point-at-eol)))))
13416 (define-key org-mode-map "\C-k" 'org-kill-line)
13418 (defun org-invisible-p ()
13419 "Check if point is at a character currently not visible."
13420 ;; Early versions of noutline don't have `outline-invisible-p'.
13421 (if (fboundp 'outline-invisible-p)
13422 (outline-invisible-p)
13423 (get-char-property (point) 'invisible)))
13425 (defun org-invisible-p2 ()
13426 "Check if point is at a character currently not visible."
13427 (save-excursion
13428 (if (and (eolp) (not (bobp))) (backward-char 1))
13429 ;; Early versions of noutline don't have `outline-invisible-p'.
13430 (if (fboundp 'outline-invisible-p)
13431 (outline-invisible-p)
13432 (get-char-property (point) 'invisible))))
13434 (defalias 'org-back-to-heading 'outline-back-to-heading)
13435 (defalias 'org-on-heading-p 'outline-on-heading-p)
13436 (defalias 'org-at-heading-p 'outline-on-heading-p)
13437 (defun org-at-heading-or-item-p ()
13438 (or (org-on-heading-p) (org-at-item-p)))
13440 (defun org-on-target-p ()
13441 (or (org-in-regexp org-radio-target-regexp)
13442 (org-in-regexp org-target-regexp)))
13444 (defun org-up-heading-all (arg)
13445 "Move to the heading line of which the present line is a subheading.
13446 This function considers both visible and invisible heading lines.
13447 With argument, move up ARG levels."
13448 (if (fboundp 'outline-up-heading-all)
13449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13452 (defun org-up-heading-safe ()
13453 "Move to the heading line of which the present line is a subheading.
13454 This version will not throw an error. It will return the level of the
13455 headline found, or nil if no higher level is found."
13456 (let ((pos (point)) start-level level
13457 (re (concat "^" outline-regexp)))
13458 (catch 'exit
13459 (outline-back-to-heading t)
13460 (setq start-level (funcall outline-level))
13461 (if (equal start-level 1) (throw 'exit nil))
13462 (while (re-search-backward re nil t)
13463 (setq level (funcall outline-level))
13464 (if (< level start-level) (throw 'exit level)))
13465 nil)))
13467 (defun org-first-sibling-p ()
13468 "Is this heading the first child of its parents?"
13469 (interactive)
13470 (let ((re (concat "^" outline-regexp))
13471 level l)
13472 (unless (org-at-heading-p t)
13473 (error "Not at a heading"))
13474 (setq level (funcall outline-level))
13475 (save-excursion
13476 (if (not (re-search-backward re nil t))
13478 (setq l (funcall outline-level))
13479 (< l level)))))
13481 (defun org-goto-sibling (&optional previous)
13482 "Goto the next sibling, even if it is invisible.
13483 When PREVIOUS is set, go to the previous sibling instead. Returns t
13484 when a sibling was found. When none is found, return nil and don't
13485 move point."
13486 (let ((fun (if previous 're-search-backward 're-search-forward))
13487 (pos (point))
13488 (re (concat "^" outline-regexp))
13489 level l)
13490 (when (condition-case nil (org-back-to-heading t) (error nil))
13491 (setq level (funcall outline-level))
13492 (catch 'exit
13493 (or previous (forward-char 1))
13494 (while (funcall fun re nil t)
13495 (setq l (funcall outline-level))
13496 (when (< l level) (goto-char pos) (throw 'exit nil))
13497 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13498 (goto-char pos)
13499 nil))))
13501 (defun org-show-siblings ()
13502 "Show all siblings of the current headline."
13503 (save-excursion
13504 (while (org-goto-sibling) (org-flag-heading nil)))
13505 (save-excursion
13506 (while (org-goto-sibling 'previous)
13507 (org-flag-heading nil))))
13509 (defun org-show-hidden-entry ()
13510 "Show an entry where even the heading is hidden."
13511 (save-excursion
13512 (org-show-entry)))
13514 (defun org-flag-heading (flag &optional entry)
13515 "Flag the current heading. FLAG non-nil means make invisible.
13516 When ENTRY is non-nil, show the entire entry."
13517 (save-excursion
13518 (org-back-to-heading t)
13519 ;; Check if we should show the entire entry
13520 (if entry
13521 (progn
13522 (org-show-entry)
13523 (save-excursion
13524 (and (outline-next-heading)
13525 (org-flag-heading nil))))
13526 (outline-flag-region (max (point-min) (1- (point)))
13527 (save-excursion (outline-end-of-heading) (point))
13528 flag))))
13530 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13531 ;; This is an exact copy of the original function, but it uses
13532 ;; `org-back-to-heading', to make it work also in invisible
13533 ;; trees. And is uses an invisible-OK argument.
13534 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13535 (org-back-to-heading invisible-OK)
13536 (let ((first t)
13537 (level (funcall outline-level)))
13538 (while (and (not (eobp))
13539 (or first (> (funcall outline-level) level)))
13540 (setq first nil)
13541 (outline-next-heading))
13542 (unless to-heading
13543 (if (memq (preceding-char) '(?\n ?\^M))
13544 (progn
13545 ;; Go to end of line before heading
13546 (forward-char -1)
13547 (if (memq (preceding-char) '(?\n ?\^M))
13548 ;; leave blank line before heading
13549 (forward-char -1))))))
13550 (point))
13552 (defun org-show-subtree ()
13553 "Show everything after this heading at deeper levels."
13554 (outline-flag-region
13555 (point)
13556 (save-excursion
13557 (outline-end-of-subtree) (outline-next-heading) (point))
13558 nil))
13560 (defun org-show-entry ()
13561 "Show the body directly following this heading.
13562 Show the heading too, if it is currently invisible."
13563 (interactive)
13564 (save-excursion
13565 (condition-case nil
13566 (progn
13567 (org-back-to-heading t)
13568 (outline-flag-region
13569 (max (point-min) (1- (point)))
13570 (save-excursion
13571 (re-search-forward
13572 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13573 (or (match-beginning 1) (point-max)))
13574 nil))
13575 (error nil))))
13577 (defun org-make-options-regexp (kwds)
13578 "Make a regular expression for keyword lines."
13579 (concat
13581 "#?[ \t]*\\+\\("
13582 (mapconcat 'regexp-quote kwds "\\|")
13583 "\\):[ \t]*"
13584 "\\(.+\\)"))
13586 ;; Make isearch reveal the necessary context
13587 (defun org-isearch-end ()
13588 "Reveal context after isearch exits."
13589 (when isearch-success ; only if search was successful
13590 (if (featurep 'xemacs)
13591 ;; Under XEmacs, the hook is run in the correct place,
13592 ;; we directly show the context.
13593 (org-show-context 'isearch)
13594 ;; In Emacs the hook runs *before* restoring the overlays.
13595 ;; So we have to use a one-time post-command-hook to do this.
13596 ;; (Emacs 22 has a special variable, see function `org-mode')
13597 (unless (and (boundp 'isearch-mode-end-hook-quit)
13598 isearch-mode-end-hook-quit)
13599 ;; Only when the isearch was not quitted.
13600 (org-add-hook 'post-command-hook 'org-isearch-post-command
13601 'append 'local)))))
13603 (defun org-isearch-post-command ()
13604 "Remove self from hook, and show context."
13605 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13606 (org-show-context 'isearch))
13609 ;;;; Integration with and fixes for other packages
13611 ;;; Imenu support
13613 (defvar org-imenu-markers nil
13614 "All markers currently used by Imenu.")
13615 (make-variable-buffer-local 'org-imenu-markers)
13617 (defun org-imenu-new-marker (&optional pos)
13618 "Return a new marker for use by Imenu, and remember the marker."
13619 (let ((m (make-marker)))
13620 (move-marker m (or pos (point)))
13621 (push m org-imenu-markers)
13624 (defun org-imenu-get-tree ()
13625 "Produce the index for Imenu."
13626 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13627 (setq org-imenu-markers nil)
13628 (let* ((n org-imenu-depth)
13629 (re (concat "^" outline-regexp))
13630 (subs (make-vector (1+ n) nil))
13631 (last-level 0)
13632 m tree level head)
13633 (save-excursion
13634 (save-restriction
13635 (widen)
13636 (goto-char (point-max))
13637 (while (re-search-backward re nil t)
13638 (setq level (org-reduced-level (funcall outline-level)))
13639 (when (<= level n)
13640 (looking-at org-complex-heading-regexp)
13641 (setq head (org-match-string-no-properties 4)
13642 m (org-imenu-new-marker))
13643 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13644 (if (>= level last-level)
13645 (push (cons head m) (aref subs level))
13646 (push (cons head (aref subs (1+ level))) (aref subs level))
13647 (loop for i from (1+ level) to n do (aset subs i nil)))
13648 (setq last-level level)))))
13649 (aref subs 1)))
13651 (eval-after-load "imenu"
13652 '(progn
13653 (add-hook 'imenu-after-jump-hook
13654 (lambda () (org-show-context 'org-goto)))))
13656 ;; Speedbar support
13658 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13659 "Overlay marking the agenda restriction line in speedbar.")
13660 (org-overlay-put org-speedbar-restriction-lock-overlay
13661 'face 'org-agenda-restriction-lock)
13662 (org-overlay-put org-speedbar-restriction-lock-overlay
13663 'help-echo "Agendas are currently limited to this item.")
13664 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13666 (defun org-speedbar-set-agenda-restriction ()
13667 "Restrict future agenda commands to the location at point in speedbar.
13668 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13669 (interactive)
13670 (require 'org-agenda)
13671 (let (p m tp np dir txt w)
13672 (cond
13673 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13674 'org-imenu t))
13675 (setq m (get-text-property p 'org-imenu-marker))
13676 (save-excursion
13677 (save-restriction
13678 (set-buffer (marker-buffer m))
13679 (goto-char m)
13680 (org-agenda-set-restriction-lock 'subtree))))
13681 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13682 'speedbar-function 'speedbar-find-file))
13683 (setq tp (previous-single-property-change
13684 (1+ p) 'speedbar-function)
13685 np (next-single-property-change
13686 tp 'speedbar-function)
13687 dir (speedbar-line-directory)
13688 txt (buffer-substring-no-properties (or tp (point-min))
13689 (or np (point-max))))
13690 (save-excursion
13691 (save-restriction
13692 (set-buffer (find-file-noselect
13693 (let ((default-directory dir))
13694 (expand-file-name txt))))
13695 (unless (org-mode-p)
13696 (error "Cannot restrict to non-Org-mode file"))
13697 (org-agenda-set-restriction-lock 'file))))
13698 (t (error "Don't know how to restrict Org-mode's agenda")))
13699 (org-move-overlay org-speedbar-restriction-lock-overlay
13700 (point-at-bol) (point-at-eol))
13701 (setq current-prefix-arg nil)
13702 (org-agenda-maybe-redo)))
13704 (eval-after-load "speedbar"
13705 '(progn
13706 (speedbar-add-supported-extension ".org")
13707 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13708 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13709 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13710 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13711 (add-hook 'speedbar-visiting-tag-hook
13712 (lambda () (org-show-context 'org-goto)))))
13715 ;;; Fixes and Hacks for problems with other packages
13717 ;; Make flyspell not check words in links, to not mess up our keymap
13718 (defun org-mode-flyspell-verify ()
13719 "Don't let flyspell put overlays at active buttons."
13720 (not (get-text-property (point) 'keymap)))
13722 ;; Make `bookmark-jump' show the jump location if it was hidden.
13723 (eval-after-load "bookmark"
13724 '(if (boundp 'bookmark-after-jump-hook)
13725 ;; We can use the hook
13726 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13727 ;; Hook not available, use advice
13728 (defadvice bookmark-jump (after org-make-visible activate)
13729 "Make the position visible."
13730 (org-bookmark-jump-unhide))))
13732 (defun org-bookmark-jump-unhide ()
13733 "Unhide the current position, to show the bookmark location."
13734 (and (org-mode-p)
13735 (or (org-invisible-p)
13736 (save-excursion (goto-char (max (point-min) (1- (point))))
13737 (org-invisible-p)))
13738 (org-show-context 'bookmark-jump)))
13740 ;; Make session.el ignore our circular variable
13741 (eval-after-load "session"
13742 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13744 ;;;; Experimental code
13746 (defun org-closed-in-range ()
13747 "Sparse tree of items closed in a certain time range.
13748 Still experimental, may disappear in the future."
13749 (interactive)
13750 ;; Get the time interval from the user.
13751 (let* ((time1 (time-to-seconds
13752 (org-read-date nil 'to-time nil "Starting date: ")))
13753 (time2 (time-to-seconds
13754 (org-read-date nil 'to-time nil "End date:")))
13755 ;; callback function
13756 (callback (lambda ()
13757 (let ((time
13758 (time-to-seconds
13759 (apply 'encode-time
13760 (org-parse-time-string
13761 (match-string 1))))))
13762 ;; check if time in interval
13763 (and (>= time time1) (<= time time2))))))
13764 ;; make tree, check each match with the callback
13765 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13768 ;;;; Finish up
13770 (provide 'org)
13772 (run-hooks 'org-load-hook)
13774 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13776 ;;; org.el ends here