Allow temporary agenda display with inactive timestamps included.
[org-mode.git] / lisp / org.el
blobf4fdc21640dc8f3bb67b44c76c4f5aa9de44ffea
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.00pre-5
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.00pre-5"
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-re-with-space nil
3105 "Matches a link with spaces, optional angular brackets around it.")
3106 (defvar org-link-re-with-space2 nil
3107 "Matches a link with spaces, optional angular brackets around it.")
3108 (defvar org-angle-link-re nil
3109 "Matches link with angular brackets, spaces are allowed.")
3110 (defvar org-plain-link-re nil
3111 "Matches plain link, without spaces.")
3112 (defvar org-bracket-link-regexp nil
3113 "Matches a link in double brackets.")
3114 (defvar org-bracket-link-analytic-regexp nil
3115 "Regular expression used to analyze links.
3116 Here is what the match groups contain after a match:
3117 1: http:
3118 2: http
3119 3: path
3120 4: [desc]
3121 5: desc")
3122 (defvar org-any-link-re nil
3123 "Regular expression matching any link.")
3125 (defun org-make-link-regexps ()
3126 "Update the link regular expressions.
3127 This should be called after the variable `org-link-types' has changed."
3128 (setq org-link-re-with-space
3129 (concat
3130 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3131 "\\([^" org-non-link-chars " ]"
3132 "[^" org-non-link-chars "]*"
3133 "[^" org-non-link-chars " ]\\)>?")
3134 org-link-re-with-space2
3135 (concat
3136 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3137 "\\([^" org-non-link-chars " ]"
3138 "[^]\t\n\r]*"
3139 "[^" org-non-link-chars " ]\\)>?")
3140 org-angle-link-re
3141 (concat
3142 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3143 "\\([^" org-non-link-chars " ]"
3144 "[^" org-non-link-chars "]*"
3145 "\\)>")
3146 org-plain-link-re
3147 (concat
3148 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3149 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3150 org-bracket-link-regexp
3151 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3152 org-bracket-link-analytic-regexp
3153 (concat
3154 "\\[\\["
3155 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3156 "\\([^]]+\\)"
3157 "\\]"
3158 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3159 "\\]")
3160 org-any-link-re
3161 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3162 org-angle-link-re "\\)\\|\\("
3163 org-plain-link-re "\\)")))
3165 (org-make-link-regexps)
3167 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3168 "Regular expression for fast time stamp matching.")
3169 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3170 "Regular expression for fast time stamp matching.")
3171 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3172 "Regular expression matching time strings for analysis.
3173 This one does not require the space after the date, so it can be used
3174 on a string that terminates immediately after the date.")
3175 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3176 "Regular expression matching time strings for analysis.")
3177 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3178 "Regular expression matching time stamps, with groups.")
3179 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3180 "Regular expression matching time stamps (also [..]), with groups.")
3181 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3182 "Regular expression matching a time stamp range.")
3183 (defconst org-tr-regexp-both
3184 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3185 "Regular expression matching a time stamp range.")
3186 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3187 org-ts-regexp "\\)?")
3188 "Regular expression matching a time stamp or time stamp range.")
3189 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3190 org-ts-regexp-both "\\)?")
3191 "Regular expression matching a time stamp or time stamp range.
3192 The time stamps may be either active or inactive.")
3194 (defvar org-emph-face nil)
3196 (defun org-do-emphasis-faces (limit)
3197 "Run through the buffer and add overlays to links."
3198 (let (rtn)
3199 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3200 (if (not (= (char-after (match-beginning 3))
3201 (char-after (match-beginning 4))))
3202 (progn
3203 (setq rtn t)
3204 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3205 'face
3206 (nth 1 (assoc (match-string 3)
3207 org-emphasis-alist)))
3208 (add-text-properties (match-beginning 2) (match-end 2)
3209 '(font-lock-multiline t))
3210 (when org-hide-emphasis-markers
3211 (add-text-properties (match-end 4) (match-beginning 5)
3212 '(invisible org-link))
3213 (add-text-properties (match-beginning 3) (match-end 3)
3214 '(invisible org-link)))))
3215 (backward-char 1))
3216 rtn))
3218 (defun org-emphasize (&optional char)
3219 "Insert or change an emphasis, i.e. a font like bold or italic.
3220 If there is an active region, change that region to a new emphasis.
3221 If there is no region, just insert the marker characters and position
3222 the cursor between them.
3223 CHAR should be either the marker character, or the first character of the
3224 HTML tag associated with that emphasis. If CHAR is a space, the means
3225 to remove the emphasis of the selected region.
3226 If char is not given (for example in an interactive call) it
3227 will be prompted for."
3228 (interactive)
3229 (let ((eal org-emphasis-alist) e det
3230 (erc org-emphasis-regexp-components)
3231 (prompt "")
3232 (string "") beg end move tag c s)
3233 (if (org-region-active-p)
3234 (setq beg (region-beginning) end (region-end)
3235 string (buffer-substring beg end))
3236 (setq move t))
3238 (while (setq e (pop eal))
3239 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3240 c (aref tag 0))
3241 (push (cons c (string-to-char (car e))) det)
3242 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3243 (substring tag 1)))))
3244 (unless char
3245 (message "%s" (concat "Emphasis marker or tag:" prompt))
3246 (setq char (read-char-exclusive)))
3247 (setq char (or (cdr (assoc char det)) char))
3248 (if (equal char ?\ )
3249 (setq s "" move nil)
3250 (unless (assoc (char-to-string char) org-emphasis-alist)
3251 (error "No such emphasis marker: \"%c\"" char))
3252 (setq s (char-to-string char)))
3253 (while (and (> (length string) 1)
3254 (equal (substring string 0 1) (substring string -1))
3255 (assoc (substring string 0 1) org-emphasis-alist))
3256 (setq string (substring string 1 -1)))
3257 (setq string (concat s string s))
3258 (if beg (delete-region beg end))
3259 (unless (or (bolp)
3260 (string-match (concat "[" (nth 0 erc) "\n]")
3261 (char-to-string (char-before (point)))))
3262 (insert " "))
3263 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3264 (char-to-string (char-after (point))))
3265 (insert " ") (backward-char 1))
3266 (insert string)
3267 (and move (backward-char 1))))
3269 (defconst org-nonsticky-props
3270 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3273 (defun org-activate-plain-links (limit)
3274 "Run through the buffer and add overlays to links."
3275 (catch 'exit
3276 (let (f)
3277 (while (re-search-forward org-plain-link-re limit t)
3278 (setq f (get-text-property (match-beginning 0) 'face))
3279 (if (or (eq f 'org-tag)
3280 (and (listp f) (memq 'org-tag f)))
3282 (add-text-properties (match-beginning 0) (match-end 0)
3283 (list 'mouse-face 'highlight
3284 'rear-nonsticky org-nonsticky-props
3285 'keymap org-mouse-map
3287 (throw 'exit t))))))
3289 (defun org-activate-code (limit)
3290 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3291 (unless (get-text-property (match-beginning 1) 'face)
3292 (remove-text-properties (match-beginning 0) (match-end 0)
3293 '(display t invisible t intangible t))
3294 t)))
3296 (defun org-activate-angle-links (limit)
3297 "Run through the buffer and add overlays to links."
3298 (if (re-search-forward org-angle-link-re limit t)
3299 (progn
3300 (add-text-properties (match-beginning 0) (match-end 0)
3301 (list 'mouse-face 'highlight
3302 'rear-nonsticky org-nonsticky-props
3303 'keymap org-mouse-map
3305 t)))
3307 (defun org-activate-bracket-links (limit)
3308 "Run through the buffer and add overlays to bracketed links."
3309 (if (re-search-forward org-bracket-link-regexp limit t)
3310 (let* ((help (concat "LINK: "
3311 (org-match-string-no-properties 1)))
3312 ;; FIXME: above we should remove the escapes.
3313 ;; but that requires another match, protecting match data,
3314 ;; a lot of overhead for font-lock.
3315 (ip (org-maybe-intangible
3316 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3317 'keymap org-mouse-map 'mouse-face 'highlight
3318 'font-lock-multiline t 'help-echo help)))
3319 (vp (list 'rear-nonsticky org-nonsticky-props
3320 'keymap org-mouse-map 'mouse-face 'highlight
3321 ' font-lock-multiline t 'help-echo help)))
3322 ;; We need to remove the invisible property here. Table narrowing
3323 ;; may have made some of this invisible.
3324 (remove-text-properties (match-beginning 0) (match-end 0)
3325 '(invisible nil))
3326 (if (match-end 3)
3327 (progn
3328 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3329 (add-text-properties (match-beginning 3) (match-end 3) vp)
3330 (add-text-properties (match-end 3) (match-end 0) ip))
3331 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3332 (add-text-properties (match-beginning 1) (match-end 1) vp)
3333 (add-text-properties (match-end 1) (match-end 0) ip))
3334 t)))
3336 (defun org-activate-dates (limit)
3337 "Run through the buffer and add overlays to dates."
3338 (if (re-search-forward org-tsr-regexp-both limit t)
3339 (progn
3340 (add-text-properties (match-beginning 0) (match-end 0)
3341 (list 'mouse-face 'highlight
3342 'rear-nonsticky org-nonsticky-props
3343 'keymap org-mouse-map))
3344 (when org-display-custom-times
3345 (if (match-end 3)
3346 (org-display-custom-time (match-beginning 3) (match-end 3)))
3347 (org-display-custom-time (match-beginning 1) (match-end 1)))
3348 t)))
3350 (defvar org-target-link-regexp nil
3351 "Regular expression matching radio targets in plain text.")
3352 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3353 "Regular expression matching a link target.")
3354 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3355 "Regular expression matching a radio target.")
3356 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3357 "Regular expression matching any target.")
3359 (defun org-activate-target-links (limit)
3360 "Run through the buffer and add overlays to target matches."
3361 (when org-target-link-regexp
3362 (let ((case-fold-search t))
3363 (if (re-search-forward org-target-link-regexp limit t)
3364 (progn
3365 (add-text-properties (match-beginning 0) (match-end 0)
3366 (list 'mouse-face 'highlight
3367 'rear-nonsticky org-nonsticky-props
3368 'keymap org-mouse-map
3369 'help-echo "Radio target link"
3370 'org-linked-text t))
3371 t)))))
3373 (defun org-update-radio-target-regexp ()
3374 "Find all radio targets in this file and update the regular expression."
3375 (interactive)
3376 (when (memq 'radio org-activate-links)
3377 (setq org-target-link-regexp
3378 (org-make-target-link-regexp (org-all-targets 'radio)))
3379 (org-restart-font-lock)))
3381 (defun org-hide-wide-columns (limit)
3382 (let (s e)
3383 (setq s (text-property-any (point) (or limit (point-max))
3384 'org-cwidth t))
3385 (when s
3386 (setq e (next-single-property-change s 'org-cwidth))
3387 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3388 (goto-char e)
3389 t)))
3391 (defvar org-latex-and-specials-regexp nil
3392 "Regular expression for highlighting export special stuff.")
3393 (defvar org-match-substring-regexp)
3394 (defvar org-match-substring-with-braces-regexp)
3395 (defvar org-export-html-special-string-regexps)
3397 (defun org-compute-latex-and-specials-regexp ()
3398 "Compute regular expression for stuff treated specially by exporters."
3399 (if (not org-highlight-latex-fragments-and-specials)
3400 (org-set-local 'org-latex-and-specials-regexp nil)
3401 (require 'org-exp)
3402 (let*
3403 ((matchers (plist-get org-format-latex-options :matchers))
3404 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3405 org-latex-regexps)))
3406 (options (org-combine-plists (org-default-export-plist)
3407 (org-infile-export-plist)))
3408 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3409 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3410 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3411 (org-export-html-expand (plist-get options :expand-quoted-html))
3412 (org-export-with-special-strings (plist-get options :special-strings))
3413 (re-sub
3414 (cond
3415 ((equal org-export-with-sub-superscripts '{})
3416 (list org-match-substring-with-braces-regexp))
3417 (org-export-with-sub-superscripts
3418 (list org-match-substring-regexp))
3419 (t nil)))
3420 (re-latex
3421 (if org-export-with-LaTeX-fragments
3422 (mapcar (lambda (x) (nth 1 x)) latexs)))
3423 (re-macros
3424 (if org-export-with-TeX-macros
3425 (list (concat "\\\\"
3426 (regexp-opt
3427 (append (mapcar 'car org-html-entities)
3428 (if (boundp 'org-latex-entities)
3429 org-latex-entities nil))
3430 'words))) ; FIXME
3432 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3433 (re-special (if org-export-with-special-strings
3434 (mapcar (lambda (x) (car x))
3435 org-export-html-special-string-regexps)))
3436 (re-rest
3437 (delq nil
3438 (list
3439 (if org-export-html-expand "@<[^>\n]+>")
3440 ))))
3441 (org-set-local
3442 'org-latex-and-specials-regexp
3443 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3444 re-rest) "\\|")))))
3446 (defun org-do-latex-and-special-faces (limit)
3447 "Run through the buffer and add overlays to links."
3448 (when org-latex-and-specials-regexp
3449 (let (rtn d)
3450 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3451 limit t))
3452 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3453 'face))
3454 '(org-code org-verbatim underline)))
3455 (progn
3456 (setq rtn t
3457 d (cond ((member (char-after (1+ (match-beginning 0)))
3458 '(?_ ?^)) 1)
3459 (t 0)))
3460 (font-lock-prepend-text-property
3461 (+ d (match-beginning 0)) (match-end 0)
3462 'face 'org-latex-and-export-specials)
3463 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3464 '(font-lock-multiline t)))))
3465 rtn)))
3467 (defun org-restart-font-lock ()
3468 "Restart font-lock-mode, to force refontification."
3469 (when (and (boundp 'font-lock-mode) font-lock-mode)
3470 (font-lock-mode -1)
3471 (font-lock-mode 1)))
3473 (defun org-all-targets (&optional radio)
3474 "Return a list of all targets in this file.
3475 With optional argument RADIO, only find radio targets."
3476 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3477 rtn)
3478 (save-excursion
3479 (goto-char (point-min))
3480 (while (re-search-forward re nil t)
3481 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3482 rtn)))
3484 (defun org-make-target-link-regexp (targets)
3485 "Make regular expression matching all strings in TARGETS.
3486 The regular expression finds the targets also if there is a line break
3487 between words."
3488 (and targets
3489 (concat
3490 "\\<\\("
3491 (mapconcat
3492 (lambda (x)
3493 (while (string-match " +" x)
3494 (setq x (replace-match "\\s-+" t t x)))
3496 targets
3497 "\\|")
3498 "\\)\\>")))
3500 (defun org-activate-tags (limit)
3501 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3502 (progn
3503 (add-text-properties (match-beginning 1) (match-end 1)
3504 (list 'mouse-face 'highlight
3505 'rear-nonsticky org-nonsticky-props
3506 'keymap org-mouse-map))
3507 t)))
3509 (defun org-outline-level ()
3510 (save-excursion
3511 (looking-at outline-regexp)
3512 (if (match-beginning 1)
3513 (+ (org-get-string-indentation (match-string 1)) 1000)
3514 (1- (- (match-end 0) (match-beginning 0))))))
3516 (defvar org-font-lock-keywords nil)
3518 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3519 "Regular expression matching a property line.")
3521 (defun org-set-font-lock-defaults ()
3522 (let* ((em org-fontify-emphasized-text)
3523 (lk org-activate-links)
3524 (org-font-lock-extra-keywords
3525 (list
3526 ;; Headlines
3527 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3528 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3529 ;; Table lines
3530 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3531 (1 'org-table t))
3532 ;; Table internals
3533 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3534 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3535 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3536 ;; Drawers
3537 (list org-drawer-regexp '(0 'org-special-keyword t))
3538 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3539 ;; Properties
3540 (list org-property-re
3541 '(1 'org-special-keyword t)
3542 '(3 'org-property-value t))
3543 (if org-format-transports-properties-p
3544 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3545 ;; Links
3546 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3547 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3548 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3549 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3550 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3551 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3552 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3553 '(org-hide-wide-columns (0 nil append))
3554 ;; TODO lines
3555 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3556 '(1 (org-get-todo-face 1) t))
3557 ;; DONE
3558 (if org-fontify-done-headline
3559 (list (concat "^[*]+ +\\<\\("
3560 (mapconcat 'regexp-quote org-done-keywords "\\|")
3561 "\\)\\(.*\\)")
3562 '(2 'org-headline-done t))
3563 nil)
3564 ;; Priorities
3565 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3566 ;; Special keywords
3567 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3568 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3569 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3570 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3571 ;; Emphasis
3572 (if em
3573 (if (featurep 'xemacs)
3574 '(org-do-emphasis-faces (0 nil append))
3575 '(org-do-emphasis-faces)))
3576 ;; Checkboxes
3577 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3578 2 'bold prepend)
3579 (if org-provide-checkbox-statistics
3580 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3581 (0 (org-get-checkbox-statistics-face) t)))
3582 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3583 '(1 'org-archived prepend))
3584 ;; Specials
3585 '(org-do-latex-and-special-faces)
3586 ;; Code
3587 '(org-activate-code (1 'org-code t))
3588 ;; COMMENT
3589 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3590 "\\|" org-quote-string "\\)\\>")
3591 '(1 'org-special-keyword t))
3592 '("^#.*" (0 'font-lock-comment-face t))
3594 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3595 ;; Now set the full font-lock-keywords
3596 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3597 (org-set-local 'font-lock-defaults
3598 '(org-font-lock-keywords t nil nil backward-paragraph))
3599 (kill-local-variable 'font-lock-keywords) nil))
3601 (defvar org-m nil)
3602 (defvar org-l nil)
3603 (defvar org-f nil)
3604 (defun org-get-level-face (n)
3605 "Get the right face for match N in font-lock matching of healdines."
3606 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3607 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3608 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3609 (cond
3610 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3611 ((eq n 2) org-f)
3612 (t (if org-level-color-stars-only nil org-f))))
3614 (defun org-get-todo-face (kwd)
3615 "Get the right face for a TODO keyword KWD.
3616 If KWD is a number, get the corresponding match group."
3617 (if (numberp kwd) (setq kwd (match-string kwd)))
3618 (or (cdr (assoc kwd org-todo-keyword-faces))
3619 (and (member kwd org-done-keywords) 'org-done)
3620 'org-todo))
3622 (defun org-unfontify-region (beg end &optional maybe_loudly)
3623 "Remove fontification and activation overlays from links."
3624 (font-lock-default-unfontify-region beg end)
3625 (let* ((buffer-undo-list t)
3626 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3627 (inhibit-modification-hooks t)
3628 deactivate-mark buffer-file-name buffer-file-truename)
3629 (remove-text-properties beg end
3630 '(mouse-face t keymap t org-linked-text t
3631 invisible t intangible t))))
3633 ;;;; Visibility cycling, including org-goto and indirect buffer
3635 ;;; Cycling
3637 (defvar org-cycle-global-status nil)
3638 (make-variable-buffer-local 'org-cycle-global-status)
3639 (defvar org-cycle-subtree-status nil)
3640 (make-variable-buffer-local 'org-cycle-subtree-status)
3642 ;;;###autoload
3643 (defun org-cycle (&optional arg)
3644 "Visibility cycling for Org-mode.
3646 - When this function is called with a prefix argument, rotate the entire
3647 buffer through 3 states (global cycling)
3648 1. OVERVIEW: Show only top-level headlines.
3649 2. CONTENTS: Show all headlines of all levels, but no body text.
3650 3. SHOW ALL: Show everything.
3652 - When point is at the beginning of a headline, rotate the subtree started
3653 by this line through 3 different states (local cycling)
3654 1. FOLDED: Only the main headline is shown.
3655 2. CHILDREN: The main headline and the direct children are shown.
3656 From this state, you can move to one of the children
3657 and zoom in further.
3658 3. SUBTREE: Show the entire subtree, including body text.
3660 - When there is a numeric prefix, go up to a heading with level ARG, do
3661 a `show-subtree' and return to the previous cursor position. If ARG
3662 is negative, go up that many levels.
3664 - When point is not at the beginning of a headline, execute
3665 `indent-relative', like TAB normally does. See the option
3666 `org-cycle-emulate-tab' for details.
3668 - Special case: if point is at the beginning of the buffer and there is
3669 no headline in line 1, this function will act as if called with prefix arg.
3670 But only if also the variable `org-cycle-global-at-bob' is t."
3671 (interactive "P")
3672 (org-load-modules-maybe)
3673 (let* ((outline-regexp
3674 (if (and (org-mode-p) org-cycle-include-plain-lists)
3675 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3676 outline-regexp))
3677 (bob-special (and org-cycle-global-at-bob (bobp)
3678 (not (looking-at outline-regexp))))
3679 (org-cycle-hook
3680 (if bob-special
3681 (delq 'org-optimize-window-after-visibility-change
3682 (copy-sequence org-cycle-hook))
3683 org-cycle-hook))
3684 (pos (point)))
3686 (if (or bob-special (equal arg '(4)))
3687 ;; special case: use global cycling
3688 (setq arg t))
3690 (cond
3692 ((org-at-table-p 'any)
3693 ;; Enter the table or move to the next field in the table
3694 (or (org-table-recognize-table.el)
3695 (progn
3696 (if arg (org-table-edit-field t)
3697 (org-table-justify-field-maybe)
3698 (call-interactively 'org-table-next-field)))))
3700 ((eq arg t) ;; Global cycling
3702 (cond
3703 ((and (eq last-command this-command)
3704 (eq org-cycle-global-status 'overview))
3705 ;; We just created the overview - now do table of contents
3706 ;; This can be slow in very large buffers, so indicate action
3707 (message "CONTENTS...")
3708 (org-content)
3709 (message "CONTENTS...done")
3710 (setq org-cycle-global-status 'contents)
3711 (run-hook-with-args 'org-cycle-hook 'contents))
3713 ((and (eq last-command this-command)
3714 (eq org-cycle-global-status 'contents))
3715 ;; We just showed the table of contents - now show everything
3716 (show-all)
3717 (message "SHOW ALL")
3718 (setq org-cycle-global-status 'all)
3719 (run-hook-with-args 'org-cycle-hook 'all))
3722 ;; Default action: go to overview
3723 (org-overview)
3724 (message "OVERVIEW")
3725 (setq org-cycle-global-status 'overview)
3726 (run-hook-with-args 'org-cycle-hook 'overview))))
3728 ((and org-drawers org-drawer-regexp
3729 (save-excursion
3730 (beginning-of-line 1)
3731 (looking-at org-drawer-regexp)))
3732 ;; Toggle block visibility
3733 (org-flag-drawer
3734 (not (get-char-property (match-end 0) 'invisible))))
3736 ((integerp arg)
3737 ;; Show-subtree, ARG levels up from here.
3738 (save-excursion
3739 (org-back-to-heading)
3740 (outline-up-heading (if (< arg 0) (- arg)
3741 (- (funcall outline-level) arg)))
3742 (org-show-subtree)))
3744 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3745 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3746 ;; At a heading: rotate between three different views
3747 (org-back-to-heading)
3748 (let ((goal-column 0) eoh eol eos)
3749 ;; First, some boundaries
3750 (save-excursion
3751 (org-back-to-heading)
3752 (save-excursion
3753 (beginning-of-line 2)
3754 (while (and (not (eobp)) ;; this is like `next-line'
3755 (get-char-property (1- (point)) 'invisible))
3756 (beginning-of-line 2)) (setq eol (point)))
3757 (outline-end-of-heading) (setq eoh (point))
3758 (org-end-of-subtree t)
3759 (unless (eobp)
3760 (skip-chars-forward " \t\n")
3761 (beginning-of-line 1) ; in case this is an item
3763 (setq eos (1- (point))))
3764 ;; Find out what to do next and set `this-command'
3765 (cond
3766 ((= eos eoh)
3767 ;; Nothing is hidden behind this heading
3768 (message "EMPTY ENTRY")
3769 (setq org-cycle-subtree-status nil)
3770 (save-excursion
3771 (goto-char eos)
3772 (outline-next-heading)
3773 (if (org-invisible-p) (org-flag-heading nil))))
3774 ((or (>= eol eos)
3775 (not (string-match "\\S-" (buffer-substring eol eos))))
3776 ;; Entire subtree is hidden in one line: open it
3777 (org-show-entry)
3778 (show-children)
3779 (message "CHILDREN")
3780 (save-excursion
3781 (goto-char eos)
3782 (outline-next-heading)
3783 (if (org-invisible-p) (org-flag-heading nil)))
3784 (setq org-cycle-subtree-status 'children)
3785 (run-hook-with-args 'org-cycle-hook 'children))
3786 ((and (eq last-command this-command)
3787 (eq org-cycle-subtree-status 'children))
3788 ;; We just showed the children, now show everything.
3789 (org-show-subtree)
3790 (message "SUBTREE")
3791 (setq org-cycle-subtree-status 'subtree)
3792 (run-hook-with-args 'org-cycle-hook 'subtree))
3794 ;; Default action: hide the subtree.
3795 (hide-subtree)
3796 (message "FOLDED")
3797 (setq org-cycle-subtree-status 'folded)
3798 (run-hook-with-args 'org-cycle-hook 'folded)))))
3800 ;; TAB emulation
3801 (buffer-read-only (org-back-to-heading))
3803 ((org-try-cdlatex-tab))
3805 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3806 (or (not (bolp))
3807 (not (looking-at outline-regexp))))
3808 (call-interactively (global-key-binding "\t")))
3810 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3811 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3812 (or (and (eq org-cycle-emulate-tab 'white)
3813 (= (match-end 0) (point-at-eol)))
3814 (and (eq org-cycle-emulate-tab 'whitestart)
3815 (>= (match-end 0) pos))))
3817 (eq org-cycle-emulate-tab t))
3818 (call-interactively (global-key-binding "\t")))
3820 (t (save-excursion
3821 (org-back-to-heading)
3822 (org-cycle))))))
3824 ;;;###autoload
3825 (defun org-global-cycle (&optional arg)
3826 "Cycle the global visibility. For details see `org-cycle'."
3827 (interactive "P")
3828 (let ((org-cycle-include-plain-lists
3829 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3830 (if (integerp arg)
3831 (progn
3832 (show-all)
3833 (hide-sublevels arg)
3834 (setq org-cycle-global-status 'contents))
3835 (org-cycle '(4)))))
3837 (defun org-overview ()
3838 "Switch to overview mode, shoing only top-level headlines.
3839 Really, this shows all headlines with level equal or greater than the level
3840 of the first headline in the buffer. This is important, because if the
3841 first headline is not level one, then (hide-sublevels 1) gives confusing
3842 results."
3843 (interactive)
3844 (let ((level (save-excursion
3845 (goto-char (point-min))
3846 (if (re-search-forward (concat "^" outline-regexp) nil t)
3847 (progn
3848 (goto-char (match-beginning 0))
3849 (funcall outline-level))))))
3850 (and level (hide-sublevels level))))
3852 (defun org-content (&optional arg)
3853 "Show all headlines in the buffer, like a table of contents.
3854 With numerical argument N, show content up to level N."
3855 (interactive "P")
3856 (save-excursion
3857 ;; Visit all headings and show their offspring
3858 (and (integerp arg) (org-overview))
3859 (goto-char (point-max))
3860 (catch 'exit
3861 (while (and (progn (condition-case nil
3862 (outline-previous-visible-heading 1)
3863 (error (goto-char (point-min))))
3865 (looking-at outline-regexp))
3866 (if (integerp arg)
3867 (show-children (1- arg))
3868 (show-branches))
3869 (if (bobp) (throw 'exit nil))))))
3872 (defun org-optimize-window-after-visibility-change (state)
3873 "Adjust the window after a change in outline visibility.
3874 This function is the default value of the hook `org-cycle-hook'."
3875 (when (get-buffer-window (current-buffer))
3876 (cond
3877 ; ((eq state 'overview) (org-first-headline-recenter 1))
3878 ; ((eq state 'overview) (org-beginning-of-line))
3879 ((eq state 'content) nil)
3880 ((eq state 'all) nil)
3881 ((eq state 'folded) nil)
3882 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3883 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3885 (defun org-compact-display-after-subtree-move ()
3886 (let (beg end)
3887 (save-excursion
3888 (if (org-up-heading-safe)
3889 (progn
3890 (hide-subtree)
3891 (show-entry)
3892 (show-children)
3893 (org-cycle-show-empty-lines 'children)
3894 (org-cycle-hide-drawers 'children))
3895 (org-overview)))))
3897 (defun org-cycle-show-empty-lines (state)
3898 "Show empty lines above all visible headlines.
3899 The region to be covered depends on STATE when called through
3900 `org-cycle-hook'. Lisp program can use t for STATE to get the
3901 entire buffer covered. Note that an empty line is only shown if there
3902 are at least `org-cycle-separator-lines' empty lines before the headeline."
3903 (when (> org-cycle-separator-lines 0)
3904 (save-excursion
3905 (let* ((n org-cycle-separator-lines)
3906 (re (cond
3907 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3908 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3909 (t (let ((ns (number-to-string (- n 2))))
3910 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3911 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3912 beg end)
3913 (cond
3914 ((memq state '(overview contents t))
3915 (setq beg (point-min) end (point-max)))
3916 ((memq state '(children folded))
3917 (setq beg (point) end (progn (org-end-of-subtree t t)
3918 (beginning-of-line 2)
3919 (point)))))
3920 (when beg
3921 (goto-char beg)
3922 (while (re-search-forward re end t)
3923 (if (not (get-char-property (match-end 1) 'invisible))
3924 (outline-flag-region
3925 (match-beginning 1) (match-end 1) nil)))))))
3926 ;; Never hide empty lines at the end of the file.
3927 (save-excursion
3928 (goto-char (point-max))
3929 (outline-previous-heading)
3930 (outline-end-of-heading)
3931 (if (and (looking-at "[ \t\n]+")
3932 (= (match-end 0) (point-max)))
3933 (outline-flag-region (point) (match-end 0) nil))))
3935 (defun org-cycle-hide-drawers (state)
3936 "Re-hide all drawers after a visibility state change."
3937 (when (and (org-mode-p)
3938 (not (memq state '(overview folded))))
3939 (save-excursion
3940 (let* ((globalp (memq state '(contents all)))
3941 (beg (if globalp (point-min) (point)))
3942 (end (if globalp (point-max) (org-end-of-subtree t))))
3943 (goto-char beg)
3944 (while (re-search-forward org-drawer-regexp end t)
3945 (org-flag-drawer t))))))
3947 (defun org-flag-drawer (flag)
3948 (save-excursion
3949 (beginning-of-line 1)
3950 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
3951 (let ((b (match-end 0))
3952 (outline-regexp org-outline-regexp))
3953 (if (re-search-forward
3954 "^[ \t]*:END:"
3955 (save-excursion (outline-next-heading) (point)) t)
3956 (outline-flag-region b (point-at-eol) flag)
3957 (error ":END: line missing"))))))
3961 (defun org-subtree-end-visible-p ()
3962 "Is the end of the current subtree visible?"
3963 (pos-visible-in-window-p
3964 (save-excursion (org-end-of-subtree t) (point))))
3966 (defun org-first-headline-recenter (&optional N)
3967 "Move cursor to the first headline and recenter the headline.
3968 Optional argument N means, put the headline into the Nth line of the window."
3969 (goto-char (point-min))
3970 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3971 (beginning-of-line)
3972 (recenter (prefix-numeric-value N))))
3974 ;;; Org-goto
3976 (defvar org-goto-window-configuration nil)
3977 (defvar org-goto-marker nil)
3978 (defvar org-goto-map
3979 (let ((map (make-sparse-keymap)))
3980 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
3981 (while (setq cmd (pop cmds))
3982 (substitute-key-definition cmd cmd map global-map)))
3983 (suppress-keymap map)
3984 (org-defkey map "\C-m" 'org-goto-ret)
3985 (org-defkey map [(return)] 'org-goto-ret)
3986 (org-defkey map [(left)] 'org-goto-left)
3987 (org-defkey map [(right)] 'org-goto-right)
3988 (org-defkey map [(control ?g)] 'org-goto-quit)
3989 (org-defkey map "\C-i" 'org-cycle)
3990 (org-defkey map [(tab)] 'org-cycle)
3991 (org-defkey map [(down)] 'outline-next-visible-heading)
3992 (org-defkey map [(up)] 'outline-previous-visible-heading)
3993 (if org-goto-auto-isearch
3994 (if (fboundp 'define-key-after)
3995 (define-key-after map [t] 'org-goto-local-auto-isearch)
3996 nil)
3997 (org-defkey map "q" 'org-goto-quit)
3998 (org-defkey map "n" 'outline-next-visible-heading)
3999 (org-defkey map "p" 'outline-previous-visible-heading)
4000 (org-defkey map "f" 'outline-forward-same-level)
4001 (org-defkey map "b" 'outline-backward-same-level)
4002 (org-defkey map "u" 'outline-up-heading))
4003 (org-defkey map "/" 'org-occur)
4004 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4005 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4006 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4007 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4008 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4009 map))
4011 (defconst org-goto-help
4012 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4013 RET=jump to location [Q]uit and return to previous location
4014 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4016 (defvar org-goto-start-pos) ; dynamically scoped parameter
4018 (defun org-goto (&optional alternative-interface)
4019 "Look up a different location in the current file, keeping current visibility.
4021 When you want look-up or go to a different location in a document, the
4022 fastest way is often to fold the entire buffer and then dive into the tree.
4023 This method has the disadvantage, that the previous location will be folded,
4024 which may not be what you want.
4026 This command works around this by showing a copy of the current buffer
4027 in an indirect buffer, in overview mode. You can dive into the tree in
4028 that copy, use org-occur and incremental search to find a location.
4029 When pressing RET or `Q', the command returns to the original buffer in
4030 which the visibility is still unchanged. After RET is will also jump to
4031 the location selected in the indirect buffer and expose the
4032 the headline hierarchy above."
4033 (interactive "P")
4034 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4035 (org-refile-use-outline-path t)
4036 (interface
4037 (if (not alternative-interface)
4038 org-goto-interface
4039 (if (eq org-goto-interface 'outline)
4040 'outline-path-completion
4041 'outline)))
4042 (org-goto-start-pos (point))
4043 (selected-point
4044 (if (eq interface 'outline)
4045 (car (org-get-location (current-buffer) org-goto-help))
4046 (nth 3 (org-refile-get-location "Goto: ")))))
4047 (if selected-point
4048 (progn
4049 (org-mark-ring-push org-goto-start-pos)
4050 (goto-char selected-point)
4051 (if (or (org-invisible-p) (org-invisible-p2))
4052 (org-show-context 'org-goto)))
4053 (message "Quit"))))
4055 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4056 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4057 (defvar org-goto-local-auto-isearch-map) ; defined below
4059 (defun org-get-location (buf help)
4060 "Let the user select a location in the Org-mode buffer BUF.
4061 This function uses a recursive edit. It returns the selected position
4062 or nil."
4063 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4064 (isearch-hide-immediately nil)
4065 (isearch-search-fun-function
4066 (lambda () 'org-goto-local-search-forward-headings))
4067 (org-goto-selected-point org-goto-exit-command))
4068 (save-excursion
4069 (save-window-excursion
4070 (delete-other-windows)
4071 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4072 (switch-to-buffer
4073 (condition-case nil
4074 (make-indirect-buffer (current-buffer) "*org-goto*")
4075 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4076 (with-output-to-temp-buffer "*Help*"
4077 (princ help))
4078 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4079 (setq buffer-read-only nil)
4080 (let ((org-startup-truncated t)
4081 (org-startup-folded nil)
4082 (org-startup-align-all-tables nil))
4083 (org-mode)
4084 (org-overview))
4085 (setq buffer-read-only t)
4086 (if (and (boundp 'org-goto-start-pos)
4087 (integer-or-marker-p org-goto-start-pos))
4088 (let ((org-show-hierarchy-above t)
4089 (org-show-siblings t)
4090 (org-show-following-heading t))
4091 (goto-char org-goto-start-pos)
4092 (and (org-invisible-p) (org-show-context)))
4093 (goto-char (point-min)))
4094 (org-beginning-of-line)
4095 (message "Select location and press RET")
4096 (use-local-map org-goto-map)
4097 (recursive-edit)
4099 (kill-buffer "*org-goto*")
4100 (cons org-goto-selected-point org-goto-exit-command)))
4102 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4103 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4104 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4105 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4107 (defun org-goto-local-search-forward-headings (string bound noerror)
4108 "Search and make sure that anu matches are in headlines."
4109 (catch 'return
4110 (while (search-forward string bound noerror)
4111 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4112 (and (member :headline context)
4113 (not (member :tags context))))
4114 (throw 'return (point))))))
4116 (defun org-goto-local-auto-isearch ()
4117 "Start isearch."
4118 (interactive)
4119 (goto-char (point-min))
4120 (let ((keys (this-command-keys)))
4121 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4122 (isearch-mode t)
4123 (isearch-process-search-char (string-to-char keys)))))
4125 (defun org-goto-ret (&optional arg)
4126 "Finish `org-goto' by going to the new location."
4127 (interactive "P")
4128 (setq org-goto-selected-point (point)
4129 org-goto-exit-command 'return)
4130 (throw 'exit nil))
4132 (defun org-goto-left ()
4133 "Finish `org-goto' by going to the new location."
4134 (interactive)
4135 (if (org-on-heading-p)
4136 (progn
4137 (beginning-of-line 1)
4138 (setq org-goto-selected-point (point)
4139 org-goto-exit-command 'left)
4140 (throw 'exit nil))
4141 (error "Not on a heading")))
4143 (defun org-goto-right ()
4144 "Finish `org-goto' by going to the new location."
4145 (interactive)
4146 (if (org-on-heading-p)
4147 (progn
4148 (setq org-goto-selected-point (point)
4149 org-goto-exit-command 'right)
4150 (throw 'exit nil))
4151 (error "Not on a heading")))
4153 (defun org-goto-quit ()
4154 "Finish `org-goto' without cursor motion."
4155 (interactive)
4156 (setq org-goto-selected-point nil)
4157 (setq org-goto-exit-command 'quit)
4158 (throw 'exit nil))
4160 ;;; Indirect buffer display of subtrees
4162 (defvar org-indirect-dedicated-frame nil
4163 "This is the frame being used for indirect tree display.")
4164 (defvar org-last-indirect-buffer nil)
4166 (defun org-tree-to-indirect-buffer (&optional arg)
4167 "Create indirect buffer and narrow it to current subtree.
4168 With numerical prefix ARG, go up to this level and then take that tree.
4169 If ARG is negative, go up that many levels.
4170 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4171 indirect buffer previously made with this command, to avoid proliferation of
4172 indirect buffers. However, when you call the command with a `C-u' prefix, or
4173 when `org-indirect-buffer-display' is `new-frame', the last buffer
4174 is kept so that you can work with several indirect buffers at the same time.
4175 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4176 requests that a new frame be made for the new buffer, so that the dedicated
4177 frame is not changed."
4178 (interactive "P")
4179 (let ((cbuf (current-buffer))
4180 (cwin (selected-window))
4181 (pos (point))
4182 beg end level heading ibuf)
4183 (save-excursion
4184 (org-back-to-heading t)
4185 (when (numberp arg)
4186 (setq level (org-outline-level))
4187 (if (< arg 0) (setq arg (+ level arg)))
4188 (while (> (setq level (org-outline-level)) arg)
4189 (outline-up-heading 1 t)))
4190 (setq beg (point)
4191 heading (org-get-heading))
4192 (org-end-of-subtree t) (setq end (point)))
4193 (if (and (buffer-live-p org-last-indirect-buffer)
4194 (not (eq org-indirect-buffer-display 'new-frame))
4195 (not arg))
4196 (kill-buffer org-last-indirect-buffer))
4197 (setq ibuf (org-get-indirect-buffer cbuf)
4198 org-last-indirect-buffer ibuf)
4199 (cond
4200 ((or (eq org-indirect-buffer-display 'new-frame)
4201 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4202 (select-frame (make-frame))
4203 (delete-other-windows)
4204 (switch-to-buffer ibuf)
4205 (org-set-frame-title heading))
4206 ((eq org-indirect-buffer-display 'dedicated-frame)
4207 (raise-frame
4208 (select-frame (or (and org-indirect-dedicated-frame
4209 (frame-live-p org-indirect-dedicated-frame)
4210 org-indirect-dedicated-frame)
4211 (setq org-indirect-dedicated-frame (make-frame)))))
4212 (delete-other-windows)
4213 (switch-to-buffer ibuf)
4214 (org-set-frame-title (concat "Indirect: " heading)))
4215 ((eq org-indirect-buffer-display 'current-window)
4216 (switch-to-buffer ibuf))
4217 ((eq org-indirect-buffer-display 'other-window)
4218 (pop-to-buffer ibuf))
4219 (t (error "Invalid value.")))
4220 (if (featurep 'xemacs)
4221 (save-excursion (org-mode) (turn-on-font-lock)))
4222 (narrow-to-region beg end)
4223 (show-all)
4224 (goto-char pos)
4225 (and (window-live-p cwin) (select-window cwin))))
4227 (defun org-get-indirect-buffer (&optional buffer)
4228 (setq buffer (or buffer (current-buffer)))
4229 (let ((n 1) (base (buffer-name buffer)) bname)
4230 (while (buffer-live-p
4231 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4232 (setq n (1+ n)))
4233 (condition-case nil
4234 (make-indirect-buffer buffer bname 'clone)
4235 (error (make-indirect-buffer buffer bname)))))
4237 (defun org-set-frame-title (title)
4238 "Set the title of the current frame to the string TITLE."
4239 ;; FIXME: how to name a single frame in XEmacs???
4240 (unless (featurep 'xemacs)
4241 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4243 ;;;; Structure editing
4245 ;;; Inserting headlines
4247 (defun org-insert-heading (&optional force-heading)
4248 "Insert a new heading or item with same depth at point.
4249 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4250 If point is at the beginning of a headline, insert a sibling before the
4251 current headline. If point is not at the beginning, do not split the line,
4252 but create the new hedline after the current line."
4253 (interactive "P")
4254 (if (= (buffer-size) 0)
4255 (insert "\n* ")
4256 (when (or force-heading (not (org-insert-item)))
4257 (let* ((head (save-excursion
4258 (condition-case nil
4259 (progn
4260 (org-back-to-heading)
4261 (match-string 0))
4262 (error "*"))))
4263 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4264 pos)
4265 (cond
4266 ((and (org-on-heading-p) (bolp)
4267 (or (bobp)
4268 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4269 ;; insert before the current line
4270 (open-line (if blank 2 1)))
4271 ((and (bolp)
4272 (or (bobp)
4273 (save-excursion
4274 (backward-char 1) (not (org-invisible-p)))))
4275 ;; insert right here
4276 nil)
4278 ;; in the middle of the line
4279 (org-show-entry)
4280 (let ((split
4281 (org-get-alist-option org-M-RET-may-split-line 'headline))
4282 tags pos)
4283 (if (org-on-heading-p)
4284 (progn
4285 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4286 (setq tags (and (match-end 2) (match-string 2)))
4287 (and (match-end 1)
4288 (delete-region (match-beginning 1) (match-end 1)))
4289 (setq pos (point-at-bol))
4290 (or split (end-of-line 1))
4291 (delete-horizontal-space)
4292 (newline (if blank 2 1))
4293 (when tags
4294 (save-excursion
4295 (goto-char pos)
4296 (end-of-line 1)
4297 (insert " " tags)
4298 (org-set-tags nil 'align))))
4299 (or split (end-of-line 1))
4300 (newline (if blank 2 1))))))
4301 (insert head) (just-one-space)
4302 (setq pos (point))
4303 (end-of-line 1)
4304 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4305 (run-hooks 'org-insert-heading-hook)))))
4307 (defun org-get-heading (&optional no-tags)
4308 "Return the heading of the current entry, without the stars."
4309 (save-excursion
4310 (org-back-to-heading t)
4311 (if (looking-at
4312 (if no-tags
4313 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4314 "\\*+[ \t]+\\([^\r\n]*\\)"))
4315 (match-string 1) "")))
4317 (defun org-insert-heading-after-current ()
4318 "Insert a new heading with same level as current, after current subtree."
4319 (interactive)
4320 (org-back-to-heading)
4321 (org-insert-heading)
4322 (org-move-subtree-down)
4323 (end-of-line 1))
4325 (defun org-insert-todo-heading (arg)
4326 "Insert a new heading with the same level and TODO state as current heading.
4327 If the heading has no TODO state, or if the state is DONE, use the first
4328 state (TODO by default). Also with prefix arg, force first state."
4329 (interactive "P")
4330 (when (not (org-insert-item 'checkbox))
4331 (org-insert-heading)
4332 (save-excursion
4333 (org-back-to-heading)
4334 (outline-previous-heading)
4335 (looking-at org-todo-line-regexp))
4336 (if (or arg
4337 (not (match-beginning 2))
4338 (member (match-string 2) org-done-keywords))
4339 (insert (car org-todo-keywords-1) " ")
4340 (insert (match-string 2) " "))))
4342 (defun org-insert-subheading (arg)
4343 "Insert a new subheading and demote it.
4344 Works for outline headings and for plain lists alike."
4345 (interactive "P")
4346 (org-insert-heading arg)
4347 (cond
4348 ((org-on-heading-p) (org-do-demote))
4349 ((org-at-item-p) (org-indent-item 1))))
4351 (defun org-insert-todo-subheading (arg)
4352 "Insert a new subheading with TODO keyword or checkbox and demote it.
4353 Works for outline headings and for plain lists alike."
4354 (interactive "P")
4355 (org-insert-todo-heading arg)
4356 (cond
4357 ((org-on-heading-p) (org-do-demote))
4358 ((org-at-item-p) (org-indent-item 1))))
4360 ;;; Promotion and Demotion
4362 (defun org-promote-subtree ()
4363 "Promote the entire subtree.
4364 See also `org-promote'."
4365 (interactive)
4366 (save-excursion
4367 (org-map-tree 'org-promote))
4368 (org-fix-position-after-promote))
4370 (defun org-demote-subtree ()
4371 "Demote the entire subtree. See `org-demote'.
4372 See also `org-promote'."
4373 (interactive)
4374 (save-excursion
4375 (org-map-tree 'org-demote))
4376 (org-fix-position-after-promote))
4379 (defun org-do-promote ()
4380 "Promote the current heading higher up the tree.
4381 If the region is active in `transient-mark-mode', promote all headings
4382 in the region."
4383 (interactive)
4384 (save-excursion
4385 (if (org-region-active-p)
4386 (org-map-region 'org-promote (region-beginning) (region-end))
4387 (org-promote)))
4388 (org-fix-position-after-promote))
4390 (defun org-do-demote ()
4391 "Demote the current heading lower down the tree.
4392 If the region is active in `transient-mark-mode', demote all headings
4393 in the region."
4394 (interactive)
4395 (save-excursion
4396 (if (org-region-active-p)
4397 (org-map-region 'org-demote (region-beginning) (region-end))
4398 (org-demote)))
4399 (org-fix-position-after-promote))
4401 (defun org-fix-position-after-promote ()
4402 "Make sure that after pro/demotion cursor position is right."
4403 (let ((pos (point)))
4404 (when (save-excursion
4405 (beginning-of-line 1)
4406 (looking-at org-todo-line-regexp)
4407 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4408 (cond ((eobp) (insert " "))
4409 ((eolp) (insert " "))
4410 ((equal (char-after) ?\ ) (forward-char 1))))))
4412 (defun org-reduced-level (l)
4413 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4415 (defun org-get-valid-level (level &optional change)
4416 "Rectify a level change under the influence of `org-odd-levels-only'
4417 LEVEL is a current level, CHANGE is by how much the level should be
4418 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4419 even level numbers will become the next higher odd number."
4420 (if org-odd-levels-only
4421 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4422 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4423 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4424 (max 1 (+ level change))))
4426 (if (boundp 'define-obsolete-function-alias)
4427 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4428 (define-obsolete-function-alias 'org-get-legal-level
4429 'org-get-valid-level)
4430 (define-obsolete-function-alias 'org-get-legal-level
4431 'org-get-valid-level "23.1")))
4433 (defun org-promote ()
4434 "Promote the current heading higher up the tree.
4435 If the region is active in `transient-mark-mode', promote all headings
4436 in the region."
4437 (org-back-to-heading t)
4438 (let* ((level (save-match-data (funcall outline-level)))
4439 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4440 (diff (abs (- level (length up-head) -1))))
4441 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4442 (replace-match up-head nil t)
4443 ;; Fixup tag positioning
4444 (and org-auto-align-tags (org-set-tags nil t))
4445 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4447 (defun org-demote ()
4448 "Demote the current heading lower down the tree.
4449 If the region is active in `transient-mark-mode', demote all headings
4450 in the region."
4451 (org-back-to-heading t)
4452 (let* ((level (save-match-data (funcall outline-level)))
4453 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4454 (diff (abs (- level (length down-head) -1))))
4455 (replace-match down-head nil t)
4456 ;; Fixup tag positioning
4457 (and org-auto-align-tags (org-set-tags nil t))
4458 (if org-adapt-indentation (org-fixup-indentation diff))))
4460 (defun org-map-tree (fun)
4461 "Call FUN for every heading underneath the current one."
4462 (org-back-to-heading)
4463 (let ((level (funcall outline-level)))
4464 (save-excursion
4465 (funcall fun)
4466 (while (and (progn
4467 (outline-next-heading)
4468 (> (funcall outline-level) level))
4469 (not (eobp)))
4470 (funcall fun)))))
4472 (defun org-map-region (fun beg end)
4473 "Call FUN for every heading between BEG and END."
4474 (let ((org-ignore-region t))
4475 (save-excursion
4476 (setq end (copy-marker end))
4477 (goto-char beg)
4478 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4479 (< (point) end))
4480 (funcall fun))
4481 (while (and (progn
4482 (outline-next-heading)
4483 (< (point) end))
4484 (not (eobp)))
4485 (funcall fun)))))
4487 (defun org-fixup-indentation (diff)
4488 "Change the indentation in the current entry by DIFF
4489 However, if any line in the current entry has no indentation, or if it
4490 would end up with no indentation after the change, nothing at all is done."
4491 (save-excursion
4492 (let ((end (save-excursion (outline-next-heading)
4493 (point-marker)))
4494 (prohibit (if (> diff 0)
4495 "^\\S-"
4496 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4497 col)
4498 (unless (save-excursion (end-of-line 1)
4499 (re-search-forward prohibit end t))
4500 (while (and (< (point) end)
4501 (re-search-forward "^[ \t]+" end t))
4502 (goto-char (match-end 0))
4503 (setq col (current-column))
4504 (if (< diff 0) (replace-match ""))
4505 (indent-to (+ diff col))))
4506 (move-marker end nil))))
4508 (defun org-convert-to-odd-levels ()
4509 "Convert an org-mode file with all levels allowed to one with odd levels.
4510 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4511 level 5 etc."
4512 (interactive)
4513 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4514 (let ((org-odd-levels-only nil) n)
4515 (save-excursion
4516 (goto-char (point-min))
4517 (while (re-search-forward "^\\*\\*+ " nil t)
4518 (setq n (- (length (match-string 0)) 2))
4519 (while (>= (setq n (1- n)) 0)
4520 (org-demote))
4521 (end-of-line 1))))))
4524 (defun org-convert-to-oddeven-levels ()
4525 "Convert an org-mode file with only odd levels to one with odd and even levels.
4526 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4527 section with an even level, conversion would destroy the structure of the file. An error
4528 is signaled in this case."
4529 (interactive)
4530 (goto-char (point-min))
4531 ;; First check if there are no even levels
4532 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4533 (org-show-context t)
4534 (error "Not all levels are odd in this file. Conversion not possible."))
4535 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4536 (let ((org-odd-levels-only nil) n)
4537 (save-excursion
4538 (goto-char (point-min))
4539 (while (re-search-forward "^\\*\\*+ " nil t)
4540 (setq n (/ (1- (length (match-string 0))) 2))
4541 (while (>= (setq n (1- n)) 0)
4542 (org-promote))
4543 (end-of-line 1))))))
4545 (defun org-tr-level (n)
4546 "Make N odd if required."
4547 (if org-odd-levels-only (1+ (/ n 2)) n))
4549 ;;; Vertical tree motion, cutting and pasting of subtrees
4551 (defun org-move-subtree-up (&optional arg)
4552 "Move the current subtree up past ARG headlines of the same level."
4553 (interactive "p")
4554 (org-move-subtree-down (- (prefix-numeric-value arg))))
4556 (defun org-move-subtree-down (&optional arg)
4557 "Move the current subtree down past ARG headlines of the same level."
4558 (interactive "p")
4559 (setq arg (prefix-numeric-value arg))
4560 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4561 'outline-get-last-sibling))
4562 (ins-point (make-marker))
4563 (cnt (abs arg))
4564 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4565 ;; Select the tree
4566 (org-back-to-heading)
4567 (setq beg0 (point))
4568 (save-excursion
4569 (setq ne-beg (org-back-over-empty-lines))
4570 (setq beg (point)))
4571 (save-match-data
4572 (save-excursion (outline-end-of-heading)
4573 (setq folded (org-invisible-p)))
4574 (outline-end-of-subtree))
4575 (outline-next-heading)
4576 (setq ne-end (org-back-over-empty-lines))
4577 (setq end (point))
4578 (goto-char beg0)
4579 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4580 ;; include less whitespace
4581 (save-excursion
4582 (goto-char beg)
4583 (forward-line (- ne-beg ne-end))
4584 (setq beg (point))))
4585 ;; Find insertion point, with error handling
4586 (while (> cnt 0)
4587 (or (and (funcall movfunc) (looking-at outline-regexp))
4588 (progn (goto-char beg0)
4589 (error "Cannot move past superior level or buffer limit")))
4590 (setq cnt (1- cnt)))
4591 (if (> arg 0)
4592 ;; Moving forward - still need to move over subtree
4593 (progn (org-end-of-subtree t t)
4594 (save-excursion
4595 (org-back-over-empty-lines)
4596 (or (bolp) (newline)))))
4597 (setq ne-ins (org-back-over-empty-lines))
4598 (move-marker ins-point (point))
4599 (setq txt (buffer-substring beg end))
4600 (delete-region beg end)
4601 (outline-flag-region (1- beg) beg nil)
4602 (outline-flag-region (1- (point)) (point) nil)
4603 (insert txt)
4604 (or (bolp) (insert "\n"))
4605 (setq ins-end (point))
4606 (goto-char ins-point)
4607 (org-skip-whitespace)
4608 (when (and (< arg 0)
4609 (org-first-sibling-p)
4610 (> ne-ins ne-beg))
4611 ;; Move whitespace back to beginning
4612 (save-excursion
4613 (goto-char ins-end)
4614 (let ((kill-whole-line t))
4615 (kill-line (- ne-ins ne-beg)) (point)))
4616 (insert (make-string (- ne-ins ne-beg) ?\n)))
4617 (move-marker ins-point nil)
4618 (org-compact-display-after-subtree-move)
4619 (unless folded
4620 (org-show-entry)
4621 (show-children)
4622 (org-cycle-hide-drawers 'children))))
4624 (defvar org-subtree-clip ""
4625 "Clipboard for cut and paste of subtrees.
4626 This is actually only a copy of the kill, because we use the normal kill
4627 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4629 (defvar org-subtree-clip-folded nil
4630 "Was the last copied subtree folded?
4631 This is used to fold the tree back after pasting.")
4633 (defun org-cut-subtree (&optional n)
4634 "Cut the current subtree into the clipboard.
4635 With prefix arg N, cut this many sequential subtrees.
4636 This is a short-hand for marking the subtree and then cutting it."
4637 (interactive "p")
4638 (org-copy-subtree n 'cut))
4640 (defun org-copy-subtree (&optional n cut)
4641 "Cut the current subtree into the clipboard.
4642 With prefix arg N, cut this many sequential subtrees.
4643 This is a short-hand for marking the subtree and then copying it.
4644 If CUT is non-nil, actually cut the subtree."
4645 (interactive "p")
4646 (let (beg end folded (beg0 (point)))
4647 (if (interactive-p)
4648 (org-back-to-heading nil) ; take what looks like a subtree
4649 (org-back-to-heading t)) ; take what is really there
4650 (org-back-over-empty-lines)
4651 (setq beg (point))
4652 (skip-chars-forward " \t\r\n")
4653 (save-match-data
4654 (save-excursion (outline-end-of-heading)
4655 (setq folded (org-invisible-p)))
4656 (condition-case nil
4657 (outline-forward-same-level (1- n))
4658 (error nil))
4659 (org-end-of-subtree t t))
4660 (org-back-over-empty-lines)
4661 (setq end (point))
4662 (goto-char beg0)
4663 (when (> end beg)
4664 (setq org-subtree-clip-folded folded)
4665 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4666 (setq org-subtree-clip (current-kill 0))
4667 (message "%s: Subtree(s) with %d characters"
4668 (if cut "Cut" "Copied")
4669 (length org-subtree-clip)))))
4671 (defun org-paste-subtree (&optional level tree)
4672 "Paste the clipboard as a subtree, with modification of headline level.
4673 The entire subtree is promoted or demoted in order to match a new headline
4674 level. By default, the new level is derived from the visible headings
4675 before and after the insertion point, and taken to be the inferior headline
4676 level of the two. So if the previous visible heading is level 3 and the
4677 next is level 4 (or vice versa), level 4 will be used for insertion.
4678 This makes sure that the subtree remains an independent subtree and does
4679 not swallow low level entries.
4681 You can also force a different level, either by using a numeric prefix
4682 argument, or by inserting the heading marker by hand. For example, if the
4683 cursor is after \"*****\", then the tree will be shifted to level 5.
4685 If you want to insert the tree as is, just use \\[yank].
4687 If optional TREE is given, use this text instead of the kill ring."
4688 (interactive "P")
4689 (unless (org-kill-is-subtree-p tree)
4690 (error "%s"
4691 (substitute-command-keys
4692 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4693 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4694 (^re (concat "^\\(" outline-regexp "\\)"))
4695 (re (concat "\\(" outline-regexp "\\)"))
4696 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4698 (old-level (if (string-match ^re txt)
4699 (- (match-end 0) (match-beginning 0) 1)
4700 -1))
4701 (force-level (cond (level (prefix-numeric-value level))
4702 ((string-match
4703 ^re_ (buffer-substring (point-at-bol) (point)))
4704 (- (match-end 1) (match-beginning 1)))
4705 (t nil)))
4706 (previous-level (save-excursion
4707 (condition-case nil
4708 (progn
4709 (outline-previous-visible-heading 1)
4710 (if (looking-at re)
4711 (- (match-end 0) (match-beginning 0) 1)
4713 (error 1))))
4714 (next-level (save-excursion
4715 (condition-case nil
4716 (progn
4717 (or (looking-at outline-regexp)
4718 (outline-next-visible-heading 1))
4719 (if (looking-at re)
4720 (- (match-end 0) (match-beginning 0) 1)
4722 (error 1))))
4723 (new-level (or force-level (max previous-level next-level)))
4724 (shift (if (or (= old-level -1)
4725 (= new-level -1)
4726 (= old-level new-level))
4728 (- new-level old-level)))
4729 (delta (if (> shift 0) -1 1))
4730 (func (if (> shift 0) 'org-demote 'org-promote))
4731 (org-odd-levels-only nil)
4732 beg end)
4733 ;; Remove the forced level indicator
4734 (if force-level
4735 (delete-region (point-at-bol) (point)))
4736 ;; Paste
4737 (beginning-of-line 1)
4738 (org-back-over-empty-lines)
4739 (setq beg (point))
4740 (insert-before-markers txt)
4741 (unless (string-match "\n\\'" txt) (insert "\n"))
4742 (setq end (point))
4743 (goto-char beg)
4744 (skip-chars-forward " \t\n\r")
4745 (setq beg (point))
4746 ;; Shift if necessary
4747 (unless (= shift 0)
4748 (save-restriction
4749 (narrow-to-region beg end)
4750 (while (not (= shift 0))
4751 (org-map-region func (point-min) (point-max))
4752 (setq shift (+ delta shift)))
4753 (goto-char (point-min))))
4754 (when (interactive-p)
4755 (message "Clipboard pasted as level %d subtree" new-level))
4756 (if (and kill-ring
4757 (eq org-subtree-clip (current-kill 0))
4758 org-subtree-clip-folded)
4759 ;; The tree was folded before it was killed/copied
4760 (hide-subtree))))
4762 (defun org-kill-is-subtree-p (&optional txt)
4763 "Check if the current kill is an outline subtree, or a set of trees.
4764 Returns nil if kill does not start with a headline, or if the first
4765 headline level is not the largest headline level in the tree.
4766 So this will actually accept several entries of equal levels as well,
4767 which is OK for `org-paste-subtree'.
4768 If optional TXT is given, check this string instead of the current kill."
4769 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4770 (start-level (and kill
4771 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4772 org-outline-regexp "\\)")
4773 kill)
4774 (- (match-end 2) (match-beginning 2) 1)))
4775 (re (concat "^" org-outline-regexp))
4776 (start (1+ (match-beginning 2))))
4777 (if (not start-level)
4778 (progn
4779 nil) ;; does not even start with a heading
4780 (catch 'exit
4781 (while (setq start (string-match re kill (1+ start)))
4782 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4783 (throw 'exit nil)))
4784 t))))
4786 (defun org-narrow-to-subtree ()
4787 "Narrow buffer to the current subtree."
4788 (interactive)
4789 (save-excursion
4790 (save-match-data
4791 (narrow-to-region
4792 (progn (org-back-to-heading) (point))
4793 (progn (org-end-of-subtree t t) (point))))))
4796 ;;; Outline Sorting
4798 (defun org-sort (with-case)
4799 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4800 Optional argument WITH-CASE means sort case-sensitively."
4801 (interactive "P")
4802 (if (org-at-table-p)
4803 (org-call-with-arg 'org-table-sort-lines with-case)
4804 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4806 (defun org-sort-remove-invisible (s)
4807 (remove-text-properties 0 (length s) org-rm-props s)
4808 (while (string-match org-bracket-link-regexp s)
4809 (setq s (replace-match (if (match-end 2)
4810 (match-string 3 s)
4811 (match-string 1 s)) t t s)))
4814 (defvar org-priority-regexp) ; defined later in the file
4816 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4817 "Sort entries on a certain level of an outline tree.
4818 If there is an active region, the entries in the region are sorted.
4819 Else, if the cursor is before the first entry, sort the top-level items.
4820 Else, the children of the entry at point are sorted.
4822 Sorting can be alphabetically, numerically, and by date/time as given by
4823 the first time stamp in the entry. The command prompts for the sorting
4824 type unless it has been given to the function through the SORTING-TYPE
4825 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4826 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4827 called with point at the beginning of the record. It must return either
4828 a string or a number that should serve as the sorting key for that record.
4830 Comparing entries ignores case by default. However, with an optional argument
4831 WITH-CASE, the sorting considers case as well."
4832 (interactive "P")
4833 (let ((case-func (if with-case 'identity 'downcase))
4834 start beg end stars re re2
4835 txt what tmp plain-list-p)
4836 ;; Find beginning and end of region to sort
4837 (cond
4838 ((org-region-active-p)
4839 ;; we will sort the region
4840 (setq end (region-end)
4841 what "region")
4842 (goto-char (region-beginning))
4843 (if (not (org-on-heading-p)) (outline-next-heading))
4844 (setq start (point)))
4845 ((org-at-item-p)
4846 ;; we will sort this plain list
4847 (org-beginning-of-item-list) (setq start (point))
4848 (org-end-of-item-list) (setq end (point))
4849 (goto-char start)
4850 (setq plain-list-p t
4851 what "plain list"))
4852 ((or (org-on-heading-p)
4853 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4854 ;; we will sort the children of the current headline
4855 (org-back-to-heading)
4856 (setq start (point)
4857 end (progn (org-end-of-subtree t t)
4858 (org-back-over-empty-lines)
4859 (point))
4860 what "children")
4861 (goto-char start)
4862 (show-subtree)
4863 (outline-next-heading))
4865 ;; we will sort the top-level entries in this file
4866 (goto-char (point-min))
4867 (or (org-on-heading-p) (outline-next-heading))
4868 (setq start (point) end (point-max) what "top-level")
4869 (goto-char start)
4870 (show-all)))
4872 (setq beg (point))
4873 (if (>= beg end) (error "Nothing to sort"))
4875 (unless plain-list-p
4876 (looking-at "\\(\\*+\\)")
4877 (setq stars (match-string 1)
4878 re (concat "^" (regexp-quote stars) " +")
4879 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4880 txt (buffer-substring beg end))
4881 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4882 (if (and (not (equal stars "*")) (string-match re2 txt))
4883 (error "Region to sort contains a level above the first entry")))
4885 (unless sorting-type
4886 (message
4887 (if plain-list-p
4888 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4889 "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:")
4890 what)
4891 (setq sorting-type (read-char-exclusive))
4893 (and (= (downcase sorting-type) ?f)
4894 (setq getkey-func
4895 (completing-read "Sort using function: "
4896 obarray 'fboundp t nil nil))
4897 (setq getkey-func (intern getkey-func)))
4899 (and (= (downcase sorting-type) ?r)
4900 (setq property
4901 (completing-read "Property: "
4902 (mapcar 'list (org-buffer-property-keys t))
4903 nil t))))
4905 (message "Sorting entries...")
4907 (save-restriction
4908 (narrow-to-region start end)
4910 (let ((dcst (downcase sorting-type))
4911 (now (current-time)))
4912 (sort-subr
4913 (/= dcst sorting-type)
4914 ;; This function moves to the beginning character of the "record" to
4915 ;; be sorted.
4916 (if plain-list-p
4917 (lambda nil
4918 (if (org-at-item-p) t (goto-char (point-max))))
4919 (lambda nil
4920 (if (re-search-forward re nil t)
4921 (goto-char (match-beginning 0))
4922 (goto-char (point-max)))))
4923 ;; This function moves to the last character of the "record" being
4924 ;; sorted.
4925 (if plain-list-p
4926 'org-end-of-item
4927 (lambda nil
4928 (save-match-data
4929 (condition-case nil
4930 (outline-forward-same-level 1)
4931 (error
4932 (goto-char (point-max)))))))
4934 ;; This function returns the value that gets sorted against.
4935 (if plain-list-p
4936 (lambda nil
4937 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
4938 (cond
4939 ((= dcst ?n)
4940 (string-to-number (buffer-substring (match-end 0)
4941 (point-at-eol))))
4942 ((= dcst ?a)
4943 (buffer-substring (match-end 0) (point-at-eol)))
4944 ((= dcst ?t)
4945 (if (re-search-forward org-ts-regexp
4946 (point-at-eol) t)
4947 (org-time-string-to-time (match-string 0))
4948 now))
4949 ((= dcst ?f)
4950 (if getkey-func
4951 (progn
4952 (setq tmp (funcall getkey-func))
4953 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4954 tmp)
4955 (error "Invalid key function `%s'" getkey-func)))
4956 (t (error "Invalid sorting type `%c'" sorting-type)))))
4957 (lambda nil
4958 (cond
4959 ((= dcst ?n)
4960 (if (looking-at outline-regexp)
4961 (string-to-number (buffer-substring (match-end 0)
4962 (point-at-eol)))
4963 nil))
4964 ((= dcst ?a)
4965 (funcall case-func (buffer-substring (point-at-bol)
4966 (point-at-eol))))
4967 ((= dcst ?t)
4968 (if (re-search-forward org-ts-regexp
4969 (save-excursion
4970 (forward-line 2)
4971 (point)) t)
4972 (org-time-string-to-time (match-string 0))
4973 now))
4974 ((= dcst ?p)
4975 (if (re-search-forward org-priority-regexp (point-at-eol) t)
4976 (string-to-char (match-string 2))
4977 org-default-priority))
4978 ((= dcst ?r)
4979 (or (org-entry-get nil property) ""))
4980 ((= dcst ?o)
4981 (if (looking-at org-complex-heading-regexp)
4982 (- 9999 (length (member (match-string 2)
4983 org-todo-keywords-1)))))
4984 ((= dcst ?f)
4985 (if getkey-func
4986 (progn
4987 (setq tmp (funcall getkey-func))
4988 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4989 tmp)
4990 (error "Invalid key function `%s'" getkey-func)))
4991 (t (error "Invalid sorting type `%c'" sorting-type)))))
4993 (cond
4994 ((= dcst ?a) 'string<)
4995 ((= dcst ?t) 'time-less-p)
4996 (t nil)))))
4997 (message "Sorting entries...done")))
4999 (defun org-do-sort (table what &optional with-case sorting-type)
5000 "Sort TABLE of WHAT according to SORTING-TYPE.
5001 The user will be prompted for the SORTING-TYPE if the call to this
5002 function does not specify it. WHAT is only for the prompt, to indicate
5003 what is being sorted. The sorting key will be extracted from
5004 the car of the elements of the table.
5005 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5006 (unless sorting-type
5007 (message
5008 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5009 what)
5010 (setq sorting-type (read-char-exclusive)))
5011 (let ((dcst (downcase sorting-type))
5012 extractfun comparefun)
5013 ;; Define the appropriate functions
5014 (cond
5015 ((= dcst ?n)
5016 (setq extractfun 'string-to-number
5017 comparefun (if (= dcst sorting-type) '< '>)))
5018 ((= dcst ?a)
5019 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5020 (lambda(x) (downcase (org-sort-remove-invisible x))))
5021 comparefun (if (= dcst sorting-type)
5022 'string<
5023 (lambda (a b) (and (not (string< a b))
5024 (not (string= a b)))))))
5025 ((= dcst ?t)
5026 (setq extractfun
5027 (lambda (x)
5028 (if (string-match org-ts-regexp x)
5029 (time-to-seconds
5030 (org-time-string-to-time (match-string 0 x)))
5032 comparefun (if (= dcst sorting-type) '< '>)))
5033 (t (error "Invalid sorting type `%c'" sorting-type)))
5035 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5036 table)
5037 (lambda (a b) (funcall comparefun (car a) (car b))))))
5039 ;;;; Plain list items, including checkboxes
5041 ;;; Plain list items
5043 (defun org-at-item-p ()
5044 "Is point in a line starting a hand-formatted item?"
5045 (let ((llt org-plain-list-ordered-item-terminator))
5046 (save-excursion
5047 (goto-char (point-at-bol))
5048 (looking-at
5049 (cond
5050 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5051 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5052 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5053 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5055 (defun org-in-item-p ()
5056 "It the cursor inside a plain list item.
5057 Does not have to be the first line."
5058 (save-excursion
5059 (condition-case nil
5060 (progn
5061 (org-beginning-of-item)
5062 (org-at-item-p)
5064 (error nil))))
5066 (defun org-insert-item (&optional checkbox)
5067 "Insert a new item at the current level.
5068 Return t when things worked, nil when we are not in an item."
5069 (when (save-excursion
5070 (condition-case nil
5071 (progn
5072 (org-beginning-of-item)
5073 (org-at-item-p)
5074 (if (org-invisible-p) (error "Invisible item"))
5076 (error nil)))
5077 (let* ((bul (match-string 0))
5078 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5079 (match-end 0)))
5080 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5081 pos)
5082 (cond
5083 ((and (org-at-item-p) (<= (point) eow))
5084 ;; before the bullet
5085 (beginning-of-line 1)
5086 (open-line (if blank 2 1)))
5087 ((<= (point) eow)
5088 (beginning-of-line 1))
5090 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5091 (end-of-line 1)
5092 (delete-horizontal-space))
5093 (newline (if blank 2 1))))
5094 (insert bul (if checkbox "[ ]" ""))
5095 (just-one-space)
5096 (setq pos (point))
5097 (end-of-line 1)
5098 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5099 (org-maybe-renumber-ordered-list)
5100 (and checkbox (org-update-checkbox-count-maybe))
5103 ;;; Checkboxes
5105 (defun org-at-item-checkbox-p ()
5106 "Is point at a line starting a plain-list item with a checklet?"
5107 (and (org-at-item-p)
5108 (save-excursion
5109 (goto-char (match-end 0))
5110 (skip-chars-forward " \t")
5111 (looking-at "\\[[- X]\\]"))))
5113 (defun org-toggle-checkbox (&optional arg)
5114 "Toggle the checkbox in the current line."
5115 (interactive "P")
5116 (catch 'exit
5117 (let (beg end status (firstnew 'unknown))
5118 (cond
5119 ((org-region-active-p)
5120 (setq beg (region-beginning) end (region-end)))
5121 ((org-on-heading-p)
5122 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5123 ((org-at-item-checkbox-p)
5124 (let ((pos (point)))
5125 (replace-match
5126 (cond (arg "[-]")
5127 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5128 (t "[ ]"))
5129 t t)
5130 (goto-char pos))
5131 (throw 'exit t))
5132 (t (error "Not at a checkbox or heading, and no active region")))
5133 (save-excursion
5134 (goto-char beg)
5135 (while (< (point) end)
5136 (when (org-at-item-checkbox-p)
5137 (setq status (equal (match-string 0) "[X]"))
5138 (when (eq firstnew 'unknown)
5139 (setq firstnew (not status)))
5140 (replace-match
5141 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5142 (beginning-of-line 2)))))
5143 (org-update-checkbox-count-maybe))
5145 (defun org-update-checkbox-count-maybe ()
5146 "Update checkbox statistics unless turned off by user."
5147 (when org-provide-checkbox-statistics
5148 (org-update-checkbox-count)))
5150 (defun org-update-checkbox-count (&optional all)
5151 "Update the checkbox statistics in the current section.
5152 This will find all statistic cookies like [57%] and [6/12] and update them
5153 with the current numbers. With optional prefix argument ALL, do this for
5154 the whole buffer."
5155 (interactive "P")
5156 (save-excursion
5157 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5158 (beg (condition-case nil
5159 (progn (outline-back-to-heading) (point))
5160 (error (point-min))))
5161 (end (move-marker (make-marker)
5162 (progn (outline-next-heading) (point))))
5163 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5164 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5165 (re-find (concat re "\\|" re-box))
5166 beg-cookie end-cookie is-percent c-on c-off lim
5167 eline curr-ind next-ind continue-from startsearch
5168 (cstat 0)
5170 (when all
5171 (goto-char (point-min))
5172 (outline-next-heading)
5173 (setq beg (point) end (point-max)))
5174 (goto-char end)
5175 ;; find each statistic cookie
5176 (while (re-search-backward re-find beg t)
5177 (setq beg-cookie (match-beginning 1)
5178 end-cookie (match-end 1)
5179 cstat (+ cstat (if end-cookie 1 0))
5180 startsearch (point-at-eol)
5181 continue-from (point-at-bol)
5182 is-percent (match-beginning 2)
5183 lim (cond
5184 ((org-on-heading-p) (outline-next-heading) (point))
5185 ((org-at-item-p) (org-end-of-item) (point))
5186 (t nil))
5187 c-on 0
5188 c-off 0)
5189 (when lim
5190 ;; find first checkbox for this cookie and gather
5191 ;; statistics from all that are at this indentation level
5192 (goto-char startsearch)
5193 (if (re-search-forward re-box lim t)
5194 (progn
5195 (org-beginning-of-item)
5196 (setq curr-ind (org-get-indentation))
5197 (setq next-ind curr-ind)
5198 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5199 (save-excursion (end-of-line) (setq eline (point)))
5200 (if (re-search-forward re-box eline t)
5201 (if (member (match-string 2) '("[ ]" "[-]"))
5202 (setq c-off (1+ c-off))
5203 (setq c-on (1+ c-on))
5206 (org-end-of-item)
5207 (setq next-ind (org-get-indentation))
5209 (goto-char continue-from)
5210 ;; update cookie
5211 (when end-cookie
5212 (delete-region beg-cookie end-cookie)
5213 (goto-char beg-cookie)
5214 (insert
5215 (if is-percent
5216 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5217 (format "[%d/%d]" c-on (+ c-on c-off)))))
5218 ;; update items checkbox if it has one
5219 (when (org-at-item-p)
5220 (org-beginning-of-item)
5221 (when (and (> (+ c-on c-off) 0)
5222 (re-search-forward re-box (point-at-eol) t))
5223 (setq beg-cookie (match-beginning 2)
5224 end-cookie (match-end 2))
5225 (delete-region beg-cookie end-cookie)
5226 (goto-char beg-cookie)
5227 (cond ((= c-off 0) (insert "[X]"))
5228 ((= c-on 0) (insert "[ ]"))
5229 (t (insert "[-]")))
5231 (goto-char continue-from))
5232 (when (interactive-p)
5233 (message "Checkbox satistics updated %s (%d places)"
5234 (if all "in entire file" "in current outline entry") cstat)))))
5236 (defun org-get-checkbox-statistics-face ()
5237 "Select the face for checkbox statistics.
5238 The face will be `org-done' when all relevant boxes are checked. Otherwise
5239 it will be `org-todo'."
5240 (if (match-end 1)
5241 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5242 (if (and (> (match-end 2) (match-beginning 2))
5243 (equal (match-string 2) (match-string 3)))
5244 'org-done
5245 'org-todo)))
5247 (defun org-get-indentation (&optional line)
5248 "Get the indentation of the current line, interpreting tabs.
5249 When LINE is given, assume it represents a line and compute its indentation."
5250 (if line
5251 (if (string-match "^ *" (org-remove-tabs line))
5252 (match-end 0))
5253 (save-excursion
5254 (beginning-of-line 1)
5255 (skip-chars-forward " \t")
5256 (current-column))))
5258 (defun org-remove-tabs (s &optional width)
5259 "Replace tabulators in S with spaces.
5260 Assumes that s is a single line, starting in column 0."
5261 (setq width (or width tab-width))
5262 (while (string-match "\t" s)
5263 (setq s (replace-match
5264 (make-string
5265 (- (* width (/ (+ (match-beginning 0) width) width))
5266 (match-beginning 0)) ?\ )
5267 t t s)))
5270 (defun org-fix-indentation (line ind)
5271 "Fix indentation in LINE.
5272 IND is a cons cell with target and minimum indentation.
5273 If the current indenation in LINE is smaller than the minimum,
5274 leave it alone. If it is larger than ind, set it to the target."
5275 (let* ((l (org-remove-tabs line))
5276 (i (org-get-indentation l))
5277 (i1 (car ind)) (i2 (cdr ind)))
5278 (if (>= i i2) (setq l (substring line i2)))
5279 (if (> i1 0)
5280 (concat (make-string i1 ?\ ) l)
5281 l)))
5283 (defun org-beginning-of-item ()
5284 "Go to the beginning of the current hand-formatted item.
5285 If the cursor is not in an item, throw an error."
5286 (interactive)
5287 (let ((pos (point))
5288 (limit (save-excursion
5289 (condition-case nil
5290 (progn
5291 (org-back-to-heading)
5292 (beginning-of-line 2) (point))
5293 (error (point-min)))))
5294 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5295 ind ind1)
5296 (if (org-at-item-p)
5297 (beginning-of-line 1)
5298 (beginning-of-line 1)
5299 (skip-chars-forward " \t")
5300 (setq ind (current-column))
5301 (if (catch 'exit
5302 (while t
5303 (beginning-of-line 0)
5304 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5306 (if (looking-at "[ \t]*$")
5307 (setq ind1 ind-empty)
5308 (skip-chars-forward " \t")
5309 (setq ind1 (current-column)))
5310 (if (< ind1 ind)
5311 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5313 (goto-char pos)
5314 (error "Not in an item")))))
5316 (defun org-end-of-item ()
5317 "Go to the end of the current hand-formatted item.
5318 If the cursor is not in an item, throw an error."
5319 (interactive)
5320 (let* ((pos (point))
5321 ind1
5322 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5323 (limit (save-excursion (outline-next-heading) (point)))
5324 (ind (save-excursion
5325 (org-beginning-of-item)
5326 (skip-chars-forward " \t")
5327 (current-column)))
5328 (end (catch 'exit
5329 (while t
5330 (beginning-of-line 2)
5331 (if (eobp) (throw 'exit (point)))
5332 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5333 (if (looking-at "[ \t]*$")
5334 (setq ind1 ind-empty)
5335 (skip-chars-forward " \t")
5336 (setq ind1 (current-column)))
5337 (if (<= ind1 ind)
5338 (throw 'exit (point-at-bol)))))))
5339 (if end
5340 (goto-char end)
5341 (goto-char pos)
5342 (error "Not in an item"))))
5344 (defun org-next-item ()
5345 "Move to the beginning of the next item in the current plain list.
5346 Error if not at a plain list, or if this is the last item in the list."
5347 (interactive)
5348 (let (ind ind1 (pos (point)))
5349 (org-beginning-of-item)
5350 (setq ind (org-get-indentation))
5351 (org-end-of-item)
5352 (setq ind1 (org-get-indentation))
5353 (unless (and (org-at-item-p) (= ind ind1))
5354 (goto-char pos)
5355 (error "On last item"))))
5357 (defun org-previous-item ()
5358 "Move to the beginning of the previous item in the current plain list.
5359 Error if not at a plain list, or if this is the first item in the list."
5360 (interactive)
5361 (let (beg ind ind1 (pos (point)))
5362 (org-beginning-of-item)
5363 (setq beg (point))
5364 (setq ind (org-get-indentation))
5365 (goto-char beg)
5366 (catch 'exit
5367 (while t
5368 (beginning-of-line 0)
5369 (if (looking-at "[ \t]*$")
5371 (if (<= (setq ind1 (org-get-indentation)) ind)
5372 (throw 'exit t)))))
5373 (condition-case nil
5374 (if (or (not (org-at-item-p))
5375 (< ind1 (1- ind)))
5376 (error "")
5377 (org-beginning-of-item))
5378 (error (goto-char pos)
5379 (error "On first item")))))
5381 (defun org-first-list-item-p ()
5382 "Is this heading the item in a plain list?"
5383 (unless (org-at-item-p)
5384 (error "Not at a plain list item"))
5385 (org-beginning-of-item)
5386 (= (point) (save-excursion (org-beginning-of-item-list))))
5388 (defun org-move-item-down ()
5389 "Move the plain list item at point down, i.e. swap with following item.
5390 Subitems (items with larger indentation) are considered part of the item,
5391 so this really moves item trees."
5392 (interactive)
5393 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5394 (org-beginning-of-item)
5395 (setq beg0 (point))
5396 (save-excursion
5397 (setq ne-beg (org-back-over-empty-lines))
5398 (setq beg (point)))
5399 (goto-char beg0)
5400 (setq ind (org-get-indentation))
5401 (org-end-of-item)
5402 (setq end0 (point))
5403 (setq ind1 (org-get-indentation))
5404 (setq ne-end (org-back-over-empty-lines))
5405 (setq end (point))
5406 (goto-char beg0)
5407 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5408 ;; include less whitespace
5409 (save-excursion
5410 (goto-char beg)
5411 (forward-line (- ne-beg ne-end))
5412 (setq beg (point))))
5413 (goto-char end0)
5414 (if (and (org-at-item-p) (= ind ind1))
5415 (progn
5416 (org-end-of-item)
5417 (org-back-over-empty-lines)
5418 (setq txt (buffer-substring beg end))
5419 (save-excursion
5420 (delete-region beg end))
5421 (setq pos (point))
5422 (insert txt)
5423 (goto-char pos) (org-skip-whitespace)
5424 (org-maybe-renumber-ordered-list))
5425 (goto-char pos)
5426 (error "Cannot move this item further down"))))
5428 (defun org-move-item-up (arg)
5429 "Move the plain list item at point up, i.e. swap with previous item.
5430 Subitems (items with larger indentation) are considered part of the item,
5431 so this really moves item trees."
5432 (interactive "p")
5433 (let (beg beg0 end ind ind1 (pos (point)) txt
5434 ne-beg ne-ins ins-end)
5435 (org-beginning-of-item)
5436 (setq beg0 (point))
5437 (setq ind (org-get-indentation))
5438 (save-excursion
5439 (setq ne-beg (org-back-over-empty-lines))
5440 (setq beg (point)))
5441 (goto-char beg0)
5442 (org-end-of-item)
5443 (setq end (point))
5444 (goto-char beg0)
5445 (catch 'exit
5446 (while t
5447 (beginning-of-line 0)
5448 (if (looking-at "[ \t]*$")
5449 (if org-empty-line-terminates-plain-lists
5450 (progn
5451 (goto-char pos)
5452 (error "Cannot move this item further up"))
5453 nil)
5454 (if (<= (setq ind1 (org-get-indentation)) ind)
5455 (throw 'exit t)))))
5456 (condition-case nil
5457 (org-beginning-of-item)
5458 (error (goto-char beg)
5459 (error "Cannot move this item further up")))
5460 (setq ind1 (org-get-indentation))
5461 (if (and (org-at-item-p) (= ind ind1))
5462 (progn
5463 (setq ne-ins (org-back-over-empty-lines))
5464 (setq txt (buffer-substring beg end))
5465 (save-excursion
5466 (delete-region beg end))
5467 (setq pos (point))
5468 (insert txt)
5469 (setq ins-end (point))
5470 (goto-char pos) (org-skip-whitespace)
5472 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5473 ;; Move whitespace back to beginning
5474 (save-excursion
5475 (goto-char ins-end)
5476 (let ((kill-whole-line t))
5477 (kill-line (- ne-ins ne-beg)) (point)))
5478 (insert (make-string (- ne-ins ne-beg) ?\n)))
5480 (org-maybe-renumber-ordered-list))
5481 (goto-char pos)
5482 (error "Cannot move this item further up"))))
5484 (defun org-maybe-renumber-ordered-list ()
5485 "Renumber the ordered list at point if setup allows it.
5486 This tests the user option `org-auto-renumber-ordered-lists' before
5487 doing the renumbering."
5488 (interactive)
5489 (when (and org-auto-renumber-ordered-lists
5490 (org-at-item-p))
5491 (if (match-beginning 3)
5492 (org-renumber-ordered-list 1)
5493 (org-fix-bullet-type))))
5495 (defun org-maybe-renumber-ordered-list-safe ()
5496 (condition-case nil
5497 (save-excursion
5498 (org-maybe-renumber-ordered-list))
5499 (error nil)))
5501 (defun org-cycle-list-bullet (&optional which)
5502 "Cycle through the different itemize/enumerate bullets.
5503 This cycle the entire list level through the sequence:
5505 `-' -> `+' -> `*' -> `1.' -> `1)'
5507 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5508 0 meand `-', 1 means `+' etc."
5509 (interactive "P")
5510 (org-preserve-lc
5511 (org-beginning-of-item-list)
5512 (org-at-item-p)
5513 (beginning-of-line 1)
5514 (let ((current (match-string 0))
5515 (prevp (eq which 'previous))
5516 new)
5517 (setq new (cond
5518 ((and (numberp which)
5519 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5520 ((string-match "-" current) (if prevp "1)" "+"))
5521 ((string-match "\\+" current)
5522 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5523 ((string-match "\\*" current) (if prevp "+" "1."))
5524 ((string-match "\\." current) (if prevp "*" "1)"))
5525 ((string-match ")" current) (if prevp "1." "-"))
5526 (t (error "This should not happen"))))
5527 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5528 (org-fix-bullet-type)
5529 (org-maybe-renumber-ordered-list))))
5531 (defun org-get-string-indentation (s)
5532 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5533 (let ((n -1) (i 0) (w tab-width) c)
5534 (catch 'exit
5535 (while (< (setq n (1+ n)) (length s))
5536 (setq c (aref s n))
5537 (cond ((= c ?\ ) (setq i (1+ i)))
5538 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5539 (t (throw 'exit t)))))
5542 (defun org-renumber-ordered-list (arg)
5543 "Renumber an ordered plain list.
5544 Cursor needs to be in the first line of an item, the line that starts
5545 with something like \"1.\" or \"2)\"."
5546 (interactive "p")
5547 (unless (and (org-at-item-p)
5548 (match-beginning 3))
5549 (error "This is not an ordered list"))
5550 (let ((line (org-current-line))
5551 (col (current-column))
5552 (ind (org-get-string-indentation
5553 (buffer-substring (point-at-bol) (match-beginning 3))))
5554 ;; (term (substring (match-string 3) -1))
5555 ind1 (n (1- arg))
5556 fmt)
5557 ;; find where this list begins
5558 (org-beginning-of-item-list)
5559 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5560 (setq fmt (concat "%d" (match-string 1)))
5561 (beginning-of-line 0)
5562 ;; walk forward and replace these numbers
5563 (catch 'exit
5564 (while t
5565 (catch 'next
5566 (beginning-of-line 2)
5567 (if (eobp) (throw 'exit nil))
5568 (if (looking-at "[ \t]*$") (throw 'next nil))
5569 (skip-chars-forward " \t") (setq ind1 (current-column))
5570 (if (> ind1 ind) (throw 'next t))
5571 (if (< ind1 ind) (throw 'exit t))
5572 (if (not (org-at-item-p)) (throw 'exit nil))
5573 (delete-region (match-beginning 2) (match-end 2))
5574 (goto-char (match-beginning 2))
5575 (insert (format fmt (setq n (1+ n)))))))
5576 (goto-line line)
5577 (move-to-column col)))
5579 (defun org-fix-bullet-type ()
5580 "Make sure all items in this list have the same bullet as the firsst item."
5581 (interactive)
5582 (unless (org-at-item-p) (error "This is not a list"))
5583 (let ((line (org-current-line))
5584 (col (current-column))
5585 (ind (current-indentation))
5586 ind1 bullet)
5587 ;; find where this list begins
5588 (org-beginning-of-item-list)
5589 (beginning-of-line 1)
5590 ;; find out what the bullet type is
5591 (looking-at "[ \t]*\\(\\S-+\\)")
5592 (setq bullet (match-string 1))
5593 ;; walk forward and replace these numbers
5594 (beginning-of-line 0)
5595 (catch 'exit
5596 (while t
5597 (catch 'next
5598 (beginning-of-line 2)
5599 (if (eobp) (throw 'exit nil))
5600 (if (looking-at "[ \t]*$") (throw 'next nil))
5601 (skip-chars-forward " \t") (setq ind1 (current-column))
5602 (if (> ind1 ind) (throw 'next t))
5603 (if (< ind1 ind) (throw 'exit t))
5604 (if (not (org-at-item-p)) (throw 'exit nil))
5605 (skip-chars-forward " \t")
5606 (looking-at "\\S-+")
5607 (replace-match bullet))))
5608 (goto-line line)
5609 (move-to-column col)
5610 (if (string-match "[0-9]" bullet)
5611 (org-renumber-ordered-list 1))))
5613 (defun org-beginning-of-item-list ()
5614 "Go to the beginning of the current item list.
5615 I.e. to the first item in this list."
5616 (interactive)
5617 (org-beginning-of-item)
5618 (let ((pos (point-at-bol))
5619 (ind (org-get-indentation))
5620 ind1)
5621 ;; find where this list begins
5622 (catch 'exit
5623 (while t
5624 (catch 'next
5625 (beginning-of-line 0)
5626 (if (looking-at "[ \t]*$")
5627 (throw (if (bobp) 'exit 'next) t))
5628 (skip-chars-forward " \t") (setq ind1 (current-column))
5629 (if (or (< ind1 ind)
5630 (and (= ind1 ind)
5631 (not (org-at-item-p)))
5632 (bobp))
5633 (throw 'exit t)
5634 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5635 (goto-char pos)))
5638 (defun org-end-of-item-list ()
5639 "Go to the end of the current item list.
5640 I.e. to the text after the last item."
5641 (interactive)
5642 (org-beginning-of-item)
5643 (let ((pos (point-at-bol))
5644 (ind (org-get-indentation))
5645 ind1)
5646 ;; find where this list begins
5647 (catch 'exit
5648 (while t
5649 (catch 'next
5650 (beginning-of-line 2)
5651 (if (looking-at "[ \t]*$")
5652 (throw (if (eobp) 'exit 'next) t))
5653 (skip-chars-forward " \t") (setq ind1 (current-column))
5654 (if (or (< ind1 ind)
5655 (and (= ind1 ind)
5656 (not (org-at-item-p)))
5657 (eobp))
5658 (progn
5659 (setq pos (point-at-bol))
5660 (throw 'exit t))))))
5661 (goto-char pos)))
5664 (defvar org-last-indent-begin-marker (make-marker))
5665 (defvar org-last-indent-end-marker (make-marker))
5667 (defun org-outdent-item (arg)
5668 "Outdent a local list item."
5669 (interactive "p")
5670 (org-indent-item (- arg)))
5672 (defun org-indent-item (arg)
5673 "Indent a local list item."
5674 (interactive "p")
5675 (unless (org-at-item-p)
5676 (error "Not on an item"))
5677 (save-excursion
5678 (let (beg end ind ind1 tmp delta ind-down ind-up)
5679 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5680 (setq beg org-last-indent-begin-marker
5681 end org-last-indent-end-marker)
5682 (org-beginning-of-item)
5683 (setq beg (move-marker org-last-indent-begin-marker (point)))
5684 (org-end-of-item)
5685 (setq end (move-marker org-last-indent-end-marker (point))))
5686 (goto-char beg)
5687 (setq tmp (org-item-indent-positions)
5688 ind (car tmp)
5689 ind-down (nth 2 tmp)
5690 ind-up (nth 1 tmp)
5691 delta (if (> arg 0)
5692 (if ind-down (- ind-down ind) 2)
5693 (if ind-up (- ind-up ind) -2)))
5694 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5695 (while (< (point) end)
5696 (beginning-of-line 1)
5697 (skip-chars-forward " \t") (setq ind1 (current-column))
5698 (delete-region (point-at-bol) (point))
5699 (or (eolp) (indent-to-column (+ ind1 delta)))
5700 (beginning-of-line 2))))
5701 (org-fix-bullet-type)
5702 (org-maybe-renumber-ordered-list-safe)
5703 (save-excursion
5704 (beginning-of-line 0)
5705 (condition-case nil (org-beginning-of-item) (error nil))
5706 (org-maybe-renumber-ordered-list-safe)))
5708 (defun org-item-indent-positions ()
5709 "Return indentation for plain list items.
5710 This returns a list with three values: The current indentation, the
5711 parent indentation and the indentation a child should habe.
5712 Assumes cursor in item line."
5713 (let* ((bolpos (point-at-bol))
5714 (ind (org-get-indentation))
5715 ind-down ind-up pos)
5716 (save-excursion
5717 (org-beginning-of-item-list)
5718 (skip-chars-backward "\n\r \t")
5719 (when (org-in-item-p)
5720 (org-beginning-of-item)
5721 (setq ind-up (org-get-indentation))))
5722 (setq pos (point))
5723 (save-excursion
5724 (cond
5725 ((and (condition-case nil (progn (org-previous-item) t)
5726 (error nil))
5727 (or (forward-char 1) t)
5728 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5729 (setq ind-down (org-get-indentation)))
5730 ((and (goto-char pos)
5731 (org-at-item-p))
5732 (goto-char (match-end 0))
5733 (skip-chars-forward " \t")
5734 (setq ind-down (current-column)))))
5735 (list ind ind-up ind-down)))
5737 ;;; The orgstruct minor mode
5739 ;; Define a minor mode which can be used in other modes in order to
5740 ;; integrate the org-mode structure editing commands.
5742 ;; This is really a hack, because the org-mode structure commands use
5743 ;; keys which normally belong to the major mode. Here is how it
5744 ;; works: The minor mode defines all the keys necessary to operate the
5745 ;; structure commands, but wraps the commands into a function which
5746 ;; tests if the cursor is currently at a headline or a plain list
5747 ;; item. If that is the case, the structure command is used,
5748 ;; temporarily setting many Org-mode variables like regular
5749 ;; expressions for filling etc. However, when any of those keys is
5750 ;; used at a different location, function uses `key-binding' to look
5751 ;; up if the key has an associated command in another currently active
5752 ;; keymap (minor modes, major mode, global), and executes that
5753 ;; command. There might be problems if any of the keys is otherwise
5754 ;; used as a prefix key.
5756 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5757 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5758 ;; addresses this by checking explicitly for both bindings.
5760 (defvar orgstruct-mode-map (make-sparse-keymap)
5761 "Keymap for the minor `orgstruct-mode'.")
5763 (defvar org-local-vars nil
5764 "List of local variables, for use by `orgstruct-mode'")
5766 ;;;###autoload
5767 (define-minor-mode orgstruct-mode
5768 "Toggle the minor more `orgstruct-mode'.
5769 This mode is for using Org-mode structure commands in other modes.
5770 The following key behave as if Org-mode was active, if the cursor
5771 is on a headline, or on a plain list item (both in the definition
5772 of Org-mode).
5774 M-up Move entry/item up
5775 M-down Move entry/item down
5776 M-left Promote
5777 M-right Demote
5778 M-S-up Move entry/item up
5779 M-S-down Move entry/item down
5780 M-S-left Promote subtree
5781 M-S-right Demote subtree
5782 M-q Fill paragraph and items like in Org-mode
5783 C-c ^ Sort entries
5784 C-c - Cycle list bullet
5785 TAB Cycle item visibility
5786 M-RET Insert new heading/item
5787 S-M-RET Insert new TODO heading / Chekbox item
5788 C-c C-c Set tags / toggle checkbox"
5789 nil " OrgStruct" nil
5790 (org-load-modules-maybe)
5791 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5793 ;;;###autoload
5794 (defun turn-on-orgstruct ()
5795 "Unconditionally turn on `orgstruct-mode'."
5796 (orgstruct-mode 1))
5798 ;;;###autoload
5799 (defun turn-on-orgstruct++ ()
5800 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5801 In addition to setting orgstruct-mode, this also exports all indentation and
5802 autofilling variables from org-mode into the buffer. Note that turning
5803 off orgstruct-mode will *not* remove these additional settings."
5804 (orgstruct-mode 1)
5805 (let (var val)
5806 (mapc
5807 (lambda (x)
5808 (when (string-match
5809 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5810 (symbol-name (car x)))
5811 (setq var (car x) val (nth 1 x))
5812 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5813 org-local-vars)))
5815 (defun orgstruct-error ()
5816 "Error when there is no default binding for a structure key."
5817 (interactive)
5818 (error "This key has no function outside structure elements"))
5820 (defun orgstruct-setup ()
5821 "Setup orgstruct keymaps."
5822 (let ((nfunc 0)
5823 (bindings
5824 (list
5825 '([(meta up)] org-metaup)
5826 '([(meta down)] org-metadown)
5827 '([(meta left)] org-metaleft)
5828 '([(meta right)] org-metaright)
5829 '([(meta shift up)] org-shiftmetaup)
5830 '([(meta shift down)] org-shiftmetadown)
5831 '([(meta shift left)] org-shiftmetaleft)
5832 '([(meta shift right)] org-shiftmetaright)
5833 '([(shift up)] org-shiftup)
5834 '([(shift down)] org-shiftdown)
5835 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5836 '("\M-q" fill-paragraph)
5837 '("\C-c^" org-sort)
5838 '("\C-c-" org-cycle-list-bullet)))
5839 elt key fun cmd)
5840 (while (setq elt (pop bindings))
5841 (setq nfunc (1+ nfunc))
5842 (setq key (org-key (car elt))
5843 fun (nth 1 elt)
5844 cmd (orgstruct-make-binding fun nfunc key))
5845 (org-defkey orgstruct-mode-map key cmd))
5847 ;; Special treatment needed for TAB and RET
5848 (org-defkey orgstruct-mode-map [(tab)]
5849 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5850 (org-defkey orgstruct-mode-map "\C-i"
5851 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5853 (org-defkey orgstruct-mode-map "\M-\C-m"
5854 (orgstruct-make-binding 'org-insert-heading 105
5855 "\M-\C-m" [(meta return)]))
5856 (org-defkey orgstruct-mode-map [(meta return)]
5857 (orgstruct-make-binding 'org-insert-heading 106
5858 [(meta return)] "\M-\C-m"))
5860 (org-defkey orgstruct-mode-map [(shift meta return)]
5861 (orgstruct-make-binding 'org-insert-todo-heading 107
5862 [(meta return)] "\M-\C-m"))
5864 (unless org-local-vars
5865 (setq org-local-vars (org-get-local-variables)))
5869 (defun orgstruct-make-binding (fun n &rest keys)
5870 "Create a function for binding in the structure minor mode.
5871 FUN is the command to call inside a table. N is used to create a unique
5872 command name. KEYS are keys that should be checked in for a command
5873 to execute outside of tables."
5874 (eval
5875 (list 'defun
5876 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5877 '(arg)
5878 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5879 "Outside of structure, run the binding of `"
5880 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5881 "'.")
5882 '(interactive "p")
5883 (list 'if
5884 '(org-context-p 'headline 'item)
5885 (list 'org-run-like-in-org-mode (list 'quote fun))
5886 (list 'let '(orgstruct-mode)
5887 (list 'call-interactively
5888 (append '(or)
5889 (mapcar (lambda (k)
5890 (list 'key-binding k))
5891 keys)
5892 '('orgstruct-error))))))))
5894 (defun org-context-p (&rest contexts)
5895 "Check if local context is and of CONTEXTS.
5896 Possible values in the list of contexts are `table', `headline', and `item'."
5897 (let ((pos (point)))
5898 (goto-char (point-at-bol))
5899 (prog1 (or (and (memq 'table contexts)
5900 (looking-at "[ \t]*|"))
5901 (and (memq 'headline contexts)
5902 (looking-at "\\*+"))
5903 (and (memq 'item contexts)
5904 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5905 (goto-char pos))))
5907 (defun org-get-local-variables ()
5908 "Return a list of all local variables in an org-mode buffer."
5909 (let (varlist)
5910 (with-current-buffer (get-buffer-create "*Org tmp*")
5911 (erase-buffer)
5912 (org-mode)
5913 (setq varlist (buffer-local-variables)))
5914 (kill-buffer "*Org tmp*")
5915 (delq nil
5916 (mapcar
5917 (lambda (x)
5918 (setq x
5919 (if (symbolp x)
5920 (list x)
5921 (list (car x) (list 'quote (cdr x)))))
5922 (if (string-match
5923 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5924 (symbol-name (car x)))
5925 x nil))
5926 varlist))))
5928 ;;;###autoload
5929 (defun org-run-like-in-org-mode (cmd)
5930 (org-load-modules-maybe)
5931 (unless org-local-vars
5932 (setq org-local-vars (org-get-local-variables)))
5933 (eval (list 'let org-local-vars
5934 (list 'call-interactively (list 'quote cmd)))))
5936 ;;;; Archiving
5938 (defun org-get-category (&optional pos)
5939 "Get the category applying to position POS."
5940 (get-text-property (or pos (point)) 'org-category))
5942 (defun org-refresh-category-properties ()
5943 "Refresh category text properties in the buffer."
5944 (let ((def-cat (cond
5945 ((null org-category)
5946 (if buffer-file-name
5947 (file-name-sans-extension
5948 (file-name-nondirectory buffer-file-name))
5949 "???"))
5950 ((symbolp org-category) (symbol-name org-category))
5951 (t org-category)))
5952 beg end cat pos optionp)
5953 (org-unmodified
5954 (save-excursion
5955 (save-restriction
5956 (widen)
5957 (goto-char (point-min))
5958 (put-text-property (point) (point-max) 'org-category def-cat)
5959 (while (re-search-forward
5960 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5961 (setq pos (match-end 0)
5962 optionp (equal (char-after (match-beginning 0)) ?#)
5963 cat (org-trim (match-string 2)))
5964 (if optionp
5965 (setq beg (point-at-bol) end (point-max))
5966 (org-back-to-heading t)
5967 (setq beg (point) end (org-end-of-subtree t t)))
5968 (put-text-property beg end 'org-category cat)
5969 (goto-char pos)))))))
5972 ;;;; Link Stuff
5974 ;;; Link abbreviations
5976 (defun org-link-expand-abbrev (link)
5977 "Apply replacements as defined in `org-link-abbrev-alist."
5978 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5979 (let* ((key (match-string 1 link))
5980 (as (or (assoc key org-link-abbrev-alist-local)
5981 (assoc key org-link-abbrev-alist)))
5982 (tag (and (match-end 2) (match-string 3 link)))
5983 rpl)
5984 (if (not as)
5985 link
5986 (setq rpl (cdr as))
5987 (cond
5988 ((symbolp rpl) (funcall rpl tag))
5989 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5990 (t (concat rpl tag)))))
5991 link))
5993 ;;; Storing and inserting links
5995 (defvar org-insert-link-history nil
5996 "Minibuffer history for links inserted with `org-insert-link'.")
5998 (defvar org-stored-links nil
5999 "Contains the links stored with `org-store-link'.")
6001 (defvar org-store-link-plist nil
6002 "Plist with info about the most recently link created with `org-store-link'.")
6004 (defvar org-link-protocols nil
6005 "Link protocols added to Org-mode using `org-add-link-type'.")
6007 (defvar org-store-link-functions nil
6008 "List of functions that are called to create and store a link.
6009 Each function will be called in turn until one returns a non-nil
6010 value. Each function should check if it is responsible for creating
6011 this link (for example by looking at the major mode).
6012 If not, it must exit and return nil.
6013 If yes, it should return a non-nil value after a calling
6014 `org-store-link-props' with a list of properties and values.
6015 Special properties are:
6017 :type The link prefix. like \"http\". This must be given.
6018 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6019 This is obligatory as well.
6020 :description Optional default description for the second pair
6021 of brackets in an Org-mode link. The user can still change
6022 this when inserting this link into an Org-mode buffer.
6024 In addition to these, any additional properties can be specified
6025 and then used in remember templates.")
6027 (defun org-add-link-type (type &optional follow export)
6028 "Add TYPE to the list of `org-link-types'.
6029 Re-compute all regular expressions depending on `org-link-types'
6031 FOLLOW and EXPORT are two functions.
6033 FOLLOW should take the link path as the single argument and do whatever
6034 is necessary to follow the link, for example find a file or display
6035 a mail message.
6037 EXPORT should format the link path for export to one of the export formats.
6038 It should be a function accepting three arguments:
6040 path the path of the link, the text after the prefix (like \"http:\")
6041 desc the description of the link, if any, nil if there was no descripton
6042 format the export format, a symbol like `html' or `latex'.
6044 The function may use the FORMAT information to return different values
6045 depending on the format. The return value will be put literally into
6046 the exported file.
6047 Org-mode has a built-in default for exporting links. If you are happy with
6048 this default, there is no need to define an export function for the link
6049 type. For a simple example of an export function, see `org-bbdb.el'."
6050 (add-to-list 'org-link-types type t)
6051 (org-make-link-regexps)
6052 (if (assoc type org-link-protocols)
6053 (setcdr (assoc type org-link-protocols) (list follow export))
6054 (push (list type follow export) org-link-protocols)))
6057 ;;;###autoload
6058 (defun org-store-link (arg)
6059 "\\<org-mode-map>Store an org-link to the current location.
6060 This link is added to `org-stored-links' and can later be inserted
6061 into an org-buffer with \\[org-insert-link].
6063 For some link types, a prefix arg is interpreted:
6064 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6065 For file links, arg negates `org-context-in-file-links'."
6066 (interactive "P")
6067 (org-load-modules-maybe)
6068 (setq org-store-link-plist nil) ; reset
6069 (let (link cpltxt desc description search txt)
6070 (cond
6072 ((run-hook-with-args-until-success 'org-store-link-functions)
6073 (setq link (plist-get org-store-link-plist :link)
6074 desc (or (plist-get org-store-link-plist :description) link)))
6076 ((eq major-mode 'calendar-mode)
6077 (let ((cd (calendar-cursor-to-date)))
6078 (setq link
6079 (format-time-string
6080 (car org-time-stamp-formats)
6081 (apply 'encode-time
6082 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6083 nil nil nil))))
6084 (org-store-link-props :type "calendar" :date cd)))
6086 ((eq major-mode 'w3-mode)
6087 (setq cpltxt (url-view-url t)
6088 link (org-make-link cpltxt))
6089 (org-store-link-props :type "w3" :url (url-view-url t)))
6091 ((eq major-mode 'w3m-mode)
6092 (setq cpltxt (or w3m-current-title w3m-current-url)
6093 link (org-make-link w3m-current-url))
6094 (org-store-link-props :type "w3m" :url (url-view-url t)))
6096 ((setq search (run-hook-with-args-until-success
6097 'org-create-file-search-functions))
6098 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6099 "::" search))
6100 (setq cpltxt (or description link)))
6102 ((eq major-mode 'image-mode)
6103 (setq cpltxt (concat "file:"
6104 (abbreviate-file-name buffer-file-name))
6105 link (org-make-link cpltxt))
6106 (org-store-link-props :type "image" :file buffer-file-name))
6108 ((eq major-mode 'dired-mode)
6109 ;; link to the file in the current line
6110 (setq cpltxt (concat "file:"
6111 (abbreviate-file-name
6112 (expand-file-name
6113 (dired-get-filename nil t))))
6114 link (org-make-link cpltxt)))
6116 ((and buffer-file-name (org-mode-p))
6117 ;; Just link to current headline
6118 (setq cpltxt (concat "file:"
6119 (abbreviate-file-name buffer-file-name)))
6120 ;; Add a context search string
6121 (when (org-xor org-context-in-file-links arg)
6122 ;; Check if we are on a target
6123 (if (org-in-regexp "<<\\(.*?\\)>>")
6124 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6125 (setq txt (cond
6126 ((org-on-heading-p) nil)
6127 ((org-region-active-p)
6128 (buffer-substring (region-beginning) (region-end)))
6129 (t (buffer-substring (point-at-bol) (point-at-eol)))))
6130 (when (or (null txt) (string-match "\\S-" txt))
6131 (setq cpltxt
6132 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6133 desc "NONE"))))
6134 (if (string-match "::\\'" cpltxt)
6135 (setq cpltxt (substring cpltxt 0 -2)))
6136 (setq link (org-make-link cpltxt)))
6138 ((buffer-file-name (buffer-base-buffer))
6139 ;; Just link to this file here.
6140 (setq cpltxt (concat "file:"
6141 (abbreviate-file-name
6142 (buffer-file-name (buffer-base-buffer)))))
6143 ;; Add a context string
6144 (when (org-xor org-context-in-file-links arg)
6145 (setq txt (if (org-region-active-p)
6146 (buffer-substring (region-beginning) (region-end))
6147 (buffer-substring (point-at-bol) (point-at-eol))))
6148 ;; Only use search option if there is some text.
6149 (when (string-match "\\S-" txt)
6150 (setq cpltxt
6151 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6152 desc "NONE")))
6153 (setq link (org-make-link cpltxt)))
6155 ((interactive-p)
6156 (error "Cannot link to a buffer which is not visiting a file"))
6158 (t (setq link nil)))
6160 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6161 (setq link (or link cpltxt)
6162 desc (or desc cpltxt))
6163 (if (equal desc "NONE") (setq desc nil))
6165 (if (and (interactive-p) link)
6166 (progn
6167 (setq org-stored-links
6168 (cons (list link desc) org-stored-links))
6169 (message "Stored: %s" (or desc link)))
6170 (and link (org-make-link-string link desc)))))
6172 (defun org-store-link-props (&rest plist)
6173 "Store link properties, extract names and addresses."
6174 (let (x adr)
6175 (when (setq x (plist-get plist :from))
6176 (setq adr (mail-extract-address-components x))
6177 (plist-put plist :fromname (car adr))
6178 (plist-put plist :fromaddress (nth 1 adr)))
6179 (when (setq x (plist-get plist :to))
6180 (setq adr (mail-extract-address-components x))
6181 (plist-put plist :toname (car adr))
6182 (plist-put plist :toaddress (nth 1 adr))))
6183 (let ((from (plist-get plist :from))
6184 (to (plist-get plist :to)))
6185 (when (and from to org-from-is-user-regexp)
6186 (plist-put plist :fromto
6187 (if (string-match org-from-is-user-regexp from)
6188 (concat "to %t")
6189 (concat "from %f")))))
6190 (setq org-store-link-plist plist))
6192 (defun org-add-link-props (&rest plist)
6193 "Add these properties to the link property list."
6194 (let (key value)
6195 (while plist
6196 (setq key (pop plist) value (pop plist))
6197 (setq org-store-link-plist
6198 (plist-put org-store-link-plist key value)))))
6200 (defun org-email-link-description (&optional fmt)
6201 "Return the description part of an email link.
6202 This takes information from `org-store-link-plist' and formats it
6203 according to FMT (default from `org-email-link-description-format')."
6204 (setq fmt (or fmt org-email-link-description-format))
6205 (let* ((p org-store-link-plist)
6206 (to (plist-get p :toaddress))
6207 (from (plist-get p :fromaddress))
6208 (table
6209 (list
6210 (cons "%c" (plist-get p :fromto))
6211 (cons "%F" (plist-get p :from))
6212 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6213 (cons "%T" (plist-get p :to))
6214 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6215 (cons "%s" (plist-get p :subject))
6216 (cons "%m" (plist-get p :message-id)))))
6217 (when (string-match "%c" fmt)
6218 ;; Check if the user wrote this message
6219 (if (and org-from-is-user-regexp from to
6220 (save-match-data (string-match org-from-is-user-regexp from)))
6221 (setq fmt (replace-match "to %t" t t fmt))
6222 (setq fmt (replace-match "from %f" t t fmt))))
6223 (org-replace-escapes fmt table)))
6225 (defun org-make-org-heading-search-string (&optional string heading)
6226 "Make search string for STRING or current headline."
6227 (interactive)
6228 (let ((s (or string (org-get-heading))))
6229 (unless (and string (not heading))
6230 ;; We are using a headline, clean up garbage in there.
6231 (if (string-match org-todo-regexp s)
6232 (setq s (replace-match "" t t s)))
6233 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6234 (setq s (replace-match "" t t s)))
6235 (setq s (org-trim s))
6236 (if (string-match (concat "^\\(" org-quote-string "\\|"
6237 org-comment-string "\\)") s)
6238 (setq s (replace-match "" t t s)))
6239 (while (string-match org-ts-regexp s)
6240 (setq s (replace-match "" t t s))))
6241 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6242 (setq s (replace-match " " t t s)))
6243 (or string (setq s (concat "*" s))) ; Add * for headlines
6244 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6246 (defun org-make-link (&rest strings)
6247 "Concatenate STRINGS."
6248 (apply 'concat strings))
6250 (defun org-make-link-string (link &optional description)
6251 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6252 (unless (string-match "\\S-" link)
6253 (error "Empty link"))
6254 (when (stringp description)
6255 ;; Remove brackets from the description, they are fatal.
6256 (while (string-match "\\[" description)
6257 (setq description (replace-match "{" t t description)))
6258 (while (string-match "\\]" description)
6259 (setq description (replace-match "}" t t description))))
6260 (when (equal (org-link-escape link) description)
6261 ;; No description needed, it is identical
6262 (setq description nil))
6263 (when (and (not description)
6264 (not (equal link (org-link-escape link))))
6265 (setq description link))
6266 (concat "[[" (org-link-escape link) "]"
6267 (if description (concat "[" description "]") "")
6268 "]"))
6270 (defconst org-link-escape-chars
6271 '((?\ . "%20")
6272 (?\[ . "%5B")
6273 (?\] . "%5D")
6274 (?\340 . "%E0") ; `a
6275 (?\342 . "%E2") ; ^a
6276 (?\347 . "%E7") ; ,c
6277 (?\350 . "%E8") ; `e
6278 (?\351 . "%E9") ; 'e
6279 (?\352 . "%EA") ; ^e
6280 (?\356 . "%EE") ; ^i
6281 (?\364 . "%F4") ; ^o
6282 (?\371 . "%F9") ; `u
6283 (?\373 . "%FB") ; ^u
6284 (?\; . "%3B")
6285 (?? . "%3F")
6286 (?= . "%3D")
6287 (?+ . "%2B")
6289 "Association list of escapes for some characters problematic in links.
6290 This is the list that is used for internal purposes.")
6292 (defconst org-link-escape-chars-browser
6293 '((?\ . "%20")) ; 32 for the SPC char
6294 "Association list of escapes for some characters problematic in links.
6295 This is the list that is used before handing over to the browser.")
6297 (defun org-link-escape (text &optional table)
6298 "Escape charaters in TEXT that are problematic for links."
6299 (setq table (or table org-link-escape-chars))
6300 (when text
6301 (let ((re (mapconcat (lambda (x) (regexp-quote
6302 (char-to-string (car x))))
6303 table "\\|")))
6304 (while (string-match re text)
6305 (setq text
6306 (replace-match
6307 (cdr (assoc (string-to-char (match-string 0 text))
6308 table))
6309 t t text)))
6310 text)))
6312 (defun org-link-unescape (text &optional table)
6313 "Reverse the action of `org-link-escape'."
6314 (setq table (or table org-link-escape-chars))
6315 (when text
6316 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6317 table "\\|")))
6318 (while (string-match re text)
6319 (setq text
6320 (replace-match
6321 (char-to-string (car (rassoc (match-string 0 text) table)))
6322 t t text)))
6323 text)))
6325 (defun org-xor (a b)
6326 "Exclusive or."
6327 (if a (not b) b))
6329 (defun org-get-header (header)
6330 "Find a header field in the current buffer."
6331 (save-excursion
6332 (goto-char (point-min))
6333 (let ((case-fold-search t) s)
6334 (cond
6335 ((eq header 'from)
6336 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6337 (setq s (match-string 1)))
6338 (while (string-match "\"" s)
6339 (setq s (replace-match "" t t s)))
6340 (if (string-match "[<(].*" s)
6341 (setq s (replace-match "" t t s))))
6342 ((eq header 'message-id)
6343 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6344 (setq s (match-string 1))))
6345 ((eq header 'subject)
6346 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6347 (setq s (match-string 1)))))
6348 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6349 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6350 s)))
6353 (defun org-fixup-message-id-for-http (s)
6354 "Replace special characters in a message id, so it can be used in an http query."
6355 (while (string-match "<" s)
6356 (setq s (replace-match "%3C" t t s)))
6357 (while (string-match ">" s)
6358 (setq s (replace-match "%3E" t t s)))
6359 (while (string-match "@" s)
6360 (setq s (replace-match "%40" t t s)))
6363 ;;;###autoload
6364 (defun org-insert-link-global ()
6365 "Insert a link like Org-mode does.
6366 This command can be called in any mode to insert a link in Org-mode syntax."
6367 (interactive)
6368 (org-load-modules-maybe)
6369 (org-run-like-in-org-mode 'org-insert-link))
6371 (defun org-insert-link (&optional complete-file link-location)
6372 "Insert a link. At the prompt, enter the link.
6374 Completion can be used to select a link previously stored with
6375 `org-store-link'. When the empty string is entered (i.e. if you just
6376 press RET at the prompt), the link defaults to the most recently
6377 stored link. As SPC triggers completion in the minibuffer, you need to
6378 use M-SPC or C-q SPC to force the insertion of a space character.
6380 You will also be prompted for a description, and if one is given, it will
6381 be displayed in the buffer instead of the link.
6383 If there is already a link at point, this command will allow you to edit link
6384 and description parts.
6386 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6387 be selected using completion. The path to the file will be relative to the
6388 current directory if the file is in the current directory or a subdirectory.
6389 Otherwise, the link will be the absolute path as completed in the minibuffer
6390 \(i.e. normally ~/path/to/file).
6392 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6393 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6394 of `org-keep-stored-link-after-insertion'.
6396 If `org-make-link-description-function' is non-nil, this function will be
6397 called with the link target, and the result will be the default
6398 link description.
6400 If the LINK-LOCATION parameter is non-nil, this value will be
6401 used as the link location instead of reading one interactively."
6402 (interactive "P")
6403 (let* ((wcf (current-window-configuration))
6404 (region (if (org-region-active-p)
6405 (buffer-substring (region-beginning) (region-end))))
6406 (remove (and region (list (region-beginning) (region-end))))
6407 (desc region)
6408 tmphist ; byte-compile incorrectly complains about this
6409 (link link-location)
6410 entry file)
6411 (cond
6412 (link-location) ; specified by arg, just use it.
6413 ((org-in-regexp org-bracket-link-regexp 1)
6414 ;; We do have a link at point, and we are going to edit it.
6415 (setq remove (list (match-beginning 0) (match-end 0)))
6416 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6417 (setq link (read-string "Link: "
6418 (org-link-unescape
6419 (org-match-string-no-properties 1)))))
6420 ((or (org-in-regexp org-angle-link-re)
6421 (org-in-regexp org-plain-link-re))
6422 ;; Convert to bracket link
6423 (setq remove (list (match-beginning 0) (match-end 0))
6424 link (read-string "Link: "
6425 (org-remove-angle-brackets (match-string 0)))))
6426 ((equal complete-file '(4))
6427 ;; Completing read for file names.
6428 (setq file (read-file-name "File: "))
6429 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6430 (pwd1 (file-name-as-directory (abbreviate-file-name
6431 (expand-file-name ".")))))
6432 (cond
6433 ((equal complete-file '(16))
6434 (setq link (org-make-link
6435 "file:"
6436 (abbreviate-file-name (expand-file-name file)))))
6437 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6438 (setq link (org-make-link "file:" (match-string 1 file))))
6439 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6440 (expand-file-name file))
6441 (setq link (org-make-link
6442 "file:" (match-string 1 (expand-file-name file)))))
6443 (t (setq link (org-make-link "file:" file))))))
6445 ;; Read link, with completion for stored links.
6446 (with-output-to-temp-buffer "*Org Links*"
6447 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6448 (when org-stored-links
6449 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6450 (princ (mapconcat
6451 (lambda (x)
6452 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6453 (reverse org-stored-links) "\n"))))
6454 (let ((cw (selected-window)))
6455 (select-window (get-buffer-window "*Org Links*"))
6456 (shrink-window-if-larger-than-buffer)
6457 (setq truncate-lines t)
6458 (select-window cw))
6459 ;; Fake a link history, containing the stored links.
6460 (setq tmphist (append (mapcar 'car org-stored-links)
6461 org-insert-link-history))
6462 (unwind-protect
6463 (setq link (org-completing-read
6464 "Link: "
6465 (append
6466 (mapcar (lambda (x) (list (concat (car x) ":")))
6467 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6468 (mapcar (lambda (x) (list (concat x ":")))
6469 org-link-types))
6470 nil nil nil
6471 'tmphist
6472 (or (car (car org-stored-links)))))
6473 (set-window-configuration wcf)
6474 (kill-buffer "*Org Links*"))
6475 (setq entry (assoc link org-stored-links))
6476 (or entry (push link org-insert-link-history))
6477 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6478 (not org-keep-stored-link-after-insertion))
6479 (setq org-stored-links (delq (assoc link org-stored-links)
6480 org-stored-links)))
6481 (setq desc (or desc (nth 1 entry)))))
6483 (if (string-match org-plain-link-re link)
6484 ;; URL-like link, normalize the use of angular brackets.
6485 (setq link (org-make-link (org-remove-angle-brackets link))))
6487 ;; Check if we are linking to the current file with a search option
6488 ;; If yes, simplify the link by using only the search option.
6489 (when (and buffer-file-name
6490 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6491 (let* ((path (match-string 1 link))
6492 (case-fold-search nil)
6493 (search (match-string 2 link)))
6494 (save-match-data
6495 (if (equal (file-truename buffer-file-name) (file-truename path))
6496 ;; We are linking to this same file, with a search option
6497 (setq link search)))))
6499 ;; Check if we can/should use a relative path. If yes, simplify the link
6500 (when (string-match "\\<file:\\(.*\\)" link)
6501 (let* ((path (match-string 1 link))
6502 (origpath path)
6503 (case-fold-search nil))
6504 (cond
6505 ((eq org-link-file-path-type 'absolute)
6506 (setq path (abbreviate-file-name (expand-file-name path))))
6507 ((eq org-link-file-path-type 'noabbrev)
6508 (setq path (expand-file-name path)))
6509 ((eq org-link-file-path-type 'relative)
6510 (setq path (file-relative-name path)))
6512 (save-match-data
6513 (if (string-match (concat "^" (regexp-quote
6514 (file-name-as-directory
6515 (expand-file-name "."))))
6516 (expand-file-name path))
6517 ;; We are linking a file with relative path name.
6518 (setq path (substring (expand-file-name path)
6519 (match-end 0)))))))
6520 (setq link (concat "file:" path))
6521 (if (equal desc origpath)
6522 (setq desc path))))
6524 (if org-make-link-description-function
6525 (setq desc (funcall org-make-link-description-function link desc)))
6527 (setq desc (read-string "Description: " desc))
6528 (unless (string-match "\\S-" desc) (setq desc nil))
6529 (if remove (apply 'delete-region remove))
6530 (insert (org-make-link-string link desc))))
6532 (defun org-completing-read (&rest args)
6533 (let ((minibuffer-local-completion-map
6534 (copy-keymap minibuffer-local-completion-map)))
6535 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6536 (apply 'completing-read args)))
6538 ;;; Opening/following a link
6540 (defvar org-link-search-failed nil)
6542 (defun org-next-link ()
6543 "Move forward to the next link.
6544 If the link is in hidden text, expose it."
6545 (interactive)
6546 (when (and org-link-search-failed (eq this-command last-command))
6547 (goto-char (point-min))
6548 (message "Link search wrapped back to beginning of buffer"))
6549 (setq org-link-search-failed nil)
6550 (let* ((pos (point))
6551 (ct (org-context))
6552 (a (assoc :link ct)))
6553 (if a (goto-char (nth 2 a)))
6554 (if (re-search-forward org-any-link-re nil t)
6555 (progn
6556 (goto-char (match-beginning 0))
6557 (if (org-invisible-p) (org-show-context)))
6558 (goto-char pos)
6559 (setq org-link-search-failed t)
6560 (error "No further link found"))))
6562 (defun org-previous-link ()
6563 "Move backward to the previous link.
6564 If the link is in hidden text, expose it."
6565 (interactive)
6566 (when (and org-link-search-failed (eq this-command last-command))
6567 (goto-char (point-max))
6568 (message "Link search wrapped back to end of buffer"))
6569 (setq org-link-search-failed nil)
6570 (let* ((pos (point))
6571 (ct (org-context))
6572 (a (assoc :link ct)))
6573 (if a (goto-char (nth 1 a)))
6574 (if (re-search-backward org-any-link-re nil t)
6575 (progn
6576 (goto-char (match-beginning 0))
6577 (if (org-invisible-p) (org-show-context)))
6578 (goto-char pos)
6579 (setq org-link-search-failed t)
6580 (error "No further link found"))))
6582 (defun org-find-file-at-mouse (ev)
6583 "Open file link or URL at mouse."
6584 (interactive "e")
6585 (mouse-set-point ev)
6586 (org-open-at-point 'in-emacs))
6588 (defun org-open-at-mouse (ev)
6589 "Open file link or URL at mouse."
6590 (interactive "e")
6591 (mouse-set-point ev)
6592 (org-open-at-point))
6594 (defvar org-window-config-before-follow-link nil
6595 "The window configuration before following a link.
6596 This is saved in case the need arises to restore it.")
6598 (defvar org-open-link-marker (make-marker)
6599 "Marker pointing to the location where `org-open-at-point; was called.")
6601 ;;;###autoload
6602 (defun org-open-at-point-global ()
6603 "Follow a link like Org-mode does.
6604 This command can be called in any mode to follow a link that has
6605 Org-mode syntax."
6606 (interactive)
6607 (org-run-like-in-org-mode 'org-open-at-point))
6609 (defun org-open-at-point (&optional in-emacs)
6610 "Open link at or after point.
6611 If there is no link at point, this function will search forward up to
6612 the end of the current subtree.
6613 Normally, files will be opened by an appropriate application. If the
6614 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6615 (interactive "P")
6616 (org-load-modules-maybe)
6617 (move-marker org-open-link-marker (point))
6618 (setq org-window-config-before-follow-link (current-window-configuration))
6619 (org-remove-occur-highlights nil nil t)
6620 (if (org-at-timestamp-p t)
6621 (org-follow-timestamp-link)
6622 (let (type path link line search (pos (point)))
6623 (catch 'match
6624 (save-excursion
6625 (skip-chars-forward "^]\n\r")
6626 (when (org-in-regexp org-bracket-link-regexp)
6627 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6628 (while (string-match " *\n *" link)
6629 (setq link (replace-match " " t t link)))
6630 (setq link (org-link-expand-abbrev link))
6631 (if (string-match org-link-re-with-space2 link)
6632 (setq type (match-string 1 link) path (match-string 2 link))
6633 (setq type "thisfile" path link))
6634 (throw 'match t)))
6636 (when (get-text-property (point) 'org-linked-text)
6637 (setq type "thisfile"
6638 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6639 (1+ (point)) (point))
6640 path (buffer-substring
6641 (previous-single-property-change pos 'org-linked-text)
6642 (next-single-property-change pos 'org-linked-text)))
6643 (throw 'match t))
6645 (save-excursion
6646 (when (or (org-in-regexp org-angle-link-re)
6647 (org-in-regexp org-plain-link-re))
6648 (setq type (match-string 1) path (match-string 2))
6649 (throw 'match t)))
6650 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6651 (setq type "tree-match"
6652 path (match-string 1))
6653 (throw 'match t))
6654 (save-excursion
6655 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6656 (setq type "tags"
6657 path (match-string 1))
6658 (while (string-match ":" path)
6659 (setq path (replace-match "+" t t path)))
6660 (throw 'match t))))
6661 (unless path
6662 (error "No link found"))
6663 ;; Remove any trailing spaces in path
6664 (if (string-match " +\\'" path)
6665 (setq path (replace-match "" t t path)))
6667 (cond
6669 ((assoc type org-link-protocols)
6670 (funcall (nth 1 (assoc type org-link-protocols)) path))
6672 ((equal type "mailto")
6673 (let ((cmd (car org-link-mailto-program))
6674 (args (cdr org-link-mailto-program)) args1
6675 (address path) (subject "") a)
6676 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6677 (setq address (match-string 1 path)
6678 subject (org-link-escape (match-string 2 path))))
6679 (while args
6680 (cond
6681 ((not (stringp (car args))) (push (pop args) args1))
6682 (t (setq a (pop args))
6683 (if (string-match "%a" a)
6684 (setq a (replace-match address t t a)))
6685 (if (string-match "%s" a)
6686 (setq a (replace-match subject t t a)))
6687 (push a args1))))
6688 (apply cmd (nreverse args1))))
6690 ((member type '("http" "https" "ftp" "news"))
6691 (browse-url (concat type ":" (org-link-escape
6692 path org-link-escape-chars-browser))))
6694 ((member type '("message"))
6695 (browse-url (concat type ":" path)))
6697 ((string= type "tags")
6698 (org-tags-view in-emacs path))
6699 ((string= type "thisfile")
6700 (if in-emacs
6701 (switch-to-buffer-other-window
6702 (org-get-buffer-for-internal-link (current-buffer)))
6703 (org-mark-ring-push))
6704 (let ((cmd `(org-link-search
6705 ,path
6706 ,(cond ((equal in-emacs '(4)) 'occur)
6707 ((equal in-emacs '(16)) 'org-occur)
6708 (t nil))
6709 ,pos)))
6710 (condition-case nil (eval cmd)
6711 (error (progn (widen) (eval cmd))))))
6713 ((string= type "tree-match")
6714 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6716 ((string= type "file")
6717 (if (string-match "::\\([0-9]+\\)\\'" path)
6718 (setq line (string-to-number (match-string 1 path))
6719 path (substring path 0 (match-beginning 0)))
6720 (if (string-match "::\\(.+\\)\\'" path)
6721 (setq search (match-string 1 path)
6722 path (substring path 0 (match-beginning 0)))))
6723 (if (string-match "[*?{]" (file-name-nondirectory path))
6724 (dired path)
6725 (org-open-file path in-emacs line search)))
6727 ((string= type "news")
6728 (require 'org-gnus)
6729 (org-gnus-follow-link path))
6731 ((string= type "shell")
6732 (let ((cmd path))
6733 (if (or (not org-confirm-shell-link-function)
6734 (funcall org-confirm-shell-link-function
6735 (format "Execute \"%s\" in shell? "
6736 (org-add-props cmd nil
6737 'face 'org-warning))))
6738 (progn
6739 (message "Executing %s" cmd)
6740 (shell-command cmd))
6741 (error "Abort"))))
6743 ((string= type "elisp")
6744 (let ((cmd path))
6745 (if (or (not org-confirm-elisp-link-function)
6746 (funcall org-confirm-elisp-link-function
6747 (format "Execute \"%s\" as elisp? "
6748 (org-add-props cmd nil
6749 'face 'org-warning))))
6750 (message "%s => %s" cmd (eval (read cmd)))
6751 (error "Abort"))))
6754 (browse-url-at-point)))))
6755 (move-marker org-open-link-marker nil)
6756 (run-hook-with-args 'org-follow-link-hook))
6758 ;;; File search
6760 (defvar org-create-file-search-functions nil
6761 "List of functions to construct the right search string for a file link.
6762 These functions are called in turn with point at the location to
6763 which the link should point.
6765 A function in the hook should first test if it would like to
6766 handle this file type, for example by checking the major-mode or
6767 the file extension. If it decides not to handle this file, it
6768 should just return nil to give other functions a chance. If it
6769 does handle the file, it must return the search string to be used
6770 when following the link. The search string will be part of the
6771 file link, given after a double colon, and `org-open-at-point'
6772 will automatically search for it. If special measures must be
6773 taken to make the search successful, another function should be
6774 added to the companion hook `org-execute-file-search-functions',
6775 which see.
6777 A function in this hook may also use `setq' to set the variable
6778 `description' to provide a suggestion for the descriptive text to
6779 be used for this link when it gets inserted into an Org-mode
6780 buffer with \\[org-insert-link].")
6782 (defvar org-execute-file-search-functions nil
6783 "List of functions to execute a file search triggered by a link.
6785 Functions added to this hook must accept a single argument, the
6786 search string that was part of the file link, the part after the
6787 double colon. The function must first check if it would like to
6788 handle this search, for example by checking the major-mode or the
6789 file extension. If it decides not to handle this search, it
6790 should just return nil to give other functions a chance. If it
6791 does handle the search, it must return a non-nil value to keep
6792 other functions from trying.
6794 Each function can access the current prefix argument through the
6795 variable `current-prefix-argument'. Note that a single prefix is
6796 used to force opening a link in Emacs, so it may be good to only
6797 use a numeric or double prefix to guide the search function.
6799 In case this is needed, a function in this hook can also restore
6800 the window configuration before `org-open-at-point' was called using:
6802 (set-window-configuration org-window-config-before-follow-link)")
6804 (defun org-link-search (s &optional type avoid-pos)
6805 "Search for a link search option.
6806 If S is surrounded by forward slashes, it is interpreted as a
6807 regular expression. In org-mode files, this will create an `org-occur'
6808 sparse tree. In ordinary files, `occur' will be used to list matches.
6809 If the current buffer is in `dired-mode', grep will be used to search
6810 in all files. If AVOID-POS is given, ignore matches near that position."
6811 (let ((case-fold-search t)
6812 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6813 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6814 (append '(("") (" ") ("\t") ("\n"))
6815 org-emphasis-alist)
6816 "\\|") "\\)"))
6817 (pos (point))
6818 (pre "") (post "")
6819 words re0 re1 re2 re3 re4 re5 re2a reall)
6820 (cond
6821 ;; First check if there are any special
6822 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6823 ;; Now try the builtin stuff
6824 ((save-excursion
6825 (goto-char (point-min))
6826 (and
6827 (re-search-forward
6828 (concat "<<" (regexp-quote s0) ">>") nil t)
6829 (setq pos (match-beginning 0))))
6830 ;; There is an exact target for this
6831 (goto-char pos))
6832 ((string-match "^/\\(.*\\)/$" s)
6833 ;; A regular expression
6834 (cond
6835 ((org-mode-p)
6836 (org-occur (match-string 1 s)))
6837 ;;((eq major-mode 'dired-mode)
6838 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6839 (t (org-do-occur (match-string 1 s)))))
6841 ;; A normal search strings
6842 (when (equal (string-to-char s) ?*)
6843 ;; Anchor on headlines, post may include tags.
6844 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6845 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6846 s (substring s 1)))
6847 (remove-text-properties
6848 0 (length s)
6849 '(face nil mouse-face nil keymap nil fontified nil) s)
6850 ;; Make a series of regular expressions to find a match
6851 (setq words (org-split-string s "[ \n\r\t]+")
6852 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6853 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6854 "\\)" markers)
6855 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6856 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6857 re1 (concat pre re2 post)
6858 re3 (concat pre re4 post)
6859 re5 (concat pre ".*" re4)
6860 re2 (concat pre re2)
6861 re2a (concat pre re2a)
6862 re4 (concat pre re4)
6863 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6864 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6865 re5 "\\)"
6867 (cond
6868 ((eq type 'org-occur) (org-occur reall))
6869 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6870 (t (goto-char (point-min))
6871 (if (or (org-search-not-self 1 re0 nil t)
6872 (org-search-not-self 1 re1 nil t)
6873 (org-search-not-self 1 re2 nil t)
6874 (org-search-not-self 1 re2a nil t)
6875 (org-search-not-self 1 re3 nil t)
6876 (org-search-not-self 1 re4 nil t)
6877 (org-search-not-self 1 re5 nil t)
6879 (goto-char (match-beginning 1))
6880 (goto-char pos)
6881 (error "No match")))))
6883 ;; Normal string-search
6884 (goto-char (point-min))
6885 (if (search-forward s nil t)
6886 (goto-char (match-beginning 0))
6887 (error "No match"))))
6888 (and (org-mode-p) (org-show-context 'link-search))))
6890 (defun org-search-not-self (group &rest args)
6891 "Execute `re-search-forward', but only accept matches that do not
6892 enclose the position of `org-open-link-marker'."
6893 (let ((m org-open-link-marker))
6894 (catch 'exit
6895 (while (apply 're-search-forward args)
6896 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6897 (goto-char (match-end group))
6898 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6899 (> (match-beginning 0) (marker-position m))
6900 (< (match-end 0) (marker-position m)))
6901 (save-match-data
6902 (or (not (org-in-regexp
6903 org-bracket-link-analytic-regexp 1))
6904 (not (match-end 4)) ; no description
6905 (and (<= (match-beginning 4) (point))
6906 (>= (match-end 4) (point))))))
6907 (throw 'exit (point))))))))
6909 (defun org-get-buffer-for-internal-link (buffer)
6910 "Return a buffer to be used for displaying the link target of internal links."
6911 (cond
6912 ((not org-display-internal-link-with-indirect-buffer)
6913 buffer)
6914 ((string-match "(Clone)$" (buffer-name buffer))
6915 (message "Buffer is already a clone, not making another one")
6916 ;; we also do not modify visibility in this case
6917 buffer)
6918 (t ; make a new indirect buffer for displaying the link
6919 (let* ((bn (buffer-name buffer))
6920 (ibn (concat bn "(Clone)"))
6921 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6922 (with-current-buffer ib (org-overview))
6923 ib))))
6925 (defun org-do-occur (regexp &optional cleanup)
6926 "Call the Emacs command `occur'.
6927 If CLEANUP is non-nil, remove the printout of the regular expression
6928 in the *Occur* buffer. This is useful if the regex is long and not useful
6929 to read."
6930 (occur regexp)
6931 (when cleanup
6932 (let ((cwin (selected-window)) win beg end)
6933 (when (setq win (get-buffer-window "*Occur*"))
6934 (select-window win))
6935 (goto-char (point-min))
6936 (when (re-search-forward "match[a-z]+" nil t)
6937 (setq beg (match-end 0))
6938 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6939 (setq end (1- (match-beginning 0)))))
6940 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6941 (goto-char (point-min))
6942 (select-window cwin))))
6944 ;;; The mark ring for links jumps
6946 (defvar org-mark-ring nil
6947 "Mark ring for positions before jumps in Org-mode.")
6948 (defvar org-mark-ring-last-goto nil
6949 "Last position in the mark ring used to go back.")
6950 ;; Fill and close the ring
6951 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6952 (loop for i from 1 to org-mark-ring-length do
6953 (push (make-marker) org-mark-ring))
6954 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6955 org-mark-ring)
6957 (defun org-mark-ring-push (&optional pos buffer)
6958 "Put the current position or POS into the mark ring and rotate it."
6959 (interactive)
6960 (setq pos (or pos (point)))
6961 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6962 (move-marker (car org-mark-ring)
6963 (or pos (point))
6964 (or buffer (current-buffer)))
6965 (message "%s"
6966 (substitute-command-keys
6967 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6969 (defun org-mark-ring-goto (&optional n)
6970 "Jump to the previous position in the mark ring.
6971 With prefix arg N, jump back that many stored positions. When
6972 called several times in succession, walk through the entire ring.
6973 Org-mode commands jumping to a different position in the current file,
6974 or to another Org-mode file, automatically push the old position
6975 onto the ring."
6976 (interactive "p")
6977 (let (p m)
6978 (if (eq last-command this-command)
6979 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6980 (setq p org-mark-ring))
6981 (setq org-mark-ring-last-goto p)
6982 (setq m (car p))
6983 (switch-to-buffer (marker-buffer m))
6984 (goto-char m)
6985 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6987 (defun org-remove-angle-brackets (s)
6988 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6989 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6991 (defun org-add-angle-brackets (s)
6992 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6993 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6996 ;;; Following specific links
6998 (defun org-follow-timestamp-link ()
6999 (cond
7000 ((org-at-date-range-p t)
7001 (let ((org-agenda-start-on-weekday)
7002 (t1 (match-string 1))
7003 (t2 (match-string 2)))
7004 (setq t1 (time-to-days (org-time-string-to-time t1))
7005 t2 (time-to-days (org-time-string-to-time t2)))
7006 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7007 ((org-at-timestamp-p t)
7008 (org-agenda-list nil (time-to-days (org-time-string-to-time
7009 (substring (match-string 1) 0 10)))
7011 (t (error "This should not happen"))))
7014 ;;; Following file links
7016 (defun org-open-file (path &optional in-emacs line search)
7017 "Open the file at PATH.
7018 First, this expands any special file name abbreviations. Then the
7019 configuration variable `org-file-apps' is checked if it contains an
7020 entry for this file type, and if yes, the corresponding command is launched.
7021 If no application is found, Emacs simply visits the file.
7022 With optional argument IN-EMACS, Emacs will visit the file.
7023 Optional LINE specifies a line to go to, optional SEARCH a string to
7024 search for. If LINE or SEARCH is given, the file will always be
7025 opened in Emacs.
7026 If the file does not exist, an error is thrown."
7027 (setq in-emacs (or in-emacs line search))
7028 (let* ((file (if (equal path "")
7029 buffer-file-name
7030 (substitute-in-file-name (expand-file-name path))))
7031 (apps (append org-file-apps (org-default-apps)))
7032 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7033 (dirp (if remp nil (file-directory-p file)))
7034 (dfile (downcase file))
7035 (old-buffer (current-buffer))
7036 (old-pos (point))
7037 (old-mode major-mode)
7038 ext cmd)
7039 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7040 (setq ext (match-string 1 dfile))
7041 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7042 (setq ext (match-string 1 dfile))))
7043 (if in-emacs
7044 (setq cmd 'emacs)
7045 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7046 (and dirp (cdr (assoc 'directory apps)))
7047 (cdr (assoc ext apps))
7048 (cdr (assoc t apps)))))
7049 (when (eq cmd 'mailcap)
7050 (require 'mailcap)
7051 (mailcap-parse-mailcaps)
7052 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7053 (command (mailcap-mime-info mime-type)))
7054 (if (stringp command)
7055 (setq cmd command)
7056 (setq cmd 'emacs))))
7057 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7058 (not (file-exists-p file))
7059 (not org-open-non-existing-files))
7060 (error "No such file: %s" file))
7061 (cond
7062 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7063 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7064 (while (string-match "['\"]%s['\"]" cmd)
7065 (setq cmd (replace-match "%s" t t cmd)))
7066 (while (string-match "%s" cmd)
7067 (setq cmd (replace-match
7068 (save-match-data (shell-quote-argument file))
7069 t t cmd)))
7070 (save-window-excursion
7071 (start-process-shell-command cmd nil cmd)))
7072 ((or (stringp cmd)
7073 (eq cmd 'emacs))
7074 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7075 (widen)
7076 (if line (goto-line line)
7077 (if search (org-link-search search))))
7078 ((consp cmd)
7079 (eval cmd))
7080 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7081 (and (org-mode-p) (eq old-mode 'org-mode)
7082 (or (not (equal old-buffer (current-buffer)))
7083 (not (equal old-pos (point))))
7084 (org-mark-ring-push old-pos old-buffer))))
7086 (defun org-default-apps ()
7087 "Return the default applications for this operating system."
7088 (cond
7089 ((eq system-type 'darwin)
7090 org-file-apps-defaults-macosx)
7091 ((eq system-type 'windows-nt)
7092 org-file-apps-defaults-windowsnt)
7093 (t org-file-apps-defaults-gnu)))
7095 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7096 (defun org-file-remote-p (file)
7097 "Test whether FILE specifies a location on a remote system.
7098 Return non-nil if the location is indeed remote.
7100 For example, the filename \"/user@host:/foo\" specifies a location
7101 on the system \"/user@host:\"."
7102 (cond ((fboundp 'file-remote-p)
7103 (file-remote-p file))
7104 ((fboundp 'tramp-handle-file-remote-p)
7105 (tramp-handle-file-remote-p file))
7106 ((and (boundp 'ange-ftp-name-format)
7107 (string-match (car ange-ftp-name-format) file))
7109 (t nil)))
7112 ;;;; Refiling
7114 (defun org-get-org-file ()
7115 "Read a filename, with default directory `org-directory'."
7116 (let ((default (or org-default-notes-file remember-data-file)))
7117 (read-file-name (format "File name [%s]: " default)
7118 (file-name-as-directory org-directory)
7119 default)))
7121 (defun org-notes-order-reversed-p ()
7122 "Check if the current file should receive notes in reversed order."
7123 (cond
7124 ((not org-reverse-note-order) nil)
7125 ((eq t org-reverse-note-order) t)
7126 ((not (listp org-reverse-note-order)) nil)
7127 (t (catch 'exit
7128 (let ((all org-reverse-note-order)
7129 entry)
7130 (while (setq entry (pop all))
7131 (if (string-match (car entry) buffer-file-name)
7132 (throw 'exit (cdr entry))))
7133 nil)))))
7135 (defvar org-refile-target-table nil
7136 "The list of refile targets, created by `org-refile'.")
7138 (defvar org-agenda-new-buffers nil
7139 "Buffers created to visit agenda files.")
7141 (defun org-get-refile-targets (&optional default-buffer)
7142 "Produce a table with refile targets."
7143 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7144 targets txt re files f desc descre)
7145 (with-current-buffer (or default-buffer (current-buffer))
7146 (while (setq entry (pop entries))
7147 (setq files (car entry) desc (cdr entry))
7148 (cond
7149 ((null files) (setq files (list (current-buffer))))
7150 ((eq files 'org-agenda-files)
7151 (setq files (org-agenda-files 'unrestricted)))
7152 ((and (symbolp files) (fboundp files))
7153 (setq files (funcall files)))
7154 ((and (symbolp files) (boundp files))
7155 (setq files (symbol-value files))))
7156 (if (stringp files) (setq files (list files)))
7157 (cond
7158 ((eq (car desc) :tag)
7159 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7160 ((eq (car desc) :todo)
7161 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7162 ((eq (car desc) :regexp)
7163 (setq descre (cdr desc)))
7164 ((eq (car desc) :level)
7165 (setq descre (concat "^\\*\\{" (number-to-string
7166 (if org-odd-levels-only
7167 (1- (* 2 (cdr desc)))
7168 (cdr desc)))
7169 "\\}[ \t]")))
7170 ((eq (car desc) :maxlevel)
7171 (setq descre (concat "^\\*\\{1," (number-to-string
7172 (if org-odd-levels-only
7173 (1- (* 2 (cdr desc)))
7174 (cdr desc)))
7175 "\\}[ \t]")))
7176 (t (error "Bad refiling target description %s" desc)))
7177 (while (setq f (pop files))
7178 (save-excursion
7179 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7180 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7181 (save-excursion
7182 (save-restriction
7183 (widen)
7184 (goto-char (point-min))
7185 (while (re-search-forward descre nil t)
7186 (goto-char (point-at-bol))
7187 (when (looking-at org-complex-heading-regexp)
7188 (setq txt (match-string 4)
7189 re (concat "^" (regexp-quote
7190 (buffer-substring (match-beginning 1)
7191 (match-end 4)))))
7192 (if (match-end 5) (setq re (concat re "[ \t]+"
7193 (regexp-quote
7194 (match-string 5)))))
7195 (setq re (concat re "[ \t]*$"))
7196 (when org-refile-use-outline-path
7197 (setq txt (mapconcat 'identity
7198 (append
7199 (if (eq org-refile-use-outline-path 'file)
7200 (list (file-name-nondirectory
7201 (buffer-file-name (buffer-base-buffer))))
7202 (if (eq org-refile-use-outline-path 'full-file-path)
7203 (list (buffer-file-name (buffer-base-buffer)))))
7204 (org-get-outline-path)
7205 (list txt))
7206 "/")))
7207 (push (list txt f re (point)) targets))
7208 (goto-char (point-at-eol))))))))
7209 (nreverse targets))))
7211 (defun org-get-outline-path ()
7212 "Return the outline path to the current entry, as a list."
7213 (let (rtn)
7214 (save-excursion
7215 (while (org-up-heading-safe)
7216 (when (looking-at org-complex-heading-regexp)
7217 (push (org-match-string-no-properties 4) rtn)))
7218 rtn)))
7220 (defvar org-refile-history nil
7221 "History for refiling operations.")
7223 (defun org-refile (&optional goto default-buffer)
7224 "Move the entry at point to another heading.
7225 The list of target headings is compiled using the information in
7226 `org-refile-targets', which see. This list is created before each use
7227 and will therefore always be up-to-date.
7229 At the target location, the entry is filed as a subitem of the target heading.
7230 Depending on `org-reverse-note-order', the new subitem will either be the
7231 first of the last subitem.
7233 With prefix arg GOTO, the command will only visit the target location,
7234 not actually move anything.
7235 With a double prefix `C-c C-c', go to the location where the last refiling
7236 operation has put the subtree."
7237 (interactive "P")
7238 (let* ((cbuf (current-buffer))
7239 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7240 pos it nbuf file re level reversed)
7241 (if (equal goto '(16))
7242 (org-refile-goto-last-stored)
7243 (when (setq it (org-refile-get-location
7244 (if goto "Goto: " "Refile to: ") default-buffer))
7245 (setq file (nth 1 it)
7246 re (nth 2 it)
7247 pos (nth 3 it))
7248 (setq nbuf (or (find-buffer-visiting file)
7249 (find-file-noselect file)))
7250 (if goto
7251 (progn
7252 (switch-to-buffer nbuf)
7253 (goto-char pos)
7254 (org-show-context 'org-goto))
7255 (org-copy-special)
7256 (save-excursion
7257 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7258 (find-file-noselect file))))
7259 (setq reversed (org-notes-order-reversed-p))
7260 (save-excursion
7261 (save-restriction
7262 (widen)
7263 (goto-char pos)
7264 (looking-at outline-regexp)
7265 (setq level (org-get-valid-level (funcall outline-level) 1))
7266 (goto-char
7267 (if reversed
7268 (outline-next-heading)
7269 (or (save-excursion (outline-get-next-sibling))
7270 (org-end-of-subtree t t)
7271 (point-max))))
7272 (bookmark-set "org-refile-last-stored")
7273 (org-paste-subtree level))))
7274 (org-cut-special)
7275 (message "Entry refiled to \"%s\"" (car it)))))))
7277 (defun org-refile-goto-last-stored ()
7278 "Go to the location where the last refile was stored."
7279 (interactive)
7280 (bookmark-jump "org-refile-last-stored")
7281 (message "This is the location of the last refile"))
7283 (defun org-refile-get-location (&optional prompt default-buffer)
7284 "Prompt the user for a refile location, using PROMPT."
7285 (let ((org-refile-targets org-refile-targets)
7286 (org-refile-use-outline-path org-refile-use-outline-path))
7287 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7288 (unless org-refile-target-table
7289 (error "No refile targets"))
7290 (let* ((cbuf (current-buffer))
7291 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7292 (fname (and filename (file-truename filename)))
7293 (tbl (mapcar
7294 (lambda (x)
7295 (if (not (equal fname (file-truename (nth 1 x))))
7296 (cons (concat (car x) " (" (file-name-nondirectory
7297 (nth 1 x)) ")")
7298 (cdr x))
7300 org-refile-target-table))
7301 (completion-ignore-case t))
7302 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7303 tbl)))
7305 ;;;; Dynamic blocks
7307 (defun org-find-dblock (name)
7308 "Find the first dynamic block with name NAME in the buffer.
7309 If not found, stay at current position and return nil."
7310 (let (pos)
7311 (save-excursion
7312 (goto-char (point-min))
7313 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7314 nil t)
7315 (match-beginning 0))))
7316 (if pos (goto-char pos))
7317 pos))
7319 (defconst org-dblock-start-re
7320 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7321 "Matches the startline of a dynamic block, with parameters.")
7323 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7324 "Matches the end of a dyhamic block.")
7326 (defun org-create-dblock (plist)
7327 "Create a dynamic block section, with parameters taken from PLIST.
7328 PLIST must containe a :name entry which is used as name of the block."
7329 (unless (bolp) (newline))
7330 (let ((name (plist-get plist :name)))
7331 (insert "#+BEGIN: " name)
7332 (while plist
7333 (if (eq (car plist) :name)
7334 (setq plist (cddr plist))
7335 (insert " " (prin1-to-string (pop plist)))))
7336 (insert "\n\n#+END:\n")
7337 (beginning-of-line -2)))
7339 (defun org-prepare-dblock ()
7340 "Prepare dynamic block for refresh.
7341 This empties the block, puts the cursor at the insert position and returns
7342 the property list including an extra property :name with the block name."
7343 (unless (looking-at org-dblock-start-re)
7344 (error "Not at a dynamic block"))
7345 (let* ((begdel (1+ (match-end 0)))
7346 (name (org-no-properties (match-string 1)))
7347 (params (append (list :name name)
7348 (read (concat "(" (match-string 3) ")")))))
7349 (unless (re-search-forward org-dblock-end-re nil t)
7350 (error "Dynamic block not terminated"))
7351 (setq params
7352 (append params
7353 (list :content (buffer-substring
7354 begdel (match-beginning 0)))))
7355 (delete-region begdel (match-beginning 0))
7356 (goto-char begdel)
7357 (open-line 1)
7358 params))
7360 (defun org-map-dblocks (&optional command)
7361 "Apply COMMAND to all dynamic blocks in the current buffer.
7362 If COMMAND is not given, use `org-update-dblock'."
7363 (let ((cmd (or command 'org-update-dblock))
7364 pos)
7365 (save-excursion
7366 (goto-char (point-min))
7367 (while (re-search-forward org-dblock-start-re nil t)
7368 (goto-char (setq pos (match-beginning 0)))
7369 (condition-case nil
7370 (funcall cmd)
7371 (error (message "Error during update of dynamic block")))
7372 (goto-char pos)
7373 (unless (re-search-forward org-dblock-end-re nil t)
7374 (error "Dynamic block not terminated"))))))
7376 (defun org-dblock-update (&optional arg)
7377 "User command for updating dynamic blocks.
7378 Update the dynamic block at point. With prefix ARG, update all dynamic
7379 blocks in the buffer."
7380 (interactive "P")
7381 (if arg
7382 (org-update-all-dblocks)
7383 (or (looking-at org-dblock-start-re)
7384 (org-beginning-of-dblock))
7385 (org-update-dblock)))
7387 (defun org-update-dblock ()
7388 "Update the dynamic block at point
7389 This means to empty the block, parse for parameters and then call
7390 the correct writing function."
7391 (save-window-excursion
7392 (let* ((pos (point))
7393 (line (org-current-line))
7394 (params (org-prepare-dblock))
7395 (name (plist-get params :name))
7396 (cmd (intern (concat "org-dblock-write:" name))))
7397 (message "Updating dynamic block `%s' at line %d..." name line)
7398 (funcall cmd params)
7399 (message "Updating dynamic block `%s' at line %d...done" name line)
7400 (goto-char pos))))
7402 (defun org-beginning-of-dblock ()
7403 "Find the beginning of the dynamic block at point.
7404 Error if there is no scuh block at point."
7405 (let ((pos (point))
7406 beg)
7407 (end-of-line 1)
7408 (if (and (re-search-backward org-dblock-start-re nil t)
7409 (setq beg (match-beginning 0))
7410 (re-search-forward org-dblock-end-re nil t)
7411 (> (match-end 0) pos))
7412 (goto-char beg)
7413 (goto-char pos)
7414 (error "Not in a dynamic block"))))
7416 (defun org-update-all-dblocks ()
7417 "Update all dynamic blocks in the buffer.
7418 This function can be used in a hook."
7419 (when (org-mode-p)
7420 (org-map-dblocks 'org-update-dblock)))
7423 ;;;; Completion
7425 (defconst org-additional-option-like-keywords
7426 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7427 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7428 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7430 (defun org-complete (&optional arg)
7431 "Perform completion on word at point.
7432 At the beginning of a headline, this completes TODO keywords as given in
7433 `org-todo-keywords'.
7434 If the current word is preceded by a backslash, completes the TeX symbols
7435 that are supported for HTML support.
7436 If the current word is preceded by \"#+\", completes special words for
7437 setting file options.
7438 In the line after \"#+STARTUP:, complete valid keywords.\"
7439 At all other locations, this simply calls the value of
7440 `org-completion-fallback-command'."
7441 (interactive "P")
7442 (org-without-partial-completion
7443 (catch 'exit
7444 (let* ((end (point))
7445 (beg1 (save-excursion
7446 (skip-chars-backward (org-re "[:alnum:]_@"))
7447 (point)))
7448 (beg (save-excursion
7449 (skip-chars-backward "a-zA-Z0-9_:$")
7450 (point)))
7451 (confirm (lambda (x) (stringp (car x))))
7452 (searchhead (equal (char-before beg) ?*))
7453 (tag (and (equal (char-before beg1) ?:)
7454 (equal (char-after (point-at-bol)) ?*)))
7455 (prop (and (equal (char-before beg1) ?:)
7456 (not (equal (char-after (point-at-bol)) ?*))))
7457 (texp (equal (char-before beg) ?\\))
7458 (link (equal (char-before beg) ?\[))
7459 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7460 beg)
7461 "#+"))
7462 (startup (string-match "^#\\+STARTUP:.*"
7463 (buffer-substring (point-at-bol) (point))))
7464 (completion-ignore-case opt)
7465 (type nil)
7466 (tbl nil)
7467 (table (cond
7468 (opt
7469 (setq type :opt)
7470 (require 'org-exp)
7471 (append
7472 (mapcar
7473 (lambda (x)
7474 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7475 (cons (match-string 2 x) (match-string 1 x)))
7476 (org-split-string (org-get-current-options) "\n"))
7477 (mapcar 'list org-additional-option-like-keywords)))
7478 (startup
7479 (setq type :startup)
7480 org-startup-options)
7481 (link (append org-link-abbrev-alist-local
7482 org-link-abbrev-alist))
7483 (texp
7484 (setq type :tex)
7485 org-html-entities)
7486 ((string-match "\\`\\*+[ \t]+\\'"
7487 (buffer-substring (point-at-bol) beg))
7488 (setq type :todo)
7489 (mapcar 'list org-todo-keywords-1))
7490 (searchhead
7491 (setq type :searchhead)
7492 (save-excursion
7493 (goto-char (point-min))
7494 (while (re-search-forward org-todo-line-regexp nil t)
7495 (push (list
7496 (org-make-org-heading-search-string
7497 (match-string 3) t))
7498 tbl)))
7499 tbl)
7500 (tag (setq type :tag beg beg1)
7501 (or org-tag-alist (org-get-buffer-tags)))
7502 (prop (setq type :prop beg beg1)
7503 (mapcar 'list (org-buffer-property-keys nil t t)))
7504 (t (progn
7505 (call-interactively org-completion-fallback-command)
7506 (throw 'exit nil)))))
7507 (pattern (buffer-substring-no-properties beg end))
7508 (completion (try-completion pattern table confirm)))
7509 (cond ((eq completion t)
7510 (if (not (assoc (upcase pattern) table))
7511 (message "Already complete")
7512 (if (and (equal type :opt)
7513 (not (member (car (assoc (upcase pattern) table))
7514 org-additional-option-like-keywords)))
7515 (insert (substring (cdr (assoc (upcase pattern) table))
7516 (length pattern)))
7517 (if (memq type '(:tag :prop)) (insert ":")))))
7518 ((null completion)
7519 (message "Can't find completion for \"%s\"" pattern)
7520 (ding))
7521 ((not (string= pattern completion))
7522 (delete-region beg end)
7523 (if (string-match " +$" completion)
7524 (setq completion (replace-match "" t t completion)))
7525 (insert completion)
7526 (if (get-buffer-window "*Completions*")
7527 (delete-window (get-buffer-window "*Completions*")))
7528 (if (assoc completion table)
7529 (if (eq type :todo) (insert " ")
7530 (if (memq type '(:tag :prop)) (insert ":"))))
7531 (if (and (equal type :opt) (assoc completion table))
7532 (message "%s" (substitute-command-keys
7533 "Press \\[org-complete] again to insert example settings"))))
7535 (message "Making completion list...")
7536 (let ((list (sort (all-completions pattern table confirm)
7537 'string<)))
7538 (with-output-to-temp-buffer "*Completions*"
7539 (condition-case nil
7540 ;; Protection needed for XEmacs and emacs 21
7541 (display-completion-list list pattern)
7542 (error (display-completion-list list)))))
7543 (message "Making completion list...%s" "done")))))))
7545 ;;;; TODO, DEADLINE, Comments
7547 (defun org-toggle-comment ()
7548 "Change the COMMENT state of an entry."
7549 (interactive)
7550 (save-excursion
7551 (org-back-to-heading)
7552 (let (case-fold-search)
7553 (if (looking-at (concat outline-regexp
7554 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7555 (replace-match "" t t nil 1)
7556 (if (looking-at outline-regexp)
7557 (progn
7558 (goto-char (match-end 0))
7559 (insert org-comment-string " ")))))))
7561 (defvar org-last-todo-state-is-todo nil
7562 "This is non-nil when the last TODO state change led to a TODO state.
7563 If the last change removed the TODO tag or switched to DONE, then
7564 this is nil.")
7566 (defvar org-setting-tags nil) ; dynamically skiped
7568 (defun org-parse-local-options (string var)
7569 "Parse STRING for startup setting relevant for variable VAR."
7570 (let ((rtn (symbol-value var))
7571 e opts)
7572 (save-match-data
7573 (if (or (not string) (not (string-match "\\S-" string)))
7575 (setq opts (delq nil (mapcar (lambda (x)
7576 (setq e (assoc x org-startup-options))
7577 (if (eq (nth 1 e) var) e nil))
7578 (org-split-string string "[ \t]+"))))
7579 (if (not opts)
7581 (setq rtn nil)
7582 (while (setq e (pop opts))
7583 (if (not (nth 3 e))
7584 (setq rtn (nth 2 e))
7585 (if (not (listp rtn)) (setq rtn nil))
7586 (push (nth 2 e) rtn)))
7587 rtn)))))
7589 (defvar org-blocker-hook nil
7590 "Hook for functions that are allowed to block a state change.
7592 Each function gets as its single argument a property list, see
7593 `org-trigger-hook' for more information about this list.
7595 If any of the functions in this hook returns nil, the state change
7596 is blocked.")
7598 (defvar org-trigger-hook nil
7599 "Hook for functions that are triggered by a state change.
7601 Each function gets as its single argument a property list with at least
7602 the following elements:
7604 (:type type-of-change :position pos-at-entry-start
7605 :from old-state :to new-state)
7607 Depending on the type, more properties may be present.
7609 This mechanism is currently implemented for:
7611 TODO state changes
7612 ------------------
7613 :type todo-state-change
7614 :from previous state (keyword as a string), or nil
7615 :to new state (keyword as a string), or nil")
7618 (defun org-todo (&optional arg)
7619 "Change the TODO state of an item.
7620 The state of an item is given by a keyword at the start of the heading,
7621 like
7622 *** TODO Write paper
7623 *** DONE Call mom
7625 The different keywords are specified in the variable `org-todo-keywords'.
7626 By default the available states are \"TODO\" and \"DONE\".
7627 So for this example: when the item starts with TODO, it is changed to DONE.
7628 When it starts with DONE, the DONE is removed. And when neither TODO nor
7629 DONE are present, add TODO at the beginning of the heading.
7631 With C-u prefix arg, use completion to determine the new state.
7632 With numeric prefix arg, switch to that state.
7634 For calling through lisp, arg is also interpreted in the following way:
7635 'none -> empty state
7636 \"\"(empty string) -> switch to empty state
7637 'done -> switch to DONE
7638 'nextset -> switch to the next set of keywords
7639 'previousset -> switch to the previous set of keywords
7640 \"WAITING\" -> switch to the specified keyword, but only if it
7641 really is a member of `org-todo-keywords'."
7642 (interactive "P")
7643 (save-excursion
7644 (catch 'exit
7645 (org-back-to-heading)
7646 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7647 (or (looking-at (concat " +" org-todo-regexp " *"))
7648 (looking-at " *"))
7649 (let* ((match-data (match-data))
7650 (startpos (point-at-bol))
7651 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7652 (org-log-done org-log-done)
7653 (org-log-repeat org-log-repeat)
7654 (org-todo-log-states org-todo-log-states)
7655 (this (match-string 1))
7656 (hl-pos (match-beginning 0))
7657 (head (org-get-todo-sequence-head this))
7658 (ass (assoc head org-todo-kwd-alist))
7659 (interpret (nth 1 ass))
7660 (done-word (nth 3 ass))
7661 (final-done-word (nth 4 ass))
7662 (last-state (or this ""))
7663 (completion-ignore-case t)
7664 (member (member this org-todo-keywords-1))
7665 (tail (cdr member))
7666 (state (cond
7667 ((and org-todo-key-trigger
7668 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7669 (and (not arg) org-use-fast-todo-selection
7670 (not (eq org-use-fast-todo-selection 'prefix)))))
7671 ;; Use fast selection
7672 (org-fast-todo-selection))
7673 ((and (equal arg '(4))
7674 (or (not org-use-fast-todo-selection)
7675 (not org-todo-key-trigger)))
7676 ;; Read a state with completion
7677 (completing-read "State: " (mapcar (lambda(x) (list x))
7678 org-todo-keywords-1)
7679 nil t))
7680 ((eq arg 'right)
7681 (if this
7682 (if tail (car tail) nil)
7683 (car org-todo-keywords-1)))
7684 ((eq arg 'left)
7685 (if (equal member org-todo-keywords-1)
7687 (if this
7688 (nth (- (length org-todo-keywords-1) (length tail) 2)
7689 org-todo-keywords-1)
7690 (org-last org-todo-keywords-1))))
7691 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7692 (setq arg nil))) ; hack to fall back to cycling
7693 (arg
7694 ;; user or caller requests a specific state
7695 (cond
7696 ((equal arg "") nil)
7697 ((eq arg 'none) nil)
7698 ((eq arg 'done) (or done-word (car org-done-keywords)))
7699 ((eq arg 'nextset)
7700 (or (car (cdr (member head org-todo-heads)))
7701 (car org-todo-heads)))
7702 ((eq arg 'previousset)
7703 (let ((org-todo-heads (reverse org-todo-heads)))
7704 (or (car (cdr (member head org-todo-heads)))
7705 (car org-todo-heads))))
7706 ((car (member arg org-todo-keywords-1)))
7707 ((nth (1- (prefix-numeric-value arg))
7708 org-todo-keywords-1))))
7709 ((null member) (or head (car org-todo-keywords-1)))
7710 ((equal this final-done-word) nil) ;; -> make empty
7711 ((null tail) nil) ;; -> first entry
7712 ((eq interpret 'sequence)
7713 (car tail))
7714 ((memq interpret '(type priority))
7715 (if (eq this-command last-command)
7716 (car tail)
7717 (if (> (length tail) 0)
7718 (or done-word (car org-done-keywords))
7719 nil)))
7720 (t nil)))
7721 (next (if state (concat " " state " ") " "))
7722 (change-plist (list :type 'todo-state-change :from this :to state
7723 :position startpos))
7724 dolog now-done-p)
7725 (when org-blocker-hook
7726 (unless (save-excursion
7727 (save-match-data
7728 (run-hook-with-args-until-failure
7729 'org-blocker-hook change-plist)))
7730 (if (interactive-p)
7731 (error "TODO state change from %s to %s blocked" this state)
7732 ;; fail silently
7733 (message "TODO state change from %s to %s blocked" this state)
7734 (throw 'exit nil))))
7735 (store-match-data match-data)
7736 (replace-match next t t)
7737 (unless (pos-visible-in-window-p hl-pos)
7738 (message "TODO state changed to %s" (org-trim next)))
7739 (unless head
7740 (setq head (org-get-todo-sequence-head state)
7741 ass (assoc head org-todo-kwd-alist)
7742 interpret (nth 1 ass)
7743 done-word (nth 3 ass)
7744 final-done-word (nth 4 ass)))
7745 (when (memq arg '(nextset previousset))
7746 (message "Keyword-Set %d/%d: %s"
7747 (- (length org-todo-sets) -1
7748 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7749 (length org-todo-sets)
7750 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7751 (setq org-last-todo-state-is-todo
7752 (not (member state org-done-keywords)))
7753 (setq now-done-p (and (member state org-done-keywords)
7754 (not (member this org-done-keywords))))
7755 (and logging (org-local-logging logging))
7756 (when (and (or org-todo-log-states org-log-done)
7757 (not (memq arg '(nextset previousset))))
7758 ;; we need to look at recording a time and note
7759 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7760 (nth 2 (assoc this org-todo-log-states))))
7761 (when (and state
7762 (member state org-not-done-keywords)
7763 (not (member this org-not-done-keywords)))
7764 ;; This is now a todo state and was not one before
7765 ;; If there was a CLOSED time stamp, get rid of it.
7766 (org-add-planning-info nil nil 'closed))
7767 (when (and now-done-p org-log-done)
7768 ;; It is now done, and it was not done before
7769 (org-add-planning-info 'closed (org-current-time))
7770 (if (and (not dolog) (eq 'note org-log-done))
7771 (org-add-log-setup 'done state 'findpos 'note)))
7772 (when (and state dolog)
7773 ;; This is a non-nil state, and we need to log it
7774 (org-add-log-setup 'state state 'findpos dolog)))
7775 ;; Fixup tag positioning
7776 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7777 (run-hooks 'org-after-todo-state-change-hook)
7778 (if (and arg (not (member state org-done-keywords)))
7779 (setq head (org-get-todo-sequence-head state)))
7780 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7781 ;; Do we need to trigger a repeat?
7782 (when now-done-p (org-auto-repeat-maybe state))
7783 ;; Fixup cursor location if close to the keyword
7784 (if (and (outline-on-heading-p)
7785 (not (bolp))
7786 (save-excursion (beginning-of-line 1)
7787 (looking-at org-todo-line-regexp))
7788 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7789 (progn
7790 (goto-char (or (match-end 2) (match-end 1)))
7791 (just-one-space)))
7792 (when org-trigger-hook
7793 (save-excursion
7794 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7796 (defun org-local-logging (value)
7797 "Get logging settings from a property VALUE."
7798 (let* (words w a)
7799 ;; directly set the variables, they are already local.
7800 (setq org-log-done nil
7801 org-log-repeat nil
7802 org-todo-log-states nil)
7803 (setq words (org-split-string value))
7804 (while (setq w (pop words))
7805 (cond
7806 ((setq a (assoc w org-startup-options))
7807 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7808 (set (nth 1 a) (nth 2 a))))
7809 ((setq a (org-extract-log-state-settings w))
7810 (and (member (car a) org-todo-keywords-1)
7811 (push a org-todo-log-states)))))))
7813 (defun org-get-todo-sequence-head (kwd)
7814 "Return the head of the TODO sequence to which KWD belongs.
7815 If KWD is not set, check if there is a text property remembering the
7816 right sequence."
7817 (let (p)
7818 (cond
7819 ((not kwd)
7820 (or (get-text-property (point-at-bol) 'org-todo-head)
7821 (progn
7822 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7823 nil (point-at-eol)))
7824 (get-text-property p 'org-todo-head))))
7825 ((not (member kwd org-todo-keywords-1))
7826 (car org-todo-keywords-1))
7827 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7829 (defun org-fast-todo-selection ()
7830 "Fast TODO keyword selection with single keys.
7831 Returns the new TODO keyword, or nil if no state change should occur."
7832 (let* ((fulltable org-todo-key-alist)
7833 (done-keywords org-done-keywords) ;; needed for the faces.
7834 (maxlen (apply 'max (mapcar
7835 (lambda (x)
7836 (if (stringp (car x)) (string-width (car x)) 0))
7837 fulltable)))
7838 (expert nil)
7839 (fwidth (+ maxlen 3 1 3))
7840 (ncol (/ (- (window-width) 4) fwidth))
7841 tg cnt e c tbl
7842 groups ingroup)
7843 (save-window-excursion
7844 (if expert
7845 (set-buffer (get-buffer-create " *Org todo*"))
7846 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7847 (erase-buffer)
7848 (org-set-local 'org-done-keywords done-keywords)
7849 (setq tbl fulltable cnt 0)
7850 (while (setq e (pop tbl))
7851 (cond
7852 ((equal e '(:startgroup))
7853 (push '() groups) (setq ingroup t)
7854 (when (not (= cnt 0))
7855 (setq cnt 0)
7856 (insert "\n"))
7857 (insert "{ "))
7858 ((equal e '(:endgroup))
7859 (setq ingroup nil cnt 0)
7860 (insert "}\n"))
7862 (setq tg (car e) c (cdr e))
7863 (if ingroup (push tg (car groups)))
7864 (setq tg (org-add-props tg nil 'face
7865 (org-get-todo-face tg)))
7866 (if (and (= cnt 0) (not ingroup)) (insert " "))
7867 (insert "[" c "] " tg (make-string
7868 (- fwidth 4 (length tg)) ?\ ))
7869 (when (= (setq cnt (1+ cnt)) ncol)
7870 (insert "\n")
7871 (if ingroup (insert " "))
7872 (setq cnt 0)))))
7873 (insert "\n")
7874 (goto-char (point-min))
7875 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7876 (fit-window-to-buffer))
7877 (message "[a-z..]:Set [SPC]:clear")
7878 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7879 (cond
7880 ((or (= c ?\C-g)
7881 (and (= c ?q) (not (rassoc c fulltable))))
7882 (setq quit-flag t))
7883 ((= c ?\ ) nil)
7884 ((setq e (rassoc c fulltable) tg (car e))
7886 (t (setq quit-flag t))))))
7888 (defun org-entry-is-todo-p ()
7889 (member (org-get-todo-state) org-not-done-keywords))
7891 (defun org-entry-is-done-p ()
7892 (member (org-get-todo-state) org-done-keywords))
7894 (defun org-get-todo-state ()
7895 (save-excursion
7896 (org-back-to-heading t)
7897 (and (looking-at org-todo-line-regexp)
7898 (match-end 2)
7899 (match-string 2))))
7901 (defun org-at-date-range-p (&optional inactive-ok)
7902 "Is the cursor inside a date range?"
7903 (interactive)
7904 (save-excursion
7905 (catch 'exit
7906 (let ((pos (point)))
7907 (skip-chars-backward "^[<\r\n")
7908 (skip-chars-backward "<[")
7909 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7910 (>= (match-end 0) pos)
7911 (throw 'exit t))
7912 (skip-chars-backward "^<[\r\n")
7913 (skip-chars-backward "<[")
7914 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7915 (>= (match-end 0) pos)
7916 (throw 'exit t)))
7917 nil)))
7919 (defun org-get-repeat ()
7920 "Check if tere is a deadline/schedule with repeater in this entry."
7921 (save-match-data
7922 (save-excursion
7923 (org-back-to-heading t)
7924 (if (re-search-forward
7925 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
7926 (match-string 1)))))
7928 (defvar org-last-changed-timestamp)
7929 (defvar org-log-post-message)
7930 (defvar org-log-note-purpose)
7931 (defvar org-log-note-how)
7932 (defun org-auto-repeat-maybe (done-word)
7933 "Check if the current headline contains a repeated deadline/schedule.
7934 If yes, set TODO state back to what it was and change the base date
7935 of repeating deadline/scheduled time stamps to new date.
7936 This function is run automatically after each state change to a DONE state."
7937 ;; last-state is dynamically scoped into this function
7938 (let* ((repeat (org-get-repeat))
7939 (aa (assoc last-state org-todo-kwd-alist))
7940 (interpret (nth 1 aa))
7941 (head (nth 2 aa))
7942 (whata '(("d" . day) ("m" . month) ("y" . year)))
7943 (msg "Entry repeats: ")
7944 (org-log-done nil)
7945 (org-todo-log-states nil)
7946 (nshiftmax 10) (nshift 0)
7947 re type n what ts mb0 time)
7948 (when repeat
7949 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
7950 (org-todo (if (eq interpret 'type) last-state head))
7951 (when org-log-repeat
7952 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
7953 (memq 'org-add-log-note post-command-hook))
7954 ;; OK, we are already setup for some record
7955 (if (eq org-log-repeat 'note)
7956 ;; make sure we take a note, not only a time stamp
7957 (setq org-log-note-how 'note))
7958 ;; Set up for taking a record
7959 (org-add-log-setup 'state (or done-word (car org-done-keywords))
7960 'findpos org-log-repeat)))
7961 (org-back-to-heading t)
7962 (org-add-planning-info nil nil 'closed)
7963 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
7964 org-deadline-time-regexp "\\)\\|\\("
7965 org-ts-regexp "\\)"))
7966 (while (re-search-forward
7967 re (save-excursion (outline-next-heading) (point)) t)
7968 (setq type (if (match-end 1) org-scheduled-string
7969 (if (match-end 3) org-deadline-string "Plain:"))
7970 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
7971 mb0 (match-beginning 0))
7972 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
7973 (setq n (string-to-number (match-string 2 ts))
7974 what (match-string 3 ts))
7975 (if (equal what "w") (setq n (* n 7) what "d"))
7976 ;; Preparation, see if we need to modify the start date for the change
7977 (when (match-end 1)
7978 (setq time (save-match-data (org-time-string-to-time ts)))
7979 (cond
7980 ((equal (match-string 1 ts) ".")
7981 ;; Shift starting date to today
7982 (org-timestamp-change
7983 (- (time-to-days (current-time)) (time-to-days time))
7984 'day))
7985 ((equal (match-string 1 ts) "+")
7986 (while (or (= nshift 0)
7987 (<= (time-to-days time) (time-to-days (current-time))))
7988 (when (= (incf nshift) nshiftmax)
7989 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
7990 (error "Abort")))
7991 (org-timestamp-change n (cdr (assoc what whata)))
7992 (org-at-timestamp-p t)
7993 (setq ts (match-string 1))
7994 (setq time (save-match-data (org-time-string-to-time ts))))
7995 (org-timestamp-change (- n) (cdr (assoc what whata)))
7996 ;; rematch, so that we have everything in place for the real shift
7997 (org-at-timestamp-p t)
7998 (setq ts (match-string 1))
7999 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8000 (org-timestamp-change n (cdr (assoc what whata)))
8001 (setq msg (concat msg type org-last-changed-timestamp " "))))
8002 (setq org-log-post-message msg)
8003 (message "%s" msg))))
8005 (defun org-show-todo-tree (arg)
8006 "Make a compact tree which shows all headlines marked with TODO.
8007 The tree will show the lines where the regexp matches, and all higher
8008 headlines above the match.
8009 With a \\[universal-argument] prefix, also show the DONE entries.
8010 With a numeric prefix N, construct a sparse tree for the Nth element
8011 of `org-todo-keywords-1'."
8012 (interactive "P")
8013 (let ((case-fold-search nil)
8014 (kwd-re
8015 (cond ((null arg) org-not-done-regexp)
8016 ((equal arg '(4))
8017 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8018 (mapcar 'list org-todo-keywords-1))))
8019 (concat "\\("
8020 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8021 "\\)\\>")))
8022 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8023 (regexp-quote (nth (1- (prefix-numeric-value arg))
8024 org-todo-keywords-1)))
8025 (t (error "Invalid prefix argument: %s" arg)))))
8026 (message "%d TODO entries found"
8027 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8029 (defun org-deadline (&optional remove)
8030 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8031 With argument REMOVE, remove any deadline from the item."
8032 (interactive "P")
8033 (if remove
8034 (progn
8035 (org-remove-timestamp-with-keyword org-deadline-string)
8036 (message "Item no longer has a deadline."))
8037 (org-add-planning-info 'deadline nil 'closed)))
8039 (defun org-schedule (&optional remove)
8040 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8041 With argument REMOVE, remove any scheduling date from the item."
8042 (interactive "P")
8043 (if remove
8044 (progn
8045 (org-remove-timestamp-with-keyword org-scheduled-string)
8046 (message "Item is no longer scheduled."))
8047 (org-add-planning-info 'scheduled nil 'closed)))
8049 (defun org-remove-timestamp-with-keyword (keyword)
8050 "Remove all time stamps with KEYWORD in the current entry."
8051 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8052 beg)
8053 (save-excursion
8054 (org-back-to-heading t)
8055 (setq beg (point))
8056 (org-end-of-subtree t t)
8057 (while (re-search-backward re beg t)
8058 (replace-match "")
8059 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8060 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8062 (defun org-add-planning-info (what &optional time &rest remove)
8063 "Insert new timestamp with keyword in the line directly after the headline.
8064 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8065 If non is given, the user is prompted for a date.
8066 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8067 be removed."
8068 (interactive)
8069 (let (org-time-was-given org-end-time-was-given ts
8070 end default-time default-input)
8072 (when (and (not time) (memq what '(scheduled deadline)))
8073 ;; Try to get a default date/time from existing timestamp
8074 (save-excursion
8075 (org-back-to-heading t)
8076 (setq end (save-excursion (outline-next-heading) (point)))
8077 (when (re-search-forward (if (eq what 'scheduled)
8078 org-scheduled-time-regexp
8079 org-deadline-time-regexp)
8080 end t)
8081 (setq ts (match-string 1)
8082 default-time
8083 (apply 'encode-time (org-parse-time-string ts))
8084 default-input (and ts (org-get-compact-tod ts))))))
8085 (when what
8086 ;; If necessary, get the time from the user
8087 (setq time (or time (org-read-date nil 'to-time nil nil
8088 default-time default-input))))
8090 (when (and org-insert-labeled-timestamps-at-point
8091 (member what '(scheduled deadline)))
8092 (insert
8093 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8094 (org-insert-time-stamp time org-time-was-given
8095 nil nil nil (list org-end-time-was-given))
8096 (setq what nil))
8097 (save-excursion
8098 (save-restriction
8099 (let (col list elt ts buffer-invisibility-spec)
8100 (org-back-to-heading t)
8101 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8102 (goto-char (match-end 1))
8103 (setq col (current-column))
8104 (goto-char (match-end 0))
8105 (if (eobp) (insert "\n") (forward-char 1))
8106 (if (and (not (looking-at outline-regexp))
8107 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8108 "[^\r\n]*"))
8109 (not (equal (match-string 1) org-clock-string)))
8110 (narrow-to-region (match-beginning 0) (match-end 0))
8111 (insert-before-markers "\n")
8112 (backward-char 1)
8113 (narrow-to-region (point) (point))
8114 (indent-to-column col))
8115 ;; Check if we have to remove something.
8116 (setq list (cons what remove))
8117 (while list
8118 (setq elt (pop list))
8119 (goto-char (point-min))
8120 (when (or (and (eq elt 'scheduled)
8121 (re-search-forward org-scheduled-time-regexp nil t))
8122 (and (eq elt 'deadline)
8123 (re-search-forward org-deadline-time-regexp nil t))
8124 (and (eq elt 'closed)
8125 (re-search-forward org-closed-time-regexp nil t)))
8126 (replace-match "")
8127 (if (looking-at "--+<[^>]+>") (replace-match ""))
8128 (if (looking-at " +") (replace-match ""))))
8129 (goto-char (point-max))
8130 (when what
8131 (insert
8132 (if (not (equal (char-before) ?\ )) " " "")
8133 (cond ((eq what 'scheduled) org-scheduled-string)
8134 ((eq what 'deadline) org-deadline-string)
8135 ((eq what 'closed) org-closed-string))
8136 " ")
8137 (setq ts (org-insert-time-stamp
8138 time
8139 (or org-time-was-given
8140 (and (eq what 'closed) org-log-done-with-time))
8141 (eq what 'closed)
8142 nil nil (list org-end-time-was-given)))
8143 (end-of-line 1))
8144 (goto-char (point-min))
8145 (widen)
8146 (if (looking-at "[ \t]+\r?\n")
8147 (replace-match ""))
8148 ts)))))
8150 (defvar org-log-note-marker (make-marker))
8151 (defvar org-log-note-purpose nil)
8152 (defvar org-log-note-state nil)
8153 (defvar org-log-note-how nil)
8154 (defvar org-log-note-window-configuration nil)
8155 (defvar org-log-note-return-to (make-marker))
8156 (defvar org-log-post-message nil
8157 "Message to be displayed after a log note has been stored.
8158 The auto-repeater uses this.")
8160 (defun org-add-note ()
8161 "Add a note to the current entry.
8162 This is done in the same way as adding a state change note."
8163 (interactive)
8164 (org-add-log-setup 'note nil t nil))
8166 (defun org-add-log-setup (&optional purpose state findpos how)
8167 "Set up the post command hook to take a note.
8168 If this is about to TODO state change, the new state is expected in STATE.
8169 When FINDPOS is non-nil, find the correct position for the note in
8170 the current entry. If not, assume that it can be inserted at point."
8171 (save-excursion
8172 (when findpos
8173 (org-back-to-heading t)
8174 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8175 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8176 "[^\r\n]*\\)?"))
8177 (goto-char (match-end 0))
8178 (unless org-log-states-order-reversed
8179 (and (= (char-after) ?\n) (forward-char 1))
8180 (org-skip-over-state-notes)
8181 (skip-chars-backward " \t\n\r")))
8182 (move-marker org-log-note-marker (point))
8183 (setq org-log-note-purpose purpose
8184 org-log-note-state state
8185 org-log-note-how how)
8186 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8188 (defun org-skip-over-state-notes ()
8189 "Skip past the list of State notes in an entry."
8190 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8191 (while (looking-at "[ \t]*- State")
8192 (condition-case nil
8193 (org-next-item)
8194 (error (org-end-of-item)))))
8196 (defun org-add-log-note (&optional purpose)
8197 "Pop up a window for taking a note, and add this note later at point."
8198 (remove-hook 'post-command-hook 'org-add-log-note)
8199 (setq org-log-note-window-configuration (current-window-configuration))
8200 (delete-other-windows)
8201 (move-marker org-log-note-return-to (point))
8202 (switch-to-buffer (marker-buffer org-log-note-marker))
8203 (goto-char org-log-note-marker)
8204 (org-switch-to-buffer-other-window "*Org Note*")
8205 (erase-buffer)
8206 (if (memq org-log-note-how '(time state))
8207 (org-store-log-note)
8208 (let ((org-inhibit-startup t)) (org-mode))
8209 (insert (format "# Insert note for %s.
8210 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8211 (cond
8212 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8213 ((eq org-log-note-purpose 'done) "closed todo item")
8214 ((eq org-log-note-purpose 'state)
8215 (format "state change to \"%s\"" org-log-note-state))
8216 ((eq org-log-note-purpose 'note)
8217 "this entry")
8218 (t (error "This should not happen")))))
8219 (org-set-local 'org-finish-function 'org-store-log-note)))
8221 (defvar org-note-abort nil) ; dynamically scoped
8222 (defun org-store-log-note ()
8223 "Finish taking a log note, and insert it to where it belongs."
8224 (let ((txt (buffer-string))
8225 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8226 lines ind)
8227 (kill-buffer (current-buffer))
8228 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8229 (setq txt (replace-match "" t t txt)))
8230 (if (string-match "\\s-+\\'" txt)
8231 (setq txt (replace-match "" t t txt)))
8232 (setq lines (org-split-string txt "\n"))
8233 (when (and note (string-match "\\S-" note))
8234 (setq note
8235 (org-replace-escapes
8236 note
8237 (list (cons "%u" (user-login-name))
8238 (cons "%U" user-full-name)
8239 (cons "%t" (format-time-string
8240 (org-time-stamp-format 'long 'inactive)
8241 (current-time)))
8242 (cons "%s" (if org-log-note-state
8243 (concat "\"" org-log-note-state "\"")
8244 "")))))
8245 (if lines (setq note (concat note " \\\\")))
8246 (push note lines))
8247 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8248 (when lines
8249 (save-excursion
8250 (set-buffer (marker-buffer org-log-note-marker))
8251 (save-excursion
8252 (goto-char org-log-note-marker)
8253 (move-marker org-log-note-marker nil)
8254 (end-of-line 1)
8255 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8256 (indent-relative nil)
8257 (insert "- " (pop lines))
8258 (org-indent-line-function)
8259 (beginning-of-line 1)
8260 (looking-at "[ \t]*")
8261 (setq ind (concat (match-string 0) " "))
8262 (end-of-line 1)
8263 (while lines (insert "\n" ind (pop lines)))))))
8264 (set-window-configuration org-log-note-window-configuration)
8265 (with-current-buffer (marker-buffer org-log-note-return-to)
8266 (goto-char org-log-note-return-to))
8267 (move-marker org-log-note-return-to nil)
8268 (and org-log-post-message (message "%s" org-log-post-message)))
8270 (defun org-sparse-tree (&optional arg)
8271 "Create a sparse tree, prompt for the details.
8272 This command can create sparse trees. You first need to select the type
8273 of match used to create the tree:
8275 t Show entries with a specific TODO keyword.
8276 T Show entries selected by a tags match.
8277 p Enter a property name and its value (both with completion on existing
8278 names/values) and show entries with that property.
8279 r Show entries matching a regular expression
8280 d Show deadlines due within `org-deadline-warning-days'."
8281 (interactive "P")
8282 (let (ans kwd value)
8283 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8284 (setq ans (read-char-exclusive))
8285 (cond
8286 ((equal ans ?d)
8287 (call-interactively 'org-check-deadlines))
8288 ((equal ans ?b)
8289 (call-interactively 'org-check-before-date))
8290 ((equal ans ?t)
8291 (org-show-todo-tree '(4)))
8292 ((equal ans ?T)
8293 (call-interactively 'org-tags-sparse-tree))
8294 ((member ans '(?p ?P))
8295 (setq kwd (completing-read "Property: "
8296 (mapcar 'list (org-buffer-property-keys))))
8297 (setq value (completing-read "Value: "
8298 (mapcar 'list (org-property-values kwd))))
8299 (unless (string-match "\\`{.*}\\'" value)
8300 (setq value (concat "\"" value "\"")))
8301 (org-tags-sparse-tree arg (concat kwd "=" value)))
8302 ((member ans '(?r ?R ?/))
8303 (call-interactively 'org-occur))
8304 (t (error "No such sparse tree command \"%c\"" ans)))))
8306 (defvar org-occur-highlights nil
8307 "List of overlays used for occur matches.")
8308 (make-variable-buffer-local 'org-occur-highlights)
8309 (defvar org-occur-parameters nil
8310 "Parameters of the active org-occur calls.
8311 This is a list, each call to org-occur pushes as cons cell,
8312 containing the regular expression and the callback, onto the list.
8313 The list can contain several entries if `org-occur' has been called
8314 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8315 will only contain one set of parameters. When the highlights are
8316 removed (for example with `C-c C-c', or with the next edit (depending
8317 on `org-remove-highlights-with-change'), this variable is emptied
8318 as well.")
8319 (make-variable-buffer-local 'org-occur-parameters)
8321 (defun org-occur (regexp &optional keep-previous callback)
8322 "Make a compact tree which shows all matches of REGEXP.
8323 The tree will show the lines where the regexp matches, and all higher
8324 headlines above the match. It will also show the heading after the match,
8325 to make sure editing the matching entry is easy.
8326 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8327 call to `org-occur' will be kept, to allow stacking of calls to this
8328 command.
8329 If CALLBACK is non-nil, it is a function which is called to confirm
8330 that the match should indeed be shown."
8331 (interactive "sRegexp: \nP")
8332 (unless keep-previous
8333 (org-remove-occur-highlights nil nil t))
8334 (push (cons regexp callback) org-occur-parameters)
8335 (let ((cnt 0))
8336 (save-excursion
8337 (goto-char (point-min))
8338 (if (or (not keep-previous) ; do not want to keep
8339 (not org-occur-highlights)) ; no previous matches
8340 ;; hide everything
8341 (org-overview))
8342 (while (re-search-forward regexp nil t)
8343 (when (or (not callback)
8344 (save-match-data (funcall callback)))
8345 (setq cnt (1+ cnt))
8346 (when org-highlight-sparse-tree-matches
8347 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8348 (org-show-context 'occur-tree))))
8349 (when org-remove-highlights-with-change
8350 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8351 nil 'local))
8352 (unless org-sparse-tree-open-archived-trees
8353 (org-hide-archived-subtrees (point-min) (point-max)))
8354 (run-hooks 'org-occur-hook)
8355 (if (interactive-p)
8356 (message "%d match(es) for regexp %s" cnt regexp))
8357 cnt))
8359 (defun org-show-context (&optional key)
8360 "Make sure point and context and visible.
8361 How much context is shown depends upon the variables
8362 `org-show-hierarchy-above', `org-show-following-heading'. and
8363 `org-show-siblings'."
8364 (let ((heading-p (org-on-heading-p t))
8365 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8366 (following-p (org-get-alist-option org-show-following-heading key))
8367 (entry-p (org-get-alist-option org-show-entry-below key))
8368 (siblings-p (org-get-alist-option org-show-siblings key)))
8369 (catch 'exit
8370 ;; Show heading or entry text
8371 (if (and heading-p (not entry-p))
8372 (org-flag-heading nil) ; only show the heading
8373 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8374 (org-show-hidden-entry))) ; show entire entry
8375 (when following-p
8376 ;; Show next sibling, or heading below text
8377 (save-excursion
8378 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8379 (org-flag-heading nil))))
8380 (when siblings-p (org-show-siblings))
8381 (when hierarchy-p
8382 ;; show all higher headings, possibly with siblings
8383 (save-excursion
8384 (while (and (condition-case nil
8385 (progn (org-up-heading-all 1) t)
8386 (error nil))
8387 (not (bobp)))
8388 (org-flag-heading nil)
8389 (when siblings-p (org-show-siblings))))))))
8391 (defun org-reveal (&optional siblings)
8392 "Show current entry, hierarchy above it, and the following headline.
8393 This can be used to show a consistent set of context around locations
8394 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8395 not t for the search context.
8397 With optional argument SIBLINGS, on each level of the hierarchy all
8398 siblings are shown. This repairs the tree structure to what it would
8399 look like when opened with hierarchical calls to `org-cycle'."
8400 (interactive "P")
8401 (let ((org-show-hierarchy-above t)
8402 (org-show-following-heading t)
8403 (org-show-siblings (if siblings t org-show-siblings)))
8404 (org-show-context nil)))
8406 (defun org-highlight-new-match (beg end)
8407 "Highlight from BEG to END and mark the highlight is an occur headline."
8408 (let ((ov (org-make-overlay beg end)))
8409 (org-overlay-put ov 'face 'secondary-selection)
8410 (push ov org-occur-highlights)))
8412 (defun org-remove-occur-highlights (&optional beg end noremove)
8413 "Remove the occur highlights from the buffer.
8414 BEG and END are ignored. If NOREMOVE is nil, remove this function
8415 from the `before-change-functions' in the current buffer."
8416 (interactive)
8417 (unless org-inhibit-highlight-removal
8418 (mapc 'org-delete-overlay org-occur-highlights)
8419 (setq org-occur-highlights nil)
8420 (setq org-occur-parameters nil)
8421 (unless noremove
8422 (remove-hook 'before-change-functions
8423 'org-remove-occur-highlights 'local))))
8425 ;;;; Priorities
8427 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8428 "Regular expression matching the priority indicator.")
8430 (defvar org-remove-priority-next-time nil)
8432 (defun org-priority-up ()
8433 "Increase the priority of the current item."
8434 (interactive)
8435 (org-priority 'up))
8437 (defun org-priority-down ()
8438 "Decrease the priority of the current item."
8439 (interactive)
8440 (org-priority 'down))
8442 (defun org-priority (&optional action)
8443 "Change the priority of an item by ARG.
8444 ACTION can be `set', `up', `down', or a character."
8445 (interactive)
8446 (setq action (or action 'set))
8447 (let (current new news have remove)
8448 (save-excursion
8449 (org-back-to-heading)
8450 (if (looking-at org-priority-regexp)
8451 (setq current (string-to-char (match-string 2))
8452 have t)
8453 (setq current org-default-priority))
8454 (cond
8455 ((or (eq action 'set) (integerp action))
8456 (if (integerp action)
8457 (setq new action)
8458 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
8459 (setq new (read-char-exclusive)))
8460 (if (and (= (upcase org-highest-priority) org-highest-priority)
8461 (= (upcase org-lowest-priority) org-lowest-priority))
8462 (setq new (upcase new)))
8463 (cond ((equal new ?\ ) (setq remove t))
8464 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8465 (error "Priority must be between `%c' and `%c'"
8466 org-highest-priority org-lowest-priority))))
8467 ((eq action 'up)
8468 (if (and (not have) (eq last-command this-command))
8469 (setq new org-lowest-priority)
8470 (setq new (if (and org-priority-start-cycle-with-default (not have))
8471 org-default-priority (1- current)))))
8472 ((eq action 'down)
8473 (if (and (not have) (eq last-command this-command))
8474 (setq new org-highest-priority)
8475 (setq new (if (and org-priority-start-cycle-with-default (not have))
8476 org-default-priority (1+ current)))))
8477 (t (error "Invalid action")))
8478 (if (or (< (upcase new) org-highest-priority)
8479 (> (upcase new) org-lowest-priority))
8480 (setq remove t))
8481 (setq news (format "%c" new))
8482 (if have
8483 (if remove
8484 (replace-match "" t t nil 1)
8485 (replace-match news t t nil 2))
8486 (if remove
8487 (error "No priority cookie found in line")
8488 (looking-at org-todo-line-regexp)
8489 (if (match-end 2)
8490 (progn
8491 (goto-char (match-end 2))
8492 (insert " [#" news "]"))
8493 (goto-char (match-beginning 3))
8494 (insert "[#" news "] ")))))
8495 (org-preserve-lc (org-set-tags nil 'align))
8496 (if remove
8497 (message "Priority removed")
8498 (message "Priority of current item set to %s" news))))
8501 (defun org-get-priority (s)
8502 "Find priority cookie and return priority."
8503 (save-match-data
8504 (if (not (string-match org-priority-regexp s))
8505 (* 1000 (- org-lowest-priority org-default-priority))
8506 (* 1000 (- org-lowest-priority
8507 (string-to-char (match-string 2 s)))))))
8509 ;;;; Tags
8511 (defun org-scan-tags (action matcher &optional todo-only)
8512 "Scan headline tags with inheritance and produce output ACTION.
8513 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8514 evaluated, testing if a given set of tags qualifies a headline for
8515 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8516 are included in the output."
8517 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8518 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8519 (org-re
8520 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8521 (props (list 'face nil
8522 'done-face 'org-done
8523 'undone-face nil
8524 'mouse-face 'highlight
8525 'org-not-done-regexp org-not-done-regexp
8526 'org-todo-regexp org-todo-regexp
8527 'keymap org-agenda-keymap
8528 'help-echo
8529 (format "mouse-2 or RET jump to org file %s"
8530 (abbreviate-file-name
8531 (or (buffer-file-name (buffer-base-buffer))
8532 (buffer-name (buffer-base-buffer)))))))
8533 (case-fold-search nil)
8534 lspos
8535 tags tags-list tags-alist (llast 0) rtn level category i txt
8536 todo marker entry priority)
8537 (save-excursion
8538 (goto-char (point-min))
8539 (when (eq action 'sparse-tree)
8540 (org-overview)
8541 (org-remove-occur-highlights))
8542 (while (re-search-forward re nil t)
8543 (catch :skip
8544 (setq todo (if (match-end 1) (match-string 2))
8545 tags (if (match-end 4) (match-string 4)))
8546 (goto-char (setq lspos (1+ (match-beginning 0))))
8547 (setq level (org-reduced-level (funcall outline-level))
8548 category (org-get-category))
8549 (setq i llast llast level)
8550 ;; remove tag lists from same and sublevels
8551 (while (>= i level)
8552 (when (setq entry (assoc i tags-alist))
8553 (setq tags-alist (delete entry tags-alist)))
8554 (setq i (1- i)))
8555 ;; add the next tags
8556 (when tags
8557 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8558 tags-alist
8559 (cons (cons level tags) tags-alist)))
8560 ;; compile tags for current headline
8561 (setq tags-list
8562 (if org-use-tag-inheritance
8563 (apply 'append (mapcar 'cdr tags-alist))
8564 tags))
8565 (when (and tags org-use-tag-inheritance
8566 (not (eq t org-use-tag-inheritance)))
8567 ;; selective inheritance, remove uninherited ones
8568 (setcdr (car tags-alist)
8569 (org-remove-uniherited-tags (cdar tags-alist))))
8570 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8571 (eval matcher)
8572 (or (not org-agenda-skip-archived-trees)
8573 (not (member org-archive-tag tags-list))))
8574 (and (eq action 'agenda) (org-agenda-skip))
8575 ;; list this headline
8577 (if (eq action 'sparse-tree)
8578 (progn
8579 (and org-highlight-sparse-tree-matches
8580 (org-get-heading) (match-end 0)
8581 (org-highlight-new-match
8582 (match-beginning 0) (match-beginning 1)))
8583 (org-show-context 'tags-tree))
8584 (setq txt (org-format-agenda-item
8586 (concat
8587 (if org-tags-match-list-sublevels
8588 (make-string (1- level) ?.) "")
8589 (org-get-heading))
8590 category tags-list)
8591 priority (org-get-priority txt))
8592 (goto-char lspos)
8593 (setq marker (org-agenda-new-marker))
8594 (org-add-props txt props
8595 'org-marker marker 'org-hd-marker marker 'org-category category
8596 'priority priority 'type "tagsmatch")
8597 (push txt rtn))
8598 ;; if we are to skip sublevels, jump to end of subtree
8599 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8600 (when (and (eq action 'sparse-tree)
8601 (not org-sparse-tree-open-archived-trees))
8602 (org-hide-archived-subtrees (point-min) (point-max)))
8603 (nreverse rtn)))
8605 (defun org-remove-uniherited-tags (tags)
8606 "Remove all tags that are not inherited from the list TAGS."
8607 (cond
8608 ((eq org-use-tag-inheritance t) tags)
8609 ((not org-use-tag-inheritance) nil)
8610 ((stringp org-use-tag-inheritance)
8611 (delq nil (mapcar
8612 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8613 tags)))
8614 ((listp org-use-tag-inheritance)
8615 (org-delete-all org-use-tag-inheritance tags))))
8617 (defvar todo-only) ;; dynamically scoped
8619 (defun org-tags-sparse-tree (&optional todo-only match)
8620 "Create a sparse tree according to tags string MATCH.
8621 MATCH can contain positive and negative selection of tags, like
8622 \"+WORK+URGENT-WITHBOSS\".
8623 If optional argument TODO_ONLY is non-nil, only select lines that are
8624 also TODO lines."
8625 (interactive "P")
8626 (org-prepare-agenda-buffers (list (current-buffer)))
8627 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8629 (defvar org-cached-props nil)
8630 (defun org-cached-entry-get (pom property)
8631 (if (or (eq t org-use-property-inheritance)
8632 (and (stringp org-use-property-inheritance)
8633 (string-match org-use-property-inheritance property))
8634 (and (listp org-use-property-inheritance)
8635 (member property org-use-property-inheritance)))
8636 ;; Caching is not possible, check it directly
8637 (org-entry-get pom property 'inherit)
8638 ;; Get all properties, so that we can do complicated checks easily
8639 (cdr (assoc property (or org-cached-props
8640 (setq org-cached-props
8641 (org-entry-properties pom)))))))
8643 (defun org-global-tags-completion-table (&optional files)
8644 "Return the list of all tags in all agenda buffer/files."
8645 (save-excursion
8646 (org-uniquify
8647 (delq nil
8648 (apply 'append
8649 (mapcar
8650 (lambda (file)
8651 (set-buffer (find-file-noselect file))
8652 (append (org-get-buffer-tags)
8653 (mapcar (lambda (x) (if (stringp (car-safe x))
8654 (list (car-safe x)) nil))
8655 org-tag-alist)))
8656 (if (and files (car files))
8657 files
8658 (org-agenda-files))))))))
8660 (defun org-make-tags-matcher (match)
8661 "Create the TAGS//TODO matcher form for the selection string MATCH."
8662 ;; todo-only is scoped dynamically into this function, and the function
8663 ;; may change it it the matcher asksk for it.
8664 (unless match
8665 ;; Get a new match request, with completion
8666 (let ((org-last-tags-completion-table
8667 (org-global-tags-completion-table)))
8668 (setq match (completing-read
8669 "Match: " 'org-tags-completion-function nil nil nil
8670 'org-tags-history))))
8672 ;; Parse the string and create a lisp form
8673 (let ((match0 match)
8674 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
8675 minus tag mm
8676 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8677 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
8678 (if (string-match "/+" match)
8679 ;; match contains also a todo-matching request
8680 (progn
8681 (setq tagsmatch (substring match 0 (match-beginning 0))
8682 todomatch (substring match (match-end 0)))
8683 (if (string-match "^!" todomatch)
8684 (setq todo-only t todomatch (substring todomatch 1)))
8685 (if (string-match "^\\s-*$" todomatch)
8686 (setq todomatch nil)))
8687 ;; only matching tags
8688 (setq tagsmatch match todomatch nil))
8690 ;; Make the tags matcher
8691 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8692 (setq tagsmatcher t)
8693 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8694 (while (setq term (pop orterms))
8695 (while (and (equal (substring term -1) "\\") orterms)
8696 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8697 (while (string-match re term)
8698 (setq minus (and (match-end 1)
8699 (equal (match-string 1 term) "-"))
8700 tag (match-string 2 term)
8701 re-p (equal (string-to-char tag) ?{)
8702 level-p (match-end 3)
8703 prop-p (match-end 4)
8704 mm (cond
8705 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8706 (level-p `(= level ,(string-to-number
8707 (match-string 3 term))))
8708 (prop-p
8709 (setq pn (match-string 4 term)
8710 pv (match-string 5 term)
8711 cat-p (equal pn "CATEGORY")
8712 re-p (equal (string-to-char pv) ?{)
8713 pv (substring pv 1 -1))
8714 (if (equal pn "CATEGORY")
8715 (setq gv '(get-text-property (point) 'org-category))
8716 (setq gv `(org-cached-entry-get nil ,pn)))
8717 (if re-p
8718 `(string-match ,pv (or ,gv ""))
8719 `(equal ,pv (or ,gv ""))))
8720 (t `(member ,(downcase tag) tags-list)))
8721 mm (if minus (list 'not mm) mm)
8722 term (substring term (match-end 0)))
8723 (push mm tagsmatcher))
8724 (push (if (> (length tagsmatcher) 1)
8725 (cons 'and tagsmatcher)
8726 (car tagsmatcher))
8727 orlist)
8728 (setq tagsmatcher nil))
8729 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8730 (setq tagsmatcher
8731 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8733 ;; Make the todo matcher
8734 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8735 (setq todomatcher t)
8736 (setq orterms (org-split-string todomatch "|") orlist nil)
8737 (while (setq term (pop orterms))
8738 (while (string-match re term)
8739 (setq minus (and (match-end 1)
8740 (equal (match-string 1 term) "-"))
8741 kwd (match-string 2 term)
8742 re-p (equal (string-to-char kwd) ?{)
8743 term (substring term (match-end 0))
8744 mm (if re-p
8745 `(string-match ,(substring kwd 1 -1) todo)
8746 (list 'equal 'todo kwd))
8747 mm (if minus (list 'not mm) mm))
8748 (push mm todomatcher))
8749 (push (if (> (length todomatcher) 1)
8750 (cons 'and todomatcher)
8751 (car todomatcher))
8752 orlist)
8753 (setq todomatcher nil))
8754 (setq todomatcher (if (> (length orlist) 1)
8755 (cons 'or orlist) (car orlist))))
8757 ;; Return the string and lisp forms of the matcher
8758 (setq matcher (if todomatcher
8759 (list 'and tagsmatcher todomatcher)
8760 tagsmatcher))
8761 (cons match0 matcher)))
8763 (defun org-match-any-p (re list)
8764 "Does re match any element of list?"
8765 (setq list (mapcar (lambda (x) (string-match re x)) list))
8766 (delq nil list))
8768 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8769 (defvar org-tags-overlay (org-make-overlay 1 1))
8770 (org-detach-overlay org-tags-overlay)
8772 (defun org-get-tags-at (&optional pos)
8773 "Get a list of all headline tags applicable at POS.
8774 POS defaults to point. If tags are inherited, the list contains
8775 the targets in the same sequence as the headlines appear, i.e.
8776 sthe tags of the current headline come last."
8777 (interactive)
8778 (let (tags ltags lastpos parent)
8779 (save-excursion
8780 (save-restriction
8781 (widen)
8782 (goto-char (or pos (point)))
8783 (save-match-data
8784 (condition-case nil
8785 (progn
8786 (org-back-to-heading t)
8787 (while (not (equal lastpos (point)))
8788 (setq lastpos (point))
8789 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8790 (setq ltags (org-split-string
8791 (org-match-string-no-properties 1) ":"))
8792 (setq tags (append (org-remove-uniherited-tags ltags)
8793 tags)))
8794 (or org-use-tag-inheritance (error ""))
8795 (org-up-heading-all 1)
8796 (setq parent t)))
8797 (error nil))))
8798 tags)))
8800 (defun org-toggle-tag (tag &optional onoff)
8801 "Toggle the tag TAG for the current line.
8802 If ONOFF is `on' or `off', don't toggle but set to this state."
8803 (unless (org-on-heading-p t) (error "Not on headling"))
8804 (let (res current)
8805 (save-excursion
8806 (beginning-of-line)
8807 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8808 (point-at-eol) t)
8809 (progn
8810 (setq current (match-string 1))
8811 (replace-match ""))
8812 (setq current ""))
8813 (setq current (nreverse (org-split-string current ":")))
8814 (cond
8815 ((eq onoff 'on)
8816 (setq res t)
8817 (or (member tag current) (push tag current)))
8818 ((eq onoff 'off)
8819 (or (not (member tag current)) (setq current (delete tag current))))
8820 (t (if (member tag current)
8821 (setq current (delete tag current))
8822 (setq res t)
8823 (push tag current))))
8824 (end-of-line 1)
8825 (if current
8826 (progn
8827 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8828 (org-set-tags nil t))
8829 (delete-horizontal-space))
8830 (run-hooks 'org-after-tags-change-hook))
8831 res))
8833 (defun org-align-tags-here (to-col)
8834 ;; Assumes that this is a headline
8835 (let ((pos (point)) (col (current-column)) tags)
8836 (beginning-of-line 1)
8837 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8838 (< pos (match-beginning 2)))
8839 (progn
8840 (setq tags (match-string 2))
8841 (goto-char (match-beginning 1))
8842 (insert " ")
8843 (delete-region (point) (1+ (match-end 0)))
8844 (backward-char 1)
8845 (move-to-column
8846 (max (1+ (current-column))
8847 (1+ col)
8848 (if (> to-col 0)
8849 to-col
8850 (- (abs to-col) (length tags))))
8852 (insert tags)
8853 (move-to-column (min (current-column) col) t))
8854 (goto-char pos))))
8856 (defun org-set-tags (&optional arg just-align)
8857 "Set the tags for the current headline.
8858 With prefix ARG, realign all tags in headings in the current buffer."
8859 (interactive "P")
8860 (let* ((re (concat "^" outline-regexp))
8861 (current (org-get-tags-string))
8862 (col (current-column))
8863 (org-setting-tags t)
8864 table current-tags inherited-tags ; computed below when needed
8865 tags p0 c0 c1 rpl)
8866 (if arg
8867 (save-excursion
8868 (goto-char (point-min))
8869 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8870 (while (re-search-forward re nil t)
8871 (org-set-tags nil t)
8872 (end-of-line 1)))
8873 (message "All tags realigned to column %d" org-tags-column))
8874 (if just-align
8875 (setq tags current)
8876 ;; Get a new set of tags from the user
8877 (save-excursion
8878 (setq table (or org-tag-alist (org-get-buffer-tags))
8879 org-last-tags-completion-table table
8880 current-tags (org-split-string current ":")
8881 inherited-tags (nreverse
8882 (nthcdr (length current-tags)
8883 (nreverse (org-get-tags-at))))
8884 tags
8885 (if (or (eq t org-use-fast-tag-selection)
8886 (and org-use-fast-tag-selection
8887 (delq nil (mapcar 'cdr table))))
8888 (org-fast-tag-selection
8889 current-tags inherited-tags table
8890 (if org-fast-tag-selection-include-todo org-todo-key-alist))
8891 (let ((org-add-colon-after-tag-completion t))
8892 (org-trim
8893 (org-without-partial-completion
8894 (completing-read "Tags: " 'org-tags-completion-function
8895 nil nil current 'org-tags-history)))))))
8896 (while (string-match "[-+&]+" tags)
8897 ;; No boolean logic, just a list
8898 (setq tags (replace-match ":" t t tags))))
8900 (if (string-match "\\`[\t ]*\\'" tags)
8901 (setq tags "")
8902 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8903 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8905 ;; Insert new tags at the correct column
8906 (beginning-of-line 1)
8907 (cond
8908 ((and (equal current "") (equal tags "")))
8909 ((re-search-forward
8910 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
8911 (point-at-eol) t)
8912 (if (equal tags "")
8913 (setq rpl "")
8914 (goto-char (match-beginning 0))
8915 (setq c0 (current-column) p0 (point)
8916 c1 (max (1+ c0) (if (> org-tags-column 0)
8917 org-tags-column
8918 (- (- org-tags-column) (length tags))))
8919 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
8920 (replace-match rpl t t)
8921 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
8922 tags)
8923 (t (error "Tags alignment failed")))
8924 (move-to-column col)
8925 (unless just-align
8926 (run-hooks 'org-after-tags-change-hook)))))
8928 (defun org-change-tag-in-region (beg end tag off)
8929 "Add or remove TAG for each entry in the region.
8930 This works in the agenda, and also in an org-mode buffer."
8931 (interactive
8932 (list (region-beginning) (region-end)
8933 (let ((org-last-tags-completion-table
8934 (if (org-mode-p)
8935 (org-get-buffer-tags)
8936 (org-global-tags-completion-table))))
8937 (completing-read
8938 "Tag: " 'org-tags-completion-function nil nil nil
8939 'org-tags-history))
8940 (progn
8941 (message "[s]et or [r]emove? ")
8942 (equal (read-char-exclusive) ?r))))
8943 (if (fboundp 'deactivate-mark) (deactivate-mark))
8944 (let ((agendap (equal major-mode 'org-agenda-mode))
8945 l1 l2 m buf pos newhead (cnt 0))
8946 (goto-char end)
8947 (setq l2 (1- (org-current-line)))
8948 (goto-char beg)
8949 (setq l1 (org-current-line))
8950 (loop for l from l1 to l2 do
8951 (goto-line l)
8952 (setq m (get-text-property (point) 'org-hd-marker))
8953 (when (or (and (org-mode-p) (org-on-heading-p))
8954 (and agendap m))
8955 (setq buf (if agendap (marker-buffer m) (current-buffer))
8956 pos (if agendap m (point)))
8957 (with-current-buffer buf
8958 (save-excursion
8959 (save-restriction
8960 (goto-char pos)
8961 (setq cnt (1+ cnt))
8962 (org-toggle-tag tag (if off 'off 'on))
8963 (setq newhead (org-get-heading)))))
8964 (and agendap (org-agenda-change-all-lines newhead m))))
8965 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
8967 (defun org-tags-completion-function (string predicate &optional flag)
8968 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8969 (confirm (lambda (x) (stringp (car x)))))
8970 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8971 (setq s1 (match-string 1 string)
8972 s2 (match-string 2 string))
8973 (setq s1 "" s2 string))
8974 (cond
8975 ((eq flag nil)
8976 ;; try completion
8977 (setq rtn (try-completion s2 ctable confirm))
8978 (if (stringp rtn)
8979 (setq rtn
8980 (concat s1 s2 (substring rtn (length s2))
8981 (if (and org-add-colon-after-tag-completion
8982 (assoc rtn ctable))
8983 ":" ""))))
8984 rtn)
8985 ((eq flag t)
8986 ;; all-completions
8987 (all-completions s2 ctable confirm)
8989 ((eq flag 'lambda)
8990 ;; exact match?
8991 (assoc s2 ctable)))
8994 (defun org-fast-tag-insert (kwd tags face &optional end)
8995 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8996 (insert (format "%-12s" (concat kwd ":"))
8997 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8998 (or end "")))
9000 (defun org-fast-tag-show-exit (flag)
9001 (save-excursion
9002 (goto-line 3)
9003 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9004 (replace-match ""))
9005 (when flag
9006 (end-of-line 1)
9007 (move-to-column (- (window-width) 19) t)
9008 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9010 (defun org-set-current-tags-overlay (current prefix)
9011 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9012 (if (featurep 'xemacs)
9013 (org-overlay-display org-tags-overlay (concat prefix s)
9014 'secondary-selection)
9015 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9016 (org-overlay-display org-tags-overlay (concat prefix s)))))
9018 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9019 "Fast tag selection with single keys.
9020 CURRENT is the current list of tags in the headline, INHERITED is the
9021 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9022 possibly with grouping information. TODO-TABLE is a similar table with
9023 TODO keywords, should these have keys assigned to them.
9024 If the keys are nil, a-z are automatically assigned.
9025 Returns the new tags string, or nil to not change the current settings."
9026 (let* ((fulltable (append table todo-table))
9027 (maxlen (apply 'max (mapcar
9028 (lambda (x)
9029 (if (stringp (car x)) (string-width (car x)) 0))
9030 fulltable)))
9031 (buf (current-buffer))
9032 (expert (eq org-fast-tag-selection-single-key 'expert))
9033 (buffer-tags nil)
9034 (fwidth (+ maxlen 3 1 3))
9035 (ncol (/ (- (window-width) 4) fwidth))
9036 (i-face 'org-done)
9037 (c-face 'org-todo)
9038 tg cnt e c char c1 c2 ntable tbl rtn
9039 ov-start ov-end ov-prefix
9040 (exit-after-next org-fast-tag-selection-single-key)
9041 (done-keywords org-done-keywords)
9042 groups ingroup)
9043 (save-excursion
9044 (beginning-of-line 1)
9045 (if (looking-at
9046 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9047 (setq ov-start (match-beginning 1)
9048 ov-end (match-end 1)
9049 ov-prefix "")
9050 (setq ov-start (1- (point-at-eol))
9051 ov-end (1+ ov-start))
9052 (skip-chars-forward "^\n\r")
9053 (setq ov-prefix
9054 (concat
9055 (buffer-substring (1- (point)) (point))
9056 (if (> (current-column) org-tags-column)
9058 (make-string (- org-tags-column (current-column)) ?\ ))))))
9059 (org-move-overlay org-tags-overlay ov-start ov-end)
9060 (save-window-excursion
9061 (if expert
9062 (set-buffer (get-buffer-create " *Org tags*"))
9063 (delete-other-windows)
9064 (split-window-vertically)
9065 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9066 (erase-buffer)
9067 (org-set-local 'org-done-keywords done-keywords)
9068 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9069 (org-fast-tag-insert "Current" current c-face "\n\n")
9070 (org-fast-tag-show-exit exit-after-next)
9071 (org-set-current-tags-overlay current ov-prefix)
9072 (setq tbl fulltable char ?a cnt 0)
9073 (while (setq e (pop tbl))
9074 (cond
9075 ((equal e '(:startgroup))
9076 (push '() groups) (setq ingroup t)
9077 (when (not (= cnt 0))
9078 (setq cnt 0)
9079 (insert "\n"))
9080 (insert "{ "))
9081 ((equal e '(:endgroup))
9082 (setq ingroup nil cnt 0)
9083 (insert "}\n"))
9085 (setq tg (car e) c2 nil)
9086 (if (cdr e)
9087 (setq c (cdr e))
9088 ;; automatically assign a character.
9089 (setq c1 (string-to-char
9090 (downcase (substring
9091 tg (if (= (string-to-char tg) ?@) 1 0)))))
9092 (if (or (rassoc c1 ntable) (rassoc c1 table))
9093 (while (or (rassoc char ntable) (rassoc char table))
9094 (setq char (1+ char)))
9095 (setq c2 c1))
9096 (setq c (or c2 char)))
9097 (if ingroup (push tg (car groups)))
9098 (setq tg (org-add-props tg nil 'face
9099 (cond
9100 ((not (assoc tg table))
9101 (org-get-todo-face tg))
9102 ((member tg current) c-face)
9103 ((member tg inherited) i-face)
9104 (t nil))))
9105 (if (and (= cnt 0) (not ingroup)) (insert " "))
9106 (insert "[" c "] " tg (make-string
9107 (- fwidth 4 (length tg)) ?\ ))
9108 (push (cons tg c) ntable)
9109 (when (= (setq cnt (1+ cnt)) ncol)
9110 (insert "\n")
9111 (if ingroup (insert " "))
9112 (setq cnt 0)))))
9113 (setq ntable (nreverse ntable))
9114 (insert "\n")
9115 (goto-char (point-min))
9116 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9117 (fit-window-to-buffer))
9118 (setq rtn
9119 (catch 'exit
9120 (while t
9121 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9122 (if groups " [!] no groups" " [!]groups")
9123 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9124 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9125 (cond
9126 ((= c ?\r) (throw 'exit t))
9127 ((= c ?!)
9128 (setq groups (not groups))
9129 (goto-char (point-min))
9130 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9131 ((= c ?\C-c)
9132 (if (not expert)
9133 (org-fast-tag-show-exit
9134 (setq exit-after-next (not exit-after-next)))
9135 (setq expert nil)
9136 (delete-other-windows)
9137 (split-window-vertically)
9138 (org-switch-to-buffer-other-window " *Org tags*")
9139 (and (fboundp 'fit-window-to-buffer)
9140 (fit-window-to-buffer))))
9141 ((or (= c ?\C-g)
9142 (and (= c ?q) (not (rassoc c ntable))))
9143 (org-detach-overlay org-tags-overlay)
9144 (setq quit-flag t))
9145 ((= c ?\ )
9146 (setq current nil)
9147 (if exit-after-next (setq exit-after-next 'now)))
9148 ((= c ?\t)
9149 (condition-case nil
9150 (setq tg (completing-read
9151 "Tag: "
9152 (or buffer-tags
9153 (with-current-buffer buf
9154 (org-get-buffer-tags)))))
9155 (quit (setq tg "")))
9156 (when (string-match "\\S-" tg)
9157 (add-to-list 'buffer-tags (list tg))
9158 (if (member tg current)
9159 (setq current (delete tg current))
9160 (push tg current)))
9161 (if exit-after-next (setq exit-after-next 'now)))
9162 ((setq e (rassoc c todo-table) tg (car e))
9163 (with-current-buffer buf
9164 (save-excursion (org-todo tg)))
9165 (if exit-after-next (setq exit-after-next 'now)))
9166 ((setq e (rassoc c ntable) tg (car e))
9167 (if (member tg current)
9168 (setq current (delete tg current))
9169 (loop for g in groups do
9170 (if (member tg g)
9171 (mapc (lambda (x)
9172 (setq current (delete x current)))
9173 g)))
9174 (push tg current))
9175 (if exit-after-next (setq exit-after-next 'now))))
9177 ;; Create a sorted list
9178 (setq current
9179 (sort current
9180 (lambda (a b)
9181 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9182 (if (eq exit-after-next 'now) (throw 'exit t))
9183 (goto-char (point-min))
9184 (beginning-of-line 2)
9185 (delete-region (point) (point-at-eol))
9186 (org-fast-tag-insert "Current" current c-face)
9187 (org-set-current-tags-overlay current ov-prefix)
9188 (while (re-search-forward
9189 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9190 (setq tg (match-string 1))
9191 (add-text-properties
9192 (match-beginning 1) (match-end 1)
9193 (list 'face
9194 (cond
9195 ((member tg current) c-face)
9196 ((member tg inherited) i-face)
9197 (t (get-text-property (match-beginning 1) 'face))))))
9198 (goto-char (point-min)))))
9199 (org-detach-overlay org-tags-overlay)
9200 (if rtn
9201 (mapconcat 'identity current ":")
9202 nil))))
9204 (defun org-get-tags-string ()
9205 "Get the TAGS string in the current headline."
9206 (unless (org-on-heading-p t)
9207 (error "Not on a heading"))
9208 (save-excursion
9209 (beginning-of-line 1)
9210 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9211 (org-match-string-no-properties 1)
9212 "")))
9214 (defun org-get-tags ()
9215 "Get the list of tags specified in the current headline."
9216 (org-split-string (org-get-tags-string) ":"))
9218 (defun org-get-buffer-tags ()
9219 "Get a table of all tags used in the buffer, for completion."
9220 (let (tags)
9221 (save-excursion
9222 (goto-char (point-min))
9223 (while (re-search-forward
9224 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9225 (when (equal (char-after (point-at-bol 0)) ?*)
9226 (mapc (lambda (x) (add-to-list 'tags x))
9227 (org-split-string (org-match-string-no-properties 1) ":")))))
9228 (mapcar 'list tags)))
9231 ;;;; Properties
9233 ;;; Setting and retrieving properties
9235 (defconst org-special-properties
9236 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9237 "TIMESTAMP" "TIMESTAMP_IA")
9238 "The special properties valid in Org-mode.
9240 These are properties that are not defined in the property drawer,
9241 but in some other way.")
9243 (defconst org-default-properties
9244 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9245 "LOCATION" "LOGGING" "COLUMNS")
9246 "Some properties that are used by Org-mode for various purposes.
9247 Being in this list makes sure that they are offered for completion.")
9249 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9250 "Regular expression matching the first line of a property drawer.")
9252 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9253 "Regular expression matching the first line of a property drawer.")
9255 (defun org-property-action ()
9256 "Do an action on properties."
9257 (interactive)
9258 (let (c)
9259 (org-at-property-p)
9260 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9261 (setq c (read-char-exclusive))
9262 (cond
9263 ((equal c ?s)
9264 (call-interactively 'org-set-property))
9265 ((equal c ?d)
9266 (call-interactively 'org-delete-property))
9267 ((equal c ?D)
9268 (call-interactively 'org-delete-property-globally))
9269 ((equal c ?c)
9270 (call-interactively 'org-compute-property-at-point))
9271 (t (error "No such property action %c" c)))))
9273 (defun org-at-property-p ()
9274 "Is the cursor in a property line?"
9275 ;; FIXME: Does not check if we are actually in the drawer.
9276 ;; FIXME: also returns true on any drawers.....
9277 ;; This is used by C-c C-c for property action.
9278 (save-excursion
9279 (beginning-of-line 1)
9280 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9282 (defun org-get-property-block (&optional beg end force)
9283 "Return the (beg . end) range of the body of the property drawer.
9284 BEG and END can be beginning and end of subtree, if not given
9285 they will be found.
9286 If the drawer does not exist and FORCE is non-nil, create the drawer."
9287 (catch 'exit
9288 (save-excursion
9289 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9290 (end (or end (progn (outline-next-heading) (point)))))
9291 (goto-char beg)
9292 (if (re-search-forward org-property-start-re end t)
9293 (setq beg (1+ (match-end 0)))
9294 (if force
9295 (save-excursion
9296 (org-insert-property-drawer)
9297 (setq end (progn (outline-next-heading) (point))))
9298 (throw 'exit nil))
9299 (goto-char beg)
9300 (if (re-search-forward org-property-start-re end t)
9301 (setq beg (1+ (match-end 0)))))
9302 (if (re-search-forward org-property-end-re end t)
9303 (setq end (match-beginning 0))
9304 (or force (throw 'exit nil))
9305 (goto-char beg)
9306 (setq end beg)
9307 (org-indent-line-function)
9308 (insert ":END:\n"))
9309 (cons beg end)))))
9311 (defun org-entry-properties (&optional pom which)
9312 "Get all properties of the entry at point-or-marker POM.
9313 This includes the TODO keyword, the tags, time strings for deadline,
9314 scheduled, and clocking, and any additional properties defined in the
9315 entry. The return value is an alist, keys may occur multiple times
9316 if the property key was used several times.
9317 POM may also be nil, in which case the current entry is used.
9318 If WHICH is nil or `all', get all properties. If WHICH is
9319 `special' or `standard', only get that subclass."
9320 (setq which (or which 'all))
9321 (org-with-point-at pom
9322 (let ((clockstr (substring org-clock-string 0 -1))
9323 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9324 beg end range props sum-props key value string clocksum)
9325 (save-excursion
9326 (when (condition-case nil (org-back-to-heading t) (error nil))
9327 (setq beg (point))
9328 (setq sum-props (get-text-property (point) 'org-summaries))
9329 (setq clocksum (get-text-property (point) :org-clock-minutes))
9330 (outline-next-heading)
9331 (setq end (point))
9332 (when (memq which '(all special))
9333 ;; Get the special properties, like TODO and tags
9334 (goto-char beg)
9335 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9336 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9337 (when (looking-at org-priority-regexp)
9338 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9339 (when (and (setq value (org-get-tags-string))
9340 (string-match "\\S-" value))
9341 (push (cons "TAGS" value) props))
9342 (when (setq value (org-get-tags-at))
9343 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9344 props))
9345 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9346 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9347 string (if (equal key clockstr)
9348 (org-no-properties
9349 (org-trim
9350 (buffer-substring
9351 (match-beginning 3) (goto-char (point-at-eol)))))
9352 (substring (org-match-string-no-properties 3) 1 -1)))
9353 (unless key
9354 (if (= (char-after (match-beginning 3)) ?\[)
9355 (setq key "TIMESTAMP_IA")
9356 (setq key "TIMESTAMP")))
9357 (when (or (equal key clockstr) (not (assoc key props)))
9358 (push (cons key string) props)))
9362 (when (memq which '(all standard))
9363 ;; Get the standard properties, like :PORP: ...
9364 (setq range (org-get-property-block beg end))
9365 (when range
9366 (goto-char (car range))
9367 (while (re-search-forward
9368 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9369 (cdr range) t)
9370 (setq key (org-match-string-no-properties 1)
9371 value (org-trim (or (org-match-string-no-properties 2) "")))
9372 (unless (member key excluded)
9373 (push (cons key (or value "")) props)))))
9374 (if clocksum
9375 (push (cons "CLOCKSUM"
9376 (org-columns-number-to-string (/ (float clocksum) 60.)
9377 'add_times))
9378 props))
9379 (append sum-props (nreverse props)))))))
9381 (defun org-entry-get (pom property &optional inherit)
9382 "Get value of PROPERTY for entry at point-or-marker POM.
9383 If INHERIT is non-nil and the entry does not have the property,
9384 then also check higher levels of the hierarchy.
9385 If INHERIT is the symbol `selective', use inheritance only if the setting
9386 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9387 If the property is present but empty, the return value is the empty string.
9388 If the property is not present at all, nil is returned."
9389 (org-with-point-at pom
9390 (if (and inherit (if (eq inherit 'selective)
9391 (org-property-inherit-p property)
9393 (org-entry-get-with-inheritance property)
9394 (if (member property org-special-properties)
9395 ;; We need a special property. Use brute force, get all properties.
9396 (cdr (assoc property (org-entry-properties nil 'special)))
9397 (let ((range (org-get-property-block)))
9398 (if (and range
9399 (goto-char (car range))
9400 (re-search-forward
9401 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9402 (cdr range) t))
9403 ;; Found the property, return it.
9404 (if (match-end 1)
9405 (org-match-string-no-properties 1)
9406 "")))))))
9408 (defun org-property-or-variable-value (var &optional inherit)
9409 "Check if there is a property fixing the value of VAR.
9410 If yes, return this value. If not, return the current value of the variable."
9411 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9412 (if (and prop (stringp prop) (string-match "\\S-" prop))
9413 (read prop)
9414 (symbol-value var))))
9416 (defun org-entry-delete (pom property)
9417 "Delete the property PROPERTY from entry at point-or-marker POM."
9418 (org-with-point-at pom
9419 (if (member property org-special-properties)
9420 nil ; cannot delete these properties.
9421 (let ((range (org-get-property-block)))
9422 (if (and range
9423 (goto-char (car range))
9424 (re-search-forward
9425 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9426 (cdr range) t))
9427 (progn
9428 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9430 nil)))))
9432 ;; Multi-values properties are properties that contain multiple values
9433 ;; These values are assumed to be single words, separated by whitespace.
9434 (defun org-entry-add-to-multivalued-property (pom property value)
9435 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9436 (let* ((old (org-entry-get pom property))
9437 (values (and old (org-split-string old "[ \t]"))))
9438 (unless (member value values)
9439 (setq values (cons value values))
9440 (org-entry-put pom property
9441 (mapconcat 'identity values " ")))))
9443 (defun org-entry-remove-from-multivalued-property (pom property value)
9444 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9445 (let* ((old (org-entry-get pom property))
9446 (values (and old (org-split-string old "[ \t]"))))
9447 (when (member value values)
9448 (setq values (delete value values))
9449 (org-entry-put pom property
9450 (mapconcat 'identity values " ")))))
9452 (defun org-entry-member-in-multivalued-property (pom property value)
9453 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9454 (let* ((old (org-entry-get pom property))
9455 (values (and old (org-split-string old "[ \t]"))))
9456 (member value values)))
9458 (defvar org-entry-property-inherited-from (make-marker))
9460 (defun org-entry-get-with-inheritance (property)
9461 "Get entry property, and search higher levels if not present."
9462 (let (tmp)
9463 (save-excursion
9464 (save-restriction
9465 (widen)
9466 (catch 'ex
9467 (while t
9468 (when (setq tmp (org-entry-get nil property))
9469 (org-back-to-heading t)
9470 (move-marker org-entry-property-inherited-from (point))
9471 (throw 'ex tmp))
9472 (or (org-up-heading-safe) (throw 'ex nil)))))
9473 (or tmp (cdr (assoc property org-local-properties))
9474 (cdr (assoc property org-global-properties))))))
9476 (defun org-entry-put (pom property value)
9477 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9478 (org-with-point-at pom
9479 (org-back-to-heading t)
9480 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9481 range)
9482 (cond
9483 ((equal property "TODO")
9484 (when (and (stringp value) (string-match "\\S-" value)
9485 (not (member value org-todo-keywords-1)))
9486 (error "\"%s\" is not a valid TODO state" value))
9487 (if (or (not value)
9488 (not (string-match "\\S-" value)))
9489 (setq value 'none))
9490 (org-todo value)
9491 (org-set-tags nil 'align))
9492 ((equal property "PRIORITY")
9493 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9494 (string-to-char value) ?\ ))
9495 (org-set-tags nil 'align))
9496 ((equal property "SCHEDULED")
9497 (if (re-search-forward org-scheduled-time-regexp end t)
9498 (cond
9499 ((eq value 'earlier) (org-timestamp-change -1 'day))
9500 ((eq value 'later) (org-timestamp-change 1 'day))
9501 (t (call-interactively 'org-schedule)))
9502 (call-interactively 'org-schedule)))
9503 ((equal property "DEADLINE")
9504 (if (re-search-forward org-deadline-time-regexp end t)
9505 (cond
9506 ((eq value 'earlier) (org-timestamp-change -1 'day))
9507 ((eq value 'later) (org-timestamp-change 1 'day))
9508 (t (call-interactively 'org-deadline)))
9509 (call-interactively 'org-deadline)))
9510 ((member property org-special-properties)
9511 (error "The %s property can not yet be set with `org-entry-put'"
9512 property))
9513 (t ; a non-special property
9514 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9515 (setq range (org-get-property-block beg end 'force))
9516 (goto-char (car range))
9517 (if (re-search-forward
9518 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9519 (progn
9520 (delete-region (match-beginning 1) (match-end 1))
9521 (goto-char (match-beginning 1)))
9522 (goto-char (cdr range))
9523 (insert "\n")
9524 (backward-char 1)
9525 (org-indent-line-function)
9526 (insert ":" property ":"))
9527 (and value (insert " " value))
9528 (org-indent-line-function)))))))
9530 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9531 "Get all property keys in the current buffer.
9532 With INCLUDE-SPECIALS, also list the special properties that relect things
9533 like tags and TODO state.
9534 With INCLUDE-DEFAULTS, also include properties that has special meaning
9535 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9536 With INCLUDE-COLUMNS, also include property names given in COLUMN
9537 formats in the current buffer."
9538 (let (rtn range cfmt cols s p)
9539 (save-excursion
9540 (save-restriction
9541 (widen)
9542 (goto-char (point-min))
9543 (while (re-search-forward org-property-start-re nil t)
9544 (setq range (org-get-property-block))
9545 (goto-char (car range))
9546 (while (re-search-forward
9547 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9548 (cdr range) t)
9549 (add-to-list 'rtn (org-match-string-no-properties 1)))
9550 (outline-next-heading))))
9552 (when include-specials
9553 (setq rtn (append org-special-properties rtn)))
9555 (when include-defaults
9556 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9558 (when include-columns
9559 (save-excursion
9560 (save-restriction
9561 (widen)
9562 (goto-char (point-min))
9563 (while (re-search-forward
9564 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9565 nil t)
9566 (setq cfmt (match-string 2) s 0)
9567 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9568 cfmt s)
9569 (setq s (match-end 0)
9570 p (match-string 1 cfmt))
9571 (unless (or (equal p "ITEM")
9572 (member p org-special-properties))
9573 (add-to-list 'rtn (match-string 1 cfmt))))))))
9575 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9577 (defun org-property-values (key)
9578 "Return a list of all values of property KEY."
9579 (save-excursion
9580 (save-restriction
9581 (widen)
9582 (goto-char (point-min))
9583 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9584 values)
9585 (while (re-search-forward re nil t)
9586 (add-to-list 'values (org-trim (match-string 1))))
9587 (delete "" values)))))
9589 (defun org-insert-property-drawer ()
9590 "Insert a property drawer into the current entry."
9591 (interactive)
9592 (org-back-to-heading t)
9593 (looking-at outline-regexp)
9594 (let ((indent (- (match-end 0)(match-beginning 0)))
9595 (beg (point))
9596 (re (concat "^[ \t]*" org-keyword-time-regexp))
9597 end hiddenp)
9598 (outline-next-heading)
9599 (setq end (point))
9600 (goto-char beg)
9601 (while (re-search-forward re end t))
9602 (setq hiddenp (org-invisible-p))
9603 (end-of-line 1)
9604 (and (equal (char-after) ?\n) (forward-char 1))
9605 (org-skip-over-state-notes)
9606 (skip-chars-backward " \t\n\r")
9607 (if (eq (char-before) ?*) (forward-char 1))
9608 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9609 (beginning-of-line 0)
9610 (indent-to-column indent)
9611 (beginning-of-line 2)
9612 (indent-to-column indent)
9613 (beginning-of-line 0)
9614 (if hiddenp
9615 (save-excursion
9616 (org-back-to-heading t)
9617 (hide-entry))
9618 (org-flag-drawer t))))
9620 (defun org-set-property (property value)
9621 "In the current entry, set PROPERTY to VALUE.
9622 When called interactively, this will prompt for a property name, offering
9623 completion on existing and default properties. And then it will prompt
9624 for a value, offering competion either on allowed values (via an inherited
9625 xxx_ALL property) or on existing values in other instances of this property
9626 in the current file."
9627 (interactive
9628 (let* ((prop (completing-read
9629 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9630 (cur (org-entry-get nil prop))
9631 (allowed (org-property-get-allowed-values nil prop 'table))
9632 (existing (mapcar 'list (org-property-values prop)))
9633 (val (if allowed
9634 (completing-read "Value: " allowed nil 'req-match)
9635 (completing-read
9636 (concat "Value" (if (and cur (string-match "\\S-" cur))
9637 (concat "[" cur "]") "")
9638 ": ")
9639 existing nil nil "" nil cur))))
9640 (list prop (if (equal val "") cur val))))
9641 (unless (equal (org-entry-get nil property) value)
9642 (org-entry-put nil property value)))
9644 (defun org-delete-property (property)
9645 "In the current entry, delete PROPERTY."
9646 (interactive
9647 (let* ((prop (completing-read
9648 "Property: " (org-entry-properties nil 'standard))))
9649 (list prop)))
9650 (message "Property %s %s" property
9651 (if (org-entry-delete nil property)
9652 "deleted"
9653 "was not present in the entry")))
9655 (defun org-delete-property-globally (property)
9656 "Remove PROPERTY globally, from all entries."
9657 (interactive
9658 (let* ((prop (completing-read
9659 "Globally remove property: "
9660 (mapcar 'list (org-buffer-property-keys)))))
9661 (list prop)))
9662 (save-excursion
9663 (save-restriction
9664 (widen)
9665 (goto-char (point-min))
9666 (let ((cnt 0))
9667 (while (re-search-forward
9668 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9669 nil t)
9670 (setq cnt (1+ cnt))
9671 (replace-match ""))
9672 (message "Property \"%s\" removed from %d entries" property cnt)))))
9674 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9676 (defun org-compute-property-at-point ()
9677 "Compute the property at point.
9678 This looks for an enclosing column format, extracts the operator and
9679 then applies it to the proerty in the column format's scope."
9680 (interactive)
9681 (unless (org-at-property-p)
9682 (error "Not at a property"))
9683 (let ((prop (org-match-string-no-properties 2)))
9684 (org-columns-get-format-and-top-level)
9685 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9686 (error "No operator defined for property %s" prop))
9687 (org-columns-compute prop)))
9689 (defun org-property-get-allowed-values (pom property &optional table)
9690 "Get allowed values for the property PROPERTY.
9691 When TABLE is non-nil, return an alist that can directly be used for
9692 completion."
9693 (let (vals)
9694 (cond
9695 ((equal property "TODO")
9696 (setq vals (org-with-point-at pom
9697 (append org-todo-keywords-1 '("")))))
9698 ((equal property "PRIORITY")
9699 (let ((n org-lowest-priority))
9700 (while (>= n org-highest-priority)
9701 (push (char-to-string n) vals)
9702 (setq n (1- n)))))
9703 ((member property org-special-properties))
9705 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9707 (when (and vals (string-match "\\S-" vals))
9708 (setq vals (car (read-from-string (concat "(" vals ")"))))
9709 (setq vals (mapcar (lambda (x)
9710 (cond ((stringp x) x)
9711 ((numberp x) (number-to-string x))
9712 ((symbolp x) (symbol-name x))
9713 (t "???")))
9714 vals)))))
9715 (if table (mapcar 'list vals) vals)))
9717 (defun org-property-previous-allowed-value (&optional previous)
9718 "Switch to the next allowed value for this property."
9719 (interactive)
9720 (org-property-next-allowed-value t))
9722 (defun org-property-next-allowed-value (&optional previous)
9723 "Switch to the next allowed value for this property."
9724 (interactive)
9725 (unless (org-at-property-p)
9726 (error "Not at a property"))
9727 (let* ((key (match-string 2))
9728 (value (match-string 3))
9729 (allowed (or (org-property-get-allowed-values (point) key)
9730 (and (member value '("[ ]" "[-]" "[X]"))
9731 '("[ ]" "[X]"))))
9732 nval)
9733 (unless allowed
9734 (error "Allowed values for this property have not been defined"))
9735 (if previous (setq allowed (reverse allowed)))
9736 (if (member value allowed)
9737 (setq nval (car (cdr (member value allowed)))))
9738 (setq nval (or nval (car allowed)))
9739 (if (equal nval value)
9740 (error "Only one allowed value for this property"))
9741 (org-at-property-p)
9742 (replace-match (concat " :" key ": " nval) t t)
9743 (org-indent-line-function)
9744 (beginning-of-line 1)
9745 (skip-chars-forward " \t")))
9747 (defun org-find-entry-with-id (ident)
9748 "Locate the entry that contains the ID property with exact value IDENT.
9749 IDENT can be a string, a symbol or a number, this function will search for
9750 the string representation of it.
9751 Return the position where this entry starts, or nil if there is no such entry."
9752 (let ((id (cond
9753 ((stringp ident) ident)
9754 ((symbol-name ident) (symbol-name ident))
9755 ((numberp ident) (number-to-string ident))
9756 (t (error "IDENT %s must be a string, symbol or number" ident))))
9757 (case-fold-search nil))
9758 (save-excursion
9759 (save-restriction
9760 (widen)
9761 (goto-char (point-min))
9762 (when (re-search-forward
9763 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9764 nil t)
9765 (org-back-to-heading)
9766 (point))))))
9768 ;;;; Timestamps
9770 (defvar org-last-changed-timestamp nil)
9771 (defvar org-time-was-given) ; dynamically scoped parameter
9772 (defvar org-end-time-was-given) ; dynamically scoped parameter
9773 (defvar org-ts-what) ; dynamically scoped parameter
9775 (defun org-time-stamp (arg)
9776 "Prompt for a date/time and insert a time stamp.
9777 If the user specifies a time like HH:MM, or if this command is called
9778 with a prefix argument, the time stamp will contain date and time.
9779 Otherwise, only the date will be included. All parts of a date not
9780 specified by the user will be filled in from the current date/time.
9781 So if you press just return without typing anything, the time stamp
9782 will represent the current date/time. If there is already a timestamp
9783 at the cursor, it will be modified."
9784 (interactive "P")
9785 (let* ((ts nil)
9786 (default-time
9787 ;; Default time is either today, or, when entering a range,
9788 ;; the range start.
9789 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9790 (save-excursion
9791 (re-search-backward
9792 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9793 (- (point) 20) t)))
9794 (apply 'encode-time (org-parse-time-string (match-string 1)))
9795 (current-time)))
9796 (default-input (and ts (org-get-compact-tod ts)))
9797 org-time-was-given org-end-time-was-given time)
9798 (cond
9799 ((and (org-at-timestamp-p)
9800 (eq last-command 'org-time-stamp)
9801 (eq this-command 'org-time-stamp))
9802 (insert "--")
9803 (setq time (let ((this-command this-command))
9804 (org-read-date arg 'totime nil nil default-time default-input)))
9805 (org-insert-time-stamp time (or org-time-was-given arg)))
9806 ((org-at-timestamp-p)
9807 (setq time (let ((this-command this-command))
9808 (org-read-date arg 'totime nil nil default-time default-input)))
9809 (when (org-at-timestamp-p) ; just to get the match data
9810 (replace-match "")
9811 (setq org-last-changed-timestamp
9812 (org-insert-time-stamp
9813 time (or org-time-was-given arg)
9814 nil nil nil (list org-end-time-was-given))))
9815 (message "Timestamp updated"))
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 nil nil nil (list org-end-time-was-given))))))
9822 ;; FIXME: can we use this for something else, like computing time differences?
9823 (defun org-get-compact-tod (s)
9824 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9825 (let* ((t1 (match-string 1 s))
9826 (h1 (string-to-number (match-string 2 s)))
9827 (m1 (string-to-number (match-string 3 s)))
9828 (t2 (and (match-end 4) (match-string 5 s)))
9829 (h2 (and t2 (string-to-number (match-string 6 s))))
9830 (m2 (and t2 (string-to-number (match-string 7 s))))
9831 dh dm)
9832 (if (not t2)
9834 (setq dh (- h2 h1) dm (- m2 m1))
9835 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9836 (concat t1 "+" (number-to-string dh)
9837 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9839 (defun org-time-stamp-inactive (&optional arg)
9840 "Insert an inactive time stamp.
9841 An inactive time stamp is enclosed in square brackets instead of angle
9842 brackets. It is inactive in the sense that it does not trigger agenda entries,
9843 does not link to the calendar and cannot be changed with the S-cursor keys.
9844 So these are more for recording a certain time/date."
9845 (interactive "P")
9846 (let (org-time-was-given org-end-time-was-given time)
9847 (setq time (org-read-date arg 'totime))
9848 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9849 nil nil (list org-end-time-was-given))))
9851 (defvar org-date-ovl (org-make-overlay 1 1))
9852 (org-overlay-put org-date-ovl 'face 'org-warning)
9853 (org-detach-overlay org-date-ovl)
9855 (defvar org-ans1) ; dynamically scoped parameter
9856 (defvar org-ans2) ; dynamically scoped parameter
9858 (defvar org-plain-time-of-day-regexp) ; defined below
9860 (defvar org-read-date-overlay nil)
9861 (defvar org-dcst nil) ; dynamically scoped
9863 (defun org-read-date (&optional with-time to-time from-string prompt
9864 default-time default-input)
9865 "Read a date, possibly a time, and make things smooth for the user.
9866 The prompt will suggest to enter an ISO date, but you can also enter anything
9867 which will at least partially be understood by `parse-time-string'.
9868 Unrecognized parts of the date will default to the current day, month, year,
9869 hour and minute. If this command is called to replace a timestamp at point,
9870 of to enter the second timestamp of a range, the default time is taken from the
9871 existing stamp. For example,
9872 3-2-5 --> 2003-02-05
9873 feb 15 --> currentyear-02-15
9874 sep 12 9 --> 2009-09-12
9875 12:45 --> today 12:45
9876 22 sept 0:34 --> currentyear-09-22 0:34
9877 12 --> currentyear-currentmonth-12
9878 Fri --> nearest Friday (today or later)
9879 etc.
9881 Furthermore you can specify a relative date by giving, as the *first* thing
9882 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
9883 change in days weeks, months, years.
9884 With a single plus or minus, the date is relative to today. With a double
9885 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
9886 +4d --> four days from today
9887 +4 --> same as above
9888 +2w --> two weeks from today
9889 ++5 --> five days from default date
9891 The function understands only English month and weekday abbreviations,
9892 but this can be configured with the variables `parse-time-months' and
9893 `parse-time-weekdays'.
9895 While prompting, a calendar is popped up - you can also select the
9896 date with the mouse (button 1). The calendar shows a period of three
9897 months. To scroll it to other months, use the keys `>' and `<'.
9898 If you don't like the calendar, turn it off with
9899 \(setq org-read-date-popup-calendar nil)
9901 With optional argument TO-TIME, the date will immediately be converted
9902 to an internal time.
9903 With an optional argument WITH-TIME, the prompt will suggest to also
9904 insert a time. Note that when WITH-TIME is not set, you can still
9905 enter a time, and this function will inform the calling routine about
9906 this change. The calling routine may then choose to change the format
9907 used to insert the time stamp into the buffer to include the time.
9908 With optional argument FROM-STRING, read from this string instead from
9909 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
9910 the time/date that is used for everything that is not specified by the
9911 user."
9912 (require 'parse-time)
9913 (let* ((org-time-stamp-rounding-minutes
9914 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
9915 (org-dcst org-display-custom-times)
9916 (ct (org-current-time))
9917 (def (or default-time ct))
9918 (defdecode (decode-time def))
9919 (dummy (progn
9920 (when (< (nth 2 defdecode) org-extend-today-until)
9921 (setcar (nthcdr 2 defdecode) -1)
9922 (setcar (nthcdr 1 defdecode) 59)
9923 (setq def (apply 'encode-time defdecode)
9924 defdecode (decode-time def)))))
9925 (calendar-move-hook nil)
9926 (calendar-view-diary-initially-flag nil)
9927 (view-diary-entries-initially nil)
9928 (calendar-view-holidays-initially-flag nil)
9929 (view-calendar-holidays-initially nil)
9930 (timestr (format-time-string
9931 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
9932 (prompt (concat (if prompt (concat prompt " ") "")
9933 (format "Date+time [%s]: " timestr)))
9934 ans (org-ans0 "") org-ans1 org-ans2 final)
9936 (cond
9937 (from-string (setq ans from-string))
9938 (org-read-date-popup-calendar
9939 (save-excursion
9940 (save-window-excursion
9941 (calendar)
9942 (calendar-forward-day (- (time-to-days def)
9943 (calendar-absolute-from-gregorian
9944 (calendar-current-date))))
9945 (org-eval-in-calendar nil t)
9946 (let* ((old-map (current-local-map))
9947 (map (copy-keymap calendar-mode-map))
9948 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
9949 (org-defkey map (kbd "RET") 'org-calendar-select)
9950 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
9951 'org-calendar-select-mouse)
9952 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
9953 'org-calendar-select-mouse)
9954 (org-defkey minibuffer-local-map [(meta shift left)]
9955 (lambda () (interactive)
9956 (org-eval-in-calendar '(calendar-backward-month 1))))
9957 (org-defkey minibuffer-local-map [(meta shift right)]
9958 (lambda () (interactive)
9959 (org-eval-in-calendar '(calendar-forward-month 1))))
9960 (org-defkey minibuffer-local-map [(meta shift up)]
9961 (lambda () (interactive)
9962 (org-eval-in-calendar '(calendar-backward-year 1))))
9963 (org-defkey minibuffer-local-map [(meta shift down)]
9964 (lambda () (interactive)
9965 (org-eval-in-calendar '(calendar-forward-year 1))))
9966 (org-defkey minibuffer-local-map [(shift up)]
9967 (lambda () (interactive)
9968 (org-eval-in-calendar '(calendar-backward-week 1))))
9969 (org-defkey minibuffer-local-map [(shift down)]
9970 (lambda () (interactive)
9971 (org-eval-in-calendar '(calendar-forward-week 1))))
9972 (org-defkey minibuffer-local-map [(shift left)]
9973 (lambda () (interactive)
9974 (org-eval-in-calendar '(calendar-backward-day 1))))
9975 (org-defkey minibuffer-local-map [(shift right)]
9976 (lambda () (interactive)
9977 (org-eval-in-calendar '(calendar-forward-day 1))))
9978 (org-defkey minibuffer-local-map ">"
9979 (lambda () (interactive)
9980 (org-eval-in-calendar '(scroll-calendar-left 1))))
9981 (org-defkey minibuffer-local-map "<"
9982 (lambda () (interactive)
9983 (org-eval-in-calendar '(scroll-calendar-right 1))))
9984 (unwind-protect
9985 (progn
9986 (use-local-map map)
9987 (add-hook 'post-command-hook 'org-read-date-display)
9988 (setq org-ans0 (read-string prompt default-input nil nil))
9989 ;; org-ans0: from prompt
9990 ;; org-ans1: from mouse click
9991 ;; org-ans2: from calendar motion
9992 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
9993 (remove-hook 'post-command-hook 'org-read-date-display)
9994 (use-local-map old-map)
9995 (when org-read-date-overlay
9996 (org-delete-overlay org-read-date-overlay)
9997 (setq org-read-date-overlay nil)))))))
9999 (t ; Naked prompt only
10000 (unwind-protect
10001 (setq ans (read-string prompt default-input nil timestr))
10002 (when org-read-date-overlay
10003 (org-delete-overlay org-read-date-overlay)
10004 (setq org-read-date-overlay nil)))))
10006 (setq final (org-read-date-analyze ans def defdecode))
10008 (if to-time
10009 (apply 'encode-time final)
10010 (if (and (boundp 'org-time-was-given) org-time-was-given)
10011 (format "%04d-%02d-%02d %02d:%02d"
10012 (nth 5 final) (nth 4 final) (nth 3 final)
10013 (nth 2 final) (nth 1 final))
10014 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10015 (defvar def)
10016 (defvar defdecode)
10017 (defvar with-time)
10018 (defun org-read-date-display ()
10019 "Display the currrent date prompt interpretation in the minibuffer."
10020 (when org-read-date-display-live
10021 (when org-read-date-overlay
10022 (org-delete-overlay org-read-date-overlay))
10023 (let ((p (point)))
10024 (end-of-line 1)
10025 (while (not (equal (buffer-substring
10026 (max (point-min) (- (point) 4)) (point))
10027 " "))
10028 (insert " "))
10029 (goto-char p))
10030 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10031 " " (or org-ans1 org-ans2)))
10032 (org-end-time-was-given nil)
10033 (f (org-read-date-analyze ans def defdecode))
10034 (fmts (if org-dcst
10035 org-time-stamp-custom-formats
10036 org-time-stamp-formats))
10037 (fmt (if (or with-time
10038 (and (boundp 'org-time-was-given) org-time-was-given))
10039 (cdr fmts)
10040 (car fmts)))
10041 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10042 (when (and org-end-time-was-given
10043 (string-match org-plain-time-of-day-regexp txt))
10044 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10045 org-end-time-was-given
10046 (substring txt (match-end 0)))))
10047 (setq org-read-date-overlay
10048 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10049 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10051 (defun org-read-date-analyze (ans def defdecode)
10052 "Analyze the combined answer of the date prompt."
10053 ;; FIXME: cleanup and comment
10054 (let (delta deltan deltaw deltadef year month day
10055 hour minute second wday pm h2 m2 tl wday1
10056 iso-year iso-weekday iso-week iso-year iso-date)
10058 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10059 (setq ans (replace-match "" t t ans)
10060 deltan (car delta)
10061 deltaw (nth 1 delta)
10062 deltadef (nth 2 delta)))
10064 ;; Check if there is an iso week date in there
10065 ;; If yes, sore the info and ostpone interpreting it until the rest
10066 ;; of the parsing is done
10067 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10068 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10069 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10070 iso-week (string-to-number (match-string 2 ans)))
10071 (setq ans (replace-match "" t t ans)))
10073 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10074 (when (string-match
10075 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10076 (setq year (if (match-end 2)
10077 (string-to-number (match-string 2 ans))
10078 (string-to-number (format-time-string "%Y")))
10079 month (string-to-number (match-string 3 ans))
10080 day (string-to-number (match-string 4 ans)))
10081 (if (< year 100) (setq year (+ 2000 year)))
10082 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10083 t nil ans)))
10084 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10085 ;; If there is a time with am/pm, and *no* time without it, we convert
10086 ;; so that matching will be successful.
10087 (loop for i from 1 to 2 do ; twice, for end time as well
10088 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10089 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10090 (setq hour (string-to-number (match-string 1 ans))
10091 minute (if (match-end 3)
10092 (string-to-number (match-string 3 ans))
10094 pm (equal ?p
10095 (string-to-char (downcase (match-string 4 ans)))))
10096 (if (and (= hour 12) (not pm))
10097 (setq hour 0)
10098 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10099 (setq ans (replace-match (format "%02d:%02d" hour minute)
10100 t t ans))))
10102 ;; Check if a time range is given as a duration
10103 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10104 (setq hour (string-to-number (match-string 1 ans))
10105 h2 (+ hour (string-to-number (match-string 3 ans)))
10106 minute (string-to-number (match-string 2 ans))
10107 m2 (+ minute (if (match-end 5) (string-to-number
10108 (match-string 5 ans))0)))
10109 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10110 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10111 t t ans)))
10113 ;; Check if there is a time range
10114 (when (boundp 'org-end-time-was-given)
10115 (setq org-time-was-given nil)
10116 (when (and (string-match org-plain-time-of-day-regexp ans)
10117 (match-end 8))
10118 (setq org-end-time-was-given (match-string 8 ans))
10119 (setq ans (concat (substring ans 0 (match-beginning 7))
10120 (substring ans (match-end 7))))))
10122 (setq tl (parse-time-string ans)
10123 day (or (nth 3 tl) (nth 3 defdecode))
10124 month (or (nth 4 tl)
10125 (if (and org-read-date-prefer-future
10126 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10127 (1+ (nth 4 defdecode))
10128 (nth 4 defdecode)))
10129 year (or (nth 5 tl)
10130 (if (and org-read-date-prefer-future
10131 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10132 (1+ (nth 5 defdecode))
10133 (nth 5 defdecode)))
10134 hour (or (nth 2 tl) (nth 2 defdecode))
10135 minute (or (nth 1 tl) (nth 1 defdecode))
10136 second (or (nth 0 tl) 0)
10137 wday (nth 6 tl))
10139 ;; Special date definitions below
10140 (cond
10141 (iso-week
10142 ;; There was an iso week
10143 (setq year (or iso-year year)
10144 day (or iso-weekday wday 1)
10145 wday nil ; to make sure that the trigger below does not match
10146 iso-date (calendar-gregorian-from-absolute
10147 (calendar-absolute-from-iso
10148 (list iso-week day year))))
10149 ; FIXME: Should we also push ISO weeks into the future?
10150 ; (when (and org-read-date-prefer-future
10151 ; (not iso-year)
10152 ; (< (calendar-absolute-from-gregorian iso-date)
10153 ; (time-to-days (current-time))))
10154 ; (setq year (1+ year)
10155 ; iso-date (calendar-gregorian-from-absolute
10156 ; (calendar-absolute-from-iso
10157 ; (list iso-week day year)))))
10158 (setq month (car iso-date)
10159 year (nth 2 iso-date)
10160 day (nth 1 iso-date)))
10161 (deltan
10162 (unless deltadef
10163 (let ((now (decode-time (current-time))))
10164 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10165 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10166 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10167 ((equal deltaw "m") (setq month (+ month deltan)))
10168 ((equal deltaw "y") (setq year (+ year deltan)))))
10169 ((and wday (not (nth 3 tl)))
10170 ;; Weekday was given, but no day, so pick that day in the week
10171 ;; on or after the derived date.
10172 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10173 (unless (equal wday wday1)
10174 (setq day (+ day (% (- wday wday1 -7) 7))))))
10175 (if (and (boundp 'org-time-was-given)
10176 (nth 2 tl))
10177 (setq org-time-was-given t))
10178 (if (< year 100) (setq year (+ 2000 year)))
10179 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10180 (list second minute hour day month year)))
10182 (defvar parse-time-weekdays)
10184 (defun org-read-date-get-relative (s today default)
10185 "Check string S for special relative date string.
10186 TODAY and DEFAULT are internal times, for today and for a default.
10187 Return shift list (N what def-flag)
10188 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10189 N is the number of WHATs to shift.
10190 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10191 the DEFAULT date rather than TODAY."
10192 (when (string-match
10193 (concat
10194 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10195 "\\([0-9]+\\)?"
10196 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10197 "\\([ \t]\\|$\\)") s)
10198 (let* ((dir (if (match-end 1)
10199 (string-to-char (substring (match-string 1 s) -1))
10200 ?+))
10201 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10202 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10203 (what (if (match-end 3) (match-string 3 s) "d"))
10204 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10205 (date (if rel default today))
10206 (wday (nth 6 (decode-time date)))
10207 delta)
10208 (if wday1
10209 (progn
10210 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10211 (if (= dir ?-) (setq delta (- delta 7)))
10212 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10213 (list delta "d" rel))
10214 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10216 (defun org-eval-in-calendar (form &optional keepdate)
10217 "Eval FORM in the calendar window and return to current window.
10218 Also, store the cursor date in variable org-ans2."
10219 (let ((sw (selected-window)))
10220 (select-window (get-buffer-window "*Calendar*"))
10221 (eval form)
10222 (when (and (not keepdate) (calendar-cursor-to-date))
10223 (let* ((date (calendar-cursor-to-date))
10224 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10225 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10226 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10227 (select-window sw)))
10229 ; ;; Update the prompt to show new default date
10230 ; (save-excursion
10231 ; (goto-char (point-min))
10232 ; (when (and org-ans2
10233 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10234 ; (get-text-property (match-end 0) 'field))
10235 ; (let ((inhibit-read-only t))
10236 ; (replace-match (concat "[" org-ans2 "]") t t)
10237 ; (add-text-properties (point-min) (1+ (match-end 0))
10238 ; (text-properties-at (1+ (point-min)))))))))
10240 (defun org-calendar-select ()
10241 "Return to `org-read-date' with the date currently selected.
10242 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10243 (interactive)
10244 (when (calendar-cursor-to-date)
10245 (let* ((date (calendar-cursor-to-date))
10246 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10247 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10248 (if (active-minibuffer-window) (exit-minibuffer))))
10250 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10251 "Insert a date stamp for the date given by the internal TIME.
10252 WITH-HM means, use the stamp format that includes the time of the day.
10253 INACTIVE means use square brackets instead of angular ones, so that the
10254 stamp will not contribute to the agenda.
10255 PRE and POST are optional strings to be inserted before and after the
10256 stamp.
10257 The command returns the inserted time stamp."
10258 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10259 stamp)
10260 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10261 (insert-before-markers (or pre ""))
10262 (insert-before-markers (setq stamp (format-time-string fmt time)))
10263 (when (listp extra)
10264 (setq extra (car extra))
10265 (if (and (stringp extra)
10266 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10267 (setq extra (format "-%02d:%02d"
10268 (string-to-number (match-string 1 extra))
10269 (string-to-number (match-string 2 extra))))
10270 (setq extra nil)))
10271 (when extra
10272 (backward-char 1)
10273 (insert-before-markers extra)
10274 (forward-char 1))
10275 (insert-before-markers (or post ""))
10276 stamp))
10278 (defun org-toggle-time-stamp-overlays ()
10279 "Toggle the use of custom time stamp formats."
10280 (interactive)
10281 (setq org-display-custom-times (not org-display-custom-times))
10282 (unless org-display-custom-times
10283 (let ((p (point-min)) (bmp (buffer-modified-p)))
10284 (while (setq p (next-single-property-change p 'display))
10285 (if (and (get-text-property p 'display)
10286 (eq (get-text-property p 'face) 'org-date))
10287 (remove-text-properties
10288 p (setq p (next-single-property-change p 'display))
10289 '(display t))))
10290 (set-buffer-modified-p bmp)))
10291 (if (featurep 'xemacs)
10292 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10293 (org-restart-font-lock)
10294 (setq org-table-may-need-update t)
10295 (if org-display-custom-times
10296 (message "Time stamps are overlayed with custom format")
10297 (message "Time stamp overlays removed")))
10299 (defun org-display-custom-time (beg end)
10300 "Overlay modified time stamp format over timestamp between BED and END."
10301 (let* ((ts (buffer-substring beg end))
10302 t1 w1 with-hm tf time str w2 (off 0))
10303 (save-match-data
10304 (setq t1 (org-parse-time-string ts t))
10305 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10306 (setq off (- (match-end 0) (match-beginning 0)))))
10307 (setq end (- end off))
10308 (setq w1 (- end beg)
10309 with-hm (and (nth 1 t1) (nth 2 t1))
10310 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10311 time (org-fix-decoded-time t1)
10312 str (org-add-props
10313 (format-time-string
10314 (substring tf 1 -1) (apply 'encode-time time))
10315 nil 'mouse-face 'highlight)
10316 w2 (length str))
10317 (if (not (= w2 w1))
10318 (add-text-properties (1+ beg) (+ 2 beg)
10319 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10320 (if (featurep 'xemacs)
10321 (progn
10322 (put-text-property beg end 'invisible t)
10323 (put-text-property beg end 'end-glyph (make-glyph str)))
10324 (put-text-property beg end 'display str))))
10326 (defun org-translate-time (string)
10327 "Translate all timestamps in STRING to custom format.
10328 But do this only if the variable `org-display-custom-times' is set."
10329 (when org-display-custom-times
10330 (save-match-data
10331 (let* ((start 0)
10332 (re org-ts-regexp-both)
10333 t1 with-hm inactive tf time str beg end)
10334 (while (setq start (string-match re string start))
10335 (setq beg (match-beginning 0)
10336 end (match-end 0)
10337 t1 (save-match-data
10338 (org-parse-time-string (substring string beg end) t))
10339 with-hm (and (nth 1 t1) (nth 2 t1))
10340 inactive (equal (substring string beg (1+ beg)) "[")
10341 tf (funcall (if with-hm 'cdr 'car)
10342 org-time-stamp-custom-formats)
10343 time (org-fix-decoded-time t1)
10344 str (format-time-string
10345 (concat
10346 (if inactive "[" "<") (substring tf 1 -1)
10347 (if inactive "]" ">"))
10348 (apply 'encode-time time))
10349 string (replace-match str t t string)
10350 start (+ start (length str)))))))
10351 string)
10353 (defun org-fix-decoded-time (time)
10354 "Set 0 instead of nil for the first 6 elements of time.
10355 Don't touch the rest."
10356 (let ((n 0))
10357 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10359 (defun org-days-to-time (timestamp-string)
10360 "Difference between TIMESTAMP-STRING and now in days."
10361 (- (time-to-days (org-time-string-to-time timestamp-string))
10362 (time-to-days (current-time))))
10364 (defun org-deadline-close (timestamp-string &optional ndays)
10365 "Is the time in TIMESTAMP-STRING close to the current date?"
10366 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10367 (and (< (org-days-to-time timestamp-string) ndays)
10368 (not (org-entry-is-done-p))))
10370 (defun org-get-wdays (ts)
10371 "Get the deadline lead time appropriate for timestring TS."
10372 (cond
10373 ((<= org-deadline-warning-days 0)
10374 ;; 0 or negative, enforce this value no matter what
10375 (- org-deadline-warning-days))
10376 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10377 ;; lead time is specified.
10378 (floor (* (string-to-number (match-string 1 ts))
10379 (cdr (assoc (match-string 2 ts)
10380 '(("d" . 1) ("w" . 7)
10381 ("m" . 30.4) ("y" . 365.25)))))))
10382 ;; go for the default.
10383 (t org-deadline-warning-days)))
10385 (defun org-calendar-select-mouse (ev)
10386 "Return to `org-read-date' with the date currently selected.
10387 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10388 (interactive "e")
10389 (mouse-set-point ev)
10390 (when (calendar-cursor-to-date)
10391 (let* ((date (calendar-cursor-to-date))
10392 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10393 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10394 (if (active-minibuffer-window) (exit-minibuffer))))
10396 (defun org-check-deadlines (ndays)
10397 "Check if there are any deadlines due or past due.
10398 A deadline is considered due if it happens within `org-deadline-warning-days'
10399 days from today's date. If the deadline appears in an entry marked DONE,
10400 it is not shown. The prefix arg NDAYS can be used to test that many
10401 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10402 (interactive "P")
10403 (let* ((org-warn-days
10404 (cond
10405 ((equal ndays '(4)) 100000)
10406 (ndays (prefix-numeric-value ndays))
10407 (t (abs org-deadline-warning-days))))
10408 (case-fold-search nil)
10409 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10410 (callback
10411 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10413 (message "%d deadlines past-due or due within %d days"
10414 (org-occur regexp nil callback)
10415 org-warn-days)))
10417 (defun org-check-before-date (date)
10418 "Check if there are deadlines or scheduled entries before DATE."
10419 (interactive (list (org-read-date)))
10420 (let ((case-fold-search nil)
10421 (regexp (concat "\\<\\(" org-deadline-string
10422 "\\|" org-scheduled-string
10423 "\\) *<\\([^>]+\\)>"))
10424 (callback
10425 (lambda () (time-less-p
10426 (org-time-string-to-time (match-string 2))
10427 (org-time-string-to-time date)))))
10428 (message "%d entries before %s"
10429 (org-occur regexp nil callback) date)))
10431 (defun org-evaluate-time-range (&optional to-buffer)
10432 "Evaluate a time range by computing the difference between start and end.
10433 Normally the result is just printed in the echo area, but with prefix arg
10434 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10435 If the time range is actually in a table, the result is inserted into the
10436 next column.
10437 For time difference computation, a year is assumed to be exactly 365
10438 days in order to avoid rounding problems."
10439 (interactive "P")
10441 (org-clock-update-time-maybe)
10442 (save-excursion
10443 (unless (org-at-date-range-p t)
10444 (goto-char (point-at-bol))
10445 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10446 (if (not (org-at-date-range-p t))
10447 (error "Not at a time-stamp range, and none found in current line")))
10448 (let* ((ts1 (match-string 1))
10449 (ts2 (match-string 2))
10450 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10451 (match-end (match-end 0))
10452 (time1 (org-time-string-to-time ts1))
10453 (time2 (org-time-string-to-time ts2))
10454 (t1 (time-to-seconds time1))
10455 (t2 (time-to-seconds time2))
10456 (diff (abs (- t2 t1)))
10457 (negative (< (- t2 t1) 0))
10458 ;; (ys (floor (* 365 24 60 60)))
10459 (ds (* 24 60 60))
10460 (hs (* 60 60))
10461 (fy "%dy %dd %02d:%02d")
10462 (fy1 "%dy %dd")
10463 (fd "%dd %02d:%02d")
10464 (fd1 "%dd")
10465 (fh "%02d:%02d")
10466 y d h m align)
10467 (if havetime
10468 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10470 d (floor (/ diff ds)) diff (mod diff ds)
10471 h (floor (/ diff hs)) diff (mod diff hs)
10472 m (floor (/ diff 60)))
10473 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10475 d (floor (+ (/ diff ds) 0.5))
10476 h 0 m 0))
10477 (if (not to-buffer)
10478 (message "%s" (org-make-tdiff-string y d h m))
10479 (if (org-at-table-p)
10480 (progn
10481 (goto-char match-end)
10482 (setq align t)
10483 (and (looking-at " *|") (goto-char (match-end 0))))
10484 (goto-char match-end))
10485 (if (looking-at
10486 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10487 (replace-match ""))
10488 (if negative (insert " -"))
10489 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10490 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10491 (insert " " (format fh h m))))
10492 (if align (org-table-align))
10493 (message "Time difference inserted")))))
10495 (defun org-make-tdiff-string (y d h m)
10496 (let ((fmt "")
10497 (l nil))
10498 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10499 l (push y l)))
10500 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10501 l (push d l)))
10502 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10503 l (push h l)))
10504 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10505 l (push m l)))
10506 (apply 'format fmt (nreverse l))))
10508 (defun org-time-string-to-time (s)
10509 (apply 'encode-time (org-parse-time-string s)))
10511 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10512 "Convert a time stamp to an absolute day number.
10513 If there is a specifyer for a cyclic time stamp, get the closest date to
10514 DAYNR.
10515 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10516 (cond
10517 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10518 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10519 daynr
10520 (+ daynr 1000)))
10521 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10522 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10523 (time-to-days (current-time))) (match-string 0 s)
10524 prefer show-all))
10525 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10527 (defun org-days-to-iso-week (days)
10528 "Return the iso week number."
10529 (require 'cal-iso)
10530 (car (calendar-iso-from-absolute days)))
10532 (defun org-small-year-to-year (year)
10533 "Convert 2-digit years into 4-digit years.
10534 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10535 The year 2000 cannot be abbreviated. Any year lager than 99
10536 is retrned unchanged."
10537 (if (< year 38)
10538 (setq year (+ 2000 year))
10539 (if (< year 100)
10540 (setq year (+ 1900 year))))
10541 year)
10543 (defun org-time-from-absolute (d)
10544 "Return the time corresponding to date D.
10545 D may be an absolute day number, or a calendar-type list (month day year)."
10546 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10547 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10549 (defun org-calendar-holiday ()
10550 "List of holidays, for Diary display in Org-mode."
10551 (require 'holidays)
10552 (let ((hl (funcall
10553 (if (fboundp 'calendar-check-holidays)
10554 'calendar-check-holidays 'check-calendar-holidays) date)))
10555 (if hl (mapconcat 'identity hl "; "))))
10557 (defun org-diary-sexp-entry (sexp entry date)
10558 "Process a SEXP diary ENTRY for DATE."
10559 (require 'diary-lib)
10560 (let ((result (if calendar-debug-sexp
10561 (let ((stack-trace-on-error t))
10562 (eval (car (read-from-string sexp))))
10563 (condition-case nil
10564 (eval (car (read-from-string sexp)))
10565 (error
10566 (beep)
10567 (message "Bad sexp at line %d in %s: %s"
10568 (org-current-line)
10569 (buffer-file-name) sexp)
10570 (sleep-for 2))))))
10571 (cond ((stringp result) result)
10572 ((and (consp result)
10573 (stringp (cdr result))) (cdr result))
10574 (result entry)
10575 (t nil))))
10577 (defun org-diary-to-ical-string (frombuf)
10578 "Get iCalendar entries from diary entries in buffer FROMBUF.
10579 This uses the icalendar.el library."
10580 (let* ((tmpdir (if (featurep 'xemacs)
10581 (temp-directory)
10582 temporary-file-directory))
10583 (tmpfile (make-temp-name
10584 (expand-file-name "orgics" tmpdir)))
10585 buf rtn b e)
10586 (save-excursion
10587 (set-buffer frombuf)
10588 (icalendar-export-region (point-min) (point-max) tmpfile)
10589 (setq buf (find-buffer-visiting tmpfile))
10590 (set-buffer buf)
10591 (goto-char (point-min))
10592 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10593 (setq b (match-beginning 0)))
10594 (goto-char (point-max))
10595 (if (re-search-backward "^END:VEVENT" nil t)
10596 (setq e (match-end 0)))
10597 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10598 (kill-buffer buf)
10599 (kill-buffer frombuf)
10600 (delete-file tmpfile)
10601 rtn))
10603 (defun org-closest-date (start current change prefer show-all)
10604 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10605 When PREFER is `past' return a date that is either CURRENT or past.
10606 When PREFER is `future', return a date that is either CURRENT or future.
10607 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10608 ;; Make the proper lists from the dates
10609 (catch 'exit
10610 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10611 dn dw sday cday n1 n2
10612 d m y y1 y2 date1 date2 nmonths nm ny m2)
10614 (setq start (org-date-to-gregorian start)
10615 current (org-date-to-gregorian
10616 (if show-all
10617 current
10618 (time-to-days (current-time))))
10619 sday (calendar-absolute-from-gregorian start)
10620 cday (calendar-absolute-from-gregorian current))
10622 (if (<= cday sday) (throw 'exit sday))
10624 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10625 (setq dn (string-to-number (match-string 1 change))
10626 dw (cdr (assoc (match-string 2 change) a1)))
10627 (error "Invalid change specifyer: %s" change))
10628 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10629 (cond
10630 ((eq dw 'day)
10631 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10632 n2 (+ n1 dn)))
10633 ((eq dw 'year)
10634 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10635 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10636 (setq date1 (list m d y1)
10637 n1 (calendar-absolute-from-gregorian date1)
10638 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10639 n2 (calendar-absolute-from-gregorian date2)))
10640 ((eq dw 'month)
10641 ;; approx number of month between the tow dates
10642 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10643 ;; How often does dn fit in there?
10644 (setq d (nth 1 start) m (car start) y (nth 2 start)
10645 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10646 m (+ m nm)
10647 ny (floor (/ m 12))
10648 y (+ y ny)
10649 m (- m (* ny 12)))
10650 (while (> m 12) (setq m (- m 12) y (1+ y)))
10651 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10652 (setq m2 (+ m dn) y2 y)
10653 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10654 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10655 (while (< n2 cday)
10656 (setq n1 n2 m m2 y y2)
10657 (setq m2 (+ m dn) y2 y)
10658 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10659 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10661 (if show-all
10662 (cond
10663 ((eq prefer 'past) n1)
10664 ((eq prefer 'future) (if (= cday n1) n1 n2))
10665 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10666 (cond
10667 ((eq prefer 'past) n1)
10668 ((eq prefer 'future) (if (= cday n1) n1 n2))
10669 (t (if (= cday n1) n1 n2)))))))
10671 (defun org-date-to-gregorian (date)
10672 "Turn any specification of DATE into a gregorian date for the calendar."
10673 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10674 ((and (listp date) (= (length date) 3)) date)
10675 ((stringp date)
10676 (setq date (org-parse-time-string date))
10677 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10678 ((listp date)
10679 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10681 (defun org-parse-time-string (s &optional nodefault)
10682 "Parse the standard Org-mode time string.
10683 This should be a lot faster than the normal `parse-time-string'.
10684 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10685 hour and minute fields will be nil if not given."
10686 (if (string-match org-ts-regexp0 s)
10687 (list 0
10688 (if (or (match-beginning 8) (not nodefault))
10689 (string-to-number (or (match-string 8 s) "0")))
10690 (if (or (match-beginning 7) (not nodefault))
10691 (string-to-number (or (match-string 7 s) "0")))
10692 (string-to-number (match-string 4 s))
10693 (string-to-number (match-string 3 s))
10694 (string-to-number (match-string 2 s))
10695 nil nil nil)
10696 (make-list 9 0)))
10698 (defun org-timestamp-up (&optional arg)
10699 "Increase the date item at the cursor by one.
10700 If the cursor is on the year, change the year. If it is on the month or
10701 the day, change that.
10702 With prefix ARG, change by that many units."
10703 (interactive "p")
10704 (org-timestamp-change (prefix-numeric-value arg)))
10706 (defun org-timestamp-down (&optional arg)
10707 "Decrease the date item at the cursor by one.
10708 If the cursor is on the year, change the year. If it is on the month or
10709 the day, change that.
10710 With prefix ARG, change by that many units."
10711 (interactive "p")
10712 (org-timestamp-change (- (prefix-numeric-value arg))))
10714 (defun org-timestamp-up-day (&optional arg)
10715 "Increase the date in the time stamp by one day.
10716 With prefix ARG, change that many days."
10717 (interactive "p")
10718 (if (and (not (org-at-timestamp-p t))
10719 (org-on-heading-p))
10720 (org-todo 'up)
10721 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10723 (defun org-timestamp-down-day (&optional arg)
10724 "Decrease the date in the time stamp by one day.
10725 With prefix ARG, change that many days."
10726 (interactive "p")
10727 (if (and (not (org-at-timestamp-p t))
10728 (org-on-heading-p))
10729 (org-todo 'down)
10730 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10732 (defun org-at-timestamp-p (&optional inactive-ok)
10733 "Determine if the cursor is in or at a timestamp."
10734 (interactive)
10735 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10736 (pos (point))
10737 (ans (or (looking-at tsr)
10738 (save-excursion
10739 (skip-chars-backward "^[<\n\r\t")
10740 (if (> (point) (point-min)) (backward-char 1))
10741 (and (looking-at tsr)
10742 (> (- (match-end 0) pos) -1))))))
10743 (and ans
10744 (boundp 'org-ts-what)
10745 (setq org-ts-what
10746 (cond
10747 ((= pos (match-beginning 0)) 'bracket)
10748 ((= pos (1- (match-end 0))) 'bracket)
10749 ((org-pos-in-match-range pos 2) 'year)
10750 ((org-pos-in-match-range pos 3) 'month)
10751 ((org-pos-in-match-range pos 7) 'hour)
10752 ((org-pos-in-match-range pos 8) 'minute)
10753 ((or (org-pos-in-match-range pos 4)
10754 (org-pos-in-match-range pos 5)) 'day)
10755 ((and (> pos (or (match-end 8) (match-end 5)))
10756 (< pos (match-end 0)))
10757 (- pos (or (match-end 8) (match-end 5))))
10758 (t 'day))))
10759 ans))
10761 (defun org-toggle-timestamp-type ()
10762 "Toggle the type (<active> or [inactive]) of a time stamp."
10763 (interactive)
10764 (when (org-at-timestamp-p t)
10765 (save-excursion
10766 (goto-char (match-beginning 0))
10767 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10768 (goto-char (1- (match-end 0)))
10769 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10770 (message "Timestamp is now %sactive"
10771 (if (equal (char-before) ?>) "in" ""))))
10773 (defun org-timestamp-change (n &optional what)
10774 "Change the date in the time stamp at point.
10775 The date will be changed by N times WHAT. WHAT can be `day', `month',
10776 `year', `minute', `second'. If WHAT is not given, the cursor position
10777 in the timestamp determines what will be changed."
10778 (let ((pos (point))
10779 with-hm inactive
10780 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10781 org-ts-what
10782 extra rem
10783 ts time time0)
10784 (if (not (org-at-timestamp-p t))
10785 (error "Not at a timestamp"))
10786 (if (and (not what) (eq org-ts-what 'bracket))
10787 (org-toggle-timestamp-type)
10788 (if (and (not what) (not (eq org-ts-what 'day))
10789 org-display-custom-times
10790 (get-text-property (point) 'display)
10791 (not (get-text-property (1- (point)) 'display)))
10792 (setq org-ts-what 'day))
10793 (setq org-ts-what (or what org-ts-what)
10794 inactive (= (char-after (match-beginning 0)) ?\[)
10795 ts (match-string 0))
10796 (replace-match "")
10797 (if (string-match
10798 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10800 (setq extra (match-string 1 ts)))
10801 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10802 (setq with-hm t))
10803 (setq time0 (org-parse-time-string ts))
10804 (when (and (eq org-ts-what 'minute)
10805 (eq current-prefix-arg nil))
10806 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10807 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10808 (setcar (cdr time0) (+ (nth 1 time0)
10809 (if (> n 0) (- rem) (- dm rem))))))
10810 (setq time
10811 (encode-time (or (car time0) 0)
10812 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10813 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10814 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10815 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10816 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10817 (nthcdr 6 time0)))
10818 (when (integerp org-ts-what)
10819 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10820 (if (eq what 'calendar)
10821 (let ((cal-date (org-get-date-from-calendar)))
10822 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10823 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10824 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10825 (setcar time0 (or (car time0) 0))
10826 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10827 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10828 (setq time (apply 'encode-time time0))))
10829 (setq org-last-changed-timestamp
10830 (org-insert-time-stamp time with-hm inactive nil nil extra))
10831 (org-clock-update-time-maybe)
10832 (goto-char pos)
10833 ;; Try to recenter the calendar window, if any
10834 (if (and org-calendar-follow-timestamp-change
10835 (get-buffer-window "*Calendar*" t)
10836 (memq org-ts-what '(day month year)))
10837 (org-recenter-calendar (time-to-days time))))))
10839 (defun org-modify-ts-extra (s pos n dm)
10840 "Change the different parts of the lead-time and repeat fields in timestamp."
10841 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10842 ng h m new rem)
10843 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10844 (cond
10845 ((or (org-pos-in-match-range pos 2)
10846 (org-pos-in-match-range pos 3))
10847 (setq m (string-to-number (match-string 3 s))
10848 h (string-to-number (match-string 2 s)))
10849 (if (org-pos-in-match-range pos 2)
10850 (setq h (+ h n))
10851 (setq n (* dm (org-no-warnings (signum n))))
10852 (when (not (= 0 (setq rem (% m dm))))
10853 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10854 (setq m (+ m n)))
10855 (if (< m 0) (setq m (+ m 60) h (1- h)))
10856 (if (> m 59) (setq m (- m 60) h (1+ h)))
10857 (setq h (min 24 (max 0 h)))
10858 (setq ng 1 new (format "-%02d:%02d" h m)))
10859 ((org-pos-in-match-range pos 6)
10860 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10861 ((org-pos-in-match-range pos 5)
10862 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10864 ((org-pos-in-match-range pos 9)
10865 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10866 ((org-pos-in-match-range pos 8)
10867 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10869 (when ng
10870 (setq s (concat
10871 (substring s 0 (match-beginning ng))
10873 (substring s (match-end ng))))))
10876 (defun org-recenter-calendar (date)
10877 "If the calendar is visible, recenter it to DATE."
10878 (let* ((win (selected-window))
10879 (cwin (get-buffer-window "*Calendar*" t))
10880 (calendar-move-hook nil))
10881 (when cwin
10882 (select-window cwin)
10883 (calendar-goto-date (if (listp date) date
10884 (calendar-gregorian-from-absolute date)))
10885 (select-window win))))
10887 (defun org-goto-calendar (&optional arg)
10888 "Go to the Emacs calendar at the current date.
10889 If there is a time stamp in the current line, go to that date.
10890 A prefix ARG can be used to force the current date."
10891 (interactive "P")
10892 (let ((tsr org-ts-regexp) diff
10893 (calendar-move-hook nil)
10894 (calendar-view-holidays-initially-flag nil)
10895 (view-calendar-holidays-initially nil)
10896 (calendar-view-diary-initially-flag nil)
10897 (view-diary-entries-initially nil))
10898 (if (or (org-at-timestamp-p)
10899 (save-excursion
10900 (beginning-of-line 1)
10901 (looking-at (concat ".*" tsr))))
10902 (let ((d1 (time-to-days (current-time)))
10903 (d2 (time-to-days
10904 (org-time-string-to-time (match-string 1)))))
10905 (setq diff (- d2 d1))))
10906 (calendar)
10907 (calendar-goto-today)
10908 (if (and diff (not arg)) (calendar-forward-day diff))))
10910 (defun org-get-date-from-calendar ()
10911 "Return a list (month day year) of date at point in calendar."
10912 (with-current-buffer "*Calendar*"
10913 (save-match-data
10914 (calendar-cursor-to-date))))
10916 (defun org-date-from-calendar ()
10917 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
10918 If there is already a time stamp at the cursor position, update it."
10919 (interactive)
10920 (if (org-at-timestamp-p t)
10921 (org-timestamp-change 0 'calendar)
10922 (let ((cal-date (org-get-date-from-calendar)))
10923 (org-insert-time-stamp
10924 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
10926 (defun org-minutes-to-hours (m)
10927 "Compute H:MM from a number of minutes."
10928 (let ((h (/ m 60)))
10929 (setq m (- m (* 60 h)))
10930 (format "%d:%02d" h m)))
10933 ;;;; Agenda files
10935 ;;;###autoload
10936 (defun org-iswitchb (&optional arg)
10937 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
10938 With a prefix argument, restrict available to files.
10939 With two prefix arguments, restrict available buffers to agenda files.
10941 Due to some yet unresolved reason, global function
10942 `iswitchb-mode' needs to be active for this function to work."
10943 (interactive "P")
10944 (require 'iswitchb)
10945 (let ((enabled iswitchb-mode) blist)
10946 (or enabled (iswitchb-mode 1))
10947 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
10948 ((equal arg '(16)) (org-buffer-list 'agenda))
10949 (t (org-buffer-list))))
10950 (unwind-protect
10951 (let ((iswitchb-make-buflist-hook
10952 (lambda ()
10953 (setq iswitchb-temp-buflist
10954 (mapcar 'buffer-name blist)))))
10955 (switch-to-buffer
10956 (iswitchb-read-buffer
10957 "Switch-to: " nil t))
10958 (or enabled (iswitchb-mode -1))))))
10960 (defun org-buffer-list (&optional predicate tmp)
10961 "Return a list of Org buffers.
10962 PREDICATE can be either 'export, 'files or 'agenda.
10964 'export restrict the list to Export buffers.
10965 'files restrict the list to buffers visiting Org files.
10966 'agenda restrict the list to buffers visiting agenda files.
10968 If TMP is non-nil, don't include temporary buffers."
10969 (let (filter blist)
10970 (setq filter
10971 (cond ((eq predicate 'files) "\.org$")
10972 ((eq predicate 'export) "\*Org .*Export")
10973 (t "\*Org \\|\.org$")))
10974 (setq blist
10975 (mapcar
10976 (lambda(b)
10977 (let ((bname (buffer-name b))
10978 (bfile (buffer-file-name b)))
10979 (if (and (string-match filter bname)
10980 (if (eq predicate 'agenda)
10981 (member bfile
10982 (mapcar (lambda(f) (file-truename f))
10983 org-agenda-files)) t)
10984 (if tmp (not (string-match "tmp" bname)) t)) b)))
10985 (buffer-list)))
10986 (delete nil blist)))
10988 (defun org-agenda-files (&optional unrestricted)
10989 "Get the list of agenda files.
10990 Optional UNRESTRICTED means return the full list even if a restriction
10991 is currently in place."
10992 (let ((files
10993 (cond
10994 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
10995 ((stringp org-agenda-files) (org-read-agenda-file-list))
10996 ((listp org-agenda-files) org-agenda-files)
10997 (t (error "Invalid value of `org-agenda-files'")))))
10998 (setq files (apply 'append
10999 (mapcar (lambda (f)
11000 (if (file-directory-p f)
11001 (directory-files f t
11002 org-agenda-file-regexp)
11003 (list f)))
11004 files)))
11005 (if org-agenda-skip-unavailable-files
11006 (delq nil
11007 (mapcar (function
11008 (lambda (file)
11009 (and (file-readable-p file) file)))
11010 files))
11011 files))) ; `org-check-agenda-file' will remove them from the list
11013 (defun org-edit-agenda-file-list ()
11014 "Edit the list of agenda files.
11015 Depending on setup, this either uses customize to edit the variable
11016 `org-agenda-files', or it visits the file that is holding the list. In the
11017 latter case, the buffer is set up in a way that saving it automatically kills
11018 the buffer and restores the previous window configuration."
11019 (interactive)
11020 (if (stringp org-agenda-files)
11021 (let ((cw (current-window-configuration)))
11022 (find-file org-agenda-files)
11023 (org-set-local 'org-window-configuration cw)
11024 (org-add-hook 'after-save-hook
11025 (lambda ()
11026 (set-window-configuration
11027 (prog1 org-window-configuration
11028 (kill-buffer (current-buffer))))
11029 (org-install-agenda-files-menu)
11030 (message "New agenda file list installed"))
11031 nil 'local)
11032 (message "%s" (substitute-command-keys
11033 "Edit list and finish with \\[save-buffer]")))
11034 (customize-variable 'org-agenda-files)))
11036 (defun org-store-new-agenda-file-list (list)
11037 "Set new value for the agenda file list and save it correcly."
11038 (if (stringp org-agenda-files)
11039 (let ((f org-agenda-files) b)
11040 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11041 (with-temp-file f
11042 (insert (mapconcat 'identity list "\n") "\n")))
11043 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11044 (setq org-agenda-files list)
11045 (customize-save-variable 'org-agenda-files org-agenda-files))))
11047 (defun org-read-agenda-file-list ()
11048 "Read the list of agenda files from a file."
11049 (when (stringp org-agenda-files)
11050 (with-temp-buffer
11051 (insert-file-contents org-agenda-files)
11052 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11055 ;;;###autoload
11056 (defun org-cycle-agenda-files ()
11057 "Cycle through the files in `org-agenda-files'.
11058 If the current buffer visits an agenda file, find the next one in the list.
11059 If the current buffer does not, find the first agenda file."
11060 (interactive)
11061 (let* ((fs (org-agenda-files t))
11062 (files (append fs (list (car fs))))
11063 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11064 file)
11065 (unless files (error "No agenda files"))
11066 (catch 'exit
11067 (while (setq file (pop files))
11068 (if (equal (file-truename file) tcf)
11069 (when (car files)
11070 (find-file (car files))
11071 (throw 'exit t))))
11072 (find-file (car fs)))
11073 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11075 (defun org-agenda-file-to-front (&optional to-end)
11076 "Move/add the current file to the top of the agenda file list.
11077 If the file is not present in the list, it is added to the front. If it is
11078 present, it is moved there. With optional argument TO-END, add/move to the
11079 end of the list."
11080 (interactive "P")
11081 (let ((org-agenda-skip-unavailable-files nil)
11082 (file-alist (mapcar (lambda (x)
11083 (cons (file-truename x) x))
11084 (org-agenda-files t)))
11085 (ctf (file-truename buffer-file-name))
11086 x had)
11087 (setq x (assoc ctf file-alist) had x)
11089 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11090 (if to-end
11091 (setq file-alist (append (delq x file-alist) (list x)))
11092 (setq file-alist (cons x (delq x file-alist))))
11093 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11094 (org-install-agenda-files-menu)
11095 (message "File %s to %s of agenda file list"
11096 (if had "moved" "added") (if to-end "end" "front"))))
11098 (defun org-remove-file (&optional file)
11099 "Remove current file from the list of files in variable `org-agenda-files'.
11100 These are the files which are being checked for agenda entries.
11101 Optional argument FILE means, use this file instead of the current."
11102 (interactive)
11103 (let* ((org-agenda-skip-unavailable-files nil)
11104 (file (or file buffer-file-name))
11105 (true-file (file-truename file))
11106 (afile (abbreviate-file-name file))
11107 (files (delq nil (mapcar
11108 (lambda (x)
11109 (if (equal true-file
11110 (file-truename x))
11111 nil x))
11112 (org-agenda-files t)))))
11113 (if (not (= (length files) (length (org-agenda-files t))))
11114 (progn
11115 (org-store-new-agenda-file-list files)
11116 (org-install-agenda-files-menu)
11117 (message "Removed file: %s" afile))
11118 (message "File was not in list: %s (not removed)" afile))))
11120 (defun org-file-menu-entry (file)
11121 (vector file (list 'find-file file) t))
11123 (defun org-check-agenda-file (file)
11124 "Make sure FILE exists. If not, ask user what to do."
11125 (when (not (file-exists-p file))
11126 (message "non-existent file %s. [R]emove from list or [A]bort?"
11127 (abbreviate-file-name file))
11128 (let ((r (downcase (read-char-exclusive))))
11129 (cond
11130 ((equal r ?r)
11131 (org-remove-file file)
11132 (throw 'nextfile t))
11133 (t (error "Abort"))))))
11135 (defun org-get-agenda-file-buffer (file)
11136 "Get a buffer visiting FILE. If the buffer needs to be created, add
11137 it to the list of buffers which might be released later."
11138 (let ((buf (org-find-base-buffer-visiting file)))
11139 (if buf
11140 buf ; just return it
11141 ;; Make a new buffer and remember it
11142 (setq buf (find-file-noselect file))
11143 (if buf (push buf org-agenda-new-buffers))
11144 buf)))
11146 (defun org-release-buffers (blist)
11147 "Release all buffers in list, asking the user for confirmation when needed.
11148 When a buffer is unmodified, it is just killed. When modified, it is saved
11149 \(if the user agrees) and then killed."
11150 (let (buf file)
11151 (while (setq buf (pop blist))
11152 (setq file (buffer-file-name buf))
11153 (when (and (buffer-modified-p buf)
11154 file
11155 (y-or-n-p (format "Save file %s? " file)))
11156 (with-current-buffer buf (save-buffer)))
11157 (kill-buffer buf))))
11159 (defun org-prepare-agenda-buffers (files)
11160 "Create buffers for all agenda files, protect archived trees and comments."
11161 (interactive)
11162 (let ((pa '(:org-archived t))
11163 (pc '(:org-comment t))
11164 (pall '(:org-archived t :org-comment t))
11165 (inhibit-read-only t)
11166 (rea (concat ":" org-archive-tag ":"))
11167 bmp file re)
11168 (save-excursion
11169 (save-restriction
11170 (while (setq file (pop files))
11171 (if (bufferp file)
11172 (set-buffer file)
11173 (org-check-agenda-file file)
11174 (set-buffer (org-get-agenda-file-buffer file)))
11175 (widen)
11176 (setq bmp (buffer-modified-p))
11177 (org-refresh-category-properties)
11178 (setq org-todo-keywords-for-agenda
11179 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11180 (setq org-done-keywords-for-agenda
11181 (append org-done-keywords-for-agenda org-done-keywords))
11182 (save-excursion
11183 (remove-text-properties (point-min) (point-max) pall)
11184 (when org-agenda-skip-archived-trees
11185 (goto-char (point-min))
11186 (while (re-search-forward rea nil t)
11187 (if (org-on-heading-p t)
11188 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11189 (goto-char (point-min))
11190 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11191 (while (re-search-forward re nil t)
11192 (add-text-properties
11193 (match-beginning 0) (org-end-of-subtree t) pc)))
11194 (set-buffer-modified-p bmp))))))
11196 ;;;; Embedded LaTeX
11198 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11199 "Keymap for the minor `org-cdlatex-mode'.")
11201 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11202 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11203 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11204 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11205 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11207 (defvar org-cdlatex-texmathp-advice-is-done nil
11208 "Flag remembering if we have applied the advice to texmathp already.")
11210 (define-minor-mode org-cdlatex-mode
11211 "Toggle the minor `org-cdlatex-mode'.
11212 This mode supports entering LaTeX environment and math in LaTeX fragments
11213 in Org-mode.
11214 \\{org-cdlatex-mode-map}"
11215 nil " OCDL" nil
11216 (when org-cdlatex-mode (require 'cdlatex))
11217 (unless org-cdlatex-texmathp-advice-is-done
11218 (setq org-cdlatex-texmathp-advice-is-done t)
11219 (defadvice texmathp (around org-math-always-on activate)
11220 "Always return t in org-mode buffers.
11221 This is because we want to insert math symbols without dollars even outside
11222 the LaTeX math segments. If Orgmode thinks that point is actually inside
11223 en embedded LaTeX fragement, let texmathp do its job.
11224 \\[org-cdlatex-mode-map]"
11225 (interactive)
11226 (let (p)
11227 (cond
11228 ((not (org-mode-p)) ad-do-it)
11229 ((eq this-command 'cdlatex-math-symbol)
11230 (setq ad-return-value t
11231 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11233 (let ((p (org-inside-LaTeX-fragment-p)))
11234 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11235 (setq ad-return-value t
11236 texmathp-why '("Org-mode embedded math" . 0))
11237 (if p ad-do-it)))))))))
11239 (defun turn-on-org-cdlatex ()
11240 "Unconditionally turn on `org-cdlatex-mode'."
11241 (org-cdlatex-mode 1))
11243 (defun org-inside-LaTeX-fragment-p ()
11244 "Test if point is inside a LaTeX fragment.
11245 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11246 sequence appearing also before point.
11247 Even though the matchers for math are configurable, this function assumes
11248 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11249 delimiters are skipped when they have been removed by customization.
11250 The return value is nil, or a cons cell with the delimiter and
11251 and the position of this delimiter.
11253 This function does a reasonably good job, but can locally be fooled by
11254 for example currency specifications. For example it will assume being in
11255 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11256 fragments that are properly closed, but during editing, we have to live
11257 with the uncertainty caused by missing closing delimiters. This function
11258 looks only before point, not after."
11259 (catch 'exit
11260 (let ((pos (point))
11261 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11262 (lim (progn
11263 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11264 (point)))
11265 dd-on str (start 0) m re)
11266 (goto-char pos)
11267 (when dodollar
11268 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11269 re (nth 1 (assoc "$" org-latex-regexps)))
11270 (while (string-match re str start)
11271 (cond
11272 ((= (match-end 0) (length str))
11273 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11274 ((= (match-end 0) (- (length str) 5))
11275 (throw 'exit nil))
11276 (t (setq start (match-end 0))))))
11277 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11278 (goto-char pos)
11279 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11280 (and (match-beginning 2) (throw 'exit nil))
11281 ;; count $$
11282 (while (re-search-backward "\\$\\$" lim t)
11283 (setq dd-on (not dd-on)))
11284 (goto-char pos)
11285 (if dd-on (cons "$$" m))))))
11288 (defun org-try-cdlatex-tab ()
11289 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11290 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11291 - inside a LaTeX fragment, or
11292 - after the first word in a line, where an abbreviation expansion could
11293 insert a LaTeX environment."
11294 (when org-cdlatex-mode
11295 (cond
11296 ((save-excursion
11297 (skip-chars-backward "a-zA-Z0-9*")
11298 (skip-chars-backward " \t")
11299 (bolp))
11300 (cdlatex-tab) t)
11301 ((org-inside-LaTeX-fragment-p)
11302 (cdlatex-tab) t)
11303 (t nil))))
11305 (defun org-cdlatex-underscore-caret (&optional arg)
11306 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11307 Revert to the normal definition outside of these fragments."
11308 (interactive "P")
11309 (if (org-inside-LaTeX-fragment-p)
11310 (call-interactively 'cdlatex-sub-superscript)
11311 (let (org-cdlatex-mode)
11312 (call-interactively (key-binding (vector last-input-event))))))
11314 (defun org-cdlatex-math-modify (&optional arg)
11315 "Execute `cdlatex-math-modify' in LaTeX fragments.
11316 Revert to the normal definition outside of these fragments."
11317 (interactive "P")
11318 (if (org-inside-LaTeX-fragment-p)
11319 (call-interactively 'cdlatex-math-modify)
11320 (let (org-cdlatex-mode)
11321 (call-interactively (key-binding (vector last-input-event))))))
11323 (defvar org-latex-fragment-image-overlays nil
11324 "List of overlays carrying the images of latex fragments.")
11325 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11327 (defun org-remove-latex-fragment-image-overlays ()
11328 "Remove all overlays with LaTeX fragment images in current buffer."
11329 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11330 (setq org-latex-fragment-image-overlays nil))
11332 (defun org-preview-latex-fragment (&optional subtree)
11333 "Preview the LaTeX fragment at point, or all locally or globally.
11334 If the cursor is in a LaTeX fragment, create the image and overlay
11335 it over the source code. If there is no fragment at point, display
11336 all fragments in the current text, from one headline to the next. With
11337 prefix SUBTREE, display all fragments in the current subtree. With a
11338 double prefix `C-u C-u', or when the cursor is before the first headline,
11339 display all fragments in the buffer.
11340 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11341 (interactive "P")
11342 (org-remove-latex-fragment-image-overlays)
11343 (save-excursion
11344 (save-restriction
11345 (let (beg end at msg)
11346 (cond
11347 ((or (equal subtree '(16))
11348 (not (save-excursion
11349 (re-search-backward (concat "^" outline-regexp) nil t))))
11350 (setq beg (point-min) end (point-max)
11351 msg "Creating images for buffer...%s"))
11352 ((equal subtree '(4))
11353 (org-back-to-heading)
11354 (setq beg (point) end (org-end-of-subtree t)
11355 msg "Creating images for subtree...%s"))
11357 (if (setq at (org-inside-LaTeX-fragment-p))
11358 (goto-char (max (point-min) (- (cdr at) 2)))
11359 (org-back-to-heading))
11360 (setq beg (point) end (progn (outline-next-heading) (point))
11361 msg (if at "Creating image...%s"
11362 "Creating images for entry...%s"))))
11363 (message msg "")
11364 (narrow-to-region beg end)
11365 (goto-char beg)
11366 (org-format-latex
11367 (concat "ltxpng/" (file-name-sans-extension
11368 (file-name-nondirectory
11369 buffer-file-name)))
11370 default-directory 'overlays msg at 'forbuffer)
11371 (message msg "done. Use `C-c C-c' to remove images.")))))
11373 (defvar org-latex-regexps
11374 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11375 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11376 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11377 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11378 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11379 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11380 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11381 "Regular expressions for matching embedded LaTeX.")
11383 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11384 "Replace LaTeX fragments with links to an image, and produce images."
11385 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11386 (let* ((prefixnodir (file-name-nondirectory prefix))
11387 (absprefix (expand-file-name prefix dir))
11388 (todir (file-name-directory absprefix))
11389 (opt org-format-latex-options)
11390 (matchers (plist-get opt :matchers))
11391 (re-list org-latex-regexps)
11392 (cnt 0) txt link beg end re e checkdir
11393 m n block linkfile movefile ov)
11394 ;; Check if there are old images files with this prefix, and remove them
11395 (when (file-directory-p todir)
11396 (mapc 'delete-file
11397 (directory-files
11398 todir 'full
11399 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11400 ;; Check the different regular expressions
11401 (while (setq e (pop re-list))
11402 (setq m (car e) re (nth 1 e) n (nth 2 e)
11403 block (if (nth 3 e) "\n\n" ""))
11404 (when (member m matchers)
11405 (goto-char (point-min))
11406 (while (re-search-forward re nil t)
11407 (when (or (not at) (equal (cdr at) (match-beginning n)))
11408 (setq txt (match-string n)
11409 beg (match-beginning n) end (match-end n)
11410 cnt (1+ cnt)
11411 linkfile (format "%s_%04d.png" prefix cnt)
11412 movefile (format "%s_%04d.png" absprefix cnt)
11413 link (concat block "[[file:" linkfile "]]" block))
11414 (if msg (message msg cnt))
11415 (goto-char beg)
11416 (unless checkdir ; make sure the directory exists
11417 (setq checkdir t)
11418 (or (file-directory-p todir) (make-directory todir)))
11419 (org-create-formula-image
11420 txt movefile opt forbuffer)
11421 (if overlays
11422 (progn
11423 (setq ov (org-make-overlay beg end))
11424 (if (featurep 'xemacs)
11425 (progn
11426 (org-overlay-put ov 'invisible t)
11427 (org-overlay-put
11428 ov 'end-glyph
11429 (make-glyph (vector 'png :file movefile))))
11430 (org-overlay-put
11431 ov 'display
11432 (list 'image :type 'png :file movefile :ascent 'center)))
11433 (push ov org-latex-fragment-image-overlays)
11434 (goto-char end))
11435 (delete-region beg end)
11436 (insert link))))))))
11438 ;; This function borrows from Ganesh Swami's latex2png.el
11439 (defun org-create-formula-image (string tofile options buffer)
11440 (let* ((tmpdir (if (featurep 'xemacs)
11441 (temp-directory)
11442 temporary-file-directory))
11443 (texfilebase (make-temp-name
11444 (expand-file-name "orgtex" tmpdir)))
11445 (texfile (concat texfilebase ".tex"))
11446 (dvifile (concat texfilebase ".dvi"))
11447 (pngfile (concat texfilebase ".png"))
11448 (fnh (face-attribute 'default :height nil))
11449 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11450 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11451 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11452 "Black"))
11453 (bg (or (plist-get options (if buffer :background :html-background))
11454 "Transparent")))
11455 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11456 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11457 (with-temp-file texfile
11458 (insert org-format-latex-header
11459 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11460 (let ((dir default-directory))
11461 (condition-case nil
11462 (progn
11463 (cd tmpdir)
11464 (call-process "latex" nil nil nil texfile))
11465 (error nil))
11466 (cd dir))
11467 (if (not (file-exists-p dvifile))
11468 (progn (message "Failed to create dvi file from %s" texfile) nil)
11469 (call-process "dvipng" nil nil nil
11470 "-E" "-fg" fg "-bg" bg
11471 "-D" dpi
11472 ;;"-x" scale "-y" scale
11473 "-T" "tight"
11474 "-o" pngfile
11475 dvifile)
11476 (if (not (file-exists-p pngfile))
11477 (progn (message "Failed to create png file from %s" texfile) nil)
11478 ;; Use the requested file name and clean up
11479 (copy-file pngfile tofile 'replace)
11480 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11481 (delete-file (concat texfilebase e)))
11482 pngfile))))
11484 (defun org-dvipng-color (attr)
11485 "Return an rgb color specification for dvipng."
11486 (apply 'format "rgb %s %s %s"
11487 (mapcar 'org-normalize-color
11488 (color-values (face-attribute 'default attr nil)))))
11490 (defun org-normalize-color (value)
11491 "Return string to be used as color value for an RGB component."
11492 (format "%g" (/ value 65535.0)))
11495 ;;;; Key bindings
11497 ;; Make `C-c C-x' a prefix key
11498 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11500 ;; TAB key with modifiers
11501 (org-defkey org-mode-map "\C-i" 'org-cycle)
11502 (org-defkey org-mode-map [(tab)] 'org-cycle)
11503 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11504 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11505 (org-defkey org-mode-map "\M-\t" 'org-complete)
11506 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11507 ;; The following line is necessary under Suse GNU/Linux
11508 (unless (featurep 'xemacs)
11509 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11510 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11511 (define-key org-mode-map [backtab] 'org-shifttab)
11513 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11514 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11515 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11517 ;; Cursor keys with modifiers
11518 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11519 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11520 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11521 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11523 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11524 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11525 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11526 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11528 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11529 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11530 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11531 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11533 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11534 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11536 ;;; Extra keys for tty access.
11537 ;; We only set them when really needed because otherwise the
11538 ;; menus don't show the simple keys
11540 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11541 (not window-system))
11542 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11543 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11544 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11545 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11546 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11547 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11548 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11549 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11550 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11551 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11552 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11553 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11554 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11555 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11556 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11557 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11558 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11559 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11560 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11561 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11562 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11563 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11565 ;; All the other keys
11567 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11568 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11569 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11570 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11571 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11572 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11573 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11574 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11575 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11576 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11577 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11578 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11579 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11580 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11581 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11582 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11583 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11584 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11585 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11586 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11587 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11588 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11589 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11590 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11591 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11592 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11593 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11594 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11595 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11596 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11597 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11598 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11599 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11600 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11601 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11602 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11603 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11604 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11605 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11606 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11607 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11608 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11609 (org-defkey org-mode-map "\C-c^" 'org-sort)
11610 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11611 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11612 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11613 (org-defkey org-mode-map "\C-m" 'org-return)
11614 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11615 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11616 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11617 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11618 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11619 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11620 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11621 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11622 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11623 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11624 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11625 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11626 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11627 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11628 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11629 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11631 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11632 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11633 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11634 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11636 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11637 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11638 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11639 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11640 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11641 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11642 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11643 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11644 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11645 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11646 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11647 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11649 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11651 (when (featurep 'xemacs)
11652 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11654 (defvar org-table-auto-blank-field) ; defined in org-table.el
11655 (defun org-self-insert-command (N)
11656 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11657 If the cursor is in a table looking at whitespace, the whitespace is
11658 overwritten, and the table is not marked as requiring realignment."
11659 (interactive "p")
11660 (if (and (org-table-p)
11661 (progn
11662 ;; check if we blank the field, and if that triggers align
11663 (and (featurep 'org-table) org-table-auto-blank-field
11664 (member last-command
11665 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11666 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11667 ;; got extra space, this field does not determine column width
11668 (let (org-table-may-need-update) (org-table-blank-field))
11669 ;; no extra space, this field may determine column width
11670 (org-table-blank-field)))
11672 (eq N 1)
11673 (looking-at "[^|\n]* |"))
11674 (let (org-table-may-need-update)
11675 (goto-char (1- (match-end 0)))
11676 (delete-backward-char 1)
11677 (goto-char (match-beginning 0))
11678 (self-insert-command N))
11679 (setq org-table-may-need-update t)
11680 (self-insert-command N)
11681 (org-fix-tags-on-the-fly)))
11683 (defun org-fix-tags-on-the-fly ()
11684 (when (and (equal (char-after (point-at-bol)) ?*)
11685 (org-on-heading-p))
11686 (org-align-tags-here org-tags-column)))
11688 (defun org-delete-backward-char (N)
11689 "Like `delete-backward-char', insert whitespace at field end in tables.
11690 When deleting backwards, in tables this function will insert whitespace in
11691 front of the next \"|\" separator, to keep the table aligned. The table will
11692 still be marked for re-alignment if the field did fill the entire column,
11693 because, in this case the deletion might narrow the column."
11694 (interactive "p")
11695 (if (and (org-table-p)
11696 (eq N 1)
11697 (string-match "|" (buffer-substring (point-at-bol) (point)))
11698 (looking-at ".*?|"))
11699 (let ((pos (point))
11700 (noalign (looking-at "[^|\n\r]* |"))
11701 (c org-table-may-need-update))
11702 (backward-delete-char N)
11703 (skip-chars-forward "^|")
11704 (insert " ")
11705 (goto-char (1- pos))
11706 ;; noalign: if there were two spaces at the end, this field
11707 ;; does not determine the width of the column.
11708 (if noalign (setq org-table-may-need-update c)))
11709 (backward-delete-char N)
11710 (org-fix-tags-on-the-fly)))
11712 (defun org-delete-char (N)
11713 "Like `delete-char', but insert whitespace at field end in tables.
11714 When deleting characters, in tables this function will insert whitespace in
11715 front of the next \"|\" separator, to keep the table aligned. The table will
11716 still be marked for re-alignment if the field did fill the entire column,
11717 because, in this case the deletion might narrow the column."
11718 (interactive "p")
11719 (if (and (org-table-p)
11720 (not (bolp))
11721 (not (= (char-after) ?|))
11722 (eq N 1))
11723 (if (looking-at ".*?|")
11724 (let ((pos (point))
11725 (noalign (looking-at "[^|\n\r]* |"))
11726 (c org-table-may-need-update))
11727 (replace-match (concat
11728 (substring (match-string 0) 1 -1)
11729 " |"))
11730 (goto-char pos)
11731 ;; noalign: if there were two spaces at the end, this field
11732 ;; does not determine the width of the column.
11733 (if noalign (setq org-table-may-need-update c)))
11734 (delete-char N))
11735 (delete-char N)
11736 (org-fix-tags-on-the-fly)))
11738 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11739 (put 'org-self-insert-command 'delete-selection t)
11740 (put 'orgtbl-self-insert-command 'delete-selection t)
11741 (put 'org-delete-char 'delete-selection 'supersede)
11742 (put 'org-delete-backward-char 'delete-selection 'supersede)
11744 ;; Make `flyspell-mode' delay after some commands
11745 (put 'org-self-insert-command 'flyspell-delayed t)
11746 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11747 (put 'org-delete-char 'flyspell-delayed t)
11748 (put 'org-delete-backward-char 'flyspell-delayed t)
11750 ;; Make pabbrev-mode expand after org-mode commands
11751 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11752 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11754 ;; How to do this: Measure non-white length of current string
11755 ;; If equal to column width, we should realign.
11757 (defun org-remap (map &rest commands)
11758 "In MAP, remap the functions given in COMMANDS.
11759 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11760 (let (new old)
11761 (while commands
11762 (setq old (pop commands) new (pop commands))
11763 (if (fboundp 'command-remapping)
11764 (org-defkey map (vector 'remap old) new)
11765 (substitute-key-definition old new map global-map)))))
11767 (when (eq org-enable-table-editor 'optimized)
11768 ;; If the user wants maximum table support, we need to hijack
11769 ;; some standard editing functions
11770 (org-remap org-mode-map
11771 'self-insert-command 'org-self-insert-command
11772 'delete-char 'org-delete-char
11773 'delete-backward-char 'org-delete-backward-char)
11774 (org-defkey org-mode-map "|" 'org-force-self-insert))
11776 (defun org-shiftcursor-error ()
11777 "Throw an error because Shift-Cursor command was applied in wrong context."
11778 (error "This command is active in special context like tables, headlines or timestamps"))
11780 (defun org-shifttab (&optional arg)
11781 "Global visibility cycling or move to previous table field.
11782 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11783 on context.
11784 See the individual commands for more information."
11785 (interactive "P")
11786 (cond
11787 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11788 (arg (message "Content view to level: ")
11789 (org-content (prefix-numeric-value arg))
11790 (setq org-cycle-global-status 'overview))
11791 (t (call-interactively 'org-global-cycle))))
11793 (defun org-shiftmetaleft ()
11794 "Promote subtree or delete table column.
11795 Calls `org-promote-subtree', `org-outdent-item',
11796 or `org-table-delete-column', depending on context.
11797 See the individual commands for more information."
11798 (interactive)
11799 (cond
11800 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11801 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11802 ((org-at-item-p) (call-interactively 'org-outdent-item))
11803 (t (org-shiftcursor-error))))
11805 (defun org-shiftmetaright ()
11806 "Demote subtree or insert table column.
11807 Calls `org-demote-subtree', `org-indent-item',
11808 or `org-table-insert-column', depending on context.
11809 See the individual commands for more information."
11810 (interactive)
11811 (cond
11812 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11813 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11814 ((org-at-item-p) (call-interactively 'org-indent-item))
11815 (t (org-shiftcursor-error))))
11817 (defun org-shiftmetaup (&optional arg)
11818 "Move subtree up or kill table row.
11819 Calls `org-move-subtree-up' or `org-table-kill-row' or
11820 `org-move-item-up' depending on context. See the individual commands
11821 for more information."
11822 (interactive "P")
11823 (cond
11824 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11825 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11826 ((org-at-item-p) (call-interactively 'org-move-item-up))
11827 (t (org-shiftcursor-error))))
11828 (defun org-shiftmetadown (&optional arg)
11829 "Move subtree down or insert table row.
11830 Calls `org-move-subtree-down' or `org-table-insert-row' or
11831 `org-move-item-down', depending on context. See the individual
11832 commands for more information."
11833 (interactive "P")
11834 (cond
11835 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11836 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11837 ((org-at-item-p) (call-interactively 'org-move-item-down))
11838 (t (org-shiftcursor-error))))
11840 (defun org-metaleft (&optional arg)
11841 "Promote heading or move table column to left.
11842 Calls `org-do-promote' or `org-table-move-column', depending on context.
11843 With no specific context, calls the Emacs default `backward-word'.
11844 See the individual commands for more information."
11845 (interactive "P")
11846 (cond
11847 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11848 ((or (org-on-heading-p) (org-region-active-p))
11849 (call-interactively 'org-do-promote))
11850 ((org-at-item-p) (call-interactively 'org-outdent-item))
11851 (t (call-interactively 'backward-word))))
11853 (defun org-metaright (&optional arg)
11854 "Demote subtree or move table column to right.
11855 Calls `org-do-demote' or `org-table-move-column', depending on context.
11856 With no specific context, calls the Emacs default `forward-word'.
11857 See the individual commands for more information."
11858 (interactive "P")
11859 (cond
11860 ((org-at-table-p) (call-interactively 'org-table-move-column))
11861 ((or (org-on-heading-p) (org-region-active-p))
11862 (call-interactively 'org-do-demote))
11863 ((org-at-item-p) (call-interactively 'org-indent-item))
11864 (t (call-interactively 'forward-word))))
11866 (defun org-metaup (&optional arg)
11867 "Move subtree up or move table row up.
11868 Calls `org-move-subtree-up' or `org-table-move-row' or
11869 `org-move-item-up', depending on context. See the individual commands
11870 for more information."
11871 (interactive "P")
11872 (cond
11873 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
11874 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11875 ((org-at-item-p) (call-interactively 'org-move-item-up))
11876 (t (transpose-lines 1) (beginning-of-line -1))))
11878 (defun org-metadown (&optional arg)
11879 "Move subtree down or move table row down.
11880 Calls `org-move-subtree-down' or `org-table-move-row' or
11881 `org-move-item-down', depending on context. See the individual
11882 commands for more information."
11883 (interactive "P")
11884 (cond
11885 ((org-at-table-p) (call-interactively 'org-table-move-row))
11886 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11887 ((org-at-item-p) (call-interactively 'org-move-item-down))
11888 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
11890 (defun org-shiftup (&optional arg)
11891 "Increase item in timestamp or increase priority of current headline.
11892 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
11893 depending on context. See the individual commands for more information."
11894 (interactive "P")
11895 (cond
11896 ((org-at-timestamp-p t)
11897 (call-interactively (if org-edit-timestamp-down-means-later
11898 'org-timestamp-down 'org-timestamp-up)))
11899 ((org-on-heading-p) (call-interactively 'org-priority-up))
11900 ((org-at-item-p) (call-interactively 'org-previous-item))
11901 ((org-clocktable-try-shift 'up arg))
11902 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
11904 (defun org-shiftdown (&optional arg)
11905 "Decrease item in timestamp or decrease priority of current headline.
11906 Calls `org-timestamp-down' or `org-priority-down', or `org-next-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-up 'org-timestamp-down)))
11913 ((org-on-heading-p) (call-interactively 'org-priority-down))
11914 ((org-clocktable-try-shift 'down arg))
11915 (t (call-interactively 'org-next-item))))
11917 (defun org-shiftright (&optional arg)
11918 "Next TODO keyword or timestamp one day later, depending on context."
11919 (interactive "P")
11920 (cond
11921 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
11922 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
11923 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
11924 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
11925 ((org-clocktable-try-shift 'right arg))
11926 (t (org-shiftcursor-error))))
11928 (defun org-shiftleft (&optional arg)
11929 "Previous TODO keyword or timestamp one day earlier, depending on context."
11930 (interactive "P")
11931 (cond
11932 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
11933 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
11934 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
11935 ((org-at-property-p)
11936 (call-interactively 'org-property-previous-allowed-value))
11937 ((org-clocktable-try-shift 'left arg))
11938 (t (org-shiftcursor-error))))
11940 (defun org-shiftcontrolright ()
11941 "Switch to next TODO set."
11942 (interactive)
11943 (cond
11944 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
11945 (t (org-shiftcursor-error))))
11947 (defun org-shiftcontrolleft ()
11948 "Switch to previous TODO set."
11949 (interactive)
11950 (cond
11951 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
11952 (t (org-shiftcursor-error))))
11954 (defun org-ctrl-c-ret ()
11955 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
11956 (interactive)
11957 (cond
11958 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
11959 (t (call-interactively 'org-insert-heading))))
11961 (defun org-copy-special ()
11962 "Copy region in table or copy current subtree.
11963 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11964 See the individual commands for more information."
11965 (interactive)
11966 (call-interactively
11967 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11969 (defun org-cut-special ()
11970 "Cut region in table or cut current subtree.
11971 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11972 See the individual commands for more information."
11973 (interactive)
11974 (call-interactively
11975 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11977 (defun org-paste-special (arg)
11978 "Paste rectangular region into table, or past subtree relative to level.
11979 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11980 See the individual commands for more information."
11981 (interactive "P")
11982 (if (org-at-table-p)
11983 (org-table-paste-rectangle)
11984 (org-paste-subtree arg)))
11986 (defun org-ctrl-c-ctrl-c (&optional arg)
11987 "Set tags in headline, or update according to changed information at point.
11989 This command does many different things, depending on context:
11991 - If the cursor is in a headline, prompt for tags and insert them
11992 into the current line, aligned to `org-tags-column'. When called
11993 with prefix arg, realign all tags in the current buffer.
11995 - If the cursor is in one of the special #+KEYWORD lines, this
11996 triggers scanning the buffer for these lines and updating the
11997 information.
11999 - If the cursor is inside a table, realign the table. This command
12000 works even if the automatic table editor has been turned off.
12002 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12003 the entire table.
12005 - If the cursor is a the beginning of a dynamic block, update it.
12007 - If the cursor is inside a table created by the table.el package,
12008 activate that table.
12010 - If the current buffer is a remember buffer, close note and file it.
12011 with a prefix argument, file it without further interaction to the default
12012 location.
12014 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12015 links in this buffer.
12017 - If the cursor is on a numbered item in a plain list, renumber the
12018 ordered list.
12020 - If the cursor is on a checkbox, toggle it."
12021 (interactive "P")
12022 (let ((org-enable-table-editor t))
12023 (cond
12024 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12025 org-occur-highlights
12026 org-latex-fragment-image-overlays)
12027 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12028 (org-remove-occur-highlights)
12029 (org-remove-latex-fragment-image-overlays)
12030 (message "Temporary highlights/overlays removed from current buffer"))
12031 ((and (local-variable-p 'org-finish-function (current-buffer))
12032 (fboundp org-finish-function))
12033 (funcall org-finish-function))
12034 ((org-at-property-p)
12035 (call-interactively 'org-property-action))
12036 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12037 ((org-on-heading-p) (call-interactively 'org-set-tags))
12038 ((org-at-table.el-p)
12039 (require 'table)
12040 (beginning-of-line 1)
12041 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12042 (call-interactively 'table-recognize-table))
12043 ((org-at-table-p)
12044 (org-table-maybe-eval-formula)
12045 (if arg
12046 (call-interactively 'org-table-recalculate)
12047 (org-table-maybe-recalculate-line))
12048 (call-interactively 'org-table-align))
12049 ((org-at-item-checkbox-p)
12050 (call-interactively 'org-toggle-checkbox))
12051 ((org-at-item-p)
12052 (call-interactively 'org-maybe-renumber-ordered-list))
12053 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12054 ;; Dynamic block
12055 (beginning-of-line 1)
12056 (org-update-dblock))
12057 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12058 (cond
12059 ((equal (match-string 1) "TBLFM")
12060 ;; Recalculate the table before this line
12061 (save-excursion
12062 (beginning-of-line 1)
12063 (skip-chars-backward " \r\n\t")
12064 (if (org-at-table-p)
12065 (org-call-with-arg 'org-table-recalculate t))))
12067 (call-interactively 'org-mode-restart))))
12068 (t (error "C-c C-c can do nothing useful at this location.")))))
12070 (defun org-mode-restart ()
12071 "Restart Org-mode, to scan again for special lines.
12072 Also updates the keyword regular expressions."
12073 (interactive)
12074 (let ((org-inhibit-startup t)) (org-mode))
12075 (message "Org-mode restarted to refresh keyword and special line setup"))
12077 (defun org-kill-note-or-show-branches ()
12078 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12079 (interactive)
12080 (if (not org-finish-function)
12081 (call-interactively 'show-branches)
12082 (let ((org-note-abort t))
12083 (funcall org-finish-function))))
12085 (defun org-return (&optional indent)
12086 "Goto next table row or insert a newline.
12087 Calls `org-table-next-row' or `newline', depending on context.
12088 See the individual commands for more information."
12089 (interactive)
12090 (cond
12091 ((bobp) (if indent (newline-and-indent) (newline)))
12092 ((and (org-at-heading-p)
12093 (looking-at
12094 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12095 (org-show-entry)
12096 (end-of-line 1)
12097 (newline))
12098 ((org-at-table-p)
12099 (org-table-justify-field-maybe)
12100 (call-interactively 'org-table-next-row))
12101 (t (if indent (newline-and-indent) (newline)))))
12103 (defun org-return-indent ()
12104 "Goto next table row or insert a newline and indent.
12105 Calls `org-table-next-row' or `newline-and-indent', depending on
12106 context. See the individual commands for more information."
12107 (interactive)
12108 (org-return t))
12110 (defun org-ctrl-c-star ()
12111 "Compute table, or change heading status of lines.
12112 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12113 depending on context. This will also turn a plain list item or a normal
12114 line into a subheading."
12115 (interactive)
12116 (cond
12117 ((org-at-table-p)
12118 (call-interactively 'org-table-recalculate))
12119 ((org-region-active-p)
12120 ;; Convert all lines in region to list items
12121 (call-interactively 'org-toggle-region-headings))
12122 ((org-on-heading-p)
12123 (org-toggle-region-headings (point-at-bol)
12124 (min (1+ (point-at-eol)) (point-max))))
12125 ((org-at-item-p)
12126 ;; Convert to heading
12127 (let ((level (save-match-data
12128 (save-excursion
12129 (condition-case nil
12130 (progn
12131 (org-back-to-heading t)
12132 (funcall outline-level))
12133 (error 0))))))
12134 (replace-match
12135 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12136 (t (org-toggle-region-headings (point-at-bol)
12137 (min (1+ (point-at-eol)) (point-max))))))
12139 (defun org-ctrl-c-minus ()
12140 "Insert separator line in table or modify bullet status of line.
12141 Also turns a plain line or a region of lines into list items.
12142 Calls `org-table-insert-hline', `org-toggle-region-items', or
12143 `org-cycle-list-bullet', depending on context."
12144 (interactive)
12145 (cond
12146 ((org-at-table-p)
12147 (call-interactively 'org-table-insert-hline))
12148 ((org-on-heading-p)
12149 ;; Convert to item
12150 (save-excursion
12151 (beginning-of-line 1)
12152 (if (looking-at "\\*+ ")
12153 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12154 ((org-region-active-p)
12155 ;; Convert all lines in region to list items
12156 (call-interactively 'org-toggle-region-items))
12157 ((org-in-item-p)
12158 (call-interactively 'org-cycle-list-bullet))
12159 (t (org-toggle-region-items (point-at-bol)
12160 (min (1+ (point-at-eol)) (point-max))))))
12162 (defun org-toggle-region-items (beg end)
12163 "Convert all lines in region to list items.
12164 If the first line is already an item, convert all list items in the region
12165 to normal lines."
12166 (interactive "r")
12167 (let (l2 l)
12168 (save-excursion
12169 (goto-char end)
12170 (setq l2 (org-current-line))
12171 (goto-char beg)
12172 (beginning-of-line 1)
12173 (setq l (1- (org-current-line)))
12174 (if (org-at-item-p)
12175 ;; We already have items, de-itemize
12176 (while (< (setq l (1+ l)) l2)
12177 (when (org-at-item-p)
12178 (goto-char (match-beginning 2))
12179 (delete-region (match-beginning 2) (match-end 2))
12180 (and (looking-at "[ \t]+") (replace-match "")))
12181 (beginning-of-line 2))
12182 (while (< (setq l (1+ l)) l2)
12183 (unless (org-at-item-p)
12184 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12185 (replace-match "\\1- \\2")))
12186 (beginning-of-line 2))))))
12188 (defun org-toggle-region-headings (beg end)
12189 "Convert all lines in region to list items.
12190 If the first line is already an item, convert all list items in the region
12191 to normal lines."
12192 (interactive "r")
12193 (let (l2 l)
12194 (save-excursion
12195 (goto-char end)
12196 (setq l2 (org-current-line))
12197 (goto-char beg)
12198 (beginning-of-line 1)
12199 (setq l (1- (org-current-line)))
12200 (if (org-on-heading-p)
12201 ;; We already have headlines, de-star them
12202 (while (< (setq l (1+ l)) l2)
12203 (when (org-on-heading-p t)
12204 (and (looking-at outline-regexp) (replace-match "")))
12205 (beginning-of-line 2))
12206 (let* ((stars (save-excursion
12207 (re-search-backward org-complex-heading-regexp nil t)
12208 (or (match-string 1) "*")))
12209 (add-stars (if org-odd-levels-only "**" "*"))
12210 (rpl (concat stars add-stars " \\2")))
12211 (while (< (setq l (1+ l)) l2)
12212 (unless (org-on-heading-p)
12213 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12214 (replace-match rpl)))
12215 (beginning-of-line 2)))))))
12217 (defun org-meta-return (&optional arg)
12218 "Insert a new heading or wrap a region in a table.
12219 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12220 See the individual commands for more information."
12221 (interactive "P")
12222 (cond
12223 ((org-at-table-p)
12224 (call-interactively 'org-table-wrap-region))
12225 (t (call-interactively 'org-insert-heading))))
12227 ;;; Menu entries
12229 ;; Define the Org-mode menus
12230 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12231 '("Tbl"
12232 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12233 ["Next Field" org-cycle (org-at-table-p)]
12234 ["Previous Field" org-shifttab (org-at-table-p)]
12235 ["Next Row" org-return (org-at-table-p)]
12236 "--"
12237 ["Blank Field" org-table-blank-field (org-at-table-p)]
12238 ["Edit Field" org-table-edit-field (org-at-table-p)]
12239 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12240 "--"
12241 ("Column"
12242 ["Move Column Left" org-metaleft (org-at-table-p)]
12243 ["Move Column Right" org-metaright (org-at-table-p)]
12244 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12245 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12246 ("Row"
12247 ["Move Row Up" org-metaup (org-at-table-p)]
12248 ["Move Row Down" org-metadown (org-at-table-p)]
12249 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12250 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12251 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12252 "--"
12253 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12254 ("Rectangle"
12255 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12256 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12257 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12258 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12259 "--"
12260 ("Calculate"
12261 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12262 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12263 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12264 "--"
12265 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12266 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12267 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12268 "--"
12269 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12270 "--"
12271 ["Sum Column/Rectangle" org-table-sum
12272 (or (org-at-table-p) (org-region-active-p))]
12273 ["Which Column?" org-table-current-column (org-at-table-p)])
12274 ["Debug Formulas"
12275 org-table-toggle-formula-debugger
12276 :style toggle :selected org-table-formula-debug]
12277 ["Show Col/Row Numbers"
12278 org-table-toggle-coordinate-overlays
12279 :style toggle :selected org-table-overlay-coordinates]
12280 "--"
12281 ["Create" org-table-create (and (not (org-at-table-p))
12282 org-enable-table-editor)]
12283 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12284 ["Import from File" org-table-import (not (org-at-table-p))]
12285 ["Export to File" org-table-export (org-at-table-p)]
12286 "--"
12287 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12289 (easy-menu-define org-org-menu org-mode-map "Org menu"
12290 '("Org"
12291 ("Show/Hide"
12292 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))
12293 :help "Cycle subtree visibility: folded->children->all->folded"]
12294 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))
12295 :help "Cycle global visibility: overview->content->all"]
12296 ["Sparse Tree..." org-sparse-tree
12297 :help "Create sparse trees using different search criteria"]
12298 ["Reveal Context" org-reveal :active t
12299 :help "Show hidden context around point, including the outline hierarchy"]
12300 ["Show All" show-all :active t
12301 :help "Show all text in the buffer, including drawers"]
12302 "--"
12303 ["Subtree to indirect buffer" org-tree-to-indirect-buffer :active t
12304 :help "Open the subtree at point in a separate window, using an indirect buffer"])
12305 "--"
12306 ["New Heading" org-insert-heading t]
12307 ("Navigate Headings"
12308 ["Up" outline-up-heading t]
12309 ["Next" outline-next-visible-heading t]
12310 ["Previous" outline-previous-visible-heading t]
12311 ["Next Same Level" outline-forward-same-level t]
12312 ["Previous Same Level" outline-backward-same-level t]
12313 "--"
12314 ["Jump" org-goto t])
12315 ("Edit Structure"
12316 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12317 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12318 "--"
12319 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12320 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12321 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12322 "--"
12323 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12324 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12325 ["Demote Heading" org-metaright (not (org-at-table-p))]
12326 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12327 "--"
12328 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12329 "--"
12330 ["Convert to odd levels" org-convert-to-odd-levels t]
12331 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12332 ("Editing"
12333 ["Emphasis..." org-emphasize t])
12334 ("Archive"
12335 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12336 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12337 ; :active t :keys "C-u C-c C-x C-a"]
12338 ["Sparse trees open ARCHIVE trees"
12339 (setq org-sparse-tree-open-archived-trees
12340 (not org-sparse-tree-open-archived-trees))
12341 :style toggle :selected org-sparse-tree-open-archived-trees]
12342 ["Cycling opens ARCHIVE trees"
12343 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12344 :style toggle :selected org-cycle-open-archived-trees]
12345 ["Agenda includes ARCHIVE trees"
12346 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12347 :style toggle :selected (not org-agenda-skip-archived-trees)]
12348 "--"
12349 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12350 ; ["Check and Move Children" (org-archive-subtree '(4))
12351 ; :active t :keys "C-u C-c C-x C-s"]
12353 "--"
12354 ("TODO Lists"
12355 ["TODO/DONE/-" org-todo t]
12356 ("Select keyword"
12357 ["Next keyword" org-shiftright (org-on-heading-p)]
12358 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12359 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12360 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12361 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12362 ["Show TODO Tree" org-show-todo-tree t]
12363 ["Global TODO list" org-todo-list t]
12364 "--"
12365 ["Set Priority" org-priority t]
12366 ["Priority Up" org-shiftup t]
12367 ["Priority Down" org-shiftdown t])
12368 ("TAGS and Properties"
12369 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12370 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12371 "--"
12372 ["Set property" 'org-set-property t]
12373 ["Column view of properties" org-columns t]
12374 ["Insert Column View DBlock" org-insert-columns-dblock t])
12375 ("Dates and Scheduling"
12376 ["Timestamp" org-time-stamp t]
12377 ["Timestamp (inactive)" org-time-stamp-inactive t]
12378 ("Change Date"
12379 ["1 Day Later" org-shiftright t]
12380 ["1 Day Earlier" org-shiftleft t]
12381 ["1 ... Later" org-shiftup t]
12382 ["1 ... Earlier" org-shiftdown t])
12383 ["Compute Time Range" org-evaluate-time-range t]
12384 ["Schedule Item" org-schedule t]
12385 ["Deadline" org-deadline t]
12386 "--"
12387 ["Custom time format" org-toggle-time-stamp-overlays
12388 :style radio :selected org-display-custom-times]
12389 "--"
12390 ["Goto Calendar" org-goto-calendar t]
12391 ["Date from Calendar" org-date-from-calendar t])
12392 ("Logging work"
12393 ["Clock in" org-clock-in t]
12394 ["Clock out" org-clock-out t]
12395 ["Clock cancel" org-clock-cancel t]
12396 ["Goto running clock" org-clock-goto t]
12397 ["Display times" org-clock-display t]
12398 ["Create clock table" org-clock-report t]
12399 "--"
12400 ["Record DONE time"
12401 (progn (setq org-log-done (not org-log-done))
12402 (message "Switching to %s will %s record a timestamp"
12403 (car org-done-keywords)
12404 (if org-log-done "automatically" "not")))
12405 :style toggle :selected org-log-done])
12406 "--"
12407 ["Agenda Command..." org-agenda t]
12408 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12409 ("File List for Agenda")
12410 ("Special views current file"
12411 ["TODO Tree" org-show-todo-tree t]
12412 ["Check Deadlines" org-check-deadlines t]
12413 ["Timeline" org-timeline t]
12414 ["Tags Tree" org-tags-sparse-tree t])
12415 "--"
12416 ("Hyperlinks"
12417 ["Store Link (Global)" org-store-link t]
12418 ["Insert Link" org-insert-link t]
12419 ["Follow Link" org-open-at-point t]
12420 "--"
12421 ["Next link" org-next-link :help "Move forward to next link in the buffer"]
12422 ["Previous link" org-previous-link t]
12423 "--"
12424 ["Descriptive Links"
12425 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12426 :style radio :help "Hide link part of links, only show the description"
12427 :selected (member '(org-link) buffer-invisibility-spec)]
12428 ["Literal Links"
12429 (progn
12430 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12431 :style radio :help "Show full links without hiding anything"
12432 :selected (not (member '(org-link) buffer-invisibility-spec))])
12433 "--"
12434 ["Export/Publish..." org-export t]
12435 ("LaTeX"
12436 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12437 :selected org-cdlatex-mode]
12438 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12439 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12440 ["Modify math symbol" org-cdlatex-math-modify
12441 (org-inside-LaTeX-fragment-p)]
12442 ["Export LaTeX fragments as images"
12443 (if (featurep 'org-exp)
12444 (setq org-export-with-LaTeX-fragments
12445 (not org-export-with-LaTeX-fragments))
12446 (require 'org-exp))
12447 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12448 org-export-with-LaTeX-fragments)])
12449 "--"
12450 ("Documentation"
12451 ["Show Version" org-version t]
12452 ["Info Documentation" org-info t])
12453 ("Customize"
12454 ["Browse Org Group" org-customize t]
12455 "--"
12456 ["Expand This Menu" org-create-customize-menu
12457 (fboundp 'customize-menu-create)])
12458 "--"
12459 ["Refresh setup" org-mode-restart t]
12462 (defun org-info (&optional node)
12463 "Read documentation for Org-mode in the info system.
12464 With optional NODE, go directly to that node."
12465 (interactive)
12466 (info (format "(org)%s" (or node ""))))
12468 (defun org-install-agenda-files-menu ()
12469 (let ((bl (buffer-list)))
12470 (save-excursion
12471 (while bl
12472 (set-buffer (pop bl))
12473 (if (org-mode-p) (setq bl nil)))
12474 (when (org-mode-p)
12475 (easy-menu-change
12476 '("Org") "File List for Agenda"
12477 (append
12478 (list
12479 ["Edit File List" (org-edit-agenda-file-list) t]
12480 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12481 ["Remove Current File from List" org-remove-file t]
12482 ["Cycle through agenda files" org-cycle-agenda-files t]
12483 ["Occur in all agenda files" org-occur-in-agenda-files t]
12484 "--")
12485 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12487 ;;;; Documentation
12489 (defun org-require-autoloaded-modules ()
12490 (interactive)
12491 (mapc 'require
12492 '(org-agenda org-archive org-clock org-colview
12493 org-exp org-export-latex org-publish
12494 org-remember org-table)))
12496 (defun org-customize ()
12497 "Call the customize function with org as argument."
12498 (interactive)
12499 (org-load-modules-maybe)
12500 (org-require-autoloaded-modules)
12501 (customize-browse 'org))
12503 (defun org-create-customize-menu ()
12504 "Create a full customization menu for Org-mode, insert it into the menu."
12505 (interactive)
12506 (org-load-modules-maybe)
12507 (org-require-autoloaded-modules)
12508 (if (fboundp 'customize-menu-create)
12509 (progn
12510 (easy-menu-change
12511 '("Org") "Customize"
12512 `(["Browse Org group" org-customize t]
12513 "--"
12514 ,(customize-menu-create 'org)
12515 ["Set" Custom-set t]
12516 ["Save" Custom-save t]
12517 ["Reset to Current" Custom-reset-current t]
12518 ["Reset to Saved" Custom-reset-saved t]
12519 ["Reset to Standard Settings" Custom-reset-standard t]))
12520 (message "\"Org\"-menu now contains full customization menu"))
12521 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12523 ;;;; Miscellaneous stuff
12525 ;;; Generally useful functions
12527 (defun org-plist-delete (plist property)
12528 "Delete PROPERTY from PLIST.
12529 This is in contrast to merely setting it to 0."
12530 (let (p)
12531 (while plist
12532 (if (not (eq property (car plist)))
12533 (setq p (plist-put p (car plist) (nth 1 plist))))
12534 (setq plist (cddr plist)))
12537 (defun org-force-self-insert (N)
12538 "Needed to enforce self-insert under remapping."
12539 (interactive "p")
12540 (self-insert-command N))
12542 (defun org-string-width (s)
12543 "Compute width of string, ignoring invisible characters.
12544 This ignores character with invisibility property `org-link', and also
12545 characters with property `org-cwidth', because these will become invisible
12546 upon the next fontification round."
12547 (let (b l)
12548 (when (or (eq t buffer-invisibility-spec)
12549 (assq 'org-link buffer-invisibility-spec))
12550 (while (setq b (text-property-any 0 (length s)
12551 'invisible 'org-link s))
12552 (setq s (concat (substring s 0 b)
12553 (substring s (or (next-single-property-change
12554 b 'invisible s) (length s)))))))
12555 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12556 (setq s (concat (substring s 0 b)
12557 (substring s (or (next-single-property-change
12558 b 'org-cwidth s) (length s))))))
12559 (setq l (string-width s) b -1)
12560 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12561 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12565 (defun org-trim (s)
12566 "Remove whitespace at beginning and end of string."
12567 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12568 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12571 (defun org-wrap (string &optional width lines)
12572 "Wrap string to either a number of lines, or a width in characters.
12573 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12574 that costs. If there is a word longer than WIDTH, the text is actually
12575 wrapped to the length of that word.
12576 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12577 many lines, whatever width that takes.
12578 The return value is a list of lines, without newlines at the end."
12579 (let* ((words (org-split-string string "[ \t\n]+"))
12580 (maxword (apply 'max (mapcar 'org-string-width words)))
12581 w ll)
12582 (cond (width
12583 (org-do-wrap words (max maxword width)))
12584 (lines
12585 (setq w maxword)
12586 (setq ll (org-do-wrap words maxword))
12587 (if (<= (length ll) lines)
12589 (setq ll words)
12590 (while (> (length ll) lines)
12591 (setq w (1+ w))
12592 (setq ll (org-do-wrap words w)))
12593 ll))
12594 (t (error "Cannot wrap this")))))
12596 (defun org-do-wrap (words width)
12597 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12598 (let (lines line)
12599 (while words
12600 (setq line (pop words))
12601 (while (and words (< (+ (length line) (length (car words))) width))
12602 (setq line (concat line " " (pop words))))
12603 (setq lines (push line lines)))
12604 (nreverse lines)))
12606 (defun org-split-string (string &optional separators)
12607 "Splits STRING into substrings at SEPARATORS.
12608 No empty strings are returned if there are matches at the beginning
12609 and end of string."
12610 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12611 (start 0)
12612 notfirst
12613 (list nil))
12614 (while (and (string-match rexp string
12615 (if (and notfirst
12616 (= start (match-beginning 0))
12617 (< start (length string)))
12618 (1+ start) start))
12619 (< (match-beginning 0) (length string)))
12620 (setq notfirst t)
12621 (or (eq (match-beginning 0) 0)
12622 (and (eq (match-beginning 0) (match-end 0))
12623 (eq (match-beginning 0) start))
12624 (setq list
12625 (cons (substring string start (match-beginning 0))
12626 list)))
12627 (setq start (match-end 0)))
12628 (or (eq start (length string))
12629 (setq list
12630 (cons (substring string start)
12631 list)))
12632 (nreverse list)))
12634 (defun org-context ()
12635 "Return a list of contexts of the current cursor position.
12636 If several contexts apply, all are returned.
12637 Each context entry is a list with a symbol naming the context, and
12638 two positions indicating start and end of the context. Possible
12639 contexts are:
12641 :headline anywhere in a headline
12642 :headline-stars on the leading stars in a headline
12643 :todo-keyword on a TODO keyword (including DONE) in a headline
12644 :tags on the TAGS in a headline
12645 :priority on the priority cookie in a headline
12646 :item on the first line of a plain list item
12647 :item-bullet on the bullet/number of a plain list item
12648 :checkbox on the checkbox in a plain list item
12649 :table in an org-mode table
12650 :table-special on a special filed in a table
12651 :table-table in a table.el table
12652 :link on a hyperlink
12653 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12654 :target on a <<target>>
12655 :radio-target on a <<<radio-target>>>
12656 :latex-fragment on a LaTeX fragment
12657 :latex-preview on a LaTeX fragment with overlayed preview image
12659 This function expects the position to be visible because it uses font-lock
12660 faces as a help to recognize the following contexts: :table-special, :link,
12661 and :keyword."
12662 (let* ((f (get-text-property (point) 'face))
12663 (faces (if (listp f) f (list f)))
12664 (p (point)) clist o)
12665 ;; First the large context
12666 (cond
12667 ((org-on-heading-p t)
12668 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12669 (when (progn
12670 (beginning-of-line 1)
12671 (looking-at org-todo-line-tags-regexp))
12672 (push (org-point-in-group p 1 :headline-stars) clist)
12673 (push (org-point-in-group p 2 :todo-keyword) clist)
12674 (push (org-point-in-group p 4 :tags) clist))
12675 (goto-char p)
12676 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12677 (if (looking-at "\\[#[A-Z0-9]\\]")
12678 (push (org-point-in-group p 0 :priority) clist)))
12680 ((org-at-item-p)
12681 (push (org-point-in-group p 2 :item-bullet) clist)
12682 (push (list :item (point-at-bol)
12683 (save-excursion (org-end-of-item) (point)))
12684 clist)
12685 (and (org-at-item-checkbox-p)
12686 (push (org-point-in-group p 0 :checkbox) clist)))
12688 ((org-at-table-p)
12689 (push (list :table (org-table-begin) (org-table-end)) clist)
12690 (if (memq 'org-formula faces)
12691 (push (list :table-special
12692 (previous-single-property-change p 'face)
12693 (next-single-property-change p 'face)) clist)))
12694 ((org-at-table-p 'any)
12695 (push (list :table-table) clist)))
12696 (goto-char p)
12698 ;; Now the small context
12699 (cond
12700 ((org-at-timestamp-p)
12701 (push (org-point-in-group p 0 :timestamp) clist))
12702 ((memq 'org-link faces)
12703 (push (list :link
12704 (previous-single-property-change p 'face)
12705 (next-single-property-change p 'face)) clist))
12706 ((memq 'org-special-keyword faces)
12707 (push (list :keyword
12708 (previous-single-property-change p 'face)
12709 (next-single-property-change p 'face)) clist))
12710 ((org-on-target-p)
12711 (push (org-point-in-group p 0 :target) clist)
12712 (goto-char (1- (match-beginning 0)))
12713 (if (looking-at org-radio-target-regexp)
12714 (push (org-point-in-group p 0 :radio-target) clist))
12715 (goto-char p))
12716 ((setq o (car (delq nil
12717 (mapcar
12718 (lambda (x)
12719 (if (memq x org-latex-fragment-image-overlays) x))
12720 (org-overlays-at (point))))))
12721 (push (list :latex-fragment
12722 (org-overlay-start o) (org-overlay-end o)) clist)
12723 (push (list :latex-preview
12724 (org-overlay-start o) (org-overlay-end o)) clist))
12725 ((org-inside-LaTeX-fragment-p)
12726 ;; FIXME: positions wrong.
12727 (push (list :latex-fragment (point) (point)) clist)))
12729 (setq clist (nreverse (delq nil clist)))
12730 clist))
12732 ;; FIXME: Compare with at-regexp-p Do we need both?
12733 (defun org-in-regexp (re &optional nlines visually)
12734 "Check if point is inside a match of regexp.
12735 Normally only the current line is checked, but you can include NLINES extra
12736 lines both before and after point into the search.
12737 If VISUALLY is set, require that the cursor is not after the match but
12738 really on, so that the block visually is on the match."
12739 (catch 'exit
12740 (let ((pos (point))
12741 (eol (point-at-eol (+ 1 (or nlines 0))))
12742 (inc (if visually 1 0)))
12743 (save-excursion
12744 (beginning-of-line (- 1 (or nlines 0)))
12745 (while (re-search-forward re eol t)
12746 (if (and (<= (match-beginning 0) pos)
12747 (>= (+ inc (match-end 0)) pos))
12748 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12750 (defun org-at-regexp-p (regexp)
12751 "Is point inside a match of REGEXP in the current line?"
12752 (catch 'exit
12753 (save-excursion
12754 (let ((pos (point)) (end (point-at-eol)))
12755 (beginning-of-line 1)
12756 (while (re-search-forward regexp end t)
12757 (if (and (<= (match-beginning 0) pos)
12758 (>= (match-end 0) pos))
12759 (throw 'exit t)))
12760 nil))))
12762 (defun org-occur-in-agenda-files (regexp &optional nlines)
12763 "Call `multi-occur' with buffers for all agenda files."
12764 (interactive "sOrg-files matching: \np")
12765 (let* ((files (org-agenda-files))
12766 (tnames (mapcar 'file-truename files))
12767 (extra org-agenda-text-search-extra-files)
12769 (while (setq f (pop extra))
12770 (unless (member (file-truename f) tnames)
12771 (add-to-list 'files f 'append)
12772 (add-to-list 'tnames (file-truename f) 'append)))
12773 (multi-occur
12774 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12775 regexp)))
12777 (if (boundp 'occur-mode-find-occurrence-hook)
12778 ;; Emacs 23
12779 (add-hook 'occur-mode-find-occurrence-hook
12780 (lambda ()
12781 (when (org-mode-p)
12782 (org-reveal))))
12783 ;; Emacs 22
12784 (defadvice occur-mode-goto-occurrence
12785 (after org-occur-reveal activate)
12786 (and (org-mode-p) (org-reveal)))
12787 (defadvice occur-mode-goto-occurrence-other-window
12788 (after org-occur-reveal activate)
12789 (and (org-mode-p) (org-reveal)))
12790 (defadvice occur-mode-display-occurrence
12791 (after org-occur-reveal activate)
12792 (when (org-mode-p)
12793 (let ((pos (occur-mode-find-occurrence)))
12794 (with-current-buffer (marker-buffer pos)
12795 (save-excursion
12796 (goto-char pos)
12797 (org-reveal)))))))
12799 (defun org-uniquify (list)
12800 "Remove duplicate elements from LIST."
12801 (let (res)
12802 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12803 res))
12805 (defun org-delete-all (elts list)
12806 "Remove all elements in ELTS from LIST."
12807 (while elts
12808 (setq list (delete (pop elts) list)))
12809 list)
12811 (defun org-back-over-empty-lines ()
12812 "Move backwards over witespace, to the beginning of the first empty line.
12813 Returns the number of empty lines passed."
12814 (let ((pos (point)))
12815 (skip-chars-backward " \t\n\r")
12816 (beginning-of-line 2)
12817 (goto-char (min (point) pos))
12818 (count-lines (point) pos)))
12820 (defun org-skip-whitespace ()
12821 (skip-chars-forward " \t\n\r"))
12823 (defun org-point-in-group (point group &optional context)
12824 "Check if POINT is in match-group GROUP.
12825 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12826 match. If the match group does ot exist or point is not inside it,
12827 return nil."
12828 (and (match-beginning group)
12829 (>= point (match-beginning group))
12830 (<= point (match-end group))
12831 (if context
12832 (list context (match-beginning group) (match-end group))
12833 t)))
12835 (defun org-switch-to-buffer-other-window (&rest args)
12836 "Switch to buffer in a second window on the current frame.
12837 In particular, do not allow pop-up frames."
12838 (let (pop-up-frames special-display-buffer-names special-display-regexps
12839 special-display-function)
12840 (apply 'switch-to-buffer-other-window args)))
12842 (defun org-combine-plists (&rest plists)
12843 "Create a single property list from all plists in PLISTS.
12844 The process starts by copying the first list, and then setting properties
12845 from the other lists. Settings in the last list are the most significant
12846 ones and overrule settings in the other lists."
12847 (let ((rtn (copy-sequence (pop plists)))
12848 p v ls)
12849 (while plists
12850 (setq ls (pop plists))
12851 (while ls
12852 (setq p (pop ls) v (pop ls))
12853 (setq rtn (plist-put rtn p v))))
12854 rtn))
12856 (defun org-move-line-down (arg)
12857 "Move the current line down. With prefix argument, move it past ARG lines."
12858 (interactive "p")
12859 (let ((col (current-column))
12860 beg end pos)
12861 (beginning-of-line 1) (setq beg (point))
12862 (beginning-of-line 2) (setq end (point))
12863 (beginning-of-line (+ 1 arg))
12864 (setq pos (move-marker (make-marker) (point)))
12865 (insert (delete-and-extract-region beg end))
12866 (goto-char pos)
12867 (move-to-column col)))
12869 (defun org-move-line-up (arg)
12870 "Move the current line up. With prefix argument, move it past ARG lines."
12871 (interactive "p")
12872 (let ((col (current-column))
12873 beg end pos)
12874 (beginning-of-line 1) (setq beg (point))
12875 (beginning-of-line 2) (setq end (point))
12876 (beginning-of-line (- arg))
12877 (setq pos (move-marker (make-marker) (point)))
12878 (insert (delete-and-extract-region beg end))
12879 (goto-char pos)
12880 (move-to-column col)))
12882 (defun org-replace-escapes (string table)
12883 "Replace %-escapes in STRING with values in TABLE.
12884 TABLE is an association list with keys like \"%a\" and string values.
12885 The sequences in STRING may contain normal field width and padding information,
12886 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
12887 so values can contain further %-escapes if they are define later in TABLE."
12888 (let ((case-fold-search nil)
12889 e re rpl)
12890 (while (setq e (pop table))
12891 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
12892 (while (string-match re string)
12893 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
12894 (cdr e)))
12895 (setq string (replace-match rpl t t string))))
12896 string))
12899 (defun org-sublist (list start end)
12900 "Return a section of LIST, from START to END.
12901 Counting starts at 1."
12902 (let (rtn (c start))
12903 (setq list (nthcdr (1- start) list))
12904 (while (and list (<= c end))
12905 (push (pop list) rtn)
12906 (setq c (1+ c)))
12907 (nreverse rtn)))
12909 (defun org-find-base-buffer-visiting (file)
12910 "Like `find-buffer-visiting' but alway return the base buffer and
12911 not an indirect buffer."
12912 (let ((buf (find-buffer-visiting file)))
12913 (if buf
12914 (or (buffer-base-buffer buf) buf)
12915 nil)))
12917 (defun org-image-file-name-regexp ()
12918 "Return regexp matching the file names of images."
12919 (if (fboundp 'image-file-name-regexp)
12920 (image-file-name-regexp)
12921 (let ((image-file-name-extensions
12922 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12923 "xbm" "xpm" "pbm" "pgm" "ppm")))
12924 (concat "\\."
12925 (regexp-opt (nconc (mapcar 'upcase
12926 image-file-name-extensions)
12927 image-file-name-extensions)
12929 "\\'"))))
12931 (defun org-file-image-p (file)
12932 "Return non-nil if FILE is an image."
12933 (save-match-data
12934 (string-match (org-image-file-name-regexp) file)))
12936 ;;; Paragraph filling stuff.
12937 ;; We want this to be just right, so use the full arsenal.
12939 (defun org-indent-line-function ()
12940 "Indent line like previous, but further if previous was headline or item."
12941 (interactive)
12942 (let* ((pos (point))
12943 (itemp (org-at-item-p))
12944 column bpos bcol tpos tcol bullet btype bullet-type)
12945 ;; Find the previous relevant line
12946 (beginning-of-line 1)
12947 (cond
12948 ((looking-at "#") (setq column 0))
12949 ((looking-at "\\*+ ") (setq column 0))
12951 (beginning-of-line 0)
12952 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
12953 (beginning-of-line 0))
12954 (cond
12955 ((looking-at "\\*+[ \t]+")
12956 (goto-char (match-end 0))
12957 (setq column (current-column)))
12958 ((org-in-item-p)
12959 (org-beginning-of-item)
12960 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12961 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
12962 (setq bpos (match-beginning 1) tpos (match-end 0)
12963 bcol (progn (goto-char bpos) (current-column))
12964 tcol (progn (goto-char tpos) (current-column))
12965 bullet (match-string 1)
12966 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
12967 (if (not itemp)
12968 (setq column tcol)
12969 (goto-char pos)
12970 (beginning-of-line 1)
12971 (if (looking-at "\\S-")
12972 (progn
12973 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12974 (setq bullet (match-string 1)
12975 btype (if (string-match "[0-9]" bullet) "n" bullet))
12976 (setq column (if (equal btype bullet-type) bcol tcol)))
12977 (setq column (org-get-indentation)))))
12978 (t (setq column (org-get-indentation))))))
12979 (goto-char pos)
12980 (if (<= (current-column) (current-indentation))
12981 (indent-line-to column)
12982 (save-excursion (indent-line-to column)))
12983 (setq column (current-column))
12984 (beginning-of-line 1)
12985 (if (looking-at
12986 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
12987 (replace-match (concat "\\1" (format org-property-format
12988 (match-string 2) (match-string 3)))
12989 t nil))
12990 (move-to-column column)))
12992 (defun org-set-autofill-regexps ()
12993 (interactive)
12994 ;; In the paragraph separator we include headlines, because filling
12995 ;; text in a line directly attached to a headline would otherwise
12996 ;; fill the headline as well.
12997 (org-set-local 'comment-start-skip "^#+[ \t]*")
12998 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
12999 ;; The paragraph starter includes hand-formatted lists.
13000 (org-set-local 'paragraph-start
13001 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13002 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13003 ;; But only if the user has not turned off tables or fixed-width regions
13004 (org-set-local
13005 'auto-fill-inhibit-regexp
13006 (concat "\\*+ \\|#\\+"
13007 "\\|[ \t]*" org-keyword-time-regexp
13008 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13009 (concat
13010 "\\|[ \t]*["
13011 (if org-enable-table-editor "|" "")
13012 (if org-enable-fixed-width-editor ":" "")
13013 "]"))))
13014 ;; We use our own fill-paragraph function, to make sure that tables
13015 ;; and fixed-width regions are not wrapped. That function will pass
13016 ;; through to `fill-paragraph' when appropriate.
13017 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13018 ; Adaptive filling: To get full control, first make sure that
13019 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13020 (org-set-local 'adaptive-fill-regexp "\000")
13021 (org-set-local 'adaptive-fill-function
13022 'org-adaptive-fill-function)
13023 (org-set-local
13024 'align-mode-rules-list
13025 '((org-in-buffer-settings
13026 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13027 (modes . '(org-mode))))))
13029 (defun org-fill-paragraph (&optional justify)
13030 "Re-align a table, pass through to fill-paragraph if no table."
13031 (let ((table-p (org-at-table-p))
13032 (table.el-p (org-at-table.el-p)))
13033 (cond ((and (equal (char-after (point-at-bol)) ?*)
13034 (save-excursion (goto-char (point-at-bol))
13035 (looking-at outline-regexp)))
13036 t) ; skip headlines
13037 (table.el-p t) ; skip table.el tables
13038 (table-p (org-table-align) t) ; align org-mode tables
13039 (t nil)))) ; call paragraph-fill
13041 ;; For reference, this is the default value of adaptive-fill-regexp
13042 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13044 (defun org-adaptive-fill-function ()
13045 "Return a fill prefix for org-mode files.
13046 In particular, this makes sure hanging paragraphs for hand-formatted lists
13047 work correctly."
13048 (cond ((looking-at "#[ \t]+")
13049 (match-string 0))
13050 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13051 (save-excursion
13052 (goto-char (match-end 0))
13053 (make-string (current-column) ?\ )))
13054 (t nil)))
13056 ;;; Other stuff.
13058 (defun org-toggle-fixed-width-section (arg)
13059 "Toggle the fixed-width export.
13060 If there is no active region, the QUOTE keyword at the current headline is
13061 inserted or removed. When present, it causes the text between this headline
13062 and the next to be exported as fixed-width text, and unmodified.
13063 If there is an active region, this command adds or removes a colon as the
13064 first character of this line. If the first character of a line is a colon,
13065 this line is also exported in fixed-width font."
13066 (interactive "P")
13067 (let* ((cc 0)
13068 (regionp (org-region-active-p))
13069 (beg (if regionp (region-beginning) (point)))
13070 (end (if regionp (region-end)))
13071 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13072 (case-fold-search nil)
13073 (re "[ \t]*\\(:\\)")
13074 off)
13075 (if regionp
13076 (save-excursion
13077 (goto-char beg)
13078 (setq cc (current-column))
13079 (beginning-of-line 1)
13080 (setq off (looking-at re))
13081 (while (> nlines 0)
13082 (setq nlines (1- nlines))
13083 (beginning-of-line 1)
13084 (cond
13085 (arg
13086 (move-to-column cc t)
13087 (insert ":\n")
13088 (forward-line -1))
13089 ((and off (looking-at re))
13090 (replace-match "" t t nil 1))
13091 ((not off) (move-to-column cc t) (insert ":")))
13092 (forward-line 1)))
13093 (save-excursion
13094 (org-back-to-heading)
13095 (if (looking-at (concat outline-regexp
13096 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13097 (replace-match "" t t nil 1)
13098 (if (looking-at outline-regexp)
13099 (progn
13100 (goto-char (match-end 0))
13101 (insert org-quote-string " "))))))))
13103 ;;;; Functions extending outline functionality
13105 (defun org-beginning-of-line (&optional arg)
13106 "Go to the beginning of the current line. If that is invisible, continue
13107 to a visible line beginning. This makes the function of C-a more intuitive.
13108 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13109 first attempt, and only move to after the tags when the cursor is already
13110 beyond the end of the headline."
13111 (interactive "P")
13112 (let ((pos (point)))
13113 (beginning-of-line 1)
13114 (if (bobp)
13116 (backward-char 1)
13117 (if (org-invisible-p)
13118 (while (and (not (bobp)) (org-invisible-p))
13119 (backward-char 1)
13120 (beginning-of-line 1))
13121 (forward-char 1)))
13122 (when org-special-ctrl-a/e
13123 (cond
13124 ((and (looking-at org-todo-line-regexp)
13125 (= (char-after (match-end 1)) ?\ ))
13126 (goto-char
13127 (if (eq org-special-ctrl-a/e t)
13128 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13129 ((= pos (point)) (match-beginning 3))
13130 (t (point)))
13131 (cond ((> pos (point)) (point))
13132 ((not (eq last-command this-command)) (point))
13133 (t (match-beginning 3))))))
13134 ((org-at-item-p)
13135 (goto-char
13136 (if (eq org-special-ctrl-a/e t)
13137 (cond ((> pos (match-end 4)) (match-end 4))
13138 ((= pos (point)) (match-end 4))
13139 (t (point)))
13140 (cond ((> pos (point)) (point))
13141 ((not (eq last-command this-command)) (point))
13142 (t (match-end 4))))))))))
13144 (defun org-end-of-line (&optional arg)
13145 "Go to the end of the line.
13146 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13147 first attempt, and only move to after the tags when the cursor is already
13148 beyond the end of the headline."
13149 (interactive "P")
13150 (if (or (not org-special-ctrl-a/e)
13151 (not (org-on-heading-p)))
13152 (end-of-line arg)
13153 (let ((pos (point)))
13154 (beginning-of-line 1)
13155 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13156 (if (eq org-special-ctrl-a/e t)
13157 (if (or (< pos (match-beginning 1))
13158 (= pos (match-end 0)))
13159 (goto-char (match-beginning 1))
13160 (goto-char (match-end 0)))
13161 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13162 (goto-char (match-end 0))
13163 (goto-char (match-beginning 1))))
13164 (end-of-line arg)))))
13166 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13167 (define-key org-mode-map "\C-e" 'org-end-of-line)
13169 (defun org-kill-line (&optional arg)
13170 "Kill line, to tags or end of line."
13171 (interactive "P")
13172 (cond
13173 ((or (not org-special-ctrl-k)
13174 (bolp)
13175 (not (org-on-heading-p)))
13176 (call-interactively 'kill-line))
13177 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13178 (kill-region (point) (match-beginning 1))
13179 (org-set-tags nil t))
13180 (t (kill-region (point) (point-at-eol)))))
13182 (define-key org-mode-map "\C-k" 'org-kill-line)
13184 (defun org-invisible-p ()
13185 "Check if point is at a character currently not visible."
13186 ;; Early versions of noutline don't have `outline-invisible-p'.
13187 (if (fboundp 'outline-invisible-p)
13188 (outline-invisible-p)
13189 (get-char-property (point) 'invisible)))
13191 (defun org-invisible-p2 ()
13192 "Check if point is at a character currently not visible."
13193 (save-excursion
13194 (if (and (eolp) (not (bobp))) (backward-char 1))
13195 ;; Early versions of noutline don't have `outline-invisible-p'.
13196 (if (fboundp 'outline-invisible-p)
13197 (outline-invisible-p)
13198 (get-char-property (point) 'invisible))))
13200 (defalias 'org-back-to-heading 'outline-back-to-heading)
13201 (defalias 'org-on-heading-p 'outline-on-heading-p)
13202 (defalias 'org-at-heading-p 'outline-on-heading-p)
13203 (defun org-at-heading-or-item-p ()
13204 (or (org-on-heading-p) (org-at-item-p)))
13206 (defun org-on-target-p ()
13207 (or (org-in-regexp org-radio-target-regexp)
13208 (org-in-regexp org-target-regexp)))
13210 (defun org-up-heading-all (arg)
13211 "Move to the heading line of which the present line is a subheading.
13212 This function considers both visible and invisible heading lines.
13213 With argument, move up ARG levels."
13214 (if (fboundp 'outline-up-heading-all)
13215 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13216 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13218 (defun org-up-heading-safe ()
13219 "Move to the heading line of which the present line is a subheading.
13220 This version will not throw an error. It will return the level of the
13221 headline found, or nil if no higher level is found."
13222 (let ((pos (point)) start-level level
13223 (re (concat "^" outline-regexp)))
13224 (catch 'exit
13225 (outline-back-to-heading t)
13226 (setq start-level (funcall outline-level))
13227 (if (equal start-level 1) (throw 'exit nil))
13228 (while (re-search-backward re nil t)
13229 (setq level (funcall outline-level))
13230 (if (< level start-level) (throw 'exit level)))
13231 nil)))
13233 (defun org-first-sibling-p ()
13234 "Is this heading the first child of its parents?"
13235 (interactive)
13236 (let ((re (concat "^" outline-regexp))
13237 level l)
13238 (unless (org-at-heading-p t)
13239 (error "Not at a heading"))
13240 (setq level (funcall outline-level))
13241 (save-excursion
13242 (if (not (re-search-backward re nil t))
13244 (setq l (funcall outline-level))
13245 (< l level)))))
13247 (defun org-goto-sibling (&optional previous)
13248 "Goto the next sibling, even if it is invisible.
13249 When PREVIOUS is set, go to the previous sibling instead. Returns t
13250 when a sibling was found. When none is found, return nil and don't
13251 move point."
13252 (let ((fun (if previous 're-search-backward 're-search-forward))
13253 (pos (point))
13254 (re (concat "^" outline-regexp))
13255 level l)
13256 (when (condition-case nil (org-back-to-heading t) (error nil))
13257 (setq level (funcall outline-level))
13258 (catch 'exit
13259 (or previous (forward-char 1))
13260 (while (funcall fun re nil t)
13261 (setq l (funcall outline-level))
13262 (when (< l level) (goto-char pos) (throw 'exit nil))
13263 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13264 (goto-char pos)
13265 nil))))
13267 (defun org-show-siblings ()
13268 "Show all siblings of the current headline."
13269 (save-excursion
13270 (while (org-goto-sibling) (org-flag-heading nil)))
13271 (save-excursion
13272 (while (org-goto-sibling 'previous)
13273 (org-flag-heading nil))))
13275 (defun org-show-hidden-entry ()
13276 "Show an entry where even the heading is hidden."
13277 (save-excursion
13278 (org-show-entry)))
13280 (defun org-flag-heading (flag &optional entry)
13281 "Flag the current heading. FLAG non-nil means make invisible.
13282 When ENTRY is non-nil, show the entire entry."
13283 (save-excursion
13284 (org-back-to-heading t)
13285 ;; Check if we should show the entire entry
13286 (if entry
13287 (progn
13288 (org-show-entry)
13289 (save-excursion
13290 (and (outline-next-heading)
13291 (org-flag-heading nil))))
13292 (outline-flag-region (max (point-min) (1- (point)))
13293 (save-excursion (outline-end-of-heading) (point))
13294 flag))))
13296 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13297 ;; This is an exact copy of the original function, but it uses
13298 ;; `org-back-to-heading', to make it work also in invisible
13299 ;; trees. And is uses an invisible-OK argument.
13300 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13301 (org-back-to-heading invisible-OK)
13302 (let ((first t)
13303 (level (funcall outline-level)))
13304 (while (and (not (eobp))
13305 (or first (> (funcall outline-level) level)))
13306 (setq first nil)
13307 (outline-next-heading))
13308 (unless to-heading
13309 (if (memq (preceding-char) '(?\n ?\^M))
13310 (progn
13311 ;; Go to end of line before heading
13312 (forward-char -1)
13313 (if (memq (preceding-char) '(?\n ?\^M))
13314 ;; leave blank line before heading
13315 (forward-char -1))))))
13316 (point))
13318 (defun org-show-subtree ()
13319 "Show everything after this heading at deeper levels."
13320 (outline-flag-region
13321 (point)
13322 (save-excursion
13323 (outline-end-of-subtree) (outline-next-heading) (point))
13324 nil))
13326 (defun org-show-entry ()
13327 "Show the body directly following this heading.
13328 Show the heading too, if it is currently invisible."
13329 (interactive)
13330 (save-excursion
13331 (condition-case nil
13332 (progn
13333 (org-back-to-heading t)
13334 (outline-flag-region
13335 (max (point-min) (1- (point)))
13336 (save-excursion
13337 (re-search-forward
13338 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13339 (or (match-beginning 1) (point-max)))
13340 nil))
13341 (error nil))))
13343 (defun org-make-options-regexp (kwds)
13344 "Make a regular expression for keyword lines."
13345 (concat
13347 "#?[ \t]*\\+\\("
13348 (mapconcat 'regexp-quote kwds "\\|")
13349 "\\):[ \t]*"
13350 "\\(.+\\)"))
13352 ;; Make isearch reveal the necessary context
13353 (defun org-isearch-end ()
13354 "Reveal context after isearch exits."
13355 (when isearch-success ; only if search was successful
13356 (if (featurep 'xemacs)
13357 ;; Under XEmacs, the hook is run in the correct place,
13358 ;; we directly show the context.
13359 (org-show-context 'isearch)
13360 ;; In Emacs the hook runs *before* restoring the overlays.
13361 ;; So we have to use a one-time post-command-hook to do this.
13362 ;; (Emacs 22 has a special variable, see function `org-mode')
13363 (unless (and (boundp 'isearch-mode-end-hook-quit)
13364 isearch-mode-end-hook-quit)
13365 ;; Only when the isearch was not quitted.
13366 (org-add-hook 'post-command-hook 'org-isearch-post-command
13367 'append 'local)))))
13369 (defun org-isearch-post-command ()
13370 "Remove self from hook, and show context."
13371 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13372 (org-show-context 'isearch))
13375 ;;;; Integration with and fixes for other packages
13377 ;;; Imenu support
13379 (defvar org-imenu-markers nil
13380 "All markers currently used by Imenu.")
13381 (make-variable-buffer-local 'org-imenu-markers)
13383 (defun org-imenu-new-marker (&optional pos)
13384 "Return a new marker for use by Imenu, and remember the marker."
13385 (let ((m (make-marker)))
13386 (move-marker m (or pos (point)))
13387 (push m org-imenu-markers)
13390 (defun org-imenu-get-tree ()
13391 "Produce the index for Imenu."
13392 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13393 (setq org-imenu-markers nil)
13394 (let* ((n org-imenu-depth)
13395 (re (concat "^" outline-regexp))
13396 (subs (make-vector (1+ n) nil))
13397 (last-level 0)
13398 m tree level head)
13399 (save-excursion
13400 (save-restriction
13401 (widen)
13402 (goto-char (point-max))
13403 (while (re-search-backward re nil t)
13404 (setq level (org-reduced-level (funcall outline-level)))
13405 (when (<= level n)
13406 (looking-at org-complex-heading-regexp)
13407 (setq head (org-match-string-no-properties 4)
13408 m (org-imenu-new-marker))
13409 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13410 (if (>= level last-level)
13411 (push (cons head m) (aref subs level))
13412 (push (cons head (aref subs (1+ level))) (aref subs level))
13413 (loop for i from (1+ level) to n do (aset subs i nil)))
13414 (setq last-level level)))))
13415 (aref subs 1)))
13417 (eval-after-load "imenu"
13418 '(progn
13419 (add-hook 'imenu-after-jump-hook
13420 (lambda () (org-show-context 'org-goto)))))
13422 ;; Speedbar support
13424 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13425 "Overlay marking the agenda restriction line in speedbar.")
13426 (org-overlay-put org-speedbar-restriction-lock-overlay
13427 'face 'org-agenda-restriction-lock)
13428 (org-overlay-put org-speedbar-restriction-lock-overlay
13429 'help-echo "Agendas are currently limited to this item.")
13430 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13432 (defun org-speedbar-set-agenda-restriction ()
13433 "Restrict future agenda commands to the location at point in speedbar.
13434 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13435 (interactive)
13436 (require 'org-agenda)
13437 (let (p m tp np dir txt w)
13438 (cond
13439 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13440 'org-imenu t))
13441 (setq m (get-text-property p 'org-imenu-marker))
13442 (save-excursion
13443 (save-restriction
13444 (set-buffer (marker-buffer m))
13445 (goto-char m)
13446 (org-agenda-set-restriction-lock 'subtree))))
13447 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13448 'speedbar-function 'speedbar-find-file))
13449 (setq tp (previous-single-property-change
13450 (1+ p) 'speedbar-function)
13451 np (next-single-property-change
13452 tp 'speedbar-function)
13453 dir (speedbar-line-directory)
13454 txt (buffer-substring-no-properties (or tp (point-min))
13455 (or np (point-max))))
13456 (save-excursion
13457 (save-restriction
13458 (set-buffer (find-file-noselect
13459 (let ((default-directory dir))
13460 (expand-file-name txt))))
13461 (unless (org-mode-p)
13462 (error "Cannot restrict to non-Org-mode file"))
13463 (org-agenda-set-restriction-lock 'file))))
13464 (t (error "Don't know how to restrict Org-mode's agenda")))
13465 (org-move-overlay org-speedbar-restriction-lock-overlay
13466 (point-at-bol) (point-at-eol))
13467 (setq current-prefix-arg nil)
13468 (org-agenda-maybe-redo)))
13470 (eval-after-load "speedbar"
13471 '(progn
13472 (speedbar-add-supported-extension ".org")
13473 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13474 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13475 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13476 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13477 (add-hook 'speedbar-visiting-tag-hook
13478 (lambda () (org-show-context 'org-goto)))))
13481 ;;; Fixes and Hacks for problems with other packages
13483 ;; Make flyspell not check words in links, to not mess up our keymap
13484 (defun org-mode-flyspell-verify ()
13485 "Don't let flyspell put overlays at active buttons."
13486 (not (get-text-property (point) 'keymap)))
13488 ;; Make `bookmark-jump' show the jump location if it was hidden.
13489 (eval-after-load "bookmark"
13490 '(if (boundp 'bookmark-after-jump-hook)
13491 ;; We can use the hook
13492 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13493 ;; Hook not available, use advice
13494 (defadvice bookmark-jump (after org-make-visible activate)
13495 "Make the position visible."
13496 (org-bookmark-jump-unhide))))
13498 (defun org-bookmark-jump-unhide ()
13499 "Unhide the current position, to show the bookmark location."
13500 (and (org-mode-p)
13501 (or (org-invisible-p)
13502 (save-excursion (goto-char (max (point-min) (1- (point))))
13503 (org-invisible-p)))
13504 (org-show-context 'bookmark-jump)))
13506 ;; Make session.el ignore our circular variable
13507 (eval-after-load "session"
13508 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13510 ;;;; Experimental code
13512 (defun org-closed-in-range ()
13513 "Sparse tree of items closed in a certain time range.
13514 Still experimental, may disappear in the future."
13515 (interactive)
13516 ;; Get the time interval from the user.
13517 (let* ((time1 (time-to-seconds
13518 (org-read-date nil 'to-time nil "Starting date: ")))
13519 (time2 (time-to-seconds
13520 (org-read-date nil 'to-time nil "End date:")))
13521 ;; callback function
13522 (callback (lambda ()
13523 (let ((time
13524 (time-to-seconds
13525 (apply 'encode-time
13526 (org-parse-time-string
13527 (match-string 1))))))
13528 ;; check if time in interval
13529 (and (>= time time1) (<= time time2))))))
13530 ;; make tree, check each match with the callback
13531 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13534 ;;;; Finish up
13536 (provide 'org)
13538 (run-hooks 'org-load-hook)
13540 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13541 ;;; org.el ends here
13543 (defun org-open-link-from-string (s &optional arg)
13544 "Open a link in the string S, as if it was in Org-mode."
13545 (interactive)
13546 (with-temp-buffer
13547 (let ((org-inhibit-startup t))
13548 (org-mode)
13549 (insert s)
13550 (goto-char (point-min))
13551 (org-open-at-point arg))))