Version number set to 6.01a, release 6.01a.
[org-mode.git] / lisp / org.el
blob9ee6c03f87cf6dc13b395b872b590cfb18e794bc
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.01a
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.01a"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
178 (const :tag "C id: Global id's for identifying entries" org-id)
179 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
180 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
181 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
182 (const :tag "C mew: Support for links to messages in Mew" org-mew)
183 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
184 (const :tag "C registry: A registry for Org links" org-registry)
185 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
186 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
187 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
188 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
191 (defgroup org-startup nil
192 "Options concerning startup of Org-mode."
193 :tag "Org Startup"
194 :group 'org)
196 (defcustom org-startup-folded t
197 "Non-nil means, entering Org-mode will switch to OVERVIEW.
198 This can also be configured on a per-file basis by adding one of
199 the following lines anywhere in the buffer:
201 #+STARTUP: fold
202 #+STARTUP: nofold
203 #+STARTUP: content"
204 :group 'org-startup
205 :type '(choice
206 (const :tag "nofold: show all" nil)
207 (const :tag "fold: overview" t)
208 (const :tag "content: all headlines" content)))
210 (defcustom org-startup-truncated t
211 "Non-nil means, entering Org-mode will set `truncate-lines'.
212 This is useful since some lines containing links can be very long and
213 uninteresting. Also tables look terrible when wrapped."
214 :group 'org-startup
215 :type 'boolean)
217 (defcustom org-startup-align-all-tables nil
218 "Non-nil means, align all tables when visiting a file.
219 This is useful when the column width in tables is forced with <N> cookies
220 in table fields. Such tables will look correct only after the first re-align.
221 This can also be configured on a per-file basis by adding one of
222 the following lines anywhere in the buffer:
223 #+STARTUP: align
224 #+STARTUP: noalign"
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-insert-mode-line-in-empty-file nil
229 "Non-nil means insert the first line setting Org-mode in empty files.
230 When the function `org-mode' is called interactively in an empty file, this
231 normally means that the file name does not automatically trigger Org-mode.
232 To ensure that the file will always be in Org-mode in the future, a
233 line enforcing Org-mode will be inserted into the buffer, if this option
234 has been set."
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-replace-disputed-keys nil
239 "Non-nil means use alternative key bindings for some keys.
240 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
241 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
242 If you want to use Org-mode together with one of these other modes,
243 or more generally if you would like to move some Org-mode commands to
244 other keys, set this variable and configure the keys with the variable
245 `org-disputed-keys'.
247 This option is only relevant at load-time of Org-mode, and must be set
248 *before* org.el is loaded. Changing it requires a restart of Emacs to
249 become effective."
250 :group 'org-startup
251 :type 'boolean)
253 (if (fboundp 'defvaralias)
254 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
256 (defcustom org-disputed-keys
257 '(([(shift up)] . [(meta p)])
258 ([(shift down)] . [(meta n)])
259 ([(shift left)] . [(meta -)])
260 ([(shift right)] . [(meta +)])
261 ([(control shift right)] . [(meta shift +)])
262 ([(control shift left)] . [(meta shift -)]))
263 "Keys for which Org-mode and other modes compete.
264 This is an alist, cars are the default keys, second element specifies
265 the alternative to use when `org-replace-disputed-keys' is t.
267 Keys can be specified in any syntax supported by `define-key'.
268 The value of this option takes effect only at Org-mode's startup,
269 therefore you'll have to restart Emacs to apply it after changing."
270 :group 'org-startup
271 :type 'alist)
273 (defun org-key (key)
274 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
275 Or return the original if not disputed."
276 (if org-replace-disputed-keys
277 (let* ((nkey (key-description key))
278 (x (org-find-if (lambda (x)
279 (equal (key-description (car x)) nkey))
280 org-disputed-keys)))
281 (if x (cdr x) key))
282 key))
284 (defun org-find-if (predicate seq)
285 (catch 'exit
286 (while seq
287 (if (funcall predicate (car seq))
288 (throw 'exit (car seq))
289 (pop seq)))))
291 (defun org-defkey (keymap key def)
292 "Define a key, possibly translated, as returned by `org-key'."
293 (define-key keymap (org-key key) def))
295 (defcustom org-ellipsis nil
296 "The ellipsis to use in the Org-mode outline.
297 When nil, just use the standard three dots. When a string, use that instead,
298 When a face, use the standart 3 dots, but with the specified face.
299 The change affects only Org-mode (which will then use its own display table).
300 Changing this requires executing `M-x org-mode' in a buffer to become
301 effective."
302 :group 'org-startup
303 :type '(choice (const :tag "Default" nil)
304 (face :tag "Face" :value org-warning)
305 (string :tag "String" :value "...#")))
307 (defvar org-display-table nil
308 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
310 (defgroup org-keywords nil
311 "Keywords in Org-mode."
312 :tag "Org Keywords"
313 :group 'org)
315 (defcustom org-deadline-string "DEADLINE:"
316 "String to mark deadline entries.
317 A deadline is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-deadline].
320 Changes become only effective after restarting Emacs."
321 :group 'org-keywords
322 :type 'string)
324 (defcustom org-scheduled-string "SCHEDULED:"
325 "String to mark scheduled TODO entries.
326 A schedule is this string, followed by a time stamp. Should be a word,
327 terminated by a colon. You can insert a schedule keyword and
328 a timestamp with \\[org-schedule].
329 Changes become only effective after restarting Emacs."
330 :group 'org-keywords
331 :type 'string)
333 (defcustom org-closed-string "CLOSED:"
334 "String used as the prefix for timestamps logging closing a TODO entry."
335 :group 'org-keywords
336 :type 'string)
338 (defcustom org-clock-string "CLOCK:"
339 "String used as prefix for timestamps clocking work hours on an item."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-comment-string "COMMENT"
344 "Entries starting with this keyword will never be exported.
345 An entry can be toggled between COMMENT and normal with
346 \\[org-toggle-comment].
347 Changes become only effective after restarting Emacs."
348 :group 'org-keywords
349 :type 'string)
351 (defcustom org-quote-string "QUOTE"
352 "Entries starting with this keyword will be exported in fixed-width font.
353 Quoting applies only to the text in the entry following the headline, and does
354 not extend beyond the next headline, even if that is lower level.
355 An entry can be toggled between QUOTE and normal with
356 \\[org-toggle-fixed-width-section]."
357 :group 'org-keywords
358 :type 'string)
360 (defconst org-repeat-re
361 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
362 "Regular expression for specifying repeated events.
363 After a match, group 1 contains the repeat expression.")
365 (defgroup org-structure nil
366 "Options concerning the general structure of Org-mode files."
367 :tag "Org Structure"
368 :group 'org)
370 (defgroup org-reveal-location nil
371 "Options about how to make context of a location visible."
372 :tag "Org Reveal Location"
373 :group 'org-structure)
375 (defconst org-context-choice
376 '(choice
377 (const :tag "Always" t)
378 (const :tag "Never" nil)
379 (repeat :greedy t :tag "Individual contexts"
380 (cons
381 (choice :tag "Context"
382 (const agenda)
383 (const org-goto)
384 (const occur-tree)
385 (const tags-tree)
386 (const link-search)
387 (const mark-goto)
388 (const bookmark-jump)
389 (const isearch)
390 (const default))
391 (boolean))))
392 "Contexts for the reveal options.")
394 (defcustom org-show-hierarchy-above '((default . t))
395 "Non-nil means, show full hierarchy when revealing a location.
396 Org-mode often shows locations in an org-mode file which might have
397 been invisible before. When this is set, the hierarchy of headings
398 above the exposed location is shown.
399 Turning this off for example for sparse trees makes them very compact.
400 Instead of t, this can also be an alist specifying this option for different
401 contexts. Valid contexts are
402 agenda when exposing an entry from the agenda
403 org-goto when using the command `org-goto' on key C-c C-j
404 occur-tree when using the command `org-occur' on key C-c /
405 tags-tree when constructing a sparse tree based on tags matches
406 link-search when exposing search matches associated with a link
407 mark-goto when exposing the jump goal of a mark
408 bookmark-jump when exposing a bookmark location
409 isearch when exiting from an incremental search
410 default default for all contexts not set explicitly"
411 :group 'org-reveal-location
412 :type org-context-choice)
414 (defcustom org-show-following-heading '((default . nil))
415 "Non-nil means, show following heading when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the heading following the
418 match is shown.
419 Turning this off for example for sparse trees makes them very compact,
420 but makes it harder to edit the location of the match. In such a case,
421 use the command \\[org-reveal] to show more context.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defcustom org-show-siblings '((default . nil) (isearch t))
428 "Non-nil means, show all sibling heading when revealing a location.
429 Org-mode often shows locations in an org-mode file which might have
430 been invisible before. When this is set, the sibling of the current entry
431 heading are all made visible. If `org-show-hierarchy-above' is t,
432 the same happens on each level of the hierarchy above the current entry.
434 By default this is on for the isearch context, off for all other contexts.
435 Turning this off for example for sparse trees makes them very compact,
436 but makes it harder to edit the location of the match. In such a case,
437 use the command \\[org-reveal] to show more context.
438 Instead of t, this can also be an alist specifying this option for different
439 contexts. See `org-show-hierarchy-above' for valid contexts."
440 :group 'org-reveal-location
441 :type org-context-choice)
443 (defcustom org-show-entry-below '((default . nil))
444 "Non-nil means, show the entry below a headline when revealing a location.
445 Org-mode often shows locations in an org-mode file which might have
446 been invisible before. When this is set, the text below the headline that is
447 exposed is also shown.
449 By default this is off for all contexts.
450 Instead of t, this can also be an alist specifying this option for different
451 contexts. See `org-show-hierarchy-above' for valid contexts."
452 :group 'org-reveal-location
453 :type org-context-choice)
455 (defcustom org-indirect-buffer-display 'other-window
456 "How should indirect tree buffers be displayed?
457 This applies to indirect buffers created with the commands
458 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
459 Valid values are:
460 current-window Display in the current window
461 other-window Just display in another window.
462 dedicated-frame Create one new frame, and re-use it each time.
463 new-frame Make a new frame each time. Note that in this case
464 previously-made indirect buffers are kept, and you need to
465 kill these buffers yourself."
466 :group 'org-structure
467 :group 'org-agenda-windows
468 :type '(choice
469 (const :tag "In current window" current-window)
470 (const :tag "In current frame, other window" other-window)
471 (const :tag "Each time a new frame" new-frame)
472 (const :tag "One dedicated frame" dedicated-frame)))
474 (defgroup org-cycle nil
475 "Options concerning visibility cycling in Org-mode."
476 :tag "Org Cycle"
477 :group 'org-structure)
479 (defcustom org-drawers '("PROPERTIES" "CLOCK")
480 "Names of drawers. Drawers are not opened by cycling on the headline above.
481 Drawers only open with a TAB on the drawer line itself. A drawer looks like
482 this:
483 :DRAWERNAME:
484 .....
485 :END:
486 The drawer \"PROPERTIES\" is special for capturing properties through
487 the property API.
489 Drawers can be defined on the per-file basis with a line like:
491 #+DRAWERS: HIDDEN STATE PROPERTIES"
492 :group 'org-structure
493 :type '(repeat (string :tag "Drawer Name")))
495 (defcustom org-cycle-global-at-bob nil
496 "Cycle globally if cursor is at beginning of buffer and not at a headline.
497 This makes it possible to do global cycling without having to use S-TAB or
498 C-u TAB. For this special case to work, the first line of the buffer
499 must not be a headline - it may be empty ot some other text. When used in
500 this way, `org-cycle-hook' is disables temporarily, to make sure the
501 cursor stays at the beginning of the buffer.
502 When this option is nil, don't do anything special at the beginning
503 of the buffer."
504 :group 'org-cycle
505 :type 'boolean)
507 (defcustom org-cycle-emulate-tab t
508 "Where should `org-cycle' emulate TAB.
509 nil Never
510 white Only in completely white lines
511 whitestart Only at the beginning of lines, before the first non-white char
512 t Everywhere except in headlines
513 exc-hl-bol Everywhere except at the start of a headline
514 If TAB is used in a place where it does not emulate TAB, the current subtree
515 visibility is cycled."
516 :group 'org-cycle
517 :type '(choice (const :tag "Never" nil)
518 (const :tag "Only in completely white lines" white)
519 (const :tag "Before first char in a line" whitestart)
520 (const :tag "Everywhere except in headlines" t)
521 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
524 (defcustom org-cycle-separator-lines 2
525 "Number of empty lines needed to keep an empty line between collapsed trees.
526 If you leave an empty line between the end of a subtree and the following
527 headline, this empty line is hidden when the subtree is folded.
528 Org-mode will leave (exactly) one empty line visible if the number of
529 empty lines is equal or larger to the number given in this variable.
530 So the default 2 means, at least 2 empty lines after the end of a subtree
531 are needed to produce free space between a collapsed subtree and the
532 following headline.
534 Special case: when 0, never leave empty lines in collapsed view."
535 :group 'org-cycle
536 :type 'integer)
538 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
539 org-cycle-hide-drawers
540 org-cycle-show-empty-lines
541 org-optimize-window-after-visibility-change)
542 "Hook that is run after `org-cycle' has changed the buffer visibility.
543 The function(s) in this hook must accept a single argument which indicates
544 the new state that was set by the most recent `org-cycle' command. The
545 argument is a symbol. After a global state change, it can have the values
546 `overview', `content', or `all'. After a local state change, it can have
547 the values `folded', `children', or `subtree'."
548 :group 'org-cycle
549 :type 'hook)
551 (defgroup org-edit-structure nil
552 "Options concerning structure editing in Org-mode."
553 :tag "Org Edit Structure"
554 :group 'org-structure)
556 (defcustom org-odd-levels-only nil
557 "Non-nil means, skip even levels and only use odd levels for the outline.
558 This has the effect that two stars are being added/taken away in
559 promotion/demotion commands. It also influences how levels are
560 handled by the exporters.
561 Changing it requires restart of `font-lock-mode' to become effective
562 for fontification also in regions already fontified.
563 You may also set this on a per-file basis by adding one of the following
564 lines to the buffer:
566 #+STARTUP: odd
567 #+STARTUP: oddeven"
568 :group 'org-edit-structure
569 :group 'org-font-lock
570 :type 'boolean)
572 (defcustom org-adapt-indentation t
573 "Non-nil means, adapt indentation when promoting and demoting.
574 When this is set and the *entire* text in an entry is indented, the
575 indentation is increased by one space in a demotion command, and
576 decreased by one in a promotion command. If any line in the entry
577 body starts at column 0, indentation is not changed at all."
578 :group 'org-edit-structure
579 :type 'boolean)
581 (defcustom org-special-ctrl-a/e nil
582 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
583 When t, `C-a' will bring back the cursor to the beginning of the
584 headline text, i.e. after the stars and after a possible TODO keyword.
585 In an item, this will be the position after the bullet.
586 When the cursor is already at that position, another `C-a' will bring
587 it to the beginning of the line.
588 `C-e' will jump to the end of the headline, ignoring the presence of tags
589 in the headline. A second `C-e' will then jump to the true end of the
590 line, after any tags.
591 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
592 and only a directly following, identical keypress will bring the cursor
593 to the special positions."
594 :group 'org-edit-structure
595 :type '(choice
596 (const :tag "off" nil)
597 (const :tag "after bullet first" t)
598 (const :tag "border first" reversed)))
600 (if (fboundp 'defvaralias)
601 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
603 (defcustom org-special-ctrl-k nil
604 "Non-nil means `C-k' will behave specially in headlines.
605 When nil, `C-k' will call the default `kill-line' command.
606 When t, the following will happen while the cursor is in the headline:
608 - When the cursor is at the beginning of a headline, kill the entire
609 line and possible the folded subtree below the line.
610 - When in the middle of the headline text, kill the headline up to the tags.
611 - When after the headline text, kill the tags."
612 :group 'org-edit-structure
613 :type 'boolean)
615 (defcustom org-M-RET-may-split-line '((default . t))
616 "Non-nil means, M-RET will split the line at the cursor position.
617 When nil, it will go to the end of the line before making a
618 new line.
619 You may also set this option in a different way for different
620 contexts. Valid contexts are:
622 headline when creating a new headline
623 item when creating a new item
624 table in a table field
625 default the value to be used for all contexts not explicitly
626 customized"
627 :group 'org-structure
628 :group 'org-table
629 :type '(choice
630 (const :tag "Always" t)
631 (const :tag "Never" nil)
632 (repeat :greedy t :tag "Individual contexts"
633 (cons
634 (choice :tag "Context"
635 (const headline)
636 (const item)
637 (const table)
638 (const default))
639 (boolean)))))
642 (defcustom org-blank-before-new-entry '((heading . nil)
643 (plain-list-item . nil))
644 "Should `org-insert-heading' leave a blank line before new heading/item?
645 The value is an alist, with `heading' and `plain-list-item' as car,
646 and a boolean flag as cdr."
647 :group 'org-edit-structure
648 :type '(list
649 (cons (const heading) (boolean))
650 (cons (const plain-list-item) (boolean))))
652 (defcustom org-insert-heading-hook nil
653 "Hook being run after inserting a new heading."
654 :group 'org-edit-structure
655 :type 'hook)
657 (defcustom org-enable-fixed-width-editor t
658 "Non-nil means, lines starting with \":\" are treated as fixed-width.
659 This currently only means, they are never auto-wrapped.
660 When nil, such lines will be treated like ordinary lines.
661 See also the QUOTE keyword."
662 :group 'org-edit-structure
663 :type 'boolean)
665 (defcustom org-goto-auto-isearch t
666 "Non-nil means, typing characters in org-goto starts incremental search."
667 :group 'org-edit-structure
668 :type 'boolean)
670 (defgroup org-sparse-trees nil
671 "Options concerning sparse trees in Org-mode."
672 :tag "Org Sparse Trees"
673 :group 'org-structure)
675 (defcustom org-highlight-sparse-tree-matches t
676 "Non-nil means, highlight all matches that define a sparse tree.
677 The highlights will automatically disappear the next time the buffer is
678 changed by an edit command."
679 :group 'org-sparse-trees
680 :type 'boolean)
682 (defcustom org-remove-highlights-with-change t
683 "Non-nil means, any change to the buffer will remove temporary highlights.
684 Such highlights are created by `org-occur' and `org-clock-display'.
685 When nil, `C-c C-c needs to be used to get rid of the highlights.
686 The highlights created by `org-preview-latex-fragment' always need
687 `C-c C-c' to be removed."
688 :group 'org-sparse-trees
689 :group 'org-time
690 :type 'boolean)
693 (defcustom org-occur-hook '(org-first-headline-recenter)
694 "Hook that is run after `org-occur' has constructed a sparse tree.
695 This can be used to recenter the window to show as much of the structure
696 as possible."
697 :group 'org-sparse-trees
698 :type 'hook)
700 (defgroup org-plain-lists nil
701 "Options concerning plain lists in Org-mode."
702 :tag "Org Plain lists"
703 :group 'org-structure)
705 (defcustom org-cycle-include-plain-lists nil
706 "Non-nil means, include plain lists into visibility cycling.
707 This means that during cycling, plain list items will *temporarily* be
708 interpreted as outline headlines with a level given by 1000+i where i is the
709 indentation of the bullet. In all other operations, plain list items are
710 not seen as headlines. For example, you cannot assign a TODO keyword to
711 such an item."
712 :group 'org-plain-lists
713 :type 'boolean)
715 (defcustom org-plain-list-ordered-item-terminator t
716 "The character that makes a line with leading number an ordered list item.
717 Valid values are ?. and ?\). To get both terminators, use t. While
718 ?. may look nicer, it creates the danger that a line with leading
719 number may be incorrectly interpreted as an item. ?\) therefore is
720 the safe choice."
721 :group 'org-plain-lists
722 :type '(choice (const :tag "dot like in \"2.\"" ?.)
723 (const :tag "paren like in \"2)\"" ?\))
724 (const :tab "both" t)))
726 (defcustom org-empty-line-terminates-plain-lists nil
727 "Non-nil means, an empty line ends all plain list levels.
728 When nil, empty lines are part of the preceeding item."
729 :group 'org-plain-lists
730 :type 'boolean)
732 (defcustom org-auto-renumber-ordered-lists t
733 "Non-nil means, automatically renumber ordered plain lists.
734 Renumbering happens when the sequence have been changed with
735 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
736 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
737 :group 'org-plain-lists
738 :type 'boolean)
740 (defcustom org-provide-checkbox-statistics t
741 "Non-nil means, update checkbox statistics after insert and toggle.
742 When this is set, checkbox statistics is updated each time you either insert
743 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
744 with \\[org-ctrl-c-ctrl-c\\]."
745 :group 'org-plain-lists
746 :type 'boolean)
749 (defgroup org-imenu-and-speedbar nil
750 "Options concerning imenu and speedbar in Org-mode."
751 :tag "Org Imenu and Speedbar"
752 :group 'org-structure)
754 (defcustom org-imenu-depth 2
755 "The maximum level for Imenu access to Org-mode headlines.
756 This also applied for speedbar access."
757 :group 'org-imenu-and-speedbar
758 :type 'number)
760 (defgroup org-table nil
761 "Options concerning tables in Org-mode."
762 :tag "Org Table"
763 :group 'org)
765 (defcustom org-enable-table-editor 'optimized
766 "Non-nil means, lines starting with \"|\" are handled by the table editor.
767 When nil, such lines will be treated like ordinary lines.
769 When equal to the symbol `optimized', the table editor will be optimized to
770 do the following:
771 - Automatic overwrite mode in front of whitespace in table fields.
772 This makes the structure of the table stay in tact as long as the edited
773 field does not exceed the column width.
774 - Minimize the number of realigns. Normally, the table is aligned each time
775 TAB or RET are pressed to move to another field. With optimization this
776 happens only if changes to a field might have changed the column width.
777 Optimization requires replacing the functions `self-insert-command',
778 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
779 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
780 very good at guessing when a re-align will be necessary, but you can always
781 force one with \\[org-ctrl-c-ctrl-c].
783 If you would like to use the optimized version in Org-mode, but the
784 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
786 This variable can be used to turn on and off the table editor during a session,
787 but in order to toggle optimization, a restart is required.
789 See also the variable `org-table-auto-blank-field'."
790 :group 'org-table
791 :type '(choice
792 (const :tag "off" nil)
793 (const :tag "on" t)
794 (const :tag "on, optimized" optimized)))
796 (defcustom org-table-tab-recognizes-table.el t
797 "Non-nil means, TAB will automatically notice a table.el table.
798 When it sees such a table, it moves point into it and - if necessary -
799 calls `table-recognize-table'."
800 :group 'org-table-editing
801 :type 'boolean)
803 (defgroup org-link nil
804 "Options concerning links in Org-mode."
805 :tag "Org Link"
806 :group 'org)
808 (defvar org-link-abbrev-alist-local nil
809 "Buffer-local version of `org-link-abbrev-alist', which see.
810 The value of this is taken from the #+LINK lines.")
811 (make-variable-buffer-local 'org-link-abbrev-alist-local)
813 (defcustom org-link-abbrev-alist nil
814 "Alist of link abbreviations.
815 The car of each element is a string, to be replaced at the start of a link.
816 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
817 links in Org-mode buffers can have an optional tag after a double colon, e.g.
819 [[linkkey:tag][description]]
821 If REPLACE is a string, the tag will simply be appended to create the link.
822 If the string contains \"%s\", the tag will be inserted there.
824 REPLACE may also be a function that will be called with the tag as the
825 only argument to create the link, which should be returned as a string.
827 See the manual for examples."
828 :group 'org-link
829 :type 'alist)
831 (defcustom org-descriptive-links t
832 "Non-nil means, hide link part and only show description of bracket links.
833 Bracket links are like [[link][descritpion]]. This variable sets the initial
834 state in new org-mode buffers. The setting can then be toggled on a
835 per-buffer basis from the Org->Hyperlinks menu."
836 :group 'org-link
837 :type 'boolean)
839 (defcustom org-link-file-path-type 'adaptive
840 "How the path name in file links should be stored.
841 Valid values are:
843 relative Relative to the current directory, i.e. the directory of the file
844 into which the link is being inserted.
845 absolute Absolute path, if possible with ~ for home directory.
846 noabbrev Absolute path, no abbreviation of home directory.
847 adaptive Use relative path for files in the current directory and sub-
848 directories of it. For other files, use an absolute path."
849 :group 'org-link
850 :type '(choice
851 (const relative)
852 (const absolute)
853 (const noabbrev)
854 (const adaptive)))
856 (defcustom org-activate-links '(bracket angle plain radio tag date)
857 "Types of links that should be activated in Org-mode files.
858 This is a list of symbols, each leading to the activation of a certain link
859 type. In principle, it does not hurt to turn on most link types - there may
860 be a small gain when turning off unused link types. The types are:
862 bracket The recommended [[link][description]] or [[link]] links with hiding.
863 angular Links in angular brackes that may contain whitespace like
864 <bbdb:Carsten Dominik>.
865 plain Plain links in normal text, no whitespace, like http://google.com.
866 radio Text that is matched by a radio target, see manual for details.
867 tag Tag settings in a headline (link to tag search).
868 date Time stamps (link to calendar).
870 Changing this variable requires a restart of Emacs to become effective."
871 :group 'org-link
872 :type '(set (const :tag "Double bracket links (new style)" bracket)
873 (const :tag "Angular bracket links (old style)" angular)
874 (const :tag "Plain text links" plain)
875 (const :tag "Radio target matches" radio)
876 (const :tag "Tags" tag)
877 (const :tag "Timestamps" date)))
879 (defcustom org-make-link-description-function nil
880 "Function to use to generate link descriptions from links. If
881 nil the link location will be used. This function must take two
882 parameters; the first is the link and the second the description
883 org-insert-link has generated, and should return the description
884 to use."
885 :group 'org-link
886 :type 'function)
888 (defgroup org-link-store nil
889 "Options concerning storing links in Org-mode."
890 :tag "Org Store Link"
891 :group 'org-link)
893 (defcustom org-email-link-description-format "Email %c: %.30s"
894 "Format of the description part of a link to an email or usenet message.
895 The following %-excapes will be replaced by corresponding information:
897 %F full \"From\" field
898 %f name, taken from \"From\" field, address if no name
899 %T full \"To\" field
900 %t first name in \"To\" field, address if no name
901 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
902 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
903 %s subject
904 %m message-id.
906 You may use normal field width specification between the % and the letter.
907 This is for example useful to limit the length of the subject.
909 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
910 :group 'org-link-store
911 :type 'string)
913 (defcustom org-from-is-user-regexp
914 (let (r1 r2)
915 (when (and user-mail-address (not (string= user-mail-address "")))
916 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
917 (when (and user-full-name (not (string= user-full-name "")))
918 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
919 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
920 "Regexp mached against the \"From:\" header of an email or usenet message.
921 It should match if the message is from the user him/herself."
922 :group 'org-link-store
923 :type 'regexp)
925 (defcustom org-context-in-file-links t
926 "Non-nil means, file links from `org-store-link' contain context.
927 A search string will be added to the file name with :: as separator and
928 used to find the context when the link is activated by the command
929 `org-open-at-point'.
930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
931 negates this setting for the duration of the command."
932 :group 'org-link-store
933 :type 'boolean)
935 (defcustom org-keep-stored-link-after-insertion nil
936 "Non-nil means, keep link in list for entire session.
938 The command `org-store-link' adds a link pointing to the current
939 location to an internal list. These links accumulate during a session.
940 The command `org-insert-link' can be used to insert links into any
941 Org-mode file (offering completion for all stored links). When this
942 option is nil, every link which has been inserted once using \\[org-insert-link]
943 will be removed from the list, to make completing the unused links
944 more efficient."
945 :group 'org-link-store
946 :type 'boolean)
948 (defgroup org-link-follow nil
949 "Options concerning following links in Org-mode."
950 :tag "Org Follow Link"
951 :group 'org-link)
953 (defcustom org-follow-link-hook nil
954 "Hook that is run after a link has been followed."
955 :group 'org-link-follow
956 :type 'hook)
958 (defcustom org-tab-follows-link nil
959 "Non-nil means, on links TAB will follow the link.
960 Needs to be set before org.el is loaded."
961 :group 'org-link-follow
962 :type 'boolean)
964 (defcustom org-return-follows-link nil
965 "Non-nil means, on links RET will follow the link.
966 Needs to be set before org.el is loaded."
967 :group 'org-link-follow
968 :type 'boolean)
970 (defcustom org-mouse-1-follows-link
971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
972 "Non-nil means, mouse-1 on a link will follow the link.
973 A longer mouse click will still set point. Does not work on XEmacs.
974 Needs to be set before org.el is loaded."
975 :group 'org-link-follow
976 :type 'boolean)
978 (defcustom org-mark-ring-length 4
979 "Number of different positions to be recorded in the ring
980 Changing this requires a restart of Emacs to work correctly."
981 :group 'org-link-follow
982 :type 'interger)
984 (defcustom org-link-frame-setup
985 '((vm . vm-visit-folder-other-frame)
986 (gnus . gnus-other-frame)
987 (file . find-file-other-window))
988 "Setup the frame configuration for following links.
989 When following a link with Emacs, it may often be useful to display
990 this link in another window or frame. This variable can be used to
991 set this up for the different types of links.
992 For VM, use any of
993 `vm-visit-folder'
994 `vm-visit-folder-other-frame'
995 For Gnus, use any of
996 `gnus'
997 `gnus-other-frame'
998 For FILE, use any of
999 `find-file'
1000 `find-file-other-window'
1001 `find-file-other-frame'
1002 For the calendar, use the variable `calendar-setup'.
1003 For BBDB, it is currently only possible to display the matches in
1004 another window."
1005 :group 'org-link-follow
1006 :type '(list
1007 (cons (const vm)
1008 (choice
1009 (const vm-visit-folder)
1010 (const vm-visit-folder-other-window)
1011 (const vm-visit-folder-other-frame)))
1012 (cons (const gnus)
1013 (choice
1014 (const gnus)
1015 (const gnus-other-frame)))
1016 (cons (const file)
1017 (choice
1018 (const find-file)
1019 (const find-file-other-window)
1020 (const find-file-other-frame)))))
1022 (defcustom org-display-internal-link-with-indirect-buffer nil
1023 "Non-nil means, use indirect buffer to display infile links.
1024 Activating internal links (from one location in a file to another location
1025 in the same file) normally just jumps to the location. When the link is
1026 activated with a C-u prefix (or with mouse-3), the link is displayed in
1027 another window. When this option is set, the other window actually displays
1028 an indirect buffer clone of the current buffer, to avoid any visibility
1029 changes to the current buffer."
1030 :group 'org-link-follow
1031 :type 'boolean)
1033 (defcustom org-open-non-existing-files nil
1034 "Non-nil means, `org-open-file' will open non-existing files.
1035 When nil, an error will be generated."
1036 :group 'org-link-follow
1037 :type 'boolean)
1039 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1040 "Function and arguments to call for following mailto links.
1041 This is a list with the first element being a lisp function, and the
1042 remaining elements being arguments to the function. In string arguments,
1043 %a will be replaced by the address, and %s will be replaced by the subject
1044 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1045 :group 'org-link-follow
1046 :type '(choice
1047 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1048 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1049 (const :tag "message-mail" (message-mail "%a" "%s"))
1050 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1052 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1053 "Non-nil means, ask for confirmation before executing shell links.
1054 Shell links can be dangerous: just think about a link
1056 [[shell:rm -rf ~/*][Google Search]]
1058 This link would show up in your Org-mode document as \"Google Search\",
1059 but really it would remove your entire home directory.
1060 Therefore we advise against setting this variable to nil.
1061 Just change it to `y-or-n-p' of you want to confirm with a
1062 single keystroke rather than having to type \"yes\"."
1063 :group 'org-link-follow
1064 :type '(choice
1065 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1066 (const :tag "with y-or-n (faster)" y-or-n-p)
1067 (const :tag "no confirmation (dangerous)" nil)))
1069 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1070 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1071 Elisp links can be dangerous: just think about a link
1073 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1075 This link would show up in your Org-mode document as \"Google Search\",
1076 but really it would remove your entire home directory.
1077 Therefore we advise against setting this variable to nil.
1078 Just change it to `y-or-n-p' of you want to confirm with a
1079 single keystroke rather than having to type \"yes\"."
1080 :group 'org-link-follow
1081 :type '(choice
1082 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1083 (const :tag "with y-or-n (faster)" y-or-n-p)
1084 (const :tag "no confirmation (dangerous)" nil)))
1086 (defconst org-file-apps-defaults-gnu
1087 '((remote . emacs)
1088 (t . mailcap))
1089 "Default file applications on a UNIX or GNU/Linux system.
1090 See `org-file-apps'.")
1092 (defconst org-file-apps-defaults-macosx
1093 '((remote . emacs)
1094 (t . "open %s")
1095 ("ps" . "gv %s")
1096 ("ps.gz" . "gv %s")
1097 ("eps" . "gv %s")
1098 ("eps.gz" . "gv %s")
1099 ("dvi" . "xdvi %s")
1100 ("fig" . "xfig %s"))
1101 "Default file applications on a MacOS X system.
1102 The system \"open\" is known as a default, but we use X11 applications
1103 for some files for which the OS does not have a good default.
1104 See `org-file-apps'.")
1106 (defconst org-file-apps-defaults-windowsnt
1107 (list
1108 '(remote . emacs)
1109 (cons t
1110 (list (if (featurep 'xemacs)
1111 'mswindows-shell-execute
1112 'w32-shell-execute)
1113 "open" 'file)))
1114 "Default file applications on a Windows NT system.
1115 The system \"open\" is used for most files.
1116 See `org-file-apps'.")
1118 (defcustom org-file-apps
1120 ("txt" . emacs)
1121 ("tex" . emacs)
1122 ("ltx" . emacs)
1123 ("org" . emacs)
1124 ("el" . emacs)
1125 ("bib" . emacs)
1127 "External applications for opening `file:path' items in a document.
1128 Org-mode uses system defaults for different file types, but
1129 you can use this variable to set the application for a given file
1130 extension. The entries in this list are cons cells where the car identifies
1131 files and the cdr the corresponding command. Possible values for the
1132 file identifier are
1133 \"ext\" A string identifying an extension
1134 `directory' Matches a directory
1135 `remote' Matches a remote file, accessible through tramp or efs.
1136 Remote files most likely should be visited through Emacs
1137 because external applications cannot handle such paths.
1138 t Default for all remaining files
1140 Possible values for the command are:
1141 `emacs' The file will be visited by the current Emacs process.
1142 `default' Use the default application for this file type.
1143 string A command to be executed by a shell; %s will be replaced
1144 by the path to the file.
1145 sexp A Lisp form which will be evaluated. The file path will
1146 be available in the Lisp variable `file'.
1147 For more examples, see the system specific constants
1148 `org-file-apps-defaults-macosx'
1149 `org-file-apps-defaults-windowsnt'
1150 `org-file-apps-defaults-gnu'."
1151 :group 'org-link-follow
1152 :type '(repeat
1153 (cons (choice :value ""
1154 (string :tag "Extension")
1155 (const :tag "Default for unrecognized files" t)
1156 (const :tag "Remote file" remote)
1157 (const :tag "Links to a directory" directory))
1158 (choice :value ""
1159 (const :tag "Visit with Emacs" emacs)
1160 (const :tag "Use system default" default)
1161 (string :tag "Command")
1162 (sexp :tag "Lisp form")))))
1164 (defgroup org-refile nil
1165 "Options concerning refiling entries in Org-mode."
1166 :tag "Org Remember"
1167 :group 'org)
1169 (defcustom org-directory "~/org"
1170 "Directory with org files.
1171 This directory will be used as default to prompt for org files.
1172 Used by the hooks for remember.el."
1173 :group 'org-refile
1174 :group 'org-remember
1175 :type 'directory)
1177 (defcustom org-default-notes-file "~/.notes"
1178 "Default target for storing notes.
1179 Used by the hooks for remember.el. This can be a string, or nil to mean
1180 the value of `remember-data-file'.
1181 You can set this on a per-template basis with the variable
1182 `org-remember-templates'."
1183 :group 'org-refile
1184 :group 'org-remember
1185 :type '(choice
1186 (const :tag "Default from remember-data-file" nil)
1187 file))
1189 (defcustom org-goto-interface 'outline
1190 "The default interface to be used for `org-goto'.
1191 Allowed vaues are:
1192 outline The interface shows an outline of the relevant file
1193 and the correct heading is found by moving through
1194 the outline or by searching with incremental search.
1195 outline-path-completion Headlines in the current buffer are offered via
1196 completion."
1197 :group 'org-refile
1198 :type '(choice
1199 (const :tag "Outline" outline)
1200 (const :tag "Outline-path-completion" outline-path-completion)))
1202 (defcustom org-reverse-note-order nil
1203 "Non-nil means, store new notes at the beginning of a file or entry.
1204 When nil, new notes will be filed to the end of a file or entry.
1205 This can also be a list with cons cells of regular expressions that
1206 are matched against file names, and values."
1207 :group 'org-remember
1208 :type '(choice
1209 (const :tag "Reverse always" t)
1210 (const :tag "Reverse never" nil)
1211 (repeat :tag "By file name regexp"
1212 (cons regexp boolean))))
1214 (defcustom org-refile-targets nil
1215 "Targets for refiling entries with \\[org-refile].
1216 This is list of cons cells. Each cell contains:
1217 - a specification of the files to be considered, either a list of files,
1218 or a symbol whose function or variable value will be used to retrieve
1219 a file name or a list of file names. Nil means, refile to a different
1220 heading in the current buffer.
1221 - A specification of how to find candidate refile targets. This may be
1222 any of
1223 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1224 This tag has to be present in all target headlines, inheritance will
1225 not be considered.
1226 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1227 todo keyword.
1228 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1229 headlines that are refiling targets.
1230 - a cons cell (:level . N). Any headline of level N is considered a target.
1231 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1232 :group 'org-remember
1233 :type '(repeat
1234 (cons
1235 (choice :value org-agenda-files
1236 (const :tag "All agenda files" org-agenda-files)
1237 (const :tag "Current buffer" nil)
1238 (function) (variable) (file))
1239 (choice :tag "Identify target headline by"
1240 (cons :tag "Specific tag" (const :tag) (string))
1241 (cons :tag "TODO keyword" (const :todo) (string))
1242 (cons :tag "Regular expression" (const :regexp) (regexp))
1243 (cons :tag "Level number" (const :level) (integer))
1244 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1246 (defcustom org-refile-use-outline-path nil
1247 "Non-nil means, provide refile targets as paths.
1248 So a level 3 headline will be available as level1/level2/level3.
1249 When the value is `file', also include the file name (without directory)
1250 into the path. When `full-file-path', include the full file path."
1251 :group 'org-remember
1252 :type '(choice
1253 (const :tag "Not" nil)
1254 (const :tag "Yes" t)
1255 (const :tag "Start with file name" file)
1256 (const :tag "Start with full file path" full-file-path)))
1258 (defgroup org-todo nil
1259 "Options concerning TODO items in Org-mode."
1260 :tag "Org TODO"
1261 :group 'org)
1263 (defgroup org-progress nil
1264 "Options concerning Progress logging in Org-mode."
1265 :tag "Org Progress"
1266 :group 'org-time)
1268 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1269 "List of TODO entry keyword sequences and their interpretation.
1270 \\<org-mode-map>This is a list of sequences.
1272 Each sequence starts with a symbol, either `sequence' or `type',
1273 indicating if the keywords should be interpreted as a sequence of
1274 action steps, or as different types of TODO items. The first
1275 keywords are states requiring action - these states will select a headline
1276 for inclusion into the global TODO list Org-mode produces. If one of
1277 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1278 signify that no further action is necessary. If \"|\" is not found,
1279 the last keyword is treated as the only DONE state of the sequence.
1281 The command \\[org-todo] cycles an entry through these states, and one
1282 additional state where no keyword is present. For details about this
1283 cycling, see the manual.
1285 TODO keywords and interpretation can also be set on a per-file basis with
1286 the special #+SEQ_TODO and #+TYP_TODO lines.
1288 Each keyword can optionally specify a character for fast state selection
1289 \(in combination with the variable `org-use-fast-todo-selection')
1290 and specifiers for state change logging, using the same syntax
1291 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1292 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1293 indicates to record a time stamp each time this state is selected.
1295 Each keyword may also specify if a timestamp or a note should be
1296 recorded when entering or leaving the state, by adding additional
1297 characters in the parenthesis after the keyword. This looks like this:
1298 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1299 record only the time of the state change. With X and Y being either
1300 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1301 Y when leaving the state if and only if the *target* state does not
1302 define X. You may omit any of the fast-selection key or X or /Y,
1303 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1305 For backward compatibility, this variable may also be just a list
1306 of keywords - in this case the interptetation (sequence or type) will be
1307 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1308 :group 'org-todo
1309 :group 'org-keywords
1310 :type '(choice
1311 (repeat :tag "Old syntax, just keywords"
1312 (string :tag "Keyword"))
1313 (repeat :tag "New syntax"
1314 (cons
1315 (choice
1316 :tag "Interpretation"
1317 (const :tag "Sequence (cycling hits every state)" sequence)
1318 (const :tag "Type (cycling directly to DONE)" type))
1319 (repeat
1320 (string :tag "Keyword"))))))
1322 (defvar org-todo-keywords-1 nil
1323 "All TODO and DONE keywords active in a buffer.")
1324 (make-variable-buffer-local 'org-todo-keywords-1)
1325 (defvar org-todo-keywords-for-agenda nil)
1326 (defvar org-done-keywords-for-agenda nil)
1327 (defvar org-not-done-keywords nil)
1328 (make-variable-buffer-local 'org-not-done-keywords)
1329 (defvar org-done-keywords nil)
1330 (make-variable-buffer-local 'org-done-keywords)
1331 (defvar org-todo-heads nil)
1332 (make-variable-buffer-local 'org-todo-heads)
1333 (defvar org-todo-sets nil)
1334 (make-variable-buffer-local 'org-todo-sets)
1335 (defvar org-todo-log-states nil)
1336 (make-variable-buffer-local 'org-todo-log-states)
1337 (defvar org-todo-kwd-alist nil)
1338 (make-variable-buffer-local 'org-todo-kwd-alist)
1339 (defvar org-todo-key-alist nil)
1340 (make-variable-buffer-local 'org-todo-key-alist)
1341 (defvar org-todo-key-trigger nil)
1342 (make-variable-buffer-local 'org-todo-key-trigger)
1344 (defcustom org-todo-interpretation 'sequence
1345 "Controls how TODO keywords are interpreted.
1346 This variable is in principle obsolete and is only used for
1347 backward compatibility, if the interpretation of todo keywords is
1348 not given already in `org-todo-keywords'. See that variable for
1349 more information."
1350 :group 'org-todo
1351 :group 'org-keywords
1352 :type '(choice (const sequence)
1353 (const type)))
1355 (defcustom org-use-fast-todo-selection 'prefix
1356 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1357 This variable describes if and under what circumstances the cycling
1358 mechanism for TODO keywords will be replaced by a single-key, direct
1359 selection scheme.
1361 When nil, fast selection is never used.
1363 When the symbol `prefix', it will be used when `org-todo' is called with
1364 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1365 in an agenda buffer.
1367 When t, fast selection is used by default. In this case, the prefix
1368 argument forces cycling instead.
1370 In all cases, the special interface is only used if access keys have actually
1371 been assigned by the user, i.e. if keywords in the configuration are followed
1372 by a letter in parenthesis, like TODO(t)."
1373 :group 'org-todo
1374 :type '(choice
1375 (const :tag "Never" nil)
1376 (const :tag "By default" t)
1377 (const :tag "Only with C-u C-c C-t" prefix)))
1379 (defcustom org-after-todo-state-change-hook nil
1380 "Hook which is run after the state of a TODO item was changed.
1381 The new state (a string with a TODO keyword, or nil) is available in the
1382 Lisp variable `state'."
1383 :group 'org-todo
1384 :type 'hook)
1386 (defcustom org-log-done nil
1387 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1388 When equal to the list (done), also prompt for a closing note.
1389 This can also be configured on a per-file basis by adding one of
1390 the following lines anywhere in the buffer:
1392 #+STARTUP: logdone
1393 #+STARTUP: lognotedone
1394 #+STARTUP: nologdone"
1395 :group 'org-todo
1396 :group 'org-progress
1397 :type '(choice
1398 (const :tag "No logging" nil)
1399 (const :tag "Record CLOSED timestamp" time)
1400 (const :tag "Record CLOSED timestamp with closing note." note)))
1402 ;; Normalize old uses of org-log-done.
1403 (cond
1404 ((eq org-log-done t) (setq org-log-done 'time))
1405 ((and (listp org-log-done) (memq 'done org-log-done))
1406 (setq org-log-done 'note)))
1408 (defcustom org-log-note-clock-out nil
1409 "Non-nil means, recored a note when clocking out of an item.
1410 This can also be configured on a per-file basis by adding one of
1411 the following lines anywhere in the buffer:
1413 #+STARTUP: lognoteclock-out
1414 #+STARTUP: nolognoteclock-out"
1415 :group 'org-todo
1416 :group 'org-progress
1417 :type 'boolean)
1419 (defcustom org-log-done-with-time t
1420 "Non-nil means, the CLOSED time stamp will contain date and time.
1421 When nil, only the date will be recorded."
1422 :group 'org-progress
1423 :type 'boolean)
1425 (defcustom org-log-note-headings
1426 '((done . "CLOSING NOTE %t")
1427 (state . "State %-12s %t")
1428 (note . "Note taken on %t")
1429 (clock-out . ""))
1430 "Headings for notes added to entries.
1431 The value is an alist, with the car being a symbol indicating the note
1432 context, and the cdr is the heading to be used. The heading may also be the
1433 empty string.
1434 %t in the heading will be replaced by a time stamp.
1435 %s will be replaced by the new TODO state, in double quotes.
1436 %u will be replaced by the user name.
1437 %U will be replaced by the full user name."
1438 :group 'org-todo
1439 :group 'org-progress
1440 :type '(list :greedy t
1441 (cons (const :tag "Heading when closing an item" done) string)
1442 (cons (const :tag
1443 "Heading when changing todo state (todo sequence only)"
1444 state) string)
1445 (cons (const :tag "Heading when just taking a note" note) string)
1446 (cons (const :tag "Heading when clocking out" clock-out) string)))
1448 (unless (assq 'note org-log-note-headings)
1449 (push '(note . "%t") org-log-note-headings))
1451 (defcustom org-log-states-order-reversed t
1452 "Non-nil means, the latest state change note will be directly after heading.
1453 When nil, the notes will be orderer according to time."
1454 :group 'org-todo
1455 :group 'org-progress
1456 :type 'boolean)
1458 (defcustom org-log-repeat 'time
1459 "Non-nil means, record moving through the DONE state when triggering repeat.
1460 An auto-repeating tasks is immediately switched back to TODO when marked
1461 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1462 the TODO keyword definition, or recording a cloing note by setting
1463 `org-log-done', there will be no record of the task moving trhough DONE.
1464 This variable forces taking a note anyway. Possible values are:
1466 nil Don't force a record
1467 time Record a time stamp
1468 note Record a note
1470 This option can also be set with on a per-file-basis with
1472 #+STARTUP: logrepeat
1473 #+STARTUP: lognoterepeat
1474 #+STARTUP: nologrepeat
1476 You can have local logging settings for a subtree by setting the LOGGING
1477 property to one or more of these keywords."
1478 :group 'org-todo
1479 :group 'org-progress
1480 :type '(choice
1481 (const :tag "Don't force a record" nil)
1482 (const :tag "Force recording the DONE state" time)
1483 (const :tag "Force recording a note with the DONE state" note)))
1486 (defgroup org-priorities nil
1487 "Priorities in Org-mode."
1488 :tag "Org Priorities"
1489 :group 'org-todo)
1491 (defcustom org-highest-priority ?A
1492 "The highest priority of TODO items. A character like ?A, ?B etc.
1493 Must have a smaller ASCII number than `org-lowest-priority'."
1494 :group 'org-priorities
1495 :type 'character)
1497 (defcustom org-lowest-priority ?C
1498 "The lowest priority of TODO items. A character like ?A, ?B etc.
1499 Must have a larger ASCII number than `org-highest-priority'."
1500 :group 'org-priorities
1501 :type 'character)
1503 (defcustom org-default-priority ?B
1504 "The default priority of TODO items.
1505 This is the priority an item get if no explicit priority is given."
1506 :group 'org-priorities
1507 :type 'character)
1509 (defcustom org-priority-start-cycle-with-default t
1510 "Non-nil means, start with default priority when starting to cycle.
1511 When this is nil, the first step in the cycle will be (depending on the
1512 command used) one higher or lower that the default priority."
1513 :group 'org-priorities
1514 :type 'boolean)
1516 (defgroup org-time nil
1517 "Options concerning time stamps and deadlines in Org-mode."
1518 :tag "Org Time"
1519 :group 'org)
1521 (defcustom org-insert-labeled-timestamps-at-point nil
1522 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1523 When nil, these labeled time stamps are forces into the second line of an
1524 entry, just after the headline. When scheduling from the global TODO list,
1525 the time stamp will always be forced into the second line."
1526 :group 'org-time
1527 :type 'boolean)
1529 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1530 "Formats for `format-time-string' which are used for time stamps.
1531 It is not recommended to change this constant.")
1533 (defcustom org-time-stamp-rounding-minutes '(0 5)
1534 "Number of minutes to round time stamps to.
1535 These are two values, the first applies when first creating a time stamp.
1536 The second applies when changing it with the commands `S-up' and `S-down'.
1537 When changing the time stamp, this means that it will change in steps
1538 of N minutes, as given by the second value.
1540 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1541 numbers should be factors of 60, so for example 5, 10, 15.
1543 When this is larger than 1, you can still force an exact time-stamp by using
1544 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1545 and by using a prefix arg to `S-up/down' to specify the exact number
1546 of minutes to shift."
1547 :group 'org-time
1548 :get '(lambda (var) ; Make sure all entries have 5 elements
1549 (if (integerp (default-value var))
1550 (list (default-value var) 5)
1551 (default-value var)))
1552 :type '(list
1553 (integer :tag "when inserting times")
1554 (integer :tag "when modifying times")))
1556 ;; Normalize old customizations of this variable.
1557 (when (integerp org-time-stamp-rounding-minutes)
1558 (setq org-time-stamp-rounding-minutes
1559 (list org-time-stamp-rounding-minutes
1560 org-time-stamp-rounding-minutes)))
1562 (defcustom org-display-custom-times nil
1563 "Non-nil means, overlay custom formats over all time stamps.
1564 The formats are defined through the variable `org-time-stamp-custom-formats'.
1565 To turn this on on a per-file basis, insert anywhere in the file:
1566 #+STARTUP: customtime"
1567 :group 'org-time
1568 :set 'set-default
1569 :type 'sexp)
1570 (make-variable-buffer-local 'org-display-custom-times)
1572 (defcustom org-time-stamp-custom-formats
1573 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1574 "Custom formats for time stamps. See `format-time-string' for the syntax.
1575 These are overlayed over the default ISO format if the variable
1576 `org-display-custom-times' is set. Time like %H:%M should be at the
1577 end of the second format."
1578 :group 'org-time
1579 :type 'sexp)
1581 (defun org-time-stamp-format (&optional long inactive)
1582 "Get the right format for a time string."
1583 (let ((f (if long (cdr org-time-stamp-formats)
1584 (car org-time-stamp-formats))))
1585 (if inactive
1586 (concat "[" (substring f 1 -1) "]")
1587 f)))
1589 (defcustom org-deadline-warning-days 14
1590 "No. of days before expiration during which a deadline becomes active.
1591 This variable governs the display in sparse trees and in the agenda.
1592 When 0 or negative, it means use this number (the absolute value of it)
1593 even if a deadline has a different individual lead time specified."
1594 :group 'org-time
1595 :group 'org-agenda-daily/weekly
1596 :type 'number)
1598 (defcustom org-read-date-prefer-future t
1599 "Non-nil means, assume future for incomplete date input from user.
1600 This affects the following situations:
1601 1. The user gives a day, but no month.
1602 For example, if today is the 15th, and you enter \"3\", Org-mode will
1603 read this as the third of *next* month. However, if you enter \"17\",
1604 it will be considered as *this* month.
1605 2. The user gives a month but not a year.
1606 For example, if it is april and you enter \"feb 2\", this will be read
1607 as feb 2, *next* year. \"May 5\", however, will be this year.
1609 Currently this does not work for ISO week specifications.
1611 When this option is nil, the current month and year will always be used
1612 as defaults."
1613 :group 'org-time
1614 :type 'boolean)
1616 (defcustom org-read-date-display-live t
1617 "Non-nil means, display current interpretation of date prompt live.
1618 This display will be in an overlay, in the minibuffer."
1619 :group 'org-time
1620 :type 'boolean)
1622 (defcustom org-read-date-popup-calendar t
1623 "Non-nil means, pop up a calendar when prompting for a date.
1624 In the calendar, the date can be selected with mouse-1. However, the
1625 minibuffer will also be active, and you can simply enter the date as well.
1626 When nil, only the minibuffer will be available."
1627 :group 'org-time
1628 :type 'boolean)
1629 (if (fboundp 'defvaralias)
1630 (defvaralias 'org-popup-calendar-for-date-prompt
1631 'org-read-date-popup-calendar))
1633 (defcustom org-extend-today-until 0
1634 "The hour when your day really ends.
1635 This has influence for the following applications:
1636 - When switching the agenda to \"today\". It it is still earlier than
1637 the time given here, the day recognized as TODAY is actually yesterday.
1638 - When a date is read from the user and it is still before the time given
1639 here, the current date and time will be assumed to be yesterday, 23:59.
1641 FIXME:
1642 IMPORTANT: This is still a very experimental feature, it may disappear
1643 again or it may be extended to mean more things."
1644 :group 'org-time
1645 :type 'number)
1647 (defcustom org-edit-timestamp-down-means-later nil
1648 "Non-nil means, S-down will increase the time in a time stamp.
1649 When nil, S-up will increase."
1650 :group 'org-time
1651 :type 'boolean)
1653 (defcustom org-calendar-follow-timestamp-change t
1654 "Non-nil means, make the calendar window follow timestamp changes.
1655 When a timestamp is modified and the calendar window is visible, it will be
1656 moved to the new date."
1657 :group 'org-time
1658 :type 'boolean)
1660 (defgroup org-tags nil
1661 "Options concerning tags in Org-mode."
1662 :tag "Org Tags"
1663 :group 'org)
1665 (defcustom org-tag-alist nil
1666 "List of tags allowed in Org-mode files.
1667 When this list is nil, Org-mode will base TAG input on what is already in the
1668 buffer.
1669 The value of this variable is an alist, the car of each entry must be a
1670 keyword as a string, the cdr may be a character that is used to select
1671 that tag through the fast-tag-selection interface.
1672 See the manual for details."
1673 :group 'org-tags
1674 :type '(repeat
1675 (choice
1676 (cons (string :tag "Tag name")
1677 (character :tag "Access char"))
1678 (const :tag "Start radio group" (:startgroup))
1679 (const :tag "End radio group" (:endgroup)))))
1681 (defcustom org-use-fast-tag-selection 'auto
1682 "Non-nil means, use fast tag selection scheme.
1683 This is a special interface to select and deselect tags with single keys.
1684 When nil, fast selection is never used.
1685 When the symbol `auto', fast selection is used if and only if selection
1686 characters for tags have been configured, either through the variable
1687 `org-tag-alist' or through a #+TAGS line in the buffer.
1688 When t, fast selection is always used and selection keys are assigned
1689 automatically if necessary."
1690 :group 'org-tags
1691 :type '(choice
1692 (const :tag "Always" t)
1693 (const :tag "Never" nil)
1694 (const :tag "When selection characters are configured" 'auto)))
1696 (defcustom org-fast-tag-selection-single-key nil
1697 "Non-nil means, fast tag selection exits after first change.
1698 When nil, you have to press RET to exit it.
1699 During fast tag selection, you can toggle this flag with `C-c'.
1700 This variable can also have the value `expert'. In this case, the window
1701 displaying the tags menu is not even shown, until you press C-c again."
1702 :group 'org-tags
1703 :type '(choice
1704 (const :tag "No" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Expert" expert)))
1708 (defvar org-fast-tag-selection-include-todo nil
1709 "Non-nil means, fast tags selection interface will also offer TODO states.
1710 This is an undocumented feature, you should not rely on it.")
1712 (defcustom org-tags-column -80
1713 "The column to which tags should be indented in a headline.
1714 If this number is positive, it specifies the column. If it is negative,
1715 it means that the tags should be flushright to that column. For example,
1716 -80 works well for a normal 80 character screen."
1717 :group 'org-tags
1718 :type 'integer)
1720 (defcustom org-auto-align-tags t
1721 "Non-nil means, realign tags after pro/demotion of TODO state change.
1722 These operations change the length of a headline and therefore shift
1723 the tags around. With this options turned on, after each such operation
1724 the tags are again aligned to `org-tags-column'."
1725 :group 'org-tags
1726 :type 'boolean)
1728 (defcustom org-use-tag-inheritance t
1729 "Non-nil means, tags in levels apply also for sublevels.
1730 When nil, only the tags directly given in a specific line apply there.
1731 If you turn off this option, you very likely want to turn on the
1732 companion option `org-tags-match-list-sublevels'.
1734 This may also be a list of tags that should be inherited, or a regexp that
1735 matches tags that should be inherited."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Not" nil)
1739 (const :tag "Always" t)
1740 (repeat :tag "Specific tags" (string :tag "Tag"))
1741 (regexp :tag "Tags matched by regexp")))
1743 (defun org-tag-inherit-p (tag)
1744 "Check if TAG is one that should be inherited."
1745 (cond
1746 ((eq org-use-tag-inheritance t) t)
1747 ((not org-use-tag-inheritance) nil)
1748 ((stringp org-use-tag-inheritance)
1749 (string-match org-use-tag-inheritance tag))
1750 ((listp org-use-tag-inheritance)
1751 (member tag org-use-tag-inheritance))
1752 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1754 (defcustom org-tags-match-list-sublevels nil
1755 "Non-nil means list also sublevels of headlines matching tag search.
1756 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1757 the sublevels of a headline matching a tag search often also match
1758 the same search. Listing all of them can create very long lists.
1759 Setting this variable to nil causes subtrees of a match to be skipped.
1760 This option is off by default, because inheritance in on. If you turn
1761 inheritance off, you very likely want to turn this option on.
1763 As a special case, if the tag search is restricted to TODO items, the
1764 value of this variable is ignored and sublevels are always checked, to
1765 make sure all corresponding TODO items find their way into the list."
1766 :group 'org-tags
1767 :type 'boolean)
1769 (defvar org-tags-history nil
1770 "History of minibuffer reads for tags.")
1771 (defvar org-last-tags-completion-table nil
1772 "The last used completion table for tags.")
1773 (defvar org-after-tags-change-hook nil
1774 "Hook that is run after the tags in a line have changed.")
1776 (defgroup org-properties nil
1777 "Options concerning properties in Org-mode."
1778 :tag "Org Properties"
1779 :group 'org)
1781 (defcustom org-property-format "%-10s %s"
1782 "How property key/value pairs should be formatted by `indent-line'.
1783 When `indent-line' hits a property definition, it will format the line
1784 according to this format, mainly to make sure that the values are
1785 lined-up with respect to each other."
1786 :group 'org-properties
1787 :type 'string)
1789 (defcustom org-use-property-inheritance nil
1790 "Non-nil means, properties apply also for sublevels.
1792 This setting is chiefly used during property searches. Turning it on can
1793 cause significant overhead when doing a search, which is why it is not
1794 on by default.
1796 When nil, only the properties directly given in the current entry count.
1797 When t, every property is inherited. The value may also be a list of
1798 properties that should have inheritance, or a regular expression matching
1799 properties that should be inherited.
1801 However, note that some special properties use inheritance under special
1802 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1803 and the properties ending in \"_ALL\" when they are used as descriptor
1804 for valid values of a property.
1806 Note for programmers:
1807 When querying an entry with `org-entry-get', you can control if inheritance
1808 should be used. By default, `org-entry-get' looks only at the local
1809 properties. You can request inheritance by setting the inherit argument
1810 to t (to force inheritance) or to `selective' (to respect the setting
1811 in this variable)."
1812 :group 'org-properties
1813 :type '(choice
1814 (const :tag "Not" nil)
1815 (const :tag "Always" t)
1816 (repeat :tag "Specific properties" (string :tag "Property"))
1817 (regexp :tag "Properties matched by regexp")))
1819 (defun org-property-inherit-p (property)
1820 "Check if PROPERTY is one that should be inherited."
1821 (cond
1822 ((eq org-use-property-inheritance t) t)
1823 ((not org-use-property-inheritance) nil)
1824 ((stringp org-use-property-inheritance)
1825 (string-match org-use-property-inheritance property))
1826 ((listp org-use-property-inheritance)
1827 (member property org-use-property-inheritance))
1828 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1830 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1831 "The default column format, if no other format has been defined.
1832 This variable can be set on the per-file basis by inserting a line
1834 #+COLUMNS: %25ITEM ....."
1835 :group 'org-properties
1836 :type 'string)
1838 (defcustom org-global-properties nil
1839 "List of property/value pairs that can be inherited by any entry.
1840 You can set buffer-local values for this by adding lines like
1842 #+PROPERTY: NAME VALUE"
1843 :group 'org-properties
1844 :type '(repeat
1845 (cons (string :tag "Property")
1846 (string :tag "Value"))))
1848 (defvar org-local-properties nil
1849 "List of property/value pairs that can be inherited by any entry.
1850 Valid for the current buffer.
1851 This variable is populated from #+PROPERTY lines.")
1853 (defgroup org-agenda nil
1854 "Options concerning agenda views in Org-mode."
1855 :tag "Org Agenda"
1856 :group 'org)
1858 (defvar org-category nil
1859 "Variable used by org files to set a category for agenda display.
1860 Such files should use a file variable to set it, for example
1862 # -*- mode: org; org-category: \"ELisp\"
1864 or contain a special line
1866 #+CATEGORY: ELisp
1868 If the file does not specify a category, then file's base name
1869 is used instead.")
1870 (make-variable-buffer-local 'org-category)
1872 (defcustom org-agenda-files nil
1873 "The files to be used for agenda display.
1874 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1875 \\[org-remove-file]. You can also use customize to edit the list.
1877 If an entry is a directory, all files in that directory that are matched by
1878 `org-agenda-file-regexp' will be part of the file list.
1880 If the value of the variable is not a list but a single file name, then
1881 the list of agenda files is actually stored and maintained in that file, one
1882 agenda file per line."
1883 :group 'org-agenda
1884 :type '(choice
1885 (repeat :tag "List of files and directories" file)
1886 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1888 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1889 "Regular expression to match files for `org-agenda-files'.
1890 If any element in the list in that variable contains a directory instead
1891 of a normal file, all files in that directory that are matched by this
1892 regular expression will be included."
1893 :group 'org-agenda
1894 :type 'regexp)
1896 (defcustom org-agenda-text-search-extra-files nil
1897 "List of extra files to be searched by text search commands.
1898 These files will be search in addition to the agenda files bu the
1899 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1900 Note that these files will only be searched for text search commands,
1901 not for the other agenda views like todo lists, tag earches or the weekly
1902 agenda. This variable is intended to list notes and possibly archive files
1903 that should also be searched by these two commands."
1904 :group 'org-agenda
1905 :type '(repeat file))
1907 (if (fboundp 'defvaralias)
1908 (defvaralias 'org-agenda-multi-occur-extra-files
1909 'org-agenda-text-search-extra-files))
1911 (defcustom org-agenda-skip-unavailable-files nil
1912 "t means to just skip non-reachable files in `org-agenda-files'.
1913 Nil means to remove them, after a query, from the list."
1914 :group 'org-agenda
1915 :type 'boolean)
1917 (defcustom org-calendar-to-agenda-key [?c]
1918 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1919 The command `org-calendar-goto-agenda' will be bound to this key. The
1920 default is the character `c' because then `c' can be used to switch back and
1921 forth between agenda and calendar."
1922 :group 'org-agenda
1923 :type 'sexp)
1925 (eval-after-load "calendar"
1926 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1927 'org-calendar-goto-agenda))
1929 (defgroup org-latex nil
1930 "Options for embedding LaTeX code into Org-mode."
1931 :tag "Org LaTeX"
1932 :group 'org)
1934 (defcustom org-format-latex-options
1935 '(:foreground default :background default :scale 1.0
1936 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1937 :matchers ("begin" "$" "$$" "\\(" "\\["))
1938 "Options for creating images from LaTeX fragments.
1939 This is a property list with the following properties:
1940 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1941 `default' means use the forground of the default face.
1942 :background the background color, or \"Transparent\".
1943 `default' means use the background of the default face.
1944 :scale a scaling factor for the size of the images
1945 :html-foreground, :html-background, :html-scale
1946 The same numbers for HTML export.
1947 :matchers a list indicating which matchers should be used to
1948 find LaTeX fragments. Valid members of this list are:
1949 \"begin\" find environments
1950 \"$\" find math expressions surrounded by $...$
1951 \"$$\" find math expressions surrounded by $$....$$
1952 \"\\(\" find math expressions surrounded by \\(...\\)
1953 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1954 :group 'org-latex
1955 :type 'plist)
1957 (defcustom org-format-latex-header "\\documentclass{article}
1958 \\usepackage{fullpage} % do not remove
1959 \\usepackage{amssymb}
1960 \\usepackage[usenames]{color}
1961 \\usepackage{amsmath}
1962 \\usepackage{latexsym}
1963 \\usepackage[mathscr]{eucal}
1964 \\pagestyle{empty} % do not remove"
1965 "The document header used for processing LaTeX fragments."
1966 :group 'org-latex
1967 :type 'string)
1970 (defgroup org-font-lock nil
1971 "Font-lock settings for highlighting in Org-mode."
1972 :tag "Org Font Lock"
1973 :group 'org)
1975 (defcustom org-level-color-stars-only nil
1976 "Non-nil means fontify only the stars in each headline.
1977 When nil, the entire headline is fontified.
1978 Changing it requires restart of `font-lock-mode' to become effective
1979 also in regions already fontified."
1980 :group 'org-font-lock
1981 :type 'boolean)
1983 (defcustom org-hide-leading-stars nil
1984 "Non-nil means, hide the first N-1 stars in a headline.
1985 This works by using the face `org-hide' for these stars. This
1986 face is white for a light background, and black for a dark
1987 background. You may have to customize the face `org-hide' to
1988 make this work.
1989 Changing it requires restart of `font-lock-mode' to become effective
1990 also in regions already fontified.
1991 You may also set this on a per-file basis by adding one of the following
1992 lines to the buffer:
1994 #+STARTUP: hidestars
1995 #+STARTUP: showstars"
1996 :group 'org-font-lock
1997 :type 'boolean)
1999 (defcustom org-fontify-done-headline nil
2000 "Non-nil means, change the face of a headline if it is marked DONE.
2001 Normally, only the TODO/DONE keyword indicates the state of a headline.
2002 When this is non-nil, the headline after the keyword is set to the
2003 `org-headline-done' as an additional indication."
2004 :group 'org-font-lock
2005 :type 'boolean)
2007 (defcustom org-fontify-emphasized-text t
2008 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2009 Changing this variable requires a restart of Emacs to take effect."
2010 :group 'org-font-lock
2011 :type 'boolean)
2013 (defcustom org-highlight-latex-fragments-and-specials nil
2014 "Non-nil means, fontify what is treated specially by the exporters."
2015 :group 'org-font-lock
2016 :type 'boolean)
2018 (defcustom org-hide-emphasis-markers nil
2019 "Non-nil mean font-lock should hide the emphasis marker characters."
2020 :group 'org-font-lock
2021 :type 'boolean)
2023 (defvar org-emph-re nil
2024 "Regular expression for matching emphasis.")
2025 (defvar org-verbatim-re nil
2026 "Regular expression for matching verbatim text.")
2027 (defvar org-emphasis-regexp-components) ; defined just below
2028 (defvar org-emphasis-alist) ; defined just below
2029 (defun org-set-emph-re (var val)
2030 "Set variable and compute the emphasis regular expression."
2031 (set var val)
2032 (when (and (boundp 'org-emphasis-alist)
2033 (boundp 'org-emphasis-regexp-components)
2034 org-emphasis-alist org-emphasis-regexp-components)
2035 (let* ((e org-emphasis-regexp-components)
2036 (pre (car e))
2037 (post (nth 1 e))
2038 (border (nth 2 e))
2039 (body (nth 3 e))
2040 (nl (nth 4 e))
2041 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2042 (body1 (concat body "*?"))
2043 (markers (mapconcat 'car org-emphasis-alist ""))
2044 (vmarkers (mapconcat
2045 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2046 org-emphasis-alist "")))
2047 ;; make sure special characters appear at the right position in the class
2048 (if (string-match "\\^" markers)
2049 (setq markers (concat (replace-match "" t t markers) "^")))
2050 (if (string-match "-" markers)
2051 (setq markers (concat (replace-match "" t t markers) "-")))
2052 (if (string-match "\\^" vmarkers)
2053 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2054 (if (string-match "-" vmarkers)
2055 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2056 (if (> nl 0)
2057 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2058 (int-to-string nl) "\\}")))
2059 ;; Make the regexp
2060 (setq org-emph-re
2061 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2062 "\\("
2063 "\\([" markers "]\\)"
2064 "\\("
2065 "[^" border "]\\|"
2066 "[^" border (if (and nil stacked) markers) "]"
2067 body1
2068 "[^" border (if (and nil stacked) markers) "]"
2069 "\\)"
2070 "\\3\\)"
2071 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2072 (setq org-verbatim-re
2073 (concat "\\([" pre "]\\|^\\)"
2074 "\\("
2075 "\\([" vmarkers "]\\)"
2076 "\\("
2077 "[^" border "]\\|"
2078 "[^" border "]"
2079 body1
2080 "[^" border "]"
2081 "\\)"
2082 "\\3\\)"
2083 "\\([" post "]\\|$\\)")))))
2085 (defcustom org-emphasis-regexp-components
2086 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2087 "Components used to build the regular expression for emphasis.
2088 This is a list with 6 entries. Terminology: In an emphasis string
2089 like \" *strong word* \", we call the initial space PREMATCH, the final
2090 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2091 and \"trong wor\" is the body. The different components in this variable
2092 specify what is allowed/forbidden in each part:
2094 pre Chars allowed as prematch. Beginning of line will be allowed too.
2095 post Chars allowed as postmatch. End of line will be allowed too.
2096 border The chars *forbidden* as border characters.
2097 body-regexp A regexp like \".\" to match a body character. Don't use
2098 non-shy groups here, and don't allow newline here.
2099 newline The maximum number of newlines allowed in an emphasis exp.
2101 Use customize to modify this, or restart Emacs after changing it."
2102 :group 'org-font-lock
2103 :set 'org-set-emph-re
2104 :type '(list
2105 (sexp :tag "Allowed chars in pre ")
2106 (sexp :tag "Allowed chars in post ")
2107 (sexp :tag "Forbidden chars in border ")
2108 (sexp :tag "Regexp for body ")
2109 (integer :tag "number of newlines allowed")
2110 (option (boolean :tag "Stacking (DISABLED) "))))
2112 (defcustom org-emphasis-alist
2113 '(("*" bold "<b>" "</b>")
2114 ("/" italic "<i>" "</i>")
2115 ("_" underline "<u>" "</u>")
2116 ("=" org-code "<code>" "</code>" verbatim)
2117 ("~" org-verbatim "" "" verbatim)
2118 ("+" (:strike-through t) "<del>" "</del>")
2120 "Special syntax for emphasized text.
2121 Text starting and ending with a special character will be emphasized, for
2122 example *bold*, _underlined_ and /italic/. This variable sets the marker
2123 characters, the face to be used by font-lock for highlighting in Org-mode
2124 Emacs buffers, and the HTML tags to be used for this.
2125 Use customize to modify this, or restart Emacs after changing it."
2126 :group 'org-font-lock
2127 :set 'org-set-emph-re
2128 :type '(repeat
2129 (list
2130 (string :tag "Marker character")
2131 (choice
2132 (face :tag "Font-lock-face")
2133 (plist :tag "Face property list"))
2134 (string :tag "HTML start tag")
2135 (string :tag "HTML end tag")
2136 (option (const verbatim)))))
2138 ;;; Miscellaneous options
2140 (defgroup org-completion nil
2141 "Completion in Org-mode."
2142 :tag "Org Completion"
2143 :group 'org)
2145 (defcustom org-completion-fallback-command 'hippie-expand
2146 "The expansion command called by \\[org-complete] in normal context.
2147 Normal means, no org-mode-specific context."
2148 :group 'org-completion
2149 :type 'function)
2151 ;;; Functions and variables from ther packages
2152 ;; Declared here to avoid compiler warnings
2154 ;; XEmacs only
2155 (defvar outline-mode-menu-heading)
2156 (defvar outline-mode-menu-show)
2157 (defvar outline-mode-menu-hide)
2158 (defvar zmacs-regions) ; XEmacs regions
2160 ;; Emacs only
2161 (defvar mark-active)
2163 ;; Various packages
2164 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2165 (declare-function calendar-forward-day "cal-move" (arg))
2166 (declare-function calendar-goto-date "cal-move" (date))
2167 (declare-function calendar-goto-today "cal-move" ())
2168 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2169 (defvar calc-embedded-close-formula)
2170 (defvar calc-embedded-open-formula)
2171 (declare-function cdlatex-tab "ext:cdlatex" ())
2172 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2173 (defvar font-lock-unfontify-region-function)
2174 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2175 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2176 (defvar iswitchb-temp-buflist)
2177 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2178 (declare-function org-agenda-skip "org-agenda" ())
2179 (declare-function org-format-agenda-item "org-agenda"
2180 (extra txt &optional category tags dotime noprefix remove-re))
2181 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2182 (declare-function org-agenda-change-all-lines "org-agenda"
2183 (newhead hdmarker &optional fixface))
2184 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2185 (declare-function org-agenda-maybe-redo "org-agenda" ())
2186 (declare-function parse-time-string "parse-time" (string))
2187 (declare-function remember "remember" (&optional initial))
2188 (declare-function remember-buffer-desc "remember" ())
2189 (declare-function remember-finalize "remember" ())
2190 (defvar remember-save-after-remembering)
2191 (defvar remember-data-file)
2192 (defvar remember-register)
2193 (defvar remember-buffer)
2194 (defvar remember-handler-functions)
2195 (defvar remember-annotation-functions)
2196 (defvar texmathp-why)
2197 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2198 (declare-function table--at-cell-p "table" (position &optional object at-column))
2200 (defvar w3m-current-url)
2201 (defvar w3m-current-title)
2203 (defvar org-latex-regexps)
2205 ;;; Autoload and prepare some org modules
2207 ;; Some table stuff that needs to be defined here, because it is used
2208 ;; by the functions setting up org-mode or checking for table context.
2210 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2211 "Detects an org-type or table-type table.")
2212 (defconst org-table-line-regexp "^[ \t]*|"
2213 "Detects an org-type table line.")
2214 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2215 "Detects an org-type table line.")
2216 (defconst org-table-hline-regexp "^[ \t]*|-"
2217 "Detects an org-type table hline.")
2218 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2219 "Detects a table-type table hline.")
2220 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2221 "Searching from within a table (any type) this finds the first line
2222 outside the table.")
2224 ;; Autoload the functions in org-table.el that are needed by functions here.
2226 (eval-and-compile
2227 (org-autoload "org-table"
2228 '(org-table-align org-table-begin org-table-blank-field
2229 org-table-convert org-table-convert-region org-table-copy-down
2230 org-table-copy-region org-table-create
2231 org-table-create-or-convert-from-region
2232 org-table-create-with-table.el org-table-current-dline
2233 org-table-cut-region org-table-delete-column org-table-edit-field
2234 org-table-edit-formulas org-table-end org-table-eval-formula
2235 org-table-export org-table-field-info
2236 org-table-get-stored-formulas org-table-goto-column
2237 org-table-hline-and-move org-table-import org-table-insert-column
2238 org-table-insert-hline org-table-insert-row org-table-iterate
2239 org-table-justify-field-maybe org-table-kill-row
2240 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2241 org-table-move-column org-table-move-column-left
2242 org-table-move-column-right org-table-move-row
2243 org-table-move-row-down org-table-move-row-up
2244 org-table-next-field org-table-next-row org-table-paste-rectangle
2245 org-table-previous-field org-table-recalculate
2246 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2247 org-table-toggle-coordinate-overlays
2248 org-table-toggle-formula-debugger org-table-wrap-region
2249 orgtbl-mode turn-on-orgtbl)))
2251 (defun org-at-table-p (&optional table-type)
2252 "Return t if the cursor is inside an org-type table.
2253 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2254 (if org-enable-table-editor
2255 (save-excursion
2256 (beginning-of-line 1)
2257 (looking-at (if table-type org-table-any-line-regexp
2258 org-table-line-regexp)))
2259 nil))
2260 (defsubst org-table-p () (org-at-table-p))
2262 (defun org-at-table.el-p ()
2263 "Return t if and only if we are at a table.el table."
2264 (and (org-at-table-p 'any)
2265 (save-excursion
2266 (goto-char (org-table-begin 'any))
2267 (looking-at org-table1-hline-regexp))))
2268 (defun org-table-recognize-table.el ()
2269 "If there is a table.el table nearby, recognize it and move into it."
2270 (if org-table-tab-recognizes-table.el
2271 (if (org-at-table.el-p)
2272 (progn
2273 (beginning-of-line 1)
2274 (if (looking-at org-table-dataline-regexp)
2276 (if (looking-at org-table1-hline-regexp)
2277 (progn
2278 (beginning-of-line 2)
2279 (if (looking-at org-table-any-border-regexp)
2280 (beginning-of-line -1)))))
2281 (if (re-search-forward "|" (org-table-end t) t)
2282 (progn
2283 (require 'table)
2284 (if (table--at-cell-p (point))
2286 (message "recognizing table.el table...")
2287 (table-recognize-table)
2288 (message "recognizing table.el table...done")))
2289 (error "This should not happen..."))
2291 nil)
2292 nil))
2294 (defun org-at-table-hline-p ()
2295 "Return t if the cursor is inside a hline in a table."
2296 (if org-enable-table-editor
2297 (save-excursion
2298 (beginning-of-line 1)
2299 (looking-at org-table-hline-regexp))
2300 nil))
2302 (defvar org-table-clean-did-remove-column nil)
2304 (defun org-table-map-tables (function)
2305 "Apply FUNCTION to the start of all tables in the buffer."
2306 (save-excursion
2307 (save-restriction
2308 (widen)
2309 (goto-char (point-min))
2310 (while (re-search-forward org-table-any-line-regexp nil t)
2311 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2312 (beginning-of-line 1)
2313 (if (looking-at org-table-line-regexp)
2314 (save-excursion (funcall function)))
2315 (re-search-forward org-table-any-border-regexp nil 1))))
2316 (message "Mapping tables: done"))
2318 ;; Declare and autoload functions from org-exp.el
2320 (declare-function org-default-export-plist "org-exp")
2321 (declare-function org-infile-export-plist "org-exp")
2322 (declare-function org-get-current-options "org-exp")
2323 (eval-and-compile
2324 (org-autoload "org-exp"
2325 '(org-export org-export-as-ascii org-export-visible
2326 org-insert-export-options-template org-export-as-html-and-open
2327 org-export-as-html-batch org-export-as-html-to-buffer
2328 org-replace-region-by-html org-export-region-as-html
2329 org-export-as-html org-export-icalendar-this-file
2330 org-export-icalendar-all-agenda-files
2331 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2333 ;; Declare and autoload functions from org-exp.el
2335 (eval-and-compile
2336 (org-autoload "org-exp"
2337 '(org-agenda org-agenda-list org-search-view
2338 org-todo-list org-tags-view org-agenda-list-stuck-projects
2339 org-diary org-agenda-to-appt)))
2341 ;; Autoload org-remember
2343 (eval-and-compile
2344 (org-autoload "org-remember"
2345 '(org-remember-insinuate org-remember-annotation
2346 org-remember-apply-template org-remember org-remember-handler)))
2348 ;; Autoload org-clock.el
2350 (defvar org-clock-marker (make-marker)
2351 "Marker recording the last clock-in.")
2353 (eval-and-compile
2354 (org-autoload
2355 "org-clock"
2356 '(org-clock-in org-clock-out org-clock-cancel
2357 org-clock-goto org-clock-sum org-clock-display
2358 org-remove-clock-overlays org-clock-report
2359 org-clocktable-shift org-dblock-write:clocktable
2360 org-get-clocktable)))
2362 (defun org-clock-update-time-maybe ()
2363 "If this is a CLOCK line, update it and return t.
2364 Otherwise, return nil."
2365 (interactive)
2366 (save-excursion
2367 (beginning-of-line 1)
2368 (skip-chars-forward " \t")
2369 (when (looking-at org-clock-string)
2370 (let ((re (concat "[ \t]*" org-clock-string
2371 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2372 "\\([ \t]*=>.*\\)?"))
2373 ts te h m s)
2374 (if (not (looking-at re))
2376 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2377 (end-of-line 1)
2378 (setq ts (match-string 1)
2379 te (match-string 2))
2380 (setq s (- (time-to-seconds
2381 (apply 'encode-time (org-parse-time-string te)))
2382 (time-to-seconds
2383 (apply 'encode-time (org-parse-time-string ts))))
2384 h (floor (/ s 3600))
2385 s (- s (* 3600 h))
2386 m (floor (/ s 60))
2387 s (- s (* 60 s)))
2388 (insert " => " (format "%2d:%02d" h m))
2389 t)))))
2391 (defun org-check-running-clock ()
2392 "Check if the current buffer contains the running clock.
2393 If yes, offer to stop it and to save the buffer with the changes."
2394 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2395 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2396 (buffer-name))))
2397 (org-clock-out)
2398 (when (y-or-n-p "Save changed buffer?")
2399 (save-buffer))))
2401 (defun org-clocktable-try-shift (dir n)
2402 "Check if this line starts a clock table, if yes, shift the time block."
2403 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2404 (org-clocktable-shift dir n)))
2406 ;; Autoload archiving code
2407 ;; The stuff that is needed for cycling and tags has to be defined here.
2409 (defgroup org-archive nil
2410 "Options concerning archiving in Org-mode."
2411 :tag "Org Archive"
2412 :group 'org-structure)
2414 (defcustom org-archive-tag "ARCHIVE"
2415 "The tag that marks a subtree as archived.
2416 An archived subtree does not open during visibility cycling, and does
2417 not contribute to the agenda listings.
2418 After changing this, font-lock must be restarted in the relevant buffers to
2419 get the proper fontification."
2420 :group 'org-archive
2421 :group 'org-keywords
2422 :type 'string)
2424 (defcustom org-agenda-skip-archived-trees t
2425 "Non-nil means, the agenda will skip any items located in archived trees.
2426 An archived tree is a tree marked with the tag ARCHIVE."
2427 :group 'org-archive
2428 :group 'org-agenda-skip
2429 :type 'boolean)
2431 (defcustom org-cycle-open-archived-trees nil
2432 "Non-nil means, `org-cycle' will open archived trees.
2433 An archived tree is a tree marked with the tag ARCHIVE.
2434 When nil, archived trees will stay folded. You can still open them with
2435 normal outline commands like `show-all', but not with the cycling commands."
2436 :group 'org-archive
2437 :group 'org-cycle
2438 :type 'boolean)
2440 (defcustom org-sparse-tree-open-archived-trees nil
2441 "Non-nil means sparse tree construction shows matches in archived trees.
2442 When nil, matches in these trees are highlighted, but the trees are kept in
2443 collapsed state."
2444 :group 'org-archive
2445 :group 'org-sparse-trees
2446 :type 'boolean)
2448 (defun org-cycle-hide-archived-subtrees (state)
2449 "Re-hide all archived subtrees after a visibility state change."
2450 (when (and (not org-cycle-open-archived-trees)
2451 (not (memq state '(overview folded))))
2452 (save-excursion
2453 (let* ((globalp (memq state '(contents all)))
2454 (beg (if globalp (point-min) (point)))
2455 (end (if globalp (point-max) (org-end-of-subtree t))))
2456 (org-hide-archived-subtrees beg end)
2457 (goto-char beg)
2458 (if (looking-at (concat ".*:" org-archive-tag ":"))
2459 (message "%s" (substitute-command-keys
2460 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2462 (defun org-force-cycle-archived ()
2463 "Cycle subtree even if it is archived."
2464 (interactive)
2465 (setq this-command 'org-cycle)
2466 (let ((org-cycle-open-archived-trees t))
2467 (call-interactively 'org-cycle)))
2469 (defun org-hide-archived-subtrees (beg end)
2470 "Re-hide all archived subtrees after a visibility state change."
2471 (save-excursion
2472 (let* ((re (concat ":" org-archive-tag ":")))
2473 (goto-char beg)
2474 (while (re-search-forward re end t)
2475 (and (org-on-heading-p) (hide-subtree))
2476 (org-end-of-subtree t)))))
2478 (org-autoload "org-archive"
2479 '(org-archive-subtree org-archive-to-archive-sibling org-toggle-archive-tag))
2481 ;; Autoload Column View Code
2483 (declare-function org-columns-number-to-string "org-colview")
2484 (declare-function org-columns-get-format-and-top-level "org-colview")
2485 (declare-function org-columns-compute "org-colview")
2487 (org-autoload "org-colview"
2488 '(org-columns-number-to-string org-columns-get-format-and-top-level
2489 org-columns-compute org-agenda-columns org-columns-remove-overlays
2490 org-columns org-insert-columns-dblock))
2492 ;;; Variables for pre-computed regular expressions, all buffer local
2494 (defvar org-drawer-regexp nil
2495 "Matches first line of a hidden block.")
2496 (make-variable-buffer-local 'org-drawer-regexp)
2497 (defvar org-todo-regexp nil
2498 "Matches any of the TODO state keywords.")
2499 (make-variable-buffer-local 'org-todo-regexp)
2500 (defvar org-not-done-regexp nil
2501 "Matches any of the TODO state keywords except the last one.")
2502 (make-variable-buffer-local 'org-not-done-regexp)
2503 (defvar org-todo-line-regexp nil
2504 "Matches a headline and puts TODO state into group 2 if present.")
2505 (make-variable-buffer-local 'org-todo-line-regexp)
2506 (defvar org-complex-heading-regexp nil
2507 "Matches a headline and puts everything into groups:
2508 group 1: the stars
2509 group 2: The todo keyword, maybe
2510 group 3: Priority cookie
2511 group 4: True headline
2512 group 5: Tags")
2513 (make-variable-buffer-local 'org-complex-heading-regexp)
2514 (defvar org-todo-line-tags-regexp nil
2515 "Matches a headline and puts TODO state into group 2 if present.
2516 Also put tags into group 4 if tags are present.")
2517 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2518 (defvar org-nl-done-regexp nil
2519 "Matches newline followed by a headline with the DONE keyword.")
2520 (make-variable-buffer-local 'org-nl-done-regexp)
2521 (defvar org-looking-at-done-regexp nil
2522 "Matches the DONE keyword a point.")
2523 (make-variable-buffer-local 'org-looking-at-done-regexp)
2524 (defvar org-ds-keyword-length 12
2525 "Maximum length of the Deadline and SCHEDULED keywords.")
2526 (make-variable-buffer-local 'org-ds-keyword-length)
2527 (defvar org-deadline-regexp nil
2528 "Matches the DEADLINE keyword.")
2529 (make-variable-buffer-local 'org-deadline-regexp)
2530 (defvar org-deadline-time-regexp nil
2531 "Matches the DEADLINE keyword together with a time stamp.")
2532 (make-variable-buffer-local 'org-deadline-time-regexp)
2533 (defvar org-deadline-line-regexp nil
2534 "Matches the DEADLINE keyword and the rest of the line.")
2535 (make-variable-buffer-local 'org-deadline-line-regexp)
2536 (defvar org-scheduled-regexp nil
2537 "Matches the SCHEDULED keyword.")
2538 (make-variable-buffer-local 'org-scheduled-regexp)
2539 (defvar org-scheduled-time-regexp nil
2540 "Matches the SCHEDULED keyword together with a time stamp.")
2541 (make-variable-buffer-local 'org-scheduled-time-regexp)
2542 (defvar org-closed-time-regexp nil
2543 "Matches the CLOSED keyword together with a time stamp.")
2544 (make-variable-buffer-local 'org-closed-time-regexp)
2546 (defvar org-keyword-time-regexp nil
2547 "Matches any of the 4 keywords, together with the time stamp.")
2548 (make-variable-buffer-local 'org-keyword-time-regexp)
2549 (defvar org-keyword-time-not-clock-regexp nil
2550 "Matches any of the 3 keywords, together with the time stamp.")
2551 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2552 (defvar org-maybe-keyword-time-regexp nil
2553 "Matches a timestamp, possibly preceeded by a keyword.")
2554 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2555 (defvar org-planning-or-clock-line-re nil
2556 "Matches a line with planning or clock info.")
2557 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2559 (defconst org-plain-time-of-day-regexp
2560 (concat
2561 "\\(\\<[012]?[0-9]"
2562 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2563 "\\(--?"
2564 "\\(\\<[012]?[0-9]"
2565 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2566 "\\)?")
2567 "Regular expression to match a plain time or time range.
2568 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2569 groups carry important information:
2570 0 the full match
2571 1 the first time, range or not
2572 8 the second time, if it is a range.")
2574 (defconst org-plain-time-extension-regexp
2575 (concat
2576 "\\(\\<[012]?[0-9]"
2577 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2578 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2579 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2580 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2581 groups carry important information:
2582 0 the full match
2583 7 hours of duration
2584 9 minutes of duration")
2586 (defconst org-stamp-time-of-day-regexp
2587 (concat
2588 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2589 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2590 "\\(--?"
2591 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2592 "Regular expression to match a timestamp time or time range.
2593 After a match, the following groups carry important information:
2594 0 the full match
2595 1 date plus weekday, for backreferencing to make sure both times on same day
2596 2 the first time, range or not
2597 4 the second time, if it is a range.")
2599 (defconst org-startup-options
2600 '(("fold" org-startup-folded t)
2601 ("overview" org-startup-folded t)
2602 ("nofold" org-startup-folded nil)
2603 ("showall" org-startup-folded nil)
2604 ("content" org-startup-folded content)
2605 ("hidestars" org-hide-leading-stars t)
2606 ("showstars" org-hide-leading-stars nil)
2607 ("odd" org-odd-levels-only t)
2608 ("oddeven" org-odd-levels-only nil)
2609 ("align" org-startup-align-all-tables t)
2610 ("noalign" org-startup-align-all-tables nil)
2611 ("customtime" org-display-custom-times t)
2612 ("logdone" org-log-done time)
2613 ("lognotedone" org-log-done note)
2614 ("nologdone" org-log-done nil)
2615 ("lognoteclock-out" org-log-note-clock-out t)
2616 ("nolognoteclock-out" org-log-note-clock-out nil)
2617 ("logrepeat" org-log-repeat state)
2618 ("lognoterepeat" org-log-repeat note)
2619 ("nologrepeat" org-log-repeat nil)
2620 ("constcgs" constants-unit-system cgs)
2621 ("constSI" constants-unit-system SI))
2622 "Variable associated with STARTUP options for org-mode.
2623 Each element is a list of three items: The startup options as written
2624 in the #+STARTUP line, the corresponding variable, and the value to
2625 set this variable to if the option is found. An optional forth element PUSH
2626 means to push this value onto the list in the variable.")
2628 (defun org-set-regexps-and-options ()
2629 "Precompute regular expressions for current buffer."
2630 (when (org-mode-p)
2631 (org-set-local 'org-todo-kwd-alist nil)
2632 (org-set-local 'org-todo-key-alist nil)
2633 (org-set-local 'org-todo-key-trigger nil)
2634 (org-set-local 'org-todo-keywords-1 nil)
2635 (org-set-local 'org-done-keywords nil)
2636 (org-set-local 'org-todo-heads nil)
2637 (org-set-local 'org-todo-sets nil)
2638 (org-set-local 'org-todo-log-states nil)
2639 (let ((re (org-make-options-regexp
2640 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2641 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2642 "CONSTANTS" "PROPERTY" "DRAWERS")))
2643 (splitre "[ \t]+")
2644 kwds kws0 kwsa key log value cat arch tags const links hw dws
2645 tail sep kws1 prio props drawers)
2646 (save-excursion
2647 (save-restriction
2648 (widen)
2649 (goto-char (point-min))
2650 (while (re-search-forward re nil t)
2651 (setq key (match-string 1) value (org-match-string-no-properties 2))
2652 (cond
2653 ((equal key "CATEGORY")
2654 (if (string-match "[ \t]+$" value)
2655 (setq value (replace-match "" t t value)))
2656 (setq cat value))
2657 ((member key '("SEQ_TODO" "TODO"))
2658 (push (cons 'sequence (org-split-string value splitre)) kwds))
2659 ((equal key "TYP_TODO")
2660 (push (cons 'type (org-split-string value splitre)) kwds))
2661 ((equal key "TAGS")
2662 (setq tags (append tags (org-split-string value splitre))))
2663 ((equal key "COLUMNS")
2664 (org-set-local 'org-columns-default-format value))
2665 ((equal key "LINK")
2666 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2667 (push (cons (match-string 1 value)
2668 (org-trim (match-string 2 value)))
2669 links)))
2670 ((equal key "PRIORITIES")
2671 (setq prio (org-split-string value " +")))
2672 ((equal key "PROPERTY")
2673 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2674 (push (cons (match-string 1 value) (match-string 2 value))
2675 props)))
2676 ((equal key "DRAWERS")
2677 (setq drawers (org-split-string value splitre)))
2678 ((equal key "CONSTANTS")
2679 (setq const (append const (org-split-string value splitre))))
2680 ((equal key "STARTUP")
2681 (let ((opts (org-split-string value splitre))
2682 l var val)
2683 (while (setq l (pop opts))
2684 (when (setq l (assoc l org-startup-options))
2685 (setq var (nth 1 l) val (nth 2 l))
2686 (if (not (nth 3 l))
2687 (set (make-local-variable var) val)
2688 (if (not (listp (symbol-value var)))
2689 (set (make-local-variable var) nil))
2690 (set (make-local-variable var) (symbol-value var))
2691 (add-to-list var val))))))
2692 ((equal key "ARCHIVE")
2693 (string-match " *$" value)
2694 (setq arch (replace-match "" t t value))
2695 (remove-text-properties 0 (length arch)
2696 '(face t fontified t) arch)))
2698 (when cat
2699 (org-set-local 'org-category (intern cat))
2700 (push (cons "CATEGORY" cat) props))
2701 (when prio
2702 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2703 (setq prio (mapcar 'string-to-char prio))
2704 (org-set-local 'org-highest-priority (nth 0 prio))
2705 (org-set-local 'org-lowest-priority (nth 1 prio))
2706 (org-set-local 'org-default-priority (nth 2 prio)))
2707 (and props (org-set-local 'org-local-properties (nreverse props)))
2708 (and drawers (org-set-local 'org-drawers drawers))
2709 (and arch (org-set-local 'org-archive-location arch))
2710 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2711 ;; Process the TODO keywords
2712 (unless kwds
2713 ;; Use the global values as if they had been given locally.
2714 (setq kwds (default-value 'org-todo-keywords))
2715 (if (stringp (car kwds))
2716 (setq kwds (list (cons org-todo-interpretation
2717 (default-value 'org-todo-keywords)))))
2718 (setq kwds (reverse kwds)))
2719 (setq kwds (nreverse kwds))
2720 (let (inter kws kw)
2721 (while (setq kws (pop kwds))
2722 (setq inter (pop kws) sep (member "|" kws)
2723 kws0 (delete "|" (copy-sequence kws))
2724 kwsa nil
2725 kws1 (mapcar
2726 (lambda (x)
2727 ;; 1 2
2728 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2729 (progn
2730 (setq kw (match-string 1 x)
2731 key (and (match-end 2) (match-string 2 x))
2732 log (org-extract-log-state-settings x))
2733 (push (cons kw (and key (string-to-char key))) kwsa)
2734 (and log (push log org-todo-log-states))
2736 (error "Invalid TODO keyword %s" x)))
2737 kws0)
2738 kwsa (if kwsa (append '((:startgroup))
2739 (nreverse kwsa)
2740 '((:endgroup))))
2741 hw (car kws1)
2742 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2743 tail (list inter hw (car dws) (org-last dws)))
2744 (add-to-list 'org-todo-heads hw 'append)
2745 (push kws1 org-todo-sets)
2746 (setq org-done-keywords (append org-done-keywords dws nil))
2747 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2748 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2749 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2750 (setq org-todo-sets (nreverse org-todo-sets)
2751 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2752 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2753 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2754 ;; Process the constants
2755 (when const
2756 (let (e cst)
2757 (while (setq e (pop const))
2758 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2759 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2760 (setq org-table-formula-constants-local cst)))
2762 ;; Process the tags.
2763 (when tags
2764 (let (e tgs)
2765 (while (setq e (pop tags))
2766 (cond
2767 ((equal e "{") (push '(:startgroup) tgs))
2768 ((equal e "}") (push '(:endgroup) tgs))
2769 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2770 (push (cons (match-string 1 e)
2771 (string-to-char (match-string 2 e)))
2772 tgs))
2773 (t (push (list e) tgs))))
2774 (org-set-local 'org-tag-alist nil)
2775 (while (setq e (pop tgs))
2776 (or (and (stringp (car e))
2777 (assoc (car e) org-tag-alist))
2778 (push e org-tag-alist))))))
2780 ;; Compute the regular expressions and other local variables
2781 (if (not org-done-keywords)
2782 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2783 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2784 (length org-scheduled-string)
2785 (length org-clock-string)
2786 (length org-closed-string)))
2787 org-drawer-regexp
2788 (concat "^[ \t]*:\\("
2789 (mapconcat 'regexp-quote org-drawers "\\|")
2790 "\\):[ \t]*$")
2791 org-not-done-keywords
2792 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2793 org-todo-regexp
2794 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2795 "\\|") "\\)\\>")
2796 org-not-done-regexp
2797 (concat "\\<\\("
2798 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2799 "\\)\\>")
2800 org-todo-line-regexp
2801 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2802 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2803 "\\)\\>\\)?[ \t]*\\(.*\\)")
2804 org-complex-heading-regexp
2805 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2806 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2807 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2808 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2809 org-nl-done-regexp
2810 (concat "\n\\*+[ \t]+"
2811 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2812 "\\)" "\\>")
2813 org-todo-line-tags-regexp
2814 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2815 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2816 (org-re
2817 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2818 org-looking-at-done-regexp
2819 (concat "^" "\\(?:"
2820 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2821 "\\>")
2822 org-deadline-regexp (concat "\\<" org-deadline-string)
2823 org-deadline-time-regexp
2824 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2825 org-deadline-line-regexp
2826 (concat "\\<\\(" org-deadline-string "\\).*")
2827 org-scheduled-regexp
2828 (concat "\\<" org-scheduled-string)
2829 org-scheduled-time-regexp
2830 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2831 org-closed-time-regexp
2832 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2833 org-keyword-time-regexp
2834 (concat "\\<\\(" org-scheduled-string
2835 "\\|" org-deadline-string
2836 "\\|" org-closed-string
2837 "\\|" org-clock-string "\\)"
2838 " *[[<]\\([^]>]+\\)[]>]")
2839 org-keyword-time-not-clock-regexp
2840 (concat "\\<\\(" org-scheduled-string
2841 "\\|" org-deadline-string
2842 "\\|" org-closed-string
2843 "\\)"
2844 " *[[<]\\([^]>]+\\)[]>]")
2845 org-maybe-keyword-time-regexp
2846 (concat "\\(\\<\\(" org-scheduled-string
2847 "\\|" org-deadline-string
2848 "\\|" org-closed-string
2849 "\\|" org-clock-string "\\)\\)?"
2850 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2851 org-planning-or-clock-line-re
2852 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2853 "\\|" org-deadline-string
2854 "\\|" org-closed-string "\\|" org-clock-string
2855 "\\)\\>\\)")
2857 (org-compute-latex-and-specials-regexp)
2858 (org-set-font-lock-defaults)))
2860 (defun org-extract-log-state-settings (x)
2861 "Extract the log state setting from a TODO keyword string.
2862 This will extract info from a string like \"WAIT(w@/!)\"."
2863 (let (kw key log1 log2)
2864 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2865 (setq kw (match-string 1 x)
2866 key (and (match-end 2) (match-string 2 x))
2867 log1 (and (match-end 3) (match-string 3 x))
2868 log2 (and (match-end 4) (match-string 4 x)))
2869 (and (or log1 log2)
2870 (list kw
2871 (and log1 (if (equal log1 "!") 'time 'note))
2872 (and log2 (if (equal log2 "!") 'time 'note)))))))
2874 (defun org-remove-keyword-keys (list)
2875 "Remove a pair of parenthesis at the end of each string in LIST."
2876 (mapcar (lambda (x)
2877 (if (string-match "(.*)$" x)
2878 (substring x 0 (match-beginning 0))
2880 list))
2882 ;; FIXME: this could be done much better, using second characters etc.
2883 (defun org-assign-fast-keys (alist)
2884 "Assign fast keys to a keyword-key alist.
2885 Respect keys that are already there."
2886 (let (new e k c c1 c2 (char ?a))
2887 (while (setq e (pop alist))
2888 (cond
2889 ((equal e '(:startgroup)) (push e new))
2890 ((equal e '(:endgroup)) (push e new))
2892 (setq k (car e) c2 nil)
2893 (if (cdr e)
2894 (setq c (cdr e))
2895 ;; automatically assign a character.
2896 (setq c1 (string-to-char
2897 (downcase (substring
2898 k (if (= (string-to-char k) ?@) 1 0)))))
2899 (if (or (rassoc c1 new) (rassoc c1 alist))
2900 (while (or (rassoc char new) (rassoc char alist))
2901 (setq char (1+ char)))
2902 (setq c2 c1))
2903 (setq c (or c2 char)))
2904 (push (cons k c) new))))
2905 (nreverse new)))
2907 ;;; Some variables used in various places
2909 (defvar org-window-configuration nil
2910 "Used in various places to store a window configuration.")
2911 (defvar org-finish-function nil
2912 "Function to be called when `C-c C-c' is used.
2913 This is for getting out of special buffers like remember.")
2916 ;; FIXME: Occasionally check by commenting these, to make sure
2917 ;; no other functions uses these, forgetting to let-bind them.
2918 (defvar entry)
2919 (defvar state)
2920 (defvar last-state)
2921 (defvar date)
2922 (defvar description)
2924 ;; Defined somewhere in this file, but used before definition.
2925 (defvar org-html-entities)
2926 (defvar org-struct-menu)
2927 (defvar org-org-menu)
2928 (defvar org-tbl-menu)
2929 (defvar org-agenda-keymap)
2931 ;;;; Define the Org-mode
2933 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2934 (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."))
2937 ;; We use a before-change function to check if a table might need
2938 ;; an update.
2939 (defvar org-table-may-need-update t
2940 "Indicates that a table might need an update.
2941 This variable is set by `org-before-change-function'.
2942 `org-table-align' sets it back to nil.")
2943 (defun org-before-change-function (beg end)
2944 "Every change indicates that a table might need an update."
2945 (setq org-table-may-need-update t))
2946 (defvar org-mode-map)
2947 (defvar org-mode-hook nil)
2948 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2950 (defvar org-table-buffer-is-an nil)
2951 (defconst org-outline-regexp "\\*+ ")
2953 ;;;###autoload
2954 (define-derived-mode org-mode outline-mode "Org"
2955 "Outline-based notes management and organizer, alias
2956 \"Carsten's outline-mode for keeping track of everything.\"
2958 Org-mode develops organizational tasks around a NOTES file which
2959 contains information about projects as plain text. Org-mode is
2960 implemented on top of outline-mode, which is ideal to keep the content
2961 of large files well structured. It supports ToDo items, deadlines and
2962 time stamps, which magically appear in the diary listing of the Emacs
2963 calendar. Tables are easily created with a built-in table editor.
2964 Plain text URL-like links connect to websites, emails (VM), Usenet
2965 messages (Gnus), BBDB entries, and any files related to the project.
2966 For printing and sharing of notes, an Org-mode file (or a part of it)
2967 can be exported as a structured ASCII or HTML file.
2969 The following commands are available:
2971 \\{org-mode-map}"
2973 ;; Get rid of Outline menus, they are not needed
2974 ;; Need to do this here because define-derived-mode sets up
2975 ;; the keymap so late. Still, it is a waste to call this each time
2976 ;; we switch another buffer into org-mode.
2977 (if (featurep 'xemacs)
2978 (when (boundp 'outline-mode-menu-heading)
2979 ;; Assume this is Greg's port, it used easymenu
2980 (easy-menu-remove outline-mode-menu-heading)
2981 (easy-menu-remove outline-mode-menu-show)
2982 (easy-menu-remove outline-mode-menu-hide))
2983 (define-key org-mode-map [menu-bar headings] 'undefined)
2984 (define-key org-mode-map [menu-bar hide] 'undefined)
2985 (define-key org-mode-map [menu-bar show] 'undefined))
2987 (org-load-modules-maybe)
2988 (easy-menu-add org-org-menu)
2989 (easy-menu-add org-tbl-menu)
2990 (org-install-agenda-files-menu)
2991 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2992 (org-add-to-invisibility-spec '(org-cwidth))
2993 (when (featurep 'xemacs)
2994 (org-set-local 'line-move-ignore-invisible t))
2995 (org-set-local 'outline-regexp org-outline-regexp)
2996 (org-set-local 'outline-level 'org-outline-level)
2997 (when (and org-ellipsis
2998 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
2999 (fboundp 'make-glyph-code))
3000 (unless org-display-table
3001 (setq org-display-table (make-display-table)))
3002 (set-display-table-slot
3003 org-display-table 4
3004 (vconcat (mapcar
3005 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3006 org-ellipsis)))
3007 (if (stringp org-ellipsis) org-ellipsis "..."))))
3008 (setq buffer-display-table org-display-table))
3009 (org-set-regexps-and-options)
3010 ;; Calc embedded
3011 (org-set-local 'calc-embedded-open-mode "# ")
3012 (modify-syntax-entry ?# "<")
3013 (modify-syntax-entry ?@ "w")
3014 (if org-startup-truncated (setq truncate-lines t))
3015 (org-set-local 'font-lock-unfontify-region-function
3016 'org-unfontify-region)
3017 ;; Activate before-change-function
3018 (org-set-local 'org-table-may-need-update t)
3019 (org-add-hook 'before-change-functions 'org-before-change-function nil
3020 'local)
3021 ;; Check for running clock before killing a buffer
3022 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3023 ;; Paragraphs and auto-filling
3024 (org-set-autofill-regexps)
3025 (setq indent-line-function 'org-indent-line-function)
3026 (org-update-radio-target-regexp)
3028 ;; Comment characters
3029 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3030 (org-set-local 'comment-padding " ")
3032 ;; Align options lines
3033 (org-set-local
3034 'align-mode-rules-list
3035 '((org-in-buffer-settings
3036 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3037 (modes . '(org-mode)))))
3039 ;; Imenu
3040 (org-set-local 'imenu-create-index-function
3041 'org-imenu-get-tree)
3043 ;; Make isearch reveal context
3044 (if (or (featurep 'xemacs)
3045 (not (boundp 'outline-isearch-open-invisible-function)))
3046 ;; Emacs 21 and XEmacs make use of the hook
3047 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3048 ;; Emacs 22 deals with this through a special variable
3049 (org-set-local 'outline-isearch-open-invisible-function
3050 (lambda (&rest ignore) (org-show-context 'isearch))))
3052 ;; If empty file that did not turn on org-mode automatically, make it to.
3053 (if (and org-insert-mode-line-in-empty-file
3054 (interactive-p)
3055 (= (point-min) (point-max)))
3056 (insert "# -*- mode: org -*-\n\n"))
3058 (unless org-inhibit-startup
3059 (when org-startup-align-all-tables
3060 (let ((bmp (buffer-modified-p)))
3061 (org-table-map-tables 'org-table-align)
3062 (set-buffer-modified-p bmp)))
3063 (org-cycle-hide-drawers 'all)
3064 (cond
3065 ((eq org-startup-folded t)
3066 (org-cycle '(4)))
3067 ((eq org-startup-folded 'content)
3068 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3069 (org-cycle '(4)) (org-cycle '(4)))))))
3071 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3073 (defun org-current-time ()
3074 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3075 (if (> (car org-time-stamp-rounding-minutes) 1)
3076 (let ((r (car org-time-stamp-rounding-minutes))
3077 (time (decode-time)))
3078 (apply 'encode-time
3079 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3080 (nthcdr 2 time))))
3081 (current-time)))
3083 ;;;; Font-Lock stuff, including the activators
3085 (defvar org-mouse-map (make-sparse-keymap))
3086 (org-defkey org-mouse-map
3087 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3088 (org-defkey org-mouse-map
3089 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3090 (when org-mouse-1-follows-link
3091 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3092 (when org-tab-follows-link
3093 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3094 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3095 (when org-return-follows-link
3096 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3097 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3099 (require 'font-lock)
3101 (defconst org-non-link-chars "]\t\n\r<>")
3102 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3103 "shell" "elisp"))
3104 (defvar org-link-types-re nil
3105 "Matches a link that has a url-like prefix like \"http:\"")
3106 (defvar org-link-re-with-space nil
3107 "Matches a link with spaces, optional angular brackets around it.")
3108 (defvar org-link-re-with-space2 nil
3109 "Matches a link with spaces, optional angular brackets around it.")
3110 (defvar org-angle-link-re nil
3111 "Matches link with angular brackets, spaces are allowed.")
3112 (defvar org-plain-link-re nil
3113 "Matches plain link, without spaces.")
3114 (defvar org-bracket-link-regexp nil
3115 "Matches a link in double brackets.")
3116 (defvar org-bracket-link-analytic-regexp nil
3117 "Regular expression used to analyze links.
3118 Here is what the match groups contain after a match:
3119 1: http:
3120 2: http
3121 3: path
3122 4: [desc]
3123 5: desc")
3124 (defvar org-any-link-re nil
3125 "Regular expression matching any link.")
3127 (defun org-make-link-regexps ()
3128 "Update the link regular expressions.
3129 This should be called after the variable `org-link-types' has changed."
3130 (setq org-link-types-re
3131 (concat
3132 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3133 org-link-re-with-space
3134 (concat
3135 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3136 "\\([^" org-non-link-chars " ]"
3137 "[^" org-non-link-chars "]*"
3138 "[^" org-non-link-chars " ]\\)>?")
3139 org-link-re-with-space2
3140 (concat
3141 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3142 "\\([^" org-non-link-chars " ]"
3143 "[^]\t\n\r]*"
3144 "[^" org-non-link-chars " ]\\)>?")
3145 org-angle-link-re
3146 (concat
3147 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3148 "\\([^" org-non-link-chars " ]"
3149 "[^" org-non-link-chars "]*"
3150 "\\)>")
3151 org-plain-link-re
3152 (concat
3153 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3154 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3155 org-bracket-link-regexp
3156 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3157 org-bracket-link-analytic-regexp
3158 (concat
3159 "\\[\\["
3160 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3161 "\\([^]]+\\)"
3162 "\\]"
3163 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3164 "\\]")
3165 org-any-link-re
3166 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3167 org-angle-link-re "\\)\\|\\("
3168 org-plain-link-re "\\)")))
3170 (org-make-link-regexps)
3172 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3173 "Regular expression for fast time stamp matching.")
3174 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3175 "Regular expression for fast time stamp matching.")
3176 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3177 "Regular expression matching time strings for analysis.
3178 This one does not require the space after the date, so it can be used
3179 on a string that terminates immediately after the date.")
3180 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3181 "Regular expression matching time strings for analysis.")
3182 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3183 "Regular expression matching time stamps, with groups.")
3184 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3185 "Regular expression matching time stamps (also [..]), with groups.")
3186 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3187 "Regular expression matching a time stamp range.")
3188 (defconst org-tr-regexp-both
3189 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3190 "Regular expression matching a time stamp range.")
3191 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3192 org-ts-regexp "\\)?")
3193 "Regular expression matching a time stamp or time stamp range.")
3194 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3195 org-ts-regexp-both "\\)?")
3196 "Regular expression matching a time stamp or time stamp range.
3197 The time stamps may be either active or inactive.")
3199 (defvar org-emph-face nil)
3201 (defun org-do-emphasis-faces (limit)
3202 "Run through the buffer and add overlays to links."
3203 (let (rtn)
3204 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3205 (if (not (= (char-after (match-beginning 3))
3206 (char-after (match-beginning 4))))
3207 (progn
3208 (setq rtn t)
3209 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3210 'face
3211 (nth 1 (assoc (match-string 3)
3212 org-emphasis-alist)))
3213 (add-text-properties (match-beginning 2) (match-end 2)
3214 '(font-lock-multiline t))
3215 (when org-hide-emphasis-markers
3216 (add-text-properties (match-end 4) (match-beginning 5)
3217 '(invisible org-link))
3218 (add-text-properties (match-beginning 3) (match-end 3)
3219 '(invisible org-link)))))
3220 (backward-char 1))
3221 rtn))
3223 (defun org-emphasize (&optional char)
3224 "Insert or change an emphasis, i.e. a font like bold or italic.
3225 If there is an active region, change that region to a new emphasis.
3226 If there is no region, just insert the marker characters and position
3227 the cursor between them.
3228 CHAR should be either the marker character, or the first character of the
3229 HTML tag associated with that emphasis. If CHAR is a space, the means
3230 to remove the emphasis of the selected region.
3231 If char is not given (for example in an interactive call) it
3232 will be prompted for."
3233 (interactive)
3234 (let ((eal org-emphasis-alist) e det
3235 (erc org-emphasis-regexp-components)
3236 (prompt "")
3237 (string "") beg end move tag c s)
3238 (if (org-region-active-p)
3239 (setq beg (region-beginning) end (region-end)
3240 string (buffer-substring beg end))
3241 (setq move t))
3243 (while (setq e (pop eal))
3244 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3245 c (aref tag 0))
3246 (push (cons c (string-to-char (car e))) det)
3247 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3248 (substring tag 1)))))
3249 (unless char
3250 (message "%s" (concat "Emphasis marker or tag:" prompt))
3251 (setq char (read-char-exclusive)))
3252 (setq char (or (cdr (assoc char det)) char))
3253 (if (equal char ?\ )
3254 (setq s "" move nil)
3255 (unless (assoc (char-to-string char) org-emphasis-alist)
3256 (error "No such emphasis marker: \"%c\"" char))
3257 (setq s (char-to-string char)))
3258 (while (and (> (length string) 1)
3259 (equal (substring string 0 1) (substring string -1))
3260 (assoc (substring string 0 1) org-emphasis-alist))
3261 (setq string (substring string 1 -1)))
3262 (setq string (concat s string s))
3263 (if beg (delete-region beg end))
3264 (unless (or (bolp)
3265 (string-match (concat "[" (nth 0 erc) "\n]")
3266 (char-to-string (char-before (point)))))
3267 (insert " "))
3268 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3269 (char-to-string (char-after (point))))
3270 (insert " ") (backward-char 1))
3271 (insert string)
3272 (and move (backward-char 1))))
3274 (defconst org-nonsticky-props
3275 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3278 (defun org-activate-plain-links (limit)
3279 "Run through the buffer and add overlays to links."
3280 (catch 'exit
3281 (let (f)
3282 (while (re-search-forward org-plain-link-re limit t)
3283 (setq f (get-text-property (match-beginning 0) 'face))
3284 (if (or (eq f 'org-tag)
3285 (and (listp f) (memq 'org-tag f)))
3287 (add-text-properties (match-beginning 0) (match-end 0)
3288 (list 'mouse-face 'highlight
3289 'rear-nonsticky org-nonsticky-props
3290 'keymap org-mouse-map
3292 (throw 'exit t))))))
3294 (defun org-activate-code (limit)
3295 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3296 (unless (get-text-property (match-beginning 1) 'face)
3297 (remove-text-properties (match-beginning 0) (match-end 0)
3298 '(display t invisible t intangible t))
3299 t)))
3301 (defun org-activate-angle-links (limit)
3302 "Run through the buffer and add overlays to links."
3303 (if (re-search-forward org-angle-link-re limit t)
3304 (progn
3305 (add-text-properties (match-beginning 0) (match-end 0)
3306 (list 'mouse-face 'highlight
3307 'rear-nonsticky org-nonsticky-props
3308 'keymap org-mouse-map
3310 t)))
3312 (defun org-activate-bracket-links (limit)
3313 "Run through the buffer and add overlays to bracketed links."
3314 (if (re-search-forward org-bracket-link-regexp limit t)
3315 (let* ((help (concat "LINK: "
3316 (org-match-string-no-properties 1)))
3317 ;; FIXME: above we should remove the escapes.
3318 ;; but that requires another match, protecting match data,
3319 ;; a lot of overhead for font-lock.
3320 (ip (org-maybe-intangible
3321 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3322 'keymap org-mouse-map 'mouse-face 'highlight
3323 'font-lock-multiline t 'help-echo help)))
3324 (vp (list 'rear-nonsticky org-nonsticky-props
3325 'keymap org-mouse-map 'mouse-face 'highlight
3326 ' font-lock-multiline t 'help-echo help)))
3327 ;; We need to remove the invisible property here. Table narrowing
3328 ;; may have made some of this invisible.
3329 (remove-text-properties (match-beginning 0) (match-end 0)
3330 '(invisible nil))
3331 (if (match-end 3)
3332 (progn
3333 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3334 (add-text-properties (match-beginning 3) (match-end 3) vp)
3335 (add-text-properties (match-end 3) (match-end 0) ip))
3336 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3337 (add-text-properties (match-beginning 1) (match-end 1) vp)
3338 (add-text-properties (match-end 1) (match-end 0) ip))
3339 t)))
3341 (defun org-activate-dates (limit)
3342 "Run through the buffer and add overlays to dates."
3343 (if (re-search-forward org-tsr-regexp-both limit t)
3344 (progn
3345 (add-text-properties (match-beginning 0) (match-end 0)
3346 (list 'mouse-face 'highlight
3347 'rear-nonsticky org-nonsticky-props
3348 'keymap org-mouse-map))
3349 (when org-display-custom-times
3350 (if (match-end 3)
3351 (org-display-custom-time (match-beginning 3) (match-end 3)))
3352 (org-display-custom-time (match-beginning 1) (match-end 1)))
3353 t)))
3355 (defvar org-target-link-regexp nil
3356 "Regular expression matching radio targets in plain text.")
3357 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3358 "Regular expression matching a link target.")
3359 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3360 "Regular expression matching a radio target.")
3361 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3362 "Regular expression matching any target.")
3364 (defun org-activate-target-links (limit)
3365 "Run through the buffer and add overlays to target matches."
3366 (when org-target-link-regexp
3367 (let ((case-fold-search t))
3368 (if (re-search-forward org-target-link-regexp limit t)
3369 (progn
3370 (add-text-properties (match-beginning 0) (match-end 0)
3371 (list 'mouse-face 'highlight
3372 'rear-nonsticky org-nonsticky-props
3373 'keymap org-mouse-map
3374 'help-echo "Radio target link"
3375 'org-linked-text t))
3376 t)))))
3378 (defun org-update-radio-target-regexp ()
3379 "Find all radio targets in this file and update the regular expression."
3380 (interactive)
3381 (when (memq 'radio org-activate-links)
3382 (setq org-target-link-regexp
3383 (org-make-target-link-regexp (org-all-targets 'radio)))
3384 (org-restart-font-lock)))
3386 (defun org-hide-wide-columns (limit)
3387 (let (s e)
3388 (setq s (text-property-any (point) (or limit (point-max))
3389 'org-cwidth t))
3390 (when s
3391 (setq e (next-single-property-change s 'org-cwidth))
3392 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3393 (goto-char e)
3394 t)))
3396 (defvar org-latex-and-specials-regexp nil
3397 "Regular expression for highlighting export special stuff.")
3398 (defvar org-match-substring-regexp)
3399 (defvar org-match-substring-with-braces-regexp)
3400 (defvar org-export-html-special-string-regexps)
3402 (defun org-compute-latex-and-specials-regexp ()
3403 "Compute regular expression for stuff treated specially by exporters."
3404 (if (not org-highlight-latex-fragments-and-specials)
3405 (org-set-local 'org-latex-and-specials-regexp nil)
3406 (require 'org-exp)
3407 (let*
3408 ((matchers (plist-get org-format-latex-options :matchers))
3409 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3410 org-latex-regexps)))
3411 (options (org-combine-plists (org-default-export-plist)
3412 (org-infile-export-plist)))
3413 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3414 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3415 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3416 (org-export-html-expand (plist-get options :expand-quoted-html))
3417 (org-export-with-special-strings (plist-get options :special-strings))
3418 (re-sub
3419 (cond
3420 ((equal org-export-with-sub-superscripts '{})
3421 (list org-match-substring-with-braces-regexp))
3422 (org-export-with-sub-superscripts
3423 (list org-match-substring-regexp))
3424 (t nil)))
3425 (re-latex
3426 (if org-export-with-LaTeX-fragments
3427 (mapcar (lambda (x) (nth 1 x)) latexs)))
3428 (re-macros
3429 (if org-export-with-TeX-macros
3430 (list (concat "\\\\"
3431 (regexp-opt
3432 (append (mapcar 'car org-html-entities)
3433 (if (boundp 'org-latex-entities)
3434 org-latex-entities nil))
3435 'words))) ; FIXME
3437 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3438 (re-special (if org-export-with-special-strings
3439 (mapcar (lambda (x) (car x))
3440 org-export-html-special-string-regexps)))
3441 (re-rest
3442 (delq nil
3443 (list
3444 (if org-export-html-expand "@<[^>\n]+>")
3445 ))))
3446 (org-set-local
3447 'org-latex-and-specials-regexp
3448 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3449 re-rest) "\\|")))))
3451 (defun org-do-latex-and-special-faces (limit)
3452 "Run through the buffer and add overlays to links."
3453 (when org-latex-and-specials-regexp
3454 (let (rtn d)
3455 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3456 limit t))
3457 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3458 'face))
3459 '(org-code org-verbatim underline)))
3460 (progn
3461 (setq rtn t
3462 d (cond ((member (char-after (1+ (match-beginning 0)))
3463 '(?_ ?^)) 1)
3464 (t 0)))
3465 (font-lock-prepend-text-property
3466 (+ d (match-beginning 0)) (match-end 0)
3467 'face 'org-latex-and-export-specials)
3468 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3469 '(font-lock-multiline t)))))
3470 rtn)))
3472 (defun org-restart-font-lock ()
3473 "Restart font-lock-mode, to force refontification."
3474 (when (and (boundp 'font-lock-mode) font-lock-mode)
3475 (font-lock-mode -1)
3476 (font-lock-mode 1)))
3478 (defun org-all-targets (&optional radio)
3479 "Return a list of all targets in this file.
3480 With optional argument RADIO, only find radio targets."
3481 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3482 rtn)
3483 (save-excursion
3484 (goto-char (point-min))
3485 (while (re-search-forward re nil t)
3486 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3487 rtn)))
3489 (defun org-make-target-link-regexp (targets)
3490 "Make regular expression matching all strings in TARGETS.
3491 The regular expression finds the targets also if there is a line break
3492 between words."
3493 (and targets
3494 (concat
3495 "\\<\\("
3496 (mapconcat
3497 (lambda (x)
3498 (while (string-match " +" x)
3499 (setq x (replace-match "\\s-+" t t x)))
3501 targets
3502 "\\|")
3503 "\\)\\>")))
3505 (defun org-activate-tags (limit)
3506 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3507 (progn
3508 (add-text-properties (match-beginning 1) (match-end 1)
3509 (list 'mouse-face 'highlight
3510 'rear-nonsticky org-nonsticky-props
3511 'keymap org-mouse-map))
3512 t)))
3514 (defun org-outline-level ()
3515 (save-excursion
3516 (looking-at outline-regexp)
3517 (if (match-beginning 1)
3518 (+ (org-get-string-indentation (match-string 1)) 1000)
3519 (1- (- (match-end 0) (match-beginning 0))))))
3521 (defvar org-font-lock-keywords nil)
3523 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3524 "Regular expression matching a property line.")
3526 (defun org-set-font-lock-defaults ()
3527 (let* ((em org-fontify-emphasized-text)
3528 (lk org-activate-links)
3529 (org-font-lock-extra-keywords
3530 (list
3531 ;; Headlines
3532 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3533 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3534 ;; Table lines
3535 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3536 (1 'org-table t))
3537 ;; Table internals
3538 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3539 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3540 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3541 ;; Drawers
3542 (list org-drawer-regexp '(0 'org-special-keyword t))
3543 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3544 ;; Properties
3545 (list org-property-re
3546 '(1 'org-special-keyword t)
3547 '(3 'org-property-value t))
3548 (if org-format-transports-properties-p
3549 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3550 ;; Links
3551 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3552 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3553 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3554 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3555 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3556 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3557 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3558 '(org-hide-wide-columns (0 nil append))
3559 ;; TODO lines
3560 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3561 '(1 (org-get-todo-face 1) t))
3562 ;; DONE
3563 (if org-fontify-done-headline
3564 (list (concat "^[*]+ +\\<\\("
3565 (mapconcat 'regexp-quote org-done-keywords "\\|")
3566 "\\)\\(.*\\)")
3567 '(2 'org-headline-done t))
3568 nil)
3569 ;; Priorities
3570 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3571 ;; Special keywords
3572 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3573 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3574 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3575 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3576 ;; Emphasis
3577 (if em
3578 (if (featurep 'xemacs)
3579 '(org-do-emphasis-faces (0 nil append))
3580 '(org-do-emphasis-faces)))
3581 ;; Checkboxes
3582 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3583 2 'bold prepend)
3584 (if org-provide-checkbox-statistics
3585 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3586 (0 (org-get-checkbox-statistics-face) t)))
3587 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3588 '(1 'org-archived prepend))
3589 ;; Specials
3590 '(org-do-latex-and-special-faces)
3591 ;; Code
3592 '(org-activate-code (1 'org-code t))
3593 ;; COMMENT
3594 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3595 "\\|" org-quote-string "\\)\\>")
3596 '(1 'org-special-keyword t))
3597 '("^#.*" (0 'font-lock-comment-face t))
3599 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3600 ;; Now set the full font-lock-keywords
3601 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3602 (org-set-local 'font-lock-defaults
3603 '(org-font-lock-keywords t nil nil backward-paragraph))
3604 (kill-local-variable 'font-lock-keywords) nil))
3606 (defvar org-m nil)
3607 (defvar org-l nil)
3608 (defvar org-f nil)
3609 (defun org-get-level-face (n)
3610 "Get the right face for match N in font-lock matching of healdines."
3611 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3612 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3613 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3614 (cond
3615 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3616 ((eq n 2) org-f)
3617 (t (if org-level-color-stars-only nil org-f))))
3619 (defun org-get-todo-face (kwd)
3620 "Get the right face for a TODO keyword KWD.
3621 If KWD is a number, get the corresponding match group."
3622 (if (numberp kwd) (setq kwd (match-string kwd)))
3623 (or (cdr (assoc kwd org-todo-keyword-faces))
3624 (and (member kwd org-done-keywords) 'org-done)
3625 'org-todo))
3627 (defun org-unfontify-region (beg end &optional maybe_loudly)
3628 "Remove fontification and activation overlays from links."
3629 (font-lock-default-unfontify-region beg end)
3630 (let* ((buffer-undo-list t)
3631 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3632 (inhibit-modification-hooks t)
3633 deactivate-mark buffer-file-name buffer-file-truename)
3634 (remove-text-properties beg end
3635 '(mouse-face t keymap t org-linked-text t
3636 invisible t intangible t))))
3638 ;;;; Visibility cycling, including org-goto and indirect buffer
3640 ;;; Cycling
3642 (defvar org-cycle-global-status nil)
3643 (make-variable-buffer-local 'org-cycle-global-status)
3644 (defvar org-cycle-subtree-status nil)
3645 (make-variable-buffer-local 'org-cycle-subtree-status)
3647 ;;;###autoload
3648 (defun org-cycle (&optional arg)
3649 "Visibility cycling for Org-mode.
3651 - When this function is called with a prefix argument, rotate the entire
3652 buffer through 3 states (global cycling)
3653 1. OVERVIEW: Show only top-level headlines.
3654 2. CONTENTS: Show all headlines of all levels, but no body text.
3655 3. SHOW ALL: Show everything.
3657 - When point is at the beginning of a headline, rotate the subtree started
3658 by this line through 3 different states (local cycling)
3659 1. FOLDED: Only the main headline is shown.
3660 2. CHILDREN: The main headline and the direct children are shown.
3661 From this state, you can move to one of the children
3662 and zoom in further.
3663 3. SUBTREE: Show the entire subtree, including body text.
3665 - When there is a numeric prefix, go up to a heading with level ARG, do
3666 a `show-subtree' and return to the previous cursor position. If ARG
3667 is negative, go up that many levels.
3669 - When point is not at the beginning of a headline, execute
3670 `indent-relative', like TAB normally does. See the option
3671 `org-cycle-emulate-tab' for details.
3673 - Special case: if point is at the beginning of the buffer and there is
3674 no headline in line 1, this function will act as if called with prefix arg.
3675 But only if also the variable `org-cycle-global-at-bob' is t."
3676 (interactive "P")
3677 (org-load-modules-maybe)
3678 (let* ((outline-regexp
3679 (if (and (org-mode-p) org-cycle-include-plain-lists)
3680 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3681 outline-regexp))
3682 (bob-special (and org-cycle-global-at-bob (bobp)
3683 (not (looking-at outline-regexp))))
3684 (org-cycle-hook
3685 (if bob-special
3686 (delq 'org-optimize-window-after-visibility-change
3687 (copy-sequence org-cycle-hook))
3688 org-cycle-hook))
3689 (pos (point)))
3691 (if (or bob-special (equal arg '(4)))
3692 ;; special case: use global cycling
3693 (setq arg t))
3695 (cond
3697 ((org-at-table-p 'any)
3698 ;; Enter the table or move to the next field in the table
3699 (or (org-table-recognize-table.el)
3700 (progn
3701 (if arg (org-table-edit-field t)
3702 (org-table-justify-field-maybe)
3703 (call-interactively 'org-table-next-field)))))
3705 ((eq arg t) ;; Global cycling
3707 (cond
3708 ((and (eq last-command this-command)
3709 (eq org-cycle-global-status 'overview))
3710 ;; We just created the overview - now do table of contents
3711 ;; This can be slow in very large buffers, so indicate action
3712 (message "CONTENTS...")
3713 (org-content)
3714 (message "CONTENTS...done")
3715 (setq org-cycle-global-status 'contents)
3716 (run-hook-with-args 'org-cycle-hook 'contents))
3718 ((and (eq last-command this-command)
3719 (eq org-cycle-global-status 'contents))
3720 ;; We just showed the table of contents - now show everything
3721 (show-all)
3722 (message "SHOW ALL")
3723 (setq org-cycle-global-status 'all)
3724 (run-hook-with-args 'org-cycle-hook 'all))
3727 ;; Default action: go to overview
3728 (org-overview)
3729 (message "OVERVIEW")
3730 (setq org-cycle-global-status 'overview)
3731 (run-hook-with-args 'org-cycle-hook 'overview))))
3733 ((and org-drawers org-drawer-regexp
3734 (save-excursion
3735 (beginning-of-line 1)
3736 (looking-at org-drawer-regexp)))
3737 ;; Toggle block visibility
3738 (org-flag-drawer
3739 (not (get-char-property (match-end 0) 'invisible))))
3741 ((integerp arg)
3742 ;; Show-subtree, ARG levels up from here.
3743 (save-excursion
3744 (org-back-to-heading)
3745 (outline-up-heading (if (< arg 0) (- arg)
3746 (- (funcall outline-level) arg)))
3747 (org-show-subtree)))
3749 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3750 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3751 ;; At a heading: rotate between three different views
3752 (org-back-to-heading)
3753 (let ((goal-column 0) eoh eol eos)
3754 ;; First, some boundaries
3755 (save-excursion
3756 (org-back-to-heading)
3757 (save-excursion
3758 (beginning-of-line 2)
3759 (while (and (not (eobp)) ;; this is like `next-line'
3760 (get-char-property (1- (point)) 'invisible))
3761 (beginning-of-line 2)) (setq eol (point)))
3762 (outline-end-of-heading) (setq eoh (point))
3763 (org-end-of-subtree t)
3764 (unless (eobp)
3765 (skip-chars-forward " \t\n")
3766 (beginning-of-line 1) ; in case this is an item
3768 (setq eos (1- (point))))
3769 ;; Find out what to do next and set `this-command'
3770 (cond
3771 ((= eos eoh)
3772 ;; Nothing is hidden behind this heading
3773 (message "EMPTY ENTRY")
3774 (setq org-cycle-subtree-status nil)
3775 (save-excursion
3776 (goto-char eos)
3777 (outline-next-heading)
3778 (if (org-invisible-p) (org-flag-heading nil))))
3779 ((or (>= eol eos)
3780 (not (string-match "\\S-" (buffer-substring eol eos))))
3781 ;; Entire subtree is hidden in one line: open it
3782 (org-show-entry)
3783 (show-children)
3784 (message "CHILDREN")
3785 (save-excursion
3786 (goto-char eos)
3787 (outline-next-heading)
3788 (if (org-invisible-p) (org-flag-heading nil)))
3789 (setq org-cycle-subtree-status 'children)
3790 (run-hook-with-args 'org-cycle-hook 'children))
3791 ((and (eq last-command this-command)
3792 (eq org-cycle-subtree-status 'children))
3793 ;; We just showed the children, now show everything.
3794 (org-show-subtree)
3795 (message "SUBTREE")
3796 (setq org-cycle-subtree-status 'subtree)
3797 (run-hook-with-args 'org-cycle-hook 'subtree))
3799 ;; Default action: hide the subtree.
3800 (hide-subtree)
3801 (message "FOLDED")
3802 (setq org-cycle-subtree-status 'folded)
3803 (run-hook-with-args 'org-cycle-hook 'folded)))))
3805 ;; TAB emulation
3806 (buffer-read-only (org-back-to-heading))
3808 ((org-try-cdlatex-tab))
3810 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3811 (or (not (bolp))
3812 (not (looking-at outline-regexp))))
3813 (call-interactively (global-key-binding "\t")))
3815 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3816 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3817 (or (and (eq org-cycle-emulate-tab 'white)
3818 (= (match-end 0) (point-at-eol)))
3819 (and (eq org-cycle-emulate-tab 'whitestart)
3820 (>= (match-end 0) pos))))
3822 (eq org-cycle-emulate-tab t))
3823 (call-interactively (global-key-binding "\t")))
3825 (t (save-excursion
3826 (org-back-to-heading)
3827 (org-cycle))))))
3829 ;;;###autoload
3830 (defun org-global-cycle (&optional arg)
3831 "Cycle the global visibility. For details see `org-cycle'."
3832 (interactive "P")
3833 (let ((org-cycle-include-plain-lists
3834 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3835 (if (integerp arg)
3836 (progn
3837 (show-all)
3838 (hide-sublevels arg)
3839 (setq org-cycle-global-status 'contents))
3840 (org-cycle '(4)))))
3842 (defun org-overview ()
3843 "Switch to overview mode, shoing only top-level headlines.
3844 Really, this shows all headlines with level equal or greater than the level
3845 of the first headline in the buffer. This is important, because if the
3846 first headline is not level one, then (hide-sublevels 1) gives confusing
3847 results."
3848 (interactive)
3849 (let ((level (save-excursion
3850 (goto-char (point-min))
3851 (if (re-search-forward (concat "^" outline-regexp) nil t)
3852 (progn
3853 (goto-char (match-beginning 0))
3854 (funcall outline-level))))))
3855 (and level (hide-sublevels level))))
3857 (defun org-content (&optional arg)
3858 "Show all headlines in the buffer, like a table of contents.
3859 With numerical argument N, show content up to level N."
3860 (interactive "P")
3861 (save-excursion
3862 ;; Visit all headings and show their offspring
3863 (and (integerp arg) (org-overview))
3864 (goto-char (point-max))
3865 (catch 'exit
3866 (while (and (progn (condition-case nil
3867 (outline-previous-visible-heading 1)
3868 (error (goto-char (point-min))))
3870 (looking-at outline-regexp))
3871 (if (integerp arg)
3872 (show-children (1- arg))
3873 (show-branches))
3874 (if (bobp) (throw 'exit nil))))))
3877 (defun org-optimize-window-after-visibility-change (state)
3878 "Adjust the window after a change in outline visibility.
3879 This function is the default value of the hook `org-cycle-hook'."
3880 (when (get-buffer-window (current-buffer))
3881 (cond
3882 ; ((eq state 'overview) (org-first-headline-recenter 1))
3883 ; ((eq state 'overview) (org-beginning-of-line))
3884 ((eq state 'content) nil)
3885 ((eq state 'all) nil)
3886 ((eq state 'folded) nil)
3887 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3888 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3890 (defun org-compact-display-after-subtree-move ()
3891 (let (beg end)
3892 (save-excursion
3893 (if (org-up-heading-safe)
3894 (progn
3895 (hide-subtree)
3896 (show-entry)
3897 (show-children)
3898 (org-cycle-show-empty-lines 'children)
3899 (org-cycle-hide-drawers 'children))
3900 (org-overview)))))
3902 (defun org-cycle-show-empty-lines (state)
3903 "Show empty lines above all visible headlines.
3904 The region to be covered depends on STATE when called through
3905 `org-cycle-hook'. Lisp program can use t for STATE to get the
3906 entire buffer covered. Note that an empty line is only shown if there
3907 are at least `org-cycle-separator-lines' empty lines before the headeline."
3908 (when (> org-cycle-separator-lines 0)
3909 (save-excursion
3910 (let* ((n org-cycle-separator-lines)
3911 (re (cond
3912 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3913 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3914 (t (let ((ns (number-to-string (- n 2))))
3915 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3916 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3917 beg end)
3918 (cond
3919 ((memq state '(overview contents t))
3920 (setq beg (point-min) end (point-max)))
3921 ((memq state '(children folded))
3922 (setq beg (point) end (progn (org-end-of-subtree t t)
3923 (beginning-of-line 2)
3924 (point)))))
3925 (when beg
3926 (goto-char beg)
3927 (while (re-search-forward re end t)
3928 (if (not (get-char-property (match-end 1) 'invisible))
3929 (outline-flag-region
3930 (match-beginning 1) (match-end 1) nil)))))))
3931 ;; Never hide empty lines at the end of the file.
3932 (save-excursion
3933 (goto-char (point-max))
3934 (outline-previous-heading)
3935 (outline-end-of-heading)
3936 (if (and (looking-at "[ \t\n]+")
3937 (= (match-end 0) (point-max)))
3938 (outline-flag-region (point) (match-end 0) nil))))
3940 (defun org-cycle-hide-drawers (state)
3941 "Re-hide all drawers after a visibility state change."
3942 (when (and (org-mode-p)
3943 (not (memq state '(overview folded))))
3944 (save-excursion
3945 (let* ((globalp (memq state '(contents all)))
3946 (beg (if globalp (point-min) (point)))
3947 (end (if globalp (point-max) (org-end-of-subtree t))))
3948 (goto-char beg)
3949 (while (re-search-forward org-drawer-regexp end t)
3950 (org-flag-drawer t))))))
3952 (defun org-flag-drawer (flag)
3953 (save-excursion
3954 (beginning-of-line 1)
3955 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
3956 (let ((b (match-end 0))
3957 (outline-regexp org-outline-regexp))
3958 (if (re-search-forward
3959 "^[ \t]*:END:"
3960 (save-excursion (outline-next-heading) (point)) t)
3961 (outline-flag-region b (point-at-eol) flag)
3962 (error ":END: line missing"))))))
3966 (defun org-subtree-end-visible-p ()
3967 "Is the end of the current subtree visible?"
3968 (pos-visible-in-window-p
3969 (save-excursion (org-end-of-subtree t) (point))))
3971 (defun org-first-headline-recenter (&optional N)
3972 "Move cursor to the first headline and recenter the headline.
3973 Optional argument N means, put the headline into the Nth line of the window."
3974 (goto-char (point-min))
3975 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3976 (beginning-of-line)
3977 (recenter (prefix-numeric-value N))))
3979 ;;; Org-goto
3981 (defvar org-goto-window-configuration nil)
3982 (defvar org-goto-marker nil)
3983 (defvar org-goto-map
3984 (let ((map (make-sparse-keymap)))
3985 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
3986 (while (setq cmd (pop cmds))
3987 (substitute-key-definition cmd cmd map global-map)))
3988 (suppress-keymap map)
3989 (org-defkey map "\C-m" 'org-goto-ret)
3990 (org-defkey map [(return)] 'org-goto-ret)
3991 (org-defkey map [(left)] 'org-goto-left)
3992 (org-defkey map [(right)] 'org-goto-right)
3993 (org-defkey map [(control ?g)] 'org-goto-quit)
3994 (org-defkey map "\C-i" 'org-cycle)
3995 (org-defkey map [(tab)] 'org-cycle)
3996 (org-defkey map [(down)] 'outline-next-visible-heading)
3997 (org-defkey map [(up)] 'outline-previous-visible-heading)
3998 (if org-goto-auto-isearch
3999 (if (fboundp 'define-key-after)
4000 (define-key-after map [t] 'org-goto-local-auto-isearch)
4001 nil)
4002 (org-defkey map "q" 'org-goto-quit)
4003 (org-defkey map "n" 'outline-next-visible-heading)
4004 (org-defkey map "p" 'outline-previous-visible-heading)
4005 (org-defkey map "f" 'outline-forward-same-level)
4006 (org-defkey map "b" 'outline-backward-same-level)
4007 (org-defkey map "u" 'outline-up-heading))
4008 (org-defkey map "/" 'org-occur)
4009 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4010 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4011 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4012 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4013 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4014 map))
4016 (defconst org-goto-help
4017 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4018 RET=jump to location [Q]uit and return to previous location
4019 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4021 (defvar org-goto-start-pos) ; dynamically scoped parameter
4023 (defun org-goto (&optional alternative-interface)
4024 "Look up a different location in the current file, keeping current visibility.
4026 When you want look-up or go to a different location in a document, the
4027 fastest way is often to fold the entire buffer and then dive into the tree.
4028 This method has the disadvantage, that the previous location will be folded,
4029 which may not be what you want.
4031 This command works around this by showing a copy of the current buffer
4032 in an indirect buffer, in overview mode. You can dive into the tree in
4033 that copy, use org-occur and incremental search to find a location.
4034 When pressing RET or `Q', the command returns to the original buffer in
4035 which the visibility is still unchanged. After RET is will also jump to
4036 the location selected in the indirect buffer and expose the
4037 the headline hierarchy above."
4038 (interactive "P")
4039 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4040 (org-refile-use-outline-path t)
4041 (interface
4042 (if (not alternative-interface)
4043 org-goto-interface
4044 (if (eq org-goto-interface 'outline)
4045 'outline-path-completion
4046 'outline)))
4047 (org-goto-start-pos (point))
4048 (selected-point
4049 (if (eq interface 'outline)
4050 (car (org-get-location (current-buffer) org-goto-help))
4051 (nth 3 (org-refile-get-location "Goto: ")))))
4052 (if selected-point
4053 (progn
4054 (org-mark-ring-push org-goto-start-pos)
4055 (goto-char selected-point)
4056 (if (or (org-invisible-p) (org-invisible-p2))
4057 (org-show-context 'org-goto)))
4058 (message "Quit"))))
4060 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4061 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4062 (defvar org-goto-local-auto-isearch-map) ; defined below
4064 (defun org-get-location (buf help)
4065 "Let the user select a location in the Org-mode buffer BUF.
4066 This function uses a recursive edit. It returns the selected position
4067 or nil."
4068 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4069 (isearch-hide-immediately nil)
4070 (isearch-search-fun-function
4071 (lambda () 'org-goto-local-search-forward-headings))
4072 (org-goto-selected-point org-goto-exit-command))
4073 (save-excursion
4074 (save-window-excursion
4075 (delete-other-windows)
4076 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4077 (switch-to-buffer
4078 (condition-case nil
4079 (make-indirect-buffer (current-buffer) "*org-goto*")
4080 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4081 (with-output-to-temp-buffer "*Help*"
4082 (princ help))
4083 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4084 (setq buffer-read-only nil)
4085 (let ((org-startup-truncated t)
4086 (org-startup-folded nil)
4087 (org-startup-align-all-tables nil))
4088 (org-mode)
4089 (org-overview))
4090 (setq buffer-read-only t)
4091 (if (and (boundp 'org-goto-start-pos)
4092 (integer-or-marker-p org-goto-start-pos))
4093 (let ((org-show-hierarchy-above t)
4094 (org-show-siblings t)
4095 (org-show-following-heading t))
4096 (goto-char org-goto-start-pos)
4097 (and (org-invisible-p) (org-show-context)))
4098 (goto-char (point-min)))
4099 (org-beginning-of-line)
4100 (message "Select location and press RET")
4101 (use-local-map org-goto-map)
4102 (recursive-edit)
4104 (kill-buffer "*org-goto*")
4105 (cons org-goto-selected-point org-goto-exit-command)))
4107 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4108 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4109 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4110 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4112 (defun org-goto-local-search-forward-headings (string bound noerror)
4113 "Search and make sure that anu matches are in headlines."
4114 (catch 'return
4115 (while (search-forward string bound noerror)
4116 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4117 (and (member :headline context)
4118 (not (member :tags context))))
4119 (throw 'return (point))))))
4121 (defun org-goto-local-auto-isearch ()
4122 "Start isearch."
4123 (interactive)
4124 (goto-char (point-min))
4125 (let ((keys (this-command-keys)))
4126 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4127 (isearch-mode t)
4128 (isearch-process-search-char (string-to-char keys)))))
4130 (defun org-goto-ret (&optional arg)
4131 "Finish `org-goto' by going to the new location."
4132 (interactive "P")
4133 (setq org-goto-selected-point (point)
4134 org-goto-exit-command 'return)
4135 (throw 'exit nil))
4137 (defun org-goto-left ()
4138 "Finish `org-goto' by going to the new location."
4139 (interactive)
4140 (if (org-on-heading-p)
4141 (progn
4142 (beginning-of-line 1)
4143 (setq org-goto-selected-point (point)
4144 org-goto-exit-command 'left)
4145 (throw 'exit nil))
4146 (error "Not on a heading")))
4148 (defun org-goto-right ()
4149 "Finish `org-goto' by going to the new location."
4150 (interactive)
4151 (if (org-on-heading-p)
4152 (progn
4153 (setq org-goto-selected-point (point)
4154 org-goto-exit-command 'right)
4155 (throw 'exit nil))
4156 (error "Not on a heading")))
4158 (defun org-goto-quit ()
4159 "Finish `org-goto' without cursor motion."
4160 (interactive)
4161 (setq org-goto-selected-point nil)
4162 (setq org-goto-exit-command 'quit)
4163 (throw 'exit nil))
4165 ;;; Indirect buffer display of subtrees
4167 (defvar org-indirect-dedicated-frame nil
4168 "This is the frame being used for indirect tree display.")
4169 (defvar org-last-indirect-buffer nil)
4171 (defun org-tree-to-indirect-buffer (&optional arg)
4172 "Create indirect buffer and narrow it to current subtree.
4173 With numerical prefix ARG, go up to this level and then take that tree.
4174 If ARG is negative, go up that many levels.
4175 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4176 indirect buffer previously made with this command, to avoid proliferation of
4177 indirect buffers. However, when you call the command with a `C-u' prefix, or
4178 when `org-indirect-buffer-display' is `new-frame', the last buffer
4179 is kept so that you can work with several indirect buffers at the same time.
4180 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4181 requests that a new frame be made for the new buffer, so that the dedicated
4182 frame is not changed."
4183 (interactive "P")
4184 (let ((cbuf (current-buffer))
4185 (cwin (selected-window))
4186 (pos (point))
4187 beg end level heading ibuf)
4188 (save-excursion
4189 (org-back-to-heading t)
4190 (when (numberp arg)
4191 (setq level (org-outline-level))
4192 (if (< arg 0) (setq arg (+ level arg)))
4193 (while (> (setq level (org-outline-level)) arg)
4194 (outline-up-heading 1 t)))
4195 (setq beg (point)
4196 heading (org-get-heading))
4197 (org-end-of-subtree t) (setq end (point)))
4198 (if (and (buffer-live-p org-last-indirect-buffer)
4199 (not (eq org-indirect-buffer-display 'new-frame))
4200 (not arg))
4201 (kill-buffer org-last-indirect-buffer))
4202 (setq ibuf (org-get-indirect-buffer cbuf)
4203 org-last-indirect-buffer ibuf)
4204 (cond
4205 ((or (eq org-indirect-buffer-display 'new-frame)
4206 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4207 (select-frame (make-frame))
4208 (delete-other-windows)
4209 (switch-to-buffer ibuf)
4210 (org-set-frame-title heading))
4211 ((eq org-indirect-buffer-display 'dedicated-frame)
4212 (raise-frame
4213 (select-frame (or (and org-indirect-dedicated-frame
4214 (frame-live-p org-indirect-dedicated-frame)
4215 org-indirect-dedicated-frame)
4216 (setq org-indirect-dedicated-frame (make-frame)))))
4217 (delete-other-windows)
4218 (switch-to-buffer ibuf)
4219 (org-set-frame-title (concat "Indirect: " heading)))
4220 ((eq org-indirect-buffer-display 'current-window)
4221 (switch-to-buffer ibuf))
4222 ((eq org-indirect-buffer-display 'other-window)
4223 (pop-to-buffer ibuf))
4224 (t (error "Invalid value.")))
4225 (if (featurep 'xemacs)
4226 (save-excursion (org-mode) (turn-on-font-lock)))
4227 (narrow-to-region beg end)
4228 (show-all)
4229 (goto-char pos)
4230 (and (window-live-p cwin) (select-window cwin))))
4232 (defun org-get-indirect-buffer (&optional buffer)
4233 (setq buffer (or buffer (current-buffer)))
4234 (let ((n 1) (base (buffer-name buffer)) bname)
4235 (while (buffer-live-p
4236 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4237 (setq n (1+ n)))
4238 (condition-case nil
4239 (make-indirect-buffer buffer bname 'clone)
4240 (error (make-indirect-buffer buffer bname)))))
4242 (defun org-set-frame-title (title)
4243 "Set the title of the current frame to the string TITLE."
4244 ;; FIXME: how to name a single frame in XEmacs???
4245 (unless (featurep 'xemacs)
4246 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4248 ;;;; Structure editing
4250 ;;; Inserting headlines
4252 (defun org-insert-heading (&optional force-heading)
4253 "Insert a new heading or item with same depth at point.
4254 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4255 If point is at the beginning of a headline, insert a sibling before the
4256 current headline. If point is not at the beginning, do not split the line,
4257 but create the new hedline after the current line."
4258 (interactive "P")
4259 (if (= (buffer-size) 0)
4260 (insert "\n* ")
4261 (when (or force-heading (not (org-insert-item)))
4262 (let* ((head (save-excursion
4263 (condition-case nil
4264 (progn
4265 (org-back-to-heading)
4266 (match-string 0))
4267 (error "*"))))
4268 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4269 pos)
4270 (cond
4271 ((and (org-on-heading-p) (bolp)
4272 (or (bobp)
4273 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4274 ;; insert before the current line
4275 (open-line (if blank 2 1)))
4276 ((and (bolp)
4277 (or (bobp)
4278 (save-excursion
4279 (backward-char 1) (not (org-invisible-p)))))
4280 ;; insert right here
4281 nil)
4283 ;; in the middle of the line
4284 (org-show-entry)
4285 (let ((split
4286 (org-get-alist-option org-M-RET-may-split-line 'headline))
4287 tags pos)
4288 (if (org-on-heading-p)
4289 (progn
4290 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4291 (setq tags (and (match-end 2) (match-string 2)))
4292 (and (match-end 1)
4293 (delete-region (match-beginning 1) (match-end 1)))
4294 (setq pos (point-at-bol))
4295 (or split (end-of-line 1))
4296 (delete-horizontal-space)
4297 (newline (if blank 2 1))
4298 (when tags
4299 (save-excursion
4300 (goto-char pos)
4301 (end-of-line 1)
4302 (insert " " tags)
4303 (org-set-tags nil 'align))))
4304 (or split (end-of-line 1))
4305 (newline (if blank 2 1))))))
4306 (insert head) (just-one-space)
4307 (setq pos (point))
4308 (end-of-line 1)
4309 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4310 (run-hooks 'org-insert-heading-hook)))))
4312 (defun org-get-heading (&optional no-tags)
4313 "Return the heading of the current entry, without the stars."
4314 (save-excursion
4315 (org-back-to-heading t)
4316 (if (looking-at
4317 (if no-tags
4318 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4319 "\\*+[ \t]+\\([^\r\n]*\\)"))
4320 (match-string 1) "")))
4322 (defun org-insert-heading-after-current ()
4323 "Insert a new heading with same level as current, after current subtree."
4324 (interactive)
4325 (org-back-to-heading)
4326 (org-insert-heading)
4327 (org-move-subtree-down)
4328 (end-of-line 1))
4330 (defun org-insert-todo-heading (arg)
4331 "Insert a new heading with the same level and TODO state as current heading.
4332 If the heading has no TODO state, or if the state is DONE, use the first
4333 state (TODO by default). Also with prefix arg, force first state."
4334 (interactive "P")
4335 (when (not (org-insert-item 'checkbox))
4336 (org-insert-heading)
4337 (save-excursion
4338 (org-back-to-heading)
4339 (outline-previous-heading)
4340 (looking-at org-todo-line-regexp))
4341 (if (or arg
4342 (not (match-beginning 2))
4343 (member (match-string 2) org-done-keywords))
4344 (insert (car org-todo-keywords-1) " ")
4345 (insert (match-string 2) " "))))
4347 (defun org-insert-subheading (arg)
4348 "Insert a new subheading and demote it.
4349 Works for outline headings and for plain lists alike."
4350 (interactive "P")
4351 (org-insert-heading arg)
4352 (cond
4353 ((org-on-heading-p) (org-do-demote))
4354 ((org-at-item-p) (org-indent-item 1))))
4356 (defun org-insert-todo-subheading (arg)
4357 "Insert a new subheading with TODO keyword or checkbox and demote it.
4358 Works for outline headings and for plain lists alike."
4359 (interactive "P")
4360 (org-insert-todo-heading arg)
4361 (cond
4362 ((org-on-heading-p) (org-do-demote))
4363 ((org-at-item-p) (org-indent-item 1))))
4365 ;;; Promotion and Demotion
4367 (defun org-promote-subtree ()
4368 "Promote the entire subtree.
4369 See also `org-promote'."
4370 (interactive)
4371 (save-excursion
4372 (org-map-tree 'org-promote))
4373 (org-fix-position-after-promote))
4375 (defun org-demote-subtree ()
4376 "Demote the entire subtree. See `org-demote'.
4377 See also `org-promote'."
4378 (interactive)
4379 (save-excursion
4380 (org-map-tree 'org-demote))
4381 (org-fix-position-after-promote))
4384 (defun org-do-promote ()
4385 "Promote the current heading higher up the tree.
4386 If the region is active in `transient-mark-mode', promote all headings
4387 in the region."
4388 (interactive)
4389 (save-excursion
4390 (if (org-region-active-p)
4391 (org-map-region 'org-promote (region-beginning) (region-end))
4392 (org-promote)))
4393 (org-fix-position-after-promote))
4395 (defun org-do-demote ()
4396 "Demote the current heading lower down the tree.
4397 If the region is active in `transient-mark-mode', demote all headings
4398 in the region."
4399 (interactive)
4400 (save-excursion
4401 (if (org-region-active-p)
4402 (org-map-region 'org-demote (region-beginning) (region-end))
4403 (org-demote)))
4404 (org-fix-position-after-promote))
4406 (defun org-fix-position-after-promote ()
4407 "Make sure that after pro/demotion cursor position is right."
4408 (let ((pos (point)))
4409 (when (save-excursion
4410 (beginning-of-line 1)
4411 (looking-at org-todo-line-regexp)
4412 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4413 (cond ((eobp) (insert " "))
4414 ((eolp) (insert " "))
4415 ((equal (char-after) ?\ ) (forward-char 1))))))
4417 (defun org-reduced-level (l)
4418 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4420 (defun org-get-valid-level (level &optional change)
4421 "Rectify a level change under the influence of `org-odd-levels-only'
4422 LEVEL is a current level, CHANGE is by how much the level should be
4423 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4424 even level numbers will become the next higher odd number."
4425 (if org-odd-levels-only
4426 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4427 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4428 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4429 (max 1 (+ level change))))
4431 (if (boundp 'define-obsolete-function-alias)
4432 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4433 (define-obsolete-function-alias 'org-get-legal-level
4434 'org-get-valid-level)
4435 (define-obsolete-function-alias 'org-get-legal-level
4436 'org-get-valid-level "23.1")))
4438 (defun org-promote ()
4439 "Promote the current heading higher up the tree.
4440 If the region is active in `transient-mark-mode', promote all headings
4441 in the region."
4442 (org-back-to-heading t)
4443 (let* ((level (save-match-data (funcall outline-level)))
4444 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4445 (diff (abs (- level (length up-head) -1))))
4446 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4447 (replace-match up-head nil t)
4448 ;; Fixup tag positioning
4449 (and org-auto-align-tags (org-set-tags nil t))
4450 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4452 (defun org-demote ()
4453 "Demote the current heading lower down the tree.
4454 If the region is active in `transient-mark-mode', demote all headings
4455 in the region."
4456 (org-back-to-heading t)
4457 (let* ((level (save-match-data (funcall outline-level)))
4458 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4459 (diff (abs (- level (length down-head) -1))))
4460 (replace-match down-head nil t)
4461 ;; Fixup tag positioning
4462 (and org-auto-align-tags (org-set-tags nil t))
4463 (if org-adapt-indentation (org-fixup-indentation diff))))
4465 (defun org-map-tree (fun)
4466 "Call FUN for every heading underneath the current one."
4467 (org-back-to-heading)
4468 (let ((level (funcall outline-level)))
4469 (save-excursion
4470 (funcall fun)
4471 (while (and (progn
4472 (outline-next-heading)
4473 (> (funcall outline-level) level))
4474 (not (eobp)))
4475 (funcall fun)))))
4477 (defun org-map-region (fun beg end)
4478 "Call FUN for every heading between BEG and END."
4479 (let ((org-ignore-region t))
4480 (save-excursion
4481 (setq end (copy-marker end))
4482 (goto-char beg)
4483 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4484 (< (point) end))
4485 (funcall fun))
4486 (while (and (progn
4487 (outline-next-heading)
4488 (< (point) end))
4489 (not (eobp)))
4490 (funcall fun)))))
4492 (defun org-fixup-indentation (diff)
4493 "Change the indentation in the current entry by DIFF
4494 However, if any line in the current entry has no indentation, or if it
4495 would end up with no indentation after the change, nothing at all is done."
4496 (save-excursion
4497 (let ((end (save-excursion (outline-next-heading)
4498 (point-marker)))
4499 (prohibit (if (> diff 0)
4500 "^\\S-"
4501 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4502 col)
4503 (unless (save-excursion (end-of-line 1)
4504 (re-search-forward prohibit end t))
4505 (while (and (< (point) end)
4506 (re-search-forward "^[ \t]+" end t))
4507 (goto-char (match-end 0))
4508 (setq col (current-column))
4509 (if (< diff 0) (replace-match ""))
4510 (indent-to (+ diff col))))
4511 (move-marker end nil))))
4513 (defun org-convert-to-odd-levels ()
4514 "Convert an org-mode file with all levels allowed to one with odd levels.
4515 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4516 level 5 etc."
4517 (interactive)
4518 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4519 (let ((org-odd-levels-only nil) n)
4520 (save-excursion
4521 (goto-char (point-min))
4522 (while (re-search-forward "^\\*\\*+ " nil t)
4523 (setq n (- (length (match-string 0)) 2))
4524 (while (>= (setq n (1- n)) 0)
4525 (org-demote))
4526 (end-of-line 1))))))
4529 (defun org-convert-to-oddeven-levels ()
4530 "Convert an org-mode file with only odd levels to one with odd and even levels.
4531 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4532 section with an even level, conversion would destroy the structure of the file. An error
4533 is signaled in this case."
4534 (interactive)
4535 (goto-char (point-min))
4536 ;; First check if there are no even levels
4537 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4538 (org-show-context t)
4539 (error "Not all levels are odd in this file. Conversion not possible."))
4540 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4541 (let ((org-odd-levels-only nil) n)
4542 (save-excursion
4543 (goto-char (point-min))
4544 (while (re-search-forward "^\\*\\*+ " nil t)
4545 (setq n (/ (1- (length (match-string 0))) 2))
4546 (while (>= (setq n (1- n)) 0)
4547 (org-promote))
4548 (end-of-line 1))))))
4550 (defun org-tr-level (n)
4551 "Make N odd if required."
4552 (if org-odd-levels-only (1+ (/ n 2)) n))
4554 ;;; Vertical tree motion, cutting and pasting of subtrees
4556 (defun org-move-subtree-up (&optional arg)
4557 "Move the current subtree up past ARG headlines of the same level."
4558 (interactive "p")
4559 (org-move-subtree-down (- (prefix-numeric-value arg))))
4561 (defun org-move-subtree-down (&optional arg)
4562 "Move the current subtree down past ARG headlines of the same level."
4563 (interactive "p")
4564 (setq arg (prefix-numeric-value arg))
4565 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4566 'outline-get-last-sibling))
4567 (ins-point (make-marker))
4568 (cnt (abs arg))
4569 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4570 ;; Select the tree
4571 (org-back-to-heading)
4572 (setq beg0 (point))
4573 (save-excursion
4574 (setq ne-beg (org-back-over-empty-lines))
4575 (setq beg (point)))
4576 (save-match-data
4577 (save-excursion (outline-end-of-heading)
4578 (setq folded (org-invisible-p)))
4579 (outline-end-of-subtree))
4580 (outline-next-heading)
4581 (setq ne-end (org-back-over-empty-lines))
4582 (setq end (point))
4583 (goto-char beg0)
4584 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4585 ;; include less whitespace
4586 (save-excursion
4587 (goto-char beg)
4588 (forward-line (- ne-beg ne-end))
4589 (setq beg (point))))
4590 ;; Find insertion point, with error handling
4591 (while (> cnt 0)
4592 (or (and (funcall movfunc) (looking-at outline-regexp))
4593 (progn (goto-char beg0)
4594 (error "Cannot move past superior level or buffer limit")))
4595 (setq cnt (1- cnt)))
4596 (if (> arg 0)
4597 ;; Moving forward - still need to move over subtree
4598 (progn (org-end-of-subtree t t)
4599 (save-excursion
4600 (org-back-over-empty-lines)
4601 (or (bolp) (newline)))))
4602 (setq ne-ins (org-back-over-empty-lines))
4603 (move-marker ins-point (point))
4604 (setq txt (buffer-substring beg end))
4605 (delete-region beg end)
4606 (outline-flag-region (1- beg) beg nil)
4607 (outline-flag-region (1- (point)) (point) nil)
4608 (insert txt)
4609 (or (bolp) (insert "\n"))
4610 (setq ins-end (point))
4611 (goto-char ins-point)
4612 (org-skip-whitespace)
4613 (when (and (< arg 0)
4614 (org-first-sibling-p)
4615 (> ne-ins ne-beg))
4616 ;; Move whitespace back to beginning
4617 (save-excursion
4618 (goto-char ins-end)
4619 (let ((kill-whole-line t))
4620 (kill-line (- ne-ins ne-beg)) (point)))
4621 (insert (make-string (- ne-ins ne-beg) ?\n)))
4622 (move-marker ins-point nil)
4623 (org-compact-display-after-subtree-move)
4624 (unless folded
4625 (org-show-entry)
4626 (show-children)
4627 (org-cycle-hide-drawers 'children))))
4629 (defvar org-subtree-clip ""
4630 "Clipboard for cut and paste of subtrees.
4631 This is actually only a copy of the kill, because we use the normal kill
4632 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4634 (defvar org-subtree-clip-folded nil
4635 "Was the last copied subtree folded?
4636 This is used to fold the tree back after pasting.")
4638 (defun org-cut-subtree (&optional n)
4639 "Cut the current subtree into the clipboard.
4640 With prefix arg N, cut this many sequential subtrees.
4641 This is a short-hand for marking the subtree and then cutting it."
4642 (interactive "p")
4643 (org-copy-subtree n 'cut))
4645 (defun org-copy-subtree (&optional n cut)
4646 "Cut the current subtree into the clipboard.
4647 With prefix arg N, cut this many sequential subtrees.
4648 This is a short-hand for marking the subtree and then copying it.
4649 If CUT is non-nil, actually cut the subtree."
4650 (interactive "p")
4651 (let (beg end folded (beg0 (point)))
4652 (if (interactive-p)
4653 (org-back-to-heading nil) ; take what looks like a subtree
4654 (org-back-to-heading t)) ; take what is really there
4655 (org-back-over-empty-lines)
4656 (setq beg (point))
4657 (skip-chars-forward " \t\r\n")
4658 (save-match-data
4659 (save-excursion (outline-end-of-heading)
4660 (setq folded (org-invisible-p)))
4661 (condition-case nil
4662 (outline-forward-same-level (1- n))
4663 (error nil))
4664 (org-end-of-subtree t t))
4665 (org-back-over-empty-lines)
4666 (setq end (point))
4667 (goto-char beg0)
4668 (when (> end beg)
4669 (setq org-subtree-clip-folded folded)
4670 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4671 (setq org-subtree-clip (current-kill 0))
4672 (message "%s: Subtree(s) with %d characters"
4673 (if cut "Cut" "Copied")
4674 (length org-subtree-clip)))))
4676 (defun org-paste-subtree (&optional level tree)
4677 "Paste the clipboard as a subtree, with modification of headline level.
4678 The entire subtree is promoted or demoted in order to match a new headline
4679 level. By default, the new level is derived from the visible headings
4680 before and after the insertion point, and taken to be the inferior headline
4681 level of the two. So if the previous visible heading is level 3 and the
4682 next is level 4 (or vice versa), level 4 will be used for insertion.
4683 This makes sure that the subtree remains an independent subtree and does
4684 not swallow low level entries.
4686 You can also force a different level, either by using a numeric prefix
4687 argument, or by inserting the heading marker by hand. For example, if the
4688 cursor is after \"*****\", then the tree will be shifted to level 5.
4690 If you want to insert the tree as is, just use \\[yank].
4692 If optional TREE is given, use this text instead of the kill ring."
4693 (interactive "P")
4694 (unless (org-kill-is-subtree-p tree)
4695 (error "%s"
4696 (substitute-command-keys
4697 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4698 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4699 (^re (concat "^\\(" outline-regexp "\\)"))
4700 (re (concat "\\(" outline-regexp "\\)"))
4701 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4703 (old-level (if (string-match ^re txt)
4704 (- (match-end 0) (match-beginning 0) 1)
4705 -1))
4706 (force-level (cond (level (prefix-numeric-value level))
4707 ((string-match
4708 ^re_ (buffer-substring (point-at-bol) (point)))
4709 (- (match-end 1) (match-beginning 1)))
4710 (t nil)))
4711 (previous-level (save-excursion
4712 (condition-case nil
4713 (progn
4714 (outline-previous-visible-heading 1)
4715 (if (looking-at re)
4716 (- (match-end 0) (match-beginning 0) 1)
4718 (error 1))))
4719 (next-level (save-excursion
4720 (condition-case nil
4721 (progn
4722 (or (looking-at outline-regexp)
4723 (outline-next-visible-heading 1))
4724 (if (looking-at re)
4725 (- (match-end 0) (match-beginning 0) 1)
4727 (error 1))))
4728 (new-level (or force-level (max previous-level next-level)))
4729 (shift (if (or (= old-level -1)
4730 (= new-level -1)
4731 (= old-level new-level))
4733 (- new-level old-level)))
4734 (delta (if (> shift 0) -1 1))
4735 (func (if (> shift 0) 'org-demote 'org-promote))
4736 (org-odd-levels-only nil)
4737 beg end)
4738 ;; Remove the forced level indicator
4739 (if force-level
4740 (delete-region (point-at-bol) (point)))
4741 ;; Paste
4742 (beginning-of-line 1)
4743 (org-back-over-empty-lines)
4744 (setq beg (point))
4745 (insert-before-markers txt)
4746 (unless (string-match "\n\\'" txt) (insert "\n"))
4747 (setq end (point))
4748 (goto-char beg)
4749 (skip-chars-forward " \t\n\r")
4750 (setq beg (point))
4751 ;; Shift if necessary
4752 (unless (= shift 0)
4753 (save-restriction
4754 (narrow-to-region beg end)
4755 (while (not (= shift 0))
4756 (org-map-region func (point-min) (point-max))
4757 (setq shift (+ delta shift)))
4758 (goto-char (point-min))))
4759 (when (interactive-p)
4760 (message "Clipboard pasted as level %d subtree" new-level))
4761 (if (and kill-ring
4762 (eq org-subtree-clip (current-kill 0))
4763 org-subtree-clip-folded)
4764 ;; The tree was folded before it was killed/copied
4765 (hide-subtree))))
4767 (defun org-kill-is-subtree-p (&optional txt)
4768 "Check if the current kill is an outline subtree, or a set of trees.
4769 Returns nil if kill does not start with a headline, or if the first
4770 headline level is not the largest headline level in the tree.
4771 So this will actually accept several entries of equal levels as well,
4772 which is OK for `org-paste-subtree'.
4773 If optional TXT is given, check this string instead of the current kill."
4774 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4775 (start-level (and kill
4776 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4777 org-outline-regexp "\\)")
4778 kill)
4779 (- (match-end 2) (match-beginning 2) 1)))
4780 (re (concat "^" org-outline-regexp))
4781 (start (1+ (match-beginning 2))))
4782 (if (not start-level)
4783 (progn
4784 nil) ;; does not even start with a heading
4785 (catch 'exit
4786 (while (setq start (string-match re kill (1+ start)))
4787 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4788 (throw 'exit nil)))
4789 t))))
4791 (defun org-narrow-to-subtree ()
4792 "Narrow buffer to the current subtree."
4793 (interactive)
4794 (save-excursion
4795 (save-match-data
4796 (narrow-to-region
4797 (progn (org-back-to-heading) (point))
4798 (progn (org-end-of-subtree t t) (point))))))
4801 ;;; Outline Sorting
4803 (defun org-sort (with-case)
4804 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4805 Optional argument WITH-CASE means sort case-sensitively."
4806 (interactive "P")
4807 (if (org-at-table-p)
4808 (org-call-with-arg 'org-table-sort-lines with-case)
4809 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4811 (defun org-sort-remove-invisible (s)
4812 (remove-text-properties 0 (length s) org-rm-props s)
4813 (while (string-match org-bracket-link-regexp s)
4814 (setq s (replace-match (if (match-end 2)
4815 (match-string 3 s)
4816 (match-string 1 s)) t t s)))
4819 (defvar org-priority-regexp) ; defined later in the file
4821 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4822 "Sort entries on a certain level of an outline tree.
4823 If there is an active region, the entries in the region are sorted.
4824 Else, if the cursor is before the first entry, sort the top-level items.
4825 Else, the children of the entry at point are sorted.
4827 Sorting can be alphabetically, numerically, and by date/time as given by
4828 the first time stamp in the entry. The command prompts for the sorting
4829 type unless it has been given to the function through the SORTING-TYPE
4830 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4831 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4832 called with point at the beginning of the record. It must return either
4833 a string or a number that should serve as the sorting key for that record.
4835 Comparing entries ignores case by default. However, with an optional argument
4836 WITH-CASE, the sorting considers case as well."
4837 (interactive "P")
4838 (let ((case-func (if with-case 'identity 'downcase))
4839 start beg end stars re re2
4840 txt what tmp plain-list-p)
4841 ;; Find beginning and end of region to sort
4842 (cond
4843 ((org-region-active-p)
4844 ;; we will sort the region
4845 (setq end (region-end)
4846 what "region")
4847 (goto-char (region-beginning))
4848 (if (not (org-on-heading-p)) (outline-next-heading))
4849 (setq start (point)))
4850 ((org-at-item-p)
4851 ;; we will sort this plain list
4852 (org-beginning-of-item-list) (setq start (point))
4853 (org-end-of-item-list) (setq end (point))
4854 (goto-char start)
4855 (setq plain-list-p t
4856 what "plain list"))
4857 ((or (org-on-heading-p)
4858 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4859 ;; we will sort the children of the current headline
4860 (org-back-to-heading)
4861 (setq start (point)
4862 end (progn (org-end-of-subtree t t)
4863 (org-back-over-empty-lines)
4864 (point))
4865 what "children")
4866 (goto-char start)
4867 (show-subtree)
4868 (outline-next-heading))
4870 ;; we will sort the top-level entries in this file
4871 (goto-char (point-min))
4872 (or (org-on-heading-p) (outline-next-heading))
4873 (setq start (point) end (point-max) what "top-level")
4874 (goto-char start)
4875 (show-all)))
4877 (setq beg (point))
4878 (if (>= beg end) (error "Nothing to sort"))
4880 (unless plain-list-p
4881 (looking-at "\\(\\*+\\)")
4882 (setq stars (match-string 1)
4883 re (concat "^" (regexp-quote stars) " +")
4884 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4885 txt (buffer-substring beg end))
4886 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4887 (if (and (not (equal stars "*")) (string-match re2 txt))
4888 (error "Region to sort contains a level above the first entry")))
4890 (unless sorting-type
4891 (message
4892 (if plain-list-p
4893 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4894 "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:")
4895 what)
4896 (setq sorting-type (read-char-exclusive))
4898 (and (= (downcase sorting-type) ?f)
4899 (setq getkey-func
4900 (completing-read "Sort using function: "
4901 obarray 'fboundp t nil nil))
4902 (setq getkey-func (intern getkey-func)))
4904 (and (= (downcase sorting-type) ?r)
4905 (setq property
4906 (completing-read "Property: "
4907 (mapcar 'list (org-buffer-property-keys t))
4908 nil t))))
4910 (message "Sorting entries...")
4912 (save-restriction
4913 (narrow-to-region start end)
4915 (let ((dcst (downcase sorting-type))
4916 (now (current-time)))
4917 (sort-subr
4918 (/= dcst sorting-type)
4919 ;; This function moves to the beginning character of the "record" to
4920 ;; be sorted.
4921 (if plain-list-p
4922 (lambda nil
4923 (if (org-at-item-p) t (goto-char (point-max))))
4924 (lambda nil
4925 (if (re-search-forward re nil t)
4926 (goto-char (match-beginning 0))
4927 (goto-char (point-max)))))
4928 ;; This function moves to the last character of the "record" being
4929 ;; sorted.
4930 (if plain-list-p
4931 'org-end-of-item
4932 (lambda nil
4933 (save-match-data
4934 (condition-case nil
4935 (outline-forward-same-level 1)
4936 (error
4937 (goto-char (point-max)))))))
4939 ;; This function returns the value that gets sorted against.
4940 (if plain-list-p
4941 (lambda nil
4942 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
4943 (cond
4944 ((= dcst ?n)
4945 (string-to-number (buffer-substring (match-end 0)
4946 (point-at-eol))))
4947 ((= dcst ?a)
4948 (buffer-substring (match-end 0) (point-at-eol)))
4949 ((= dcst ?t)
4950 (if (re-search-forward org-ts-regexp
4951 (point-at-eol) t)
4952 (org-time-string-to-time (match-string 0))
4953 now))
4954 ((= dcst ?f)
4955 (if getkey-func
4956 (progn
4957 (setq tmp (funcall getkey-func))
4958 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4959 tmp)
4960 (error "Invalid key function `%s'" getkey-func)))
4961 (t (error "Invalid sorting type `%c'" sorting-type)))))
4962 (lambda nil
4963 (cond
4964 ((= dcst ?n)
4965 (if (looking-at outline-regexp)
4966 (string-to-number (buffer-substring (match-end 0)
4967 (point-at-eol)))
4968 nil))
4969 ((= dcst ?a)
4970 (funcall case-func (buffer-substring (point-at-bol)
4971 (point-at-eol))))
4972 ((= dcst ?t)
4973 (if (re-search-forward org-ts-regexp
4974 (save-excursion
4975 (forward-line 2)
4976 (point)) t)
4977 (org-time-string-to-time (match-string 0))
4978 now))
4979 ((= dcst ?p)
4980 (if (re-search-forward org-priority-regexp (point-at-eol) t)
4981 (string-to-char (match-string 2))
4982 org-default-priority))
4983 ((= dcst ?r)
4984 (or (org-entry-get nil property) ""))
4985 ((= dcst ?o)
4986 (if (looking-at org-complex-heading-regexp)
4987 (- 9999 (length (member (match-string 2)
4988 org-todo-keywords-1)))))
4989 ((= dcst ?f)
4990 (if getkey-func
4991 (progn
4992 (setq tmp (funcall getkey-func))
4993 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4994 tmp)
4995 (error "Invalid key function `%s'" getkey-func)))
4996 (t (error "Invalid sorting type `%c'" sorting-type)))))
4998 (cond
4999 ((= dcst ?a) 'string<)
5000 ((= dcst ?t) 'time-less-p)
5001 (t nil)))))
5002 (message "Sorting entries...done")))
5004 (defun org-do-sort (table what &optional with-case sorting-type)
5005 "Sort TABLE of WHAT according to SORTING-TYPE.
5006 The user will be prompted for the SORTING-TYPE if the call to this
5007 function does not specify it. WHAT is only for the prompt, to indicate
5008 what is being sorted. The sorting key will be extracted from
5009 the car of the elements of the table.
5010 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5011 (unless sorting-type
5012 (message
5013 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5014 what)
5015 (setq sorting-type (read-char-exclusive)))
5016 (let ((dcst (downcase sorting-type))
5017 extractfun comparefun)
5018 ;; Define the appropriate functions
5019 (cond
5020 ((= dcst ?n)
5021 (setq extractfun 'string-to-number
5022 comparefun (if (= dcst sorting-type) '< '>)))
5023 ((= dcst ?a)
5024 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5025 (lambda(x) (downcase (org-sort-remove-invisible x))))
5026 comparefun (if (= dcst sorting-type)
5027 'string<
5028 (lambda (a b) (and (not (string< a b))
5029 (not (string= a b)))))))
5030 ((= dcst ?t)
5031 (setq extractfun
5032 (lambda (x)
5033 (if (string-match org-ts-regexp x)
5034 (time-to-seconds
5035 (org-time-string-to-time (match-string 0 x)))
5037 comparefun (if (= dcst sorting-type) '< '>)))
5038 (t (error "Invalid sorting type `%c'" sorting-type)))
5040 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5041 table)
5042 (lambda (a b) (funcall comparefun (car a) (car b))))))
5044 ;;;; Plain list items, including checkboxes
5046 ;;; Plain list items
5048 (defun org-at-item-p ()
5049 "Is point in a line starting a hand-formatted item?"
5050 (let ((llt org-plain-list-ordered-item-terminator))
5051 (save-excursion
5052 (goto-char (point-at-bol))
5053 (looking-at
5054 (cond
5055 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5056 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5057 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5058 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5060 (defun org-in-item-p ()
5061 "It the cursor inside a plain list item.
5062 Does not have to be the first line."
5063 (save-excursion
5064 (condition-case nil
5065 (progn
5066 (org-beginning-of-item)
5067 (org-at-item-p)
5069 (error nil))))
5071 (defun org-insert-item (&optional checkbox)
5072 "Insert a new item at the current level.
5073 Return t when things worked, nil when we are not in an item."
5074 (when (save-excursion
5075 (condition-case nil
5076 (progn
5077 (org-beginning-of-item)
5078 (org-at-item-p)
5079 (if (org-invisible-p) (error "Invisible item"))
5081 (error nil)))
5082 (let* ((bul (match-string 0))
5083 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5084 (match-end 0)))
5085 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5086 pos)
5087 (cond
5088 ((and (org-at-item-p) (<= (point) eow))
5089 ;; before the bullet
5090 (beginning-of-line 1)
5091 (open-line (if blank 2 1)))
5092 ((<= (point) eow)
5093 (beginning-of-line 1))
5095 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5096 (end-of-line 1)
5097 (delete-horizontal-space))
5098 (newline (if blank 2 1))))
5099 (insert bul (if checkbox "[ ]" ""))
5100 (just-one-space)
5101 (setq pos (point))
5102 (end-of-line 1)
5103 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5104 (org-maybe-renumber-ordered-list)
5105 (and checkbox (org-update-checkbox-count-maybe))
5108 ;;; Checkboxes
5110 (defun org-at-item-checkbox-p ()
5111 "Is point at a line starting a plain-list item with a checklet?"
5112 (and (org-at-item-p)
5113 (save-excursion
5114 (goto-char (match-end 0))
5115 (skip-chars-forward " \t")
5116 (looking-at "\\[[- X]\\]"))))
5118 (defun org-toggle-checkbox (&optional arg)
5119 "Toggle the checkbox in the current line."
5120 (interactive "P")
5121 (catch 'exit
5122 (let (beg end status (firstnew 'unknown))
5123 (cond
5124 ((org-region-active-p)
5125 (setq beg (region-beginning) end (region-end)))
5126 ((org-on-heading-p)
5127 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5128 ((org-at-item-checkbox-p)
5129 (let ((pos (point)))
5130 (replace-match
5131 (cond (arg "[-]")
5132 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5133 (t "[ ]"))
5134 t t)
5135 (goto-char pos))
5136 (throw 'exit t))
5137 (t (error "Not at a checkbox or heading, and no active region")))
5138 (save-excursion
5139 (goto-char beg)
5140 (while (< (point) end)
5141 (when (org-at-item-checkbox-p)
5142 (setq status (equal (match-string 0) "[X]"))
5143 (when (eq firstnew 'unknown)
5144 (setq firstnew (not status)))
5145 (replace-match
5146 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5147 (beginning-of-line 2)))))
5148 (org-update-checkbox-count-maybe))
5150 (defun org-update-checkbox-count-maybe ()
5151 "Update checkbox statistics unless turned off by user."
5152 (when org-provide-checkbox-statistics
5153 (org-update-checkbox-count)))
5155 (defun org-update-checkbox-count (&optional all)
5156 "Update the checkbox statistics in the current section.
5157 This will find all statistic cookies like [57%] and [6/12] and update them
5158 with the current numbers. With optional prefix argument ALL, do this for
5159 the whole buffer."
5160 (interactive "P")
5161 (save-excursion
5162 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5163 (beg (condition-case nil
5164 (progn (outline-back-to-heading) (point))
5165 (error (point-min))))
5166 (end (move-marker (make-marker)
5167 (progn (outline-next-heading) (point))))
5168 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5169 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5170 (re-find (concat re "\\|" re-box))
5171 beg-cookie end-cookie is-percent c-on c-off lim
5172 eline curr-ind next-ind continue-from startsearch
5173 (cstat 0)
5175 (when all
5176 (goto-char (point-min))
5177 (outline-next-heading)
5178 (setq beg (point) end (point-max)))
5179 (goto-char end)
5180 ;; find each statistic cookie
5181 (while (re-search-backward re-find beg t)
5182 (setq beg-cookie (match-beginning 1)
5183 end-cookie (match-end 1)
5184 cstat (+ cstat (if end-cookie 1 0))
5185 startsearch (point-at-eol)
5186 continue-from (point-at-bol)
5187 is-percent (match-beginning 2)
5188 lim (cond
5189 ((org-on-heading-p) (outline-next-heading) (point))
5190 ((org-at-item-p) (org-end-of-item) (point))
5191 (t nil))
5192 c-on 0
5193 c-off 0)
5194 (when lim
5195 ;; find first checkbox for this cookie and gather
5196 ;; statistics from all that are at this indentation level
5197 (goto-char startsearch)
5198 (if (re-search-forward re-box lim t)
5199 (progn
5200 (org-beginning-of-item)
5201 (setq curr-ind (org-get-indentation))
5202 (setq next-ind curr-ind)
5203 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5204 (save-excursion (end-of-line) (setq eline (point)))
5205 (if (re-search-forward re-box eline t)
5206 (if (member (match-string 2) '("[ ]" "[-]"))
5207 (setq c-off (1+ c-off))
5208 (setq c-on (1+ c-on))
5211 (org-end-of-item)
5212 (setq next-ind (org-get-indentation))
5214 (goto-char continue-from)
5215 ;; update cookie
5216 (when end-cookie
5217 (delete-region beg-cookie end-cookie)
5218 (goto-char beg-cookie)
5219 (insert
5220 (if is-percent
5221 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5222 (format "[%d/%d]" c-on (+ c-on c-off)))))
5223 ;; update items checkbox if it has one
5224 (when (org-at-item-p)
5225 (org-beginning-of-item)
5226 (when (and (> (+ c-on c-off) 0)
5227 (re-search-forward re-box (point-at-eol) t))
5228 (setq beg-cookie (match-beginning 2)
5229 end-cookie (match-end 2))
5230 (delete-region beg-cookie end-cookie)
5231 (goto-char beg-cookie)
5232 (cond ((= c-off 0) (insert "[X]"))
5233 ((= c-on 0) (insert "[ ]"))
5234 (t (insert "[-]")))
5236 (goto-char continue-from))
5237 (when (interactive-p)
5238 (message "Checkbox satistics updated %s (%d places)"
5239 (if all "in entire file" "in current outline entry") cstat)))))
5241 (defun org-get-checkbox-statistics-face ()
5242 "Select the face for checkbox statistics.
5243 The face will be `org-done' when all relevant boxes are checked. Otherwise
5244 it will be `org-todo'."
5245 (if (match-end 1)
5246 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5247 (if (and (> (match-end 2) (match-beginning 2))
5248 (equal (match-string 2) (match-string 3)))
5249 'org-done
5250 'org-todo)))
5252 (defun org-get-indentation (&optional line)
5253 "Get the indentation of the current line, interpreting tabs.
5254 When LINE is given, assume it represents a line and compute its indentation."
5255 (if line
5256 (if (string-match "^ *" (org-remove-tabs line))
5257 (match-end 0))
5258 (save-excursion
5259 (beginning-of-line 1)
5260 (skip-chars-forward " \t")
5261 (current-column))))
5263 (defun org-remove-tabs (s &optional width)
5264 "Replace tabulators in S with spaces.
5265 Assumes that s is a single line, starting in column 0."
5266 (setq width (or width tab-width))
5267 (while (string-match "\t" s)
5268 (setq s (replace-match
5269 (make-string
5270 (- (* width (/ (+ (match-beginning 0) width) width))
5271 (match-beginning 0)) ?\ )
5272 t t s)))
5275 (defun org-fix-indentation (line ind)
5276 "Fix indentation in LINE.
5277 IND is a cons cell with target and minimum indentation.
5278 If the current indenation in LINE is smaller than the minimum,
5279 leave it alone. If it is larger than ind, set it to the target."
5280 (let* ((l (org-remove-tabs line))
5281 (i (org-get-indentation l))
5282 (i1 (car ind)) (i2 (cdr ind)))
5283 (if (>= i i2) (setq l (substring line i2)))
5284 (if (> i1 0)
5285 (concat (make-string i1 ?\ ) l)
5286 l)))
5288 (defun org-beginning-of-item ()
5289 "Go to the beginning of the current hand-formatted item.
5290 If the cursor is not in an item, throw an error."
5291 (interactive)
5292 (let ((pos (point))
5293 (limit (save-excursion
5294 (condition-case nil
5295 (progn
5296 (org-back-to-heading)
5297 (beginning-of-line 2) (point))
5298 (error (point-min)))))
5299 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5300 ind ind1)
5301 (if (org-at-item-p)
5302 (beginning-of-line 1)
5303 (beginning-of-line 1)
5304 (skip-chars-forward " \t")
5305 (setq ind (current-column))
5306 (if (catch 'exit
5307 (while t
5308 (beginning-of-line 0)
5309 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5311 (if (looking-at "[ \t]*$")
5312 (setq ind1 ind-empty)
5313 (skip-chars-forward " \t")
5314 (setq ind1 (current-column)))
5315 (if (< ind1 ind)
5316 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5318 (goto-char pos)
5319 (error "Not in an item")))))
5321 (defun org-end-of-item ()
5322 "Go to the end of the current hand-formatted item.
5323 If the cursor is not in an item, throw an error."
5324 (interactive)
5325 (let* ((pos (point))
5326 ind1
5327 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5328 (limit (save-excursion (outline-next-heading) (point)))
5329 (ind (save-excursion
5330 (org-beginning-of-item)
5331 (skip-chars-forward " \t")
5332 (current-column)))
5333 (end (catch 'exit
5334 (while t
5335 (beginning-of-line 2)
5336 (if (eobp) (throw 'exit (point)))
5337 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5338 (if (looking-at "[ \t]*$")
5339 (setq ind1 ind-empty)
5340 (skip-chars-forward " \t")
5341 (setq ind1 (current-column)))
5342 (if (<= ind1 ind)
5343 (throw 'exit (point-at-bol)))))))
5344 (if end
5345 (goto-char end)
5346 (goto-char pos)
5347 (error "Not in an item"))))
5349 (defun org-next-item ()
5350 "Move to the beginning of the next item in the current plain list.
5351 Error if not at a plain list, or if this is the last item in the list."
5352 (interactive)
5353 (let (ind ind1 (pos (point)))
5354 (org-beginning-of-item)
5355 (setq ind (org-get-indentation))
5356 (org-end-of-item)
5357 (setq ind1 (org-get-indentation))
5358 (unless (and (org-at-item-p) (= ind ind1))
5359 (goto-char pos)
5360 (error "On last item"))))
5362 (defun org-previous-item ()
5363 "Move to the beginning of the previous item in the current plain list.
5364 Error if not at a plain list, or if this is the first item in the list."
5365 (interactive)
5366 (let (beg ind ind1 (pos (point)))
5367 (org-beginning-of-item)
5368 (setq beg (point))
5369 (setq ind (org-get-indentation))
5370 (goto-char beg)
5371 (catch 'exit
5372 (while t
5373 (beginning-of-line 0)
5374 (if (looking-at "[ \t]*$")
5376 (if (<= (setq ind1 (org-get-indentation)) ind)
5377 (throw 'exit t)))))
5378 (condition-case nil
5379 (if (or (not (org-at-item-p))
5380 (< ind1 (1- ind)))
5381 (error "")
5382 (org-beginning-of-item))
5383 (error (goto-char pos)
5384 (error "On first item")))))
5386 (defun org-first-list-item-p ()
5387 "Is this heading the item in a plain list?"
5388 (unless (org-at-item-p)
5389 (error "Not at a plain list item"))
5390 (org-beginning-of-item)
5391 (= (point) (save-excursion (org-beginning-of-item-list))))
5393 (defun org-move-item-down ()
5394 "Move the plain list item at point down, i.e. swap with following item.
5395 Subitems (items with larger indentation) are considered part of the item,
5396 so this really moves item trees."
5397 (interactive)
5398 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5399 (org-beginning-of-item)
5400 (setq beg0 (point))
5401 (save-excursion
5402 (setq ne-beg (org-back-over-empty-lines))
5403 (setq beg (point)))
5404 (goto-char beg0)
5405 (setq ind (org-get-indentation))
5406 (org-end-of-item)
5407 (setq end0 (point))
5408 (setq ind1 (org-get-indentation))
5409 (setq ne-end (org-back-over-empty-lines))
5410 (setq end (point))
5411 (goto-char beg0)
5412 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5413 ;; include less whitespace
5414 (save-excursion
5415 (goto-char beg)
5416 (forward-line (- ne-beg ne-end))
5417 (setq beg (point))))
5418 (goto-char end0)
5419 (if (and (org-at-item-p) (= ind ind1))
5420 (progn
5421 (org-end-of-item)
5422 (org-back-over-empty-lines)
5423 (setq txt (buffer-substring beg end))
5424 (save-excursion
5425 (delete-region beg end))
5426 (setq pos (point))
5427 (insert txt)
5428 (goto-char pos) (org-skip-whitespace)
5429 (org-maybe-renumber-ordered-list))
5430 (goto-char pos)
5431 (error "Cannot move this item further down"))))
5433 (defun org-move-item-up (arg)
5434 "Move the plain list item at point up, i.e. swap with previous item.
5435 Subitems (items with larger indentation) are considered part of the item,
5436 so this really moves item trees."
5437 (interactive "p")
5438 (let (beg beg0 end ind ind1 (pos (point)) txt
5439 ne-beg ne-ins ins-end)
5440 (org-beginning-of-item)
5441 (setq beg0 (point))
5442 (setq ind (org-get-indentation))
5443 (save-excursion
5444 (setq ne-beg (org-back-over-empty-lines))
5445 (setq beg (point)))
5446 (goto-char beg0)
5447 (org-end-of-item)
5448 (setq end (point))
5449 (goto-char beg0)
5450 (catch 'exit
5451 (while t
5452 (beginning-of-line 0)
5453 (if (looking-at "[ \t]*$")
5454 (if org-empty-line-terminates-plain-lists
5455 (progn
5456 (goto-char pos)
5457 (error "Cannot move this item further up"))
5458 nil)
5459 (if (<= (setq ind1 (org-get-indentation)) ind)
5460 (throw 'exit t)))))
5461 (condition-case nil
5462 (org-beginning-of-item)
5463 (error (goto-char beg)
5464 (error "Cannot move this item further up")))
5465 (setq ind1 (org-get-indentation))
5466 (if (and (org-at-item-p) (= ind ind1))
5467 (progn
5468 (setq ne-ins (org-back-over-empty-lines))
5469 (setq txt (buffer-substring beg end))
5470 (save-excursion
5471 (delete-region beg end))
5472 (setq pos (point))
5473 (insert txt)
5474 (setq ins-end (point))
5475 (goto-char pos) (org-skip-whitespace)
5477 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5478 ;; Move whitespace back to beginning
5479 (save-excursion
5480 (goto-char ins-end)
5481 (let ((kill-whole-line t))
5482 (kill-line (- ne-ins ne-beg)) (point)))
5483 (insert (make-string (- ne-ins ne-beg) ?\n)))
5485 (org-maybe-renumber-ordered-list))
5486 (goto-char pos)
5487 (error "Cannot move this item further up"))))
5489 (defun org-maybe-renumber-ordered-list ()
5490 "Renumber the ordered list at point if setup allows it.
5491 This tests the user option `org-auto-renumber-ordered-lists' before
5492 doing the renumbering."
5493 (interactive)
5494 (when (and org-auto-renumber-ordered-lists
5495 (org-at-item-p))
5496 (if (match-beginning 3)
5497 (org-renumber-ordered-list 1)
5498 (org-fix-bullet-type))))
5500 (defun org-maybe-renumber-ordered-list-safe ()
5501 (condition-case nil
5502 (save-excursion
5503 (org-maybe-renumber-ordered-list))
5504 (error nil)))
5506 (defun org-cycle-list-bullet (&optional which)
5507 "Cycle through the different itemize/enumerate bullets.
5508 This cycle the entire list level through the sequence:
5510 `-' -> `+' -> `*' -> `1.' -> `1)'
5512 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5513 0 meand `-', 1 means `+' etc."
5514 (interactive "P")
5515 (org-preserve-lc
5516 (org-beginning-of-item-list)
5517 (org-at-item-p)
5518 (beginning-of-line 1)
5519 (let ((current (match-string 0))
5520 (prevp (eq which 'previous))
5521 new)
5522 (setq new (cond
5523 ((and (numberp which)
5524 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5525 ((string-match "-" current) (if prevp "1)" "+"))
5526 ((string-match "\\+" current)
5527 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5528 ((string-match "\\*" current) (if prevp "+" "1."))
5529 ((string-match "\\." current) (if prevp "*" "1)"))
5530 ((string-match ")" current) (if prevp "1." "-"))
5531 (t (error "This should not happen"))))
5532 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5533 (org-fix-bullet-type)
5534 (org-maybe-renumber-ordered-list))))
5536 (defun org-get-string-indentation (s)
5537 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5538 (let ((n -1) (i 0) (w tab-width) c)
5539 (catch 'exit
5540 (while (< (setq n (1+ n)) (length s))
5541 (setq c (aref s n))
5542 (cond ((= c ?\ ) (setq i (1+ i)))
5543 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5544 (t (throw 'exit t)))))
5547 (defun org-renumber-ordered-list (arg)
5548 "Renumber an ordered plain list.
5549 Cursor needs to be in the first line of an item, the line that starts
5550 with something like \"1.\" or \"2)\"."
5551 (interactive "p")
5552 (unless (and (org-at-item-p)
5553 (match-beginning 3))
5554 (error "This is not an ordered list"))
5555 (let ((line (org-current-line))
5556 (col (current-column))
5557 (ind (org-get-string-indentation
5558 (buffer-substring (point-at-bol) (match-beginning 3))))
5559 ;; (term (substring (match-string 3) -1))
5560 ind1 (n (1- arg))
5561 fmt)
5562 ;; find where this list begins
5563 (org-beginning-of-item-list)
5564 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5565 (setq fmt (concat "%d" (match-string 1)))
5566 (beginning-of-line 0)
5567 ;; walk forward and replace these numbers
5568 (catch 'exit
5569 (while t
5570 (catch 'next
5571 (beginning-of-line 2)
5572 (if (eobp) (throw 'exit nil))
5573 (if (looking-at "[ \t]*$") (throw 'next nil))
5574 (skip-chars-forward " \t") (setq ind1 (current-column))
5575 (if (> ind1 ind) (throw 'next t))
5576 (if (< ind1 ind) (throw 'exit t))
5577 (if (not (org-at-item-p)) (throw 'exit nil))
5578 (delete-region (match-beginning 2) (match-end 2))
5579 (goto-char (match-beginning 2))
5580 (insert (format fmt (setq n (1+ n)))))))
5581 (goto-line line)
5582 (move-to-column col)))
5584 (defun org-fix-bullet-type ()
5585 "Make sure all items in this list have the same bullet as the firsst item."
5586 (interactive)
5587 (unless (org-at-item-p) (error "This is not a list"))
5588 (let ((line (org-current-line))
5589 (col (current-column))
5590 (ind (current-indentation))
5591 ind1 bullet)
5592 ;; find where this list begins
5593 (org-beginning-of-item-list)
5594 (beginning-of-line 1)
5595 ;; find out what the bullet type is
5596 (looking-at "[ \t]*\\(\\S-+\\)")
5597 (setq bullet (match-string 1))
5598 ;; walk forward and replace these numbers
5599 (beginning-of-line 0)
5600 (catch 'exit
5601 (while t
5602 (catch 'next
5603 (beginning-of-line 2)
5604 (if (eobp) (throw 'exit nil))
5605 (if (looking-at "[ \t]*$") (throw 'next nil))
5606 (skip-chars-forward " \t") (setq ind1 (current-column))
5607 (if (> ind1 ind) (throw 'next t))
5608 (if (< ind1 ind) (throw 'exit t))
5609 (if (not (org-at-item-p)) (throw 'exit nil))
5610 (skip-chars-forward " \t")
5611 (looking-at "\\S-+")
5612 (replace-match bullet))))
5613 (goto-line line)
5614 (move-to-column col)
5615 (if (string-match "[0-9]" bullet)
5616 (org-renumber-ordered-list 1))))
5618 (defun org-beginning-of-item-list ()
5619 "Go to the beginning of the current item list.
5620 I.e. to the first item in this list."
5621 (interactive)
5622 (org-beginning-of-item)
5623 (let ((pos (point-at-bol))
5624 (ind (org-get-indentation))
5625 ind1)
5626 ;; find where this list begins
5627 (catch 'exit
5628 (while t
5629 (catch 'next
5630 (beginning-of-line 0)
5631 (if (looking-at "[ \t]*$")
5632 (throw (if (bobp) 'exit 'next) t))
5633 (skip-chars-forward " \t") (setq ind1 (current-column))
5634 (if (or (< ind1 ind)
5635 (and (= ind1 ind)
5636 (not (org-at-item-p)))
5637 (bobp))
5638 (throw 'exit t)
5639 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5640 (goto-char pos)))
5643 (defun org-end-of-item-list ()
5644 "Go to the end of the current item list.
5645 I.e. to the text after the last item."
5646 (interactive)
5647 (org-beginning-of-item)
5648 (let ((pos (point-at-bol))
5649 (ind (org-get-indentation))
5650 ind1)
5651 ;; find where this list begins
5652 (catch 'exit
5653 (while t
5654 (catch 'next
5655 (beginning-of-line 2)
5656 (if (looking-at "[ \t]*$")
5657 (throw (if (eobp) 'exit 'next) t))
5658 (skip-chars-forward " \t") (setq ind1 (current-column))
5659 (if (or (< ind1 ind)
5660 (and (= ind1 ind)
5661 (not (org-at-item-p)))
5662 (eobp))
5663 (progn
5664 (setq pos (point-at-bol))
5665 (throw 'exit t))))))
5666 (goto-char pos)))
5669 (defvar org-last-indent-begin-marker (make-marker))
5670 (defvar org-last-indent-end-marker (make-marker))
5672 (defun org-outdent-item (arg)
5673 "Outdent a local list item."
5674 (interactive "p")
5675 (org-indent-item (- arg)))
5677 (defun org-indent-item (arg)
5678 "Indent a local list item."
5679 (interactive "p")
5680 (unless (org-at-item-p)
5681 (error "Not on an item"))
5682 (save-excursion
5683 (let (beg end ind ind1 tmp delta ind-down ind-up)
5684 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5685 (setq beg org-last-indent-begin-marker
5686 end org-last-indent-end-marker)
5687 (org-beginning-of-item)
5688 (setq beg (move-marker org-last-indent-begin-marker (point)))
5689 (org-end-of-item)
5690 (setq end (move-marker org-last-indent-end-marker (point))))
5691 (goto-char beg)
5692 (setq tmp (org-item-indent-positions)
5693 ind (car tmp)
5694 ind-down (nth 2 tmp)
5695 ind-up (nth 1 tmp)
5696 delta (if (> arg 0)
5697 (if ind-down (- ind-down ind) 2)
5698 (if ind-up (- ind-up ind) -2)))
5699 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5700 (while (< (point) end)
5701 (beginning-of-line 1)
5702 (skip-chars-forward " \t") (setq ind1 (current-column))
5703 (delete-region (point-at-bol) (point))
5704 (or (eolp) (indent-to-column (+ ind1 delta)))
5705 (beginning-of-line 2))))
5706 (org-fix-bullet-type)
5707 (org-maybe-renumber-ordered-list-safe)
5708 (save-excursion
5709 (beginning-of-line 0)
5710 (condition-case nil (org-beginning-of-item) (error nil))
5711 (org-maybe-renumber-ordered-list-safe)))
5713 (defun org-item-indent-positions ()
5714 "Return indentation for plain list items.
5715 This returns a list with three values: The current indentation, the
5716 parent indentation and the indentation a child should habe.
5717 Assumes cursor in item line."
5718 (let* ((bolpos (point-at-bol))
5719 (ind (org-get-indentation))
5720 ind-down ind-up pos)
5721 (save-excursion
5722 (org-beginning-of-item-list)
5723 (skip-chars-backward "\n\r \t")
5724 (when (org-in-item-p)
5725 (org-beginning-of-item)
5726 (setq ind-up (org-get-indentation))))
5727 (setq pos (point))
5728 (save-excursion
5729 (cond
5730 ((and (condition-case nil (progn (org-previous-item) t)
5731 (error nil))
5732 (or (forward-char 1) t)
5733 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5734 (setq ind-down (org-get-indentation)))
5735 ((and (goto-char pos)
5736 (org-at-item-p))
5737 (goto-char (match-end 0))
5738 (skip-chars-forward " \t")
5739 (setq ind-down (current-column)))))
5740 (list ind ind-up ind-down)))
5742 ;;; The orgstruct minor mode
5744 ;; Define a minor mode which can be used in other modes in order to
5745 ;; integrate the org-mode structure editing commands.
5747 ;; This is really a hack, because the org-mode structure commands use
5748 ;; keys which normally belong to the major mode. Here is how it
5749 ;; works: The minor mode defines all the keys necessary to operate the
5750 ;; structure commands, but wraps the commands into a function which
5751 ;; tests if the cursor is currently at a headline or a plain list
5752 ;; item. If that is the case, the structure command is used,
5753 ;; temporarily setting many Org-mode variables like regular
5754 ;; expressions for filling etc. However, when any of those keys is
5755 ;; used at a different location, function uses `key-binding' to look
5756 ;; up if the key has an associated command in another currently active
5757 ;; keymap (minor modes, major mode, global), and executes that
5758 ;; command. There might be problems if any of the keys is otherwise
5759 ;; used as a prefix key.
5761 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5762 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5763 ;; addresses this by checking explicitly for both bindings.
5765 (defvar orgstruct-mode-map (make-sparse-keymap)
5766 "Keymap for the minor `orgstruct-mode'.")
5768 (defvar org-local-vars nil
5769 "List of local variables, for use by `orgstruct-mode'")
5771 ;;;###autoload
5772 (define-minor-mode orgstruct-mode
5773 "Toggle the minor more `orgstruct-mode'.
5774 This mode is for using Org-mode structure commands in other modes.
5775 The following key behave as if Org-mode was active, if the cursor
5776 is on a headline, or on a plain list item (both in the definition
5777 of Org-mode).
5779 M-up Move entry/item up
5780 M-down Move entry/item down
5781 M-left Promote
5782 M-right Demote
5783 M-S-up Move entry/item up
5784 M-S-down Move entry/item down
5785 M-S-left Promote subtree
5786 M-S-right Demote subtree
5787 M-q Fill paragraph and items like in Org-mode
5788 C-c ^ Sort entries
5789 C-c - Cycle list bullet
5790 TAB Cycle item visibility
5791 M-RET Insert new heading/item
5792 S-M-RET Insert new TODO heading / Chekbox item
5793 C-c C-c Set tags / toggle checkbox"
5794 nil " OrgStruct" nil
5795 (org-load-modules-maybe)
5796 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5798 ;;;###autoload
5799 (defun turn-on-orgstruct ()
5800 "Unconditionally turn on `orgstruct-mode'."
5801 (orgstruct-mode 1))
5803 ;;;###autoload
5804 (defun turn-on-orgstruct++ ()
5805 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5806 In addition to setting orgstruct-mode, this also exports all indentation and
5807 autofilling variables from org-mode into the buffer. Note that turning
5808 off orgstruct-mode will *not* remove these additional settings."
5809 (orgstruct-mode 1)
5810 (let (var val)
5811 (mapc
5812 (lambda (x)
5813 (when (string-match
5814 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5815 (symbol-name (car x)))
5816 (setq var (car x) val (nth 1 x))
5817 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5818 org-local-vars)))
5820 (defun orgstruct-error ()
5821 "Error when there is no default binding for a structure key."
5822 (interactive)
5823 (error "This key has no function outside structure elements"))
5825 (defun orgstruct-setup ()
5826 "Setup orgstruct keymaps."
5827 (let ((nfunc 0)
5828 (bindings
5829 (list
5830 '([(meta up)] org-metaup)
5831 '([(meta down)] org-metadown)
5832 '([(meta left)] org-metaleft)
5833 '([(meta right)] org-metaright)
5834 '([(meta shift up)] org-shiftmetaup)
5835 '([(meta shift down)] org-shiftmetadown)
5836 '([(meta shift left)] org-shiftmetaleft)
5837 '([(meta shift right)] org-shiftmetaright)
5838 '([(shift up)] org-shiftup)
5839 '([(shift down)] org-shiftdown)
5840 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5841 '("\M-q" fill-paragraph)
5842 '("\C-c^" org-sort)
5843 '("\C-c-" org-cycle-list-bullet)))
5844 elt key fun cmd)
5845 (while (setq elt (pop bindings))
5846 (setq nfunc (1+ nfunc))
5847 (setq key (org-key (car elt))
5848 fun (nth 1 elt)
5849 cmd (orgstruct-make-binding fun nfunc key))
5850 (org-defkey orgstruct-mode-map key cmd))
5852 ;; Special treatment needed for TAB and RET
5853 (org-defkey orgstruct-mode-map [(tab)]
5854 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5855 (org-defkey orgstruct-mode-map "\C-i"
5856 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5858 (org-defkey orgstruct-mode-map "\M-\C-m"
5859 (orgstruct-make-binding 'org-insert-heading 105
5860 "\M-\C-m" [(meta return)]))
5861 (org-defkey orgstruct-mode-map [(meta return)]
5862 (orgstruct-make-binding 'org-insert-heading 106
5863 [(meta return)] "\M-\C-m"))
5865 (org-defkey orgstruct-mode-map [(shift meta return)]
5866 (orgstruct-make-binding 'org-insert-todo-heading 107
5867 [(meta return)] "\M-\C-m"))
5869 (unless org-local-vars
5870 (setq org-local-vars (org-get-local-variables)))
5874 (defun orgstruct-make-binding (fun n &rest keys)
5875 "Create a function for binding in the structure minor mode.
5876 FUN is the command to call inside a table. N is used to create a unique
5877 command name. KEYS are keys that should be checked in for a command
5878 to execute outside of tables."
5879 (eval
5880 (list 'defun
5881 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5882 '(arg)
5883 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5884 "Outside of structure, run the binding of `"
5885 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5886 "'.")
5887 '(interactive "p")
5888 (list 'if
5889 '(org-context-p 'headline 'item)
5890 (list 'org-run-like-in-org-mode (list 'quote fun))
5891 (list 'let '(orgstruct-mode)
5892 (list 'call-interactively
5893 (append '(or)
5894 (mapcar (lambda (k)
5895 (list 'key-binding k))
5896 keys)
5897 '('orgstruct-error))))))))
5899 (defun org-context-p (&rest contexts)
5900 "Check if local context is and of CONTEXTS.
5901 Possible values in the list of contexts are `table', `headline', and `item'."
5902 (let ((pos (point)))
5903 (goto-char (point-at-bol))
5904 (prog1 (or (and (memq 'table contexts)
5905 (looking-at "[ \t]*|"))
5906 (and (memq 'headline contexts)
5907 (looking-at "\\*+"))
5908 (and (memq 'item contexts)
5909 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5910 (goto-char pos))))
5912 (defun org-get-local-variables ()
5913 "Return a list of all local variables in an org-mode buffer."
5914 (let (varlist)
5915 (with-current-buffer (get-buffer-create "*Org tmp*")
5916 (erase-buffer)
5917 (org-mode)
5918 (setq varlist (buffer-local-variables)))
5919 (kill-buffer "*Org tmp*")
5920 (delq nil
5921 (mapcar
5922 (lambda (x)
5923 (setq x
5924 (if (symbolp x)
5925 (list x)
5926 (list (car x) (list 'quote (cdr x)))))
5927 (if (string-match
5928 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5929 (symbol-name (car x)))
5930 x nil))
5931 varlist))))
5933 ;;;###autoload
5934 (defun org-run-like-in-org-mode (cmd)
5935 (org-load-modules-maybe)
5936 (unless org-local-vars
5937 (setq org-local-vars (org-get-local-variables)))
5938 (eval (list 'let org-local-vars
5939 (list 'call-interactively (list 'quote cmd)))))
5941 ;;;; Archiving
5943 (defun org-get-category (&optional pos)
5944 "Get the category applying to position POS."
5945 (get-text-property (or pos (point)) 'org-category))
5947 (defun org-refresh-category-properties ()
5948 "Refresh category text properties in the buffer."
5949 (let ((def-cat (cond
5950 ((null org-category)
5951 (if buffer-file-name
5952 (file-name-sans-extension
5953 (file-name-nondirectory buffer-file-name))
5954 "???"))
5955 ((symbolp org-category) (symbol-name org-category))
5956 (t org-category)))
5957 beg end cat pos optionp)
5958 (org-unmodified
5959 (save-excursion
5960 (save-restriction
5961 (widen)
5962 (goto-char (point-min))
5963 (put-text-property (point) (point-max) 'org-category def-cat)
5964 (while (re-search-forward
5965 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5966 (setq pos (match-end 0)
5967 optionp (equal (char-after (match-beginning 0)) ?#)
5968 cat (org-trim (match-string 2)))
5969 (if optionp
5970 (setq beg (point-at-bol) end (point-max))
5971 (org-back-to-heading t)
5972 (setq beg (point) end (org-end-of-subtree t t)))
5973 (put-text-property beg end 'org-category cat)
5974 (goto-char pos)))))))
5977 ;;;; Link Stuff
5979 ;;; Link abbreviations
5981 (defun org-link-expand-abbrev (link)
5982 "Apply replacements as defined in `org-link-abbrev-alist."
5983 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5984 (let* ((key (match-string 1 link))
5985 (as (or (assoc key org-link-abbrev-alist-local)
5986 (assoc key org-link-abbrev-alist)))
5987 (tag (and (match-end 2) (match-string 3 link)))
5988 rpl)
5989 (if (not as)
5990 link
5991 (setq rpl (cdr as))
5992 (cond
5993 ((symbolp rpl) (funcall rpl tag))
5994 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5995 (t (concat rpl tag)))))
5996 link))
5998 ;;; Storing and inserting links
6000 (defvar org-insert-link-history nil
6001 "Minibuffer history for links inserted with `org-insert-link'.")
6003 (defvar org-stored-links nil
6004 "Contains the links stored with `org-store-link'.")
6006 (defvar org-store-link-plist nil
6007 "Plist with info about the most recently link created with `org-store-link'.")
6009 (defvar org-link-protocols nil
6010 "Link protocols added to Org-mode using `org-add-link-type'.")
6012 (defvar org-store-link-functions nil
6013 "List of functions that are called to create and store a link.
6014 Each function will be called in turn until one returns a non-nil
6015 value. Each function should check if it is responsible for creating
6016 this link (for example by looking at the major mode).
6017 If not, it must exit and return nil.
6018 If yes, it should return a non-nil value after a calling
6019 `org-store-link-props' with a list of properties and values.
6020 Special properties are:
6022 :type The link prefix. like \"http\". This must be given.
6023 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6024 This is obligatory as well.
6025 :description Optional default description for the second pair
6026 of brackets in an Org-mode link. The user can still change
6027 this when inserting this link into an Org-mode buffer.
6029 In addition to these, any additional properties can be specified
6030 and then used in remember templates.")
6032 (defun org-add-link-type (type &optional follow export)
6033 "Add TYPE to the list of `org-link-types'.
6034 Re-compute all regular expressions depending on `org-link-types'
6036 FOLLOW and EXPORT are two functions.
6038 FOLLOW should take the link path as the single argument and do whatever
6039 is necessary to follow the link, for example find a file or display
6040 a mail message.
6042 EXPORT should format the link path for export to one of the export formats.
6043 It should be a function accepting three arguments:
6045 path the path of the link, the text after the prefix (like \"http:\")
6046 desc the description of the link, if any, nil if there was no descripton
6047 format the export format, a symbol like `html' or `latex'.
6049 The function may use the FORMAT information to return different values
6050 depending on the format. The return value will be put literally into
6051 the exported file.
6052 Org-mode has a built-in default for exporting links. If you are happy with
6053 this default, there is no need to define an export function for the link
6054 type. For a simple example of an export function, see `org-bbdb.el'."
6055 (add-to-list 'org-link-types type t)
6056 (org-make-link-regexps)
6057 (if (assoc type org-link-protocols)
6058 (setcdr (assoc type org-link-protocols) (list follow export))
6059 (push (list type follow export) org-link-protocols)))
6062 ;;;###autoload
6063 (defun org-store-link (arg)
6064 "\\<org-mode-map>Store an org-link to the current location.
6065 This link is added to `org-stored-links' and can later be inserted
6066 into an org-buffer with \\[org-insert-link].
6068 For some link types, a prefix arg is interpreted:
6069 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6070 For file links, arg negates `org-context-in-file-links'."
6071 (interactive "P")
6072 (org-load-modules-maybe)
6073 (setq org-store-link-plist nil) ; reset
6074 (let (link cpltxt desc description search txt)
6075 (cond
6077 ((run-hook-with-args-until-success 'org-store-link-functions)
6078 (setq link (plist-get org-store-link-plist :link)
6079 desc (or (plist-get org-store-link-plist :description) link)))
6081 ((eq major-mode 'calendar-mode)
6082 (let ((cd (calendar-cursor-to-date)))
6083 (setq link
6084 (format-time-string
6085 (car org-time-stamp-formats)
6086 (apply 'encode-time
6087 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6088 nil nil nil))))
6089 (org-store-link-props :type "calendar" :date cd)))
6091 ((eq major-mode 'w3-mode)
6092 (setq cpltxt (url-view-url t)
6093 link (org-make-link cpltxt))
6094 (org-store-link-props :type "w3" :url (url-view-url t)))
6096 ((eq major-mode 'w3m-mode)
6097 (setq cpltxt (or w3m-current-title w3m-current-url)
6098 link (org-make-link w3m-current-url))
6099 (org-store-link-props :type "w3m" :url (url-view-url t)))
6101 ((setq search (run-hook-with-args-until-success
6102 'org-create-file-search-functions))
6103 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6104 "::" search))
6105 (setq cpltxt (or description link)))
6107 ((eq major-mode 'image-mode)
6108 (setq cpltxt (concat "file:"
6109 (abbreviate-file-name buffer-file-name))
6110 link (org-make-link cpltxt))
6111 (org-store-link-props :type "image" :file buffer-file-name))
6113 ((eq major-mode 'dired-mode)
6114 ;; link to the file in the current line
6115 (setq cpltxt (concat "file:"
6116 (abbreviate-file-name
6117 (expand-file-name
6118 (dired-get-filename nil t))))
6119 link (org-make-link cpltxt)))
6121 ((and buffer-file-name (org-mode-p))
6122 ;; Just link to current headline
6123 (setq cpltxt (concat "file:"
6124 (abbreviate-file-name buffer-file-name)))
6125 ;; Add a context search string
6126 (when (org-xor org-context-in-file-links arg)
6127 ;; Check if we are on a target
6128 (if (org-in-regexp "<<\\(.*?\\)>>")
6129 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6130 (setq txt (cond
6131 ((org-on-heading-p) nil)
6132 ((org-region-active-p)
6133 (buffer-substring (region-beginning) (region-end)))
6134 (t nil)))
6135 (when (or (null txt) (string-match "\\S-" txt))
6136 (setq cpltxt
6137 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6138 desc "NONE"))))
6139 (if (string-match "::\\'" cpltxt)
6140 (setq cpltxt (substring cpltxt 0 -2)))
6141 (setq link (org-make-link cpltxt)))
6143 ((buffer-file-name (buffer-base-buffer))
6144 ;; Just link to this file here.
6145 (setq cpltxt (concat "file:"
6146 (abbreviate-file-name
6147 (buffer-file-name (buffer-base-buffer)))))
6148 ;; Add a context string
6149 (when (org-xor org-context-in-file-links arg)
6150 (setq txt (if (org-region-active-p)
6151 (buffer-substring (region-beginning) (region-end))
6152 (buffer-substring (point-at-bol) (point-at-eol))))
6153 ;; Only use search option if there is some text.
6154 (when (string-match "\\S-" txt)
6155 (setq cpltxt
6156 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6157 desc "NONE")))
6158 (setq link (org-make-link cpltxt)))
6160 ((interactive-p)
6161 (error "Cannot link to a buffer which is not visiting a file"))
6163 (t (setq link nil)))
6165 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6166 (setq link (or link cpltxt)
6167 desc (or desc cpltxt))
6168 (if (equal desc "NONE") (setq desc nil))
6170 (if (and (interactive-p) link)
6171 (progn
6172 (setq org-stored-links
6173 (cons (list link desc) org-stored-links))
6174 (message "Stored: %s" (or desc link)))
6175 (and link (org-make-link-string link desc)))))
6177 (defun org-store-link-props (&rest plist)
6178 "Store link properties, extract names and addresses."
6179 (let (x adr)
6180 (when (setq x (plist-get plist :from))
6181 (setq adr (mail-extract-address-components x))
6182 (plist-put plist :fromname (car adr))
6183 (plist-put plist :fromaddress (nth 1 adr)))
6184 (when (setq x (plist-get plist :to))
6185 (setq adr (mail-extract-address-components x))
6186 (plist-put plist :toname (car adr))
6187 (plist-put plist :toaddress (nth 1 adr))))
6188 (let ((from (plist-get plist :from))
6189 (to (plist-get plist :to)))
6190 (when (and from to org-from-is-user-regexp)
6191 (plist-put plist :fromto
6192 (if (string-match org-from-is-user-regexp from)
6193 (concat "to %t")
6194 (concat "from %f")))))
6195 (setq org-store-link-plist plist))
6197 (defun org-add-link-props (&rest plist)
6198 "Add these properties to the link property list."
6199 (let (key value)
6200 (while plist
6201 (setq key (pop plist) value (pop plist))
6202 (setq org-store-link-plist
6203 (plist-put org-store-link-plist key value)))))
6205 (defun org-email-link-description (&optional fmt)
6206 "Return the description part of an email link.
6207 This takes information from `org-store-link-plist' and formats it
6208 according to FMT (default from `org-email-link-description-format')."
6209 (setq fmt (or fmt org-email-link-description-format))
6210 (let* ((p org-store-link-plist)
6211 (to (plist-get p :toaddress))
6212 (from (plist-get p :fromaddress))
6213 (table
6214 (list
6215 (cons "%c" (plist-get p :fromto))
6216 (cons "%F" (plist-get p :from))
6217 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6218 (cons "%T" (plist-get p :to))
6219 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6220 (cons "%s" (plist-get p :subject))
6221 (cons "%m" (plist-get p :message-id)))))
6222 (when (string-match "%c" fmt)
6223 ;; Check if the user wrote this message
6224 (if (and org-from-is-user-regexp from to
6225 (save-match-data (string-match org-from-is-user-regexp from)))
6226 (setq fmt (replace-match "to %t" t t fmt))
6227 (setq fmt (replace-match "from %f" t t fmt))))
6228 (org-replace-escapes fmt table)))
6230 (defun org-make-org-heading-search-string (&optional string heading)
6231 "Make search string for STRING or current headline."
6232 (interactive)
6233 (let ((s (or string (org-get-heading))))
6234 (unless (and string (not heading))
6235 ;; We are using a headline, clean up garbage in there.
6236 (if (string-match org-todo-regexp s)
6237 (setq s (replace-match "" t t s)))
6238 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6239 (setq s (replace-match "" t t s)))
6240 (setq s (org-trim s))
6241 (if (string-match (concat "^\\(" org-quote-string "\\|"
6242 org-comment-string "\\)") s)
6243 (setq s (replace-match "" t t s)))
6244 (while (string-match org-ts-regexp s)
6245 (setq s (replace-match "" t t s))))
6246 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6247 (setq s (replace-match " " t t s)))
6248 (or string (setq s (concat "*" s))) ; Add * for headlines
6249 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6251 (defun org-make-link (&rest strings)
6252 "Concatenate STRINGS."
6253 (apply 'concat strings))
6255 (defun org-make-link-string (link &optional description)
6256 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6257 (unless (string-match "\\S-" link)
6258 (error "Empty link"))
6259 (when (stringp description)
6260 ;; Remove brackets from the description, they are fatal.
6261 (while (string-match "\\[" description)
6262 (setq description (replace-match "{" t t description)))
6263 (while (string-match "\\]" description)
6264 (setq description (replace-match "}" t t description))))
6265 (when (equal (org-link-escape link) description)
6266 ;; No description needed, it is identical
6267 (setq description nil))
6268 (when (and (not description)
6269 (not (equal link (org-link-escape link))))
6270 (setq description link))
6271 (concat "[[" (org-link-escape link) "]"
6272 (if description (concat "[" description "]") "")
6273 "]"))
6275 (defconst org-link-escape-chars
6276 '((?\ . "%20")
6277 (?\[ . "%5B")
6278 (?\] . "%5D")
6279 (?\340 . "%E0") ; `a
6280 (?\342 . "%E2") ; ^a
6281 (?\347 . "%E7") ; ,c
6282 (?\350 . "%E8") ; `e
6283 (?\351 . "%E9") ; 'e
6284 (?\352 . "%EA") ; ^e
6285 (?\356 . "%EE") ; ^i
6286 (?\364 . "%F4") ; ^o
6287 (?\371 . "%F9") ; `u
6288 (?\373 . "%FB") ; ^u
6289 (?\; . "%3B")
6290 (?? . "%3F")
6291 (?= . "%3D")
6292 (?+ . "%2B")
6294 "Association list of escapes for some characters problematic in links.
6295 This is the list that is used for internal purposes.")
6297 (defconst org-link-escape-chars-browser
6298 '((?\ . "%20")) ; 32 for the SPC char
6299 "Association list of escapes for some characters problematic in links.
6300 This is the list that is used before handing over to the browser.")
6302 (defun org-link-escape (text &optional table)
6303 "Escape charaters in TEXT that are problematic for links."
6304 (setq table (or table org-link-escape-chars))
6305 (when text
6306 (let ((re (mapconcat (lambda (x) (regexp-quote
6307 (char-to-string (car x))))
6308 table "\\|")))
6309 (while (string-match re text)
6310 (setq text
6311 (replace-match
6312 (cdr (assoc (string-to-char (match-string 0 text))
6313 table))
6314 t t text)))
6315 text)))
6317 (defun org-link-unescape (text &optional table)
6318 "Reverse the action of `org-link-escape'."
6319 (setq table (or table org-link-escape-chars))
6320 (when text
6321 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6322 table "\\|")))
6323 (while (string-match re text)
6324 (setq text
6325 (replace-match
6326 (char-to-string (car (rassoc (match-string 0 text) table)))
6327 t t text)))
6328 text)))
6330 (defun org-xor (a b)
6331 "Exclusive or."
6332 (if a (not b) b))
6334 (defun org-get-header (header)
6335 "Find a header field in the current buffer."
6336 (save-excursion
6337 (goto-char (point-min))
6338 (let ((case-fold-search t) s)
6339 (cond
6340 ((eq header 'from)
6341 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6342 (setq s (match-string 1)))
6343 (while (string-match "\"" s)
6344 (setq s (replace-match "" t t s)))
6345 (if (string-match "[<(].*" s)
6346 (setq s (replace-match "" t t s))))
6347 ((eq header 'message-id)
6348 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6349 (setq s (match-string 1))))
6350 ((eq header 'subject)
6351 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6352 (setq s (match-string 1)))))
6353 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6354 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6355 s)))
6358 (defun org-fixup-message-id-for-http (s)
6359 "Replace special characters in a message id, so it can be used in an http query."
6360 (while (string-match "<" s)
6361 (setq s (replace-match "%3C" t t s)))
6362 (while (string-match ">" s)
6363 (setq s (replace-match "%3E" t t s)))
6364 (while (string-match "@" s)
6365 (setq s (replace-match "%40" t t s)))
6368 ;;;###autoload
6369 (defun org-insert-link-global ()
6370 "Insert a link like Org-mode does.
6371 This command can be called in any mode to insert a link in Org-mode syntax."
6372 (interactive)
6373 (org-load-modules-maybe)
6374 (org-run-like-in-org-mode 'org-insert-link))
6376 (defun org-insert-link (&optional complete-file link-location)
6377 "Insert a link. At the prompt, enter the link.
6379 Completion can be used to select a link previously stored with
6380 `org-store-link'. When the empty string is entered (i.e. if you just
6381 press RET at the prompt), the link defaults to the most recently
6382 stored link. As SPC triggers completion in the minibuffer, you need to
6383 use M-SPC or C-q SPC to force the insertion of a space character.
6385 You will also be prompted for a description, and if one is given, it will
6386 be displayed in the buffer instead of the link.
6388 If there is already a link at point, this command will allow you to edit link
6389 and description parts.
6391 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6392 be selected using completion. The path to the file will be relative to the
6393 current directory if the file is in the current directory or a subdirectory.
6394 Otherwise, the link will be the absolute path as completed in the minibuffer
6395 \(i.e. normally ~/path/to/file).
6397 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6398 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6399 of `org-keep-stored-link-after-insertion'.
6401 If `org-make-link-description-function' is non-nil, this function will be
6402 called with the link target, and the result will be the default
6403 link description.
6405 If the LINK-LOCATION parameter is non-nil, this value will be
6406 used as the link location instead of reading one interactively."
6407 (interactive "P")
6408 (let* ((wcf (current-window-configuration))
6409 (region (if (org-region-active-p)
6410 (buffer-substring (region-beginning) (region-end))))
6411 (remove (and region (list (region-beginning) (region-end))))
6412 (desc region)
6413 tmphist ; byte-compile incorrectly complains about this
6414 (link link-location)
6415 entry file)
6416 (cond
6417 (link-location) ; specified by arg, just use it.
6418 ((org-in-regexp org-bracket-link-regexp 1)
6419 ;; We do have a link at point, and we are going to edit it.
6420 (setq remove (list (match-beginning 0) (match-end 0)))
6421 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6422 (setq link (read-string "Link: "
6423 (org-link-unescape
6424 (org-match-string-no-properties 1)))))
6425 ((or (org-in-regexp org-angle-link-re)
6426 (org-in-regexp org-plain-link-re))
6427 ;; Convert to bracket link
6428 (setq remove (list (match-beginning 0) (match-end 0))
6429 link (read-string "Link: "
6430 (org-remove-angle-brackets (match-string 0)))))
6431 ((equal complete-file '(4))
6432 ;; Completing read for file names.
6433 (setq file (read-file-name "File: "))
6434 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6435 (pwd1 (file-name-as-directory (abbreviate-file-name
6436 (expand-file-name ".")))))
6437 (cond
6438 ((equal complete-file '(16))
6439 (setq link (org-make-link
6440 "file:"
6441 (abbreviate-file-name (expand-file-name file)))))
6442 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6443 (setq link (org-make-link "file:" (match-string 1 file))))
6444 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6445 (expand-file-name file))
6446 (setq link (org-make-link
6447 "file:" (match-string 1 (expand-file-name file)))))
6448 (t (setq link (org-make-link "file:" file))))))
6450 ;; Read link, with completion for stored links.
6451 (with-output-to-temp-buffer "*Org Links*"
6452 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6453 (when org-stored-links
6454 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6455 (princ (mapconcat
6456 (lambda (x)
6457 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6458 (reverse org-stored-links) "\n"))))
6459 (let ((cw (selected-window)))
6460 (select-window (get-buffer-window "*Org Links*"))
6461 (shrink-window-if-larger-than-buffer)
6462 (setq truncate-lines t)
6463 (select-window cw))
6464 ;; Fake a link history, containing the stored links.
6465 (setq tmphist (append (mapcar 'car org-stored-links)
6466 org-insert-link-history))
6467 (unwind-protect
6468 (setq link (org-completing-read
6469 "Link: "
6470 (append
6471 (mapcar (lambda (x) (list (concat (car x) ":")))
6472 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6473 (mapcar (lambda (x) (list (concat x ":")))
6474 org-link-types))
6475 nil nil nil
6476 'tmphist
6477 (or (car (car org-stored-links)))))
6478 (set-window-configuration wcf)
6479 (kill-buffer "*Org Links*"))
6480 (setq entry (assoc link org-stored-links))
6481 (or entry (push link org-insert-link-history))
6482 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6483 (not org-keep-stored-link-after-insertion))
6484 (setq org-stored-links (delq (assoc link org-stored-links)
6485 org-stored-links)))
6486 (setq desc (or desc (nth 1 entry)))))
6488 (if (string-match org-plain-link-re link)
6489 ;; URL-like link, normalize the use of angular brackets.
6490 (setq link (org-make-link (org-remove-angle-brackets link))))
6492 ;; Check if we are linking to the current file with a search option
6493 ;; If yes, simplify the link by using only the search option.
6494 (when (and buffer-file-name
6495 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6496 (let* ((path (match-string 1 link))
6497 (case-fold-search nil)
6498 (search (match-string 2 link)))
6499 (save-match-data
6500 (if (equal (file-truename buffer-file-name) (file-truename path))
6501 ;; We are linking to this same file, with a search option
6502 (setq link search)))))
6504 ;; Check if we can/should use a relative path. If yes, simplify the link
6505 (when (string-match "\\<file:\\(.*\\)" link)
6506 (let* ((path (match-string 1 link))
6507 (origpath path)
6508 (case-fold-search nil))
6509 (cond
6510 ((eq org-link-file-path-type 'absolute)
6511 (setq path (abbreviate-file-name (expand-file-name path))))
6512 ((eq org-link-file-path-type 'noabbrev)
6513 (setq path (expand-file-name path)))
6514 ((eq org-link-file-path-type 'relative)
6515 (setq path (file-relative-name path)))
6517 (save-match-data
6518 (if (string-match (concat "^" (regexp-quote
6519 (file-name-as-directory
6520 (expand-file-name "."))))
6521 (expand-file-name path))
6522 ;; We are linking a file with relative path name.
6523 (setq path (substring (expand-file-name path)
6524 (match-end 0)))))))
6525 (setq link (concat "file:" path))
6526 (if (equal desc origpath)
6527 (setq desc path))))
6529 (if org-make-link-description-function
6530 (setq desc (funcall org-make-link-description-function link desc)))
6532 (setq desc (read-string "Description: " desc))
6533 (unless (string-match "\\S-" desc) (setq desc nil))
6534 (if remove (apply 'delete-region remove))
6535 (insert (org-make-link-string link desc))))
6537 (defun org-completing-read (&rest args)
6538 (let ((minibuffer-local-completion-map
6539 (copy-keymap minibuffer-local-completion-map)))
6540 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6541 (apply 'completing-read args)))
6543 ;;; Opening/following a link
6545 (defvar org-link-search-failed nil)
6547 (defun org-next-link ()
6548 "Move forward to the next link.
6549 If the link is in hidden text, expose it."
6550 (interactive)
6551 (when (and org-link-search-failed (eq this-command last-command))
6552 (goto-char (point-min))
6553 (message "Link search wrapped back to beginning of buffer"))
6554 (setq org-link-search-failed nil)
6555 (let* ((pos (point))
6556 (ct (org-context))
6557 (a (assoc :link ct)))
6558 (if a (goto-char (nth 2 a)))
6559 (if (re-search-forward org-any-link-re nil t)
6560 (progn
6561 (goto-char (match-beginning 0))
6562 (if (org-invisible-p) (org-show-context)))
6563 (goto-char pos)
6564 (setq org-link-search-failed t)
6565 (error "No further link found"))))
6567 (defun org-previous-link ()
6568 "Move backward to the previous link.
6569 If the link is in hidden text, expose it."
6570 (interactive)
6571 (when (and org-link-search-failed (eq this-command last-command))
6572 (goto-char (point-max))
6573 (message "Link search wrapped back to end of buffer"))
6574 (setq org-link-search-failed nil)
6575 (let* ((pos (point))
6576 (ct (org-context))
6577 (a (assoc :link ct)))
6578 (if a (goto-char (nth 1 a)))
6579 (if (re-search-backward org-any-link-re nil t)
6580 (progn
6581 (goto-char (match-beginning 0))
6582 (if (org-invisible-p) (org-show-context)))
6583 (goto-char pos)
6584 (setq org-link-search-failed t)
6585 (error "No further link found"))))
6587 (defun org-find-file-at-mouse (ev)
6588 "Open file link or URL at mouse."
6589 (interactive "e")
6590 (mouse-set-point ev)
6591 (org-open-at-point 'in-emacs))
6593 (defun org-open-at-mouse (ev)
6594 "Open file link or URL at mouse."
6595 (interactive "e")
6596 (mouse-set-point ev)
6597 (org-open-at-point))
6599 (defvar org-window-config-before-follow-link nil
6600 "The window configuration before following a link.
6601 This is saved in case the need arises to restore it.")
6603 (defvar org-open-link-marker (make-marker)
6604 "Marker pointing to the location where `org-open-at-point; was called.")
6606 ;;;###autoload
6607 (defun org-open-at-point-global ()
6608 "Follow a link like Org-mode does.
6609 This command can be called in any mode to follow a link that has
6610 Org-mode syntax."
6611 (interactive)
6612 (org-run-like-in-org-mode 'org-open-at-point))
6614 (defun org-open-at-point (&optional in-emacs)
6615 "Open link at or after point.
6616 If there is no link at point, this function will search forward up to
6617 the end of the current subtree.
6618 Normally, files will be opened by an appropriate application. If the
6619 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6620 (interactive "P")
6621 (org-load-modules-maybe)
6622 (move-marker org-open-link-marker (point))
6623 (setq org-window-config-before-follow-link (current-window-configuration))
6624 (org-remove-occur-highlights nil nil t)
6625 (if (org-at-timestamp-p t)
6626 (org-follow-timestamp-link)
6627 (let (type path link line search (pos (point)))
6628 (catch 'match
6629 (save-excursion
6630 (skip-chars-forward "^]\n\r")
6631 (when (org-in-regexp org-bracket-link-regexp)
6632 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6633 (while (string-match " *\n *" link)
6634 (setq link (replace-match " " t t link)))
6635 (setq link (org-link-expand-abbrev link))
6636 (if (string-match org-link-re-with-space2 link)
6637 (setq type (match-string 1 link) path (match-string 2 link))
6638 (setq type "thisfile" path link))
6639 (throw 'match t)))
6641 (when (get-text-property (point) 'org-linked-text)
6642 (setq type "thisfile"
6643 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6644 (1+ (point)) (point))
6645 path (buffer-substring
6646 (previous-single-property-change pos 'org-linked-text)
6647 (next-single-property-change pos 'org-linked-text)))
6648 (throw 'match t))
6650 (save-excursion
6651 (when (or (org-in-regexp org-angle-link-re)
6652 (org-in-regexp org-plain-link-re))
6653 (setq type (match-string 1) path (match-string 2))
6654 (throw 'match t)))
6655 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6656 (setq type "tree-match"
6657 path (match-string 1))
6658 (throw 'match t))
6659 (save-excursion
6660 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6661 (setq type "tags"
6662 path (match-string 1))
6663 (while (string-match ":" path)
6664 (setq path (replace-match "+" t t path)))
6665 (throw 'match t))))
6666 (unless path
6667 (error "No link found"))
6668 ;; Remove any trailing spaces in path
6669 (if (string-match " +\\'" path)
6670 (setq path (replace-match "" t t path)))
6672 (cond
6674 ((assoc type org-link-protocols)
6675 (funcall (nth 1 (assoc type org-link-protocols)) path))
6677 ((equal type "mailto")
6678 (let ((cmd (car org-link-mailto-program))
6679 (args (cdr org-link-mailto-program)) args1
6680 (address path) (subject "") a)
6681 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6682 (setq address (match-string 1 path)
6683 subject (org-link-escape (match-string 2 path))))
6684 (while args
6685 (cond
6686 ((not (stringp (car args))) (push (pop args) args1))
6687 (t (setq a (pop args))
6688 (if (string-match "%a" a)
6689 (setq a (replace-match address t t a)))
6690 (if (string-match "%s" a)
6691 (setq a (replace-match subject t t a)))
6692 (push a args1))))
6693 (apply cmd (nreverse args1))))
6695 ((member type '("http" "https" "ftp" "news"))
6696 (browse-url (concat type ":" (org-link-escape
6697 path org-link-escape-chars-browser))))
6699 ((member type '("message"))
6700 (browse-url (concat type ":" path)))
6702 ((string= type "tags")
6703 (org-tags-view in-emacs path))
6704 ((string= type "thisfile")
6705 (if in-emacs
6706 (switch-to-buffer-other-window
6707 (org-get-buffer-for-internal-link (current-buffer)))
6708 (org-mark-ring-push))
6709 (let ((cmd `(org-link-search
6710 ,path
6711 ,(cond ((equal in-emacs '(4)) 'occur)
6712 ((equal in-emacs '(16)) 'org-occur)
6713 (t nil))
6714 ,pos)))
6715 (condition-case nil (eval cmd)
6716 (error (progn (widen) (eval cmd))))))
6718 ((string= type "tree-match")
6719 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6721 ((string= type "file")
6722 (if (string-match "::\\([0-9]+\\)\\'" path)
6723 (setq line (string-to-number (match-string 1 path))
6724 path (substring path 0 (match-beginning 0)))
6725 (if (string-match "::\\(.+\\)\\'" path)
6726 (setq search (match-string 1 path)
6727 path (substring path 0 (match-beginning 0)))))
6728 (if (string-match "[*?{]" (file-name-nondirectory path))
6729 (dired path)
6730 (org-open-file path in-emacs line search)))
6732 ((string= type "news")
6733 (require 'org-gnus)
6734 (org-gnus-follow-link path))
6736 ((string= type "shell")
6737 (let ((cmd path))
6738 (if (or (not org-confirm-shell-link-function)
6739 (funcall org-confirm-shell-link-function
6740 (format "Execute \"%s\" in shell? "
6741 (org-add-props cmd nil
6742 'face 'org-warning))))
6743 (progn
6744 (message "Executing %s" cmd)
6745 (shell-command cmd))
6746 (error "Abort"))))
6748 ((string= type "elisp")
6749 (let ((cmd path))
6750 (if (or (not org-confirm-elisp-link-function)
6751 (funcall org-confirm-elisp-link-function
6752 (format "Execute \"%s\" as elisp? "
6753 (org-add-props cmd nil
6754 'face 'org-warning))))
6755 (message "%s => %s" cmd (eval (read cmd)))
6756 (error "Abort"))))
6759 (browse-url-at-point)))))
6760 (move-marker org-open-link-marker nil)
6761 (run-hook-with-args 'org-follow-link-hook))
6763 ;;; File search
6765 (defvar org-create-file-search-functions nil
6766 "List of functions to construct the right search string for a file link.
6767 These functions are called in turn with point at the location to
6768 which the link should point.
6770 A function in the hook should first test if it would like to
6771 handle this file type, for example by checking the major-mode or
6772 the file extension. If it decides not to handle this file, it
6773 should just return nil to give other functions a chance. If it
6774 does handle the file, it must return the search string to be used
6775 when following the link. The search string will be part of the
6776 file link, given after a double colon, and `org-open-at-point'
6777 will automatically search for it. If special measures must be
6778 taken to make the search successful, another function should be
6779 added to the companion hook `org-execute-file-search-functions',
6780 which see.
6782 A function in this hook may also use `setq' to set the variable
6783 `description' to provide a suggestion for the descriptive text to
6784 be used for this link when it gets inserted into an Org-mode
6785 buffer with \\[org-insert-link].")
6787 (defvar org-execute-file-search-functions nil
6788 "List of functions to execute a file search triggered by a link.
6790 Functions added to this hook must accept a single argument, the
6791 search string that was part of the file link, the part after the
6792 double colon. The function must first check if it would like to
6793 handle this search, for example by checking the major-mode or the
6794 file extension. If it decides not to handle this search, it
6795 should just return nil to give other functions a chance. If it
6796 does handle the search, it must return a non-nil value to keep
6797 other functions from trying.
6799 Each function can access the current prefix argument through the
6800 variable `current-prefix-argument'. Note that a single prefix is
6801 used to force opening a link in Emacs, so it may be good to only
6802 use a numeric or double prefix to guide the search function.
6804 In case this is needed, a function in this hook can also restore
6805 the window configuration before `org-open-at-point' was called using:
6807 (set-window-configuration org-window-config-before-follow-link)")
6809 (defun org-link-search (s &optional type avoid-pos)
6810 "Search for a link search option.
6811 If S is surrounded by forward slashes, it is interpreted as a
6812 regular expression. In org-mode files, this will create an `org-occur'
6813 sparse tree. In ordinary files, `occur' will be used to list matches.
6814 If the current buffer is in `dired-mode', grep will be used to search
6815 in all files. If AVOID-POS is given, ignore matches near that position."
6816 (let ((case-fold-search t)
6817 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6818 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6819 (append '(("") (" ") ("\t") ("\n"))
6820 org-emphasis-alist)
6821 "\\|") "\\)"))
6822 (pos (point))
6823 (pre nil) (post nil)
6824 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6825 (cond
6826 ;; First check if there are any special
6827 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6828 ;; Now try the builtin stuff
6829 ((save-excursion
6830 (goto-char (point-min))
6831 (and
6832 (re-search-forward
6833 (concat "<<" (regexp-quote s0) ">>") nil t)
6834 (setq type 'dedicated
6835 pos (match-beginning 0))))
6836 ;; There is an exact target for this
6837 (goto-char pos))
6838 ((string-match "^/\\(.*\\)/$" s)
6839 ;; A regular expression
6840 (cond
6841 ((org-mode-p)
6842 (org-occur (match-string 1 s)))
6843 ;;((eq major-mode 'dired-mode)
6844 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6845 (t (org-do-occur (match-string 1 s)))))
6847 ;; A normal search strings
6848 (when (equal (string-to-char s) ?*)
6849 ;; Anchor on headlines, post may include tags.
6850 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6851 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6852 s (substring s 1)))
6853 (remove-text-properties
6854 0 (length s)
6855 '(face nil mouse-face nil keymap nil fontified nil) s)
6856 ;; Make a series of regular expressions to find a match
6857 (setq words (org-split-string s "[ \n\r\t]+")
6859 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6860 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6861 "\\)" markers)
6862 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6863 re2a (concat "[ \t\r\n]" re2a_)
6864 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6865 re4 (concat "[^a-zA-Z_]" re4_)
6867 re1 (concat pre re2 post)
6868 re3 (concat pre (if pre re4_ re4) post)
6869 re5 (concat pre ".*" re4)
6870 re2 (concat pre re2)
6871 re2a (concat pre (if pre re2a_ re2a))
6872 re4 (concat pre (if pre re4_ re4))
6873 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6874 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6875 re5 "\\)"
6877 (cond
6878 ((eq type 'org-occur) (org-occur reall))
6879 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6880 (t (goto-char (point-min))
6881 (setq type 'fuzzy)
6882 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6883 (org-search-not-self 1 re1 nil t)
6884 (org-search-not-self 1 re2 nil t)
6885 (org-search-not-self 1 re2a nil t)
6886 (org-search-not-self 1 re3 nil t)
6887 (org-search-not-self 1 re4 nil t)
6888 (org-search-not-self 1 re5 nil t)
6890 (goto-char (match-beginning 1))
6891 (goto-char pos)
6892 (error "No match")))))
6894 ;; Normal string-search
6895 (goto-char (point-min))
6896 (if (search-forward s nil t)
6897 (goto-char (match-beginning 0))
6898 (error "No match"))))
6899 (and (org-mode-p) (org-show-context 'link-search))
6900 type))
6902 (defun org-search-not-self (group &rest args)
6903 "Execute `re-search-forward', but only accept matches that do not
6904 enclose the position of `org-open-link-marker'."
6905 (let ((m org-open-link-marker))
6906 (catch 'exit
6907 (while (apply 're-search-forward args)
6908 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6909 (goto-char (match-end group))
6910 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6911 (> (match-beginning 0) (marker-position m))
6912 (< (match-end 0) (marker-position m)))
6913 (save-match-data
6914 (or (not (org-in-regexp
6915 org-bracket-link-analytic-regexp 1))
6916 (not (match-end 4)) ; no description
6917 (and (<= (match-beginning 4) (point))
6918 (>= (match-end 4) (point))))))
6919 (throw 'exit (point))))))))
6921 (defun org-get-buffer-for-internal-link (buffer)
6922 "Return a buffer to be used for displaying the link target of internal links."
6923 (cond
6924 ((not org-display-internal-link-with-indirect-buffer)
6925 buffer)
6926 ((string-match "(Clone)$" (buffer-name buffer))
6927 (message "Buffer is already a clone, not making another one")
6928 ;; we also do not modify visibility in this case
6929 buffer)
6930 (t ; make a new indirect buffer for displaying the link
6931 (let* ((bn (buffer-name buffer))
6932 (ibn (concat bn "(Clone)"))
6933 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6934 (with-current-buffer ib (org-overview))
6935 ib))))
6937 (defun org-do-occur (regexp &optional cleanup)
6938 "Call the Emacs command `occur'.
6939 If CLEANUP is non-nil, remove the printout of the regular expression
6940 in the *Occur* buffer. This is useful if the regex is long and not useful
6941 to read."
6942 (occur regexp)
6943 (when cleanup
6944 (let ((cwin (selected-window)) win beg end)
6945 (when (setq win (get-buffer-window "*Occur*"))
6946 (select-window win))
6947 (goto-char (point-min))
6948 (when (re-search-forward "match[a-z]+" nil t)
6949 (setq beg (match-end 0))
6950 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6951 (setq end (1- (match-beginning 0)))))
6952 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6953 (goto-char (point-min))
6954 (select-window cwin))))
6956 ;;; The mark ring for links jumps
6958 (defvar org-mark-ring nil
6959 "Mark ring for positions before jumps in Org-mode.")
6960 (defvar org-mark-ring-last-goto nil
6961 "Last position in the mark ring used to go back.")
6962 ;; Fill and close the ring
6963 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6964 (loop for i from 1 to org-mark-ring-length do
6965 (push (make-marker) org-mark-ring))
6966 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6967 org-mark-ring)
6969 (defun org-mark-ring-push (&optional pos buffer)
6970 "Put the current position or POS into the mark ring and rotate it."
6971 (interactive)
6972 (setq pos (or pos (point)))
6973 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6974 (move-marker (car org-mark-ring)
6975 (or pos (point))
6976 (or buffer (current-buffer)))
6977 (message "%s"
6978 (substitute-command-keys
6979 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6981 (defun org-mark-ring-goto (&optional n)
6982 "Jump to the previous position in the mark ring.
6983 With prefix arg N, jump back that many stored positions. When
6984 called several times in succession, walk through the entire ring.
6985 Org-mode commands jumping to a different position in the current file,
6986 or to another Org-mode file, automatically push the old position
6987 onto the ring."
6988 (interactive "p")
6989 (let (p m)
6990 (if (eq last-command this-command)
6991 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6992 (setq p org-mark-ring))
6993 (setq org-mark-ring-last-goto p)
6994 (setq m (car p))
6995 (switch-to-buffer (marker-buffer m))
6996 (goto-char m)
6997 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6999 (defun org-remove-angle-brackets (s)
7000 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7001 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7003 (defun org-add-angle-brackets (s)
7004 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7005 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7008 ;;; Following specific links
7010 (defun org-follow-timestamp-link ()
7011 (cond
7012 ((org-at-date-range-p t)
7013 (let ((org-agenda-start-on-weekday)
7014 (t1 (match-string 1))
7015 (t2 (match-string 2)))
7016 (setq t1 (time-to-days (org-time-string-to-time t1))
7017 t2 (time-to-days (org-time-string-to-time t2)))
7018 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7019 ((org-at-timestamp-p t)
7020 (org-agenda-list nil (time-to-days (org-time-string-to-time
7021 (substring (match-string 1) 0 10)))
7023 (t (error "This should not happen"))))
7026 ;;; Following file links
7027 (defvar org-wait nil)
7028 (defun org-open-file (path &optional in-emacs line search)
7029 "Open the file at PATH.
7030 First, this expands any special file name abbreviations. Then the
7031 configuration variable `org-file-apps' is checked if it contains an
7032 entry for this file type, and if yes, the corresponding command is launched.
7033 If no application is found, Emacs simply visits the file.
7034 With optional argument IN-EMACS, Emacs will visit the file.
7035 Optional LINE specifies a line to go to, optional SEARCH a string to
7036 search for. If LINE or SEARCH is given, the file will always be
7037 opened in Emacs.
7038 If the file does not exist, an error is thrown."
7039 (setq in-emacs (or in-emacs line search))
7040 (let* ((file (if (equal path "")
7041 buffer-file-name
7042 (substitute-in-file-name (expand-file-name path))))
7043 (apps (append org-file-apps (org-default-apps)))
7044 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7045 (dirp (if remp nil (file-directory-p file)))
7046 (dfile (downcase file))
7047 (old-buffer (current-buffer))
7048 (old-pos (point))
7049 (old-mode major-mode)
7050 ext cmd)
7051 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7052 (setq ext (match-string 1 dfile))
7053 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7054 (setq ext (match-string 1 dfile))))
7055 (if in-emacs
7056 (setq cmd 'emacs)
7057 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7058 (and dirp (cdr (assoc 'directory apps)))
7059 (cdr (assoc ext apps))
7060 (cdr (assoc t apps)))))
7061 (when (eq cmd 'mailcap)
7062 (require 'mailcap)
7063 (mailcap-parse-mailcaps)
7064 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7065 (command (mailcap-mime-info mime-type)))
7066 (if (stringp command)
7067 (setq cmd command)
7068 (setq cmd 'emacs))))
7069 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7070 (not (file-exists-p file))
7071 (not org-open-non-existing-files))
7072 (error "No such file: %s" file))
7073 (cond
7074 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7075 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7076 (while (string-match "['\"]%s['\"]" cmd)
7077 (setq cmd (replace-match "%s" t t cmd)))
7078 (while (string-match "%s" cmd)
7079 (setq cmd (replace-match
7080 (save-match-data (shell-quote-argument file))
7081 t t cmd)))
7082 (save-window-excursion
7083 (start-process-shell-command cmd nil cmd)
7084 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7086 ((or (stringp cmd)
7087 (eq cmd 'emacs))
7088 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7089 (widen)
7090 (if line (goto-line line)
7091 (if search (org-link-search search))))
7092 ((consp cmd)
7093 (eval cmd))
7094 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7095 (and (org-mode-p) (eq old-mode 'org-mode)
7096 (or (not (equal old-buffer (current-buffer)))
7097 (not (equal old-pos (point))))
7098 (org-mark-ring-push old-pos old-buffer))))
7100 (defun org-default-apps ()
7101 "Return the default applications for this operating system."
7102 (cond
7103 ((eq system-type 'darwin)
7104 org-file-apps-defaults-macosx)
7105 ((eq system-type 'windows-nt)
7106 org-file-apps-defaults-windowsnt)
7107 (t org-file-apps-defaults-gnu)))
7109 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7110 (defun org-file-remote-p (file)
7111 "Test whether FILE specifies a location on a remote system.
7112 Return non-nil if the location is indeed remote.
7114 For example, the filename \"/user@host:/foo\" specifies a location
7115 on the system \"/user@host:\"."
7116 (cond ((fboundp 'file-remote-p)
7117 (file-remote-p file))
7118 ((fboundp 'tramp-handle-file-remote-p)
7119 (tramp-handle-file-remote-p file))
7120 ((and (boundp 'ange-ftp-name-format)
7121 (string-match (car ange-ftp-name-format) file))
7123 (t nil)))
7126 ;;;; Refiling
7128 (defun org-get-org-file ()
7129 "Read a filename, with default directory `org-directory'."
7130 (let ((default (or org-default-notes-file remember-data-file)))
7131 (read-file-name (format "File name [%s]: " default)
7132 (file-name-as-directory org-directory)
7133 default)))
7135 (defun org-notes-order-reversed-p ()
7136 "Check if the current file should receive notes in reversed order."
7137 (cond
7138 ((not org-reverse-note-order) nil)
7139 ((eq t org-reverse-note-order) t)
7140 ((not (listp org-reverse-note-order)) nil)
7141 (t (catch 'exit
7142 (let ((all org-reverse-note-order)
7143 entry)
7144 (while (setq entry (pop all))
7145 (if (string-match (car entry) buffer-file-name)
7146 (throw 'exit (cdr entry))))
7147 nil)))))
7149 (defvar org-refile-target-table nil
7150 "The list of refile targets, created by `org-refile'.")
7152 (defvar org-agenda-new-buffers nil
7153 "Buffers created to visit agenda files.")
7155 (defun org-get-refile-targets (&optional default-buffer)
7156 "Produce a table with refile targets."
7157 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7158 targets txt re files f desc descre)
7159 (with-current-buffer (or default-buffer (current-buffer))
7160 (while (setq entry (pop entries))
7161 (setq files (car entry) desc (cdr entry))
7162 (cond
7163 ((null files) (setq files (list (current-buffer))))
7164 ((eq files 'org-agenda-files)
7165 (setq files (org-agenda-files 'unrestricted)))
7166 ((and (symbolp files) (fboundp files))
7167 (setq files (funcall files)))
7168 ((and (symbolp files) (boundp files))
7169 (setq files (symbol-value files))))
7170 (if (stringp files) (setq files (list files)))
7171 (cond
7172 ((eq (car desc) :tag)
7173 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7174 ((eq (car desc) :todo)
7175 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7176 ((eq (car desc) :regexp)
7177 (setq descre (cdr desc)))
7178 ((eq (car desc) :level)
7179 (setq descre (concat "^\\*\\{" (number-to-string
7180 (if org-odd-levels-only
7181 (1- (* 2 (cdr desc)))
7182 (cdr desc)))
7183 "\\}[ \t]")))
7184 ((eq (car desc) :maxlevel)
7185 (setq descre (concat "^\\*\\{1," (number-to-string
7186 (if org-odd-levels-only
7187 (1- (* 2 (cdr desc)))
7188 (cdr desc)))
7189 "\\}[ \t]")))
7190 (t (error "Bad refiling target description %s" desc)))
7191 (while (setq f (pop files))
7192 (save-excursion
7193 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7194 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7195 (save-excursion
7196 (save-restriction
7197 (widen)
7198 (goto-char (point-min))
7199 (while (re-search-forward descre nil t)
7200 (goto-char (point-at-bol))
7201 (when (looking-at org-complex-heading-regexp)
7202 (setq txt (match-string 4)
7203 re (concat "^" (regexp-quote
7204 (buffer-substring (match-beginning 1)
7205 (match-end 4)))))
7206 (if (match-end 5) (setq re (concat re "[ \t]+"
7207 (regexp-quote
7208 (match-string 5)))))
7209 (setq re (concat re "[ \t]*$"))
7210 (when org-refile-use-outline-path
7211 (setq txt (mapconcat 'identity
7212 (append
7213 (if (eq org-refile-use-outline-path 'file)
7214 (list (file-name-nondirectory
7215 (buffer-file-name (buffer-base-buffer))))
7216 (if (eq org-refile-use-outline-path 'full-file-path)
7217 (list (buffer-file-name (buffer-base-buffer)))))
7218 (org-get-outline-path)
7219 (list txt))
7220 "/")))
7221 (push (list txt f re (point)) targets))
7222 (goto-char (point-at-eol))))))))
7223 (nreverse targets))))
7225 (defun org-get-outline-path ()
7226 "Return the outline path to the current entry, as a list."
7227 (let (rtn)
7228 (save-excursion
7229 (while (org-up-heading-safe)
7230 (when (looking-at org-complex-heading-regexp)
7231 (push (org-match-string-no-properties 4) rtn)))
7232 rtn)))
7234 (defvar org-refile-history nil
7235 "History for refiling operations.")
7237 (defun org-refile (&optional goto default-buffer)
7238 "Move the entry at point to another heading.
7239 The list of target headings is compiled using the information in
7240 `org-refile-targets', which see. This list is created before each use
7241 and will therefore always be up-to-date.
7243 At the target location, the entry is filed as a subitem of the target heading.
7244 Depending on `org-reverse-note-order', the new subitem will either be the
7245 first of the last subitem.
7247 With prefix arg GOTO, the command will only visit the target location,
7248 not actually move anything.
7249 With a double prefix `C-c C-c', go to the location where the last refiling
7250 operation has put the subtree."
7251 (interactive "P")
7252 (let* ((cbuf (current-buffer))
7253 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7254 pos it nbuf file re level reversed)
7255 (if (equal goto '(16))
7256 (org-refile-goto-last-stored)
7257 (when (setq it (org-refile-get-location
7258 (if goto "Goto: " "Refile to: ") default-buffer))
7259 (setq file (nth 1 it)
7260 re (nth 2 it)
7261 pos (nth 3 it))
7262 (setq nbuf (or (find-buffer-visiting file)
7263 (find-file-noselect file)))
7264 (if goto
7265 (progn
7266 (switch-to-buffer nbuf)
7267 (goto-char pos)
7268 (org-show-context 'org-goto))
7269 (org-copy-special)
7270 (save-excursion
7271 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7272 (find-file-noselect file))))
7273 (setq reversed (org-notes-order-reversed-p))
7274 (save-excursion
7275 (save-restriction
7276 (widen)
7277 (goto-char pos)
7278 (looking-at outline-regexp)
7279 (setq level (org-get-valid-level (funcall outline-level) 1))
7280 (goto-char
7281 (if reversed
7282 (outline-next-heading)
7283 (or (save-excursion (outline-get-next-sibling))
7284 (org-end-of-subtree t t)
7285 (point-max))))
7286 (bookmark-set "org-refile-last-stored")
7287 (org-paste-subtree level))))
7288 (org-cut-special)
7289 (message "Entry refiled to \"%s\"" (car it)))))))
7291 (defun org-refile-goto-last-stored ()
7292 "Go to the location where the last refile was stored."
7293 (interactive)
7294 (bookmark-jump "org-refile-last-stored")
7295 (message "This is the location of the last refile"))
7297 (defun org-refile-get-location (&optional prompt default-buffer)
7298 "Prompt the user for a refile location, using PROMPT."
7299 (let ((org-refile-targets org-refile-targets)
7300 (org-refile-use-outline-path org-refile-use-outline-path))
7301 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7302 (unless org-refile-target-table
7303 (error "No refile targets"))
7304 (let* ((cbuf (current-buffer))
7305 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7306 (fname (and filename (file-truename filename)))
7307 (tbl (mapcar
7308 (lambda (x)
7309 (if (not (equal fname (file-truename (nth 1 x))))
7310 (cons (concat (car x) " (" (file-name-nondirectory
7311 (nth 1 x)) ")")
7312 (cdr x))
7314 org-refile-target-table))
7315 (completion-ignore-case t))
7316 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7317 tbl)))
7319 ;;;; Dynamic blocks
7321 (defun org-find-dblock (name)
7322 "Find the first dynamic block with name NAME in the buffer.
7323 If not found, stay at current position and return nil."
7324 (let (pos)
7325 (save-excursion
7326 (goto-char (point-min))
7327 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7328 nil t)
7329 (match-beginning 0))))
7330 (if pos (goto-char pos))
7331 pos))
7333 (defconst org-dblock-start-re
7334 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7335 "Matches the startline of a dynamic block, with parameters.")
7337 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7338 "Matches the end of a dyhamic block.")
7340 (defun org-create-dblock (plist)
7341 "Create a dynamic block section, with parameters taken from PLIST.
7342 PLIST must containe a :name entry which is used as name of the block."
7343 (unless (bolp) (newline))
7344 (let ((name (plist-get plist :name)))
7345 (insert "#+BEGIN: " name)
7346 (while plist
7347 (if (eq (car plist) :name)
7348 (setq plist (cddr plist))
7349 (insert " " (prin1-to-string (pop plist)))))
7350 (insert "\n\n#+END:\n")
7351 (beginning-of-line -2)))
7353 (defun org-prepare-dblock ()
7354 "Prepare dynamic block for refresh.
7355 This empties the block, puts the cursor at the insert position and returns
7356 the property list including an extra property :name with the block name."
7357 (unless (looking-at org-dblock-start-re)
7358 (error "Not at a dynamic block"))
7359 (let* ((begdel (1+ (match-end 0)))
7360 (name (org-no-properties (match-string 1)))
7361 (params (append (list :name name)
7362 (read (concat "(" (match-string 3) ")")))))
7363 (unless (re-search-forward org-dblock-end-re nil t)
7364 (error "Dynamic block not terminated"))
7365 (setq params
7366 (append params
7367 (list :content (buffer-substring
7368 begdel (match-beginning 0)))))
7369 (delete-region begdel (match-beginning 0))
7370 (goto-char begdel)
7371 (open-line 1)
7372 params))
7374 (defun org-map-dblocks (&optional command)
7375 "Apply COMMAND to all dynamic blocks in the current buffer.
7376 If COMMAND is not given, use `org-update-dblock'."
7377 (let ((cmd (or command 'org-update-dblock))
7378 pos)
7379 (save-excursion
7380 (goto-char (point-min))
7381 (while (re-search-forward org-dblock-start-re nil t)
7382 (goto-char (setq pos (match-beginning 0)))
7383 (condition-case nil
7384 (funcall cmd)
7385 (error (message "Error during update of dynamic block")))
7386 (goto-char pos)
7387 (unless (re-search-forward org-dblock-end-re nil t)
7388 (error "Dynamic block not terminated"))))))
7390 (defun org-dblock-update (&optional arg)
7391 "User command for updating dynamic blocks.
7392 Update the dynamic block at point. With prefix ARG, update all dynamic
7393 blocks in the buffer."
7394 (interactive "P")
7395 (if arg
7396 (org-update-all-dblocks)
7397 (or (looking-at org-dblock-start-re)
7398 (org-beginning-of-dblock))
7399 (org-update-dblock)))
7401 (defun org-update-dblock ()
7402 "Update the dynamic block at point
7403 This means to empty the block, parse for parameters and then call
7404 the correct writing function."
7405 (save-window-excursion
7406 (let* ((pos (point))
7407 (line (org-current-line))
7408 (params (org-prepare-dblock))
7409 (name (plist-get params :name))
7410 (cmd (intern (concat "org-dblock-write:" name))))
7411 (message "Updating dynamic block `%s' at line %d..." name line)
7412 (funcall cmd params)
7413 (message "Updating dynamic block `%s' at line %d...done" name line)
7414 (goto-char pos))))
7416 (defun org-beginning-of-dblock ()
7417 "Find the beginning of the dynamic block at point.
7418 Error if there is no scuh block at point."
7419 (let ((pos (point))
7420 beg)
7421 (end-of-line 1)
7422 (if (and (re-search-backward org-dblock-start-re nil t)
7423 (setq beg (match-beginning 0))
7424 (re-search-forward org-dblock-end-re nil t)
7425 (> (match-end 0) pos))
7426 (goto-char beg)
7427 (goto-char pos)
7428 (error "Not in a dynamic block"))))
7430 (defun org-update-all-dblocks ()
7431 "Update all dynamic blocks in the buffer.
7432 This function can be used in a hook."
7433 (when (org-mode-p)
7434 (org-map-dblocks 'org-update-dblock)))
7437 ;;;; Completion
7439 (defconst org-additional-option-like-keywords
7440 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7441 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7442 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7444 (defun org-complete (&optional arg)
7445 "Perform completion on word at point.
7446 At the beginning of a headline, this completes TODO keywords as given in
7447 `org-todo-keywords'.
7448 If the current word is preceded by a backslash, completes the TeX symbols
7449 that are supported for HTML support.
7450 If the current word is preceded by \"#+\", completes special words for
7451 setting file options.
7452 In the line after \"#+STARTUP:, complete valid keywords.\"
7453 At all other locations, this simply calls the value of
7454 `org-completion-fallback-command'."
7455 (interactive "P")
7456 (org-without-partial-completion
7457 (catch 'exit
7458 (let* ((end (point))
7459 (beg1 (save-excursion
7460 (skip-chars-backward (org-re "[:alnum:]_@"))
7461 (point)))
7462 (beg (save-excursion
7463 (skip-chars-backward "a-zA-Z0-9_:$")
7464 (point)))
7465 (confirm (lambda (x) (stringp (car x))))
7466 (searchhead (equal (char-before beg) ?*))
7467 (tag (and (equal (char-before beg1) ?:)
7468 (equal (char-after (point-at-bol)) ?*)))
7469 (prop (and (equal (char-before beg1) ?:)
7470 (not (equal (char-after (point-at-bol)) ?*))))
7471 (texp (equal (char-before beg) ?\\))
7472 (link (equal (char-before beg) ?\[))
7473 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7474 beg)
7475 "#+"))
7476 (startup (string-match "^#\\+STARTUP:.*"
7477 (buffer-substring (point-at-bol) (point))))
7478 (completion-ignore-case opt)
7479 (type nil)
7480 (tbl nil)
7481 (table (cond
7482 (opt
7483 (setq type :opt)
7484 (require 'org-exp)
7485 (append
7486 (mapcar
7487 (lambda (x)
7488 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7489 (cons (match-string 2 x) (match-string 1 x)))
7490 (org-split-string (org-get-current-options) "\n"))
7491 (mapcar 'list org-additional-option-like-keywords)))
7492 (startup
7493 (setq type :startup)
7494 org-startup-options)
7495 (link (append org-link-abbrev-alist-local
7496 org-link-abbrev-alist))
7497 (texp
7498 (setq type :tex)
7499 org-html-entities)
7500 ((string-match "\\`\\*+[ \t]+\\'"
7501 (buffer-substring (point-at-bol) beg))
7502 (setq type :todo)
7503 (mapcar 'list org-todo-keywords-1))
7504 (searchhead
7505 (setq type :searchhead)
7506 (save-excursion
7507 (goto-char (point-min))
7508 (while (re-search-forward org-todo-line-regexp nil t)
7509 (push (list
7510 (org-make-org-heading-search-string
7511 (match-string 3) t))
7512 tbl)))
7513 tbl)
7514 (tag (setq type :tag beg beg1)
7515 (or org-tag-alist (org-get-buffer-tags)))
7516 (prop (setq type :prop beg beg1)
7517 (mapcar 'list (org-buffer-property-keys nil t t)))
7518 (t (progn
7519 (call-interactively org-completion-fallback-command)
7520 (throw 'exit nil)))))
7521 (pattern (buffer-substring-no-properties beg end))
7522 (completion (try-completion pattern table confirm)))
7523 (cond ((eq completion t)
7524 (if (not (assoc (upcase pattern) table))
7525 (message "Already complete")
7526 (if (and (equal type :opt)
7527 (not (member (car (assoc (upcase pattern) table))
7528 org-additional-option-like-keywords)))
7529 (insert (substring (cdr (assoc (upcase pattern) table))
7530 (length pattern)))
7531 (if (memq type '(:tag :prop)) (insert ":")))))
7532 ((null completion)
7533 (message "Can't find completion for \"%s\"" pattern)
7534 (ding))
7535 ((not (string= pattern completion))
7536 (delete-region beg end)
7537 (if (string-match " +$" completion)
7538 (setq completion (replace-match "" t t completion)))
7539 (insert completion)
7540 (if (get-buffer-window "*Completions*")
7541 (delete-window (get-buffer-window "*Completions*")))
7542 (if (assoc completion table)
7543 (if (eq type :todo) (insert " ")
7544 (if (memq type '(:tag :prop)) (insert ":"))))
7545 (if (and (equal type :opt) (assoc completion table))
7546 (message "%s" (substitute-command-keys
7547 "Press \\[org-complete] again to insert example settings"))))
7549 (message "Making completion list...")
7550 (let ((list (sort (all-completions pattern table confirm)
7551 'string<)))
7552 (with-output-to-temp-buffer "*Completions*"
7553 (condition-case nil
7554 ;; Protection needed for XEmacs and emacs 21
7555 (display-completion-list list pattern)
7556 (error (display-completion-list list)))))
7557 (message "Making completion list...%s" "done")))))))
7559 ;;;; TODO, DEADLINE, Comments
7561 (defun org-toggle-comment ()
7562 "Change the COMMENT state of an entry."
7563 (interactive)
7564 (save-excursion
7565 (org-back-to-heading)
7566 (let (case-fold-search)
7567 (if (looking-at (concat outline-regexp
7568 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7569 (replace-match "" t t nil 1)
7570 (if (looking-at outline-regexp)
7571 (progn
7572 (goto-char (match-end 0))
7573 (insert org-comment-string " ")))))))
7575 (defvar org-last-todo-state-is-todo nil
7576 "This is non-nil when the last TODO state change led to a TODO state.
7577 If the last change removed the TODO tag or switched to DONE, then
7578 this is nil.")
7580 (defvar org-setting-tags nil) ; dynamically skiped
7582 (defun org-parse-local-options (string var)
7583 "Parse STRING for startup setting relevant for variable VAR."
7584 (let ((rtn (symbol-value var))
7585 e opts)
7586 (save-match-data
7587 (if (or (not string) (not (string-match "\\S-" string)))
7589 (setq opts (delq nil (mapcar (lambda (x)
7590 (setq e (assoc x org-startup-options))
7591 (if (eq (nth 1 e) var) e nil))
7592 (org-split-string string "[ \t]+"))))
7593 (if (not opts)
7595 (setq rtn nil)
7596 (while (setq e (pop opts))
7597 (if (not (nth 3 e))
7598 (setq rtn (nth 2 e))
7599 (if (not (listp rtn)) (setq rtn nil))
7600 (push (nth 2 e) rtn)))
7601 rtn)))))
7603 (defvar org-blocker-hook nil
7604 "Hook for functions that are allowed to block a state change.
7606 Each function gets as its single argument a property list, see
7607 `org-trigger-hook' for more information about this list.
7609 If any of the functions in this hook returns nil, the state change
7610 is blocked.")
7612 (defvar org-trigger-hook nil
7613 "Hook for functions that are triggered by a state change.
7615 Each function gets as its single argument a property list with at least
7616 the following elements:
7618 (:type type-of-change :position pos-at-entry-start
7619 :from old-state :to new-state)
7621 Depending on the type, more properties may be present.
7623 This mechanism is currently implemented for:
7625 TODO state changes
7626 ------------------
7627 :type todo-state-change
7628 :from previous state (keyword as a string), or nil
7629 :to new state (keyword as a string), or nil")
7632 (defun org-todo (&optional arg)
7633 "Change the TODO state of an item.
7634 The state of an item is given by a keyword at the start of the heading,
7635 like
7636 *** TODO Write paper
7637 *** DONE Call mom
7639 The different keywords are specified in the variable `org-todo-keywords'.
7640 By default the available states are \"TODO\" and \"DONE\".
7641 So for this example: when the item starts with TODO, it is changed to DONE.
7642 When it starts with DONE, the DONE is removed. And when neither TODO nor
7643 DONE are present, add TODO at the beginning of the heading.
7645 With C-u prefix arg, use completion to determine the new state.
7646 With numeric prefix arg, switch to that state.
7648 For calling through lisp, arg is also interpreted in the following way:
7649 'none -> empty state
7650 \"\"(empty string) -> switch to empty state
7651 'done -> switch to DONE
7652 'nextset -> switch to the next set of keywords
7653 'previousset -> switch to the previous set of keywords
7654 \"WAITING\" -> switch to the specified keyword, but only if it
7655 really is a member of `org-todo-keywords'."
7656 (interactive "P")
7657 (save-excursion
7658 (catch 'exit
7659 (org-back-to-heading)
7660 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7661 (or (looking-at (concat " +" org-todo-regexp " *"))
7662 (looking-at " *"))
7663 (let* ((match-data (match-data))
7664 (startpos (point-at-bol))
7665 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7666 (org-log-done org-log-done)
7667 (org-log-repeat org-log-repeat)
7668 (org-todo-log-states org-todo-log-states)
7669 (this (match-string 1))
7670 (hl-pos (match-beginning 0))
7671 (head (org-get-todo-sequence-head this))
7672 (ass (assoc head org-todo-kwd-alist))
7673 (interpret (nth 1 ass))
7674 (done-word (nth 3 ass))
7675 (final-done-word (nth 4 ass))
7676 (last-state (or this ""))
7677 (completion-ignore-case t)
7678 (member (member this org-todo-keywords-1))
7679 (tail (cdr member))
7680 (state (cond
7681 ((and org-todo-key-trigger
7682 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7683 (and (not arg) org-use-fast-todo-selection
7684 (not (eq org-use-fast-todo-selection 'prefix)))))
7685 ;; Use fast selection
7686 (org-fast-todo-selection))
7687 ((and (equal arg '(4))
7688 (or (not org-use-fast-todo-selection)
7689 (not org-todo-key-trigger)))
7690 ;; Read a state with completion
7691 (completing-read "State: " (mapcar (lambda(x) (list x))
7692 org-todo-keywords-1)
7693 nil t))
7694 ((eq arg 'right)
7695 (if this
7696 (if tail (car tail) nil)
7697 (car org-todo-keywords-1)))
7698 ((eq arg 'left)
7699 (if (equal member org-todo-keywords-1)
7701 (if this
7702 (nth (- (length org-todo-keywords-1) (length tail) 2)
7703 org-todo-keywords-1)
7704 (org-last org-todo-keywords-1))))
7705 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7706 (setq arg nil))) ; hack to fall back to cycling
7707 (arg
7708 ;; user or caller requests a specific state
7709 (cond
7710 ((equal arg "") nil)
7711 ((eq arg 'none) nil)
7712 ((eq arg 'done) (or done-word (car org-done-keywords)))
7713 ((eq arg 'nextset)
7714 (or (car (cdr (member head org-todo-heads)))
7715 (car org-todo-heads)))
7716 ((eq arg 'previousset)
7717 (let ((org-todo-heads (reverse org-todo-heads)))
7718 (or (car (cdr (member head org-todo-heads)))
7719 (car org-todo-heads))))
7720 ((car (member arg org-todo-keywords-1)))
7721 ((nth (1- (prefix-numeric-value arg))
7722 org-todo-keywords-1))))
7723 ((null member) (or head (car org-todo-keywords-1)))
7724 ((equal this final-done-word) nil) ;; -> make empty
7725 ((null tail) nil) ;; -> first entry
7726 ((eq interpret 'sequence)
7727 (car tail))
7728 ((memq interpret '(type priority))
7729 (if (eq this-command last-command)
7730 (car tail)
7731 (if (> (length tail) 0)
7732 (or done-word (car org-done-keywords))
7733 nil)))
7734 (t nil)))
7735 (next (if state (concat " " state " ") " "))
7736 (change-plist (list :type 'todo-state-change :from this :to state
7737 :position startpos))
7738 dolog now-done-p)
7739 (when org-blocker-hook
7740 (unless (save-excursion
7741 (save-match-data
7742 (run-hook-with-args-until-failure
7743 'org-blocker-hook change-plist)))
7744 (if (interactive-p)
7745 (error "TODO state change from %s to %s blocked" this state)
7746 ;; fail silently
7747 (message "TODO state change from %s to %s blocked" this state)
7748 (throw 'exit nil))))
7749 (store-match-data match-data)
7750 (replace-match next t t)
7751 (unless (pos-visible-in-window-p hl-pos)
7752 (message "TODO state changed to %s" (org-trim next)))
7753 (unless head
7754 (setq head (org-get-todo-sequence-head state)
7755 ass (assoc head org-todo-kwd-alist)
7756 interpret (nth 1 ass)
7757 done-word (nth 3 ass)
7758 final-done-word (nth 4 ass)))
7759 (when (memq arg '(nextset previousset))
7760 (message "Keyword-Set %d/%d: %s"
7761 (- (length org-todo-sets) -1
7762 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7763 (length org-todo-sets)
7764 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7765 (setq org-last-todo-state-is-todo
7766 (not (member state org-done-keywords)))
7767 (setq now-done-p (and (member state org-done-keywords)
7768 (not (member this org-done-keywords))))
7769 (and logging (org-local-logging logging))
7770 (when (and (or org-todo-log-states org-log-done)
7771 (not (memq arg '(nextset previousset))))
7772 ;; we need to look at recording a time and note
7773 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7774 (nth 2 (assoc this org-todo-log-states))))
7775 (when (and state
7776 (member state org-not-done-keywords)
7777 (not (member this org-not-done-keywords)))
7778 ;; This is now a todo state and was not one before
7779 ;; If there was a CLOSED time stamp, get rid of it.
7780 (org-add-planning-info nil nil 'closed))
7781 (when (and now-done-p org-log-done)
7782 ;; It is now done, and it was not done before
7783 (org-add-planning-info 'closed (org-current-time))
7784 (if (and (not dolog) (eq 'note org-log-done))
7785 (org-add-log-setup 'done state 'findpos 'note)))
7786 (when (and state dolog)
7787 ;; This is a non-nil state, and we need to log it
7788 (org-add-log-setup 'state state 'findpos dolog)))
7789 ;; Fixup tag positioning
7790 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7791 (run-hooks 'org-after-todo-state-change-hook)
7792 (if (and arg (not (member state org-done-keywords)))
7793 (setq head (org-get-todo-sequence-head state)))
7794 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7795 ;; Do we need to trigger a repeat?
7796 (when now-done-p (org-auto-repeat-maybe state))
7797 ;; Fixup cursor location if close to the keyword
7798 (if (and (outline-on-heading-p)
7799 (not (bolp))
7800 (save-excursion (beginning-of-line 1)
7801 (looking-at org-todo-line-regexp))
7802 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7803 (progn
7804 (goto-char (or (match-end 2) (match-end 1)))
7805 (just-one-space)))
7806 (when org-trigger-hook
7807 (save-excursion
7808 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7810 (defun org-local-logging (value)
7811 "Get logging settings from a property VALUE."
7812 (let* (words w a)
7813 ;; directly set the variables, they are already local.
7814 (setq org-log-done nil
7815 org-log-repeat nil
7816 org-todo-log-states nil)
7817 (setq words (org-split-string value))
7818 (while (setq w (pop words))
7819 (cond
7820 ((setq a (assoc w org-startup-options))
7821 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7822 (set (nth 1 a) (nth 2 a))))
7823 ((setq a (org-extract-log-state-settings w))
7824 (and (member (car a) org-todo-keywords-1)
7825 (push a org-todo-log-states)))))))
7827 (defun org-get-todo-sequence-head (kwd)
7828 "Return the head of the TODO sequence to which KWD belongs.
7829 If KWD is not set, check if there is a text property remembering the
7830 right sequence."
7831 (let (p)
7832 (cond
7833 ((not kwd)
7834 (or (get-text-property (point-at-bol) 'org-todo-head)
7835 (progn
7836 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7837 nil (point-at-eol)))
7838 (get-text-property p 'org-todo-head))))
7839 ((not (member kwd org-todo-keywords-1))
7840 (car org-todo-keywords-1))
7841 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7843 (defun org-fast-todo-selection ()
7844 "Fast TODO keyword selection with single keys.
7845 Returns the new TODO keyword, or nil if no state change should occur."
7846 (let* ((fulltable org-todo-key-alist)
7847 (done-keywords org-done-keywords) ;; needed for the faces.
7848 (maxlen (apply 'max (mapcar
7849 (lambda (x)
7850 (if (stringp (car x)) (string-width (car x)) 0))
7851 fulltable)))
7852 (expert nil)
7853 (fwidth (+ maxlen 3 1 3))
7854 (ncol (/ (- (window-width) 4) fwidth))
7855 tg cnt e c tbl
7856 groups ingroup)
7857 (save-window-excursion
7858 (if expert
7859 (set-buffer (get-buffer-create " *Org todo*"))
7860 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7861 (erase-buffer)
7862 (org-set-local 'org-done-keywords done-keywords)
7863 (setq tbl fulltable cnt 0)
7864 (while (setq e (pop tbl))
7865 (cond
7866 ((equal e '(:startgroup))
7867 (push '() groups) (setq ingroup t)
7868 (when (not (= cnt 0))
7869 (setq cnt 0)
7870 (insert "\n"))
7871 (insert "{ "))
7872 ((equal e '(:endgroup))
7873 (setq ingroup nil cnt 0)
7874 (insert "}\n"))
7876 (setq tg (car e) c (cdr e))
7877 (if ingroup (push tg (car groups)))
7878 (setq tg (org-add-props tg nil 'face
7879 (org-get-todo-face tg)))
7880 (if (and (= cnt 0) (not ingroup)) (insert " "))
7881 (insert "[" c "] " tg (make-string
7882 (- fwidth 4 (length tg)) ?\ ))
7883 (when (= (setq cnt (1+ cnt)) ncol)
7884 (insert "\n")
7885 (if ingroup (insert " "))
7886 (setq cnt 0)))))
7887 (insert "\n")
7888 (goto-char (point-min))
7889 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7890 (fit-window-to-buffer))
7891 (message "[a-z..]:Set [SPC]:clear")
7892 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7893 (cond
7894 ((or (= c ?\C-g)
7895 (and (= c ?q) (not (rassoc c fulltable))))
7896 (setq quit-flag t))
7897 ((= c ?\ ) nil)
7898 ((setq e (rassoc c fulltable) tg (car e))
7900 (t (setq quit-flag t))))))
7902 (defun org-entry-is-todo-p ()
7903 (member (org-get-todo-state) org-not-done-keywords))
7905 (defun org-entry-is-done-p ()
7906 (member (org-get-todo-state) org-done-keywords))
7908 (defun org-get-todo-state ()
7909 (save-excursion
7910 (org-back-to-heading t)
7911 (and (looking-at org-todo-line-regexp)
7912 (match-end 2)
7913 (match-string 2))))
7915 (defun org-at-date-range-p (&optional inactive-ok)
7916 "Is the cursor inside a date range?"
7917 (interactive)
7918 (save-excursion
7919 (catch 'exit
7920 (let ((pos (point)))
7921 (skip-chars-backward "^[<\r\n")
7922 (skip-chars-backward "<[")
7923 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7924 (>= (match-end 0) pos)
7925 (throw 'exit t))
7926 (skip-chars-backward "^<[\r\n")
7927 (skip-chars-backward "<[")
7928 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7929 (>= (match-end 0) pos)
7930 (throw 'exit t)))
7931 nil)))
7933 (defun org-get-repeat ()
7934 "Check if tere is a deadline/schedule with repeater in this entry."
7935 (save-match-data
7936 (save-excursion
7937 (org-back-to-heading t)
7938 (if (re-search-forward
7939 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
7940 (match-string 1)))))
7942 (defvar org-last-changed-timestamp)
7943 (defvar org-log-post-message)
7944 (defvar org-log-note-purpose)
7945 (defvar org-log-note-how)
7946 (defun org-auto-repeat-maybe (done-word)
7947 "Check if the current headline contains a repeated deadline/schedule.
7948 If yes, set TODO state back to what it was and change the base date
7949 of repeating deadline/scheduled time stamps to new date.
7950 This function is run automatically after each state change to a DONE state."
7951 ;; last-state is dynamically scoped into this function
7952 (let* ((repeat (org-get-repeat))
7953 (aa (assoc last-state org-todo-kwd-alist))
7954 (interpret (nth 1 aa))
7955 (head (nth 2 aa))
7956 (whata '(("d" . day) ("m" . month) ("y" . year)))
7957 (msg "Entry repeats: ")
7958 (org-log-done nil)
7959 (org-todo-log-states nil)
7960 (nshiftmax 10) (nshift 0)
7961 re type n what ts mb0 time)
7962 (when repeat
7963 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
7964 (org-todo (if (eq interpret 'type) last-state head))
7965 (when org-log-repeat
7966 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
7967 (memq 'org-add-log-note post-command-hook))
7968 ;; OK, we are already setup for some record
7969 (if (eq org-log-repeat 'note)
7970 ;; make sure we take a note, not only a time stamp
7971 (setq org-log-note-how 'note))
7972 ;; Set up for taking a record
7973 (org-add-log-setup 'state (or done-word (car org-done-keywords))
7974 'findpos org-log-repeat)))
7975 (org-back-to-heading t)
7976 (org-add-planning-info nil nil 'closed)
7977 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
7978 org-deadline-time-regexp "\\)\\|\\("
7979 org-ts-regexp "\\)"))
7980 (while (re-search-forward
7981 re (save-excursion (outline-next-heading) (point)) t)
7982 (setq type (if (match-end 1) org-scheduled-string
7983 (if (match-end 3) org-deadline-string "Plain:"))
7984 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
7985 mb0 (match-beginning 0))
7986 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
7987 (setq n (string-to-number (match-string 2 ts))
7988 what (match-string 3 ts))
7989 (if (equal what "w") (setq n (* n 7) what "d"))
7990 ;; Preparation, see if we need to modify the start date for the change
7991 (when (match-end 1)
7992 (setq time (save-match-data (org-time-string-to-time ts)))
7993 (cond
7994 ((equal (match-string 1 ts) ".")
7995 ;; Shift starting date to today
7996 (org-timestamp-change
7997 (- (time-to-days (current-time)) (time-to-days time))
7998 'day))
7999 ((equal (match-string 1 ts) "+")
8000 (while (or (= nshift 0)
8001 (<= (time-to-days time) (time-to-days (current-time))))
8002 (when (= (incf nshift) nshiftmax)
8003 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8004 (error "Abort")))
8005 (org-timestamp-change n (cdr (assoc what whata)))
8006 (org-at-timestamp-p t)
8007 (setq ts (match-string 1))
8008 (setq time (save-match-data (org-time-string-to-time ts))))
8009 (org-timestamp-change (- n) (cdr (assoc what whata)))
8010 ;; rematch, so that we have everything in place for the real shift
8011 (org-at-timestamp-p t)
8012 (setq ts (match-string 1))
8013 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8014 (org-timestamp-change n (cdr (assoc what whata)))
8015 (setq msg (concat msg type org-last-changed-timestamp " "))))
8016 (setq org-log-post-message msg)
8017 (message "%s" msg))))
8019 (defun org-show-todo-tree (arg)
8020 "Make a compact tree which shows all headlines marked with TODO.
8021 The tree will show the lines where the regexp matches, and all higher
8022 headlines above the match.
8023 With a \\[universal-argument] prefix, also show the DONE entries.
8024 With a numeric prefix N, construct a sparse tree for the Nth element
8025 of `org-todo-keywords-1'."
8026 (interactive "P")
8027 (let ((case-fold-search nil)
8028 (kwd-re
8029 (cond ((null arg) org-not-done-regexp)
8030 ((equal arg '(4))
8031 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8032 (mapcar 'list org-todo-keywords-1))))
8033 (concat "\\("
8034 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8035 "\\)\\>")))
8036 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8037 (regexp-quote (nth (1- (prefix-numeric-value arg))
8038 org-todo-keywords-1)))
8039 (t (error "Invalid prefix argument: %s" arg)))))
8040 (message "%d TODO entries found"
8041 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8043 (defun org-deadline (&optional remove)
8044 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8045 With argument REMOVE, remove any deadline from the item."
8046 (interactive "P")
8047 (if remove
8048 (progn
8049 (org-remove-timestamp-with-keyword org-deadline-string)
8050 (message "Item no longer has a deadline."))
8051 (org-add-planning-info 'deadline nil 'closed)))
8053 (defun org-schedule (&optional remove)
8054 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8055 With argument REMOVE, remove any scheduling date from the item."
8056 (interactive "P")
8057 (if remove
8058 (progn
8059 (org-remove-timestamp-with-keyword org-scheduled-string)
8060 (message "Item is no longer scheduled."))
8061 (org-add-planning-info 'scheduled nil 'closed)))
8063 (defun org-remove-timestamp-with-keyword (keyword)
8064 "Remove all time stamps with KEYWORD in the current entry."
8065 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8066 beg)
8067 (save-excursion
8068 (org-back-to-heading t)
8069 (setq beg (point))
8070 (org-end-of-subtree t t)
8071 (while (re-search-backward re beg t)
8072 (replace-match "")
8073 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8074 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8076 (defun org-add-planning-info (what &optional time &rest remove)
8077 "Insert new timestamp with keyword in the line directly after the headline.
8078 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8079 If non is given, the user is prompted for a date.
8080 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8081 be removed."
8082 (interactive)
8083 (let (org-time-was-given org-end-time-was-given ts
8084 end default-time default-input)
8086 (when (and (not time) (memq what '(scheduled deadline)))
8087 ;; Try to get a default date/time from existing timestamp
8088 (save-excursion
8089 (org-back-to-heading t)
8090 (setq end (save-excursion (outline-next-heading) (point)))
8091 (when (re-search-forward (if (eq what 'scheduled)
8092 org-scheduled-time-regexp
8093 org-deadline-time-regexp)
8094 end t)
8095 (setq ts (match-string 1)
8096 default-time
8097 (apply 'encode-time (org-parse-time-string ts))
8098 default-input (and ts (org-get-compact-tod ts))))))
8099 (when what
8100 ;; If necessary, get the time from the user
8101 (setq time (or time (org-read-date nil 'to-time nil nil
8102 default-time default-input))))
8104 (when (and org-insert-labeled-timestamps-at-point
8105 (member what '(scheduled deadline)))
8106 (insert
8107 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8108 (org-insert-time-stamp time org-time-was-given
8109 nil nil nil (list org-end-time-was-given))
8110 (setq what nil))
8111 (save-excursion
8112 (save-restriction
8113 (let (col list elt ts buffer-invisibility-spec)
8114 (org-back-to-heading t)
8115 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8116 (goto-char (match-end 1))
8117 (setq col (current-column))
8118 (goto-char (match-end 0))
8119 (if (eobp) (insert "\n") (forward-char 1))
8120 (if (and (not (looking-at outline-regexp))
8121 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8122 "[^\r\n]*"))
8123 (not (equal (match-string 1) org-clock-string)))
8124 (narrow-to-region (match-beginning 0) (match-end 0))
8125 (insert-before-markers "\n")
8126 (backward-char 1)
8127 (narrow-to-region (point) (point))
8128 (indent-to-column col))
8129 ;; Check if we have to remove something.
8130 (setq list (cons what remove))
8131 (while list
8132 (setq elt (pop list))
8133 (goto-char (point-min))
8134 (when (or (and (eq elt 'scheduled)
8135 (re-search-forward org-scheduled-time-regexp nil t))
8136 (and (eq elt 'deadline)
8137 (re-search-forward org-deadline-time-regexp nil t))
8138 (and (eq elt 'closed)
8139 (re-search-forward org-closed-time-regexp nil t)))
8140 (replace-match "")
8141 (if (looking-at "--+<[^>]+>") (replace-match ""))
8142 (if (looking-at " +") (replace-match ""))))
8143 (goto-char (point-max))
8144 (when what
8145 (insert
8146 (if (not (equal (char-before) ?\ )) " " "")
8147 (cond ((eq what 'scheduled) org-scheduled-string)
8148 ((eq what 'deadline) org-deadline-string)
8149 ((eq what 'closed) org-closed-string))
8150 " ")
8151 (setq ts (org-insert-time-stamp
8152 time
8153 (or org-time-was-given
8154 (and (eq what 'closed) org-log-done-with-time))
8155 (eq what 'closed)
8156 nil nil (list org-end-time-was-given)))
8157 (end-of-line 1))
8158 (goto-char (point-min))
8159 (widen)
8160 (if (looking-at "[ \t]+\r?\n")
8161 (replace-match ""))
8162 ts)))))
8164 (defvar org-log-note-marker (make-marker))
8165 (defvar org-log-note-purpose nil)
8166 (defvar org-log-note-state nil)
8167 (defvar org-log-note-how nil)
8168 (defvar org-log-note-window-configuration nil)
8169 (defvar org-log-note-return-to (make-marker))
8170 (defvar org-log-post-message nil
8171 "Message to be displayed after a log note has been stored.
8172 The auto-repeater uses this.")
8174 (defun org-add-note ()
8175 "Add a note to the current entry.
8176 This is done in the same way as adding a state change note."
8177 (interactive)
8178 (org-add-log-setup 'note nil t nil))
8180 (defun org-add-log-setup (&optional purpose state findpos how)
8181 "Set up the post command hook to take a note.
8182 If this is about to TODO state change, the new state is expected in STATE.
8183 When FINDPOS is non-nil, find the correct position for the note in
8184 the current entry. If not, assume that it can be inserted at point."
8185 (save-excursion
8186 (when findpos
8187 (org-back-to-heading t)
8188 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8189 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8190 "[^\r\n]*\\)?"))
8191 (goto-char (match-end 0))
8192 (unless org-log-states-order-reversed
8193 (and (= (char-after) ?\n) (forward-char 1))
8194 (org-skip-over-state-notes)
8195 (skip-chars-backward " \t\n\r")))
8196 (move-marker org-log-note-marker (point))
8197 (setq org-log-note-purpose purpose
8198 org-log-note-state state
8199 org-log-note-how how)
8200 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8202 (defun org-skip-over-state-notes ()
8203 "Skip past the list of State notes in an entry."
8204 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8205 (while (looking-at "[ \t]*- State")
8206 (condition-case nil
8207 (org-next-item)
8208 (error (org-end-of-item)))))
8210 (defun org-add-log-note (&optional purpose)
8211 "Pop up a window for taking a note, and add this note later at point."
8212 (remove-hook 'post-command-hook 'org-add-log-note)
8213 (setq org-log-note-window-configuration (current-window-configuration))
8214 (delete-other-windows)
8215 (move-marker org-log-note-return-to (point))
8216 (switch-to-buffer (marker-buffer org-log-note-marker))
8217 (goto-char org-log-note-marker)
8218 (org-switch-to-buffer-other-window "*Org Note*")
8219 (erase-buffer)
8220 (if (memq org-log-note-how '(time state))
8221 (org-store-log-note)
8222 (let ((org-inhibit-startup t)) (org-mode))
8223 (insert (format "# Insert note for %s.
8224 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8225 (cond
8226 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8227 ((eq org-log-note-purpose 'done) "closed todo item")
8228 ((eq org-log-note-purpose 'state)
8229 (format "state change to \"%s\"" org-log-note-state))
8230 ((eq org-log-note-purpose 'note)
8231 "this entry")
8232 (t (error "This should not happen")))))
8233 (org-set-local 'org-finish-function 'org-store-log-note)))
8235 (defvar org-note-abort nil) ; dynamically scoped
8236 (defun org-store-log-note ()
8237 "Finish taking a log note, and insert it to where it belongs."
8238 (let ((txt (buffer-string))
8239 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8240 lines ind)
8241 (kill-buffer (current-buffer))
8242 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8243 (setq txt (replace-match "" t t txt)))
8244 (if (string-match "\\s-+\\'" txt)
8245 (setq txt (replace-match "" t t txt)))
8246 (setq lines (org-split-string txt "\n"))
8247 (when (and note (string-match "\\S-" note))
8248 (setq note
8249 (org-replace-escapes
8250 note
8251 (list (cons "%u" (user-login-name))
8252 (cons "%U" user-full-name)
8253 (cons "%t" (format-time-string
8254 (org-time-stamp-format 'long 'inactive)
8255 (current-time)))
8256 (cons "%s" (if org-log-note-state
8257 (concat "\"" org-log-note-state "\"")
8258 "")))))
8259 (if lines (setq note (concat note " \\\\")))
8260 (push note lines))
8261 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8262 (when lines
8263 (save-excursion
8264 (set-buffer (marker-buffer org-log-note-marker))
8265 (save-excursion
8266 (goto-char org-log-note-marker)
8267 (move-marker org-log-note-marker nil)
8268 (end-of-line 1)
8269 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8270 (indent-relative nil)
8271 (insert "- " (pop lines))
8272 (org-indent-line-function)
8273 (beginning-of-line 1)
8274 (looking-at "[ \t]*")
8275 (setq ind (concat (match-string 0) " "))
8276 (end-of-line 1)
8277 (while lines (insert "\n" ind (pop lines)))))))
8278 (set-window-configuration org-log-note-window-configuration)
8279 (with-current-buffer (marker-buffer org-log-note-return-to)
8280 (goto-char org-log-note-return-to))
8281 (move-marker org-log-note-return-to nil)
8282 (and org-log-post-message (message "%s" org-log-post-message)))
8284 (defun org-sparse-tree (&optional arg)
8285 "Create a sparse tree, prompt for the details.
8286 This command can create sparse trees. You first need to select the type
8287 of match used to create the tree:
8289 t Show entries with a specific TODO keyword.
8290 T Show entries selected by a tags match.
8291 p Enter a property name and its value (both with completion on existing
8292 names/values) and show entries with that property.
8293 r Show entries matching a regular expression
8294 d Show deadlines due within `org-deadline-warning-days'."
8295 (interactive "P")
8296 (let (ans kwd value)
8297 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8298 (setq ans (read-char-exclusive))
8299 (cond
8300 ((equal ans ?d)
8301 (call-interactively 'org-check-deadlines))
8302 ((equal ans ?b)
8303 (call-interactively 'org-check-before-date))
8304 ((equal ans ?t)
8305 (org-show-todo-tree '(4)))
8306 ((equal ans ?T)
8307 (call-interactively 'org-tags-sparse-tree))
8308 ((member ans '(?p ?P))
8309 (setq kwd (completing-read "Property: "
8310 (mapcar 'list (org-buffer-property-keys))))
8311 (setq value (completing-read "Value: "
8312 (mapcar 'list (org-property-values kwd))))
8313 (unless (string-match "\\`{.*}\\'" value)
8314 (setq value (concat "\"" value "\"")))
8315 (org-tags-sparse-tree arg (concat kwd "=" value)))
8316 ((member ans '(?r ?R ?/))
8317 (call-interactively 'org-occur))
8318 (t (error "No such sparse tree command \"%c\"" ans)))))
8320 (defvar org-occur-highlights nil
8321 "List of overlays used for occur matches.")
8322 (make-variable-buffer-local 'org-occur-highlights)
8323 (defvar org-occur-parameters nil
8324 "Parameters of the active org-occur calls.
8325 This is a list, each call to org-occur pushes as cons cell,
8326 containing the regular expression and the callback, onto the list.
8327 The list can contain several entries if `org-occur' has been called
8328 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8329 will only contain one set of parameters. When the highlights are
8330 removed (for example with `C-c C-c', or with the next edit (depending
8331 on `org-remove-highlights-with-change'), this variable is emptied
8332 as well.")
8333 (make-variable-buffer-local 'org-occur-parameters)
8335 (defun org-occur (regexp &optional keep-previous callback)
8336 "Make a compact tree which shows all matches of REGEXP.
8337 The tree will show the lines where the regexp matches, and all higher
8338 headlines above the match. It will also show the heading after the match,
8339 to make sure editing the matching entry is easy.
8340 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8341 call to `org-occur' will be kept, to allow stacking of calls to this
8342 command.
8343 If CALLBACK is non-nil, it is a function which is called to confirm
8344 that the match should indeed be shown."
8345 (interactive "sRegexp: \nP")
8346 (unless keep-previous
8347 (org-remove-occur-highlights nil nil t))
8348 (push (cons regexp callback) org-occur-parameters)
8349 (let ((cnt 0))
8350 (save-excursion
8351 (goto-char (point-min))
8352 (if (or (not keep-previous) ; do not want to keep
8353 (not org-occur-highlights)) ; no previous matches
8354 ;; hide everything
8355 (org-overview))
8356 (while (re-search-forward regexp nil t)
8357 (when (or (not callback)
8358 (save-match-data (funcall callback)))
8359 (setq cnt (1+ cnt))
8360 (when org-highlight-sparse-tree-matches
8361 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8362 (org-show-context 'occur-tree))))
8363 (when org-remove-highlights-with-change
8364 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8365 nil 'local))
8366 (unless org-sparse-tree-open-archived-trees
8367 (org-hide-archived-subtrees (point-min) (point-max)))
8368 (run-hooks 'org-occur-hook)
8369 (if (interactive-p)
8370 (message "%d match(es) for regexp %s" cnt regexp))
8371 cnt))
8373 (defun org-show-context (&optional key)
8374 "Make sure point and context and visible.
8375 How much context is shown depends upon the variables
8376 `org-show-hierarchy-above', `org-show-following-heading'. and
8377 `org-show-siblings'."
8378 (let ((heading-p (org-on-heading-p t))
8379 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8380 (following-p (org-get-alist-option org-show-following-heading key))
8381 (entry-p (org-get-alist-option org-show-entry-below key))
8382 (siblings-p (org-get-alist-option org-show-siblings key)))
8383 (catch 'exit
8384 ;; Show heading or entry text
8385 (if (and heading-p (not entry-p))
8386 (org-flag-heading nil) ; only show the heading
8387 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8388 (org-show-hidden-entry))) ; show entire entry
8389 (when following-p
8390 ;; Show next sibling, or heading below text
8391 (save-excursion
8392 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8393 (org-flag-heading nil))))
8394 (when siblings-p (org-show-siblings))
8395 (when hierarchy-p
8396 ;; show all higher headings, possibly with siblings
8397 (save-excursion
8398 (while (and (condition-case nil
8399 (progn (org-up-heading-all 1) t)
8400 (error nil))
8401 (not (bobp)))
8402 (org-flag-heading nil)
8403 (when siblings-p (org-show-siblings))))))))
8405 (defun org-reveal (&optional siblings)
8406 "Show current entry, hierarchy above it, and the following headline.
8407 This can be used to show a consistent set of context around locations
8408 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8409 not t for the search context.
8411 With optional argument SIBLINGS, on each level of the hierarchy all
8412 siblings are shown. This repairs the tree structure to what it would
8413 look like when opened with hierarchical calls to `org-cycle'."
8414 (interactive "P")
8415 (let ((org-show-hierarchy-above t)
8416 (org-show-following-heading t)
8417 (org-show-siblings (if siblings t org-show-siblings)))
8418 (org-show-context nil)))
8420 (defun org-highlight-new-match (beg end)
8421 "Highlight from BEG to END and mark the highlight is an occur headline."
8422 (let ((ov (org-make-overlay beg end)))
8423 (org-overlay-put ov 'face 'secondary-selection)
8424 (push ov org-occur-highlights)))
8426 (defun org-remove-occur-highlights (&optional beg end noremove)
8427 "Remove the occur highlights from the buffer.
8428 BEG and END are ignored. If NOREMOVE is nil, remove this function
8429 from the `before-change-functions' in the current buffer."
8430 (interactive)
8431 (unless org-inhibit-highlight-removal
8432 (mapc 'org-delete-overlay org-occur-highlights)
8433 (setq org-occur-highlights nil)
8434 (setq org-occur-parameters nil)
8435 (unless noremove
8436 (remove-hook 'before-change-functions
8437 'org-remove-occur-highlights 'local))))
8439 ;;;; Priorities
8441 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8442 "Regular expression matching the priority indicator.")
8444 (defvar org-remove-priority-next-time nil)
8446 (defun org-priority-up ()
8447 "Increase the priority of the current item."
8448 (interactive)
8449 (org-priority 'up))
8451 (defun org-priority-down ()
8452 "Decrease the priority of the current item."
8453 (interactive)
8454 (org-priority 'down))
8456 (defun org-priority (&optional action)
8457 "Change the priority of an item by ARG.
8458 ACTION can be `set', `up', `down', or a character."
8459 (interactive)
8460 (setq action (or action 'set))
8461 (let (current new news have remove)
8462 (save-excursion
8463 (org-back-to-heading)
8464 (if (looking-at org-priority-regexp)
8465 (setq current (string-to-char (match-string 2))
8466 have t)
8467 (setq current org-default-priority))
8468 (cond
8469 ((or (eq action 'set) (integerp action))
8470 (if (integerp action)
8471 (setq new action)
8472 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
8473 (setq new (read-char-exclusive)))
8474 (if (and (= (upcase org-highest-priority) org-highest-priority)
8475 (= (upcase org-lowest-priority) org-lowest-priority))
8476 (setq new (upcase new)))
8477 (cond ((equal new ?\ ) (setq remove t))
8478 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8479 (error "Priority must be between `%c' and `%c'"
8480 org-highest-priority org-lowest-priority))))
8481 ((eq action 'up)
8482 (if (and (not have) (eq last-command this-command))
8483 (setq new org-lowest-priority)
8484 (setq new (if (and org-priority-start-cycle-with-default (not have))
8485 org-default-priority (1- current)))))
8486 ((eq action 'down)
8487 (if (and (not have) (eq last-command this-command))
8488 (setq new org-highest-priority)
8489 (setq new (if (and org-priority-start-cycle-with-default (not have))
8490 org-default-priority (1+ current)))))
8491 (t (error "Invalid action")))
8492 (if (or (< (upcase new) org-highest-priority)
8493 (> (upcase new) org-lowest-priority))
8494 (setq remove t))
8495 (setq news (format "%c" new))
8496 (if have
8497 (if remove
8498 (replace-match "" t t nil 1)
8499 (replace-match news t t nil 2))
8500 (if remove
8501 (error "No priority cookie found in line")
8502 (looking-at org-todo-line-regexp)
8503 (if (match-end 2)
8504 (progn
8505 (goto-char (match-end 2))
8506 (insert " [#" news "]"))
8507 (goto-char (match-beginning 3))
8508 (insert "[#" news "] ")))))
8509 (org-preserve-lc (org-set-tags nil 'align))
8510 (if remove
8511 (message "Priority removed")
8512 (message "Priority of current item set to %s" news))))
8515 (defun org-get-priority (s)
8516 "Find priority cookie and return priority."
8517 (save-match-data
8518 (if (not (string-match org-priority-regexp s))
8519 (* 1000 (- org-lowest-priority org-default-priority))
8520 (* 1000 (- org-lowest-priority
8521 (string-to-char (match-string 2 s)))))))
8523 ;;;; Tags
8525 (defun org-scan-tags (action matcher &optional todo-only)
8526 "Scan headline tags with inheritance and produce output ACTION.
8527 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8528 evaluated, testing if a given set of tags qualifies a headline for
8529 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8530 are included in the output."
8531 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8532 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8533 (org-re
8534 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8535 (props (list 'face nil
8536 'done-face 'org-done
8537 'undone-face nil
8538 'mouse-face 'highlight
8539 'org-not-done-regexp org-not-done-regexp
8540 'org-todo-regexp org-todo-regexp
8541 'keymap org-agenda-keymap
8542 'help-echo
8543 (format "mouse-2 or RET jump to org file %s"
8544 (abbreviate-file-name
8545 (or (buffer-file-name (buffer-base-buffer))
8546 (buffer-name (buffer-base-buffer)))))))
8547 (case-fold-search nil)
8548 lspos
8549 tags tags-list tags-alist (llast 0) rtn level category i txt
8550 todo marker entry priority)
8551 (save-excursion
8552 (goto-char (point-min))
8553 (when (eq action 'sparse-tree)
8554 (org-overview)
8555 (org-remove-occur-highlights))
8556 (while (re-search-forward re nil t)
8557 (catch :skip
8558 (setq todo (if (match-end 1) (match-string 2))
8559 tags (if (match-end 4) (match-string 4)))
8560 (goto-char (setq lspos (1+ (match-beginning 0))))
8561 (setq level (org-reduced-level (funcall outline-level))
8562 category (org-get-category))
8563 (setq i llast llast level)
8564 ;; remove tag lists from same and sublevels
8565 (while (>= i level)
8566 (when (setq entry (assoc i tags-alist))
8567 (setq tags-alist (delete entry tags-alist)))
8568 (setq i (1- i)))
8569 ;; add the next tags
8570 (when tags
8571 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8572 tags-alist
8573 (cons (cons level tags) tags-alist)))
8574 ;; compile tags for current headline
8575 (setq tags-list
8576 (if org-use-tag-inheritance
8577 (apply 'append (mapcar 'cdr tags-alist))
8578 tags))
8579 (when (and tags org-use-tag-inheritance
8580 (not (eq t org-use-tag-inheritance)))
8581 ;; selective inheritance, remove uninherited ones
8582 (setcdr (car tags-alist)
8583 (org-remove-uniherited-tags (cdar tags-alist))))
8584 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8585 (eval matcher)
8586 (or (not org-agenda-skip-archived-trees)
8587 (not (member org-archive-tag tags-list))))
8588 (and (eq action 'agenda) (org-agenda-skip))
8589 ;; list this headline
8591 (if (eq action 'sparse-tree)
8592 (progn
8593 (and org-highlight-sparse-tree-matches
8594 (org-get-heading) (match-end 0)
8595 (org-highlight-new-match
8596 (match-beginning 0) (match-beginning 1)))
8597 (org-show-context 'tags-tree))
8598 (setq txt (org-format-agenda-item
8600 (concat
8601 (if org-tags-match-list-sublevels
8602 (make-string (1- level) ?.) "")
8603 (org-get-heading))
8604 category tags-list)
8605 priority (org-get-priority txt))
8606 (goto-char lspos)
8607 (setq marker (org-agenda-new-marker))
8608 (org-add-props txt props
8609 'org-marker marker 'org-hd-marker marker 'org-category category
8610 'priority priority 'type "tagsmatch")
8611 (push txt rtn))
8612 ;; if we are to skip sublevels, jump to end of subtree
8613 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8614 (when (and (eq action 'sparse-tree)
8615 (not org-sparse-tree-open-archived-trees))
8616 (org-hide-archived-subtrees (point-min) (point-max)))
8617 (nreverse rtn)))
8619 (defun org-remove-uniherited-tags (tags)
8620 "Remove all tags that are not inherited from the list TAGS."
8621 (cond
8622 ((eq org-use-tag-inheritance t) tags)
8623 ((not org-use-tag-inheritance) nil)
8624 ((stringp org-use-tag-inheritance)
8625 (delq nil (mapcar
8626 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8627 tags)))
8628 ((listp org-use-tag-inheritance)
8629 (org-delete-all org-use-tag-inheritance tags))))
8631 (defvar todo-only) ;; dynamically scoped
8633 (defun org-tags-sparse-tree (&optional todo-only match)
8634 "Create a sparse tree according to tags string MATCH.
8635 MATCH can contain positive and negative selection of tags, like
8636 \"+WORK+URGENT-WITHBOSS\".
8637 If optional argument TODO_ONLY is non-nil, only select lines that are
8638 also TODO lines."
8639 (interactive "P")
8640 (org-prepare-agenda-buffers (list (current-buffer)))
8641 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8643 (defvar org-cached-props nil)
8644 (defun org-cached-entry-get (pom property)
8645 (if (or (eq t org-use-property-inheritance)
8646 (and (stringp org-use-property-inheritance)
8647 (string-match org-use-property-inheritance property))
8648 (and (listp org-use-property-inheritance)
8649 (member property org-use-property-inheritance)))
8650 ;; Caching is not possible, check it directly
8651 (org-entry-get pom property 'inherit)
8652 ;; Get all properties, so that we can do complicated checks easily
8653 (cdr (assoc property (or org-cached-props
8654 (setq org-cached-props
8655 (org-entry-properties pom)))))))
8657 (defun org-global-tags-completion-table (&optional files)
8658 "Return the list of all tags in all agenda buffer/files."
8659 (save-excursion
8660 (org-uniquify
8661 (delq nil
8662 (apply 'append
8663 (mapcar
8664 (lambda (file)
8665 (set-buffer (find-file-noselect file))
8666 (append (org-get-buffer-tags)
8667 (mapcar (lambda (x) (if (stringp (car-safe x))
8668 (list (car-safe x)) nil))
8669 org-tag-alist)))
8670 (if (and files (car files))
8671 files
8672 (org-agenda-files))))))))
8674 (defun org-make-tags-matcher (match)
8675 "Create the TAGS//TODO matcher form for the selection string MATCH."
8676 ;; todo-only is scoped dynamically into this function, and the function
8677 ;; may change it it the matcher asksk for it.
8678 (unless match
8679 ;; Get a new match request, with completion
8680 (let ((org-last-tags-completion-table
8681 (org-global-tags-completion-table)))
8682 (setq match (completing-read
8683 "Match: " 'org-tags-completion-function nil nil nil
8684 'org-tags-history))))
8686 ;; Parse the string and create a lisp form
8687 (let ((match0 match)
8688 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
8689 minus tag mm
8690 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8691 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
8692 (if (string-match "/+" match)
8693 ;; match contains also a todo-matching request
8694 (progn
8695 (setq tagsmatch (substring match 0 (match-beginning 0))
8696 todomatch (substring match (match-end 0)))
8697 (if (string-match "^!" todomatch)
8698 (setq todo-only t todomatch (substring todomatch 1)))
8699 (if (string-match "^\\s-*$" todomatch)
8700 (setq todomatch nil)))
8701 ;; only matching tags
8702 (setq tagsmatch match todomatch nil))
8704 ;; Make the tags matcher
8705 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8706 (setq tagsmatcher t)
8707 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8708 (while (setq term (pop orterms))
8709 (while (and (equal (substring term -1) "\\") orterms)
8710 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8711 (while (string-match re term)
8712 (setq minus (and (match-end 1)
8713 (equal (match-string 1 term) "-"))
8714 tag (match-string 2 term)
8715 re-p (equal (string-to-char tag) ?{)
8716 level-p (match-end 3)
8717 prop-p (match-end 4)
8718 mm (cond
8719 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8720 (level-p `(= level ,(string-to-number
8721 (match-string 3 term))))
8722 (prop-p
8723 (setq pn (match-string 4 term)
8724 pv (match-string 5 term)
8725 cat-p (equal pn "CATEGORY")
8726 re-p (equal (string-to-char pv) ?{)
8727 pv (substring pv 1 -1))
8728 (if (equal pn "CATEGORY")
8729 (setq gv '(get-text-property (point) 'org-category))
8730 (setq gv `(org-cached-entry-get nil ,pn)))
8731 (if re-p
8732 `(string-match ,pv (or ,gv ""))
8733 `(equal ,pv (or ,gv ""))))
8734 (t `(member ,(downcase tag) tags-list)))
8735 mm (if minus (list 'not mm) mm)
8736 term (substring term (match-end 0)))
8737 (push mm tagsmatcher))
8738 (push (if (> (length tagsmatcher) 1)
8739 (cons 'and tagsmatcher)
8740 (car tagsmatcher))
8741 orlist)
8742 (setq tagsmatcher nil))
8743 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8744 (setq tagsmatcher
8745 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8747 ;; Make the todo matcher
8748 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8749 (setq todomatcher t)
8750 (setq orterms (org-split-string todomatch "|") orlist nil)
8751 (while (setq term (pop orterms))
8752 (while (string-match re term)
8753 (setq minus (and (match-end 1)
8754 (equal (match-string 1 term) "-"))
8755 kwd (match-string 2 term)
8756 re-p (equal (string-to-char kwd) ?{)
8757 term (substring term (match-end 0))
8758 mm (if re-p
8759 `(string-match ,(substring kwd 1 -1) todo)
8760 (list 'equal 'todo kwd))
8761 mm (if minus (list 'not mm) mm))
8762 (push mm todomatcher))
8763 (push (if (> (length todomatcher) 1)
8764 (cons 'and todomatcher)
8765 (car todomatcher))
8766 orlist)
8767 (setq todomatcher nil))
8768 (setq todomatcher (if (> (length orlist) 1)
8769 (cons 'or orlist) (car orlist))))
8771 ;; Return the string and lisp forms of the matcher
8772 (setq matcher (if todomatcher
8773 (list 'and tagsmatcher todomatcher)
8774 tagsmatcher))
8775 (cons match0 matcher)))
8777 (defun org-match-any-p (re list)
8778 "Does re match any element of list?"
8779 (setq list (mapcar (lambda (x) (string-match re x)) list))
8780 (delq nil list))
8782 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8783 (defvar org-tags-overlay (org-make-overlay 1 1))
8784 (org-detach-overlay org-tags-overlay)
8786 (defun org-get-tags-at (&optional pos)
8787 "Get a list of all headline tags applicable at POS.
8788 POS defaults to point. If tags are inherited, the list contains
8789 the targets in the same sequence as the headlines appear, i.e.
8790 sthe tags of the current headline come last."
8791 (interactive)
8792 (let (tags ltags lastpos parent)
8793 (save-excursion
8794 (save-restriction
8795 (widen)
8796 (goto-char (or pos (point)))
8797 (save-match-data
8798 (condition-case nil
8799 (progn
8800 (org-back-to-heading t)
8801 (while (not (equal lastpos (point)))
8802 (setq lastpos (point))
8803 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8804 (setq ltags (org-split-string
8805 (org-match-string-no-properties 1) ":"))
8806 (setq tags (append (org-remove-uniherited-tags ltags)
8807 tags)))
8808 (or org-use-tag-inheritance (error ""))
8809 (org-up-heading-all 1)
8810 (setq parent t)))
8811 (error nil))))
8812 tags)))
8814 (defun org-toggle-tag (tag &optional onoff)
8815 "Toggle the tag TAG for the current line.
8816 If ONOFF is `on' or `off', don't toggle but set to this state."
8817 (unless (org-on-heading-p t) (error "Not on headling"))
8818 (let (res current)
8819 (save-excursion
8820 (beginning-of-line)
8821 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8822 (point-at-eol) t)
8823 (progn
8824 (setq current (match-string 1))
8825 (replace-match ""))
8826 (setq current ""))
8827 (setq current (nreverse (org-split-string current ":")))
8828 (cond
8829 ((eq onoff 'on)
8830 (setq res t)
8831 (or (member tag current) (push tag current)))
8832 ((eq onoff 'off)
8833 (or (not (member tag current)) (setq current (delete tag current))))
8834 (t (if (member tag current)
8835 (setq current (delete tag current))
8836 (setq res t)
8837 (push tag current))))
8838 (end-of-line 1)
8839 (if current
8840 (progn
8841 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8842 (org-set-tags nil t))
8843 (delete-horizontal-space))
8844 (run-hooks 'org-after-tags-change-hook))
8845 res))
8847 (defun org-align-tags-here (to-col)
8848 ;; Assumes that this is a headline
8849 (let ((pos (point)) (col (current-column)) tags)
8850 (beginning-of-line 1)
8851 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8852 (< pos (match-beginning 2)))
8853 (progn
8854 (setq tags (match-string 2))
8855 (goto-char (match-beginning 1))
8856 (insert " ")
8857 (delete-region (point) (1+ (match-end 0)))
8858 (backward-char 1)
8859 (move-to-column
8860 (max (1+ (current-column))
8861 (1+ col)
8862 (if (> to-col 0)
8863 to-col
8864 (- (abs to-col) (length tags))))
8866 (insert tags)
8867 (move-to-column (min (current-column) col) t))
8868 (goto-char pos))))
8870 (defun org-set-tags (&optional arg just-align)
8871 "Set the tags for the current headline.
8872 With prefix ARG, realign all tags in headings in the current buffer."
8873 (interactive "P")
8874 (let* ((re (concat "^" outline-regexp))
8875 (current (org-get-tags-string))
8876 (col (current-column))
8877 (org-setting-tags t)
8878 table current-tags inherited-tags ; computed below when needed
8879 tags p0 c0 c1 rpl)
8880 (if arg
8881 (save-excursion
8882 (goto-char (point-min))
8883 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8884 (while (re-search-forward re nil t)
8885 (org-set-tags nil t)
8886 (end-of-line 1)))
8887 (message "All tags realigned to column %d" org-tags-column))
8888 (if just-align
8889 (setq tags current)
8890 ;; Get a new set of tags from the user
8891 (save-excursion
8892 (setq table (or org-tag-alist (org-get-buffer-tags))
8893 org-last-tags-completion-table table
8894 current-tags (org-split-string current ":")
8895 inherited-tags (nreverse
8896 (nthcdr (length current-tags)
8897 (nreverse (org-get-tags-at))))
8898 tags
8899 (if (or (eq t org-use-fast-tag-selection)
8900 (and org-use-fast-tag-selection
8901 (delq nil (mapcar 'cdr table))))
8902 (org-fast-tag-selection
8903 current-tags inherited-tags table
8904 (if org-fast-tag-selection-include-todo org-todo-key-alist))
8905 (let ((org-add-colon-after-tag-completion t))
8906 (org-trim
8907 (org-without-partial-completion
8908 (completing-read "Tags: " 'org-tags-completion-function
8909 nil nil current 'org-tags-history)))))))
8910 (while (string-match "[-+&]+" tags)
8911 ;; No boolean logic, just a list
8912 (setq tags (replace-match ":" t t tags))))
8914 (if (string-match "\\`[\t ]*\\'" tags)
8915 (setq tags "")
8916 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8917 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8919 ;; Insert new tags at the correct column
8920 (beginning-of-line 1)
8921 (cond
8922 ((and (equal current "") (equal tags "")))
8923 ((re-search-forward
8924 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
8925 (point-at-eol) t)
8926 (if (equal tags "")
8927 (setq rpl "")
8928 (goto-char (match-beginning 0))
8929 (setq c0 (current-column) p0 (point)
8930 c1 (max (1+ c0) (if (> org-tags-column 0)
8931 org-tags-column
8932 (- (- org-tags-column) (length tags))))
8933 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
8934 (replace-match rpl t t)
8935 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
8936 tags)
8937 (t (error "Tags alignment failed")))
8938 (move-to-column col)
8939 (unless just-align
8940 (run-hooks 'org-after-tags-change-hook)))))
8942 (defun org-change-tag-in-region (beg end tag off)
8943 "Add or remove TAG for each entry in the region.
8944 This works in the agenda, and also in an org-mode buffer."
8945 (interactive
8946 (list (region-beginning) (region-end)
8947 (let ((org-last-tags-completion-table
8948 (if (org-mode-p)
8949 (org-get-buffer-tags)
8950 (org-global-tags-completion-table))))
8951 (completing-read
8952 "Tag: " 'org-tags-completion-function nil nil nil
8953 'org-tags-history))
8954 (progn
8955 (message "[s]et or [r]emove? ")
8956 (equal (read-char-exclusive) ?r))))
8957 (if (fboundp 'deactivate-mark) (deactivate-mark))
8958 (let ((agendap (equal major-mode 'org-agenda-mode))
8959 l1 l2 m buf pos newhead (cnt 0))
8960 (goto-char end)
8961 (setq l2 (1- (org-current-line)))
8962 (goto-char beg)
8963 (setq l1 (org-current-line))
8964 (loop for l from l1 to l2 do
8965 (goto-line l)
8966 (setq m (get-text-property (point) 'org-hd-marker))
8967 (when (or (and (org-mode-p) (org-on-heading-p))
8968 (and agendap m))
8969 (setq buf (if agendap (marker-buffer m) (current-buffer))
8970 pos (if agendap m (point)))
8971 (with-current-buffer buf
8972 (save-excursion
8973 (save-restriction
8974 (goto-char pos)
8975 (setq cnt (1+ cnt))
8976 (org-toggle-tag tag (if off 'off 'on))
8977 (setq newhead (org-get-heading)))))
8978 (and agendap (org-agenda-change-all-lines newhead m))))
8979 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
8981 (defun org-tags-completion-function (string predicate &optional flag)
8982 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8983 (confirm (lambda (x) (stringp (car x)))))
8984 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8985 (setq s1 (match-string 1 string)
8986 s2 (match-string 2 string))
8987 (setq s1 "" s2 string))
8988 (cond
8989 ((eq flag nil)
8990 ;; try completion
8991 (setq rtn (try-completion s2 ctable confirm))
8992 (if (stringp rtn)
8993 (setq rtn
8994 (concat s1 s2 (substring rtn (length s2))
8995 (if (and org-add-colon-after-tag-completion
8996 (assoc rtn ctable))
8997 ":" ""))))
8998 rtn)
8999 ((eq flag t)
9000 ;; all-completions
9001 (all-completions s2 ctable confirm)
9003 ((eq flag 'lambda)
9004 ;; exact match?
9005 (assoc s2 ctable)))
9008 (defun org-fast-tag-insert (kwd tags face &optional end)
9009 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9010 (insert (format "%-12s" (concat kwd ":"))
9011 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9012 (or end "")))
9014 (defun org-fast-tag-show-exit (flag)
9015 (save-excursion
9016 (goto-line 3)
9017 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9018 (replace-match ""))
9019 (when flag
9020 (end-of-line 1)
9021 (move-to-column (- (window-width) 19) t)
9022 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9024 (defun org-set-current-tags-overlay (current prefix)
9025 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9026 (if (featurep 'xemacs)
9027 (org-overlay-display org-tags-overlay (concat prefix s)
9028 'secondary-selection)
9029 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9030 (org-overlay-display org-tags-overlay (concat prefix s)))))
9032 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9033 "Fast tag selection with single keys.
9034 CURRENT is the current list of tags in the headline, INHERITED is the
9035 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9036 possibly with grouping information. TODO-TABLE is a similar table with
9037 TODO keywords, should these have keys assigned to them.
9038 If the keys are nil, a-z are automatically assigned.
9039 Returns the new tags string, or nil to not change the current settings."
9040 (let* ((fulltable (append table todo-table))
9041 (maxlen (apply 'max (mapcar
9042 (lambda (x)
9043 (if (stringp (car x)) (string-width (car x)) 0))
9044 fulltable)))
9045 (buf (current-buffer))
9046 (expert (eq org-fast-tag-selection-single-key 'expert))
9047 (buffer-tags nil)
9048 (fwidth (+ maxlen 3 1 3))
9049 (ncol (/ (- (window-width) 4) fwidth))
9050 (i-face 'org-done)
9051 (c-face 'org-todo)
9052 tg cnt e c char c1 c2 ntable tbl rtn
9053 ov-start ov-end ov-prefix
9054 (exit-after-next org-fast-tag-selection-single-key)
9055 (done-keywords org-done-keywords)
9056 groups ingroup)
9057 (save-excursion
9058 (beginning-of-line 1)
9059 (if (looking-at
9060 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9061 (setq ov-start (match-beginning 1)
9062 ov-end (match-end 1)
9063 ov-prefix "")
9064 (setq ov-start (1- (point-at-eol))
9065 ov-end (1+ ov-start))
9066 (skip-chars-forward "^\n\r")
9067 (setq ov-prefix
9068 (concat
9069 (buffer-substring (1- (point)) (point))
9070 (if (> (current-column) org-tags-column)
9072 (make-string (- org-tags-column (current-column)) ?\ ))))))
9073 (org-move-overlay org-tags-overlay ov-start ov-end)
9074 (save-window-excursion
9075 (if expert
9076 (set-buffer (get-buffer-create " *Org tags*"))
9077 (delete-other-windows)
9078 (split-window-vertically)
9079 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9080 (erase-buffer)
9081 (org-set-local 'org-done-keywords done-keywords)
9082 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9083 (org-fast-tag-insert "Current" current c-face "\n\n")
9084 (org-fast-tag-show-exit exit-after-next)
9085 (org-set-current-tags-overlay current ov-prefix)
9086 (setq tbl fulltable char ?a cnt 0)
9087 (while (setq e (pop tbl))
9088 (cond
9089 ((equal e '(:startgroup))
9090 (push '() groups) (setq ingroup t)
9091 (when (not (= cnt 0))
9092 (setq cnt 0)
9093 (insert "\n"))
9094 (insert "{ "))
9095 ((equal e '(:endgroup))
9096 (setq ingroup nil cnt 0)
9097 (insert "}\n"))
9099 (setq tg (car e) c2 nil)
9100 (if (cdr e)
9101 (setq c (cdr e))
9102 ;; automatically assign a character.
9103 (setq c1 (string-to-char
9104 (downcase (substring
9105 tg (if (= (string-to-char tg) ?@) 1 0)))))
9106 (if (or (rassoc c1 ntable) (rassoc c1 table))
9107 (while (or (rassoc char ntable) (rassoc char table))
9108 (setq char (1+ char)))
9109 (setq c2 c1))
9110 (setq c (or c2 char)))
9111 (if ingroup (push tg (car groups)))
9112 (setq tg (org-add-props tg nil 'face
9113 (cond
9114 ((not (assoc tg table))
9115 (org-get-todo-face tg))
9116 ((member tg current) c-face)
9117 ((member tg inherited) i-face)
9118 (t nil))))
9119 (if (and (= cnt 0) (not ingroup)) (insert " "))
9120 (insert "[" c "] " tg (make-string
9121 (- fwidth 4 (length tg)) ?\ ))
9122 (push (cons tg c) ntable)
9123 (when (= (setq cnt (1+ cnt)) ncol)
9124 (insert "\n")
9125 (if ingroup (insert " "))
9126 (setq cnt 0)))))
9127 (setq ntable (nreverse ntable))
9128 (insert "\n")
9129 (goto-char (point-min))
9130 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9131 (fit-window-to-buffer))
9132 (setq rtn
9133 (catch 'exit
9134 (while t
9135 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9136 (if groups " [!] no groups" " [!]groups")
9137 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9138 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9139 (cond
9140 ((= c ?\r) (throw 'exit t))
9141 ((= c ?!)
9142 (setq groups (not groups))
9143 (goto-char (point-min))
9144 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9145 ((= c ?\C-c)
9146 (if (not expert)
9147 (org-fast-tag-show-exit
9148 (setq exit-after-next (not exit-after-next)))
9149 (setq expert nil)
9150 (delete-other-windows)
9151 (split-window-vertically)
9152 (org-switch-to-buffer-other-window " *Org tags*")
9153 (and (fboundp 'fit-window-to-buffer)
9154 (fit-window-to-buffer))))
9155 ((or (= c ?\C-g)
9156 (and (= c ?q) (not (rassoc c ntable))))
9157 (org-detach-overlay org-tags-overlay)
9158 (setq quit-flag t))
9159 ((= c ?\ )
9160 (setq current nil)
9161 (if exit-after-next (setq exit-after-next 'now)))
9162 ((= c ?\t)
9163 (condition-case nil
9164 (setq tg (completing-read
9165 "Tag: "
9166 (or buffer-tags
9167 (with-current-buffer buf
9168 (org-get-buffer-tags)))))
9169 (quit (setq tg "")))
9170 (when (string-match "\\S-" tg)
9171 (add-to-list 'buffer-tags (list tg))
9172 (if (member tg current)
9173 (setq current (delete tg current))
9174 (push tg current)))
9175 (if exit-after-next (setq exit-after-next 'now)))
9176 ((setq e (rassoc c todo-table) tg (car e))
9177 (with-current-buffer buf
9178 (save-excursion (org-todo tg)))
9179 (if exit-after-next (setq exit-after-next 'now)))
9180 ((setq e (rassoc c ntable) tg (car e))
9181 (if (member tg current)
9182 (setq current (delete tg current))
9183 (loop for g in groups do
9184 (if (member tg g)
9185 (mapc (lambda (x)
9186 (setq current (delete x current)))
9187 g)))
9188 (push tg current))
9189 (if exit-after-next (setq exit-after-next 'now))))
9191 ;; Create a sorted list
9192 (setq current
9193 (sort current
9194 (lambda (a b)
9195 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9196 (if (eq exit-after-next 'now) (throw 'exit t))
9197 (goto-char (point-min))
9198 (beginning-of-line 2)
9199 (delete-region (point) (point-at-eol))
9200 (org-fast-tag-insert "Current" current c-face)
9201 (org-set-current-tags-overlay current ov-prefix)
9202 (while (re-search-forward
9203 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9204 (setq tg (match-string 1))
9205 (add-text-properties
9206 (match-beginning 1) (match-end 1)
9207 (list 'face
9208 (cond
9209 ((member tg current) c-face)
9210 ((member tg inherited) i-face)
9211 (t (get-text-property (match-beginning 1) 'face))))))
9212 (goto-char (point-min)))))
9213 (org-detach-overlay org-tags-overlay)
9214 (if rtn
9215 (mapconcat 'identity current ":")
9216 nil))))
9218 (defun org-get-tags-string ()
9219 "Get the TAGS string in the current headline."
9220 (unless (org-on-heading-p t)
9221 (error "Not on a heading"))
9222 (save-excursion
9223 (beginning-of-line 1)
9224 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9225 (org-match-string-no-properties 1)
9226 "")))
9228 (defun org-get-tags ()
9229 "Get the list of tags specified in the current headline."
9230 (org-split-string (org-get-tags-string) ":"))
9232 (defun org-get-buffer-tags ()
9233 "Get a table of all tags used in the buffer, for completion."
9234 (let (tags)
9235 (save-excursion
9236 (goto-char (point-min))
9237 (while (re-search-forward
9238 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9239 (when (equal (char-after (point-at-bol 0)) ?*)
9240 (mapc (lambda (x) (add-to-list 'tags x))
9241 (org-split-string (org-match-string-no-properties 1) ":")))))
9242 (mapcar 'list tags)))
9245 ;;;; Properties
9247 ;;; Setting and retrieving properties
9249 (defconst org-special-properties
9250 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9251 "TIMESTAMP" "TIMESTAMP_IA")
9252 "The special properties valid in Org-mode.
9254 These are properties that are not defined in the property drawer,
9255 but in some other way.")
9257 (defconst org-default-properties
9258 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9259 "LOCATION" "LOGGING" "COLUMNS")
9260 "Some properties that are used by Org-mode for various purposes.
9261 Being in this list makes sure that they are offered for completion.")
9263 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9264 "Regular expression matching the first line of a property drawer.")
9266 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9267 "Regular expression matching the first line of a property drawer.")
9269 (defun org-property-action ()
9270 "Do an action on properties."
9271 (interactive)
9272 (let (c)
9273 (org-at-property-p)
9274 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9275 (setq c (read-char-exclusive))
9276 (cond
9277 ((equal c ?s)
9278 (call-interactively 'org-set-property))
9279 ((equal c ?d)
9280 (call-interactively 'org-delete-property))
9281 ((equal c ?D)
9282 (call-interactively 'org-delete-property-globally))
9283 ((equal c ?c)
9284 (call-interactively 'org-compute-property-at-point))
9285 (t (error "No such property action %c" c)))))
9287 (defun org-at-property-p ()
9288 "Is the cursor in a property line?"
9289 ;; FIXME: Does not check if we are actually in the drawer.
9290 ;; FIXME: also returns true on any drawers.....
9291 ;; This is used by C-c C-c for property action.
9292 (save-excursion
9293 (beginning-of-line 1)
9294 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9296 (defun org-get-property-block (&optional beg end force)
9297 "Return the (beg . end) range of the body of the property drawer.
9298 BEG and END can be beginning and end of subtree, if not given
9299 they will be found.
9300 If the drawer does not exist and FORCE is non-nil, create the drawer."
9301 (catch 'exit
9302 (save-excursion
9303 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9304 (end (or end (progn (outline-next-heading) (point)))))
9305 (goto-char beg)
9306 (if (re-search-forward org-property-start-re end t)
9307 (setq beg (1+ (match-end 0)))
9308 (if force
9309 (save-excursion
9310 (org-insert-property-drawer)
9311 (setq end (progn (outline-next-heading) (point))))
9312 (throw 'exit nil))
9313 (goto-char beg)
9314 (if (re-search-forward org-property-start-re end t)
9315 (setq beg (1+ (match-end 0)))))
9316 (if (re-search-forward org-property-end-re end t)
9317 (setq end (match-beginning 0))
9318 (or force (throw 'exit nil))
9319 (goto-char beg)
9320 (setq end beg)
9321 (org-indent-line-function)
9322 (insert ":END:\n"))
9323 (cons beg end)))))
9325 (defun org-entry-properties (&optional pom which)
9326 "Get all properties of the entry at point-or-marker POM.
9327 This includes the TODO keyword, the tags, time strings for deadline,
9328 scheduled, and clocking, and any additional properties defined in the
9329 entry. The return value is an alist, keys may occur multiple times
9330 if the property key was used several times.
9331 POM may also be nil, in which case the current entry is used.
9332 If WHICH is nil or `all', get all properties. If WHICH is
9333 `special' or `standard', only get that subclass."
9334 (setq which (or which 'all))
9335 (org-with-point-at pom
9336 (let ((clockstr (substring org-clock-string 0 -1))
9337 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9338 beg end range props sum-props key value string clocksum)
9339 (save-excursion
9340 (when (condition-case nil (org-back-to-heading t) (error nil))
9341 (setq beg (point))
9342 (setq sum-props (get-text-property (point) 'org-summaries))
9343 (setq clocksum (get-text-property (point) :org-clock-minutes))
9344 (outline-next-heading)
9345 (setq end (point))
9346 (when (memq which '(all special))
9347 ;; Get the special properties, like TODO and tags
9348 (goto-char beg)
9349 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9350 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9351 (when (looking-at org-priority-regexp)
9352 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9353 (when (and (setq value (org-get-tags-string))
9354 (string-match "\\S-" value))
9355 (push (cons "TAGS" value) props))
9356 (when (setq value (org-get-tags-at))
9357 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9358 props))
9359 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9360 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9361 string (if (equal key clockstr)
9362 (org-no-properties
9363 (org-trim
9364 (buffer-substring
9365 (match-beginning 3) (goto-char (point-at-eol)))))
9366 (substring (org-match-string-no-properties 3) 1 -1)))
9367 (unless key
9368 (if (= (char-after (match-beginning 3)) ?\[)
9369 (setq key "TIMESTAMP_IA")
9370 (setq key "TIMESTAMP")))
9371 (when (or (equal key clockstr) (not (assoc key props)))
9372 (push (cons key string) props)))
9376 (when (memq which '(all standard))
9377 ;; Get the standard properties, like :PORP: ...
9378 (setq range (org-get-property-block beg end))
9379 (when range
9380 (goto-char (car range))
9381 (while (re-search-forward
9382 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9383 (cdr range) t)
9384 (setq key (org-match-string-no-properties 1)
9385 value (org-trim (or (org-match-string-no-properties 2) "")))
9386 (unless (member key excluded)
9387 (push (cons key (or value "")) props)))))
9388 (if clocksum
9389 (push (cons "CLOCKSUM"
9390 (org-columns-number-to-string (/ (float clocksum) 60.)
9391 'add_times))
9392 props))
9393 (append sum-props (nreverse props)))))))
9395 (defun org-entry-get (pom property &optional inherit)
9396 "Get value of PROPERTY for entry at point-or-marker POM.
9397 If INHERIT is non-nil and the entry does not have the property,
9398 then also check higher levels of the hierarchy.
9399 If INHERIT is the symbol `selective', use inheritance only if the setting
9400 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9401 If the property is present but empty, the return value is the empty string.
9402 If the property is not present at all, nil is returned."
9403 (org-with-point-at pom
9404 (if (and inherit (if (eq inherit 'selective)
9405 (org-property-inherit-p property)
9407 (org-entry-get-with-inheritance property)
9408 (if (member property org-special-properties)
9409 ;; We need a special property. Use brute force, get all properties.
9410 (cdr (assoc property (org-entry-properties nil 'special)))
9411 (let ((range (org-get-property-block)))
9412 (if (and range
9413 (goto-char (car range))
9414 (re-search-forward
9415 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9416 (cdr range) t))
9417 ;; Found the property, return it.
9418 (if (match-end 1)
9419 (org-match-string-no-properties 1)
9420 "")))))))
9422 (defun org-property-or-variable-value (var &optional inherit)
9423 "Check if there is a property fixing the value of VAR.
9424 If yes, return this value. If not, return the current value of the variable."
9425 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9426 (if (and prop (stringp prop) (string-match "\\S-" prop))
9427 (read prop)
9428 (symbol-value var))))
9430 (defun org-entry-delete (pom property)
9431 "Delete the property PROPERTY from entry at point-or-marker POM."
9432 (org-with-point-at pom
9433 (if (member property org-special-properties)
9434 nil ; cannot delete these properties.
9435 (let ((range (org-get-property-block)))
9436 (if (and range
9437 (goto-char (car range))
9438 (re-search-forward
9439 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9440 (cdr range) t))
9441 (progn
9442 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9444 nil)))))
9446 ;; Multi-values properties are properties that contain multiple values
9447 ;; These values are assumed to be single words, separated by whitespace.
9448 (defun org-entry-add-to-multivalued-property (pom property value)
9449 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9450 (let* ((old (org-entry-get pom property))
9451 (values (and old (org-split-string old "[ \t]"))))
9452 (unless (member value values)
9453 (setq values (cons value values))
9454 (org-entry-put pom property
9455 (mapconcat 'identity values " ")))))
9457 (defun org-entry-remove-from-multivalued-property (pom property value)
9458 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9459 (let* ((old (org-entry-get pom property))
9460 (values (and old (org-split-string old "[ \t]"))))
9461 (when (member value values)
9462 (setq values (delete value values))
9463 (org-entry-put pom property
9464 (mapconcat 'identity values " ")))))
9466 (defun org-entry-member-in-multivalued-property (pom property value)
9467 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9468 (let* ((old (org-entry-get pom property))
9469 (values (and old (org-split-string old "[ \t]"))))
9470 (member value values)))
9472 (defvar org-entry-property-inherited-from (make-marker))
9474 (defun org-entry-get-with-inheritance (property)
9475 "Get entry property, and search higher levels if not present."
9476 (let (tmp)
9477 (save-excursion
9478 (save-restriction
9479 (widen)
9480 (catch 'ex
9481 (while t
9482 (when (setq tmp (org-entry-get nil property))
9483 (org-back-to-heading t)
9484 (move-marker org-entry-property-inherited-from (point))
9485 (throw 'ex tmp))
9486 (or (org-up-heading-safe) (throw 'ex nil)))))
9487 (or tmp (cdr (assoc property org-local-properties))
9488 (cdr (assoc property org-global-properties))))))
9490 (defun org-entry-put (pom property value)
9491 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9492 (org-with-point-at pom
9493 (org-back-to-heading t)
9494 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9495 range)
9496 (cond
9497 ((equal property "TODO")
9498 (when (and (stringp value) (string-match "\\S-" value)
9499 (not (member value org-todo-keywords-1)))
9500 (error "\"%s\" is not a valid TODO state" value))
9501 (if (or (not value)
9502 (not (string-match "\\S-" value)))
9503 (setq value 'none))
9504 (org-todo value)
9505 (org-set-tags nil 'align))
9506 ((equal property "PRIORITY")
9507 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9508 (string-to-char value) ?\ ))
9509 (org-set-tags nil 'align))
9510 ((equal property "SCHEDULED")
9511 (if (re-search-forward org-scheduled-time-regexp end t)
9512 (cond
9513 ((eq value 'earlier) (org-timestamp-change -1 'day))
9514 ((eq value 'later) (org-timestamp-change 1 'day))
9515 (t (call-interactively 'org-schedule)))
9516 (call-interactively 'org-schedule)))
9517 ((equal property "DEADLINE")
9518 (if (re-search-forward org-deadline-time-regexp end t)
9519 (cond
9520 ((eq value 'earlier) (org-timestamp-change -1 'day))
9521 ((eq value 'later) (org-timestamp-change 1 'day))
9522 (t (call-interactively 'org-deadline)))
9523 (call-interactively 'org-deadline)))
9524 ((member property org-special-properties)
9525 (error "The %s property can not yet be set with `org-entry-put'"
9526 property))
9527 (t ; a non-special property
9528 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9529 (setq range (org-get-property-block beg end 'force))
9530 (goto-char (car range))
9531 (if (re-search-forward
9532 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9533 (progn
9534 (delete-region (match-beginning 1) (match-end 1))
9535 (goto-char (match-beginning 1)))
9536 (goto-char (cdr range))
9537 (insert "\n")
9538 (backward-char 1)
9539 (org-indent-line-function)
9540 (insert ":" property ":"))
9541 (and value (insert " " value))
9542 (org-indent-line-function)))))))
9544 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9545 "Get all property keys in the current buffer.
9546 With INCLUDE-SPECIALS, also list the special properties that relect things
9547 like tags and TODO state.
9548 With INCLUDE-DEFAULTS, also include properties that has special meaning
9549 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9550 With INCLUDE-COLUMNS, also include property names given in COLUMN
9551 formats in the current buffer."
9552 (let (rtn range cfmt cols s p)
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (point-min))
9557 (while (re-search-forward org-property-start-re nil t)
9558 (setq range (org-get-property-block))
9559 (goto-char (car range))
9560 (while (re-search-forward
9561 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9562 (cdr range) t)
9563 (add-to-list 'rtn (org-match-string-no-properties 1)))
9564 (outline-next-heading))))
9566 (when include-specials
9567 (setq rtn (append org-special-properties rtn)))
9569 (when include-defaults
9570 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9572 (when include-columns
9573 (save-excursion
9574 (save-restriction
9575 (widen)
9576 (goto-char (point-min))
9577 (while (re-search-forward
9578 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9579 nil t)
9580 (setq cfmt (match-string 2) s 0)
9581 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9582 cfmt s)
9583 (setq s (match-end 0)
9584 p (match-string 1 cfmt))
9585 (unless (or (equal p "ITEM")
9586 (member p org-special-properties))
9587 (add-to-list 'rtn (match-string 1 cfmt))))))))
9589 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9591 (defun org-property-values (key)
9592 "Return a list of all values of property KEY."
9593 (save-excursion
9594 (save-restriction
9595 (widen)
9596 (goto-char (point-min))
9597 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9598 values)
9599 (while (re-search-forward re nil t)
9600 (add-to-list 'values (org-trim (match-string 1))))
9601 (delete "" values)))))
9603 (defun org-insert-property-drawer ()
9604 "Insert a property drawer into the current entry."
9605 (interactive)
9606 (org-back-to-heading t)
9607 (looking-at outline-regexp)
9608 (let ((indent (- (match-end 0)(match-beginning 0)))
9609 (beg (point))
9610 (re (concat "^[ \t]*" org-keyword-time-regexp))
9611 end hiddenp)
9612 (outline-next-heading)
9613 (setq end (point))
9614 (goto-char beg)
9615 (while (re-search-forward re end t))
9616 (setq hiddenp (org-invisible-p))
9617 (end-of-line 1)
9618 (and (equal (char-after) ?\n) (forward-char 1))
9619 (org-skip-over-state-notes)
9620 (skip-chars-backward " \t\n\r")
9621 (if (eq (char-before) ?*) (forward-char 1))
9622 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9623 (beginning-of-line 0)
9624 (indent-to-column indent)
9625 (beginning-of-line 2)
9626 (indent-to-column indent)
9627 (beginning-of-line 0)
9628 (if hiddenp
9629 (save-excursion
9630 (org-back-to-heading t)
9631 (hide-entry))
9632 (org-flag-drawer t))))
9634 (defun org-set-property (property value)
9635 "In the current entry, set PROPERTY to VALUE.
9636 When called interactively, this will prompt for a property name, offering
9637 completion on existing and default properties. And then it will prompt
9638 for a value, offering competion either on allowed values (via an inherited
9639 xxx_ALL property) or on existing values in other instances of this property
9640 in the current file."
9641 (interactive
9642 (let* ((prop (completing-read
9643 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9644 (cur (org-entry-get nil prop))
9645 (allowed (org-property-get-allowed-values nil prop 'table))
9646 (existing (mapcar 'list (org-property-values prop)))
9647 (val (if allowed
9648 (completing-read "Value: " allowed nil 'req-match)
9649 (completing-read
9650 (concat "Value" (if (and cur (string-match "\\S-" cur))
9651 (concat "[" cur "]") "")
9652 ": ")
9653 existing nil nil "" nil cur))))
9654 (list prop (if (equal val "") cur val))))
9655 (unless (equal (org-entry-get nil property) value)
9656 (org-entry-put nil property value)))
9658 (defun org-delete-property (property)
9659 "In the current entry, delete PROPERTY."
9660 (interactive
9661 (let* ((prop (completing-read
9662 "Property: " (org-entry-properties nil 'standard))))
9663 (list prop)))
9664 (message "Property %s %s" property
9665 (if (org-entry-delete nil property)
9666 "deleted"
9667 "was not present in the entry")))
9669 (defun org-delete-property-globally (property)
9670 "Remove PROPERTY globally, from all entries."
9671 (interactive
9672 (let* ((prop (completing-read
9673 "Globally remove property: "
9674 (mapcar 'list (org-buffer-property-keys)))))
9675 (list prop)))
9676 (save-excursion
9677 (save-restriction
9678 (widen)
9679 (goto-char (point-min))
9680 (let ((cnt 0))
9681 (while (re-search-forward
9682 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9683 nil t)
9684 (setq cnt (1+ cnt))
9685 (replace-match ""))
9686 (message "Property \"%s\" removed from %d entries" property cnt)))))
9688 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9690 (defun org-compute-property-at-point ()
9691 "Compute the property at point.
9692 This looks for an enclosing column format, extracts the operator and
9693 then applies it to the proerty in the column format's scope."
9694 (interactive)
9695 (unless (org-at-property-p)
9696 (error "Not at a property"))
9697 (let ((prop (org-match-string-no-properties 2)))
9698 (org-columns-get-format-and-top-level)
9699 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9700 (error "No operator defined for property %s" prop))
9701 (org-columns-compute prop)))
9703 (defun org-property-get-allowed-values (pom property &optional table)
9704 "Get allowed values for the property PROPERTY.
9705 When TABLE is non-nil, return an alist that can directly be used for
9706 completion."
9707 (let (vals)
9708 (cond
9709 ((equal property "TODO")
9710 (setq vals (org-with-point-at pom
9711 (append org-todo-keywords-1 '("")))))
9712 ((equal property "PRIORITY")
9713 (let ((n org-lowest-priority))
9714 (while (>= n org-highest-priority)
9715 (push (char-to-string n) vals)
9716 (setq n (1- n)))))
9717 ((member property org-special-properties))
9719 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9721 (when (and vals (string-match "\\S-" vals))
9722 (setq vals (car (read-from-string (concat "(" vals ")"))))
9723 (setq vals (mapcar (lambda (x)
9724 (cond ((stringp x) x)
9725 ((numberp x) (number-to-string x))
9726 ((symbolp x) (symbol-name x))
9727 (t "???")))
9728 vals)))))
9729 (if table (mapcar 'list vals) vals)))
9731 (defun org-property-previous-allowed-value (&optional previous)
9732 "Switch to the next allowed value for this property."
9733 (interactive)
9734 (org-property-next-allowed-value t))
9736 (defun org-property-next-allowed-value (&optional previous)
9737 "Switch to the next allowed value for this property."
9738 (interactive)
9739 (unless (org-at-property-p)
9740 (error "Not at a property"))
9741 (let* ((key (match-string 2))
9742 (value (match-string 3))
9743 (allowed (or (org-property-get-allowed-values (point) key)
9744 (and (member value '("[ ]" "[-]" "[X]"))
9745 '("[ ]" "[X]"))))
9746 nval)
9747 (unless allowed
9748 (error "Allowed values for this property have not been defined"))
9749 (if previous (setq allowed (reverse allowed)))
9750 (if (member value allowed)
9751 (setq nval (car (cdr (member value allowed)))))
9752 (setq nval (or nval (car allowed)))
9753 (if (equal nval value)
9754 (error "Only one allowed value for this property"))
9755 (org-at-property-p)
9756 (replace-match (concat " :" key ": " nval) t t)
9757 (org-indent-line-function)
9758 (beginning-of-line 1)
9759 (skip-chars-forward " \t")))
9761 (defun org-find-entry-with-id (ident)
9762 "Locate the entry that contains the ID property with exact value IDENT.
9763 IDENT can be a string, a symbol or a number, this function will search for
9764 the string representation of it.
9765 Return the position where this entry starts, or nil if there is no such entry."
9766 (let ((id (cond
9767 ((stringp ident) ident)
9768 ((symbol-name ident) (symbol-name ident))
9769 ((numberp ident) (number-to-string ident))
9770 (t (error "IDENT %s must be a string, symbol or number" ident))))
9771 (case-fold-search nil))
9772 (save-excursion
9773 (save-restriction
9774 (widen)
9775 (goto-char (point-min))
9776 (when (re-search-forward
9777 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9778 nil t)
9779 (org-back-to-heading)
9780 (point))))))
9782 ;;;; Timestamps
9784 (defvar org-last-changed-timestamp nil)
9785 (defvar org-time-was-given) ; dynamically scoped parameter
9786 (defvar org-end-time-was-given) ; dynamically scoped parameter
9787 (defvar org-ts-what) ; dynamically scoped parameter
9789 (defun org-time-stamp (arg)
9790 "Prompt for a date/time and insert a time stamp.
9791 If the user specifies a time like HH:MM, or if this command is called
9792 with a prefix argument, the time stamp will contain date and time.
9793 Otherwise, only the date will be included. All parts of a date not
9794 specified by the user will be filled in from the current date/time.
9795 So if you press just return without typing anything, the time stamp
9796 will represent the current date/time. If there is already a timestamp
9797 at the cursor, it will be modified."
9798 (interactive "P")
9799 (let* ((ts nil)
9800 (default-time
9801 ;; Default time is either today, or, when entering a range,
9802 ;; the range start.
9803 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9804 (save-excursion
9805 (re-search-backward
9806 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9807 (- (point) 20) t)))
9808 (apply 'encode-time (org-parse-time-string (match-string 1)))
9809 (current-time)))
9810 (default-input (and ts (org-get-compact-tod ts)))
9811 org-time-was-given org-end-time-was-given time)
9812 (cond
9813 ((and (org-at-timestamp-p)
9814 (eq last-command 'org-time-stamp)
9815 (eq this-command 'org-time-stamp))
9816 (insert "--")
9817 (setq time (let ((this-command this-command))
9818 (org-read-date arg 'totime nil nil default-time default-input)))
9819 (org-insert-time-stamp time (or org-time-was-given arg)))
9820 ((org-at-timestamp-p)
9821 (setq time (let ((this-command this-command))
9822 (org-read-date arg 'totime nil nil default-time default-input)))
9823 (when (org-at-timestamp-p) ; just to get the match data
9824 (replace-match "")
9825 (setq org-last-changed-timestamp
9826 (org-insert-time-stamp
9827 time (or org-time-was-given arg)
9828 nil nil nil (list org-end-time-was-given))))
9829 (message "Timestamp updated"))
9831 (setq time (let ((this-command this-command))
9832 (org-read-date arg 'totime nil nil default-time default-input)))
9833 (org-insert-time-stamp time (or org-time-was-given arg)
9834 nil nil nil (list org-end-time-was-given))))))
9836 ;; FIXME: can we use this for something else, like computing time differences?
9837 (defun org-get-compact-tod (s)
9838 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9839 (let* ((t1 (match-string 1 s))
9840 (h1 (string-to-number (match-string 2 s)))
9841 (m1 (string-to-number (match-string 3 s)))
9842 (t2 (and (match-end 4) (match-string 5 s)))
9843 (h2 (and t2 (string-to-number (match-string 6 s))))
9844 (m2 (and t2 (string-to-number (match-string 7 s))))
9845 dh dm)
9846 (if (not t2)
9848 (setq dh (- h2 h1) dm (- m2 m1))
9849 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9850 (concat t1 "+" (number-to-string dh)
9851 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9853 (defun org-time-stamp-inactive (&optional arg)
9854 "Insert an inactive time stamp.
9855 An inactive time stamp is enclosed in square brackets instead of angle
9856 brackets. It is inactive in the sense that it does not trigger agenda entries,
9857 does not link to the calendar and cannot be changed with the S-cursor keys.
9858 So these are more for recording a certain time/date."
9859 (interactive "P")
9860 (let (org-time-was-given org-end-time-was-given time)
9861 (setq time (org-read-date arg 'totime))
9862 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9863 nil nil (list org-end-time-was-given))))
9865 (defvar org-date-ovl (org-make-overlay 1 1))
9866 (org-overlay-put org-date-ovl 'face 'org-warning)
9867 (org-detach-overlay org-date-ovl)
9869 (defvar org-ans1) ; dynamically scoped parameter
9870 (defvar org-ans2) ; dynamically scoped parameter
9872 (defvar org-plain-time-of-day-regexp) ; defined below
9874 (defvar org-read-date-overlay nil)
9875 (defvar org-dcst nil) ; dynamically scoped
9877 (defun org-read-date (&optional with-time to-time from-string prompt
9878 default-time default-input)
9879 "Read a date, possibly a time, and make things smooth for the user.
9880 The prompt will suggest to enter an ISO date, but you can also enter anything
9881 which will at least partially be understood by `parse-time-string'.
9882 Unrecognized parts of the date will default to the current day, month, year,
9883 hour and minute. If this command is called to replace a timestamp at point,
9884 of to enter the second timestamp of a range, the default time is taken from the
9885 existing stamp. For example,
9886 3-2-5 --> 2003-02-05
9887 feb 15 --> currentyear-02-15
9888 sep 12 9 --> 2009-09-12
9889 12:45 --> today 12:45
9890 22 sept 0:34 --> currentyear-09-22 0:34
9891 12 --> currentyear-currentmonth-12
9892 Fri --> nearest Friday (today or later)
9893 etc.
9895 Furthermore you can specify a relative date by giving, as the *first* thing
9896 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
9897 change in days weeks, months, years.
9898 With a single plus or minus, the date is relative to today. With a double
9899 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
9900 +4d --> four days from today
9901 +4 --> same as above
9902 +2w --> two weeks from today
9903 ++5 --> five days from default date
9905 The function understands only English month and weekday abbreviations,
9906 but this can be configured with the variables `parse-time-months' and
9907 `parse-time-weekdays'.
9909 While prompting, a calendar is popped up - you can also select the
9910 date with the mouse (button 1). The calendar shows a period of three
9911 months. To scroll it to other months, use the keys `>' and `<'.
9912 If you don't like the calendar, turn it off with
9913 \(setq org-read-date-popup-calendar nil)
9915 With optional argument TO-TIME, the date will immediately be converted
9916 to an internal time.
9917 With an optional argument WITH-TIME, the prompt will suggest to also
9918 insert a time. Note that when WITH-TIME is not set, you can still
9919 enter a time, and this function will inform the calling routine about
9920 this change. The calling routine may then choose to change the format
9921 used to insert the time stamp into the buffer to include the time.
9922 With optional argument FROM-STRING, read from this string instead from
9923 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
9924 the time/date that is used for everything that is not specified by the
9925 user."
9926 (require 'parse-time)
9927 (let* ((org-time-stamp-rounding-minutes
9928 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
9929 (org-dcst org-display-custom-times)
9930 (ct (org-current-time))
9931 (def (or default-time ct))
9932 (defdecode (decode-time def))
9933 (dummy (progn
9934 (when (< (nth 2 defdecode) org-extend-today-until)
9935 (setcar (nthcdr 2 defdecode) -1)
9936 (setcar (nthcdr 1 defdecode) 59)
9937 (setq def (apply 'encode-time defdecode)
9938 defdecode (decode-time def)))))
9939 (calendar-move-hook nil)
9940 (calendar-view-diary-initially-flag nil)
9941 (view-diary-entries-initially nil)
9942 (calendar-view-holidays-initially-flag nil)
9943 (view-calendar-holidays-initially nil)
9944 (timestr (format-time-string
9945 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
9946 (prompt (concat (if prompt (concat prompt " ") "")
9947 (format "Date+time [%s]: " timestr)))
9948 ans (org-ans0 "") org-ans1 org-ans2 final)
9950 (cond
9951 (from-string (setq ans from-string))
9952 (org-read-date-popup-calendar
9953 (save-excursion
9954 (save-window-excursion
9955 (calendar)
9956 (calendar-forward-day (- (time-to-days def)
9957 (calendar-absolute-from-gregorian
9958 (calendar-current-date))))
9959 (org-eval-in-calendar nil t)
9960 (let* ((old-map (current-local-map))
9961 (map (copy-keymap calendar-mode-map))
9962 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
9963 (org-defkey map (kbd "RET") 'org-calendar-select)
9964 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
9965 'org-calendar-select-mouse)
9966 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
9967 'org-calendar-select-mouse)
9968 (org-defkey minibuffer-local-map [(meta shift left)]
9969 (lambda () (interactive)
9970 (org-eval-in-calendar '(calendar-backward-month 1))))
9971 (org-defkey minibuffer-local-map [(meta shift right)]
9972 (lambda () (interactive)
9973 (org-eval-in-calendar '(calendar-forward-month 1))))
9974 (org-defkey minibuffer-local-map [(meta shift up)]
9975 (lambda () (interactive)
9976 (org-eval-in-calendar '(calendar-backward-year 1))))
9977 (org-defkey minibuffer-local-map [(meta shift down)]
9978 (lambda () (interactive)
9979 (org-eval-in-calendar '(calendar-forward-year 1))))
9980 (org-defkey minibuffer-local-map [(shift up)]
9981 (lambda () (interactive)
9982 (org-eval-in-calendar '(calendar-backward-week 1))))
9983 (org-defkey minibuffer-local-map [(shift down)]
9984 (lambda () (interactive)
9985 (org-eval-in-calendar '(calendar-forward-week 1))))
9986 (org-defkey minibuffer-local-map [(shift left)]
9987 (lambda () (interactive)
9988 (org-eval-in-calendar '(calendar-backward-day 1))))
9989 (org-defkey minibuffer-local-map [(shift right)]
9990 (lambda () (interactive)
9991 (org-eval-in-calendar '(calendar-forward-day 1))))
9992 (org-defkey minibuffer-local-map ">"
9993 (lambda () (interactive)
9994 (org-eval-in-calendar '(scroll-calendar-left 1))))
9995 (org-defkey minibuffer-local-map "<"
9996 (lambda () (interactive)
9997 (org-eval-in-calendar '(scroll-calendar-right 1))))
9998 (unwind-protect
9999 (progn
10000 (use-local-map map)
10001 (add-hook 'post-command-hook 'org-read-date-display)
10002 (setq org-ans0 (read-string prompt default-input nil nil))
10003 ;; org-ans0: from prompt
10004 ;; org-ans1: from mouse click
10005 ;; org-ans2: from calendar motion
10006 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10007 (remove-hook 'post-command-hook 'org-read-date-display)
10008 (use-local-map old-map)
10009 (when org-read-date-overlay
10010 (org-delete-overlay org-read-date-overlay)
10011 (setq org-read-date-overlay nil)))))))
10013 (t ; Naked prompt only
10014 (unwind-protect
10015 (setq ans (read-string prompt default-input nil timestr))
10016 (when org-read-date-overlay
10017 (org-delete-overlay org-read-date-overlay)
10018 (setq org-read-date-overlay nil)))))
10020 (setq final (org-read-date-analyze ans def defdecode))
10022 (if to-time
10023 (apply 'encode-time final)
10024 (if (and (boundp 'org-time-was-given) org-time-was-given)
10025 (format "%04d-%02d-%02d %02d:%02d"
10026 (nth 5 final) (nth 4 final) (nth 3 final)
10027 (nth 2 final) (nth 1 final))
10028 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10029 (defvar def)
10030 (defvar defdecode)
10031 (defvar with-time)
10032 (defun org-read-date-display ()
10033 "Display the currrent date prompt interpretation in the minibuffer."
10034 (when org-read-date-display-live
10035 (when org-read-date-overlay
10036 (org-delete-overlay org-read-date-overlay))
10037 (let ((p (point)))
10038 (end-of-line 1)
10039 (while (not (equal (buffer-substring
10040 (max (point-min) (- (point) 4)) (point))
10041 " "))
10042 (insert " "))
10043 (goto-char p))
10044 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10045 " " (or org-ans1 org-ans2)))
10046 (org-end-time-was-given nil)
10047 (f (org-read-date-analyze ans def defdecode))
10048 (fmts (if org-dcst
10049 org-time-stamp-custom-formats
10050 org-time-stamp-formats))
10051 (fmt (if (or with-time
10052 (and (boundp 'org-time-was-given) org-time-was-given))
10053 (cdr fmts)
10054 (car fmts)))
10055 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10056 (when (and org-end-time-was-given
10057 (string-match org-plain-time-of-day-regexp txt))
10058 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10059 org-end-time-was-given
10060 (substring txt (match-end 0)))))
10061 (setq org-read-date-overlay
10062 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10063 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10065 (defun org-read-date-analyze (ans def defdecode)
10066 "Analyze the combined answer of the date prompt."
10067 ;; FIXME: cleanup and comment
10068 (let (delta deltan deltaw deltadef year month day
10069 hour minute second wday pm h2 m2 tl wday1
10070 iso-year iso-weekday iso-week iso-year iso-date)
10072 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10073 (setq ans (replace-match "" t t ans)
10074 deltan (car delta)
10075 deltaw (nth 1 delta)
10076 deltadef (nth 2 delta)))
10078 ;; Check if there is an iso week date in there
10079 ;; If yes, sore the info and ostpone interpreting it until the rest
10080 ;; of the parsing is done
10081 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10082 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10083 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10084 iso-week (string-to-number (match-string 2 ans)))
10085 (setq ans (replace-match "" t t ans)))
10087 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10088 (when (string-match
10089 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10090 (setq year (if (match-end 2)
10091 (string-to-number (match-string 2 ans))
10092 (string-to-number (format-time-string "%Y")))
10093 month (string-to-number (match-string 3 ans))
10094 day (string-to-number (match-string 4 ans)))
10095 (if (< year 100) (setq year (+ 2000 year)))
10096 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10097 t nil ans)))
10098 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10099 ;; If there is a time with am/pm, and *no* time without it, we convert
10100 ;; so that matching will be successful.
10101 (loop for i from 1 to 2 do ; twice, for end time as well
10102 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10103 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10104 (setq hour (string-to-number (match-string 1 ans))
10105 minute (if (match-end 3)
10106 (string-to-number (match-string 3 ans))
10108 pm (equal ?p
10109 (string-to-char (downcase (match-string 4 ans)))))
10110 (if (and (= hour 12) (not pm))
10111 (setq hour 0)
10112 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10113 (setq ans (replace-match (format "%02d:%02d" hour minute)
10114 t t ans))))
10116 ;; Check if a time range is given as a duration
10117 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10118 (setq hour (string-to-number (match-string 1 ans))
10119 h2 (+ hour (string-to-number (match-string 3 ans)))
10120 minute (string-to-number (match-string 2 ans))
10121 m2 (+ minute (if (match-end 5) (string-to-number
10122 (match-string 5 ans))0)))
10123 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10124 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10125 t t ans)))
10127 ;; Check if there is a time range
10128 (when (boundp 'org-end-time-was-given)
10129 (setq org-time-was-given nil)
10130 (when (and (string-match org-plain-time-of-day-regexp ans)
10131 (match-end 8))
10132 (setq org-end-time-was-given (match-string 8 ans))
10133 (setq ans (concat (substring ans 0 (match-beginning 7))
10134 (substring ans (match-end 7))))))
10136 (setq tl (parse-time-string ans)
10137 day (or (nth 3 tl) (nth 3 defdecode))
10138 month (or (nth 4 tl)
10139 (if (and org-read-date-prefer-future
10140 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10141 (1+ (nth 4 defdecode))
10142 (nth 4 defdecode)))
10143 year (or (nth 5 tl)
10144 (if (and org-read-date-prefer-future
10145 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10146 (1+ (nth 5 defdecode))
10147 (nth 5 defdecode)))
10148 hour (or (nth 2 tl) (nth 2 defdecode))
10149 minute (or (nth 1 tl) (nth 1 defdecode))
10150 second (or (nth 0 tl) 0)
10151 wday (nth 6 tl))
10153 ;; Special date definitions below
10154 (cond
10155 (iso-week
10156 ;; There was an iso week
10157 (setq year (or iso-year year)
10158 day (or iso-weekday wday 1)
10159 wday nil ; to make sure that the trigger below does not match
10160 iso-date (calendar-gregorian-from-absolute
10161 (calendar-absolute-from-iso
10162 (list iso-week day year))))
10163 ; FIXME: Should we also push ISO weeks into the future?
10164 ; (when (and org-read-date-prefer-future
10165 ; (not iso-year)
10166 ; (< (calendar-absolute-from-gregorian iso-date)
10167 ; (time-to-days (current-time))))
10168 ; (setq year (1+ year)
10169 ; iso-date (calendar-gregorian-from-absolute
10170 ; (calendar-absolute-from-iso
10171 ; (list iso-week day year)))))
10172 (setq month (car iso-date)
10173 year (nth 2 iso-date)
10174 day (nth 1 iso-date)))
10175 (deltan
10176 (unless deltadef
10177 (let ((now (decode-time (current-time))))
10178 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10179 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10180 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10181 ((equal deltaw "m") (setq month (+ month deltan)))
10182 ((equal deltaw "y") (setq year (+ year deltan)))))
10183 ((and wday (not (nth 3 tl)))
10184 ;; Weekday was given, but no day, so pick that day in the week
10185 ;; on or after the derived date.
10186 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10187 (unless (equal wday wday1)
10188 (setq day (+ day (% (- wday wday1 -7) 7))))))
10189 (if (and (boundp 'org-time-was-given)
10190 (nth 2 tl))
10191 (setq org-time-was-given t))
10192 (if (< year 100) (setq year (+ 2000 year)))
10193 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10194 (list second minute hour day month year)))
10196 (defvar parse-time-weekdays)
10198 (defun org-read-date-get-relative (s today default)
10199 "Check string S for special relative date string.
10200 TODAY and DEFAULT are internal times, for today and for a default.
10201 Return shift list (N what def-flag)
10202 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10203 N is the number of WHATs to shift.
10204 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10205 the DEFAULT date rather than TODAY."
10206 (when (string-match
10207 (concat
10208 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10209 "\\([0-9]+\\)?"
10210 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10211 "\\([ \t]\\|$\\)") s)
10212 (let* ((dir (if (match-end 1)
10213 (string-to-char (substring (match-string 1 s) -1))
10214 ?+))
10215 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10216 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10217 (what (if (match-end 3) (match-string 3 s) "d"))
10218 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10219 (date (if rel default today))
10220 (wday (nth 6 (decode-time date)))
10221 delta)
10222 (if wday1
10223 (progn
10224 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10225 (if (= dir ?-) (setq delta (- delta 7)))
10226 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10227 (list delta "d" rel))
10228 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10230 (defun org-eval-in-calendar (form &optional keepdate)
10231 "Eval FORM in the calendar window and return to current window.
10232 Also, store the cursor date in variable org-ans2."
10233 (let ((sw (selected-window)))
10234 (select-window (get-buffer-window "*Calendar*"))
10235 (eval form)
10236 (when (and (not keepdate) (calendar-cursor-to-date))
10237 (let* ((date (calendar-cursor-to-date))
10238 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10239 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10240 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10241 (select-window sw)))
10243 ; ;; Update the prompt to show new default date
10244 ; (save-excursion
10245 ; (goto-char (point-min))
10246 ; (when (and org-ans2
10247 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10248 ; (get-text-property (match-end 0) 'field))
10249 ; (let ((inhibit-read-only t))
10250 ; (replace-match (concat "[" org-ans2 "]") t t)
10251 ; (add-text-properties (point-min) (1+ (match-end 0))
10252 ; (text-properties-at (1+ (point-min)))))))))
10254 (defun org-calendar-select ()
10255 "Return to `org-read-date' with the date currently selected.
10256 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10257 (interactive)
10258 (when (calendar-cursor-to-date)
10259 (let* ((date (calendar-cursor-to-date))
10260 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10261 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10262 (if (active-minibuffer-window) (exit-minibuffer))))
10264 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10265 "Insert a date stamp for the date given by the internal TIME.
10266 WITH-HM means, use the stamp format that includes the time of the day.
10267 INACTIVE means use square brackets instead of angular ones, so that the
10268 stamp will not contribute to the agenda.
10269 PRE and POST are optional strings to be inserted before and after the
10270 stamp.
10271 The command returns the inserted time stamp."
10272 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10273 stamp)
10274 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10275 (insert-before-markers (or pre ""))
10276 (insert-before-markers (setq stamp (format-time-string fmt time)))
10277 (when (listp extra)
10278 (setq extra (car extra))
10279 (if (and (stringp extra)
10280 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10281 (setq extra (format "-%02d:%02d"
10282 (string-to-number (match-string 1 extra))
10283 (string-to-number (match-string 2 extra))))
10284 (setq extra nil)))
10285 (when extra
10286 (backward-char 1)
10287 (insert-before-markers extra)
10288 (forward-char 1))
10289 (insert-before-markers (or post ""))
10290 stamp))
10292 (defun org-toggle-time-stamp-overlays ()
10293 "Toggle the use of custom time stamp formats."
10294 (interactive)
10295 (setq org-display-custom-times (not org-display-custom-times))
10296 (unless org-display-custom-times
10297 (let ((p (point-min)) (bmp (buffer-modified-p)))
10298 (while (setq p (next-single-property-change p 'display))
10299 (if (and (get-text-property p 'display)
10300 (eq (get-text-property p 'face) 'org-date))
10301 (remove-text-properties
10302 p (setq p (next-single-property-change p 'display))
10303 '(display t))))
10304 (set-buffer-modified-p bmp)))
10305 (if (featurep 'xemacs)
10306 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10307 (org-restart-font-lock)
10308 (setq org-table-may-need-update t)
10309 (if org-display-custom-times
10310 (message "Time stamps are overlayed with custom format")
10311 (message "Time stamp overlays removed")))
10313 (defun org-display-custom-time (beg end)
10314 "Overlay modified time stamp format over timestamp between BED and END."
10315 (let* ((ts (buffer-substring beg end))
10316 t1 w1 with-hm tf time str w2 (off 0))
10317 (save-match-data
10318 (setq t1 (org-parse-time-string ts t))
10319 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10320 (setq off (- (match-end 0) (match-beginning 0)))))
10321 (setq end (- end off))
10322 (setq w1 (- end beg)
10323 with-hm (and (nth 1 t1) (nth 2 t1))
10324 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10325 time (org-fix-decoded-time t1)
10326 str (org-add-props
10327 (format-time-string
10328 (substring tf 1 -1) (apply 'encode-time time))
10329 nil 'mouse-face 'highlight)
10330 w2 (length str))
10331 (if (not (= w2 w1))
10332 (add-text-properties (1+ beg) (+ 2 beg)
10333 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10334 (if (featurep 'xemacs)
10335 (progn
10336 (put-text-property beg end 'invisible t)
10337 (put-text-property beg end 'end-glyph (make-glyph str)))
10338 (put-text-property beg end 'display str))))
10340 (defun org-translate-time (string)
10341 "Translate all timestamps in STRING to custom format.
10342 But do this only if the variable `org-display-custom-times' is set."
10343 (when org-display-custom-times
10344 (save-match-data
10345 (let* ((start 0)
10346 (re org-ts-regexp-both)
10347 t1 with-hm inactive tf time str beg end)
10348 (while (setq start (string-match re string start))
10349 (setq beg (match-beginning 0)
10350 end (match-end 0)
10351 t1 (save-match-data
10352 (org-parse-time-string (substring string beg end) t))
10353 with-hm (and (nth 1 t1) (nth 2 t1))
10354 inactive (equal (substring string beg (1+ beg)) "[")
10355 tf (funcall (if with-hm 'cdr 'car)
10356 org-time-stamp-custom-formats)
10357 time (org-fix-decoded-time t1)
10358 str (format-time-string
10359 (concat
10360 (if inactive "[" "<") (substring tf 1 -1)
10361 (if inactive "]" ">"))
10362 (apply 'encode-time time))
10363 string (replace-match str t t string)
10364 start (+ start (length str)))))))
10365 string)
10367 (defun org-fix-decoded-time (time)
10368 "Set 0 instead of nil for the first 6 elements of time.
10369 Don't touch the rest."
10370 (let ((n 0))
10371 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10373 (defun org-days-to-time (timestamp-string)
10374 "Difference between TIMESTAMP-STRING and now in days."
10375 (- (time-to-days (org-time-string-to-time timestamp-string))
10376 (time-to-days (current-time))))
10378 (defun org-deadline-close (timestamp-string &optional ndays)
10379 "Is the time in TIMESTAMP-STRING close to the current date?"
10380 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10381 (and (< (org-days-to-time timestamp-string) ndays)
10382 (not (org-entry-is-done-p))))
10384 (defun org-get-wdays (ts)
10385 "Get the deadline lead time appropriate for timestring TS."
10386 (cond
10387 ((<= org-deadline-warning-days 0)
10388 ;; 0 or negative, enforce this value no matter what
10389 (- org-deadline-warning-days))
10390 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10391 ;; lead time is specified.
10392 (floor (* (string-to-number (match-string 1 ts))
10393 (cdr (assoc (match-string 2 ts)
10394 '(("d" . 1) ("w" . 7)
10395 ("m" . 30.4) ("y" . 365.25)))))))
10396 ;; go for the default.
10397 (t org-deadline-warning-days)))
10399 (defun org-calendar-select-mouse (ev)
10400 "Return to `org-read-date' with the date currently selected.
10401 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10402 (interactive "e")
10403 (mouse-set-point ev)
10404 (when (calendar-cursor-to-date)
10405 (let* ((date (calendar-cursor-to-date))
10406 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10407 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10408 (if (active-minibuffer-window) (exit-minibuffer))))
10410 (defun org-check-deadlines (ndays)
10411 "Check if there are any deadlines due or past due.
10412 A deadline is considered due if it happens within `org-deadline-warning-days'
10413 days from today's date. If the deadline appears in an entry marked DONE,
10414 it is not shown. The prefix arg NDAYS can be used to test that many
10415 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10416 (interactive "P")
10417 (let* ((org-warn-days
10418 (cond
10419 ((equal ndays '(4)) 100000)
10420 (ndays (prefix-numeric-value ndays))
10421 (t (abs org-deadline-warning-days))))
10422 (case-fold-search nil)
10423 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10424 (callback
10425 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10427 (message "%d deadlines past-due or due within %d days"
10428 (org-occur regexp nil callback)
10429 org-warn-days)))
10431 (defun org-check-before-date (date)
10432 "Check if there are deadlines or scheduled entries before DATE."
10433 (interactive (list (org-read-date)))
10434 (let ((case-fold-search nil)
10435 (regexp (concat "\\<\\(" org-deadline-string
10436 "\\|" org-scheduled-string
10437 "\\) *<\\([^>]+\\)>"))
10438 (callback
10439 (lambda () (time-less-p
10440 (org-time-string-to-time (match-string 2))
10441 (org-time-string-to-time date)))))
10442 (message "%d entries before %s"
10443 (org-occur regexp nil callback) date)))
10445 (defun org-evaluate-time-range (&optional to-buffer)
10446 "Evaluate a time range by computing the difference between start and end.
10447 Normally the result is just printed in the echo area, but with prefix arg
10448 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10449 If the time range is actually in a table, the result is inserted into the
10450 next column.
10451 For time difference computation, a year is assumed to be exactly 365
10452 days in order to avoid rounding problems."
10453 (interactive "P")
10455 (org-clock-update-time-maybe)
10456 (save-excursion
10457 (unless (org-at-date-range-p t)
10458 (goto-char (point-at-bol))
10459 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10460 (if (not (org-at-date-range-p t))
10461 (error "Not at a time-stamp range, and none found in current line")))
10462 (let* ((ts1 (match-string 1))
10463 (ts2 (match-string 2))
10464 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10465 (match-end (match-end 0))
10466 (time1 (org-time-string-to-time ts1))
10467 (time2 (org-time-string-to-time ts2))
10468 (t1 (time-to-seconds time1))
10469 (t2 (time-to-seconds time2))
10470 (diff (abs (- t2 t1)))
10471 (negative (< (- t2 t1) 0))
10472 ;; (ys (floor (* 365 24 60 60)))
10473 (ds (* 24 60 60))
10474 (hs (* 60 60))
10475 (fy "%dy %dd %02d:%02d")
10476 (fy1 "%dy %dd")
10477 (fd "%dd %02d:%02d")
10478 (fd1 "%dd")
10479 (fh "%02d:%02d")
10480 y d h m align)
10481 (if havetime
10482 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10484 d (floor (/ diff ds)) diff (mod diff ds)
10485 h (floor (/ diff hs)) diff (mod diff hs)
10486 m (floor (/ diff 60)))
10487 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10489 d (floor (+ (/ diff ds) 0.5))
10490 h 0 m 0))
10491 (if (not to-buffer)
10492 (message "%s" (org-make-tdiff-string y d h m))
10493 (if (org-at-table-p)
10494 (progn
10495 (goto-char match-end)
10496 (setq align t)
10497 (and (looking-at " *|") (goto-char (match-end 0))))
10498 (goto-char match-end))
10499 (if (looking-at
10500 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10501 (replace-match ""))
10502 (if negative (insert " -"))
10503 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10504 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10505 (insert " " (format fh h m))))
10506 (if align (org-table-align))
10507 (message "Time difference inserted")))))
10509 (defun org-make-tdiff-string (y d h m)
10510 (let ((fmt "")
10511 (l nil))
10512 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10513 l (push y l)))
10514 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10515 l (push d l)))
10516 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10517 l (push h l)))
10518 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10519 l (push m l)))
10520 (apply 'format fmt (nreverse l))))
10522 (defun org-time-string-to-time (s)
10523 (apply 'encode-time (org-parse-time-string s)))
10525 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10526 "Convert a time stamp to an absolute day number.
10527 If there is a specifyer for a cyclic time stamp, get the closest date to
10528 DAYNR.
10529 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10530 (cond
10531 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10532 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10533 daynr
10534 (+ daynr 1000)))
10535 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10536 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10537 (time-to-days (current-time))) (match-string 0 s)
10538 prefer show-all))
10539 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10541 (defun org-days-to-iso-week (days)
10542 "Return the iso week number."
10543 (require 'cal-iso)
10544 (car (calendar-iso-from-absolute days)))
10546 (defun org-small-year-to-year (year)
10547 "Convert 2-digit years into 4-digit years.
10548 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10549 The year 2000 cannot be abbreviated. Any year lager than 99
10550 is retrned unchanged."
10551 (if (< year 38)
10552 (setq year (+ 2000 year))
10553 (if (< year 100)
10554 (setq year (+ 1900 year))))
10555 year)
10557 (defun org-time-from-absolute (d)
10558 "Return the time corresponding to date D.
10559 D may be an absolute day number, or a calendar-type list (month day year)."
10560 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10561 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10563 (defun org-calendar-holiday ()
10564 "List of holidays, for Diary display in Org-mode."
10565 (require 'holidays)
10566 (let ((hl (funcall
10567 (if (fboundp 'calendar-check-holidays)
10568 'calendar-check-holidays 'check-calendar-holidays) date)))
10569 (if hl (mapconcat 'identity hl "; "))))
10571 (defun org-diary-sexp-entry (sexp entry date)
10572 "Process a SEXP diary ENTRY for DATE."
10573 (require 'diary-lib)
10574 (let ((result (if calendar-debug-sexp
10575 (let ((stack-trace-on-error t))
10576 (eval (car (read-from-string sexp))))
10577 (condition-case nil
10578 (eval (car (read-from-string sexp)))
10579 (error
10580 (beep)
10581 (message "Bad sexp at line %d in %s: %s"
10582 (org-current-line)
10583 (buffer-file-name) sexp)
10584 (sleep-for 2))))))
10585 (cond ((stringp result) result)
10586 ((and (consp result)
10587 (stringp (cdr result))) (cdr result))
10588 (result entry)
10589 (t nil))))
10591 (defun org-diary-to-ical-string (frombuf)
10592 "Get iCalendar entries from diary entries in buffer FROMBUF.
10593 This uses the icalendar.el library."
10594 (let* ((tmpdir (if (featurep 'xemacs)
10595 (temp-directory)
10596 temporary-file-directory))
10597 (tmpfile (make-temp-name
10598 (expand-file-name "orgics" tmpdir)))
10599 buf rtn b e)
10600 (save-excursion
10601 (set-buffer frombuf)
10602 (icalendar-export-region (point-min) (point-max) tmpfile)
10603 (setq buf (find-buffer-visiting tmpfile))
10604 (set-buffer buf)
10605 (goto-char (point-min))
10606 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10607 (setq b (match-beginning 0)))
10608 (goto-char (point-max))
10609 (if (re-search-backward "^END:VEVENT" nil t)
10610 (setq e (match-end 0)))
10611 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10612 (kill-buffer buf)
10613 (kill-buffer frombuf)
10614 (delete-file tmpfile)
10615 rtn))
10617 (defun org-closest-date (start current change prefer show-all)
10618 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10619 When PREFER is `past' return a date that is either CURRENT or past.
10620 When PREFER is `future', return a date that is either CURRENT or future.
10621 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10622 ;; Make the proper lists from the dates
10623 (catch 'exit
10624 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10625 dn dw sday cday n1 n2
10626 d m y y1 y2 date1 date2 nmonths nm ny m2)
10628 (setq start (org-date-to-gregorian start)
10629 current (org-date-to-gregorian
10630 (if show-all
10631 current
10632 (time-to-days (current-time))))
10633 sday (calendar-absolute-from-gregorian start)
10634 cday (calendar-absolute-from-gregorian current))
10636 (if (<= cday sday) (throw 'exit sday))
10638 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10639 (setq dn (string-to-number (match-string 1 change))
10640 dw (cdr (assoc (match-string 2 change) a1)))
10641 (error "Invalid change specifyer: %s" change))
10642 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10643 (cond
10644 ((eq dw 'day)
10645 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10646 n2 (+ n1 dn)))
10647 ((eq dw 'year)
10648 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10649 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10650 (setq date1 (list m d y1)
10651 n1 (calendar-absolute-from-gregorian date1)
10652 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10653 n2 (calendar-absolute-from-gregorian date2)))
10654 ((eq dw 'month)
10655 ;; approx number of month between the tow dates
10656 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10657 ;; How often does dn fit in there?
10658 (setq d (nth 1 start) m (car start) y (nth 2 start)
10659 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10660 m (+ m nm)
10661 ny (floor (/ m 12))
10662 y (+ y ny)
10663 m (- m (* ny 12)))
10664 (while (> m 12) (setq m (- m 12) y (1+ y)))
10665 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10666 (setq m2 (+ m dn) y2 y)
10667 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10668 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10669 (while (< n2 cday)
10670 (setq n1 n2 m m2 y y2)
10671 (setq m2 (+ m dn) y2 y)
10672 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10673 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10675 (if show-all
10676 (cond
10677 ((eq prefer 'past) n1)
10678 ((eq prefer 'future) (if (= cday n1) n1 n2))
10679 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10680 (cond
10681 ((eq prefer 'past) n1)
10682 ((eq prefer 'future) (if (= cday n1) n1 n2))
10683 (t (if (= cday n1) n1 n2)))))))
10685 (defun org-date-to-gregorian (date)
10686 "Turn any specification of DATE into a gregorian date for the calendar."
10687 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10688 ((and (listp date) (= (length date) 3)) date)
10689 ((stringp date)
10690 (setq date (org-parse-time-string date))
10691 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10692 ((listp date)
10693 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10695 (defun org-parse-time-string (s &optional nodefault)
10696 "Parse the standard Org-mode time string.
10697 This should be a lot faster than the normal `parse-time-string'.
10698 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10699 hour and minute fields will be nil if not given."
10700 (if (string-match org-ts-regexp0 s)
10701 (list 0
10702 (if (or (match-beginning 8) (not nodefault))
10703 (string-to-number (or (match-string 8 s) "0")))
10704 (if (or (match-beginning 7) (not nodefault))
10705 (string-to-number (or (match-string 7 s) "0")))
10706 (string-to-number (match-string 4 s))
10707 (string-to-number (match-string 3 s))
10708 (string-to-number (match-string 2 s))
10709 nil nil nil)
10710 (make-list 9 0)))
10712 (defun org-timestamp-up (&optional arg)
10713 "Increase the date item at the cursor by one.
10714 If the cursor is on the year, change the year. If it is on the month or
10715 the day, change that.
10716 With prefix ARG, change by that many units."
10717 (interactive "p")
10718 (org-timestamp-change (prefix-numeric-value arg)))
10720 (defun org-timestamp-down (&optional arg)
10721 "Decrease the date item at the cursor by one.
10722 If the cursor is on the year, change the year. If it is on the month or
10723 the day, change that.
10724 With prefix ARG, change by that many units."
10725 (interactive "p")
10726 (org-timestamp-change (- (prefix-numeric-value arg))))
10728 (defun org-timestamp-up-day (&optional arg)
10729 "Increase the date in the time stamp by one day.
10730 With prefix ARG, change that many days."
10731 (interactive "p")
10732 (if (and (not (org-at-timestamp-p t))
10733 (org-on-heading-p))
10734 (org-todo 'up)
10735 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10737 (defun org-timestamp-down-day (&optional arg)
10738 "Decrease the date in the time stamp by one day.
10739 With prefix ARG, change that many days."
10740 (interactive "p")
10741 (if (and (not (org-at-timestamp-p t))
10742 (org-on-heading-p))
10743 (org-todo 'down)
10744 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10746 (defun org-at-timestamp-p (&optional inactive-ok)
10747 "Determine if the cursor is in or at a timestamp."
10748 (interactive)
10749 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10750 (pos (point))
10751 (ans (or (looking-at tsr)
10752 (save-excursion
10753 (skip-chars-backward "^[<\n\r\t")
10754 (if (> (point) (point-min)) (backward-char 1))
10755 (and (looking-at tsr)
10756 (> (- (match-end 0) pos) -1))))))
10757 (and ans
10758 (boundp 'org-ts-what)
10759 (setq org-ts-what
10760 (cond
10761 ((= pos (match-beginning 0)) 'bracket)
10762 ((= pos (1- (match-end 0))) 'bracket)
10763 ((org-pos-in-match-range pos 2) 'year)
10764 ((org-pos-in-match-range pos 3) 'month)
10765 ((org-pos-in-match-range pos 7) 'hour)
10766 ((org-pos-in-match-range pos 8) 'minute)
10767 ((or (org-pos-in-match-range pos 4)
10768 (org-pos-in-match-range pos 5)) 'day)
10769 ((and (> pos (or (match-end 8) (match-end 5)))
10770 (< pos (match-end 0)))
10771 (- pos (or (match-end 8) (match-end 5))))
10772 (t 'day))))
10773 ans))
10775 (defun org-toggle-timestamp-type ()
10776 "Toggle the type (<active> or [inactive]) of a time stamp."
10777 (interactive)
10778 (when (org-at-timestamp-p t)
10779 (save-excursion
10780 (goto-char (match-beginning 0))
10781 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10782 (goto-char (1- (match-end 0)))
10783 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10784 (message "Timestamp is now %sactive"
10785 (if (equal (char-before) ?>) "in" ""))))
10787 (defun org-timestamp-change (n &optional what)
10788 "Change the date in the time stamp at point.
10789 The date will be changed by N times WHAT. WHAT can be `day', `month',
10790 `year', `minute', `second'. If WHAT is not given, the cursor position
10791 in the timestamp determines what will be changed."
10792 (let ((pos (point))
10793 with-hm inactive
10794 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10795 org-ts-what
10796 extra rem
10797 ts time time0)
10798 (if (not (org-at-timestamp-p t))
10799 (error "Not at a timestamp"))
10800 (if (and (not what) (eq org-ts-what 'bracket))
10801 (org-toggle-timestamp-type)
10802 (if (and (not what) (not (eq org-ts-what 'day))
10803 org-display-custom-times
10804 (get-text-property (point) 'display)
10805 (not (get-text-property (1- (point)) 'display)))
10806 (setq org-ts-what 'day))
10807 (setq org-ts-what (or what org-ts-what)
10808 inactive (= (char-after (match-beginning 0)) ?\[)
10809 ts (match-string 0))
10810 (replace-match "")
10811 (if (string-match
10812 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10814 (setq extra (match-string 1 ts)))
10815 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10816 (setq with-hm t))
10817 (setq time0 (org-parse-time-string ts))
10818 (when (and (eq org-ts-what 'minute)
10819 (eq current-prefix-arg nil))
10820 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10821 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10822 (setcar (cdr time0) (+ (nth 1 time0)
10823 (if (> n 0) (- rem) (- dm rem))))))
10824 (setq time
10825 (encode-time (or (car time0) 0)
10826 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10827 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10828 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10829 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10830 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10831 (nthcdr 6 time0)))
10832 (when (integerp org-ts-what)
10833 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10834 (if (eq what 'calendar)
10835 (let ((cal-date (org-get-date-from-calendar)))
10836 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10837 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10838 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10839 (setcar time0 (or (car time0) 0))
10840 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10841 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10842 (setq time (apply 'encode-time time0))))
10843 (setq org-last-changed-timestamp
10844 (org-insert-time-stamp time with-hm inactive nil nil extra))
10845 (org-clock-update-time-maybe)
10846 (goto-char pos)
10847 ;; Try to recenter the calendar window, if any
10848 (if (and org-calendar-follow-timestamp-change
10849 (get-buffer-window "*Calendar*" t)
10850 (memq org-ts-what '(day month year)))
10851 (org-recenter-calendar (time-to-days time))))))
10853 (defun org-modify-ts-extra (s pos n dm)
10854 "Change the different parts of the lead-time and repeat fields in timestamp."
10855 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10856 ng h m new rem)
10857 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10858 (cond
10859 ((or (org-pos-in-match-range pos 2)
10860 (org-pos-in-match-range pos 3))
10861 (setq m (string-to-number (match-string 3 s))
10862 h (string-to-number (match-string 2 s)))
10863 (if (org-pos-in-match-range pos 2)
10864 (setq h (+ h n))
10865 (setq n (* dm (org-no-warnings (signum n))))
10866 (when (not (= 0 (setq rem (% m dm))))
10867 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10868 (setq m (+ m n)))
10869 (if (< m 0) (setq m (+ m 60) h (1- h)))
10870 (if (> m 59) (setq m (- m 60) h (1+ h)))
10871 (setq h (min 24 (max 0 h)))
10872 (setq ng 1 new (format "-%02d:%02d" h m)))
10873 ((org-pos-in-match-range pos 6)
10874 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10875 ((org-pos-in-match-range pos 5)
10876 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10878 ((org-pos-in-match-range pos 9)
10879 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10880 ((org-pos-in-match-range pos 8)
10881 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10883 (when ng
10884 (setq s (concat
10885 (substring s 0 (match-beginning ng))
10887 (substring s (match-end ng))))))
10890 (defun org-recenter-calendar (date)
10891 "If the calendar is visible, recenter it to DATE."
10892 (let* ((win (selected-window))
10893 (cwin (get-buffer-window "*Calendar*" t))
10894 (calendar-move-hook nil))
10895 (when cwin
10896 (select-window cwin)
10897 (calendar-goto-date (if (listp date) date
10898 (calendar-gregorian-from-absolute date)))
10899 (select-window win))))
10901 (defun org-goto-calendar (&optional arg)
10902 "Go to the Emacs calendar at the current date.
10903 If there is a time stamp in the current line, go to that date.
10904 A prefix ARG can be used to force the current date."
10905 (interactive "P")
10906 (let ((tsr org-ts-regexp) diff
10907 (calendar-move-hook nil)
10908 (calendar-view-holidays-initially-flag nil)
10909 (view-calendar-holidays-initially nil)
10910 (calendar-view-diary-initially-flag nil)
10911 (view-diary-entries-initially nil))
10912 (if (or (org-at-timestamp-p)
10913 (save-excursion
10914 (beginning-of-line 1)
10915 (looking-at (concat ".*" tsr))))
10916 (let ((d1 (time-to-days (current-time)))
10917 (d2 (time-to-days
10918 (org-time-string-to-time (match-string 1)))))
10919 (setq diff (- d2 d1))))
10920 (calendar)
10921 (calendar-goto-today)
10922 (if (and diff (not arg)) (calendar-forward-day diff))))
10924 (defun org-get-date-from-calendar ()
10925 "Return a list (month day year) of date at point in calendar."
10926 (with-current-buffer "*Calendar*"
10927 (save-match-data
10928 (calendar-cursor-to-date))))
10930 (defun org-date-from-calendar ()
10931 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
10932 If there is already a time stamp at the cursor position, update it."
10933 (interactive)
10934 (if (org-at-timestamp-p t)
10935 (org-timestamp-change 0 'calendar)
10936 (let ((cal-date (org-get-date-from-calendar)))
10937 (org-insert-time-stamp
10938 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
10940 (defun org-minutes-to-hours (m)
10941 "Compute H:MM from a number of minutes."
10942 (let ((h (/ m 60)))
10943 (setq m (- m (* 60 h)))
10944 (format "%d:%02d" h m)))
10947 ;;;; Agenda files
10949 ;;;###autoload
10950 (defun org-iswitchb (&optional arg)
10951 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
10952 With a prefix argument, restrict available to files.
10953 With two prefix arguments, restrict available buffers to agenda files.
10955 Due to some yet unresolved reason, global function
10956 `iswitchb-mode' needs to be active for this function to work."
10957 (interactive "P")
10958 (require 'iswitchb)
10959 (let ((enabled iswitchb-mode) blist)
10960 (or enabled (iswitchb-mode 1))
10961 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
10962 ((equal arg '(16)) (org-buffer-list 'agenda))
10963 (t (org-buffer-list))))
10964 (unwind-protect
10965 (let ((iswitchb-make-buflist-hook
10966 (lambda ()
10967 (setq iswitchb-temp-buflist
10968 (mapcar 'buffer-name blist)))))
10969 (switch-to-buffer
10970 (iswitchb-read-buffer
10971 "Switch-to: " nil t))
10972 (or enabled (iswitchb-mode -1))))))
10974 (defun org-buffer-list (&optional predicate tmp)
10975 "Return a list of Org buffers.
10976 PREDICATE can be either 'export, 'files or 'agenda.
10978 'export restrict the list to Export buffers.
10979 'files restrict the list to buffers visiting Org files.
10980 'agenda restrict the list to buffers visiting agenda files.
10982 If TMP is non-nil, don't include temporary buffers."
10983 (let (filter blist)
10984 (setq filter
10985 (cond ((eq predicate 'files) "\.org$")
10986 ((eq predicate 'export) "\*Org .*Export")
10987 (t "\*Org \\|\.org$")))
10988 (setq blist
10989 (mapcar
10990 (lambda(b)
10991 (let ((bname (buffer-name b))
10992 (bfile (buffer-file-name b)))
10993 (if (and (string-match filter bname)
10994 (if (eq predicate 'agenda)
10995 (member bfile
10996 (mapcar (lambda(f) (file-truename f))
10997 org-agenda-files)) t)
10998 (if tmp (not (string-match "tmp" bname)) t)) b)))
10999 (buffer-list)))
11000 (delete nil blist)))
11002 (defun org-agenda-files (&optional unrestricted)
11003 "Get the list of agenda files.
11004 Optional UNRESTRICTED means return the full list even if a restriction
11005 is currently in place."
11006 (let ((files
11007 (cond
11008 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11009 ((stringp org-agenda-files) (org-read-agenda-file-list))
11010 ((listp org-agenda-files) org-agenda-files)
11011 (t (error "Invalid value of `org-agenda-files'")))))
11012 (setq files (apply 'append
11013 (mapcar (lambda (f)
11014 (if (file-directory-p f)
11015 (directory-files f t
11016 org-agenda-file-regexp)
11017 (list f)))
11018 files)))
11019 (if org-agenda-skip-unavailable-files
11020 (delq nil
11021 (mapcar (function
11022 (lambda (file)
11023 (and (file-readable-p file) file)))
11024 files))
11025 files))) ; `org-check-agenda-file' will remove them from the list
11027 (defun org-edit-agenda-file-list ()
11028 "Edit the list of agenda files.
11029 Depending on setup, this either uses customize to edit the variable
11030 `org-agenda-files', or it visits the file that is holding the list. In the
11031 latter case, the buffer is set up in a way that saving it automatically kills
11032 the buffer and restores the previous window configuration."
11033 (interactive)
11034 (if (stringp org-agenda-files)
11035 (let ((cw (current-window-configuration)))
11036 (find-file org-agenda-files)
11037 (org-set-local 'org-window-configuration cw)
11038 (org-add-hook 'after-save-hook
11039 (lambda ()
11040 (set-window-configuration
11041 (prog1 org-window-configuration
11042 (kill-buffer (current-buffer))))
11043 (org-install-agenda-files-menu)
11044 (message "New agenda file list installed"))
11045 nil 'local)
11046 (message "%s" (substitute-command-keys
11047 "Edit list and finish with \\[save-buffer]")))
11048 (customize-variable 'org-agenda-files)))
11050 (defun org-store-new-agenda-file-list (list)
11051 "Set new value for the agenda file list and save it correcly."
11052 (if (stringp org-agenda-files)
11053 (let ((f org-agenda-files) b)
11054 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11055 (with-temp-file f
11056 (insert (mapconcat 'identity list "\n") "\n")))
11057 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11058 (setq org-agenda-files list)
11059 (customize-save-variable 'org-agenda-files org-agenda-files))))
11061 (defun org-read-agenda-file-list ()
11062 "Read the list of agenda files from a file."
11063 (when (stringp org-agenda-files)
11064 (with-temp-buffer
11065 (insert-file-contents org-agenda-files)
11066 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11069 ;;;###autoload
11070 (defun org-cycle-agenda-files ()
11071 "Cycle through the files in `org-agenda-files'.
11072 If the current buffer visits an agenda file, find the next one in the list.
11073 If the current buffer does not, find the first agenda file."
11074 (interactive)
11075 (let* ((fs (org-agenda-files t))
11076 (files (append fs (list (car fs))))
11077 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11078 file)
11079 (unless files (error "No agenda files"))
11080 (catch 'exit
11081 (while (setq file (pop files))
11082 (if (equal (file-truename file) tcf)
11083 (when (car files)
11084 (find-file (car files))
11085 (throw 'exit t))))
11086 (find-file (car fs)))
11087 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11089 (defun org-agenda-file-to-front (&optional to-end)
11090 "Move/add the current file to the top of the agenda file list.
11091 If the file is not present in the list, it is added to the front. If it is
11092 present, it is moved there. With optional argument TO-END, add/move to the
11093 end of the list."
11094 (interactive "P")
11095 (let ((org-agenda-skip-unavailable-files nil)
11096 (file-alist (mapcar (lambda (x)
11097 (cons (file-truename x) x))
11098 (org-agenda-files t)))
11099 (ctf (file-truename buffer-file-name))
11100 x had)
11101 (setq x (assoc ctf file-alist) had x)
11103 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11104 (if to-end
11105 (setq file-alist (append (delq x file-alist) (list x)))
11106 (setq file-alist (cons x (delq x file-alist))))
11107 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11108 (org-install-agenda-files-menu)
11109 (message "File %s to %s of agenda file list"
11110 (if had "moved" "added") (if to-end "end" "front"))))
11112 (defun org-remove-file (&optional file)
11113 "Remove current file from the list of files in variable `org-agenda-files'.
11114 These are the files which are being checked for agenda entries.
11115 Optional argument FILE means, use this file instead of the current."
11116 (interactive)
11117 (let* ((org-agenda-skip-unavailable-files nil)
11118 (file (or file buffer-file-name))
11119 (true-file (file-truename file))
11120 (afile (abbreviate-file-name file))
11121 (files (delq nil (mapcar
11122 (lambda (x)
11123 (if (equal true-file
11124 (file-truename x))
11125 nil x))
11126 (org-agenda-files t)))))
11127 (if (not (= (length files) (length (org-agenda-files t))))
11128 (progn
11129 (org-store-new-agenda-file-list files)
11130 (org-install-agenda-files-menu)
11131 (message "Removed file: %s" afile))
11132 (message "File was not in list: %s (not removed)" afile))))
11134 (defun org-file-menu-entry (file)
11135 (vector file (list 'find-file file) t))
11137 (defun org-check-agenda-file (file)
11138 "Make sure FILE exists. If not, ask user what to do."
11139 (when (not (file-exists-p file))
11140 (message "non-existent file %s. [R]emove from list or [A]bort?"
11141 (abbreviate-file-name file))
11142 (let ((r (downcase (read-char-exclusive))))
11143 (cond
11144 ((equal r ?r)
11145 (org-remove-file file)
11146 (throw 'nextfile t))
11147 (t (error "Abort"))))))
11149 (defun org-get-agenda-file-buffer (file)
11150 "Get a buffer visiting FILE. If the buffer needs to be created, add
11151 it to the list of buffers which might be released later."
11152 (let ((buf (org-find-base-buffer-visiting file)))
11153 (if buf
11154 buf ; just return it
11155 ;; Make a new buffer and remember it
11156 (setq buf (find-file-noselect file))
11157 (if buf (push buf org-agenda-new-buffers))
11158 buf)))
11160 (defun org-release-buffers (blist)
11161 "Release all buffers in list, asking the user for confirmation when needed.
11162 When a buffer is unmodified, it is just killed. When modified, it is saved
11163 \(if the user agrees) and then killed."
11164 (let (buf file)
11165 (while (setq buf (pop blist))
11166 (setq file (buffer-file-name buf))
11167 (when (and (buffer-modified-p buf)
11168 file
11169 (y-or-n-p (format "Save file %s? " file)))
11170 (with-current-buffer buf (save-buffer)))
11171 (kill-buffer buf))))
11173 (defun org-prepare-agenda-buffers (files)
11174 "Create buffers for all agenda files, protect archived trees and comments."
11175 (interactive)
11176 (let ((pa '(:org-archived t))
11177 (pc '(:org-comment t))
11178 (pall '(:org-archived t :org-comment t))
11179 (inhibit-read-only t)
11180 (rea (concat ":" org-archive-tag ":"))
11181 bmp file re)
11182 (save-excursion
11183 (save-restriction
11184 (while (setq file (pop files))
11185 (if (bufferp file)
11186 (set-buffer file)
11187 (org-check-agenda-file file)
11188 (set-buffer (org-get-agenda-file-buffer file)))
11189 (widen)
11190 (setq bmp (buffer-modified-p))
11191 (org-refresh-category-properties)
11192 (setq org-todo-keywords-for-agenda
11193 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11194 (setq org-done-keywords-for-agenda
11195 (append org-done-keywords-for-agenda org-done-keywords))
11196 (save-excursion
11197 (remove-text-properties (point-min) (point-max) pall)
11198 (when org-agenda-skip-archived-trees
11199 (goto-char (point-min))
11200 (while (re-search-forward rea nil t)
11201 (if (org-on-heading-p t)
11202 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11203 (goto-char (point-min))
11204 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11205 (while (re-search-forward re nil t)
11206 (add-text-properties
11207 (match-beginning 0) (org-end-of-subtree t) pc)))
11208 (set-buffer-modified-p bmp))))))
11210 ;;;; Embedded LaTeX
11212 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11213 "Keymap for the minor `org-cdlatex-mode'.")
11215 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11216 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11217 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11218 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11219 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11221 (defvar org-cdlatex-texmathp-advice-is-done nil
11222 "Flag remembering if we have applied the advice to texmathp already.")
11224 (define-minor-mode org-cdlatex-mode
11225 "Toggle the minor `org-cdlatex-mode'.
11226 This mode supports entering LaTeX environment and math in LaTeX fragments
11227 in Org-mode.
11228 \\{org-cdlatex-mode-map}"
11229 nil " OCDL" nil
11230 (when org-cdlatex-mode (require 'cdlatex))
11231 (unless org-cdlatex-texmathp-advice-is-done
11232 (setq org-cdlatex-texmathp-advice-is-done t)
11233 (defadvice texmathp (around org-math-always-on activate)
11234 "Always return t in org-mode buffers.
11235 This is because we want to insert math symbols without dollars even outside
11236 the LaTeX math segments. If Orgmode thinks that point is actually inside
11237 en embedded LaTeX fragement, let texmathp do its job.
11238 \\[org-cdlatex-mode-map]"
11239 (interactive)
11240 (let (p)
11241 (cond
11242 ((not (org-mode-p)) ad-do-it)
11243 ((eq this-command 'cdlatex-math-symbol)
11244 (setq ad-return-value t
11245 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11247 (let ((p (org-inside-LaTeX-fragment-p)))
11248 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11249 (setq ad-return-value t
11250 texmathp-why '("Org-mode embedded math" . 0))
11251 (if p ad-do-it)))))))))
11253 (defun turn-on-org-cdlatex ()
11254 "Unconditionally turn on `org-cdlatex-mode'."
11255 (org-cdlatex-mode 1))
11257 (defun org-inside-LaTeX-fragment-p ()
11258 "Test if point is inside a LaTeX fragment.
11259 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11260 sequence appearing also before point.
11261 Even though the matchers for math are configurable, this function assumes
11262 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11263 delimiters are skipped when they have been removed by customization.
11264 The return value is nil, or a cons cell with the delimiter and
11265 and the position of this delimiter.
11267 This function does a reasonably good job, but can locally be fooled by
11268 for example currency specifications. For example it will assume being in
11269 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11270 fragments that are properly closed, but during editing, we have to live
11271 with the uncertainty caused by missing closing delimiters. This function
11272 looks only before point, not after."
11273 (catch 'exit
11274 (let ((pos (point))
11275 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11276 (lim (progn
11277 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11278 (point)))
11279 dd-on str (start 0) m re)
11280 (goto-char pos)
11281 (when dodollar
11282 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11283 re (nth 1 (assoc "$" org-latex-regexps)))
11284 (while (string-match re str start)
11285 (cond
11286 ((= (match-end 0) (length str))
11287 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11288 ((= (match-end 0) (- (length str) 5))
11289 (throw 'exit nil))
11290 (t (setq start (match-end 0))))))
11291 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11292 (goto-char pos)
11293 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11294 (and (match-beginning 2) (throw 'exit nil))
11295 ;; count $$
11296 (while (re-search-backward "\\$\\$" lim t)
11297 (setq dd-on (not dd-on)))
11298 (goto-char pos)
11299 (if dd-on (cons "$$" m))))))
11302 (defun org-try-cdlatex-tab ()
11303 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11304 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11305 - inside a LaTeX fragment, or
11306 - after the first word in a line, where an abbreviation expansion could
11307 insert a LaTeX environment."
11308 (when org-cdlatex-mode
11309 (cond
11310 ((save-excursion
11311 (skip-chars-backward "a-zA-Z0-9*")
11312 (skip-chars-backward " \t")
11313 (bolp))
11314 (cdlatex-tab) t)
11315 ((org-inside-LaTeX-fragment-p)
11316 (cdlatex-tab) t)
11317 (t nil))))
11319 (defun org-cdlatex-underscore-caret (&optional arg)
11320 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11321 Revert to the normal definition outside of these fragments."
11322 (interactive "P")
11323 (if (org-inside-LaTeX-fragment-p)
11324 (call-interactively 'cdlatex-sub-superscript)
11325 (let (org-cdlatex-mode)
11326 (call-interactively (key-binding (vector last-input-event))))))
11328 (defun org-cdlatex-math-modify (&optional arg)
11329 "Execute `cdlatex-math-modify' in LaTeX fragments.
11330 Revert to the normal definition outside of these fragments."
11331 (interactive "P")
11332 (if (org-inside-LaTeX-fragment-p)
11333 (call-interactively 'cdlatex-math-modify)
11334 (let (org-cdlatex-mode)
11335 (call-interactively (key-binding (vector last-input-event))))))
11337 (defvar org-latex-fragment-image-overlays nil
11338 "List of overlays carrying the images of latex fragments.")
11339 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11341 (defun org-remove-latex-fragment-image-overlays ()
11342 "Remove all overlays with LaTeX fragment images in current buffer."
11343 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11344 (setq org-latex-fragment-image-overlays nil))
11346 (defun org-preview-latex-fragment (&optional subtree)
11347 "Preview the LaTeX fragment at point, or all locally or globally.
11348 If the cursor is in a LaTeX fragment, create the image and overlay
11349 it over the source code. If there is no fragment at point, display
11350 all fragments in the current text, from one headline to the next. With
11351 prefix SUBTREE, display all fragments in the current subtree. With a
11352 double prefix `C-u C-u', or when the cursor is before the first headline,
11353 display all fragments in the buffer.
11354 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11355 (interactive "P")
11356 (org-remove-latex-fragment-image-overlays)
11357 (save-excursion
11358 (save-restriction
11359 (let (beg end at msg)
11360 (cond
11361 ((or (equal subtree '(16))
11362 (not (save-excursion
11363 (re-search-backward (concat "^" outline-regexp) nil t))))
11364 (setq beg (point-min) end (point-max)
11365 msg "Creating images for buffer...%s"))
11366 ((equal subtree '(4))
11367 (org-back-to-heading)
11368 (setq beg (point) end (org-end-of-subtree t)
11369 msg "Creating images for subtree...%s"))
11371 (if (setq at (org-inside-LaTeX-fragment-p))
11372 (goto-char (max (point-min) (- (cdr at) 2)))
11373 (org-back-to-heading))
11374 (setq beg (point) end (progn (outline-next-heading) (point))
11375 msg (if at "Creating image...%s"
11376 "Creating images for entry...%s"))))
11377 (message msg "")
11378 (narrow-to-region beg end)
11379 (goto-char beg)
11380 (org-format-latex
11381 (concat "ltxpng/" (file-name-sans-extension
11382 (file-name-nondirectory
11383 buffer-file-name)))
11384 default-directory 'overlays msg at 'forbuffer)
11385 (message msg "done. Use `C-c C-c' to remove images.")))))
11387 (defvar org-latex-regexps
11388 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11389 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11390 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11391 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11392 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11393 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11394 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11395 "Regular expressions for matching embedded LaTeX.")
11397 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11398 "Replace LaTeX fragments with links to an image, and produce images."
11399 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11400 (let* ((prefixnodir (file-name-nondirectory prefix))
11401 (absprefix (expand-file-name prefix dir))
11402 (todir (file-name-directory absprefix))
11403 (opt org-format-latex-options)
11404 (matchers (plist-get opt :matchers))
11405 (re-list org-latex-regexps)
11406 (cnt 0) txt link beg end re e checkdir
11407 m n block linkfile movefile ov)
11408 ;; Check if there are old images files with this prefix, and remove them
11409 (when (file-directory-p todir)
11410 (mapc 'delete-file
11411 (directory-files
11412 todir 'full
11413 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11414 ;; Check the different regular expressions
11415 (while (setq e (pop re-list))
11416 (setq m (car e) re (nth 1 e) n (nth 2 e)
11417 block (if (nth 3 e) "\n\n" ""))
11418 (when (member m matchers)
11419 (goto-char (point-min))
11420 (while (re-search-forward re nil t)
11421 (when (or (not at) (equal (cdr at) (match-beginning n)))
11422 (setq txt (match-string n)
11423 beg (match-beginning n) end (match-end n)
11424 cnt (1+ cnt)
11425 linkfile (format "%s_%04d.png" prefix cnt)
11426 movefile (format "%s_%04d.png" absprefix cnt)
11427 link (concat block "[[file:" linkfile "]]" block))
11428 (if msg (message msg cnt))
11429 (goto-char beg)
11430 (unless checkdir ; make sure the directory exists
11431 (setq checkdir t)
11432 (or (file-directory-p todir) (make-directory todir)))
11433 (org-create-formula-image
11434 txt movefile opt forbuffer)
11435 (if overlays
11436 (progn
11437 (setq ov (org-make-overlay beg end))
11438 (if (featurep 'xemacs)
11439 (progn
11440 (org-overlay-put ov 'invisible t)
11441 (org-overlay-put
11442 ov 'end-glyph
11443 (make-glyph (vector 'png :file movefile))))
11444 (org-overlay-put
11445 ov 'display
11446 (list 'image :type 'png :file movefile :ascent 'center)))
11447 (push ov org-latex-fragment-image-overlays)
11448 (goto-char end))
11449 (delete-region beg end)
11450 (insert link))))))))
11452 ;; This function borrows from Ganesh Swami's latex2png.el
11453 (defun org-create-formula-image (string tofile options buffer)
11454 (let* ((tmpdir (if (featurep 'xemacs)
11455 (temp-directory)
11456 temporary-file-directory))
11457 (texfilebase (make-temp-name
11458 (expand-file-name "orgtex" tmpdir)))
11459 (texfile (concat texfilebase ".tex"))
11460 (dvifile (concat texfilebase ".dvi"))
11461 (pngfile (concat texfilebase ".png"))
11462 (fnh (face-attribute 'default :height nil))
11463 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11464 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11465 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11466 "Black"))
11467 (bg (or (plist-get options (if buffer :background :html-background))
11468 "Transparent")))
11469 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11470 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11471 (with-temp-file texfile
11472 (insert org-format-latex-header
11473 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11474 (let ((dir default-directory))
11475 (condition-case nil
11476 (progn
11477 (cd tmpdir)
11478 (call-process "latex" nil nil nil texfile))
11479 (error nil))
11480 (cd dir))
11481 (if (not (file-exists-p dvifile))
11482 (progn (message "Failed to create dvi file from %s" texfile) nil)
11483 (call-process "dvipng" nil nil nil
11484 "-E" "-fg" fg "-bg" bg
11485 "-D" dpi
11486 ;;"-x" scale "-y" scale
11487 "-T" "tight"
11488 "-o" pngfile
11489 dvifile)
11490 (if (not (file-exists-p pngfile))
11491 (progn (message "Failed to create png file from %s" texfile) nil)
11492 ;; Use the requested file name and clean up
11493 (copy-file pngfile tofile 'replace)
11494 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11495 (delete-file (concat texfilebase e)))
11496 pngfile))))
11498 (defun org-dvipng-color (attr)
11499 "Return an rgb color specification for dvipng."
11500 (apply 'format "rgb %s %s %s"
11501 (mapcar 'org-normalize-color
11502 (color-values (face-attribute 'default attr nil)))))
11504 (defun org-normalize-color (value)
11505 "Return string to be used as color value for an RGB component."
11506 (format "%g" (/ value 65535.0)))
11509 ;;;; Key bindings
11511 ;; Make `C-c C-x' a prefix key
11512 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11514 ;; TAB key with modifiers
11515 (org-defkey org-mode-map "\C-i" 'org-cycle)
11516 (org-defkey org-mode-map [(tab)] 'org-cycle)
11517 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11518 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11519 (org-defkey org-mode-map "\M-\t" 'org-complete)
11520 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11521 ;; The following line is necessary under Suse GNU/Linux
11522 (unless (featurep 'xemacs)
11523 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11524 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11525 (define-key org-mode-map [backtab] 'org-shifttab)
11527 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11528 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11529 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11531 ;; Cursor keys with modifiers
11532 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11533 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11534 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11535 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11537 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11538 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11539 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11540 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11542 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11543 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11544 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11545 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11547 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11548 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11550 ;;; Extra keys for tty access.
11551 ;; We only set them when really needed because otherwise the
11552 ;; menus don't show the simple keys
11554 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11555 (not window-system))
11556 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11557 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11558 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11559 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11560 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11561 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11562 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11563 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11564 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11565 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11566 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11567 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11568 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11569 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11570 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11571 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11572 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11573 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11574 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11575 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11576 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11577 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11579 ;; All the other keys
11581 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11582 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11583 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11584 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11585 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11586 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11587 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11588 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11589 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11590 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11591 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11592 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11593 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11594 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11595 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11596 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11597 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11598 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11599 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11600 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11601 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11602 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11603 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11604 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11605 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11606 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11607 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11608 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11609 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11610 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11611 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11612 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11613 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11614 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11615 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11616 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11617 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11618 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11619 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11620 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11621 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11622 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11623 (org-defkey org-mode-map "\C-c^" 'org-sort)
11624 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11625 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11626 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11627 (org-defkey org-mode-map "\C-m" 'org-return)
11628 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11629 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11630 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11631 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11632 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11633 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11634 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11635 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11636 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11637 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11638 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11639 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11640 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11641 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11642 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11643 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11645 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11646 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11647 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11648 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11650 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11651 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11652 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11653 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11654 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11655 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11656 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11657 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11658 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11659 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11660 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11661 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11663 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11665 (when (featurep 'xemacs)
11666 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11668 (defvar org-table-auto-blank-field) ; defined in org-table.el
11669 (defun org-self-insert-command (N)
11670 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11671 If the cursor is in a table looking at whitespace, the whitespace is
11672 overwritten, and the table is not marked as requiring realignment."
11673 (interactive "p")
11674 (if (and (org-table-p)
11675 (progn
11676 ;; check if we blank the field, and if that triggers align
11677 (and (featurep 'org-table) org-table-auto-blank-field
11678 (member last-command
11679 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11680 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11681 ;; got extra space, this field does not determine column width
11682 (let (org-table-may-need-update) (org-table-blank-field))
11683 ;; no extra space, this field may determine column width
11684 (org-table-blank-field)))
11686 (eq N 1)
11687 (looking-at "[^|\n]* |"))
11688 (let (org-table-may-need-update)
11689 (goto-char (1- (match-end 0)))
11690 (delete-backward-char 1)
11691 (goto-char (match-beginning 0))
11692 (self-insert-command N))
11693 (setq org-table-may-need-update t)
11694 (self-insert-command N)
11695 (org-fix-tags-on-the-fly)))
11697 (defun org-fix-tags-on-the-fly ()
11698 (when (and (equal (char-after (point-at-bol)) ?*)
11699 (org-on-heading-p))
11700 (org-align-tags-here org-tags-column)))
11702 (defun org-delete-backward-char (N)
11703 "Like `delete-backward-char', insert whitespace at field end in tables.
11704 When deleting backwards, in tables this function will insert whitespace in
11705 front of the next \"|\" separator, to keep the table aligned. The table will
11706 still be marked for re-alignment if the field did fill the entire column,
11707 because, in this case the deletion might narrow the column."
11708 (interactive "p")
11709 (if (and (org-table-p)
11710 (eq N 1)
11711 (string-match "|" (buffer-substring (point-at-bol) (point)))
11712 (looking-at ".*?|"))
11713 (let ((pos (point))
11714 (noalign (looking-at "[^|\n\r]* |"))
11715 (c org-table-may-need-update))
11716 (backward-delete-char N)
11717 (skip-chars-forward "^|")
11718 (insert " ")
11719 (goto-char (1- pos))
11720 ;; noalign: if there were two spaces at the end, this field
11721 ;; does not determine the width of the column.
11722 (if noalign (setq org-table-may-need-update c)))
11723 (backward-delete-char N)
11724 (org-fix-tags-on-the-fly)))
11726 (defun org-delete-char (N)
11727 "Like `delete-char', but insert whitespace at field end in tables.
11728 When deleting characters, in tables this function will insert whitespace in
11729 front of the next \"|\" separator, to keep the table aligned. The table will
11730 still be marked for re-alignment if the field did fill the entire column,
11731 because, in this case the deletion might narrow the column."
11732 (interactive "p")
11733 (if (and (org-table-p)
11734 (not (bolp))
11735 (not (= (char-after) ?|))
11736 (eq N 1))
11737 (if (looking-at ".*?|")
11738 (let ((pos (point))
11739 (noalign (looking-at "[^|\n\r]* |"))
11740 (c org-table-may-need-update))
11741 (replace-match (concat
11742 (substring (match-string 0) 1 -1)
11743 " |"))
11744 (goto-char pos)
11745 ;; noalign: if there were two spaces at the end, this field
11746 ;; does not determine the width of the column.
11747 (if noalign (setq org-table-may-need-update c)))
11748 (delete-char N))
11749 (delete-char N)
11750 (org-fix-tags-on-the-fly)))
11752 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11753 (put 'org-self-insert-command 'delete-selection t)
11754 (put 'orgtbl-self-insert-command 'delete-selection t)
11755 (put 'org-delete-char 'delete-selection 'supersede)
11756 (put 'org-delete-backward-char 'delete-selection 'supersede)
11758 ;; Make `flyspell-mode' delay after some commands
11759 (put 'org-self-insert-command 'flyspell-delayed t)
11760 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11761 (put 'org-delete-char 'flyspell-delayed t)
11762 (put 'org-delete-backward-char 'flyspell-delayed t)
11764 ;; Make pabbrev-mode expand after org-mode commands
11765 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11766 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11768 ;; How to do this: Measure non-white length of current string
11769 ;; If equal to column width, we should realign.
11771 (defun org-remap (map &rest commands)
11772 "In MAP, remap the functions given in COMMANDS.
11773 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11774 (let (new old)
11775 (while commands
11776 (setq old (pop commands) new (pop commands))
11777 (if (fboundp 'command-remapping)
11778 (org-defkey map (vector 'remap old) new)
11779 (substitute-key-definition old new map global-map)))))
11781 (when (eq org-enable-table-editor 'optimized)
11782 ;; If the user wants maximum table support, we need to hijack
11783 ;; some standard editing functions
11784 (org-remap org-mode-map
11785 'self-insert-command 'org-self-insert-command
11786 'delete-char 'org-delete-char
11787 'delete-backward-char 'org-delete-backward-char)
11788 (org-defkey org-mode-map "|" 'org-force-self-insert))
11790 (defun org-shiftcursor-error ()
11791 "Throw an error because Shift-Cursor command was applied in wrong context."
11792 (error "This command is active in special context like tables, headlines or timestamps"))
11794 (defun org-shifttab (&optional arg)
11795 "Global visibility cycling or move to previous table field.
11796 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11797 on context.
11798 See the individual commands for more information."
11799 (interactive "P")
11800 (cond
11801 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11802 (arg (message "Content view to level: ")
11803 (org-content (prefix-numeric-value arg))
11804 (setq org-cycle-global-status 'overview))
11805 (t (call-interactively 'org-global-cycle))))
11807 (defun org-shiftmetaleft ()
11808 "Promote subtree or delete table column.
11809 Calls `org-promote-subtree', `org-outdent-item',
11810 or `org-table-delete-column', depending on context.
11811 See the individual commands for more information."
11812 (interactive)
11813 (cond
11814 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11815 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11816 ((org-at-item-p) (call-interactively 'org-outdent-item))
11817 (t (org-shiftcursor-error))))
11819 (defun org-shiftmetaright ()
11820 "Demote subtree or insert table column.
11821 Calls `org-demote-subtree', `org-indent-item',
11822 or `org-table-insert-column', depending on context.
11823 See the individual commands for more information."
11824 (interactive)
11825 (cond
11826 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11827 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11828 ((org-at-item-p) (call-interactively 'org-indent-item))
11829 (t (org-shiftcursor-error))))
11831 (defun org-shiftmetaup (&optional arg)
11832 "Move subtree up or kill table row.
11833 Calls `org-move-subtree-up' or `org-table-kill-row' or
11834 `org-move-item-up' depending on context. See the individual commands
11835 for more information."
11836 (interactive "P")
11837 (cond
11838 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11839 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11840 ((org-at-item-p) (call-interactively 'org-move-item-up))
11841 (t (org-shiftcursor-error))))
11842 (defun org-shiftmetadown (&optional arg)
11843 "Move subtree down or insert table row.
11844 Calls `org-move-subtree-down' or `org-table-insert-row' or
11845 `org-move-item-down', depending on context. See the individual
11846 commands for more information."
11847 (interactive "P")
11848 (cond
11849 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11850 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11851 ((org-at-item-p) (call-interactively 'org-move-item-down))
11852 (t (org-shiftcursor-error))))
11854 (defun org-metaleft (&optional arg)
11855 "Promote heading or move table column to left.
11856 Calls `org-do-promote' or `org-table-move-column', depending on context.
11857 With no specific context, calls the Emacs default `backward-word'.
11858 See the individual commands for more information."
11859 (interactive "P")
11860 (cond
11861 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11862 ((or (org-on-heading-p) (org-region-active-p))
11863 (call-interactively 'org-do-promote))
11864 ((org-at-item-p) (call-interactively 'org-outdent-item))
11865 (t (call-interactively 'backward-word))))
11867 (defun org-metaright (&optional arg)
11868 "Demote subtree or move table column to right.
11869 Calls `org-do-demote' or `org-table-move-column', depending on context.
11870 With no specific context, calls the Emacs default `forward-word'.
11871 See the individual commands for more information."
11872 (interactive "P")
11873 (cond
11874 ((org-at-table-p) (call-interactively 'org-table-move-column))
11875 ((or (org-on-heading-p) (org-region-active-p))
11876 (call-interactively 'org-do-demote))
11877 ((org-at-item-p) (call-interactively 'org-indent-item))
11878 (t (call-interactively 'forward-word))))
11880 (defun org-metaup (&optional arg)
11881 "Move subtree up or move table row up.
11882 Calls `org-move-subtree-up' or `org-table-move-row' or
11883 `org-move-item-up', depending on context. See the individual commands
11884 for more information."
11885 (interactive "P")
11886 (cond
11887 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
11888 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11889 ((org-at-item-p) (call-interactively 'org-move-item-up))
11890 (t (transpose-lines 1) (beginning-of-line -1))))
11892 (defun org-metadown (&optional arg)
11893 "Move subtree down or move table row down.
11894 Calls `org-move-subtree-down' or `org-table-move-row' or
11895 `org-move-item-down', depending on context. See the individual
11896 commands for more information."
11897 (interactive "P")
11898 (cond
11899 ((org-at-table-p) (call-interactively 'org-table-move-row))
11900 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11901 ((org-at-item-p) (call-interactively 'org-move-item-down))
11902 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
11904 (defun org-shiftup (&optional arg)
11905 "Increase item in timestamp or increase priority of current headline.
11906 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
11907 depending on context. See the individual commands for more information."
11908 (interactive "P")
11909 (cond
11910 ((org-at-timestamp-p t)
11911 (call-interactively (if org-edit-timestamp-down-means-later
11912 'org-timestamp-down 'org-timestamp-up)))
11913 ((org-on-heading-p) (call-interactively 'org-priority-up))
11914 ((org-at-item-p) (call-interactively 'org-previous-item))
11915 ((org-clocktable-try-shift 'up arg))
11916 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
11918 (defun org-shiftdown (&optional arg)
11919 "Decrease item in timestamp or decrease priority of current headline.
11920 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
11921 depending on context. See the individual commands for more information."
11922 (interactive "P")
11923 (cond
11924 ((org-at-timestamp-p t)
11925 (call-interactively (if org-edit-timestamp-down-means-later
11926 'org-timestamp-up 'org-timestamp-down)))
11927 ((org-on-heading-p) (call-interactively 'org-priority-down))
11928 ((org-clocktable-try-shift 'down arg))
11929 (t (call-interactively 'org-next-item))))
11931 (defun org-shiftright (&optional arg)
11932 "Next TODO keyword or timestamp one day later, depending on context."
11933 (interactive "P")
11934 (cond
11935 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
11936 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
11937 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
11938 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
11939 ((org-clocktable-try-shift 'right arg))
11940 (t (org-shiftcursor-error))))
11942 (defun org-shiftleft (&optional arg)
11943 "Previous TODO keyword or timestamp one day earlier, depending on context."
11944 (interactive "P")
11945 (cond
11946 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
11947 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
11948 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
11949 ((org-at-property-p)
11950 (call-interactively 'org-property-previous-allowed-value))
11951 ((org-clocktable-try-shift 'left arg))
11952 (t (org-shiftcursor-error))))
11954 (defun org-shiftcontrolright ()
11955 "Switch to next TODO set."
11956 (interactive)
11957 (cond
11958 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
11959 (t (org-shiftcursor-error))))
11961 (defun org-shiftcontrolleft ()
11962 "Switch to previous TODO set."
11963 (interactive)
11964 (cond
11965 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
11966 (t (org-shiftcursor-error))))
11968 (defun org-ctrl-c-ret ()
11969 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
11970 (interactive)
11971 (cond
11972 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
11973 (t (call-interactively 'org-insert-heading))))
11975 (defun org-copy-special ()
11976 "Copy region in table or copy current subtree.
11977 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11978 See the individual commands for more information."
11979 (interactive)
11980 (call-interactively
11981 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11983 (defun org-cut-special ()
11984 "Cut region in table or cut current subtree.
11985 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11986 See the individual commands for more information."
11987 (interactive)
11988 (call-interactively
11989 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11991 (defun org-paste-special (arg)
11992 "Paste rectangular region into table, or past subtree relative to level.
11993 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11994 See the individual commands for more information."
11995 (interactive "P")
11996 (if (org-at-table-p)
11997 (org-table-paste-rectangle)
11998 (org-paste-subtree arg)))
12000 (defun org-ctrl-c-ctrl-c (&optional arg)
12001 "Set tags in headline, or update according to changed information at point.
12003 This command does many different things, depending on context:
12005 - If the cursor is in a headline, prompt for tags and insert them
12006 into the current line, aligned to `org-tags-column'. When called
12007 with prefix arg, realign all tags in the current buffer.
12009 - If the cursor is in one of the special #+KEYWORD lines, this
12010 triggers scanning the buffer for these lines and updating the
12011 information.
12013 - If the cursor is inside a table, realign the table. This command
12014 works even if the automatic table editor has been turned off.
12016 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12017 the entire table.
12019 - If the cursor is a the beginning of a dynamic block, update it.
12021 - If the cursor is inside a table created by the table.el package,
12022 activate that table.
12024 - If the current buffer is a remember buffer, close note and file it.
12025 with a prefix argument, file it without further interaction to the default
12026 location.
12028 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12029 links in this buffer.
12031 - If the cursor is on a numbered item in a plain list, renumber the
12032 ordered list.
12034 - If the cursor is on a checkbox, toggle it."
12035 (interactive "P")
12036 (let ((org-enable-table-editor t))
12037 (cond
12038 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12039 org-occur-highlights
12040 org-latex-fragment-image-overlays)
12041 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12042 (org-remove-occur-highlights)
12043 (org-remove-latex-fragment-image-overlays)
12044 (message "Temporary highlights/overlays removed from current buffer"))
12045 ((and (local-variable-p 'org-finish-function (current-buffer))
12046 (fboundp org-finish-function))
12047 (funcall org-finish-function))
12048 ((org-at-property-p)
12049 (call-interactively 'org-property-action))
12050 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12051 ((org-on-heading-p) (call-interactively 'org-set-tags))
12052 ((org-at-table.el-p)
12053 (require 'table)
12054 (beginning-of-line 1)
12055 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12056 (call-interactively 'table-recognize-table))
12057 ((org-at-table-p)
12058 (org-table-maybe-eval-formula)
12059 (if arg
12060 (call-interactively 'org-table-recalculate)
12061 (org-table-maybe-recalculate-line))
12062 (call-interactively 'org-table-align))
12063 ((org-at-item-checkbox-p)
12064 (call-interactively 'org-toggle-checkbox))
12065 ((org-at-item-p)
12066 (call-interactively 'org-maybe-renumber-ordered-list))
12067 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12068 ;; Dynamic block
12069 (beginning-of-line 1)
12070 (org-update-dblock))
12071 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12072 (cond
12073 ((equal (match-string 1) "TBLFM")
12074 ;; Recalculate the table before this line
12075 (save-excursion
12076 (beginning-of-line 1)
12077 (skip-chars-backward " \r\n\t")
12078 (if (org-at-table-p)
12079 (org-call-with-arg 'org-table-recalculate t))))
12081 (call-interactively 'org-mode-restart))))
12082 (t (error "C-c C-c can do nothing useful at this location.")))))
12084 (defun org-mode-restart ()
12085 "Restart Org-mode, to scan again for special lines.
12086 Also updates the keyword regular expressions."
12087 (interactive)
12088 (let ((org-inhibit-startup t)) (org-mode))
12089 (message "Org-mode restarted to refresh keyword and special line setup"))
12091 (defun org-kill-note-or-show-branches ()
12092 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12093 (interactive)
12094 (if (not org-finish-function)
12095 (call-interactively 'show-branches)
12096 (let ((org-note-abort t))
12097 (funcall org-finish-function))))
12099 (defun org-return (&optional indent)
12100 "Goto next table row or insert a newline.
12101 Calls `org-table-next-row' or `newline', depending on context.
12102 See the individual commands for more information."
12103 (interactive)
12104 (cond
12105 ((bobp) (if indent (newline-and-indent) (newline)))
12106 ((and (org-at-heading-p)
12107 (looking-at
12108 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12109 (org-show-entry)
12110 (end-of-line 1)
12111 (newline))
12112 ((org-at-table-p)
12113 (org-table-justify-field-maybe)
12114 (call-interactively 'org-table-next-row))
12115 (t (if indent (newline-and-indent) (newline)))))
12117 (defun org-return-indent ()
12118 "Goto next table row or insert a newline and indent.
12119 Calls `org-table-next-row' or `newline-and-indent', depending on
12120 context. See the individual commands for more information."
12121 (interactive)
12122 (org-return t))
12124 (defun org-ctrl-c-star ()
12125 "Compute table, or change heading status of lines.
12126 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12127 depending on context. This will also turn a plain list item or a normal
12128 line into a subheading."
12129 (interactive)
12130 (cond
12131 ((org-at-table-p)
12132 (call-interactively 'org-table-recalculate))
12133 ((org-region-active-p)
12134 ;; Convert all lines in region to list items
12135 (call-interactively 'org-toggle-region-headings))
12136 ((org-on-heading-p)
12137 (org-toggle-region-headings (point-at-bol)
12138 (min (1+ (point-at-eol)) (point-max))))
12139 ((org-at-item-p)
12140 ;; Convert to heading
12141 (let ((level (save-match-data
12142 (save-excursion
12143 (condition-case nil
12144 (progn
12145 (org-back-to-heading t)
12146 (funcall outline-level))
12147 (error 0))))))
12148 (replace-match
12149 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12150 (t (org-toggle-region-headings (point-at-bol)
12151 (min (1+ (point-at-eol)) (point-max))))))
12153 (defun org-ctrl-c-minus ()
12154 "Insert separator line in table or modify bullet status of line.
12155 Also turns a plain line or a region of lines into list items.
12156 Calls `org-table-insert-hline', `org-toggle-region-items', or
12157 `org-cycle-list-bullet', depending on context."
12158 (interactive)
12159 (cond
12160 ((org-at-table-p)
12161 (call-interactively 'org-table-insert-hline))
12162 ((org-on-heading-p)
12163 ;; Convert to item
12164 (save-excursion
12165 (beginning-of-line 1)
12166 (if (looking-at "\\*+ ")
12167 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12168 ((org-region-active-p)
12169 ;; Convert all lines in region to list items
12170 (call-interactively 'org-toggle-region-items))
12171 ((org-in-item-p)
12172 (call-interactively 'org-cycle-list-bullet))
12173 (t (org-toggle-region-items (point-at-bol)
12174 (min (1+ (point-at-eol)) (point-max))))))
12176 (defun org-toggle-region-items (beg end)
12177 "Convert all lines in region to list items.
12178 If the first line is already an item, convert all list items in the region
12179 to normal lines."
12180 (interactive "r")
12181 (let (l2 l)
12182 (save-excursion
12183 (goto-char end)
12184 (setq l2 (org-current-line))
12185 (goto-char beg)
12186 (beginning-of-line 1)
12187 (setq l (1- (org-current-line)))
12188 (if (org-at-item-p)
12189 ;; We already have items, de-itemize
12190 (while (< (setq l (1+ l)) l2)
12191 (when (org-at-item-p)
12192 (goto-char (match-beginning 2))
12193 (delete-region (match-beginning 2) (match-end 2))
12194 (and (looking-at "[ \t]+") (replace-match "")))
12195 (beginning-of-line 2))
12196 (while (< (setq l (1+ l)) l2)
12197 (unless (org-at-item-p)
12198 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12199 (replace-match "\\1- \\2")))
12200 (beginning-of-line 2))))))
12202 (defun org-toggle-region-headings (beg end)
12203 "Convert all lines in region to list items.
12204 If the first line is already an item, convert all list items in the region
12205 to normal lines."
12206 (interactive "r")
12207 (let (l2 l)
12208 (save-excursion
12209 (goto-char end)
12210 (setq l2 (org-current-line))
12211 (goto-char beg)
12212 (beginning-of-line 1)
12213 (setq l (1- (org-current-line)))
12214 (if (org-on-heading-p)
12215 ;; We already have headlines, de-star them
12216 (while (< (setq l (1+ l)) l2)
12217 (when (org-on-heading-p t)
12218 (and (looking-at outline-regexp) (replace-match "")))
12219 (beginning-of-line 2))
12220 (let* ((stars (save-excursion
12221 (re-search-backward org-complex-heading-regexp nil t)
12222 (or (match-string 1) "*")))
12223 (add-stars (if org-odd-levels-only "**" "*"))
12224 (rpl (concat stars add-stars " \\2")))
12225 (while (< (setq l (1+ l)) l2)
12226 (unless (org-on-heading-p)
12227 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12228 (replace-match rpl)))
12229 (beginning-of-line 2)))))))
12231 (defun org-meta-return (&optional arg)
12232 "Insert a new heading or wrap a region in a table.
12233 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12234 See the individual commands for more information."
12235 (interactive "P")
12236 (cond
12237 ((org-at-table-p)
12238 (call-interactively 'org-table-wrap-region))
12239 (t (call-interactively 'org-insert-heading))))
12241 ;;; Menu entries
12243 ;; Define the Org-mode menus
12244 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12245 '("Tbl"
12246 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12247 ["Next Field" org-cycle (org-at-table-p)]
12248 ["Previous Field" org-shifttab (org-at-table-p)]
12249 ["Next Row" org-return (org-at-table-p)]
12250 "--"
12251 ["Blank Field" org-table-blank-field (org-at-table-p)]
12252 ["Edit Field" org-table-edit-field (org-at-table-p)]
12253 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12254 "--"
12255 ("Column"
12256 ["Move Column Left" org-metaleft (org-at-table-p)]
12257 ["Move Column Right" org-metaright (org-at-table-p)]
12258 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12259 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12260 ("Row"
12261 ["Move Row Up" org-metaup (org-at-table-p)]
12262 ["Move Row Down" org-metadown (org-at-table-p)]
12263 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12264 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12265 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12266 "--"
12267 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12268 ("Rectangle"
12269 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12270 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12271 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12272 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12273 "--"
12274 ("Calculate"
12275 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12276 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12277 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12278 "--"
12279 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12280 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12281 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12282 "--"
12283 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12284 "--"
12285 ["Sum Column/Rectangle" org-table-sum
12286 (or (org-at-table-p) (org-region-active-p))]
12287 ["Which Column?" org-table-current-column (org-at-table-p)])
12288 ["Debug Formulas"
12289 org-table-toggle-formula-debugger
12290 :style toggle :selected org-table-formula-debug]
12291 ["Show Col/Row Numbers"
12292 org-table-toggle-coordinate-overlays
12293 :style toggle :selected org-table-overlay-coordinates]
12294 "--"
12295 ["Create" org-table-create (and (not (org-at-table-p))
12296 org-enable-table-editor)]
12297 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12298 ["Import from File" org-table-import (not (org-at-table-p))]
12299 ["Export to File" org-table-export (org-at-table-p)]
12300 "--"
12301 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12303 (easy-menu-define org-org-menu org-mode-map "Org menu"
12304 '("Org"
12305 ("Show/Hide"
12306 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12307 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12308 ["Sparse Tree..." org-sparse-tree t]
12309 ["Reveal Context" org-reveal t]
12310 ["Show All" show-all t]
12311 "--"
12312 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12313 "--"
12314 ["New Heading" org-insert-heading t]
12315 ("Navigate Headings"
12316 ["Up" outline-up-heading t]
12317 ["Next" outline-next-visible-heading t]
12318 ["Previous" outline-previous-visible-heading t]
12319 ["Next Same Level" outline-forward-same-level t]
12320 ["Previous Same Level" outline-backward-same-level t]
12321 "--"
12322 ["Jump" org-goto t])
12323 ("Edit Structure"
12324 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12325 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12326 "--"
12327 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12328 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12329 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12330 "--"
12331 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12332 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12333 ["Demote Heading" org-metaright (not (org-at-table-p))]
12334 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12335 "--"
12336 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12337 "--"
12338 ["Convert to odd levels" org-convert-to-odd-levels t]
12339 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12340 ("Editing"
12341 ["Emphasis..." org-emphasize t])
12342 ("Archive"
12343 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12344 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12345 ; :active t :keys "C-u C-c C-x C-a"]
12346 ["Sparse trees open ARCHIVE trees"
12347 (setq org-sparse-tree-open-archived-trees
12348 (not org-sparse-tree-open-archived-trees))
12349 :style toggle :selected org-sparse-tree-open-archived-trees]
12350 ["Cycling opens ARCHIVE trees"
12351 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12352 :style toggle :selected org-cycle-open-archived-trees]
12353 ["Agenda includes ARCHIVE trees"
12354 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12355 :style toggle :selected (not org-agenda-skip-archived-trees)]
12356 "--"
12357 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12358 ; ["Check and Move Children" (org-archive-subtree '(4))
12359 ; :active t :keys "C-u C-c C-x C-s"]
12361 "--"
12362 ("TODO Lists"
12363 ["TODO/DONE/-" org-todo t]
12364 ("Select keyword"
12365 ["Next keyword" org-shiftright (org-on-heading-p)]
12366 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12367 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12368 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12369 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12370 ["Show TODO Tree" org-show-todo-tree t]
12371 ["Global TODO list" org-todo-list t]
12372 "--"
12373 ["Set Priority" org-priority t]
12374 ["Priority Up" org-shiftup t]
12375 ["Priority Down" org-shiftdown t])
12376 ("TAGS and Properties"
12377 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12378 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12379 "--"
12380 ["Set property" 'org-set-property t]
12381 ["Column view of properties" org-columns t]
12382 ["Insert Column View DBlock" org-insert-columns-dblock t])
12383 ("Dates and Scheduling"
12384 ["Timestamp" org-time-stamp t]
12385 ["Timestamp (inactive)" org-time-stamp-inactive t]
12386 ("Change Date"
12387 ["1 Day Later" org-shiftright t]
12388 ["1 Day Earlier" org-shiftleft t]
12389 ["1 ... Later" org-shiftup t]
12390 ["1 ... Earlier" org-shiftdown t])
12391 ["Compute Time Range" org-evaluate-time-range t]
12392 ["Schedule Item" org-schedule t]
12393 ["Deadline" org-deadline t]
12394 "--"
12395 ["Custom time format" org-toggle-time-stamp-overlays
12396 :style radio :selected org-display-custom-times]
12397 "--"
12398 ["Goto Calendar" org-goto-calendar t]
12399 ["Date from Calendar" org-date-from-calendar t])
12400 ("Logging work"
12401 ["Clock in" org-clock-in t]
12402 ["Clock out" org-clock-out t]
12403 ["Clock cancel" org-clock-cancel t]
12404 ["Goto running clock" org-clock-goto t]
12405 ["Display times" org-clock-display t]
12406 ["Create clock table" org-clock-report t]
12407 "--"
12408 ["Record DONE time"
12409 (progn (setq org-log-done (not org-log-done))
12410 (message "Switching to %s will %s record a timestamp"
12411 (car org-done-keywords)
12412 (if org-log-done "automatically" "not")))
12413 :style toggle :selected org-log-done])
12414 "--"
12415 ["Agenda Command..." org-agenda t]
12416 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12417 ("File List for Agenda")
12418 ("Special views current file"
12419 ["TODO Tree" org-show-todo-tree t]
12420 ["Check Deadlines" org-check-deadlines t]
12421 ["Timeline" org-timeline t]
12422 ["Tags Tree" org-tags-sparse-tree t])
12423 "--"
12424 ("Hyperlinks"
12425 ["Store Link (Global)" org-store-link t]
12426 ["Insert Link" org-insert-link t]
12427 ["Follow Link" org-open-at-point t]
12428 "--"
12429 ["Next link" org-next-link t]
12430 ["Previous link" org-previous-link t]
12431 "--"
12432 ["Descriptive Links"
12433 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12434 :style radio
12435 :selected (member '(org-link) buffer-invisibility-spec)]
12436 ["Literal Links"
12437 (progn
12438 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12439 :style radio
12440 :selected (not (member '(org-link) buffer-invisibility-spec))])
12441 "--"
12442 ["Export/Publish..." org-export t]
12443 ("LaTeX"
12444 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12445 :selected org-cdlatex-mode]
12446 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12447 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12448 ["Modify math symbol" org-cdlatex-math-modify
12449 (org-inside-LaTeX-fragment-p)]
12450 ["Export LaTeX fragments as images"
12451 (if (featurep 'org-exp)
12452 (setq org-export-with-LaTeX-fragments
12453 (not org-export-with-LaTeX-fragments))
12454 (require 'org-exp))
12455 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12456 org-export-with-LaTeX-fragments)])
12457 "--"
12458 ("Documentation"
12459 ["Show Version" org-version t]
12460 ["Info Documentation" org-info t])
12461 ("Customize"
12462 ["Browse Org Group" org-customize t]
12463 "--"
12464 ["Expand This Menu" org-create-customize-menu
12465 (fboundp 'customize-menu-create)])
12466 "--"
12467 ["Refresh setup" org-mode-restart t]
12470 (defun org-info (&optional node)
12471 "Read documentation for Org-mode in the info system.
12472 With optional NODE, go directly to that node."
12473 (interactive)
12474 (info (format "(org)%s" (or node ""))))
12476 (defun org-install-agenda-files-menu ()
12477 (let ((bl (buffer-list)))
12478 (save-excursion
12479 (while bl
12480 (set-buffer (pop bl))
12481 (if (org-mode-p) (setq bl nil)))
12482 (when (org-mode-p)
12483 (easy-menu-change
12484 '("Org") "File List for Agenda"
12485 (append
12486 (list
12487 ["Edit File List" (org-edit-agenda-file-list) t]
12488 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12489 ["Remove Current File from List" org-remove-file t]
12490 ["Cycle through agenda files" org-cycle-agenda-files t]
12491 ["Occur in all agenda files" org-occur-in-agenda-files t]
12492 "--")
12493 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12495 ;;;; Documentation
12497 (defun org-require-autoloaded-modules ()
12498 (interactive)
12499 (mapc 'require
12500 '(org-agenda org-archive org-clock org-colview
12501 org-exp org-export-latex org-publish
12502 org-remember org-table)))
12504 (defun org-customize ()
12505 "Call the customize function with org as argument."
12506 (interactive)
12507 (org-load-modules-maybe)
12508 (org-require-autoloaded-modules)
12509 (customize-browse 'org))
12511 (defun org-create-customize-menu ()
12512 "Create a full customization menu for Org-mode, insert it into the menu."
12513 (interactive)
12514 (org-load-modules-maybe)
12515 (org-require-autoloaded-modules)
12516 (if (fboundp 'customize-menu-create)
12517 (progn
12518 (easy-menu-change
12519 '("Org") "Customize"
12520 `(["Browse Org group" org-customize t]
12521 "--"
12522 ,(customize-menu-create 'org)
12523 ["Set" Custom-set t]
12524 ["Save" Custom-save t]
12525 ["Reset to Current" Custom-reset-current t]
12526 ["Reset to Saved" Custom-reset-saved t]
12527 ["Reset to Standard Settings" Custom-reset-standard t]))
12528 (message "\"Org\"-menu now contains full customization menu"))
12529 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12531 ;;;; Miscellaneous stuff
12533 ;;; Generally useful functions
12535 (defun org-plist-delete (plist property)
12536 "Delete PROPERTY from PLIST.
12537 This is in contrast to merely setting it to 0."
12538 (let (p)
12539 (while plist
12540 (if (not (eq property (car plist)))
12541 (setq p (plist-put p (car plist) (nth 1 plist))))
12542 (setq plist (cddr plist)))
12545 (defun org-force-self-insert (N)
12546 "Needed to enforce self-insert under remapping."
12547 (interactive "p")
12548 (self-insert-command N))
12550 (defun org-string-width (s)
12551 "Compute width of string, ignoring invisible characters.
12552 This ignores character with invisibility property `org-link', and also
12553 characters with property `org-cwidth', because these will become invisible
12554 upon the next fontification round."
12555 (let (b l)
12556 (when (or (eq t buffer-invisibility-spec)
12557 (assq 'org-link buffer-invisibility-spec))
12558 (while (setq b (text-property-any 0 (length s)
12559 'invisible 'org-link s))
12560 (setq s (concat (substring s 0 b)
12561 (substring s (or (next-single-property-change
12562 b 'invisible s) (length s)))))))
12563 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12564 (setq s (concat (substring s 0 b)
12565 (substring s (or (next-single-property-change
12566 b 'org-cwidth s) (length s))))))
12567 (setq l (string-width s) b -1)
12568 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12569 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12573 (defun org-trim (s)
12574 "Remove whitespace at beginning and end of string."
12575 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12576 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12579 (defun org-wrap (string &optional width lines)
12580 "Wrap string to either a number of lines, or a width in characters.
12581 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12582 that costs. If there is a word longer than WIDTH, the text is actually
12583 wrapped to the length of that word.
12584 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12585 many lines, whatever width that takes.
12586 The return value is a list of lines, without newlines at the end."
12587 (let* ((words (org-split-string string "[ \t\n]+"))
12588 (maxword (apply 'max (mapcar 'org-string-width words)))
12589 w ll)
12590 (cond (width
12591 (org-do-wrap words (max maxword width)))
12592 (lines
12593 (setq w maxword)
12594 (setq ll (org-do-wrap words maxword))
12595 (if (<= (length ll) lines)
12597 (setq ll words)
12598 (while (> (length ll) lines)
12599 (setq w (1+ w))
12600 (setq ll (org-do-wrap words w)))
12601 ll))
12602 (t (error "Cannot wrap this")))))
12604 (defun org-do-wrap (words width)
12605 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12606 (let (lines line)
12607 (while words
12608 (setq line (pop words))
12609 (while (and words (< (+ (length line) (length (car words))) width))
12610 (setq line (concat line " " (pop words))))
12611 (setq lines (push line lines)))
12612 (nreverse lines)))
12614 (defun org-split-string (string &optional separators)
12615 "Splits STRING into substrings at SEPARATORS.
12616 No empty strings are returned if there are matches at the beginning
12617 and end of string."
12618 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12619 (start 0)
12620 notfirst
12621 (list nil))
12622 (while (and (string-match rexp string
12623 (if (and notfirst
12624 (= start (match-beginning 0))
12625 (< start (length string)))
12626 (1+ start) start))
12627 (< (match-beginning 0) (length string)))
12628 (setq notfirst t)
12629 (or (eq (match-beginning 0) 0)
12630 (and (eq (match-beginning 0) (match-end 0))
12631 (eq (match-beginning 0) start))
12632 (setq list
12633 (cons (substring string start (match-beginning 0))
12634 list)))
12635 (setq start (match-end 0)))
12636 (or (eq start (length string))
12637 (setq list
12638 (cons (substring string start)
12639 list)))
12640 (nreverse list)))
12642 (defun org-context ()
12643 "Return a list of contexts of the current cursor position.
12644 If several contexts apply, all are returned.
12645 Each context entry is a list with a symbol naming the context, and
12646 two positions indicating start and end of the context. Possible
12647 contexts are:
12649 :headline anywhere in a headline
12650 :headline-stars on the leading stars in a headline
12651 :todo-keyword on a TODO keyword (including DONE) in a headline
12652 :tags on the TAGS in a headline
12653 :priority on the priority cookie in a headline
12654 :item on the first line of a plain list item
12655 :item-bullet on the bullet/number of a plain list item
12656 :checkbox on the checkbox in a plain list item
12657 :table in an org-mode table
12658 :table-special on a special filed in a table
12659 :table-table in a table.el table
12660 :link on a hyperlink
12661 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12662 :target on a <<target>>
12663 :radio-target on a <<<radio-target>>>
12664 :latex-fragment on a LaTeX fragment
12665 :latex-preview on a LaTeX fragment with overlayed preview image
12667 This function expects the position to be visible because it uses font-lock
12668 faces as a help to recognize the following contexts: :table-special, :link,
12669 and :keyword."
12670 (let* ((f (get-text-property (point) 'face))
12671 (faces (if (listp f) f (list f)))
12672 (p (point)) clist o)
12673 ;; First the large context
12674 (cond
12675 ((org-on-heading-p t)
12676 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12677 (when (progn
12678 (beginning-of-line 1)
12679 (looking-at org-todo-line-tags-regexp))
12680 (push (org-point-in-group p 1 :headline-stars) clist)
12681 (push (org-point-in-group p 2 :todo-keyword) clist)
12682 (push (org-point-in-group p 4 :tags) clist))
12683 (goto-char p)
12684 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12685 (if (looking-at "\\[#[A-Z0-9]\\]")
12686 (push (org-point-in-group p 0 :priority) clist)))
12688 ((org-at-item-p)
12689 (push (org-point-in-group p 2 :item-bullet) clist)
12690 (push (list :item (point-at-bol)
12691 (save-excursion (org-end-of-item) (point)))
12692 clist)
12693 (and (org-at-item-checkbox-p)
12694 (push (org-point-in-group p 0 :checkbox) clist)))
12696 ((org-at-table-p)
12697 (push (list :table (org-table-begin) (org-table-end)) clist)
12698 (if (memq 'org-formula faces)
12699 (push (list :table-special
12700 (previous-single-property-change p 'face)
12701 (next-single-property-change p 'face)) clist)))
12702 ((org-at-table-p 'any)
12703 (push (list :table-table) clist)))
12704 (goto-char p)
12706 ;; Now the small context
12707 (cond
12708 ((org-at-timestamp-p)
12709 (push (org-point-in-group p 0 :timestamp) clist))
12710 ((memq 'org-link faces)
12711 (push (list :link
12712 (previous-single-property-change p 'face)
12713 (next-single-property-change p 'face)) clist))
12714 ((memq 'org-special-keyword faces)
12715 (push (list :keyword
12716 (previous-single-property-change p 'face)
12717 (next-single-property-change p 'face)) clist))
12718 ((org-on-target-p)
12719 (push (org-point-in-group p 0 :target) clist)
12720 (goto-char (1- (match-beginning 0)))
12721 (if (looking-at org-radio-target-regexp)
12722 (push (org-point-in-group p 0 :radio-target) clist))
12723 (goto-char p))
12724 ((setq o (car (delq nil
12725 (mapcar
12726 (lambda (x)
12727 (if (memq x org-latex-fragment-image-overlays) x))
12728 (org-overlays-at (point))))))
12729 (push (list :latex-fragment
12730 (org-overlay-start o) (org-overlay-end o)) clist)
12731 (push (list :latex-preview
12732 (org-overlay-start o) (org-overlay-end o)) clist))
12733 ((org-inside-LaTeX-fragment-p)
12734 ;; FIXME: positions wrong.
12735 (push (list :latex-fragment (point) (point)) clist)))
12737 (setq clist (nreverse (delq nil clist)))
12738 clist))
12740 ;; FIXME: Compare with at-regexp-p Do we need both?
12741 (defun org-in-regexp (re &optional nlines visually)
12742 "Check if point is inside a match of regexp.
12743 Normally only the current line is checked, but you can include NLINES extra
12744 lines both before and after point into the search.
12745 If VISUALLY is set, require that the cursor is not after the match but
12746 really on, so that the block visually is on the match."
12747 (catch 'exit
12748 (let ((pos (point))
12749 (eol (point-at-eol (+ 1 (or nlines 0))))
12750 (inc (if visually 1 0)))
12751 (save-excursion
12752 (beginning-of-line (- 1 (or nlines 0)))
12753 (while (re-search-forward re eol t)
12754 (if (and (<= (match-beginning 0) pos)
12755 (>= (+ inc (match-end 0)) pos))
12756 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12758 (defun org-at-regexp-p (regexp)
12759 "Is point inside a match of REGEXP in the current line?"
12760 (catch 'exit
12761 (save-excursion
12762 (let ((pos (point)) (end (point-at-eol)))
12763 (beginning-of-line 1)
12764 (while (re-search-forward regexp end t)
12765 (if (and (<= (match-beginning 0) pos)
12766 (>= (match-end 0) pos))
12767 (throw 'exit t)))
12768 nil))))
12770 (defun org-occur-in-agenda-files (regexp &optional nlines)
12771 "Call `multi-occur' with buffers for all agenda files."
12772 (interactive "sOrg-files matching: \np")
12773 (let* ((files (org-agenda-files))
12774 (tnames (mapcar 'file-truename files))
12775 (extra org-agenda-text-search-extra-files)
12777 (while (setq f (pop extra))
12778 (unless (member (file-truename f) tnames)
12779 (add-to-list 'files f 'append)
12780 (add-to-list 'tnames (file-truename f) 'append)))
12781 (multi-occur
12782 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12783 regexp)))
12785 (if (boundp 'occur-mode-find-occurrence-hook)
12786 ;; Emacs 23
12787 (add-hook 'occur-mode-find-occurrence-hook
12788 (lambda ()
12789 (when (org-mode-p)
12790 (org-reveal))))
12791 ;; Emacs 22
12792 (defadvice occur-mode-goto-occurrence
12793 (after org-occur-reveal activate)
12794 (and (org-mode-p) (org-reveal)))
12795 (defadvice occur-mode-goto-occurrence-other-window
12796 (after org-occur-reveal activate)
12797 (and (org-mode-p) (org-reveal)))
12798 (defadvice occur-mode-display-occurrence
12799 (after org-occur-reveal activate)
12800 (when (org-mode-p)
12801 (let ((pos (occur-mode-find-occurrence)))
12802 (with-current-buffer (marker-buffer pos)
12803 (save-excursion
12804 (goto-char pos)
12805 (org-reveal)))))))
12807 (defun org-uniquify (list)
12808 "Remove duplicate elements from LIST."
12809 (let (res)
12810 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12811 res))
12813 (defun org-delete-all (elts list)
12814 "Remove all elements in ELTS from LIST."
12815 (while elts
12816 (setq list (delete (pop elts) list)))
12817 list)
12819 (defun org-back-over-empty-lines ()
12820 "Move backwards over witespace, to the beginning of the first empty line.
12821 Returns the number of empty lines passed."
12822 (let ((pos (point)))
12823 (skip-chars-backward " \t\n\r")
12824 (beginning-of-line 2)
12825 (goto-char (min (point) pos))
12826 (count-lines (point) pos)))
12828 (defun org-skip-whitespace ()
12829 (skip-chars-forward " \t\n\r"))
12831 (defun org-point-in-group (point group &optional context)
12832 "Check if POINT is in match-group GROUP.
12833 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12834 match. If the match group does ot exist or point is not inside it,
12835 return nil."
12836 (and (match-beginning group)
12837 (>= point (match-beginning group))
12838 (<= point (match-end group))
12839 (if context
12840 (list context (match-beginning group) (match-end group))
12841 t)))
12843 (defun org-switch-to-buffer-other-window (&rest args)
12844 "Switch to buffer in a second window on the current frame.
12845 In particular, do not allow pop-up frames."
12846 (let (pop-up-frames special-display-buffer-names special-display-regexps
12847 special-display-function)
12848 (apply 'switch-to-buffer-other-window args)))
12850 (defun org-combine-plists (&rest plists)
12851 "Create a single property list from all plists in PLISTS.
12852 The process starts by copying the first list, and then setting properties
12853 from the other lists. Settings in the last list are the most significant
12854 ones and overrule settings in the other lists."
12855 (let ((rtn (copy-sequence (pop plists)))
12856 p v ls)
12857 (while plists
12858 (setq ls (pop plists))
12859 (while ls
12860 (setq p (pop ls) v (pop ls))
12861 (setq rtn (plist-put rtn p v))))
12862 rtn))
12864 (defun org-move-line-down (arg)
12865 "Move the current line down. With prefix argument, move it past ARG lines."
12866 (interactive "p")
12867 (let ((col (current-column))
12868 beg end pos)
12869 (beginning-of-line 1) (setq beg (point))
12870 (beginning-of-line 2) (setq end (point))
12871 (beginning-of-line (+ 1 arg))
12872 (setq pos (move-marker (make-marker) (point)))
12873 (insert (delete-and-extract-region beg end))
12874 (goto-char pos)
12875 (move-to-column col)))
12877 (defun org-move-line-up (arg)
12878 "Move the current line up. With prefix argument, move it past ARG lines."
12879 (interactive "p")
12880 (let ((col (current-column))
12881 beg end pos)
12882 (beginning-of-line 1) (setq beg (point))
12883 (beginning-of-line 2) (setq end (point))
12884 (beginning-of-line (- arg))
12885 (setq pos (move-marker (make-marker) (point)))
12886 (insert (delete-and-extract-region beg end))
12887 (goto-char pos)
12888 (move-to-column col)))
12890 (defun org-replace-escapes (string table)
12891 "Replace %-escapes in STRING with values in TABLE.
12892 TABLE is an association list with keys like \"%a\" and string values.
12893 The sequences in STRING may contain normal field width and padding information,
12894 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
12895 so values can contain further %-escapes if they are define later in TABLE."
12896 (let ((case-fold-search nil)
12897 e re rpl)
12898 (while (setq e (pop table))
12899 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
12900 (while (string-match re string)
12901 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
12902 (cdr e)))
12903 (setq string (replace-match rpl t t string))))
12904 string))
12907 (defun org-sublist (list start end)
12908 "Return a section of LIST, from START to END.
12909 Counting starts at 1."
12910 (let (rtn (c start))
12911 (setq list (nthcdr (1- start) list))
12912 (while (and list (<= c end))
12913 (push (pop list) rtn)
12914 (setq c (1+ c)))
12915 (nreverse rtn)))
12917 (defun org-find-base-buffer-visiting (file)
12918 "Like `find-buffer-visiting' but alway return the base buffer and
12919 not an indirect buffer."
12920 (let ((buf (find-buffer-visiting file)))
12921 (if buf
12922 (or (buffer-base-buffer buf) buf)
12923 nil)))
12925 (defun org-image-file-name-regexp ()
12926 "Return regexp matching the file names of images."
12927 (if (fboundp 'image-file-name-regexp)
12928 (image-file-name-regexp)
12929 (let ((image-file-name-extensions
12930 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12931 "xbm" "xpm" "pbm" "pgm" "ppm")))
12932 (concat "\\."
12933 (regexp-opt (nconc (mapcar 'upcase
12934 image-file-name-extensions)
12935 image-file-name-extensions)
12937 "\\'"))))
12939 (defun org-file-image-p (file)
12940 "Return non-nil if FILE is an image."
12941 (save-match-data
12942 (string-match (org-image-file-name-regexp) file)))
12944 ;;; Paragraph filling stuff.
12945 ;; We want this to be just right, so use the full arsenal.
12947 (defun org-indent-line-function ()
12948 "Indent line like previous, but further if previous was headline or item."
12949 (interactive)
12950 (let* ((pos (point))
12951 (itemp (org-at-item-p))
12952 column bpos bcol tpos tcol bullet btype bullet-type)
12953 ;; Find the previous relevant line
12954 (beginning-of-line 1)
12955 (cond
12956 ((looking-at "#") (setq column 0))
12957 ((looking-at "\\*+ ") (setq column 0))
12959 (beginning-of-line 0)
12960 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
12961 (beginning-of-line 0))
12962 (cond
12963 ((looking-at "\\*+[ \t]+")
12964 (goto-char (match-end 0))
12965 (setq column (current-column)))
12966 ((org-in-item-p)
12967 (org-beginning-of-item)
12968 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12969 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
12970 (setq bpos (match-beginning 1) tpos (match-end 0)
12971 bcol (progn (goto-char bpos) (current-column))
12972 tcol (progn (goto-char tpos) (current-column))
12973 bullet (match-string 1)
12974 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
12975 (if (not itemp)
12976 (setq column tcol)
12977 (goto-char pos)
12978 (beginning-of-line 1)
12979 (if (looking-at "\\S-")
12980 (progn
12981 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12982 (setq bullet (match-string 1)
12983 btype (if (string-match "[0-9]" bullet) "n" bullet))
12984 (setq column (if (equal btype bullet-type) bcol tcol)))
12985 (setq column (org-get-indentation)))))
12986 (t (setq column (org-get-indentation))))))
12987 (goto-char pos)
12988 (if (<= (current-column) (current-indentation))
12989 (indent-line-to column)
12990 (save-excursion (indent-line-to column)))
12991 (setq column (current-column))
12992 (beginning-of-line 1)
12993 (if (looking-at
12994 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
12995 (replace-match (concat "\\1" (format org-property-format
12996 (match-string 2) (match-string 3)))
12997 t nil))
12998 (move-to-column column)))
13000 (defun org-set-autofill-regexps ()
13001 (interactive)
13002 ;; In the paragraph separator we include headlines, because filling
13003 ;; text in a line directly attached to a headline would otherwise
13004 ;; fill the headline as well.
13005 (org-set-local 'comment-start-skip "^#+[ \t]*")
13006 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13007 ;; The paragraph starter includes hand-formatted lists.
13008 (org-set-local 'paragraph-start
13009 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13010 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13011 ;; But only if the user has not turned off tables or fixed-width regions
13012 (org-set-local
13013 'auto-fill-inhibit-regexp
13014 (concat "\\*+ \\|#\\+"
13015 "\\|[ \t]*" org-keyword-time-regexp
13016 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13017 (concat
13018 "\\|[ \t]*["
13019 (if org-enable-table-editor "|" "")
13020 (if org-enable-fixed-width-editor ":" "")
13021 "]"))))
13022 ;; We use our own fill-paragraph function, to make sure that tables
13023 ;; and fixed-width regions are not wrapped. That function will pass
13024 ;; through to `fill-paragraph' when appropriate.
13025 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13026 ; Adaptive filling: To get full control, first make sure that
13027 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13028 (org-set-local 'adaptive-fill-regexp "\000")
13029 (org-set-local 'adaptive-fill-function
13030 'org-adaptive-fill-function)
13031 (org-set-local
13032 'align-mode-rules-list
13033 '((org-in-buffer-settings
13034 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13035 (modes . '(org-mode))))))
13037 (defun org-fill-paragraph (&optional justify)
13038 "Re-align a table, pass through to fill-paragraph if no table."
13039 (let ((table-p (org-at-table-p))
13040 (table.el-p (org-at-table.el-p)))
13041 (cond ((and (equal (char-after (point-at-bol)) ?*)
13042 (save-excursion (goto-char (point-at-bol))
13043 (looking-at outline-regexp)))
13044 t) ; skip headlines
13045 (table.el-p t) ; skip table.el tables
13046 (table-p (org-table-align) t) ; align org-mode tables
13047 (t nil)))) ; call paragraph-fill
13049 ;; For reference, this is the default value of adaptive-fill-regexp
13050 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13052 (defun org-adaptive-fill-function ()
13053 "Return a fill prefix for org-mode files.
13054 In particular, this makes sure hanging paragraphs for hand-formatted lists
13055 work correctly."
13056 (cond ((looking-at "#[ \t]+")
13057 (match-string 0))
13058 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13059 (save-excursion
13060 (goto-char (match-end 0))
13061 (make-string (current-column) ?\ )))
13062 (t nil)))
13064 ;;; Other stuff.
13066 (defun org-toggle-fixed-width-section (arg)
13067 "Toggle the fixed-width export.
13068 If there is no active region, the QUOTE keyword at the current headline is
13069 inserted or removed. When present, it causes the text between this headline
13070 and the next to be exported as fixed-width text, and unmodified.
13071 If there is an active region, this command adds or removes a colon as the
13072 first character of this line. If the first character of a line is a colon,
13073 this line is also exported in fixed-width font."
13074 (interactive "P")
13075 (let* ((cc 0)
13076 (regionp (org-region-active-p))
13077 (beg (if regionp (region-beginning) (point)))
13078 (end (if regionp (region-end)))
13079 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13080 (case-fold-search nil)
13081 (re "[ \t]*\\(:\\)")
13082 off)
13083 (if regionp
13084 (save-excursion
13085 (goto-char beg)
13086 (setq cc (current-column))
13087 (beginning-of-line 1)
13088 (setq off (looking-at re))
13089 (while (> nlines 0)
13090 (setq nlines (1- nlines))
13091 (beginning-of-line 1)
13092 (cond
13093 (arg
13094 (move-to-column cc t)
13095 (insert ":\n")
13096 (forward-line -1))
13097 ((and off (looking-at re))
13098 (replace-match "" t t nil 1))
13099 ((not off) (move-to-column cc t) (insert ":")))
13100 (forward-line 1)))
13101 (save-excursion
13102 (org-back-to-heading)
13103 (if (looking-at (concat outline-regexp
13104 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13105 (replace-match "" t t nil 1)
13106 (if (looking-at outline-regexp)
13107 (progn
13108 (goto-char (match-end 0))
13109 (insert org-quote-string " "))))))))
13111 ;;;; Functions extending outline functionality
13113 (defun org-beginning-of-line (&optional arg)
13114 "Go to the beginning of the current line. If that is invisible, continue
13115 to a visible line beginning. This makes the function of C-a more intuitive.
13116 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13117 first attempt, and only move to after the tags when the cursor is already
13118 beyond the end of the headline."
13119 (interactive "P")
13120 (let ((pos (point)))
13121 (beginning-of-line 1)
13122 (if (bobp)
13124 (backward-char 1)
13125 (if (org-invisible-p)
13126 (while (and (not (bobp)) (org-invisible-p))
13127 (backward-char 1)
13128 (beginning-of-line 1))
13129 (forward-char 1)))
13130 (when org-special-ctrl-a/e
13131 (cond
13132 ((and (looking-at org-todo-line-regexp)
13133 (= (char-after (match-end 1)) ?\ ))
13134 (goto-char
13135 (if (eq org-special-ctrl-a/e t)
13136 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13137 ((= pos (point)) (match-beginning 3))
13138 (t (point)))
13139 (cond ((> pos (point)) (point))
13140 ((not (eq last-command this-command)) (point))
13141 (t (match-beginning 3))))))
13142 ((org-at-item-p)
13143 (goto-char
13144 (if (eq org-special-ctrl-a/e t)
13145 (cond ((> pos (match-end 4)) (match-end 4))
13146 ((= pos (point)) (match-end 4))
13147 (t (point)))
13148 (cond ((> pos (point)) (point))
13149 ((not (eq last-command this-command)) (point))
13150 (t (match-end 4))))))))))
13152 (defun org-end-of-line (&optional arg)
13153 "Go to the end of the line.
13154 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13155 first attempt, and only move to after the tags when the cursor is already
13156 beyond the end of the headline."
13157 (interactive "P")
13158 (if (or (not org-special-ctrl-a/e)
13159 (not (org-on-heading-p)))
13160 (end-of-line arg)
13161 (let ((pos (point)))
13162 (beginning-of-line 1)
13163 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13164 (if (eq org-special-ctrl-a/e t)
13165 (if (or (< pos (match-beginning 1))
13166 (= pos (match-end 0)))
13167 (goto-char (match-beginning 1))
13168 (goto-char (match-end 0)))
13169 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13170 (goto-char (match-end 0))
13171 (goto-char (match-beginning 1))))
13172 (end-of-line arg)))))
13174 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13175 (define-key org-mode-map "\C-e" 'org-end-of-line)
13177 (defun org-kill-line (&optional arg)
13178 "Kill line, to tags or end of line."
13179 (interactive "P")
13180 (cond
13181 ((or (not org-special-ctrl-k)
13182 (bolp)
13183 (not (org-on-heading-p)))
13184 (call-interactively 'kill-line))
13185 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13186 (kill-region (point) (match-beginning 1))
13187 (org-set-tags nil t))
13188 (t (kill-region (point) (point-at-eol)))))
13190 (define-key org-mode-map "\C-k" 'org-kill-line)
13192 (defun org-invisible-p ()
13193 "Check if point is at a character currently not visible."
13194 ;; Early versions of noutline don't have `outline-invisible-p'.
13195 (if (fboundp 'outline-invisible-p)
13196 (outline-invisible-p)
13197 (get-char-property (point) 'invisible)))
13199 (defun org-invisible-p2 ()
13200 "Check if point is at a character currently not visible."
13201 (save-excursion
13202 (if (and (eolp) (not (bobp))) (backward-char 1))
13203 ;; Early versions of noutline don't have `outline-invisible-p'.
13204 (if (fboundp 'outline-invisible-p)
13205 (outline-invisible-p)
13206 (get-char-property (point) 'invisible))))
13208 (defalias 'org-back-to-heading 'outline-back-to-heading)
13209 (defalias 'org-on-heading-p 'outline-on-heading-p)
13210 (defalias 'org-at-heading-p 'outline-on-heading-p)
13211 (defun org-at-heading-or-item-p ()
13212 (or (org-on-heading-p) (org-at-item-p)))
13214 (defun org-on-target-p ()
13215 (or (org-in-regexp org-radio-target-regexp)
13216 (org-in-regexp org-target-regexp)))
13218 (defun org-up-heading-all (arg)
13219 "Move to the heading line of which the present line is a subheading.
13220 This function considers both visible and invisible heading lines.
13221 With argument, move up ARG levels."
13222 (if (fboundp 'outline-up-heading-all)
13223 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13224 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13226 (defun org-up-heading-safe ()
13227 "Move to the heading line of which the present line is a subheading.
13228 This version will not throw an error. It will return the level of the
13229 headline found, or nil if no higher level is found."
13230 (let ((pos (point)) start-level level
13231 (re (concat "^" outline-regexp)))
13232 (catch 'exit
13233 (outline-back-to-heading t)
13234 (setq start-level (funcall outline-level))
13235 (if (equal start-level 1) (throw 'exit nil))
13236 (while (re-search-backward re nil t)
13237 (setq level (funcall outline-level))
13238 (if (< level start-level) (throw 'exit level)))
13239 nil)))
13241 (defun org-first-sibling-p ()
13242 "Is this heading the first child of its parents?"
13243 (interactive)
13244 (let ((re (concat "^" outline-regexp))
13245 level l)
13246 (unless (org-at-heading-p t)
13247 (error "Not at a heading"))
13248 (setq level (funcall outline-level))
13249 (save-excursion
13250 (if (not (re-search-backward re nil t))
13252 (setq l (funcall outline-level))
13253 (< l level)))))
13255 (defun org-goto-sibling (&optional previous)
13256 "Goto the next sibling, even if it is invisible.
13257 When PREVIOUS is set, go to the previous sibling instead. Returns t
13258 when a sibling was found. When none is found, return nil and don't
13259 move point."
13260 (let ((fun (if previous 're-search-backward 're-search-forward))
13261 (pos (point))
13262 (re (concat "^" outline-regexp))
13263 level l)
13264 (when (condition-case nil (org-back-to-heading t) (error nil))
13265 (setq level (funcall outline-level))
13266 (catch 'exit
13267 (or previous (forward-char 1))
13268 (while (funcall fun re nil t)
13269 (setq l (funcall outline-level))
13270 (when (< l level) (goto-char pos) (throw 'exit nil))
13271 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13272 (goto-char pos)
13273 nil))))
13275 (defun org-show-siblings ()
13276 "Show all siblings of the current headline."
13277 (save-excursion
13278 (while (org-goto-sibling) (org-flag-heading nil)))
13279 (save-excursion
13280 (while (org-goto-sibling 'previous)
13281 (org-flag-heading nil))))
13283 (defun org-show-hidden-entry ()
13284 "Show an entry where even the heading is hidden."
13285 (save-excursion
13286 (org-show-entry)))
13288 (defun org-flag-heading (flag &optional entry)
13289 "Flag the current heading. FLAG non-nil means make invisible.
13290 When ENTRY is non-nil, show the entire entry."
13291 (save-excursion
13292 (org-back-to-heading t)
13293 ;; Check if we should show the entire entry
13294 (if entry
13295 (progn
13296 (org-show-entry)
13297 (save-excursion
13298 (and (outline-next-heading)
13299 (org-flag-heading nil))))
13300 (outline-flag-region (max (point-min) (1- (point)))
13301 (save-excursion (outline-end-of-heading) (point))
13302 flag))))
13304 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13305 ;; This is an exact copy of the original function, but it uses
13306 ;; `org-back-to-heading', to make it work also in invisible
13307 ;; trees. And is uses an invisible-OK argument.
13308 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13309 (org-back-to-heading invisible-OK)
13310 (let ((first t)
13311 (level (funcall outline-level)))
13312 (while (and (not (eobp))
13313 (or first (> (funcall outline-level) level)))
13314 (setq first nil)
13315 (outline-next-heading))
13316 (unless to-heading
13317 (if (memq (preceding-char) '(?\n ?\^M))
13318 (progn
13319 ;; Go to end of line before heading
13320 (forward-char -1)
13321 (if (memq (preceding-char) '(?\n ?\^M))
13322 ;; leave blank line before heading
13323 (forward-char -1))))))
13324 (point))
13326 (defun org-show-subtree ()
13327 "Show everything after this heading at deeper levels."
13328 (outline-flag-region
13329 (point)
13330 (save-excursion
13331 (outline-end-of-subtree) (outline-next-heading) (point))
13332 nil))
13334 (defun org-show-entry ()
13335 "Show the body directly following this heading.
13336 Show the heading too, if it is currently invisible."
13337 (interactive)
13338 (save-excursion
13339 (condition-case nil
13340 (progn
13341 (org-back-to-heading t)
13342 (outline-flag-region
13343 (max (point-min) (1- (point)))
13344 (save-excursion
13345 (re-search-forward
13346 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13347 (or (match-beginning 1) (point-max)))
13348 nil))
13349 (error nil))))
13351 (defun org-make-options-regexp (kwds)
13352 "Make a regular expression for keyword lines."
13353 (concat
13355 "#?[ \t]*\\+\\("
13356 (mapconcat 'regexp-quote kwds "\\|")
13357 "\\):[ \t]*"
13358 "\\(.+\\)"))
13360 ;; Make isearch reveal the necessary context
13361 (defun org-isearch-end ()
13362 "Reveal context after isearch exits."
13363 (when isearch-success ; only if search was successful
13364 (if (featurep 'xemacs)
13365 ;; Under XEmacs, the hook is run in the correct place,
13366 ;; we directly show the context.
13367 (org-show-context 'isearch)
13368 ;; In Emacs the hook runs *before* restoring the overlays.
13369 ;; So we have to use a one-time post-command-hook to do this.
13370 ;; (Emacs 22 has a special variable, see function `org-mode')
13371 (unless (and (boundp 'isearch-mode-end-hook-quit)
13372 isearch-mode-end-hook-quit)
13373 ;; Only when the isearch was not quitted.
13374 (org-add-hook 'post-command-hook 'org-isearch-post-command
13375 'append 'local)))))
13377 (defun org-isearch-post-command ()
13378 "Remove self from hook, and show context."
13379 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13380 (org-show-context 'isearch))
13383 ;;;; Integration with and fixes for other packages
13385 ;;; Imenu support
13387 (defvar org-imenu-markers nil
13388 "All markers currently used by Imenu.")
13389 (make-variable-buffer-local 'org-imenu-markers)
13391 (defun org-imenu-new-marker (&optional pos)
13392 "Return a new marker for use by Imenu, and remember the marker."
13393 (let ((m (make-marker)))
13394 (move-marker m (or pos (point)))
13395 (push m org-imenu-markers)
13398 (defun org-imenu-get-tree ()
13399 "Produce the index for Imenu."
13400 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13401 (setq org-imenu-markers nil)
13402 (let* ((n org-imenu-depth)
13403 (re (concat "^" outline-regexp))
13404 (subs (make-vector (1+ n) nil))
13405 (last-level 0)
13406 m tree level head)
13407 (save-excursion
13408 (save-restriction
13409 (widen)
13410 (goto-char (point-max))
13411 (while (re-search-backward re nil t)
13412 (setq level (org-reduced-level (funcall outline-level)))
13413 (when (<= level n)
13414 (looking-at org-complex-heading-regexp)
13415 (setq head (org-match-string-no-properties 4)
13416 m (org-imenu-new-marker))
13417 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13418 (if (>= level last-level)
13419 (push (cons head m) (aref subs level))
13420 (push (cons head (aref subs (1+ level))) (aref subs level))
13421 (loop for i from (1+ level) to n do (aset subs i nil)))
13422 (setq last-level level)))))
13423 (aref subs 1)))
13425 (eval-after-load "imenu"
13426 '(progn
13427 (add-hook 'imenu-after-jump-hook
13428 (lambda () (org-show-context 'org-goto)))))
13430 ;; Speedbar support
13432 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13433 "Overlay marking the agenda restriction line in speedbar.")
13434 (org-overlay-put org-speedbar-restriction-lock-overlay
13435 'face 'org-agenda-restriction-lock)
13436 (org-overlay-put org-speedbar-restriction-lock-overlay
13437 'help-echo "Agendas are currently limited to this item.")
13438 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13440 (defun org-speedbar-set-agenda-restriction ()
13441 "Restrict future agenda commands to the location at point in speedbar.
13442 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13443 (interactive)
13444 (require 'org-agenda)
13445 (let (p m tp np dir txt w)
13446 (cond
13447 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13448 'org-imenu t))
13449 (setq m (get-text-property p 'org-imenu-marker))
13450 (save-excursion
13451 (save-restriction
13452 (set-buffer (marker-buffer m))
13453 (goto-char m)
13454 (org-agenda-set-restriction-lock 'subtree))))
13455 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13456 'speedbar-function 'speedbar-find-file))
13457 (setq tp (previous-single-property-change
13458 (1+ p) 'speedbar-function)
13459 np (next-single-property-change
13460 tp 'speedbar-function)
13461 dir (speedbar-line-directory)
13462 txt (buffer-substring-no-properties (or tp (point-min))
13463 (or np (point-max))))
13464 (save-excursion
13465 (save-restriction
13466 (set-buffer (find-file-noselect
13467 (let ((default-directory dir))
13468 (expand-file-name txt))))
13469 (unless (org-mode-p)
13470 (error "Cannot restrict to non-Org-mode file"))
13471 (org-agenda-set-restriction-lock 'file))))
13472 (t (error "Don't know how to restrict Org-mode's agenda")))
13473 (org-move-overlay org-speedbar-restriction-lock-overlay
13474 (point-at-bol) (point-at-eol))
13475 (setq current-prefix-arg nil)
13476 (org-agenda-maybe-redo)))
13478 (eval-after-load "speedbar"
13479 '(progn
13480 (speedbar-add-supported-extension ".org")
13481 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13482 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13483 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13484 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13485 (add-hook 'speedbar-visiting-tag-hook
13486 (lambda () (org-show-context 'org-goto)))))
13489 ;;; Fixes and Hacks for problems with other packages
13491 ;; Make flyspell not check words in links, to not mess up our keymap
13492 (defun org-mode-flyspell-verify ()
13493 "Don't let flyspell put overlays at active buttons."
13494 (not (get-text-property (point) 'keymap)))
13496 ;; Make `bookmark-jump' show the jump location if it was hidden.
13497 (eval-after-load "bookmark"
13498 '(if (boundp 'bookmark-after-jump-hook)
13499 ;; We can use the hook
13500 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13501 ;; Hook not available, use advice
13502 (defadvice bookmark-jump (after org-make-visible activate)
13503 "Make the position visible."
13504 (org-bookmark-jump-unhide))))
13506 (defun org-bookmark-jump-unhide ()
13507 "Unhide the current position, to show the bookmark location."
13508 (and (org-mode-p)
13509 (or (org-invisible-p)
13510 (save-excursion (goto-char (max (point-min) (1- (point))))
13511 (org-invisible-p)))
13512 (org-show-context 'bookmark-jump)))
13514 ;; Make session.el ignore our circular variable
13515 (eval-after-load "session"
13516 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13518 ;;;; Experimental code
13520 (defun org-closed-in-range ()
13521 "Sparse tree of items closed in a certain time range.
13522 Still experimental, may disappear in the future."
13523 (interactive)
13524 ;; Get the time interval from the user.
13525 (let* ((time1 (time-to-seconds
13526 (org-read-date nil 'to-time nil "Starting date: ")))
13527 (time2 (time-to-seconds
13528 (org-read-date nil 'to-time nil "End date:")))
13529 ;; callback function
13530 (callback (lambda ()
13531 (let ((time
13532 (time-to-seconds
13533 (apply 'encode-time
13534 (org-parse-time-string
13535 (match-string 1))))))
13536 ;; check if time in interval
13537 (and (>= time time1) (<= time time2))))))
13538 ;; make tree, check each match with the callback
13539 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13542 ;;;; Finish up
13544 (provide 'org)
13546 (run-hooks 'org-load-hook)
13548 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13549 ;;; org.el ends here
13551 (defun org-open-link-from-string (s &optional arg)
13552 "Open a link in the string S, as if it was in Org-mode."
13553 (interactive)
13554 (with-temp-buffer
13555 (let ((org-inhibit-startup t))
13556 (org-mode)
13557 (insert s)
13558 (goto-char (point-min))
13559 (org-open-at-point arg))))