Split out org-faces, org-archive.el, org-colview.el from org.el.
[org-mode.git] / lisp / org.el
blob7c0ffbace9b7179c5383dc055f9dfb906c95312f
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-4
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-4"
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 (defgroup org-link-store nil
880 "Options concerning storing links in Org-mode."
881 :tag "Org Store Link"
882 :group 'org-link)
884 (defcustom org-email-link-description-format "Email %c: %.30s"
885 "Format of the description part of a link to an email or usenet message.
886 The following %-excapes will be replaced by corresponding information:
888 %F full \"From\" field
889 %f name, taken from \"From\" field, address if no name
890 %T full \"To\" field
891 %t first name in \"To\" field, address if no name
892 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
893 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
894 %s subject
895 %m message-id.
897 You may use normal field width specification between the % and the letter.
898 This is for example useful to limit the length of the subject.
900 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
901 :group 'org-link-store
902 :type 'string)
904 (defcustom org-from-is-user-regexp
905 (let (r1 r2)
906 (when (and user-mail-address (not (string= user-mail-address "")))
907 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
908 (when (and user-full-name (not (string= user-full-name "")))
909 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
910 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
911 "Regexp mached against the \"From:\" header of an email or usenet message.
912 It should match if the message is from the user him/herself."
913 :group 'org-link-store
914 :type 'regexp)
916 (defcustom org-context-in-file-links t
917 "Non-nil means, file links from `org-store-link' contain context.
918 A search string will be added to the file name with :: as separator and
919 used to find the context when the link is activated by the command
920 `org-open-at-point'.
921 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
922 negates this setting for the duration of the command."
923 :group 'org-link-store
924 :type 'boolean)
926 (defcustom org-keep-stored-link-after-insertion nil
927 "Non-nil means, keep link in list for entire session.
929 The command `org-store-link' adds a link pointing to the current
930 location to an internal list. These links accumulate during a session.
931 The command `org-insert-link' can be used to insert links into any
932 Org-mode file (offering completion for all stored links). When this
933 option is nil, every link which has been inserted once using \\[org-insert-link]
934 will be removed from the list, to make completing the unused links
935 more efficient."
936 :group 'org-link-store
937 :type 'boolean)
939 (defgroup org-link-follow nil
940 "Options concerning following links in Org-mode."
941 :tag "Org Follow Link"
942 :group 'org-link)
944 (defcustom org-follow-link-hook nil
945 "Hook that is run after a link has been followed."
946 :group 'org-link-follow
947 :type 'hook)
949 (defcustom org-tab-follows-link nil
950 "Non-nil means, on links TAB will follow the link.
951 Needs to be set before org.el is loaded."
952 :group 'org-link-follow
953 :type 'boolean)
955 (defcustom org-return-follows-link nil
956 "Non-nil means, on links RET will follow the link.
957 Needs to be set before org.el is loaded."
958 :group 'org-link-follow
959 :type 'boolean)
961 (defcustom org-mouse-1-follows-link
962 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
963 "Non-nil means, mouse-1 on a link will follow the link.
964 A longer mouse click will still set point. Does not work on XEmacs.
965 Needs to be set before org.el is loaded."
966 :group 'org-link-follow
967 :type 'boolean)
969 (defcustom org-mark-ring-length 4
970 "Number of different positions to be recorded in the ring
971 Changing this requires a restart of Emacs to work correctly."
972 :group 'org-link-follow
973 :type 'interger)
975 (defcustom org-link-frame-setup
976 '((vm . vm-visit-folder-other-frame)
977 (gnus . gnus-other-frame)
978 (file . find-file-other-window))
979 "Setup the frame configuration for following links.
980 When following a link with Emacs, it may often be useful to display
981 this link in another window or frame. This variable can be used to
982 set this up for the different types of links.
983 For VM, use any of
984 `vm-visit-folder'
985 `vm-visit-folder-other-frame'
986 For Gnus, use any of
987 `gnus'
988 `gnus-other-frame'
989 For FILE, use any of
990 `find-file'
991 `find-file-other-window'
992 `find-file-other-frame'
993 For the calendar, use the variable `calendar-setup'.
994 For BBDB, it is currently only possible to display the matches in
995 another window."
996 :group 'org-link-follow
997 :type '(list
998 (cons (const vm)
999 (choice
1000 (const vm-visit-folder)
1001 (const vm-visit-folder-other-window)
1002 (const vm-visit-folder-other-frame)))
1003 (cons (const gnus)
1004 (choice
1005 (const gnus)
1006 (const gnus-other-frame)))
1007 (cons (const file)
1008 (choice
1009 (const find-file)
1010 (const find-file-other-window)
1011 (const find-file-other-frame)))))
1013 (defcustom org-display-internal-link-with-indirect-buffer nil
1014 "Non-nil means, use indirect buffer to display infile links.
1015 Activating internal links (from one location in a file to another location
1016 in the same file) normally just jumps to the location. When the link is
1017 activated with a C-u prefix (or with mouse-3), the link is displayed in
1018 another window. When this option is set, the other window actually displays
1019 an indirect buffer clone of the current buffer, to avoid any visibility
1020 changes to the current buffer."
1021 :group 'org-link-follow
1022 :type 'boolean)
1024 (defcustom org-open-non-existing-files nil
1025 "Non-nil means, `org-open-file' will open non-existing files.
1026 When nil, an error will be generated."
1027 :group 'org-link-follow
1028 :type 'boolean)
1030 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1031 "Function and arguments to call for following mailto links.
1032 This is a list with the first element being a lisp function, and the
1033 remaining elements being arguments to the function. In string arguments,
1034 %a will be replaced by the address, and %s will be replaced by the subject
1035 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1036 :group 'org-link-follow
1037 :type '(choice
1038 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1039 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1040 (const :tag "message-mail" (message-mail "%a" "%s"))
1041 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1043 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1044 "Non-nil means, ask for confirmation before executing shell links.
1045 Shell links can be dangerous: just think about a link
1047 [[shell:rm -rf ~/*][Google Search]]
1049 This link would show up in your Org-mode document as \"Google Search\",
1050 but really it would remove your entire home directory.
1051 Therefore we advise against setting this variable to nil.
1052 Just change it to `y-or-n-p' of you want to confirm with a
1053 single keystroke rather than having to type \"yes\"."
1054 :group 'org-link-follow
1055 :type '(choice
1056 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1057 (const :tag "with y-or-n (faster)" y-or-n-p)
1058 (const :tag "no confirmation (dangerous)" nil)))
1060 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1061 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1062 Elisp links can be dangerous: just think about a link
1064 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1066 This link would show up in your Org-mode document as \"Google Search\",
1067 but really it would remove your entire home directory.
1068 Therefore we advise against setting this variable to nil.
1069 Just change it to `y-or-n-p' of you want to confirm with a
1070 single keystroke rather than having to type \"yes\"."
1071 :group 'org-link-follow
1072 :type '(choice
1073 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1074 (const :tag "with y-or-n (faster)" y-or-n-p)
1075 (const :tag "no confirmation (dangerous)" nil)))
1077 (defconst org-file-apps-defaults-gnu
1078 '((remote . emacs)
1079 (t . mailcap))
1080 "Default file applications on a UNIX or GNU/Linux system.
1081 See `org-file-apps'.")
1083 (defconst org-file-apps-defaults-macosx
1084 '((remote . emacs)
1085 (t . "open %s")
1086 ("ps" . "gv %s")
1087 ("ps.gz" . "gv %s")
1088 ("eps" . "gv %s")
1089 ("eps.gz" . "gv %s")
1090 ("dvi" . "xdvi %s")
1091 ("fig" . "xfig %s"))
1092 "Default file applications on a MacOS X system.
1093 The system \"open\" is known as a default, but we use X11 applications
1094 for some files for which the OS does not have a good default.
1095 See `org-file-apps'.")
1097 (defconst org-file-apps-defaults-windowsnt
1098 (list
1099 '(remote . emacs)
1100 (cons t
1101 (list (if (featurep 'xemacs)
1102 'mswindows-shell-execute
1103 'w32-shell-execute)
1104 "open" 'file)))
1105 "Default file applications on a Windows NT system.
1106 The system \"open\" is used for most files.
1107 See `org-file-apps'.")
1109 (defcustom org-file-apps
1111 ("txt" . emacs)
1112 ("tex" . emacs)
1113 ("ltx" . emacs)
1114 ("org" . emacs)
1115 ("el" . emacs)
1116 ("bib" . emacs)
1118 "External applications for opening `file:path' items in a document.
1119 Org-mode uses system defaults for different file types, but
1120 you can use this variable to set the application for a given file
1121 extension. The entries in this list are cons cells where the car identifies
1122 files and the cdr the corresponding command. Possible values for the
1123 file identifier are
1124 \"ext\" A string identifying an extension
1125 `directory' Matches a directory
1126 `remote' Matches a remote file, accessible through tramp or efs.
1127 Remote files most likely should be visited through Emacs
1128 because external applications cannot handle such paths.
1129 t Default for all remaining files
1131 Possible values for the command are:
1132 `emacs' The file will be visited by the current Emacs process.
1133 `default' Use the default application for this file type.
1134 string A command to be executed by a shell; %s will be replaced
1135 by the path to the file.
1136 sexp A Lisp form which will be evaluated. The file path will
1137 be available in the Lisp variable `file'.
1138 For more examples, see the system specific constants
1139 `org-file-apps-defaults-macosx'
1140 `org-file-apps-defaults-windowsnt'
1141 `org-file-apps-defaults-gnu'."
1142 :group 'org-link-follow
1143 :type '(repeat
1144 (cons (choice :value ""
1145 (string :tag "Extension")
1146 (const :tag "Default for unrecognized files" t)
1147 (const :tag "Remote file" remote)
1148 (const :tag "Links to a directory" directory))
1149 (choice :value ""
1150 (const :tag "Visit with Emacs" emacs)
1151 (const :tag "Use system default" default)
1152 (string :tag "Command")
1153 (sexp :tag "Lisp form")))))
1155 (defgroup org-refile nil
1156 "Options concerning refiling entries in Org-mode."
1157 :tag "Org Remember"
1158 :group 'org)
1160 (defcustom org-directory "~/org"
1161 "Directory with org files.
1162 This directory will be used as default to prompt for org files.
1163 Used by the hooks for remember.el."
1164 :group 'org-refile
1165 :group 'org-remember
1166 :type 'directory)
1168 (defcustom org-default-notes-file "~/.notes"
1169 "Default target for storing notes.
1170 Used by the hooks for remember.el. This can be a string, or nil to mean
1171 the value of `remember-data-file'.
1172 You can set this on a per-template basis with the variable
1173 `org-remember-templates'."
1174 :group 'org-refile
1175 :group 'org-remember
1176 :type '(choice
1177 (const :tag "Default from remember-data-file" nil)
1178 file))
1180 (defcustom org-goto-interface 'outline
1181 "The default interface to be used for `org-goto'.
1182 Allowed vaues are:
1183 outline The interface shows an outline of the relevant file
1184 and the correct heading is found by moving through
1185 the outline or by searching with incremental search.
1186 outline-path-completion Headlines in the current buffer are offered via
1187 completion."
1188 :group 'org-refile
1189 :type '(choice
1190 (const :tag "Outline" outline)
1191 (const :tag "Outline-path-completion" outline-path-completion)))
1193 (defcustom org-reverse-note-order nil
1194 "Non-nil means, store new notes at the beginning of a file or entry.
1195 When nil, new notes will be filed to the end of a file or entry.
1196 This can also be a list with cons cells of regular expressions that
1197 are matched against file names, and values."
1198 :group 'org-remember
1199 :type '(choice
1200 (const :tag "Reverse always" t)
1201 (const :tag "Reverse never" nil)
1202 (repeat :tag "By file name regexp"
1203 (cons regexp boolean))))
1205 (defcustom org-refile-targets nil
1206 "Targets for refiling entries with \\[org-refile].
1207 This is list of cons cells. Each cell contains:
1208 - a specification of the files to be considered, either a list of files,
1209 or a symbol whose function or variable value will be used to retrieve
1210 a file name or a list of file names. Nil means, refile to a different
1211 heading in the current buffer.
1212 - A specification of how to find candidate refile targets. This may be
1213 any of
1214 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1215 This tag has to be present in all target headlines, inheritance will
1216 not be considered.
1217 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1218 todo keyword.
1219 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1220 headlines that are refiling targets.
1221 - a cons cell (:level . N). Any headline of level N is considered a target.
1222 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1223 :group 'org-remember
1224 :type '(repeat
1225 (cons
1226 (choice :value org-agenda-files
1227 (const :tag "All agenda files" org-agenda-files)
1228 (const :tag "Current buffer" nil)
1229 (function) (variable) (file))
1230 (choice :tag "Identify target headline by"
1231 (cons :tag "Specific tag" (const :tag) (string))
1232 (cons :tag "TODO keyword" (const :todo) (string))
1233 (cons :tag "Regular expression" (const :regexp) (regexp))
1234 (cons :tag "Level number" (const :level) (integer))
1235 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1237 (defcustom org-refile-use-outline-path nil
1238 "Non-nil means, provide refile targets as paths.
1239 So a level 3 headline will be available as level1/level2/level3.
1240 When the value is `file', also include the file name (without directory)
1241 into the path. When `full-file-path', include the full file path."
1242 :group 'org-remember
1243 :type '(choice
1244 (const :tag "Not" nil)
1245 (const :tag "Yes" t)
1246 (const :tag "Start with file name" file)
1247 (const :tag "Start with full file path" full-file-path)))
1249 (defgroup org-todo nil
1250 "Options concerning TODO items in Org-mode."
1251 :tag "Org TODO"
1252 :group 'org)
1254 (defgroup org-progress nil
1255 "Options concerning Progress logging in Org-mode."
1256 :tag "Org Progress"
1257 :group 'org-time)
1259 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1260 "List of TODO entry keyword sequences and their interpretation.
1261 \\<org-mode-map>This is a list of sequences.
1263 Each sequence starts with a symbol, either `sequence' or `type',
1264 indicating if the keywords should be interpreted as a sequence of
1265 action steps, or as different types of TODO items. The first
1266 keywords are states requiring action - these states will select a headline
1267 for inclusion into the global TODO list Org-mode produces. If one of
1268 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1269 signify that no further action is necessary. If \"|\" is not found,
1270 the last keyword is treated as the only DONE state of the sequence.
1272 The command \\[org-todo] cycles an entry through these states, and one
1273 additional state where no keyword is present. For details about this
1274 cycling, see the manual.
1276 TODO keywords and interpretation can also be set on a per-file basis with
1277 the special #+SEQ_TODO and #+TYP_TODO lines.
1279 Each keyword can optionally specify a character for fast state selection
1280 \(in combination with the variable `org-use-fast-todo-selection')
1281 and specifiers for state change logging, using the same syntax
1282 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1283 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1284 indicates to record a time stamp each time this state is selected.
1286 Each keyword may also specify if a timestamp or a note should be
1287 recorded when entering or leaving the state, by adding additional
1288 characters in the parenthesis after the keyword. This looks like this:
1289 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1290 record only the time of the state change. With X and Y being either
1291 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1292 Y when leaving the state if and only if the *target* state does not
1293 define X. You may omit any of the fast-selection key or X or /Y,
1294 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1296 For backward compatibility, this variable may also be just a list
1297 of keywords - in this case the interptetation (sequence or type) will be
1298 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1299 :group 'org-todo
1300 :group 'org-keywords
1301 :type '(choice
1302 (repeat :tag "Old syntax, just keywords"
1303 (string :tag "Keyword"))
1304 (repeat :tag "New syntax"
1305 (cons
1306 (choice
1307 :tag "Interpretation"
1308 (const :tag "Sequence (cycling hits every state)" sequence)
1309 (const :tag "Type (cycling directly to DONE)" type))
1310 (repeat
1311 (string :tag "Keyword"))))))
1313 (defvar org-todo-keywords-1 nil
1314 "All TODO and DONE keywords active in a buffer.")
1315 (make-variable-buffer-local 'org-todo-keywords-1)
1316 (defvar org-todo-keywords-for-agenda nil)
1317 (defvar org-done-keywords-for-agenda nil)
1318 (defvar org-not-done-keywords nil)
1319 (make-variable-buffer-local 'org-not-done-keywords)
1320 (defvar org-done-keywords nil)
1321 (make-variable-buffer-local 'org-done-keywords)
1322 (defvar org-todo-heads nil)
1323 (make-variable-buffer-local 'org-todo-heads)
1324 (defvar org-todo-sets nil)
1325 (make-variable-buffer-local 'org-todo-sets)
1326 (defvar org-todo-log-states nil)
1327 (make-variable-buffer-local 'org-todo-log-states)
1328 (defvar org-todo-kwd-alist nil)
1329 (make-variable-buffer-local 'org-todo-kwd-alist)
1330 (defvar org-todo-key-alist nil)
1331 (make-variable-buffer-local 'org-todo-key-alist)
1332 (defvar org-todo-key-trigger nil)
1333 (make-variable-buffer-local 'org-todo-key-trigger)
1335 (defcustom org-todo-interpretation 'sequence
1336 "Controls how TODO keywords are interpreted.
1337 This variable is in principle obsolete and is only used for
1338 backward compatibility, if the interpretation of todo keywords is
1339 not given already in `org-todo-keywords'. See that variable for
1340 more information."
1341 :group 'org-todo
1342 :group 'org-keywords
1343 :type '(choice (const sequence)
1344 (const type)))
1346 (defcustom org-use-fast-todo-selection 'prefix
1347 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1348 This variable describes if and under what circumstances the cycling
1349 mechanism for TODO keywords will be replaced by a single-key, direct
1350 selection scheme.
1352 When nil, fast selection is never used.
1354 When the symbol `prefix', it will be used when `org-todo' is called with
1355 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1356 in an agenda buffer.
1358 When t, fast selection is used by default. In this case, the prefix
1359 argument forces cycling instead.
1361 In all cases, the special interface is only used if access keys have actually
1362 been assigned by the user, i.e. if keywords in the configuration are followed
1363 by a letter in parenthesis, like TODO(t)."
1364 :group 'org-todo
1365 :type '(choice
1366 (const :tag "Never" nil)
1367 (const :tag "By default" t)
1368 (const :tag "Only with C-u C-c C-t" prefix)))
1370 (defcustom org-after-todo-state-change-hook nil
1371 "Hook which is run after the state of a TODO item was changed.
1372 The new state (a string with a TODO keyword, or nil) is available in the
1373 Lisp variable `state'."
1374 :group 'org-todo
1375 :type 'hook)
1377 (defcustom org-log-done nil
1378 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1379 When equal to the list (done), also prompt for a closing note.
1380 This can also be configured on a per-file basis by adding one of
1381 the following lines anywhere in the buffer:
1383 #+STARTUP: logdone
1384 #+STARTUP: lognotedone
1385 #+STARTUP: nologdone"
1386 :group 'org-todo
1387 :group 'org-progress
1388 :type '(choice
1389 (const :tag "No logging" nil)
1390 (const :tag "Record CLOSED timestamp" time)
1391 (const :tag "Record CLOSED timestamp with closing note." note)))
1393 ;; Normalize old uses of org-log-done.
1394 (cond
1395 ((eq org-log-done t) (setq org-log-done 'time))
1396 ((and (listp org-log-done) (memq 'done org-log-done))
1397 (setq org-log-done 'note)))
1399 (defcustom org-log-note-clock-out nil
1400 "Non-nil means, recored a note when clocking out of an item.
1401 This can also be configured on a per-file basis by adding one of
1402 the following lines anywhere in the buffer:
1404 #+STARTUP: lognoteclock-out
1405 #+STARTUP: nolognoteclock-out"
1406 :group 'org-todo
1407 :group 'org-progress
1408 :type 'boolean)
1410 (defcustom org-log-done-with-time t
1411 "Non-nil means, the CLOSED time stamp will contain date and time.
1412 When nil, only the date will be recorded."
1413 :group 'org-progress
1414 :type 'boolean)
1416 (defcustom org-log-note-headings
1417 '((done . "CLOSING NOTE %t")
1418 (state . "State %-12s %t")
1419 (note . "Note taken on %t")
1420 (clock-out . ""))
1421 "Headings for notes added to entries.
1422 The value is an alist, with the car being a symbol indicating the note
1423 context, and the cdr is the heading to be used. The heading may also be the
1424 empty string.
1425 %t in the heading will be replaced by a time stamp.
1426 %s will be replaced by the new TODO state, in double quotes.
1427 %u will be replaced by the user name.
1428 %U will be replaced by the full user name."
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(list :greedy t
1432 (cons (const :tag "Heading when closing an item" done) string)
1433 (cons (const :tag
1434 "Heading when changing todo state (todo sequence only)"
1435 state) string)
1436 (cons (const :tag "Heading when just taking a note" note) string)
1437 (cons (const :tag "Heading when clocking out" clock-out) string)))
1439 (unless (assq 'note org-log-note-headings)
1440 (push '(note . "%t") org-log-note-headings))
1442 (defcustom org-log-states-order-reversed t
1443 "Non-nil means, the latest state change note will be directly after heading.
1444 When nil, the notes will be orderer according to time."
1445 :group 'org-todo
1446 :group 'org-progress
1447 :type 'boolean)
1449 (defcustom org-log-repeat 'time
1450 "Non-nil means, record moving through the DONE state when triggering repeat.
1451 An auto-repeating tasks is immediately switched back to TODO when marked
1452 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1453 the TODO keyword definition, or recording a cloing note by setting
1454 `org-log-done', there will be no record of the task moving trhough DONE.
1455 This variable forces taking a note anyway. Possible values are:
1457 nil Don't force a record
1458 time Record a time stamp
1459 note Record a note
1461 This option can also be set with on a per-file-basis with
1463 #+STARTUP: logrepeat
1464 #+STARTUP: lognoterepeat
1465 #+STARTUP: nologrepeat
1467 You can have local logging settings for a subtree by setting the LOGGING
1468 property to one or more of these keywords."
1469 :group 'org-todo
1470 :group 'org-progress
1471 :type '(choice
1472 (const :tag "Don't force a record" nil)
1473 (const :tag "Force recording the DONE state" time)
1474 (const :tag "Force recording a note with the DONE state" note)))
1477 (defgroup org-priorities nil
1478 "Priorities in Org-mode."
1479 :tag "Org Priorities"
1480 :group 'org-todo)
1482 (defcustom org-highest-priority ?A
1483 "The highest priority of TODO items. A character like ?A, ?B etc.
1484 Must have a smaller ASCII number than `org-lowest-priority'."
1485 :group 'org-priorities
1486 :type 'character)
1488 (defcustom org-lowest-priority ?C
1489 "The lowest priority of TODO items. A character like ?A, ?B etc.
1490 Must have a larger ASCII number than `org-highest-priority'."
1491 :group 'org-priorities
1492 :type 'character)
1494 (defcustom org-default-priority ?B
1495 "The default priority of TODO items.
1496 This is the priority an item get if no explicit priority is given."
1497 :group 'org-priorities
1498 :type 'character)
1500 (defcustom org-priority-start-cycle-with-default t
1501 "Non-nil means, start with default priority when starting to cycle.
1502 When this is nil, the first step in the cycle will be (depending on the
1503 command used) one higher or lower that the default priority."
1504 :group 'org-priorities
1505 :type 'boolean)
1507 (defgroup org-time nil
1508 "Options concerning time stamps and deadlines in Org-mode."
1509 :tag "Org Time"
1510 :group 'org)
1512 (defcustom org-insert-labeled-timestamps-at-point nil
1513 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1514 When nil, these labeled time stamps are forces into the second line of an
1515 entry, just after the headline. When scheduling from the global TODO list,
1516 the time stamp will always be forced into the second line."
1517 :group 'org-time
1518 :type 'boolean)
1520 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1521 "Formats for `format-time-string' which are used for time stamps.
1522 It is not recommended to change this constant.")
1524 (defcustom org-time-stamp-rounding-minutes '(0 5)
1525 "Number of minutes to round time stamps to.
1526 These are two values, the first applies when first creating a time stamp.
1527 The second applies when changing it with the commands `S-up' and `S-down'.
1528 When changing the time stamp, this means that it will change in steps
1529 of N minutes, as given by the second value.
1531 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1532 numbers should be factors of 60, so for example 5, 10, 15.
1534 When this is larger than 1, you can still force an exact time-stamp by using
1535 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1536 and by using a prefix arg to `S-up/down' to specify the exact number
1537 of minutes to shift."
1538 :group 'org-time
1539 :get '(lambda (var) ; Make sure all entries have 5 elements
1540 (if (integerp (default-value var))
1541 (list (default-value var) 5)
1542 (default-value var)))
1543 :type '(list
1544 (integer :tag "when inserting times")
1545 (integer :tag "when modifying times")))
1547 ;; Normalize old customizations of this variable.
1548 (when (integerp org-time-stamp-rounding-minutes)
1549 (setq org-time-stamp-rounding-minutes
1550 (list org-time-stamp-rounding-minutes
1551 org-time-stamp-rounding-minutes)))
1553 (defcustom org-display-custom-times nil
1554 "Non-nil means, overlay custom formats over all time stamps.
1555 The formats are defined through the variable `org-time-stamp-custom-formats'.
1556 To turn this on on a per-file basis, insert anywhere in the file:
1557 #+STARTUP: customtime"
1558 :group 'org-time
1559 :set 'set-default
1560 :type 'sexp)
1561 (make-variable-buffer-local 'org-display-custom-times)
1563 (defcustom org-time-stamp-custom-formats
1564 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1565 "Custom formats for time stamps. See `format-time-string' for the syntax.
1566 These are overlayed over the default ISO format if the variable
1567 `org-display-custom-times' is set. Time like %H:%M should be at the
1568 end of the second format."
1569 :group 'org-time
1570 :type 'sexp)
1572 (defun org-time-stamp-format (&optional long inactive)
1573 "Get the right format for a time string."
1574 (let ((f (if long (cdr org-time-stamp-formats)
1575 (car org-time-stamp-formats))))
1576 (if inactive
1577 (concat "[" (substring f 1 -1) "]")
1578 f)))
1580 (defcustom org-deadline-warning-days 14
1581 "No. of days before expiration during which a deadline becomes active.
1582 This variable governs the display in sparse trees and in the agenda.
1583 When 0 or negative, it means use this number (the absolute value of it)
1584 even if a deadline has a different individual lead time specified."
1585 :group 'org-time
1586 :group 'org-agenda-daily/weekly
1587 :type 'number)
1589 (defcustom org-read-date-prefer-future t
1590 "Non-nil means, assume future for incomplete date input from user.
1591 This affects the following situations:
1592 1. The user gives a day, but no month.
1593 For example, if today is the 15th, and you enter \"3\", Org-mode will
1594 read this as the third of *next* month. However, if you enter \"17\",
1595 it will be considered as *this* month.
1596 2. The user gives a month but not a year.
1597 For example, if it is april and you enter \"feb 2\", this will be read
1598 as feb 2, *next* year. \"May 5\", however, will be this year.
1600 Currently this does not work for ISO week specifications.
1602 When this option is nil, the current month and year will always be used
1603 as defaults."
1604 :group 'org-time
1605 :type 'boolean)
1607 (defcustom org-read-date-display-live t
1608 "Non-nil means, display current interpretation of date prompt live.
1609 This display will be in an overlay, in the minibuffer."
1610 :group 'org-time
1611 :type 'boolean)
1613 (defcustom org-read-date-popup-calendar t
1614 "Non-nil means, pop up a calendar when prompting for a date.
1615 In the calendar, the date can be selected with mouse-1. However, the
1616 minibuffer will also be active, and you can simply enter the date as well.
1617 When nil, only the minibuffer will be available."
1618 :group 'org-time
1619 :type 'boolean)
1620 (if (fboundp 'defvaralias)
1621 (defvaralias 'org-popup-calendar-for-date-prompt
1622 'org-read-date-popup-calendar))
1624 (defcustom org-extend-today-until 0
1625 "The hour when your day really ends.
1626 This has influence for the following applications:
1627 - When switching the agenda to \"today\". It it is still earlier than
1628 the time given here, the day recognized as TODAY is actually yesterday.
1629 - When a date is read from the user and it is still before the time given
1630 here, the current date and time will be assumed to be yesterday, 23:59.
1632 FIXME:
1633 IMPORTANT: This is still a very experimental feature, it may disappear
1634 again or it may be extended to mean more things."
1635 :group 'org-time
1636 :type 'number)
1638 (defcustom org-edit-timestamp-down-means-later nil
1639 "Non-nil means, S-down will increase the time in a time stamp.
1640 When nil, S-up will increase."
1641 :group 'org-time
1642 :type 'boolean)
1644 (defcustom org-calendar-follow-timestamp-change t
1645 "Non-nil means, make the calendar window follow timestamp changes.
1646 When a timestamp is modified and the calendar window is visible, it will be
1647 moved to the new date."
1648 :group 'org-time
1649 :type 'boolean)
1651 (defgroup org-tags nil
1652 "Options concerning tags in Org-mode."
1653 :tag "Org Tags"
1654 :group 'org)
1656 (defcustom org-tag-alist nil
1657 "List of tags allowed in Org-mode files.
1658 When this list is nil, Org-mode will base TAG input on what is already in the
1659 buffer.
1660 The value of this variable is an alist, the car of each entry must be a
1661 keyword as a string, the cdr may be a character that is used to select
1662 that tag through the fast-tag-selection interface.
1663 See the manual for details."
1664 :group 'org-tags
1665 :type '(repeat
1666 (choice
1667 (cons (string :tag "Tag name")
1668 (character :tag "Access char"))
1669 (const :tag "Start radio group" (:startgroup))
1670 (const :tag "End radio group" (:endgroup)))))
1672 (defcustom org-use-fast-tag-selection 'auto
1673 "Non-nil means, use fast tag selection scheme.
1674 This is a special interface to select and deselect tags with single keys.
1675 When nil, fast selection is never used.
1676 When the symbol `auto', fast selection is used if and only if selection
1677 characters for tags have been configured, either through the variable
1678 `org-tag-alist' or through a #+TAGS line in the buffer.
1679 When t, fast selection is always used and selection keys are assigned
1680 automatically if necessary."
1681 :group 'org-tags
1682 :type '(choice
1683 (const :tag "Always" t)
1684 (const :tag "Never" nil)
1685 (const :tag "When selection characters are configured" 'auto)))
1687 (defcustom org-fast-tag-selection-single-key nil
1688 "Non-nil means, fast tag selection exits after first change.
1689 When nil, you have to press RET to exit it.
1690 During fast tag selection, you can toggle this flag with `C-c'.
1691 This variable can also have the value `expert'. In this case, the window
1692 displaying the tags menu is not even shown, until you press C-c again."
1693 :group 'org-tags
1694 :type '(choice
1695 (const :tag "No" nil)
1696 (const :tag "Yes" t)
1697 (const :tag "Expert" expert)))
1699 (defvar org-fast-tag-selection-include-todo nil
1700 "Non-nil means, fast tags selection interface will also offer TODO states.
1701 This is an undocumented feature, you should not rely on it.")
1703 (defcustom org-tags-column -80
1704 "The column to which tags should be indented in a headline.
1705 If this number is positive, it specifies the column. If it is negative,
1706 it means that the tags should be flushright to that column. For example,
1707 -80 works well for a normal 80 character screen."
1708 :group 'org-tags
1709 :type 'integer)
1711 (defcustom org-auto-align-tags t
1712 "Non-nil means, realign tags after pro/demotion of TODO state change.
1713 These operations change the length of a headline and therefore shift
1714 the tags around. With this options turned on, after each such operation
1715 the tags are again aligned to `org-tags-column'."
1716 :group 'org-tags
1717 :type 'boolean)
1719 (defcustom org-use-tag-inheritance t
1720 "Non-nil means, tags in levels apply also for sublevels.
1721 When nil, only the tags directly given in a specific line apply there.
1722 If you turn off this option, you very likely want to turn on the
1723 companion option `org-tags-match-list-sublevels'.
1725 This may also be a list of tags that should be inherited, or a regexp that
1726 matches tags that should be inherited."
1727 :group 'org-tags
1728 :type '(choice
1729 (const :tag "Not" nil)
1730 (const :tag "Always" t)
1731 (repeat :tag "Specific tags" (string :tag "Tag"))
1732 (regexp :tag "Tags matched by regexp")))
1734 (defun org-tag-inherit-p (tag)
1735 "Check if TAG is one that should be inherited."
1736 (cond
1737 ((eq org-use-tag-inheritance t) t)
1738 ((not org-use-tag-inheritance) nil)
1739 ((stringp org-use-tag-inheritance)
1740 (string-match org-use-tag-inheritance tag))
1741 ((listp org-use-tag-inheritance)
1742 (member tag org-use-tag-inheritance))
1743 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1745 (defcustom org-tags-match-list-sublevels nil
1746 "Non-nil means list also sublevels of headlines matching tag search.
1747 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1748 the sublevels of a headline matching a tag search often also match
1749 the same search. Listing all of them can create very long lists.
1750 Setting this variable to nil causes subtrees of a match to be skipped.
1751 This option is off by default, because inheritance in on. If you turn
1752 inheritance off, you very likely want to turn this option on.
1754 As a special case, if the tag search is restricted to TODO items, the
1755 value of this variable is ignored and sublevels are always checked, to
1756 make sure all corresponding TODO items find their way into the list."
1757 :group 'org-tags
1758 :type 'boolean)
1760 (defvar org-tags-history nil
1761 "History of minibuffer reads for tags.")
1762 (defvar org-last-tags-completion-table nil
1763 "The last used completion table for tags.")
1764 (defvar org-after-tags-change-hook nil
1765 "Hook that is run after the tags in a line have changed.")
1767 (defgroup org-properties nil
1768 "Options concerning properties in Org-mode."
1769 :tag "Org Properties"
1770 :group 'org)
1772 (defcustom org-property-format "%-10s %s"
1773 "How property key/value pairs should be formatted by `indent-line'.
1774 When `indent-line' hits a property definition, it will format the line
1775 according to this format, mainly to make sure that the values are
1776 lined-up with respect to each other."
1777 :group 'org-properties
1778 :type 'string)
1780 (defcustom org-use-property-inheritance nil
1781 "Non-nil means, properties apply also for sublevels.
1783 This setting is chiefly used during property searches. Turning it on can
1784 cause significant overhead when doing a search, which is why it is not
1785 on by default.
1787 When nil, only the properties directly given in the current entry count.
1788 When t, every property is inherited. The value may also be a list of
1789 properties that should have inheritance, or a regular expression matching
1790 properties that should be inherited.
1792 However, note that some special properties use inheritance under special
1793 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1794 and the properties ending in \"_ALL\" when they are used as descriptor
1795 for valid values of a property.
1797 Note for programmers:
1798 When querying an entry with `org-entry-get', you can control if inheritance
1799 should be used. By default, `org-entry-get' looks only at the local
1800 properties. You can request inheritance by setting the inherit argument
1801 to t (to force inheritance) or to `selective' (to respect the setting
1802 in this variable)."
1803 :group 'org-properties
1804 :type '(choice
1805 (const :tag "Not" nil)
1806 (const :tag "Always" t)
1807 (repeat :tag "Specific properties" (string :tag "Property"))
1808 (regexp :tag "Properties matched by regexp")))
1810 (defun org-property-inherit-p (property)
1811 "Check if PROPERTY is one that should be inherited."
1812 (cond
1813 ((eq org-use-property-inheritance t) t)
1814 ((not org-use-property-inheritance) nil)
1815 ((stringp org-use-property-inheritance)
1816 (string-match org-use-property-inheritance property))
1817 ((listp org-use-property-inheritance)
1818 (member property org-use-property-inheritance))
1819 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1821 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1822 "The default column format, if no other format has been defined.
1823 This variable can be set on the per-file basis by inserting a line
1825 #+COLUMNS: %25ITEM ....."
1826 :group 'org-properties
1827 :type 'string)
1829 (defcustom org-global-properties nil
1830 "List of property/value pairs that can be inherited by any entry.
1831 You can set buffer-local values for this by adding lines like
1833 #+PROPERTY: NAME VALUE"
1834 :group 'org-properties
1835 :type '(repeat
1836 (cons (string :tag "Property")
1837 (string :tag "Value"))))
1839 (defvar org-local-properties nil
1840 "List of property/value pairs that can be inherited by any entry.
1841 Valid for the current buffer.
1842 This variable is populated from #+PROPERTY lines.")
1844 (defgroup org-agenda nil
1845 "Options concerning agenda views in Org-mode."
1846 :tag "Org Agenda"
1847 :group 'org)
1849 (defvar org-category nil
1850 "Variable used by org files to set a category for agenda display.
1851 Such files should use a file variable to set it, for example
1853 # -*- mode: org; org-category: \"ELisp\"
1855 or contain a special line
1857 #+CATEGORY: ELisp
1859 If the file does not specify a category, then file's base name
1860 is used instead.")
1861 (make-variable-buffer-local 'org-category)
1863 (defcustom org-agenda-files nil
1864 "The files to be used for agenda display.
1865 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1866 \\[org-remove-file]. You can also use customize to edit the list.
1868 If an entry is a directory, all files in that directory that are matched by
1869 `org-agenda-file-regexp' will be part of the file list.
1871 If the value of the variable is not a list but a single file name, then
1872 the list of agenda files is actually stored and maintained in that file, one
1873 agenda file per line."
1874 :group 'org-agenda
1875 :type '(choice
1876 (repeat :tag "List of files and directories" file)
1877 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1879 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1880 "Regular expression to match files for `org-agenda-files'.
1881 If any element in the list in that variable contains a directory instead
1882 of a normal file, all files in that directory that are matched by this
1883 regular expression will be included."
1884 :group 'org-agenda
1885 :type 'regexp)
1887 (defcustom org-agenda-text-search-extra-files nil
1888 "List of extra files to be searched by text search commands.
1889 These files will be search in addition to the agenda files bu the
1890 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1891 Note that these files will only be searched for text search commands,
1892 not for the other agenda views like todo lists, tag earches or the weekly
1893 agenda. This variable is intended to list notes and possibly archive files
1894 that should also be searched by these two commands."
1895 :group 'org-agenda
1896 :type '(repeat file))
1898 (if (fboundp 'defvaralias)
1899 (defvaralias 'org-agenda-multi-occur-extra-files
1900 'org-agenda-text-search-extra-files))
1902 (defcustom org-agenda-skip-unavailable-files nil
1903 "t means to just skip non-reachable files in `org-agenda-files'.
1904 Nil means to remove them, after a query, from the list."
1905 :group 'org-agenda
1906 :type 'boolean)
1908 (defcustom org-calendar-to-agenda-key [?c]
1909 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1910 The command `org-calendar-goto-agenda' will be bound to this key. The
1911 default is the character `c' because then `c' can be used to switch back and
1912 forth between agenda and calendar."
1913 :group 'org-agenda
1914 :type 'sexp)
1916 (eval-after-load "calendar"
1917 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1918 'org-calendar-goto-agenda))
1920 (defgroup org-latex nil
1921 "Options for embedding LaTeX code into Org-mode."
1922 :tag "Org LaTeX"
1923 :group 'org)
1925 (defcustom org-format-latex-options
1926 '(:foreground default :background default :scale 1.0
1927 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1928 :matchers ("begin" "$" "$$" "\\(" "\\["))
1929 "Options for creating images from LaTeX fragments.
1930 This is a property list with the following properties:
1931 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1932 `default' means use the forground of the default face.
1933 :background the background color, or \"Transparent\".
1934 `default' means use the background of the default face.
1935 :scale a scaling factor for the size of the images
1936 :html-foreground, :html-background, :html-scale
1937 The same numbers for HTML export.
1938 :matchers a list indicating which matchers should be used to
1939 find LaTeX fragments. Valid members of this list are:
1940 \"begin\" find environments
1941 \"$\" find math expressions surrounded by $...$
1942 \"$$\" find math expressions surrounded by $$....$$
1943 \"\\(\" find math expressions surrounded by \\(...\\)
1944 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1945 :group 'org-latex
1946 :type 'plist)
1948 (defcustom org-format-latex-header "\\documentclass{article}
1949 \\usepackage{fullpage} % do not remove
1950 \\usepackage{amssymb}
1951 \\usepackage[usenames]{color}
1952 \\usepackage{amsmath}
1953 \\usepackage{latexsym}
1954 \\usepackage[mathscr]{eucal}
1955 \\pagestyle{empty} % do not remove"
1956 "The document header used for processing LaTeX fragments."
1957 :group 'org-latex
1958 :type 'string)
1961 (defgroup org-font-lock nil
1962 "Font-lock settings for highlighting in Org-mode."
1963 :tag "Org Font Lock"
1964 :group 'org)
1966 (defcustom org-level-color-stars-only nil
1967 "Non-nil means fontify only the stars in each headline.
1968 When nil, the entire headline is fontified.
1969 Changing it requires restart of `font-lock-mode' to become effective
1970 also in regions already fontified."
1971 :group 'org-font-lock
1972 :type 'boolean)
1974 (defcustom org-hide-leading-stars nil
1975 "Non-nil means, hide the first N-1 stars in a headline.
1976 This works by using the face `org-hide' for these stars. This
1977 face is white for a light background, and black for a dark
1978 background. You may have to customize the face `org-hide' to
1979 make this work.
1980 Changing it requires restart of `font-lock-mode' to become effective
1981 also in regions already fontified.
1982 You may also set this on a per-file basis by adding one of the following
1983 lines to the buffer:
1985 #+STARTUP: hidestars
1986 #+STARTUP: showstars"
1987 :group 'org-font-lock
1988 :type 'boolean)
1990 (defcustom org-fontify-done-headline nil
1991 "Non-nil means, change the face of a headline if it is marked DONE.
1992 Normally, only the TODO/DONE keyword indicates the state of a headline.
1993 When this is non-nil, the headline after the keyword is set to the
1994 `org-headline-done' as an additional indication."
1995 :group 'org-font-lock
1996 :type 'boolean)
1998 (defcustom org-fontify-emphasized-text t
1999 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2000 Changing this variable requires a restart of Emacs to take effect."
2001 :group 'org-font-lock
2002 :type 'boolean)
2004 (defcustom org-highlight-latex-fragments-and-specials nil
2005 "Non-nil means, fontify what is treated specially by the exporters."
2006 :group 'org-font-lock
2007 :type 'boolean)
2009 (defcustom org-hide-emphasis-markers nil
2010 "Non-nil mean font-lock should hide the emphasis marker characters."
2011 :group 'org-font-lock
2012 :type 'boolean)
2014 (defvar org-emph-re nil
2015 "Regular expression for matching emphasis.")
2016 (defvar org-verbatim-re nil
2017 "Regular expression for matching verbatim text.")
2018 (defvar org-emphasis-regexp-components) ; defined just below
2019 (defvar org-emphasis-alist) ; defined just below
2020 (defun org-set-emph-re (var val)
2021 "Set variable and compute the emphasis regular expression."
2022 (set var val)
2023 (when (and (boundp 'org-emphasis-alist)
2024 (boundp 'org-emphasis-regexp-components)
2025 org-emphasis-alist org-emphasis-regexp-components)
2026 (let* ((e org-emphasis-regexp-components)
2027 (pre (car e))
2028 (post (nth 1 e))
2029 (border (nth 2 e))
2030 (body (nth 3 e))
2031 (nl (nth 4 e))
2032 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2033 (body1 (concat body "*?"))
2034 (markers (mapconcat 'car org-emphasis-alist ""))
2035 (vmarkers (mapconcat
2036 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2037 org-emphasis-alist "")))
2038 ;; make sure special characters appear at the right position in the class
2039 (if (string-match "\\^" markers)
2040 (setq markers (concat (replace-match "" t t markers) "^")))
2041 (if (string-match "-" markers)
2042 (setq markers (concat (replace-match "" t t markers) "-")))
2043 (if (string-match "\\^" vmarkers)
2044 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2045 (if (string-match "-" vmarkers)
2046 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2047 (if (> nl 0)
2048 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2049 (int-to-string nl) "\\}")))
2050 ;; Make the regexp
2051 (setq org-emph-re
2052 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2053 "\\("
2054 "\\([" markers "]\\)"
2055 "\\("
2056 "[^" border "]\\|"
2057 "[^" border (if (and nil stacked) markers) "]"
2058 body1
2059 "[^" border (if (and nil stacked) markers) "]"
2060 "\\)"
2061 "\\3\\)"
2062 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2063 (setq org-verbatim-re
2064 (concat "\\([" pre "]\\|^\\)"
2065 "\\("
2066 "\\([" vmarkers "]\\)"
2067 "\\("
2068 "[^" border "]\\|"
2069 "[^" border "]"
2070 body1
2071 "[^" border "]"
2072 "\\)"
2073 "\\3\\)"
2074 "\\([" post "]\\|$\\)")))))
2076 (defcustom org-emphasis-regexp-components
2077 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2078 "Components used to build the regular expression for emphasis.
2079 This is a list with 6 entries. Terminology: In an emphasis string
2080 like \" *strong word* \", we call the initial space PREMATCH, the final
2081 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2082 and \"trong wor\" is the body. The different components in this variable
2083 specify what is allowed/forbidden in each part:
2085 pre Chars allowed as prematch. Beginning of line will be allowed too.
2086 post Chars allowed as postmatch. End of line will be allowed too.
2087 border The chars *forbidden* as border characters.
2088 body-regexp A regexp like \".\" to match a body character. Don't use
2089 non-shy groups here, and don't allow newline here.
2090 newline The maximum number of newlines allowed in an emphasis exp.
2092 Use customize to modify this, or restart Emacs after changing it."
2093 :group 'org-font-lock
2094 :set 'org-set-emph-re
2095 :type '(list
2096 (sexp :tag "Allowed chars in pre ")
2097 (sexp :tag "Allowed chars in post ")
2098 (sexp :tag "Forbidden chars in border ")
2099 (sexp :tag "Regexp for body ")
2100 (integer :tag "number of newlines allowed")
2101 (option (boolean :tag "Stacking (DISABLED) "))))
2103 (defcustom org-emphasis-alist
2104 '(("*" bold "<b>" "</b>")
2105 ("/" italic "<i>" "</i>")
2106 ("_" underline "<u>" "</u>")
2107 ("=" org-code "<code>" "</code>" verbatim)
2108 ("~" org-verbatim "" "" verbatim)
2109 ("+" (:strike-through t) "<del>" "</del>")
2111 "Special syntax for emphasized text.
2112 Text starting and ending with a special character will be emphasized, for
2113 example *bold*, _underlined_ and /italic/. This variable sets the marker
2114 characters, the face to be used by font-lock for highlighting in Org-mode
2115 Emacs buffers, and the HTML tags to be used for this.
2116 Use customize to modify this, or restart Emacs after changing it."
2117 :group 'org-font-lock
2118 :set 'org-set-emph-re
2119 :type '(repeat
2120 (list
2121 (string :tag "Marker character")
2122 (choice
2123 (face :tag "Font-lock-face")
2124 (plist :tag "Face property list"))
2125 (string :tag "HTML start tag")
2126 (string :tag "HTML end tag")
2127 (option (const verbatim)))))
2129 ;;; Miscellaneous options
2131 (defgroup org-completion nil
2132 "Completion in Org-mode."
2133 :tag "Org Completion"
2134 :group 'org)
2136 (defcustom org-completion-fallback-command 'hippie-expand
2137 "The expansion command called by \\[org-complete] in normal context.
2138 Normal means, no org-mode-specific context."
2139 :group 'org-completion
2140 :type 'function)
2142 ;;; Functions and variables from ther packages
2143 ;; Declared here to avoid compiler warnings
2145 ;; XEmacs only
2146 (defvar outline-mode-menu-heading)
2147 (defvar outline-mode-menu-show)
2148 (defvar outline-mode-menu-hide)
2149 (defvar zmacs-regions) ; XEmacs regions
2151 ;; Emacs only
2152 (defvar mark-active)
2154 ;; Various packages
2155 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2156 (declare-function calendar-forward-day "cal-move" (arg))
2157 (declare-function calendar-goto-date "cal-move" (date))
2158 (declare-function calendar-goto-today "cal-move" ())
2159 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2160 (defvar calc-embedded-close-formula)
2161 (defvar calc-embedded-open-formula)
2162 (declare-function cdlatex-tab "ext:cdlatex" ())
2163 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2164 (defvar font-lock-unfontify-region-function)
2165 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2166 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2167 (defvar iswitchb-temp-buflist)
2168 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2169 (declare-function org-agenda-skip "org-agenda" ())
2170 (declare-function org-format-agenda-item "org-agenda"
2171 (extra txt &optional category tags dotime noprefix remove-re))
2172 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2173 (declare-function org-agenda-change-all-lines "org-agenda"
2174 (newhead hdmarker &optional fixface))
2175 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2176 (declare-function org-agenda-maybe-redo "org-agenda" ())
2177 (declare-function parse-time-string "parse-time" (string))
2178 (declare-function remember "remember" (&optional initial))
2179 (declare-function remember-buffer-desc "remember" ())
2180 (declare-function remember-finalize "remember" ())
2181 (defvar remember-save-after-remembering)
2182 (defvar remember-data-file)
2183 (defvar remember-register)
2184 (defvar remember-buffer)
2185 (defvar remember-handler-functions)
2186 (defvar remember-annotation-functions)
2187 (defvar texmathp-why)
2188 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2189 (declare-function table--at-cell-p "table" (position &optional object at-column))
2191 (defvar w3m-current-url)
2192 (defvar w3m-current-title)
2194 (defvar org-latex-regexps)
2196 ;;; Autoload and prepare some org modules
2198 ;; Some table stuff that needs to be defined here, because it is used
2199 ;; by the functions setting up org-mode or checking for table context.
2201 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2202 "Detects an org-type or table-type table.")
2203 (defconst org-table-line-regexp "^[ \t]*|"
2204 "Detects an org-type table line.")
2205 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2206 "Detects an org-type table line.")
2207 (defconst org-table-hline-regexp "^[ \t]*|-"
2208 "Detects an org-type table hline.")
2209 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2210 "Detects a table-type table hline.")
2211 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2212 "Searching from within a table (any type) this finds the first line
2213 outside the table.")
2215 ;; Autoload the functions in org-table.el that are needed by functions here.
2217 (eval-and-compile
2218 (org-autoload "org-table"
2219 '(org-table-align org-table-begin org-table-blank-field
2220 org-table-convert org-table-convert-region org-table-copy-down
2221 org-table-copy-region org-table-create
2222 org-table-create-or-convert-from-region
2223 org-table-create-with-table.el org-table-current-dline
2224 org-table-cut-region org-table-delete-column org-table-edit-field
2225 org-table-edit-formulas org-table-end org-table-eval-formula
2226 org-table-export org-table-field-info
2227 org-table-get-stored-formulas org-table-goto-column
2228 org-table-hline-and-move org-table-import org-table-insert-column
2229 org-table-insert-hline org-table-insert-row org-table-iterate
2230 org-table-justify-field-maybe org-table-kill-row
2231 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2232 org-table-move-column org-table-move-column-left
2233 org-table-move-column-right org-table-move-row
2234 org-table-move-row-down org-table-move-row-up
2235 org-table-next-field org-table-next-row org-table-paste-rectangle
2236 org-table-previous-field org-table-recalculate
2237 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2238 org-table-toggle-coordinate-overlays
2239 org-table-toggle-formula-debugger org-table-wrap-region
2240 orgtbl-mode turn-on-orgtbl)))
2242 (defun org-at-table-p (&optional table-type)
2243 "Return t if the cursor is inside an org-type table.
2244 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2245 (if org-enable-table-editor
2246 (save-excursion
2247 (beginning-of-line 1)
2248 (looking-at (if table-type org-table-any-line-regexp
2249 org-table-line-regexp)))
2250 nil))
2251 (defsubst org-table-p () (org-at-table-p))
2253 (defun org-at-table.el-p ()
2254 "Return t if and only if we are at a table.el table."
2255 (and (org-at-table-p 'any)
2256 (save-excursion
2257 (goto-char (org-table-begin 'any))
2258 (looking-at org-table1-hline-regexp))))
2259 (defun org-table-recognize-table.el ()
2260 "If there is a table.el table nearby, recognize it and move into it."
2261 (if org-table-tab-recognizes-table.el
2262 (if (org-at-table.el-p)
2263 (progn
2264 (beginning-of-line 1)
2265 (if (looking-at org-table-dataline-regexp)
2267 (if (looking-at org-table1-hline-regexp)
2268 (progn
2269 (beginning-of-line 2)
2270 (if (looking-at org-table-any-border-regexp)
2271 (beginning-of-line -1)))))
2272 (if (re-search-forward "|" (org-table-end t) t)
2273 (progn
2274 (require 'table)
2275 (if (table--at-cell-p (point))
2277 (message "recognizing table.el table...")
2278 (table-recognize-table)
2279 (message "recognizing table.el table...done")))
2280 (error "This should not happen..."))
2282 nil)
2283 nil))
2285 (defun org-at-table-hline-p ()
2286 "Return t if the cursor is inside a hline in a table."
2287 (if org-enable-table-editor
2288 (save-excursion
2289 (beginning-of-line 1)
2290 (looking-at org-table-hline-regexp))
2291 nil))
2293 (defvar org-table-clean-did-remove-column nil)
2295 (defun org-table-map-tables (function)
2296 "Apply FUNCTION to the start of all tables in the buffer."
2297 (save-excursion
2298 (save-restriction
2299 (widen)
2300 (goto-char (point-min))
2301 (while (re-search-forward org-table-any-line-regexp nil t)
2302 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2303 (beginning-of-line 1)
2304 (if (looking-at org-table-line-regexp)
2305 (save-excursion (funcall function)))
2306 (re-search-forward org-table-any-border-regexp nil 1))))
2307 (message "Mapping tables: done"))
2309 ;; Declare and autoload functions from org-exp.el
2311 (declare-function org-default-export-plist "org-exp")
2312 (declare-function org-infile-export-plist "org-exp")
2313 (declare-function org-get-current-options "org-exp")
2314 (eval-and-compile
2315 (org-autoload "org-exp"
2316 '(org-export org-export-as-ascii org-export-visible
2317 org-insert-export-options-template org-export-as-html-and-open
2318 org-export-as-html-batch org-export-as-html-to-buffer
2319 org-replace-region-by-html org-export-region-as-html
2320 org-export-as-html org-export-icalendar-this-file
2321 org-export-icalendar-all-agenda-files
2322 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2324 ;; Declare and autoload functions from org-exp.el
2326 (eval-and-compile
2327 (org-autoload "org-exp"
2328 '(org-agenda org-agenda-list org-search-view
2329 org-todo-list org-tags-view org-agenda-list-stuck-projects
2330 org-diary org-agenda-to-appt)))
2332 ;; Autoload org-remember
2334 (eval-and-compile
2335 (org-autoload "org-remember"
2336 '(org-remember-insinuate org-remember-annotation
2337 org-remember-apply-template org-remember org-remember-handler)))
2339 ;; Autoload org-clock.el
2341 (defvar org-clock-marker (make-marker)
2342 "Marker recording the last clock-in.")
2344 (eval-and-compile
2345 (org-autoload
2346 "org-clock"
2347 '(org-clock-in org-clock-out org-clock-cancel
2348 org-clock-goto org-clock-sum org-clock-display
2349 org-remove-clock-overlays org-clock-report
2350 org-clocktable-shift org-dblock-write:clocktable
2351 org-get-clocktable)))
2353 (defun org-clock-update-time-maybe ()
2354 "If this is a CLOCK line, update it and return t.
2355 Otherwise, return nil."
2356 (interactive)
2357 (save-excursion
2358 (beginning-of-line 1)
2359 (skip-chars-forward " \t")
2360 (when (looking-at org-clock-string)
2361 (let ((re (concat "[ \t]*" org-clock-string
2362 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2363 "\\([ \t]*=>.*\\)?"))
2364 ts te h m s)
2365 (if (not (looking-at re))
2367 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2368 (end-of-line 1)
2369 (setq ts (match-string 1)
2370 te (match-string 2))
2371 (setq s (- (time-to-seconds
2372 (apply 'encode-time (org-parse-time-string te)))
2373 (time-to-seconds
2374 (apply 'encode-time (org-parse-time-string ts))))
2375 h (floor (/ s 3600))
2376 s (- s (* 3600 h))
2377 m (floor (/ s 60))
2378 s (- s (* 60 s)))
2379 (insert " => " (format "%2d:%02d" h m))
2380 t)))))
2382 (defun org-check-running-clock ()
2383 "Check if the current buffer contains the running clock.
2384 If yes, offer to stop it and to save the buffer with the changes."
2385 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2386 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2387 (buffer-name))))
2388 (org-clock-out)
2389 (when (y-or-n-p "Save changed buffer?")
2390 (save-buffer))))
2392 (defun org-clocktable-try-shift (dir n)
2393 "Check if this line starts a clock table, if yes, shift the time block."
2394 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2395 (org-clocktable-shift dir n)))
2397 ;; Autoload archiving code
2398 ;; The stuff that is needed for cycling and tags has to be defined here.
2400 (defgroup org-archive nil
2401 "Options concerning archiving in Org-mode."
2402 :tag "Org Archive"
2403 :group 'org-structure)
2405 (defcustom org-archive-tag "ARCHIVE"
2406 "The tag that marks a subtree as archived.
2407 An archived subtree does not open during visibility cycling, and does
2408 not contribute to the agenda listings.
2409 After changing this, font-lock must be restarted in the relevant buffers to
2410 get the proper fontification."
2411 :group 'org-archive
2412 :group 'org-keywords
2413 :type 'string)
2415 (defcustom org-agenda-skip-archived-trees t
2416 "Non-nil means, the agenda will skip any items located in archived trees.
2417 An archived tree is a tree marked with the tag ARCHIVE."
2418 :group 'org-archive
2419 :group 'org-agenda-skip
2420 :type 'boolean)
2422 (defcustom org-cycle-open-archived-trees nil
2423 "Non-nil means, `org-cycle' will open archived trees.
2424 An archived tree is a tree marked with the tag ARCHIVE.
2425 When nil, archived trees will stay folded. You can still open them with
2426 normal outline commands like `show-all', but not with the cycling commands."
2427 :group 'org-archive
2428 :group 'org-cycle
2429 :type 'boolean)
2431 (defcustom org-sparse-tree-open-archived-trees nil
2432 "Non-nil means sparse tree construction shows matches in archived trees.
2433 When nil, matches in these trees are highlighted, but the trees are kept in
2434 collapsed state."
2435 :group 'org-archive
2436 :group 'org-sparse-trees
2437 :type 'boolean)
2439 (defun org-cycle-hide-archived-subtrees (state)
2440 "Re-hide all archived subtrees after a visibility state change."
2441 (when (and (not org-cycle-open-archived-trees)
2442 (not (memq state '(overview folded))))
2443 (save-excursion
2444 (let* ((globalp (memq state '(contents all)))
2445 (beg (if globalp (point-min) (point)))
2446 (end (if globalp (point-max) (org-end-of-subtree t))))
2447 (org-hide-archived-subtrees beg end)
2448 (goto-char beg)
2449 (if (looking-at (concat ".*:" org-archive-tag ":"))
2450 (message "%s" (substitute-command-keys
2451 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2453 (defun org-force-cycle-archived ()
2454 "Cycle subtree even if it is archived."
2455 (interactive)
2456 (setq this-command 'org-cycle)
2457 (let ((org-cycle-open-archived-trees t))
2458 (call-interactively 'org-cycle)))
2460 (defun org-hide-archived-subtrees (beg end)
2461 "Re-hide all archived subtrees after a visibility state change."
2462 (save-excursion
2463 (let* ((re (concat ":" org-archive-tag ":")))
2464 (goto-char beg)
2465 (while (re-search-forward re end t)
2466 (and (org-on-heading-p) (hide-subtree))
2467 (org-end-of-subtree t)))))
2469 (org-autoload "org-archive"
2470 '(org-archive-subtree org-archive-to-attic-sibling org-toggle-archive-tag))
2472 ;; Autoload Column View Code
2474 (declare-function org-columns-number-to-string "org-colview")
2475 (declare-function org-columns-get-format-and-top-level "org-colview")
2476 (declare-function org-columns-compute "org-colview")
2478 (org-autoload "org-colview"
2479 '(org-columns-number-to-string org-columns-get-format-and-top-level
2480 org-columns-compute org-agenda-columns org-columns-remove-overlays
2481 org-columns org-insert-columns-dblock))
2483 ;;; Variables for pre-computed regular expressions, all buffer local
2485 (defvar org-drawer-regexp nil
2486 "Matches first line of a hidden block.")
2487 (make-variable-buffer-local 'org-drawer-regexp)
2488 (defvar org-todo-regexp nil
2489 "Matches any of the TODO state keywords.")
2490 (make-variable-buffer-local 'org-todo-regexp)
2491 (defvar org-not-done-regexp nil
2492 "Matches any of the TODO state keywords except the last one.")
2493 (make-variable-buffer-local 'org-not-done-regexp)
2494 (defvar org-todo-line-regexp nil
2495 "Matches a headline and puts TODO state into group 2 if present.")
2496 (make-variable-buffer-local 'org-todo-line-regexp)
2497 (defvar org-complex-heading-regexp nil
2498 "Matches a headline and puts everything into groups:
2499 group 1: the stars
2500 group 2: The todo keyword, maybe
2501 group 3: Priority cookie
2502 group 4: True headline
2503 group 5: Tags")
2504 (make-variable-buffer-local 'org-complex-heading-regexp)
2505 (defvar org-todo-line-tags-regexp nil
2506 "Matches a headline and puts TODO state into group 2 if present.
2507 Also put tags into group 4 if tags are present.")
2508 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2509 (defvar org-nl-done-regexp nil
2510 "Matches newline followed by a headline with the DONE keyword.")
2511 (make-variable-buffer-local 'org-nl-done-regexp)
2512 (defvar org-looking-at-done-regexp nil
2513 "Matches the DONE keyword a point.")
2514 (make-variable-buffer-local 'org-looking-at-done-regexp)
2515 (defvar org-ds-keyword-length 12
2516 "Maximum length of the Deadline and SCHEDULED keywords.")
2517 (make-variable-buffer-local 'org-ds-keyword-length)
2518 (defvar org-deadline-regexp nil
2519 "Matches the DEADLINE keyword.")
2520 (make-variable-buffer-local 'org-deadline-regexp)
2521 (defvar org-deadline-time-regexp nil
2522 "Matches the DEADLINE keyword together with a time stamp.")
2523 (make-variable-buffer-local 'org-deadline-time-regexp)
2524 (defvar org-deadline-line-regexp nil
2525 "Matches the DEADLINE keyword and the rest of the line.")
2526 (make-variable-buffer-local 'org-deadline-line-regexp)
2527 (defvar org-scheduled-regexp nil
2528 "Matches the SCHEDULED keyword.")
2529 (make-variable-buffer-local 'org-scheduled-regexp)
2530 (defvar org-scheduled-time-regexp nil
2531 "Matches the SCHEDULED keyword together with a time stamp.")
2532 (make-variable-buffer-local 'org-scheduled-time-regexp)
2533 (defvar org-closed-time-regexp nil
2534 "Matches the CLOSED keyword together with a time stamp.")
2535 (make-variable-buffer-local 'org-closed-time-regexp)
2537 (defvar org-keyword-time-regexp nil
2538 "Matches any of the 4 keywords, together with the time stamp.")
2539 (make-variable-buffer-local 'org-keyword-time-regexp)
2540 (defvar org-keyword-time-not-clock-regexp nil
2541 "Matches any of the 3 keywords, together with the time stamp.")
2542 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2543 (defvar org-maybe-keyword-time-regexp nil
2544 "Matches a timestamp, possibly preceeded by a keyword.")
2545 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2546 (defvar org-planning-or-clock-line-re nil
2547 "Matches a line with planning or clock info.")
2548 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2550 (defconst org-plain-time-of-day-regexp
2551 (concat
2552 "\\(\\<[012]?[0-9]"
2553 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2554 "\\(--?"
2555 "\\(\\<[012]?[0-9]"
2556 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2557 "\\)?")
2558 "Regular expression to match a plain time or time range.
2559 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2560 groups carry important information:
2561 0 the full match
2562 1 the first time, range or not
2563 8 the second time, if it is a range.")
2565 (defconst org-plain-time-extension-regexp
2566 (concat
2567 "\\(\\<[012]?[0-9]"
2568 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2569 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2570 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2571 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2572 groups carry important information:
2573 0 the full match
2574 7 hours of duration
2575 9 minutes of duration")
2577 (defconst org-stamp-time-of-day-regexp
2578 (concat
2579 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2580 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2581 "\\(--?"
2582 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2583 "Regular expression to match a timestamp time or time range.
2584 After a match, the following groups carry important information:
2585 0 the full match
2586 1 date plus weekday, for backreferencing to make sure both times on same day
2587 2 the first time, range or not
2588 4 the second time, if it is a range.")
2590 (defconst org-startup-options
2591 '(("fold" org-startup-folded t)
2592 ("overview" org-startup-folded t)
2593 ("nofold" org-startup-folded nil)
2594 ("showall" org-startup-folded nil)
2595 ("content" org-startup-folded content)
2596 ("hidestars" org-hide-leading-stars t)
2597 ("showstars" org-hide-leading-stars nil)
2598 ("odd" org-odd-levels-only t)
2599 ("oddeven" org-odd-levels-only nil)
2600 ("align" org-startup-align-all-tables t)
2601 ("noalign" org-startup-align-all-tables nil)
2602 ("customtime" org-display-custom-times t)
2603 ("logdone" org-log-done time)
2604 ("lognotedone" org-log-done note)
2605 ("nologdone" org-log-done nil)
2606 ("lognoteclock-out" org-log-note-clock-out t)
2607 ("nolognoteclock-out" org-log-note-clock-out nil)
2608 ("logrepeat" org-log-repeat state)
2609 ("lognoterepeat" org-log-repeat note)
2610 ("nologrepeat" org-log-repeat nil)
2611 ("constcgs" constants-unit-system cgs)
2612 ("constSI" constants-unit-system SI))
2613 "Variable associated with STARTUP options for org-mode.
2614 Each element is a list of three items: The startup options as written
2615 in the #+STARTUP line, the corresponding variable, and the value to
2616 set this variable to if the option is found. An optional forth element PUSH
2617 means to push this value onto the list in the variable.")
2619 (defun org-set-regexps-and-options ()
2620 "Precompute regular expressions for current buffer."
2621 (when (org-mode-p)
2622 (org-set-local 'org-todo-kwd-alist nil)
2623 (org-set-local 'org-todo-key-alist nil)
2624 (org-set-local 'org-todo-key-trigger nil)
2625 (org-set-local 'org-todo-keywords-1 nil)
2626 (org-set-local 'org-done-keywords nil)
2627 (org-set-local 'org-todo-heads nil)
2628 (org-set-local 'org-todo-sets nil)
2629 (org-set-local 'org-todo-log-states nil)
2630 (let ((re (org-make-options-regexp
2631 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2632 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2633 "CONSTANTS" "PROPERTY" "DRAWERS")))
2634 (splitre "[ \t]+")
2635 kwds kws0 kwsa key log value cat arch tags const links hw dws
2636 tail sep kws1 prio props drawers)
2637 (save-excursion
2638 (save-restriction
2639 (widen)
2640 (goto-char (point-min))
2641 (while (re-search-forward re nil t)
2642 (setq key (match-string 1) value (org-match-string-no-properties 2))
2643 (cond
2644 ((equal key "CATEGORY")
2645 (if (string-match "[ \t]+$" value)
2646 (setq value (replace-match "" t t value)))
2647 (setq cat value))
2648 ((member key '("SEQ_TODO" "TODO"))
2649 (push (cons 'sequence (org-split-string value splitre)) kwds))
2650 ((equal key "TYP_TODO")
2651 (push (cons 'type (org-split-string value splitre)) kwds))
2652 ((equal key "TAGS")
2653 (setq tags (append tags (org-split-string value splitre))))
2654 ((equal key "COLUMNS")
2655 (org-set-local 'org-columns-default-format value))
2656 ((equal key "LINK")
2657 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2658 (push (cons (match-string 1 value)
2659 (org-trim (match-string 2 value)))
2660 links)))
2661 ((equal key "PRIORITIES")
2662 (setq prio (org-split-string value " +")))
2663 ((equal key "PROPERTY")
2664 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2665 (push (cons (match-string 1 value) (match-string 2 value))
2666 props)))
2667 ((equal key "DRAWERS")
2668 (setq drawers (org-split-string value splitre)))
2669 ((equal key "CONSTANTS")
2670 (setq const (append const (org-split-string value splitre))))
2671 ((equal key "STARTUP")
2672 (let ((opts (org-split-string value splitre))
2673 l var val)
2674 (while (setq l (pop opts))
2675 (when (setq l (assoc l org-startup-options))
2676 (setq var (nth 1 l) val (nth 2 l))
2677 (if (not (nth 3 l))
2678 (set (make-local-variable var) val)
2679 (if (not (listp (symbol-value var)))
2680 (set (make-local-variable var) nil))
2681 (set (make-local-variable var) (symbol-value var))
2682 (add-to-list var val))))))
2683 ((equal key "ARCHIVE")
2684 (string-match " *$" value)
2685 (setq arch (replace-match "" t t value))
2686 (remove-text-properties 0 (length arch)
2687 '(face t fontified t) arch)))
2689 (when cat
2690 (org-set-local 'org-category (intern cat))
2691 (push (cons "CATEGORY" cat) props))
2692 (when prio
2693 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2694 (setq prio (mapcar 'string-to-char prio))
2695 (org-set-local 'org-highest-priority (nth 0 prio))
2696 (org-set-local 'org-lowest-priority (nth 1 prio))
2697 (org-set-local 'org-default-priority (nth 2 prio)))
2698 (and props (org-set-local 'org-local-properties (nreverse props)))
2699 (and drawers (org-set-local 'org-drawers drawers))
2700 (and arch (org-set-local 'org-archive-location arch))
2701 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2702 ;; Process the TODO keywords
2703 (unless kwds
2704 ;; Use the global values as if they had been given locally.
2705 (setq kwds (default-value 'org-todo-keywords))
2706 (if (stringp (car kwds))
2707 (setq kwds (list (cons org-todo-interpretation
2708 (default-value 'org-todo-keywords)))))
2709 (setq kwds (reverse kwds)))
2710 (setq kwds (nreverse kwds))
2711 (let (inter kws kw)
2712 (while (setq kws (pop kwds))
2713 (setq inter (pop kws) sep (member "|" kws)
2714 kws0 (delete "|" (copy-sequence kws))
2715 kwsa nil
2716 kws1 (mapcar
2717 (lambda (x)
2718 ;; 1 2
2719 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2720 (progn
2721 (setq kw (match-string 1 x)
2722 key (and (match-end 2) (match-string 2 x))
2723 log (org-extract-log-state-settings x))
2724 (push (cons kw (and key (string-to-char key))) kwsa)
2725 (and log (push log org-todo-log-states))
2727 (error "Invalid TODO keyword %s" x)))
2728 kws0)
2729 kwsa (if kwsa (append '((:startgroup))
2730 (nreverse kwsa)
2731 '((:endgroup))))
2732 hw (car kws1)
2733 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2734 tail (list inter hw (car dws) (org-last dws)))
2735 (add-to-list 'org-todo-heads hw 'append)
2736 (push kws1 org-todo-sets)
2737 (setq org-done-keywords (append org-done-keywords dws nil))
2738 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2739 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2740 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2741 (setq org-todo-sets (nreverse org-todo-sets)
2742 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2743 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2744 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2745 ;; Process the constants
2746 (when const
2747 (let (e cst)
2748 (while (setq e (pop const))
2749 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2750 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2751 (setq org-table-formula-constants-local cst)))
2753 ;; Process the tags.
2754 (when tags
2755 (let (e tgs)
2756 (while (setq e (pop tags))
2757 (cond
2758 ((equal e "{") (push '(:startgroup) tgs))
2759 ((equal e "}") (push '(:endgroup) tgs))
2760 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2761 (push (cons (match-string 1 e)
2762 (string-to-char (match-string 2 e)))
2763 tgs))
2764 (t (push (list e) tgs))))
2765 (org-set-local 'org-tag-alist nil)
2766 (while (setq e (pop tgs))
2767 (or (and (stringp (car e))
2768 (assoc (car e) org-tag-alist))
2769 (push e org-tag-alist))))))
2771 ;; Compute the regular expressions and other local variables
2772 (if (not org-done-keywords)
2773 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2774 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2775 (length org-scheduled-string)))
2776 org-drawer-regexp
2777 (concat "^[ \t]*:\\("
2778 (mapconcat 'regexp-quote org-drawers "\\|")
2779 "\\):[ \t]*$")
2780 org-not-done-keywords
2781 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2782 org-todo-regexp
2783 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2784 "\\|") "\\)\\>")
2785 org-not-done-regexp
2786 (concat "\\<\\("
2787 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2788 "\\)\\>")
2789 org-todo-line-regexp
2790 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2791 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2792 "\\)\\>\\)?[ \t]*\\(.*\\)")
2793 org-complex-heading-regexp
2794 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2795 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2796 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2797 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2798 org-nl-done-regexp
2799 (concat "\n\\*+[ \t]+"
2800 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2801 "\\)" "\\>")
2802 org-todo-line-tags-regexp
2803 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2804 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2805 (org-re
2806 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2807 org-looking-at-done-regexp
2808 (concat "^" "\\(?:"
2809 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2810 "\\>")
2811 org-deadline-regexp (concat "\\<" org-deadline-string)
2812 org-deadline-time-regexp
2813 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2814 org-deadline-line-regexp
2815 (concat "\\<\\(" org-deadline-string "\\).*")
2816 org-scheduled-regexp
2817 (concat "\\<" org-scheduled-string)
2818 org-scheduled-time-regexp
2819 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2820 org-closed-time-regexp
2821 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2822 org-keyword-time-regexp
2823 (concat "\\<\\(" org-scheduled-string
2824 "\\|" org-deadline-string
2825 "\\|" org-closed-string
2826 "\\|" org-clock-string "\\)"
2827 " *[[<]\\([^]>]+\\)[]>]")
2828 org-keyword-time-not-clock-regexp
2829 (concat "\\<\\(" org-scheduled-string
2830 "\\|" org-deadline-string
2831 "\\|" org-closed-string
2832 "\\)"
2833 " *[[<]\\([^]>]+\\)[]>]")
2834 org-maybe-keyword-time-regexp
2835 (concat "\\(\\<\\(" org-scheduled-string
2836 "\\|" org-deadline-string
2837 "\\|" org-closed-string
2838 "\\|" org-clock-string "\\)\\)?"
2839 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2840 org-planning-or-clock-line-re
2841 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2842 "\\|" org-deadline-string
2843 "\\|" org-closed-string "\\|" org-clock-string
2844 "\\)\\>\\)")
2846 (org-compute-latex-and-specials-regexp)
2847 (org-set-font-lock-defaults)))
2849 (defun org-extract-log-state-settings (x)
2850 "Extract the log state setting from a TODO keyword string.
2851 This will extract info from a string like \"WAIT(w@/!)\"."
2852 (let (kw key log1 log2)
2853 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2854 (setq kw (match-string 1 x)
2855 key (and (match-end 2) (match-string 2 x))
2856 log1 (and (match-end 3) (match-string 3 x))
2857 log2 (and (match-end 4) (match-string 4 x)))
2858 (and (or log1 log2)
2859 (list kw
2860 (and log1 (if (equal log1 "!") 'time 'note))
2861 (and log2 (if (equal log2 "!") 'time 'note)))))))
2863 (defun org-remove-keyword-keys (list)
2864 "Remove a pair of parenthesis at the end of each string in LIST."
2865 (mapcar (lambda (x)
2866 (if (string-match "(.*)$" x)
2867 (substring x 0 (match-beginning 0))
2869 list))
2871 ;; FIXME: this could be done much better, using second characters etc.
2872 (defun org-assign-fast-keys (alist)
2873 "Assign fast keys to a keyword-key alist.
2874 Respect keys that are already there."
2875 (let (new e k c c1 c2 (char ?a))
2876 (while (setq e (pop alist))
2877 (cond
2878 ((equal e '(:startgroup)) (push e new))
2879 ((equal e '(:endgroup)) (push e new))
2881 (setq k (car e) c2 nil)
2882 (if (cdr e)
2883 (setq c (cdr e))
2884 ;; automatically assign a character.
2885 (setq c1 (string-to-char
2886 (downcase (substring
2887 k (if (= (string-to-char k) ?@) 1 0)))))
2888 (if (or (rassoc c1 new) (rassoc c1 alist))
2889 (while (or (rassoc char new) (rassoc char alist))
2890 (setq char (1+ char)))
2891 (setq c2 c1))
2892 (setq c (or c2 char)))
2893 (push (cons k c) new))))
2894 (nreverse new)))
2896 ;;; Some variables used in various places
2898 (defvar org-window-configuration nil
2899 "Used in various places to store a window configuration.")
2900 (defvar org-finish-function nil
2901 "Function to be called when `C-c C-c' is used.
2902 This is for getting out of special buffers like remember.")
2905 ;; FIXME: Occasionally check by commenting these, to make sure
2906 ;; no other functions uses these, forgetting to let-bind them.
2907 (defvar entry)
2908 (defvar state)
2909 (defvar last-state)
2910 (defvar date)
2911 (defvar description)
2913 ;; Defined somewhere in this file, but used before definition.
2914 (defvar org-html-entities)
2915 (defvar org-struct-menu)
2916 (defvar org-org-menu)
2917 (defvar org-tbl-menu)
2918 (defvar org-agenda-keymap)
2920 ;;;; Define the Org-mode
2922 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2923 (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."))
2926 ;; We use a before-change function to check if a table might need
2927 ;; an update.
2928 (defvar org-table-may-need-update t
2929 "Indicates that a table might need an update.
2930 This variable is set by `org-before-change-function'.
2931 `org-table-align' sets it back to nil.")
2932 (defun org-before-change-function (beg end)
2933 "Every change indicates that a table might need an update."
2934 (setq org-table-may-need-update t))
2935 (defvar org-mode-map)
2936 (defvar org-mode-hook nil)
2937 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2938 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2939 (defvar org-table-buffer-is-an nil)
2940 (defconst org-outline-regexp "\\*+ ")
2942 ;;;###autoload
2943 (define-derived-mode org-mode outline-mode "Org"
2944 "Outline-based notes management and organizer, alias
2945 \"Carsten's outline-mode for keeping track of everything.\"
2947 Org-mode develops organizational tasks around a NOTES file which
2948 contains information about projects as plain text. Org-mode is
2949 implemented on top of outline-mode, which is ideal to keep the content
2950 of large files well structured. It supports ToDo items, deadlines and
2951 time stamps, which magically appear in the diary listing of the Emacs
2952 calendar. Tables are easily created with a built-in table editor.
2953 Plain text URL-like links connect to websites, emails (VM), Usenet
2954 messages (Gnus), BBDB entries, and any files related to the project.
2955 For printing and sharing of notes, an Org-mode file (or a part of it)
2956 can be exported as a structured ASCII or HTML file.
2958 The following commands are available:
2960 \\{org-mode-map}"
2962 ;; Get rid of Outline menus, they are not needed
2963 ;; Need to do this here because define-derived-mode sets up
2964 ;; the keymap so late. Still, it is a waste to call this each time
2965 ;; we switch another buffer into org-mode.
2966 (if (featurep 'xemacs)
2967 (when (boundp 'outline-mode-menu-heading)
2968 ;; Assume this is Greg's port, it used easymenu
2969 (easy-menu-remove outline-mode-menu-heading)
2970 (easy-menu-remove outline-mode-menu-show)
2971 (easy-menu-remove outline-mode-menu-hide))
2972 (define-key org-mode-map [menu-bar headings] 'undefined)
2973 (define-key org-mode-map [menu-bar hide] 'undefined)
2974 (define-key org-mode-map [menu-bar show] 'undefined))
2976 (org-load-modules-maybe)
2977 (easy-menu-add org-org-menu)
2978 (easy-menu-add org-tbl-menu)
2979 (org-install-agenda-files-menu)
2980 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2981 (org-add-to-invisibility-spec '(org-cwidth))
2982 (when (featurep 'xemacs)
2983 (org-set-local 'line-move-ignore-invisible t))
2984 (org-set-local 'outline-regexp org-outline-regexp)
2985 (org-set-local 'outline-level 'org-outline-level)
2986 (when (and org-ellipsis
2987 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
2988 (fboundp 'make-glyph-code))
2989 (unless org-display-table
2990 (setq org-display-table (make-display-table)))
2991 (set-display-table-slot
2992 org-display-table 4
2993 (vconcat (mapcar
2994 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
2995 org-ellipsis)))
2996 (if (stringp org-ellipsis) org-ellipsis "..."))))
2997 (setq buffer-display-table org-display-table))
2998 (org-set-regexps-and-options)
2999 ;; Calc embedded
3000 (org-set-local 'calc-embedded-open-mode "# ")
3001 (modify-syntax-entry ?# "<")
3002 (modify-syntax-entry ?@ "w")
3003 (if org-startup-truncated (setq truncate-lines t))
3004 (org-set-local 'font-lock-unfontify-region-function
3005 'org-unfontify-region)
3006 ;; Activate before-change-function
3007 (org-set-local 'org-table-may-need-update t)
3008 (org-add-hook 'before-change-functions 'org-before-change-function nil
3009 'local)
3010 ;; Check for running clock before killing a buffer
3011 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3012 ;; Paragraphs and auto-filling
3013 (org-set-autofill-regexps)
3014 (setq indent-line-function 'org-indent-line-function)
3015 (org-update-radio-target-regexp)
3017 ;; Comment characters
3018 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3019 (org-set-local 'comment-padding " ")
3021 ;; Align options lines
3022 (org-set-local
3023 'align-mode-rules-list
3024 '((org-in-buffer-settings
3025 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3026 (modes . '(org-mode)))))
3028 ;; Imenu
3029 (org-set-local 'imenu-create-index-function
3030 'org-imenu-get-tree)
3032 ;; Make isearch reveal context
3033 (if (or (featurep 'xemacs)
3034 (not (boundp 'outline-isearch-open-invisible-function)))
3035 ;; Emacs 21 and XEmacs make use of the hook
3036 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3037 ;; Emacs 22 deals with this through a special variable
3038 (org-set-local 'outline-isearch-open-invisible-function
3039 (lambda (&rest ignore) (org-show-context 'isearch))))
3041 ;; If empty file that did not turn on org-mode automatically, make it to.
3042 (if (and org-insert-mode-line-in-empty-file
3043 (interactive-p)
3044 (= (point-min) (point-max)))
3045 (insert "# -*- mode: org -*-\n\n"))
3047 (unless org-inhibit-startup
3048 (when org-startup-align-all-tables
3049 (let ((bmp (buffer-modified-p)))
3050 (org-table-map-tables 'org-table-align)
3051 (set-buffer-modified-p bmp)))
3052 (org-cycle-hide-drawers 'all)
3053 (cond
3054 ((eq org-startup-folded t)
3055 (org-cycle '(4)))
3056 ((eq org-startup-folded 'content)
3057 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3058 (org-cycle '(4)) (org-cycle '(4)))))))
3060 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3062 (defun org-current-time ()
3063 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3064 (if (> (car org-time-stamp-rounding-minutes) 1)
3065 (let ((r (car org-time-stamp-rounding-minutes))
3066 (time (decode-time)))
3067 (apply 'encode-time
3068 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3069 (nthcdr 2 time))))
3070 (current-time)))
3072 ;;;; Font-Lock stuff, including the activators
3074 (defvar org-mouse-map (make-sparse-keymap))
3075 (org-defkey org-mouse-map
3076 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3077 (org-defkey org-mouse-map
3078 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3079 (when org-mouse-1-follows-link
3080 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3081 (when org-tab-follows-link
3082 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3083 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3084 (when org-return-follows-link
3085 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3086 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3088 (require 'font-lock)
3090 (defconst org-non-link-chars "]\t\n\r<>")
3091 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3092 "shell" "elisp"))
3093 (defvar org-link-re-with-space nil
3094 "Matches a link with spaces, optional angular brackets around it.")
3095 (defvar org-link-re-with-space2 nil
3096 "Matches a link with spaces, optional angular brackets around it.")
3097 (defvar org-angle-link-re nil
3098 "Matches link with angular brackets, spaces are allowed.")
3099 (defvar org-plain-link-re nil
3100 "Matches plain link, without spaces.")
3101 (defvar org-bracket-link-regexp nil
3102 "Matches a link in double brackets.")
3103 (defvar org-bracket-link-analytic-regexp nil
3104 "Regular expression used to analyze links.
3105 Here is what the match groups contain after a match:
3106 1: http:
3107 2: http
3108 3: path
3109 4: [desc]
3110 5: desc")
3111 (defvar org-any-link-re nil
3112 "Regular expression matching any link.")
3114 (defun org-make-link-regexps ()
3115 "Update the link regular expressions.
3116 This should be called after the variable `org-link-types' has changed."
3117 (setq org-link-re-with-space
3118 (concat
3119 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3120 "\\([^" org-non-link-chars " ]"
3121 "[^" org-non-link-chars "]*"
3122 "[^" org-non-link-chars " ]\\)>?")
3123 org-link-re-with-space2
3124 (concat
3125 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3126 "\\([^" org-non-link-chars " ]"
3127 "[^]\t\n\r]*"
3128 "[^" org-non-link-chars " ]\\)>?")
3129 org-angle-link-re
3130 (concat
3131 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3132 "\\([^" org-non-link-chars " ]"
3133 "[^" org-non-link-chars "]*"
3134 "\\)>")
3135 org-plain-link-re
3136 (concat
3137 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3138 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3139 org-bracket-link-regexp
3140 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3141 org-bracket-link-analytic-regexp
3142 (concat
3143 "\\[\\["
3144 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3145 "\\([^]]+\\)"
3146 "\\]"
3147 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3148 "\\]")
3149 org-any-link-re
3150 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3151 org-angle-link-re "\\)\\|\\("
3152 org-plain-link-re "\\)")))
3154 (org-make-link-regexps)
3156 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3157 "Regular expression for fast time stamp matching.")
3158 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3159 "Regular expression for fast time stamp matching.")
3160 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3161 "Regular expression matching time strings for analysis.
3162 This one does not require the space after the date, so it can be used
3163 on a string that terminates immediately after the date.")
3164 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3165 "Regular expression matching time strings for analysis.")
3166 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3167 "Regular expression matching time stamps, with groups.")
3168 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3169 "Regular expression matching time stamps (also [..]), with groups.")
3170 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3171 "Regular expression matching a time stamp range.")
3172 (defconst org-tr-regexp-both
3173 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3174 "Regular expression matching a time stamp range.")
3175 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3176 org-ts-regexp "\\)?")
3177 "Regular expression matching a time stamp or time stamp range.")
3178 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3179 org-ts-regexp-both "\\)?")
3180 "Regular expression matching a time stamp or time stamp range.
3181 The time stamps may be either active or inactive.")
3183 (defvar org-emph-face nil)
3185 (defun org-do-emphasis-faces (limit)
3186 "Run through the buffer and add overlays to links."
3187 (let (rtn)
3188 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3189 (if (not (= (char-after (match-beginning 3))
3190 (char-after (match-beginning 4))))
3191 (progn
3192 (setq rtn t)
3193 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3194 'face
3195 (nth 1 (assoc (match-string 3)
3196 org-emphasis-alist)))
3197 (add-text-properties (match-beginning 2) (match-end 2)
3198 '(font-lock-multiline t))
3199 (when org-hide-emphasis-markers
3200 (add-text-properties (match-end 4) (match-beginning 5)
3201 '(invisible org-link))
3202 (add-text-properties (match-beginning 3) (match-end 3)
3203 '(invisible org-link)))))
3204 (backward-char 1))
3205 rtn))
3207 (defun org-emphasize (&optional char)
3208 "Insert or change an emphasis, i.e. a font like bold or italic.
3209 If there is an active region, change that region to a new emphasis.
3210 If there is no region, just insert the marker characters and position
3211 the cursor between them.
3212 CHAR should be either the marker character, or the first character of the
3213 HTML tag associated with that emphasis. If CHAR is a space, the means
3214 to remove the emphasis of the selected region.
3215 If char is not given (for example in an interactive call) it
3216 will be prompted for."
3217 (interactive)
3218 (let ((eal org-emphasis-alist) e det
3219 (erc org-emphasis-regexp-components)
3220 (prompt "")
3221 (string "") beg end move tag c s)
3222 (if (org-region-active-p)
3223 (setq beg (region-beginning) end (region-end)
3224 string (buffer-substring beg end))
3225 (setq move t))
3227 (while (setq e (pop eal))
3228 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3229 c (aref tag 0))
3230 (push (cons c (string-to-char (car e))) det)
3231 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3232 (substring tag 1)))))
3233 (unless char
3234 (message "%s" (concat "Emphasis marker or tag:" prompt))
3235 (setq char (read-char-exclusive)))
3236 (setq char (or (cdr (assoc char det)) char))
3237 (if (equal char ?\ )
3238 (setq s "" move nil)
3239 (unless (assoc (char-to-string char) org-emphasis-alist)
3240 (error "No such emphasis marker: \"%c\"" char))
3241 (setq s (char-to-string char)))
3242 (while (and (> (length string) 1)
3243 (equal (substring string 0 1) (substring string -1))
3244 (assoc (substring string 0 1) org-emphasis-alist))
3245 (setq string (substring string 1 -1)))
3246 (setq string (concat s string s))
3247 (if beg (delete-region beg end))
3248 (unless (or (bolp)
3249 (string-match (concat "[" (nth 0 erc) "\n]")
3250 (char-to-string (char-before (point)))))
3251 (insert " "))
3252 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3253 (char-to-string (char-after (point))))
3254 (insert " ") (backward-char 1))
3255 (insert string)
3256 (and move (backward-char 1))))
3258 (defconst org-nonsticky-props
3259 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3262 (defun org-activate-plain-links (limit)
3263 "Run through the buffer and add overlays to links."
3264 (catch 'exit
3265 (let (f)
3266 (while (re-search-forward org-plain-link-re limit t)
3267 (setq f (get-text-property (match-beginning 0) 'face))
3268 (if (or (eq f 'org-tag)
3269 (and (listp f) (memq 'org-tag f)))
3271 (add-text-properties (match-beginning 0) (match-end 0)
3272 (list 'mouse-face 'highlight
3273 'rear-nonsticky org-nonsticky-props
3274 'keymap org-mouse-map
3276 (throw 'exit t))))))
3278 (defun org-activate-code (limit)
3279 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3280 (unless (get-text-property (match-beginning 1) 'face)
3281 (remove-text-properties (match-beginning 0) (match-end 0)
3282 '(display t invisible t intangible t))
3283 t)))
3285 (defun org-activate-angle-links (limit)
3286 "Run through the buffer and add overlays to links."
3287 (if (re-search-forward org-angle-link-re limit t)
3288 (progn
3289 (add-text-properties (match-beginning 0) (match-end 0)
3290 (list 'mouse-face 'highlight
3291 'rear-nonsticky org-nonsticky-props
3292 'keymap org-mouse-map
3294 t)))
3296 (defun org-activate-bracket-links (limit)
3297 "Run through the buffer and add overlays to bracketed links."
3298 (if (re-search-forward org-bracket-link-regexp limit t)
3299 (let* ((help (concat "LINK: "
3300 (org-match-string-no-properties 1)))
3301 ;; FIXME: above we should remove the escapes.
3302 ;; but that requires another match, protecting match data,
3303 ;; a lot of overhead for font-lock.
3304 (ip (org-maybe-intangible
3305 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3306 'keymap org-mouse-map 'mouse-face 'highlight
3307 'font-lock-multiline t 'help-echo help)))
3308 (vp (list 'rear-nonsticky org-nonsticky-props
3309 'keymap org-mouse-map 'mouse-face 'highlight
3310 ' font-lock-multiline t 'help-echo help)))
3311 ;; We need to remove the invisible property here. Table narrowing
3312 ;; may have made some of this invisible.
3313 (remove-text-properties (match-beginning 0) (match-end 0)
3314 '(invisible nil))
3315 (if (match-end 3)
3316 (progn
3317 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3318 (add-text-properties (match-beginning 3) (match-end 3) vp)
3319 (add-text-properties (match-end 3) (match-end 0) ip))
3320 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3321 (add-text-properties (match-beginning 1) (match-end 1) vp)
3322 (add-text-properties (match-end 1) (match-end 0) ip))
3323 t)))
3325 (defun org-activate-dates (limit)
3326 "Run through the buffer and add overlays to dates."
3327 (if (re-search-forward org-tsr-regexp-both limit t)
3328 (progn
3329 (add-text-properties (match-beginning 0) (match-end 0)
3330 (list 'mouse-face 'highlight
3331 'rear-nonsticky org-nonsticky-props
3332 'keymap org-mouse-map))
3333 (when org-display-custom-times
3334 (if (match-end 3)
3335 (org-display-custom-time (match-beginning 3) (match-end 3)))
3336 (org-display-custom-time (match-beginning 1) (match-end 1)))
3337 t)))
3339 (defvar org-target-link-regexp nil
3340 "Regular expression matching radio targets in plain text.")
3341 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3342 "Regular expression matching a link target.")
3343 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3344 "Regular expression matching a radio target.")
3345 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3346 "Regular expression matching any target.")
3348 (defun org-activate-target-links (limit)
3349 "Run through the buffer and add overlays to target matches."
3350 (when org-target-link-regexp
3351 (let ((case-fold-search t))
3352 (if (re-search-forward org-target-link-regexp limit t)
3353 (progn
3354 (add-text-properties (match-beginning 0) (match-end 0)
3355 (list 'mouse-face 'highlight
3356 'rear-nonsticky org-nonsticky-props
3357 'keymap org-mouse-map
3358 'help-echo "Radio target link"
3359 'org-linked-text t))
3360 t)))))
3362 (defun org-update-radio-target-regexp ()
3363 "Find all radio targets in this file and update the regular expression."
3364 (interactive)
3365 (when (memq 'radio org-activate-links)
3366 (setq org-target-link-regexp
3367 (org-make-target-link-regexp (org-all-targets 'radio)))
3368 (org-restart-font-lock)))
3370 (defun org-hide-wide-columns (limit)
3371 (let (s e)
3372 (setq s (text-property-any (point) (or limit (point-max))
3373 'org-cwidth t))
3374 (when s
3375 (setq e (next-single-property-change s 'org-cwidth))
3376 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3377 (goto-char e)
3378 t)))
3380 (defvar org-latex-and-specials-regexp nil
3381 "Regular expression for highlighting export special stuff.")
3382 (defvar org-match-substring-regexp)
3383 (defvar org-match-substring-with-braces-regexp)
3384 (defvar org-export-html-special-string-regexps)
3386 (defun org-compute-latex-and-specials-regexp ()
3387 "Compute regular expression for stuff treated specially by exporters."
3388 (if (not org-highlight-latex-fragments-and-specials)
3389 (org-set-local 'org-latex-and-specials-regexp nil)
3390 (require 'org-exp)
3391 (let*
3392 ((matchers (plist-get org-format-latex-options :matchers))
3393 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3394 org-latex-regexps)))
3395 (options (org-combine-plists (org-default-export-plist)
3396 (org-infile-export-plist)))
3397 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3398 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3399 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3400 (org-export-html-expand (plist-get options :expand-quoted-html))
3401 (org-export-with-special-strings (plist-get options :special-strings))
3402 (re-sub
3403 (cond
3404 ((equal org-export-with-sub-superscripts '{})
3405 (list org-match-substring-with-braces-regexp))
3406 (org-export-with-sub-superscripts
3407 (list org-match-substring-regexp))
3408 (t nil)))
3409 (re-latex
3410 (if org-export-with-LaTeX-fragments
3411 (mapcar (lambda (x) (nth 1 x)) latexs)))
3412 (re-macros
3413 (if org-export-with-TeX-macros
3414 (list (concat "\\\\"
3415 (regexp-opt
3416 (append (mapcar 'car org-html-entities)
3417 (if (boundp 'org-latex-entities)
3418 org-latex-entities nil))
3419 'words))) ; FIXME
3421 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3422 (re-special (if org-export-with-special-strings
3423 (mapcar (lambda (x) (car x))
3424 org-export-html-special-string-regexps)))
3425 (re-rest
3426 (delq nil
3427 (list
3428 (if org-export-html-expand "@<[^>\n]+>")
3429 ))))
3430 (org-set-local
3431 'org-latex-and-specials-regexp
3432 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3433 re-rest) "\\|")))))
3435 (defun org-do-latex-and-special-faces (limit)
3436 "Run through the buffer and add overlays to links."
3437 (when org-latex-and-specials-regexp
3438 (let (rtn d)
3439 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3440 limit t))
3441 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3442 'face))
3443 '(org-code org-verbatim underline)))
3444 (progn
3445 (setq rtn t
3446 d (cond ((member (char-after (1+ (match-beginning 0)))
3447 '(?_ ?^)) 1)
3448 (t 0)))
3449 (font-lock-prepend-text-property
3450 (+ d (match-beginning 0)) (match-end 0)
3451 'face 'org-latex-and-export-specials)
3452 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3453 '(font-lock-multiline t)))))
3454 rtn)))
3456 (defun org-restart-font-lock ()
3457 "Restart font-lock-mode, to force refontification."
3458 (when (and (boundp 'font-lock-mode) font-lock-mode)
3459 (font-lock-mode -1)
3460 (font-lock-mode 1)))
3462 (defun org-all-targets (&optional radio)
3463 "Return a list of all targets in this file.
3464 With optional argument RADIO, only find radio targets."
3465 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3466 rtn)
3467 (save-excursion
3468 (goto-char (point-min))
3469 (while (re-search-forward re nil t)
3470 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3471 rtn)))
3473 (defun org-make-target-link-regexp (targets)
3474 "Make regular expression matching all strings in TARGETS.
3475 The regular expression finds the targets also if there is a line break
3476 between words."
3477 (and targets
3478 (concat
3479 "\\<\\("
3480 (mapconcat
3481 (lambda (x)
3482 (while (string-match " +" x)
3483 (setq x (replace-match "\\s-+" t t x)))
3485 targets
3486 "\\|")
3487 "\\)\\>")))
3489 (defun org-activate-tags (limit)
3490 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3491 (progn
3492 (add-text-properties (match-beginning 1) (match-end 1)
3493 (list 'mouse-face 'highlight
3494 'rear-nonsticky org-nonsticky-props
3495 'keymap org-mouse-map))
3496 t)))
3498 (defun org-outline-level ()
3499 (save-excursion
3500 (looking-at outline-regexp)
3501 (if (match-beginning 1)
3502 (+ (org-get-string-indentation (match-string 1)) 1000)
3503 (1- (- (match-end 0) (match-beginning 0))))))
3505 (defvar org-font-lock-keywords nil)
3507 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3508 "Regular expression matching a property line.")
3510 (defun org-set-font-lock-defaults ()
3511 (let* ((em org-fontify-emphasized-text)
3512 (lk org-activate-links)
3513 (org-font-lock-extra-keywords
3514 (list
3515 ;; Headlines
3516 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3517 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3518 ;; Table lines
3519 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3520 (1 'org-table t))
3521 ;; Table internals
3522 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3523 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3524 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3525 ;; Drawers
3526 (list org-drawer-regexp '(0 'org-special-keyword t))
3527 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3528 ;; Properties
3529 (list org-property-re
3530 '(1 'org-special-keyword t)
3531 '(3 'org-property-value t))
3532 (if org-format-transports-properties-p
3533 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3534 ;; Links
3535 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3536 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3537 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3538 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3539 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3540 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3541 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3542 '(org-hide-wide-columns (0 nil append))
3543 ;; TODO lines
3544 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3545 '(1 (org-get-todo-face 1) t))
3546 ;; DONE
3547 (if org-fontify-done-headline
3548 (list (concat "^[*]+ +\\<\\("
3549 (mapconcat 'regexp-quote org-done-keywords "\\|")
3550 "\\)\\(.*\\)")
3551 '(2 'org-headline-done t))
3552 nil)
3553 ;; Priorities
3554 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3555 ;; Special keywords
3556 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3557 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3558 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3559 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3560 ;; Emphasis
3561 (if em
3562 (if (featurep 'xemacs)
3563 '(org-do-emphasis-faces (0 nil append))
3564 '(org-do-emphasis-faces)))
3565 ;; Checkboxes
3566 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3567 2 'bold prepend)
3568 (if org-provide-checkbox-statistics
3569 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3570 (0 (org-get-checkbox-statistics-face) t)))
3571 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3572 '(1 'org-archived prepend))
3573 ;; Specials
3574 '(org-do-latex-and-special-faces)
3575 ;; Code
3576 '(org-activate-code (1 'org-code t))
3577 ;; COMMENT
3578 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3579 "\\|" org-quote-string "\\)\\>")
3580 '(1 'org-special-keyword t))
3581 '("^#.*" (0 'font-lock-comment-face t))
3583 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3584 ;; Now set the full font-lock-keywords
3585 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3586 (org-set-local 'font-lock-defaults
3587 '(org-font-lock-keywords t nil nil backward-paragraph))
3588 (kill-local-variable 'font-lock-keywords) nil))
3590 (defvar org-m nil)
3591 (defvar org-l nil)
3592 (defvar org-f nil)
3593 (defun org-get-level-face (n)
3594 "Get the right face for match N in font-lock matching of healdines."
3595 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3596 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3597 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3598 (cond
3599 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3600 ((eq n 2) org-f)
3601 (t (if org-level-color-stars-only nil org-f))))
3603 (defun org-get-todo-face (kwd)
3604 "Get the right face for a TODO keyword KWD.
3605 If KWD is a number, get the corresponding match group."
3606 (if (numberp kwd) (setq kwd (match-string kwd)))
3607 (or (cdr (assoc kwd org-todo-keyword-faces))
3608 (and (member kwd org-done-keywords) 'org-done)
3609 'org-todo))
3611 (defun org-unfontify-region (beg end &optional maybe_loudly)
3612 "Remove fontification and activation overlays from links."
3613 (font-lock-default-unfontify-region beg end)
3614 (let* ((buffer-undo-list t)
3615 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3616 (inhibit-modification-hooks t)
3617 deactivate-mark buffer-file-name buffer-file-truename)
3618 (remove-text-properties beg end
3619 '(mouse-face t keymap t org-linked-text t
3620 invisible t intangible t))))
3622 ;;;; Visibility cycling, including org-goto and indirect buffer
3624 ;;; Cycling
3626 (defvar org-cycle-global-status nil)
3627 (make-variable-buffer-local 'org-cycle-global-status)
3628 (defvar org-cycle-subtree-status nil)
3629 (make-variable-buffer-local 'org-cycle-subtree-status)
3631 ;;;###autoload
3632 (defun org-cycle (&optional arg)
3633 "Visibility cycling for Org-mode.
3635 - When this function is called with a prefix argument, rotate the entire
3636 buffer through 3 states (global cycling)
3637 1. OVERVIEW: Show only top-level headlines.
3638 2. CONTENTS: Show all headlines of all levels, but no body text.
3639 3. SHOW ALL: Show everything.
3641 - When point is at the beginning of a headline, rotate the subtree started
3642 by this line through 3 different states (local cycling)
3643 1. FOLDED: Only the main headline is shown.
3644 2. CHILDREN: The main headline and the direct children are shown.
3645 From this state, you can move to one of the children
3646 and zoom in further.
3647 3. SUBTREE: Show the entire subtree, including body text.
3649 - When there is a numeric prefix, go up to a heading with level ARG, do
3650 a `show-subtree' and return to the previous cursor position. If ARG
3651 is negative, go up that many levels.
3653 - When point is not at the beginning of a headline, execute
3654 `indent-relative', like TAB normally does. See the option
3655 `org-cycle-emulate-tab' for details.
3657 - Special case: if point is at the beginning of the buffer and there is
3658 no headline in line 1, this function will act as if called with prefix arg.
3659 But only if also the variable `org-cycle-global-at-bob' is t."
3660 (interactive "P")
3661 (org-load-modules-maybe)
3662 (let* ((outline-regexp
3663 (if (and (org-mode-p) org-cycle-include-plain-lists)
3664 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3665 outline-regexp))
3666 (bob-special (and org-cycle-global-at-bob (bobp)
3667 (not (looking-at outline-regexp))))
3668 (org-cycle-hook
3669 (if bob-special
3670 (delq 'org-optimize-window-after-visibility-change
3671 (copy-sequence org-cycle-hook))
3672 org-cycle-hook))
3673 (pos (point)))
3675 (if (or bob-special (equal arg '(4)))
3676 ;; special case: use global cycling
3677 (setq arg t))
3679 (cond
3681 ((org-at-table-p 'any)
3682 ;; Enter the table or move to the next field in the table
3683 (or (org-table-recognize-table.el)
3684 (progn
3685 (if arg (org-table-edit-field t)
3686 (org-table-justify-field-maybe)
3687 (call-interactively 'org-table-next-field)))))
3689 ((eq arg t) ;; Global cycling
3691 (cond
3692 ((and (eq last-command this-command)
3693 (eq org-cycle-global-status 'overview))
3694 ;; We just created the overview - now do table of contents
3695 ;; This can be slow in very large buffers, so indicate action
3696 (message "CONTENTS...")
3697 (org-content)
3698 (message "CONTENTS...done")
3699 (setq org-cycle-global-status 'contents)
3700 (run-hook-with-args 'org-cycle-hook 'contents))
3702 ((and (eq last-command this-command)
3703 (eq org-cycle-global-status 'contents))
3704 ;; We just showed the table of contents - now show everything
3705 (show-all)
3706 (message "SHOW ALL")
3707 (setq org-cycle-global-status 'all)
3708 (run-hook-with-args 'org-cycle-hook 'all))
3711 ;; Default action: go to overview
3712 (org-overview)
3713 (message "OVERVIEW")
3714 (setq org-cycle-global-status 'overview)
3715 (run-hook-with-args 'org-cycle-hook 'overview))))
3717 ((and org-drawers org-drawer-regexp
3718 (save-excursion
3719 (beginning-of-line 1)
3720 (looking-at org-drawer-regexp)))
3721 ;; Toggle block visibility
3722 (org-flag-drawer
3723 (not (get-char-property (match-end 0) 'invisible))))
3725 ((integerp arg)
3726 ;; Show-subtree, ARG levels up from here.
3727 (save-excursion
3728 (org-back-to-heading)
3729 (outline-up-heading (if (< arg 0) (- arg)
3730 (- (funcall outline-level) arg)))
3731 (org-show-subtree)))
3733 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3734 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3735 ;; At a heading: rotate between three different views
3736 (org-back-to-heading)
3737 (let ((goal-column 0) eoh eol eos)
3738 ;; First, some boundaries
3739 (save-excursion
3740 (org-back-to-heading)
3741 (save-excursion
3742 (beginning-of-line 2)
3743 (while (and (not (eobp)) ;; this is like `next-line'
3744 (get-char-property (1- (point)) 'invisible))
3745 (beginning-of-line 2)) (setq eol (point)))
3746 (outline-end-of-heading) (setq eoh (point))
3747 (org-end-of-subtree t)
3748 (unless (eobp)
3749 (skip-chars-forward " \t\n")
3750 (beginning-of-line 1) ; in case this is an item
3752 (setq eos (1- (point))))
3753 ;; Find out what to do next and set `this-command'
3754 (cond
3755 ((= eos eoh)
3756 ;; Nothing is hidden behind this heading
3757 (message "EMPTY ENTRY")
3758 (setq org-cycle-subtree-status nil)
3759 (save-excursion
3760 (goto-char eos)
3761 (outline-next-heading)
3762 (if (org-invisible-p) (org-flag-heading nil))))
3763 ((or (>= eol eos)
3764 (not (string-match "\\S-" (buffer-substring eol eos))))
3765 ;; Entire subtree is hidden in one line: open it
3766 (org-show-entry)
3767 (show-children)
3768 (message "CHILDREN")
3769 (save-excursion
3770 (goto-char eos)
3771 (outline-next-heading)
3772 (if (org-invisible-p) (org-flag-heading nil)))
3773 (setq org-cycle-subtree-status 'children)
3774 (run-hook-with-args 'org-cycle-hook 'children))
3775 ((and (eq last-command this-command)
3776 (eq org-cycle-subtree-status 'children))
3777 ;; We just showed the children, now show everything.
3778 (org-show-subtree)
3779 (message "SUBTREE")
3780 (setq org-cycle-subtree-status 'subtree)
3781 (run-hook-with-args 'org-cycle-hook 'subtree))
3783 ;; Default action: hide the subtree.
3784 (hide-subtree)
3785 (message "FOLDED")
3786 (setq org-cycle-subtree-status 'folded)
3787 (run-hook-with-args 'org-cycle-hook 'folded)))))
3789 ;; TAB emulation
3790 (buffer-read-only (org-back-to-heading))
3792 ((org-try-cdlatex-tab))
3794 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3795 (or (not (bolp))
3796 (not (looking-at outline-regexp))))
3797 (call-interactively (global-key-binding "\t")))
3799 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3800 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3801 (or (and (eq org-cycle-emulate-tab 'white)
3802 (= (match-end 0) (point-at-eol)))
3803 (and (eq org-cycle-emulate-tab 'whitestart)
3804 (>= (match-end 0) pos))))
3806 (eq org-cycle-emulate-tab t))
3807 (call-interactively (global-key-binding "\t")))
3809 (t (save-excursion
3810 (org-back-to-heading)
3811 (org-cycle))))))
3813 ;;;###autoload
3814 (defun org-global-cycle (&optional arg)
3815 "Cycle the global visibility. For details see `org-cycle'."
3816 (interactive "P")
3817 (let ((org-cycle-include-plain-lists
3818 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3819 (if (integerp arg)
3820 (progn
3821 (show-all)
3822 (hide-sublevels arg)
3823 (setq org-cycle-global-status 'contents))
3824 (org-cycle '(4)))))
3826 (defun org-overview ()
3827 "Switch to overview mode, shoing only top-level headlines.
3828 Really, this shows all headlines with level equal or greater than the level
3829 of the first headline in the buffer. This is important, because if the
3830 first headline is not level one, then (hide-sublevels 1) gives confusing
3831 results."
3832 (interactive)
3833 (let ((level (save-excursion
3834 (goto-char (point-min))
3835 (if (re-search-forward (concat "^" outline-regexp) nil t)
3836 (progn
3837 (goto-char (match-beginning 0))
3838 (funcall outline-level))))))
3839 (and level (hide-sublevels level))))
3841 (defun org-content (&optional arg)
3842 "Show all headlines in the buffer, like a table of contents.
3843 With numerical argument N, show content up to level N."
3844 (interactive "P")
3845 (save-excursion
3846 ;; Visit all headings and show their offspring
3847 (and (integerp arg) (org-overview))
3848 (goto-char (point-max))
3849 (catch 'exit
3850 (while (and (progn (condition-case nil
3851 (outline-previous-visible-heading 1)
3852 (error (goto-char (point-min))))
3854 (looking-at outline-regexp))
3855 (if (integerp arg)
3856 (show-children (1- arg))
3857 (show-branches))
3858 (if (bobp) (throw 'exit nil))))))
3861 (defun org-optimize-window-after-visibility-change (state)
3862 "Adjust the window after a change in outline visibility.
3863 This function is the default value of the hook `org-cycle-hook'."
3864 (when (get-buffer-window (current-buffer))
3865 (cond
3866 ; ((eq state 'overview) (org-first-headline-recenter 1))
3867 ; ((eq state 'overview) (org-beginning-of-line))
3868 ((eq state 'content) nil)
3869 ((eq state 'all) nil)
3870 ((eq state 'folded) nil)
3871 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3872 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3874 (defun org-compact-display-after-subtree-move ()
3875 (let (beg end)
3876 (save-excursion
3877 (if (org-up-heading-safe)
3878 (progn
3879 (hide-subtree)
3880 (show-entry)
3881 (show-children)
3882 (org-cycle-show-empty-lines 'children)
3883 (org-cycle-hide-drawers 'children))
3884 (org-overview)))))
3886 (defun org-cycle-show-empty-lines (state)
3887 "Show empty lines above all visible headlines.
3888 The region to be covered depends on STATE when called through
3889 `org-cycle-hook'. Lisp program can use t for STATE to get the
3890 entire buffer covered. Note that an empty line is only shown if there
3891 are at least `org-cycle-separator-lines' empty lines before the headeline."
3892 (when (> org-cycle-separator-lines 0)
3893 (save-excursion
3894 (let* ((n org-cycle-separator-lines)
3895 (re (cond
3896 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3897 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3898 (t (let ((ns (number-to-string (- n 2))))
3899 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3900 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3901 beg end)
3902 (cond
3903 ((memq state '(overview contents t))
3904 (setq beg (point-min) end (point-max)))
3905 ((memq state '(children folded))
3906 (setq beg (point) end (progn (org-end-of-subtree t t)
3907 (beginning-of-line 2)
3908 (point)))))
3909 (when beg
3910 (goto-char beg)
3911 (while (re-search-forward re end t)
3912 (if (not (get-char-property (match-end 1) 'invisible))
3913 (outline-flag-region
3914 (match-beginning 1) (match-end 1) nil)))))))
3915 ;; Never hide empty lines at the end of the file.
3916 (save-excursion
3917 (goto-char (point-max))
3918 (outline-previous-heading)
3919 (outline-end-of-heading)
3920 (if (and (looking-at "[ \t\n]+")
3921 (= (match-end 0) (point-max)))
3922 (outline-flag-region (point) (match-end 0) nil))))
3924 (defun org-cycle-hide-drawers (state)
3925 "Re-hide all drawers after a visibility state change."
3926 (when (and (org-mode-p)
3927 (not (memq state '(overview folded))))
3928 (save-excursion
3929 (let* ((globalp (memq state '(contents all)))
3930 (beg (if globalp (point-min) (point)))
3931 (end (if globalp (point-max) (org-end-of-subtree t))))
3932 (goto-char beg)
3933 (while (re-search-forward org-drawer-regexp end t)
3934 (org-flag-drawer t))))))
3936 (defun org-flag-drawer (flag)
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
3940 (let ((b (match-end 0))
3941 (outline-regexp org-outline-regexp))
3942 (if (re-search-forward
3943 "^[ \t]*:END:"
3944 (save-excursion (outline-next-heading) (point)) t)
3945 (outline-flag-region b (point-at-eol) flag)
3946 (error ":END: line missing"))))))
3950 (defun org-subtree-end-visible-p ()
3951 "Is the end of the current subtree visible?"
3952 (pos-visible-in-window-p
3953 (save-excursion (org-end-of-subtree t) (point))))
3955 (defun org-first-headline-recenter (&optional N)
3956 "Move cursor to the first headline and recenter the headline.
3957 Optional argument N means, put the headline into the Nth line of the window."
3958 (goto-char (point-min))
3959 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3960 (beginning-of-line)
3961 (recenter (prefix-numeric-value N))))
3963 ;;; Org-goto
3965 (defvar org-goto-window-configuration nil)
3966 (defvar org-goto-marker nil)
3967 (defvar org-goto-map
3968 (let ((map (make-sparse-keymap)))
3969 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
3970 (while (setq cmd (pop cmds))
3971 (substitute-key-definition cmd cmd map global-map)))
3972 (suppress-keymap map)
3973 (org-defkey map "\C-m" 'org-goto-ret)
3974 (org-defkey map [(return)] 'org-goto-ret)
3975 (org-defkey map [(left)] 'org-goto-left)
3976 (org-defkey map [(right)] 'org-goto-right)
3977 (org-defkey map [(control ?g)] 'org-goto-quit)
3978 (org-defkey map "\C-i" 'org-cycle)
3979 (org-defkey map [(tab)] 'org-cycle)
3980 (org-defkey map [(down)] 'outline-next-visible-heading)
3981 (org-defkey map [(up)] 'outline-previous-visible-heading)
3982 (if org-goto-auto-isearch
3983 (if (fboundp 'define-key-after)
3984 (define-key-after map [t] 'org-goto-local-auto-isearch)
3985 nil)
3986 (org-defkey map "q" 'org-goto-quit)
3987 (org-defkey map "n" 'outline-next-visible-heading)
3988 (org-defkey map "p" 'outline-previous-visible-heading)
3989 (org-defkey map "f" 'outline-forward-same-level)
3990 (org-defkey map "b" 'outline-backward-same-level)
3991 (org-defkey map "u" 'outline-up-heading))
3992 (org-defkey map "/" 'org-occur)
3993 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
3994 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
3995 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
3996 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
3997 (org-defkey map "\C-c\C-u" 'outline-up-heading)
3998 map))
4000 (defconst org-goto-help
4001 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4002 RET=jump to location [Q]uit and return to previous location
4003 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4005 (defvar org-goto-start-pos) ; dynamically scoped parameter
4007 (defun org-goto (&optional alternative-interface)
4008 "Look up a different location in the current file, keeping current visibility.
4010 When you want look-up or go to a different location in a document, the
4011 fastest way is often to fold the entire buffer and then dive into the tree.
4012 This method has the disadvantage, that the previous location will be folded,
4013 which may not be what you want.
4015 This command works around this by showing a copy of the current buffer
4016 in an indirect buffer, in overview mode. You can dive into the tree in
4017 that copy, use org-occur and incremental search to find a location.
4018 When pressing RET or `Q', the command returns to the original buffer in
4019 which the visibility is still unchanged. After RET is will also jump to
4020 the location selected in the indirect buffer and expose the
4021 the headline hierarchy above."
4022 (interactive "P")
4023 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4024 (org-refile-use-outline-path t)
4025 (interface
4026 (if (not alternative-interface)
4027 org-goto-interface
4028 (if (eq org-goto-interface 'outline)
4029 'outline-path-completion
4030 'outline)))
4031 (org-goto-start-pos (point))
4032 (selected-point
4033 (if (eq interface 'outline)
4034 (car (org-get-location (current-buffer) org-goto-help))
4035 (nth 3 (org-refile-get-location "Goto: ")))))
4036 (if selected-point
4037 (progn
4038 (org-mark-ring-push org-goto-start-pos)
4039 (goto-char selected-point)
4040 (if (or (org-invisible-p) (org-invisible-p2))
4041 (org-show-context 'org-goto)))
4042 (message "Quit"))))
4044 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4045 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4046 (defvar org-goto-local-auto-isearch-map) ; defined below
4048 (defun org-get-location (buf help)
4049 "Let the user select a location in the Org-mode buffer BUF.
4050 This function uses a recursive edit. It returns the selected position
4051 or nil."
4052 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4053 (isearch-hide-immediately nil)
4054 (isearch-search-fun-function
4055 (lambda () 'org-goto-local-search-forward-headings))
4056 (org-goto-selected-point org-goto-exit-command))
4057 (save-excursion
4058 (save-window-excursion
4059 (delete-other-windows)
4060 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4061 (switch-to-buffer
4062 (condition-case nil
4063 (make-indirect-buffer (current-buffer) "*org-goto*")
4064 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4065 (with-output-to-temp-buffer "*Help*"
4066 (princ help))
4067 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4068 (setq buffer-read-only nil)
4069 (let ((org-startup-truncated t)
4070 (org-startup-folded nil)
4071 (org-startup-align-all-tables nil))
4072 (org-mode)
4073 (org-overview))
4074 (setq buffer-read-only t)
4075 (if (and (boundp 'org-goto-start-pos)
4076 (integer-or-marker-p org-goto-start-pos))
4077 (let ((org-show-hierarchy-above t)
4078 (org-show-siblings t)
4079 (org-show-following-heading t))
4080 (goto-char org-goto-start-pos)
4081 (and (org-invisible-p) (org-show-context)))
4082 (goto-char (point-min)))
4083 (org-beginning-of-line)
4084 (message "Select location and press RET")
4085 (use-local-map org-goto-map)
4086 (recursive-edit)
4088 (kill-buffer "*org-goto*")
4089 (cons org-goto-selected-point org-goto-exit-command)))
4091 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4092 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4093 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4094 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4096 (defun org-goto-local-search-forward-headings (string bound noerror)
4097 "Search and make sure that anu matches are in headlines."
4098 (catch 'return
4099 (while (search-forward string bound noerror)
4100 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4101 (and (member :headline context)
4102 (not (member :tags context))))
4103 (throw 'return (point))))))
4105 (defun org-goto-local-auto-isearch ()
4106 "Start isearch."
4107 (interactive)
4108 (goto-char (point-min))
4109 (let ((keys (this-command-keys)))
4110 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4111 (isearch-mode t)
4112 (isearch-process-search-char (string-to-char keys)))))
4114 (defun org-goto-ret (&optional arg)
4115 "Finish `org-goto' by going to the new location."
4116 (interactive "P")
4117 (setq org-goto-selected-point (point)
4118 org-goto-exit-command 'return)
4119 (throw 'exit nil))
4121 (defun org-goto-left ()
4122 "Finish `org-goto' by going to the new location."
4123 (interactive)
4124 (if (org-on-heading-p)
4125 (progn
4126 (beginning-of-line 1)
4127 (setq org-goto-selected-point (point)
4128 org-goto-exit-command 'left)
4129 (throw 'exit nil))
4130 (error "Not on a heading")))
4132 (defun org-goto-right ()
4133 "Finish `org-goto' by going to the new location."
4134 (interactive)
4135 (if (org-on-heading-p)
4136 (progn
4137 (setq org-goto-selected-point (point)
4138 org-goto-exit-command 'right)
4139 (throw 'exit nil))
4140 (error "Not on a heading")))
4142 (defun org-goto-quit ()
4143 "Finish `org-goto' without cursor motion."
4144 (interactive)
4145 (setq org-goto-selected-point nil)
4146 (setq org-goto-exit-command 'quit)
4147 (throw 'exit nil))
4149 ;;; Indirect buffer display of subtrees
4151 (defvar org-indirect-dedicated-frame nil
4152 "This is the frame being used for indirect tree display.")
4153 (defvar org-last-indirect-buffer nil)
4155 (defun org-tree-to-indirect-buffer (&optional arg)
4156 "Create indirect buffer and narrow it to current subtree.
4157 With numerical prefix ARG, go up to this level and then take that tree.
4158 If ARG is negative, go up that many levels.
4159 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4160 indirect buffer previously made with this command, to avoid proliferation of
4161 indirect buffers. However, when you call the command with a `C-u' prefix, or
4162 when `org-indirect-buffer-display' is `new-frame', the last buffer
4163 is kept so that you can work with several indirect buffers at the same time.
4164 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4165 requests that a new frame be made for the new buffer, so that the dedicated
4166 frame is not changed."
4167 (interactive "P")
4168 (let ((cbuf (current-buffer))
4169 (cwin (selected-window))
4170 (pos (point))
4171 beg end level heading ibuf)
4172 (save-excursion
4173 (org-back-to-heading t)
4174 (when (numberp arg)
4175 (setq level (org-outline-level))
4176 (if (< arg 0) (setq arg (+ level arg)))
4177 (while (> (setq level (org-outline-level)) arg)
4178 (outline-up-heading 1 t)))
4179 (setq beg (point)
4180 heading (org-get-heading))
4181 (org-end-of-subtree t) (setq end (point)))
4182 (if (and (buffer-live-p org-last-indirect-buffer)
4183 (not (eq org-indirect-buffer-display 'new-frame))
4184 (not arg))
4185 (kill-buffer org-last-indirect-buffer))
4186 (setq ibuf (org-get-indirect-buffer cbuf)
4187 org-last-indirect-buffer ibuf)
4188 (cond
4189 ((or (eq org-indirect-buffer-display 'new-frame)
4190 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4191 (select-frame (make-frame))
4192 (delete-other-windows)
4193 (switch-to-buffer ibuf)
4194 (org-set-frame-title heading))
4195 ((eq org-indirect-buffer-display 'dedicated-frame)
4196 (raise-frame
4197 (select-frame (or (and org-indirect-dedicated-frame
4198 (frame-live-p org-indirect-dedicated-frame)
4199 org-indirect-dedicated-frame)
4200 (setq org-indirect-dedicated-frame (make-frame)))))
4201 (delete-other-windows)
4202 (switch-to-buffer ibuf)
4203 (org-set-frame-title (concat "Indirect: " heading)))
4204 ((eq org-indirect-buffer-display 'current-window)
4205 (switch-to-buffer ibuf))
4206 ((eq org-indirect-buffer-display 'other-window)
4207 (pop-to-buffer ibuf))
4208 (t (error "Invalid value.")))
4209 (if (featurep 'xemacs)
4210 (save-excursion (org-mode) (turn-on-font-lock)))
4211 (narrow-to-region beg end)
4212 (show-all)
4213 (goto-char pos)
4214 (and (window-live-p cwin) (select-window cwin))))
4216 (defun org-get-indirect-buffer (&optional buffer)
4217 (setq buffer (or buffer (current-buffer)))
4218 (let ((n 1) (base (buffer-name buffer)) bname)
4219 (while (buffer-live-p
4220 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4221 (setq n (1+ n)))
4222 (condition-case nil
4223 (make-indirect-buffer buffer bname 'clone)
4224 (error (make-indirect-buffer buffer bname)))))
4226 (defun org-set-frame-title (title)
4227 "Set the title of the current frame to the string TITLE."
4228 ;; FIXME: how to name a single frame in XEmacs???
4229 (unless (featurep 'xemacs)
4230 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4232 ;;;; Structure editing
4234 ;;; Inserting headlines
4236 (defun org-insert-heading (&optional force-heading)
4237 "Insert a new heading or item with same depth at point.
4238 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4239 If point is at the beginning of a headline, insert a sibling before the
4240 current headline. If point is not at the beginning, do not split the line,
4241 but create the new hedline after the current line."
4242 (interactive "P")
4243 (if (= (buffer-size) 0)
4244 (insert "\n* ")
4245 (when (or force-heading (not (org-insert-item)))
4246 (let* ((head (save-excursion
4247 (condition-case nil
4248 (progn
4249 (org-back-to-heading)
4250 (match-string 0))
4251 (error "*"))))
4252 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4253 pos)
4254 (cond
4255 ((and (org-on-heading-p) (bolp)
4256 (or (bobp)
4257 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4258 ;; insert before the current line
4259 (open-line (if blank 2 1)))
4260 ((and (bolp)
4261 (or (bobp)
4262 (save-excursion
4263 (backward-char 1) (not (org-invisible-p)))))
4264 ;; insert right here
4265 nil)
4267 ;; in the middle of the line
4268 (org-show-entry)
4269 (let ((split
4270 (org-get-alist-option org-M-RET-may-split-line 'headline))
4271 tags pos)
4272 (if (org-on-heading-p)
4273 (progn
4274 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4275 (setq tags (and (match-end 2) (match-string 2)))
4276 (and (match-end 1)
4277 (delete-region (match-beginning 1) (match-end 1)))
4278 (setq pos (point-at-bol))
4279 (or split (end-of-line 1))
4280 (delete-horizontal-space)
4281 (newline (if blank 2 1))
4282 (when tags
4283 (save-excursion
4284 (goto-char pos)
4285 (end-of-line 1)
4286 (insert " " tags)
4287 (org-set-tags nil 'align))))
4288 (or split (end-of-line 1))
4289 (newline (if blank 2 1))))))
4290 (insert head) (just-one-space)
4291 (setq pos (point))
4292 (end-of-line 1)
4293 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4294 (run-hooks 'org-insert-heading-hook)))))
4296 (defun org-get-heading (&optional no-tags)
4297 "Return the heading of the current entry, without the stars."
4298 (save-excursion
4299 (org-back-to-heading t)
4300 (if (looking-at
4301 (if no-tags
4302 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4303 "\\*+[ \t]+\\([^\r\n]*\\)"))
4304 (match-string 1) "")))
4306 (defun org-insert-heading-after-current ()
4307 "Insert a new heading with same level as current, after current subtree."
4308 (interactive)
4309 (org-back-to-heading)
4310 (org-insert-heading)
4311 (org-move-subtree-down)
4312 (end-of-line 1))
4314 (defun org-insert-todo-heading (arg)
4315 "Insert a new heading with the same level and TODO state as current heading.
4316 If the heading has no TODO state, or if the state is DONE, use the first
4317 state (TODO by default). Also with prefix arg, force first state."
4318 (interactive "P")
4319 (when (not (org-insert-item 'checkbox))
4320 (org-insert-heading)
4321 (save-excursion
4322 (org-back-to-heading)
4323 (outline-previous-heading)
4324 (looking-at org-todo-line-regexp))
4325 (if (or arg
4326 (not (match-beginning 2))
4327 (member (match-string 2) org-done-keywords))
4328 (insert (car org-todo-keywords-1) " ")
4329 (insert (match-string 2) " "))))
4331 (defun org-insert-subheading (arg)
4332 "Insert a new subheading and demote it.
4333 Works for outline headings and for plain lists alike."
4334 (interactive "P")
4335 (org-insert-heading arg)
4336 (cond
4337 ((org-on-heading-p) (org-do-demote))
4338 ((org-at-item-p) (org-indent-item 1))))
4340 (defun org-insert-todo-subheading (arg)
4341 "Insert a new subheading with TODO keyword or checkbox and demote it.
4342 Works for outline headings and for plain lists alike."
4343 (interactive "P")
4344 (org-insert-todo-heading arg)
4345 (cond
4346 ((org-on-heading-p) (org-do-demote))
4347 ((org-at-item-p) (org-indent-item 1))))
4349 ;;; Promotion and Demotion
4351 (defun org-promote-subtree ()
4352 "Promote the entire subtree.
4353 See also `org-promote'."
4354 (interactive)
4355 (save-excursion
4356 (org-map-tree 'org-promote))
4357 (org-fix-position-after-promote))
4359 (defun org-demote-subtree ()
4360 "Demote the entire subtree. See `org-demote'.
4361 See also `org-promote'."
4362 (interactive)
4363 (save-excursion
4364 (org-map-tree 'org-demote))
4365 (org-fix-position-after-promote))
4368 (defun org-do-promote ()
4369 "Promote the current heading higher up the tree.
4370 If the region is active in `transient-mark-mode', promote all headings
4371 in the region."
4372 (interactive)
4373 (save-excursion
4374 (if (org-region-active-p)
4375 (org-map-region 'org-promote (region-beginning) (region-end))
4376 (org-promote)))
4377 (org-fix-position-after-promote))
4379 (defun org-do-demote ()
4380 "Demote the current heading lower down the tree.
4381 If the region is active in `transient-mark-mode', demote all headings
4382 in the region."
4383 (interactive)
4384 (save-excursion
4385 (if (org-region-active-p)
4386 (org-map-region 'org-demote (region-beginning) (region-end))
4387 (org-demote)))
4388 (org-fix-position-after-promote))
4390 (defun org-fix-position-after-promote ()
4391 "Make sure that after pro/demotion cursor position is right."
4392 (let ((pos (point)))
4393 (when (save-excursion
4394 (beginning-of-line 1)
4395 (looking-at org-todo-line-regexp)
4396 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4397 (cond ((eobp) (insert " "))
4398 ((eolp) (insert " "))
4399 ((equal (char-after) ?\ ) (forward-char 1))))))
4401 (defun org-reduced-level (l)
4402 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4404 (defun org-get-valid-level (level &optional change)
4405 "Rectify a level change under the influence of `org-odd-levels-only'
4406 LEVEL is a current level, CHANGE is by how much the level should be
4407 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4408 even level numbers will become the next higher odd number."
4409 (if org-odd-levels-only
4410 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4411 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4412 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4413 (max 1 (+ level change))))
4415 (if (boundp 'define-obsolete-function-alias)
4416 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4417 (define-obsolete-function-alias 'org-get-legal-level
4418 'org-get-valid-level)
4419 (define-obsolete-function-alias 'org-get-legal-level
4420 'org-get-valid-level "23.1")))
4422 (defun org-promote ()
4423 "Promote the current heading higher up the tree.
4424 If the region is active in `transient-mark-mode', promote all headings
4425 in the region."
4426 (org-back-to-heading t)
4427 (let* ((level (save-match-data (funcall outline-level)))
4428 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4429 (diff (abs (- level (length up-head) -1))))
4430 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4431 (replace-match up-head nil t)
4432 ;; Fixup tag positioning
4433 (and org-auto-align-tags (org-set-tags nil t))
4434 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4436 (defun org-demote ()
4437 "Demote the current heading lower down the tree.
4438 If the region is active in `transient-mark-mode', demote all headings
4439 in the region."
4440 (org-back-to-heading t)
4441 (let* ((level (save-match-data (funcall outline-level)))
4442 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4443 (diff (abs (- level (length down-head) -1))))
4444 (replace-match down-head nil t)
4445 ;; Fixup tag positioning
4446 (and org-auto-align-tags (org-set-tags nil t))
4447 (if org-adapt-indentation (org-fixup-indentation diff))))
4449 (defun org-map-tree (fun)
4450 "Call FUN for every heading underneath the current one."
4451 (org-back-to-heading)
4452 (let ((level (funcall outline-level)))
4453 (save-excursion
4454 (funcall fun)
4455 (while (and (progn
4456 (outline-next-heading)
4457 (> (funcall outline-level) level))
4458 (not (eobp)))
4459 (funcall fun)))))
4461 (defun org-map-region (fun beg end)
4462 "Call FUN for every heading between BEG and END."
4463 (let ((org-ignore-region t))
4464 (save-excursion
4465 (setq end (copy-marker end))
4466 (goto-char beg)
4467 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4468 (< (point) end))
4469 (funcall fun))
4470 (while (and (progn
4471 (outline-next-heading)
4472 (< (point) end))
4473 (not (eobp)))
4474 (funcall fun)))))
4476 (defun org-fixup-indentation (diff)
4477 "Change the indentation in the current entry by DIFF
4478 However, if any line in the current entry has no indentation, or if it
4479 would end up with no indentation after the change, nothing at all is done."
4480 (save-excursion
4481 (let ((end (save-excursion (outline-next-heading)
4482 (point-marker)))
4483 (prohibit (if (> diff 0)
4484 "^\\S-"
4485 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4486 col)
4487 (unless (save-excursion (end-of-line 1)
4488 (re-search-forward prohibit end t))
4489 (while (and (< (point) end)
4490 (re-search-forward "^[ \t]+" end t))
4491 (goto-char (match-end 0))
4492 (setq col (current-column))
4493 (if (< diff 0) (replace-match ""))
4494 (indent-to (+ diff col))))
4495 (move-marker end nil))))
4497 (defun org-convert-to-odd-levels ()
4498 "Convert an org-mode file with all levels allowed to one with odd levels.
4499 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4500 level 5 etc."
4501 (interactive)
4502 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4503 (let ((org-odd-levels-only nil) n)
4504 (save-excursion
4505 (goto-char (point-min))
4506 (while (re-search-forward "^\\*\\*+ " nil t)
4507 (setq n (- (length (match-string 0)) 2))
4508 (while (>= (setq n (1- n)) 0)
4509 (org-demote))
4510 (end-of-line 1))))))
4513 (defun org-convert-to-oddeven-levels ()
4514 "Convert an org-mode file with only odd levels to one with odd and even levels.
4515 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4516 section with an even level, conversion would destroy the structure of the file. An error
4517 is signaled in this case."
4518 (interactive)
4519 (goto-char (point-min))
4520 ;; First check if there are no even levels
4521 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4522 (org-show-context t)
4523 (error "Not all levels are odd in this file. Conversion not possible."))
4524 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4525 (let ((org-odd-levels-only nil) n)
4526 (save-excursion
4527 (goto-char (point-min))
4528 (while (re-search-forward "^\\*\\*+ " nil t)
4529 (setq n (/ (1- (length (match-string 0))) 2))
4530 (while (>= (setq n (1- n)) 0)
4531 (org-promote))
4532 (end-of-line 1))))))
4534 (defun org-tr-level (n)
4535 "Make N odd if required."
4536 (if org-odd-levels-only (1+ (/ n 2)) n))
4538 ;;; Vertical tree motion, cutting and pasting of subtrees
4540 (defun org-move-subtree-up (&optional arg)
4541 "Move the current subtree up past ARG headlines of the same level."
4542 (interactive "p")
4543 (org-move-subtree-down (- (prefix-numeric-value arg))))
4545 (defun org-move-subtree-down (&optional arg)
4546 "Move the current subtree down past ARG headlines of the same level."
4547 (interactive "p")
4548 (setq arg (prefix-numeric-value arg))
4549 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4550 'outline-get-last-sibling))
4551 (ins-point (make-marker))
4552 (cnt (abs arg))
4553 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4554 ;; Select the tree
4555 (org-back-to-heading)
4556 (setq beg0 (point))
4557 (save-excursion
4558 (setq ne-beg (org-back-over-empty-lines))
4559 (setq beg (point)))
4560 (save-match-data
4561 (save-excursion (outline-end-of-heading)
4562 (setq folded (org-invisible-p)))
4563 (outline-end-of-subtree))
4564 (outline-next-heading)
4565 (setq ne-end (org-back-over-empty-lines))
4566 (setq end (point))
4567 (goto-char beg0)
4568 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4569 ;; include less whitespace
4570 (save-excursion
4571 (goto-char beg)
4572 (forward-line (- ne-beg ne-end))
4573 (setq beg (point))))
4574 ;; Find insertion point, with error handling
4575 (while (> cnt 0)
4576 (or (and (funcall movfunc) (looking-at outline-regexp))
4577 (progn (goto-char beg0)
4578 (error "Cannot move past superior level or buffer limit")))
4579 (setq cnt (1- cnt)))
4580 (if (> arg 0)
4581 ;; Moving forward - still need to move over subtree
4582 (progn (org-end-of-subtree t t)
4583 (save-excursion
4584 (org-back-over-empty-lines)
4585 (or (bolp) (newline)))))
4586 (setq ne-ins (org-back-over-empty-lines))
4587 (move-marker ins-point (point))
4588 (setq txt (buffer-substring beg end))
4589 (delete-region beg end)
4590 (outline-flag-region (1- beg) beg nil)
4591 (outline-flag-region (1- (point)) (point) nil)
4592 (insert txt)
4593 (or (bolp) (insert "\n"))
4594 (setq ins-end (point))
4595 (goto-char ins-point)
4596 (org-skip-whitespace)
4597 (when (and (< arg 0)
4598 (org-first-sibling-p)
4599 (> ne-ins ne-beg))
4600 ;; Move whitespace back to beginning
4601 (save-excursion
4602 (goto-char ins-end)
4603 (let ((kill-whole-line t))
4604 (kill-line (- ne-ins ne-beg)) (point)))
4605 (insert (make-string (- ne-ins ne-beg) ?\n)))
4606 (move-marker ins-point nil)
4607 (org-compact-display-after-subtree-move)
4608 (unless folded
4609 (org-show-entry)
4610 (show-children)
4611 (org-cycle-hide-drawers 'children))))
4613 (defvar org-subtree-clip ""
4614 "Clipboard for cut and paste of subtrees.
4615 This is actually only a copy of the kill, because we use the normal kill
4616 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4618 (defvar org-subtree-clip-folded nil
4619 "Was the last copied subtree folded?
4620 This is used to fold the tree back after pasting.")
4622 (defun org-cut-subtree (&optional n)
4623 "Cut the current subtree into the clipboard.
4624 With prefix arg N, cut this many sequential subtrees.
4625 This is a short-hand for marking the subtree and then cutting it."
4626 (interactive "p")
4627 (org-copy-subtree n 'cut))
4629 (defun org-copy-subtree (&optional n cut)
4630 "Cut the current subtree into the clipboard.
4631 With prefix arg N, cut this many sequential subtrees.
4632 This is a short-hand for marking the subtree and then copying it.
4633 If CUT is non-nil, actually cut the subtree."
4634 (interactive "p")
4635 (let (beg end folded (beg0 (point)))
4636 (if (interactive-p)
4637 (org-back-to-heading nil) ; take what looks like a subtree
4638 (org-back-to-heading t)) ; take what is really there
4639 (org-back-over-empty-lines)
4640 (setq beg (point))
4641 (skip-chars-forward " \t\r\n")
4642 (save-match-data
4643 (save-excursion (outline-end-of-heading)
4644 (setq folded (org-invisible-p)))
4645 (condition-case nil
4646 (outline-forward-same-level (1- n))
4647 (error nil))
4648 (org-end-of-subtree t t))
4649 (org-back-over-empty-lines)
4650 (setq end (point))
4651 (goto-char beg0)
4652 (when (> end beg)
4653 (setq org-subtree-clip-folded folded)
4654 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4655 (setq org-subtree-clip (current-kill 0))
4656 (message "%s: Subtree(s) with %d characters"
4657 (if cut "Cut" "Copied")
4658 (length org-subtree-clip)))))
4660 (defun org-paste-subtree (&optional level tree)
4661 "Paste the clipboard as a subtree, with modification of headline level.
4662 The entire subtree is promoted or demoted in order to match a new headline
4663 level. By default, the new level is derived from the visible headings
4664 before and after the insertion point, and taken to be the inferior headline
4665 level of the two. So if the previous visible heading is level 3 and the
4666 next is level 4 (or vice versa), level 4 will be used for insertion.
4667 This makes sure that the subtree remains an independent subtree and does
4668 not swallow low level entries.
4670 You can also force a different level, either by using a numeric prefix
4671 argument, or by inserting the heading marker by hand. For example, if the
4672 cursor is after \"*****\", then the tree will be shifted to level 5.
4674 If you want to insert the tree as is, just use \\[yank].
4676 If optional TREE is given, use this text instead of the kill ring."
4677 (interactive "P")
4678 (unless (org-kill-is-subtree-p tree)
4679 (error "%s"
4680 (substitute-command-keys
4681 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4682 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4683 (^re (concat "^\\(" outline-regexp "\\)"))
4684 (re (concat "\\(" outline-regexp "\\)"))
4685 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4687 (old-level (if (string-match ^re txt)
4688 (- (match-end 0) (match-beginning 0) 1)
4689 -1))
4690 (force-level (cond (level (prefix-numeric-value level))
4691 ((string-match
4692 ^re_ (buffer-substring (point-at-bol) (point)))
4693 (- (match-end 1) (match-beginning 1)))
4694 (t nil)))
4695 (previous-level (save-excursion
4696 (condition-case nil
4697 (progn
4698 (outline-previous-visible-heading 1)
4699 (if (looking-at re)
4700 (- (match-end 0) (match-beginning 0) 1)
4702 (error 1))))
4703 (next-level (save-excursion
4704 (condition-case nil
4705 (progn
4706 (or (looking-at outline-regexp)
4707 (outline-next-visible-heading 1))
4708 (if (looking-at re)
4709 (- (match-end 0) (match-beginning 0) 1)
4711 (error 1))))
4712 (new-level (or force-level (max previous-level next-level)))
4713 (shift (if (or (= old-level -1)
4714 (= new-level -1)
4715 (= old-level new-level))
4717 (- new-level old-level)))
4718 (delta (if (> shift 0) -1 1))
4719 (func (if (> shift 0) 'org-demote 'org-promote))
4720 (org-odd-levels-only nil)
4721 beg end)
4722 ;; Remove the forced level indicator
4723 (if force-level
4724 (delete-region (point-at-bol) (point)))
4725 ;; Paste
4726 (beginning-of-line 1)
4727 (org-back-over-empty-lines)
4728 (setq beg (point))
4729 (insert-before-markers txt)
4730 (unless (string-match "\n\\'" txt) (insert "\n"))
4731 (setq end (point))
4732 (goto-char beg)
4733 (skip-chars-forward " \t\n\r")
4734 (setq beg (point))
4735 ;; Shift if necessary
4736 (unless (= shift 0)
4737 (save-restriction
4738 (narrow-to-region beg end)
4739 (while (not (= shift 0))
4740 (org-map-region func (point-min) (point-max))
4741 (setq shift (+ delta shift)))
4742 (goto-char (point-min))))
4743 (when (interactive-p)
4744 (message "Clipboard pasted as level %d subtree" new-level))
4745 (if (and kill-ring
4746 (eq org-subtree-clip (current-kill 0))
4747 org-subtree-clip-folded)
4748 ;; The tree was folded before it was killed/copied
4749 (hide-subtree))))
4751 (defun org-kill-is-subtree-p (&optional txt)
4752 "Check if the current kill is an outline subtree, or a set of trees.
4753 Returns nil if kill does not start with a headline, or if the first
4754 headline level is not the largest headline level in the tree.
4755 So this will actually accept several entries of equal levels as well,
4756 which is OK for `org-paste-subtree'.
4757 If optional TXT is given, check this string instead of the current kill."
4758 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4759 (start-level (and kill
4760 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4761 org-outline-regexp "\\)")
4762 kill)
4763 (- (match-end 2) (match-beginning 2) 1)))
4764 (re (concat "^" org-outline-regexp))
4765 (start (1+ (match-beginning 2))))
4766 (if (not start-level)
4767 (progn
4768 nil) ;; does not even start with a heading
4769 (catch 'exit
4770 (while (setq start (string-match re kill (1+ start)))
4771 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4772 (throw 'exit nil)))
4773 t))))
4775 (defun org-narrow-to-subtree ()
4776 "Narrow buffer to the current subtree."
4777 (interactive)
4778 (save-excursion
4779 (save-match-data
4780 (narrow-to-region
4781 (progn (org-back-to-heading) (point))
4782 (progn (org-end-of-subtree t t) (point))))))
4785 ;;; Outline Sorting
4787 (defun org-sort (with-case)
4788 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4789 Optional argument WITH-CASE means sort case-sensitively."
4790 (interactive "P")
4791 (if (org-at-table-p)
4792 (org-call-with-arg 'org-table-sort-lines with-case)
4793 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4795 (defun org-sort-remove-invisible (s)
4796 (remove-text-properties 0 (length s) org-rm-props s)
4797 (while (string-match org-bracket-link-regexp s)
4798 (setq s (replace-match (if (match-end 2)
4799 (match-string 3 s)
4800 (match-string 1 s)) t t s)))
4803 (defvar org-priority-regexp) ; defined later in the file
4805 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4806 "Sort entries on a certain level of an outline tree.
4807 If there is an active region, the entries in the region are sorted.
4808 Else, if the cursor is before the first entry, sort the top-level items.
4809 Else, the children of the entry at point are sorted.
4811 Sorting can be alphabetically, numerically, and by date/time as given by
4812 the first time stamp in the entry. The command prompts for the sorting
4813 type unless it has been given to the function through the SORTING-TYPE
4814 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4815 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4816 called with point at the beginning of the record. It must return either
4817 a string or a number that should serve as the sorting key for that record.
4819 Comparing entries ignores case by default. However, with an optional argument
4820 WITH-CASE, the sorting considers case as well."
4821 (interactive "P")
4822 (let ((case-func (if with-case 'identity 'downcase))
4823 start beg end stars re re2
4824 txt what tmp plain-list-p)
4825 ;; Find beginning and end of region to sort
4826 (cond
4827 ((org-region-active-p)
4828 ;; we will sort the region
4829 (setq end (region-end)
4830 what "region")
4831 (goto-char (region-beginning))
4832 (if (not (org-on-heading-p)) (outline-next-heading))
4833 (setq start (point)))
4834 ((org-at-item-p)
4835 ;; we will sort this plain list
4836 (org-beginning-of-item-list) (setq start (point))
4837 (org-end-of-item-list) (setq end (point))
4838 (goto-char start)
4839 (setq plain-list-p t
4840 what "plain list"))
4841 ((or (org-on-heading-p)
4842 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4843 ;; we will sort the children of the current headline
4844 (org-back-to-heading)
4845 (setq start (point)
4846 end (progn (org-end-of-subtree t t)
4847 (org-back-over-empty-lines)
4848 (point))
4849 what "children")
4850 (goto-char start)
4851 (show-subtree)
4852 (outline-next-heading))
4854 ;; we will sort the top-level entries in this file
4855 (goto-char (point-min))
4856 (or (org-on-heading-p) (outline-next-heading))
4857 (setq start (point) end (point-max) what "top-level")
4858 (goto-char start)
4859 (show-all)))
4861 (setq beg (point))
4862 (if (>= beg end) (error "Nothing to sort"))
4864 (unless plain-list-p
4865 (looking-at "\\(\\*+\\)")
4866 (setq stars (match-string 1)
4867 re (concat "^" (regexp-quote stars) " +")
4868 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4869 txt (buffer-substring beg end))
4870 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4871 (if (and (not (equal stars "*")) (string-match re2 txt))
4872 (error "Region to sort contains a level above the first entry")))
4874 (unless sorting-type
4875 (message
4876 (if plain-list-p
4877 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4878 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
4879 what)
4880 (setq sorting-type (read-char-exclusive))
4882 (and (= (downcase sorting-type) ?f)
4883 (setq getkey-func
4884 (completing-read "Sort using function: "
4885 obarray 'fboundp t nil nil))
4886 (setq getkey-func (intern getkey-func)))
4888 (and (= (downcase sorting-type) ?r)
4889 (setq property
4890 (completing-read "Property: "
4891 (mapcar 'list (org-buffer-property-keys t))
4892 nil t))))
4894 (message "Sorting entries...")
4896 (save-restriction
4897 (narrow-to-region start end)
4899 (let ((dcst (downcase sorting-type))
4900 (now (current-time)))
4901 (sort-subr
4902 (/= dcst sorting-type)
4903 ;; This function moves to the beginning character of the "record" to
4904 ;; be sorted.
4905 (if plain-list-p
4906 (lambda nil
4907 (if (org-at-item-p) t (goto-char (point-max))))
4908 (lambda nil
4909 (if (re-search-forward re nil t)
4910 (goto-char (match-beginning 0))
4911 (goto-char (point-max)))))
4912 ;; This function moves to the last character of the "record" being
4913 ;; sorted.
4914 (if plain-list-p
4915 'org-end-of-item
4916 (lambda nil
4917 (save-match-data
4918 (condition-case nil
4919 (outline-forward-same-level 1)
4920 (error
4921 (goto-char (point-max)))))))
4923 ;; This function returns the value that gets sorted against.
4924 (if plain-list-p
4925 (lambda nil
4926 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
4927 (cond
4928 ((= dcst ?n)
4929 (string-to-number (buffer-substring (match-end 0)
4930 (point-at-eol))))
4931 ((= dcst ?a)
4932 (buffer-substring (match-end 0) (point-at-eol)))
4933 ((= dcst ?t)
4934 (if (re-search-forward org-ts-regexp
4935 (point-at-eol) t)
4936 (org-time-string-to-time (match-string 0))
4937 now))
4938 ((= dcst ?f)
4939 (if getkey-func
4940 (progn
4941 (setq tmp (funcall getkey-func))
4942 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4943 tmp)
4944 (error "Invalid key function `%s'" getkey-func)))
4945 (t (error "Invalid sorting type `%c'" sorting-type)))))
4946 (lambda nil
4947 (cond
4948 ((= dcst ?n)
4949 (if (looking-at outline-regexp)
4950 (string-to-number (buffer-substring (match-end 0)
4951 (point-at-eol)))
4952 nil))
4953 ((= dcst ?a)
4954 (funcall case-func (buffer-substring (point-at-bol)
4955 (point-at-eol))))
4956 ((= dcst ?t)
4957 (if (re-search-forward org-ts-regexp
4958 (save-excursion
4959 (forward-line 2)
4960 (point)) t)
4961 (org-time-string-to-time (match-string 0))
4962 now))
4963 ((= dcst ?p)
4964 (if (re-search-forward org-priority-regexp (point-at-eol) t)
4965 (string-to-char (match-string 2))
4966 org-default-priority))
4967 ((= dcst ?r)
4968 (or (org-entry-get nil property) ""))
4969 ((= dcst ?f)
4970 (if getkey-func
4971 (progn
4972 (setq tmp (funcall getkey-func))
4973 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
4974 tmp)
4975 (error "Invalid key function `%s'" getkey-func)))
4976 (t (error "Invalid sorting type `%c'" sorting-type)))))
4978 (cond
4979 ((= dcst ?a) 'string<)
4980 ((= dcst ?t) 'time-less-p)
4981 (t nil)))))
4982 (message "Sorting entries...done")))
4984 (defun org-do-sort (table what &optional with-case sorting-type)
4985 "Sort TABLE of WHAT according to SORTING-TYPE.
4986 The user will be prompted for the SORTING-TYPE if the call to this
4987 function does not specify it. WHAT is only for the prompt, to indicate
4988 what is being sorted. The sorting key will be extracted from
4989 the car of the elements of the table.
4990 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4991 (unless sorting-type
4992 (message
4993 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
4994 what)
4995 (setq sorting-type (read-char-exclusive)))
4996 (let ((dcst (downcase sorting-type))
4997 extractfun comparefun)
4998 ;; Define the appropriate functions
4999 (cond
5000 ((= dcst ?n)
5001 (setq extractfun 'string-to-number
5002 comparefun (if (= dcst sorting-type) '< '>)))
5003 ((= dcst ?a)
5004 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5005 (lambda(x) (downcase (org-sort-remove-invisible x))))
5006 comparefun (if (= dcst sorting-type)
5007 'string<
5008 (lambda (a b) (and (not (string< a b))
5009 (not (string= a b)))))))
5010 ((= dcst ?t)
5011 (setq extractfun
5012 (lambda (x)
5013 (if (string-match org-ts-regexp x)
5014 (time-to-seconds
5015 (org-time-string-to-time (match-string 0 x)))
5017 comparefun (if (= dcst sorting-type) '< '>)))
5018 (t (error "Invalid sorting type `%c'" sorting-type)))
5020 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5021 table)
5022 (lambda (a b) (funcall comparefun (car a) (car b))))))
5024 ;;;; Plain list items, including checkboxes
5026 ;;; Plain list items
5028 (defun org-at-item-p ()
5029 "Is point in a line starting a hand-formatted item?"
5030 (let ((llt org-plain-list-ordered-item-terminator))
5031 (save-excursion
5032 (goto-char (point-at-bol))
5033 (looking-at
5034 (cond
5035 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5036 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5037 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5038 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5040 (defun org-in-item-p ()
5041 "It the cursor inside a plain list item.
5042 Does not have to be the first line."
5043 (save-excursion
5044 (condition-case nil
5045 (progn
5046 (org-beginning-of-item)
5047 (org-at-item-p)
5049 (error nil))))
5051 (defun org-insert-item (&optional checkbox)
5052 "Insert a new item at the current level.
5053 Return t when things worked, nil when we are not in an item."
5054 (when (save-excursion
5055 (condition-case nil
5056 (progn
5057 (org-beginning-of-item)
5058 (org-at-item-p)
5059 (if (org-invisible-p) (error "Invisible item"))
5061 (error nil)))
5062 (let* ((bul (match-string 0))
5063 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5064 (match-end 0)))
5065 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5066 pos)
5067 (cond
5068 ((and (org-at-item-p) (<= (point) eow))
5069 ;; before the bullet
5070 (beginning-of-line 1)
5071 (open-line (if blank 2 1)))
5072 ((<= (point) eow)
5073 (beginning-of-line 1))
5075 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5076 (end-of-line 1)
5077 (delete-horizontal-space))
5078 (newline (if blank 2 1))))
5079 (insert bul (if checkbox "[ ]" ""))
5080 (just-one-space)
5081 (setq pos (point))
5082 (end-of-line 1)
5083 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5084 (org-maybe-renumber-ordered-list)
5085 (and checkbox (org-update-checkbox-count-maybe))
5088 ;;; Checkboxes
5090 (defun org-at-item-checkbox-p ()
5091 "Is point at a line starting a plain-list item with a checklet?"
5092 (and (org-at-item-p)
5093 (save-excursion
5094 (goto-char (match-end 0))
5095 (skip-chars-forward " \t")
5096 (looking-at "\\[[- X]\\]"))))
5098 (defun org-toggle-checkbox (&optional arg)
5099 "Toggle the checkbox in the current line."
5100 (interactive "P")
5101 (catch 'exit
5102 (let (beg end status (firstnew 'unknown))
5103 (cond
5104 ((org-region-active-p)
5105 (setq beg (region-beginning) end (region-end)))
5106 ((org-on-heading-p)
5107 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5108 ((org-at-item-checkbox-p)
5109 (let ((pos (point)))
5110 (replace-match
5111 (cond (arg "[-]")
5112 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5113 (t "[ ]"))
5114 t t)
5115 (goto-char pos))
5116 (throw 'exit t))
5117 (t (error "Not at a checkbox or heading, and no active region")))
5118 (save-excursion
5119 (goto-char beg)
5120 (while (< (point) end)
5121 (when (org-at-item-checkbox-p)
5122 (setq status (equal (match-string 0) "[X]"))
5123 (when (eq firstnew 'unknown)
5124 (setq firstnew (not status)))
5125 (replace-match
5126 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5127 (beginning-of-line 2)))))
5128 (org-update-checkbox-count-maybe))
5130 (defun org-update-checkbox-count-maybe ()
5131 "Update checkbox statistics unless turned off by user."
5132 (when org-provide-checkbox-statistics
5133 (org-update-checkbox-count)))
5135 (defun org-update-checkbox-count (&optional all)
5136 "Update the checkbox statistics in the current section.
5137 This will find all statistic cookies like [57%] and [6/12] and update them
5138 with the current numbers. With optional prefix argument ALL, do this for
5139 the whole buffer."
5140 (interactive "P")
5141 (save-excursion
5142 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5143 (beg (condition-case nil
5144 (progn (outline-back-to-heading) (point))
5145 (error (point-min))))
5146 (end (move-marker (make-marker)
5147 (progn (outline-next-heading) (point))))
5148 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5149 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5150 (re-find (concat re "\\|" re-box))
5151 beg-cookie end-cookie is-percent c-on c-off lim
5152 eline curr-ind next-ind continue-from startsearch
5153 (cstat 0)
5155 (when all
5156 (goto-char (point-min))
5157 (outline-next-heading)
5158 (setq beg (point) end (point-max)))
5159 (goto-char end)
5160 ;; find each statistic cookie
5161 (while (re-search-backward re-find beg t)
5162 (setq beg-cookie (match-beginning 1)
5163 end-cookie (match-end 1)
5164 cstat (+ cstat (if end-cookie 1 0))
5165 startsearch (point-at-eol)
5166 continue-from (point-at-bol)
5167 is-percent (match-beginning 2)
5168 lim (cond
5169 ((org-on-heading-p) (outline-next-heading) (point))
5170 ((org-at-item-p) (org-end-of-item) (point))
5171 (t nil))
5172 c-on 0
5173 c-off 0)
5174 (when lim
5175 ;; find first checkbox for this cookie and gather
5176 ;; statistics from all that are at this indentation level
5177 (goto-char startsearch)
5178 (if (re-search-forward re-box lim t)
5179 (progn
5180 (org-beginning-of-item)
5181 (setq curr-ind (org-get-indentation))
5182 (setq next-ind curr-ind)
5183 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5184 (save-excursion (end-of-line) (setq eline (point)))
5185 (if (re-search-forward re-box eline t)
5186 (if (member (match-string 2) '("[ ]" "[-]"))
5187 (setq c-off (1+ c-off))
5188 (setq c-on (1+ c-on))
5191 (org-end-of-item)
5192 (setq next-ind (org-get-indentation))
5194 (goto-char continue-from)
5195 ;; update cookie
5196 (when end-cookie
5197 (delete-region beg-cookie end-cookie)
5198 (goto-char beg-cookie)
5199 (insert
5200 (if is-percent
5201 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5202 (format "[%d/%d]" c-on (+ c-on c-off)))))
5203 ;; update items checkbox if it has one
5204 (when (org-at-item-p)
5205 (org-beginning-of-item)
5206 (when (and (> (+ c-on c-off) 0)
5207 (re-search-forward re-box (point-at-eol) t))
5208 (setq beg-cookie (match-beginning 2)
5209 end-cookie (match-end 2))
5210 (delete-region beg-cookie end-cookie)
5211 (goto-char beg-cookie)
5212 (cond ((= c-off 0) (insert "[X]"))
5213 ((= c-on 0) (insert "[ ]"))
5214 (t (insert "[-]")))
5216 (goto-char continue-from))
5217 (when (interactive-p)
5218 (message "Checkbox satistics updated %s (%d places)"
5219 (if all "in entire file" "in current outline entry") cstat)))))
5221 (defun org-get-checkbox-statistics-face ()
5222 "Select the face for checkbox statistics.
5223 The face will be `org-done' when all relevant boxes are checked. Otherwise
5224 it will be `org-todo'."
5225 (if (match-end 1)
5226 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5227 (if (and (> (match-end 2) (match-beginning 2))
5228 (equal (match-string 2) (match-string 3)))
5229 'org-done
5230 'org-todo)))
5232 (defun org-get-indentation (&optional line)
5233 "Get the indentation of the current line, interpreting tabs.
5234 When LINE is given, assume it represents a line and compute its indentation."
5235 (if line
5236 (if (string-match "^ *" (org-remove-tabs line))
5237 (match-end 0))
5238 (save-excursion
5239 (beginning-of-line 1)
5240 (skip-chars-forward " \t")
5241 (current-column))))
5243 (defun org-remove-tabs (s &optional width)
5244 "Replace tabulators in S with spaces.
5245 Assumes that s is a single line, starting in column 0."
5246 (setq width (or width tab-width))
5247 (while (string-match "\t" s)
5248 (setq s (replace-match
5249 (make-string
5250 (- (* width (/ (+ (match-beginning 0) width) width))
5251 (match-beginning 0)) ?\ )
5252 t t s)))
5255 (defun org-fix-indentation (line ind)
5256 "Fix indentation in LINE.
5257 IND is a cons cell with target and minimum indentation.
5258 If the current indenation in LINE is smaller than the minimum,
5259 leave it alone. If it is larger than ind, set it to the target."
5260 (let* ((l (org-remove-tabs line))
5261 (i (org-get-indentation l))
5262 (i1 (car ind)) (i2 (cdr ind)))
5263 (if (>= i i2) (setq l (substring line i2)))
5264 (if (> i1 0)
5265 (concat (make-string i1 ?\ ) l)
5266 l)))
5268 (defun org-beginning-of-item ()
5269 "Go to the beginning of the current hand-formatted item.
5270 If the cursor is not in an item, throw an error."
5271 (interactive)
5272 (let ((pos (point))
5273 (limit (save-excursion
5274 (condition-case nil
5275 (progn
5276 (org-back-to-heading)
5277 (beginning-of-line 2) (point))
5278 (error (point-min)))))
5279 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5280 ind ind1)
5281 (if (org-at-item-p)
5282 (beginning-of-line 1)
5283 (beginning-of-line 1)
5284 (skip-chars-forward " \t")
5285 (setq ind (current-column))
5286 (if (catch 'exit
5287 (while t
5288 (beginning-of-line 0)
5289 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5291 (if (looking-at "[ \t]*$")
5292 (setq ind1 ind-empty)
5293 (skip-chars-forward " \t")
5294 (setq ind1 (current-column)))
5295 (if (< ind1 ind)
5296 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5298 (goto-char pos)
5299 (error "Not in an item")))))
5301 (defun org-end-of-item ()
5302 "Go to the end of the current hand-formatted item.
5303 If the cursor is not in an item, throw an error."
5304 (interactive)
5305 (let* ((pos (point))
5306 ind1
5307 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5308 (limit (save-excursion (outline-next-heading) (point)))
5309 (ind (save-excursion
5310 (org-beginning-of-item)
5311 (skip-chars-forward " \t")
5312 (current-column)))
5313 (end (catch 'exit
5314 (while t
5315 (beginning-of-line 2)
5316 (if (eobp) (throw 'exit (point)))
5317 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5318 (if (looking-at "[ \t]*$")
5319 (setq ind1 ind-empty)
5320 (skip-chars-forward " \t")
5321 (setq ind1 (current-column)))
5322 (if (<= ind1 ind)
5323 (throw 'exit (point-at-bol)))))))
5324 (if end
5325 (goto-char end)
5326 (goto-char pos)
5327 (error "Not in an item"))))
5329 (defun org-next-item ()
5330 "Move to the beginning of the next item in the current plain list.
5331 Error if not at a plain list, or if this is the last item in the list."
5332 (interactive)
5333 (let (ind ind1 (pos (point)))
5334 (org-beginning-of-item)
5335 (setq ind (org-get-indentation))
5336 (org-end-of-item)
5337 (setq ind1 (org-get-indentation))
5338 (unless (and (org-at-item-p) (= ind ind1))
5339 (goto-char pos)
5340 (error "On last item"))))
5342 (defun org-previous-item ()
5343 "Move to the beginning of the previous item in the current plain list.
5344 Error if not at a plain list, or if this is the first item in the list."
5345 (interactive)
5346 (let (beg ind ind1 (pos (point)))
5347 (org-beginning-of-item)
5348 (setq beg (point))
5349 (setq ind (org-get-indentation))
5350 (goto-char beg)
5351 (catch 'exit
5352 (while t
5353 (beginning-of-line 0)
5354 (if (looking-at "[ \t]*$")
5356 (if (<= (setq ind1 (org-get-indentation)) ind)
5357 (throw 'exit t)))))
5358 (condition-case nil
5359 (if (or (not (org-at-item-p))
5360 (< ind1 (1- ind)))
5361 (error "")
5362 (org-beginning-of-item))
5363 (error (goto-char pos)
5364 (error "On first item")))))
5366 (defun org-first-list-item-p ()
5367 "Is this heading the item in a plain list?"
5368 (unless (org-at-item-p)
5369 (error "Not at a plain list item"))
5370 (org-beginning-of-item)
5371 (= (point) (save-excursion (org-beginning-of-item-list))))
5373 (defun org-move-item-down ()
5374 "Move the plain list item at point down, i.e. swap with following item.
5375 Subitems (items with larger indentation) are considered part of the item,
5376 so this really moves item trees."
5377 (interactive)
5378 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5379 (org-beginning-of-item)
5380 (setq beg0 (point))
5381 (save-excursion
5382 (setq ne-beg (org-back-over-empty-lines))
5383 (setq beg (point)))
5384 (goto-char beg0)
5385 (setq ind (org-get-indentation))
5386 (org-end-of-item)
5387 (setq end0 (point))
5388 (setq ind1 (org-get-indentation))
5389 (setq ne-end (org-back-over-empty-lines))
5390 (setq end (point))
5391 (goto-char beg0)
5392 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5393 ;; include less whitespace
5394 (save-excursion
5395 (goto-char beg)
5396 (forward-line (- ne-beg ne-end))
5397 (setq beg (point))))
5398 (goto-char end0)
5399 (if (and (org-at-item-p) (= ind ind1))
5400 (progn
5401 (org-end-of-item)
5402 (org-back-over-empty-lines)
5403 (setq txt (buffer-substring beg end))
5404 (save-excursion
5405 (delete-region beg end))
5406 (setq pos (point))
5407 (insert txt)
5408 (goto-char pos) (org-skip-whitespace)
5409 (org-maybe-renumber-ordered-list))
5410 (goto-char pos)
5411 (error "Cannot move this item further down"))))
5413 (defun org-move-item-up (arg)
5414 "Move the plain list item at point up, i.e. swap with previous item.
5415 Subitems (items with larger indentation) are considered part of the item,
5416 so this really moves item trees."
5417 (interactive "p")
5418 (let (beg beg0 end ind ind1 (pos (point)) txt
5419 ne-beg ne-ins ins-end)
5420 (org-beginning-of-item)
5421 (setq beg0 (point))
5422 (setq ind (org-get-indentation))
5423 (save-excursion
5424 (setq ne-beg (org-back-over-empty-lines))
5425 (setq beg (point)))
5426 (goto-char beg0)
5427 (org-end-of-item)
5428 (setq end (point))
5429 (goto-char beg0)
5430 (catch 'exit
5431 (while t
5432 (beginning-of-line 0)
5433 (if (looking-at "[ \t]*$")
5434 (if org-empty-line-terminates-plain-lists
5435 (progn
5436 (goto-char pos)
5437 (error "Cannot move this item further up"))
5438 nil)
5439 (if (<= (setq ind1 (org-get-indentation)) ind)
5440 (throw 'exit t)))))
5441 (condition-case nil
5442 (org-beginning-of-item)
5443 (error (goto-char beg)
5444 (error "Cannot move this item further up")))
5445 (setq ind1 (org-get-indentation))
5446 (if (and (org-at-item-p) (= ind ind1))
5447 (progn
5448 (setq ne-ins (org-back-over-empty-lines))
5449 (setq txt (buffer-substring beg end))
5450 (save-excursion
5451 (delete-region beg end))
5452 (setq pos (point))
5453 (insert txt)
5454 (setq ins-end (point))
5455 (goto-char pos) (org-skip-whitespace)
5457 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5458 ;; Move whitespace back to beginning
5459 (save-excursion
5460 (goto-char ins-end)
5461 (let ((kill-whole-line t))
5462 (kill-line (- ne-ins ne-beg)) (point)))
5463 (insert (make-string (- ne-ins ne-beg) ?\n)))
5465 (org-maybe-renumber-ordered-list))
5466 (goto-char pos)
5467 (error "Cannot move this item further up"))))
5469 (defun org-maybe-renumber-ordered-list ()
5470 "Renumber the ordered list at point if setup allows it.
5471 This tests the user option `org-auto-renumber-ordered-lists' before
5472 doing the renumbering."
5473 (interactive)
5474 (when (and org-auto-renumber-ordered-lists
5475 (org-at-item-p))
5476 (if (match-beginning 3)
5477 (org-renumber-ordered-list 1)
5478 (org-fix-bullet-type))))
5480 (defun org-maybe-renumber-ordered-list-safe ()
5481 (condition-case nil
5482 (save-excursion
5483 (org-maybe-renumber-ordered-list))
5484 (error nil)))
5486 (defun org-cycle-list-bullet (&optional which)
5487 "Cycle through the different itemize/enumerate bullets.
5488 This cycle the entire list level through the sequence:
5490 `-' -> `+' -> `*' -> `1.' -> `1)'
5492 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5493 0 meand `-', 1 means `+' etc."
5494 (interactive "P")
5495 (org-preserve-lc
5496 (org-beginning-of-item-list)
5497 (org-at-item-p)
5498 (beginning-of-line 1)
5499 (let ((current (match-string 0))
5500 (prevp (eq which 'previous))
5501 new)
5502 (setq new (cond
5503 ((and (numberp which)
5504 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5505 ((string-match "-" current) (if prevp "1)" "+"))
5506 ((string-match "\\+" current)
5507 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5508 ((string-match "\\*" current) (if prevp "+" "1."))
5509 ((string-match "\\." current) (if prevp "*" "1)"))
5510 ((string-match ")" current) (if prevp "1." "-"))
5511 (t (error "This should not happen"))))
5512 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5513 (org-fix-bullet-type)
5514 (org-maybe-renumber-ordered-list))))
5516 (defun org-get-string-indentation (s)
5517 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5518 (let ((n -1) (i 0) (w tab-width) c)
5519 (catch 'exit
5520 (while (< (setq n (1+ n)) (length s))
5521 (setq c (aref s n))
5522 (cond ((= c ?\ ) (setq i (1+ i)))
5523 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5524 (t (throw 'exit t)))))
5527 (defun org-renumber-ordered-list (arg)
5528 "Renumber an ordered plain list.
5529 Cursor needs to be in the first line of an item, the line that starts
5530 with something like \"1.\" or \"2)\"."
5531 (interactive "p")
5532 (unless (and (org-at-item-p)
5533 (match-beginning 3))
5534 (error "This is not an ordered list"))
5535 (let ((line (org-current-line))
5536 (col (current-column))
5537 (ind (org-get-string-indentation
5538 (buffer-substring (point-at-bol) (match-beginning 3))))
5539 ;; (term (substring (match-string 3) -1))
5540 ind1 (n (1- arg))
5541 fmt)
5542 ;; find where this list begins
5543 (org-beginning-of-item-list)
5544 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5545 (setq fmt (concat "%d" (match-string 1)))
5546 (beginning-of-line 0)
5547 ;; walk forward and replace these numbers
5548 (catch 'exit
5549 (while t
5550 (catch 'next
5551 (beginning-of-line 2)
5552 (if (eobp) (throw 'exit nil))
5553 (if (looking-at "[ \t]*$") (throw 'next nil))
5554 (skip-chars-forward " \t") (setq ind1 (current-column))
5555 (if (> ind1 ind) (throw 'next t))
5556 (if (< ind1 ind) (throw 'exit t))
5557 (if (not (org-at-item-p)) (throw 'exit nil))
5558 (delete-region (match-beginning 2) (match-end 2))
5559 (goto-char (match-beginning 2))
5560 (insert (format fmt (setq n (1+ n)))))))
5561 (goto-line line)
5562 (move-to-column col)))
5564 (defun org-fix-bullet-type ()
5565 "Make sure all items in this list have the same bullet as the firsst item."
5566 (interactive)
5567 (unless (org-at-item-p) (error "This is not a list"))
5568 (let ((line (org-current-line))
5569 (col (current-column))
5570 (ind (current-indentation))
5571 ind1 bullet)
5572 ;; find where this list begins
5573 (org-beginning-of-item-list)
5574 (beginning-of-line 1)
5575 ;; find out what the bullet type is
5576 (looking-at "[ \t]*\\(\\S-+\\)")
5577 (setq bullet (match-string 1))
5578 ;; walk forward and replace these numbers
5579 (beginning-of-line 0)
5580 (catch 'exit
5581 (while t
5582 (catch 'next
5583 (beginning-of-line 2)
5584 (if (eobp) (throw 'exit nil))
5585 (if (looking-at "[ \t]*$") (throw 'next nil))
5586 (skip-chars-forward " \t") (setq ind1 (current-column))
5587 (if (> ind1 ind) (throw 'next t))
5588 (if (< ind1 ind) (throw 'exit t))
5589 (if (not (org-at-item-p)) (throw 'exit nil))
5590 (skip-chars-forward " \t")
5591 (looking-at "\\S-+")
5592 (replace-match bullet))))
5593 (goto-line line)
5594 (move-to-column col)
5595 (if (string-match "[0-9]" bullet)
5596 (org-renumber-ordered-list 1))))
5598 (defun org-beginning-of-item-list ()
5599 "Go to the beginning of the current item list.
5600 I.e. to the first item in this list."
5601 (interactive)
5602 (org-beginning-of-item)
5603 (let ((pos (point-at-bol))
5604 (ind (org-get-indentation))
5605 ind1)
5606 ;; find where this list begins
5607 (catch 'exit
5608 (while t
5609 (catch 'next
5610 (beginning-of-line 0)
5611 (if (looking-at "[ \t]*$")
5612 (throw (if (bobp) 'exit 'next) t))
5613 (skip-chars-forward " \t") (setq ind1 (current-column))
5614 (if (or (< ind1 ind)
5615 (and (= ind1 ind)
5616 (not (org-at-item-p)))
5617 (bobp))
5618 (throw 'exit t)
5619 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5620 (goto-char pos)))
5623 (defun org-end-of-item-list ()
5624 "Go to the end of the current item list.
5625 I.e. to the text after the last item."
5626 (interactive)
5627 (org-beginning-of-item)
5628 (let ((pos (point-at-bol))
5629 (ind (org-get-indentation))
5630 ind1)
5631 ;; find where this list begins
5632 (catch 'exit
5633 (while t
5634 (catch 'next
5635 (beginning-of-line 2)
5636 (if (looking-at "[ \t]*$")
5637 (throw (if (eobp) 'exit 'next) t))
5638 (skip-chars-forward " \t") (setq ind1 (current-column))
5639 (if (or (< ind1 ind)
5640 (and (= ind1 ind)
5641 (not (org-at-item-p)))
5642 (eobp))
5643 (progn
5644 (setq pos (point-at-bol))
5645 (throw 'exit t))))))
5646 (goto-char pos)))
5649 (defvar org-last-indent-begin-marker (make-marker))
5650 (defvar org-last-indent-end-marker (make-marker))
5652 (defun org-outdent-item (arg)
5653 "Outdent a local list item."
5654 (interactive "p")
5655 (org-indent-item (- arg)))
5657 (defun org-indent-item (arg)
5658 "Indent a local list item."
5659 (interactive "p")
5660 (unless (org-at-item-p)
5661 (error "Not on an item"))
5662 (save-excursion
5663 (let (beg end ind ind1 tmp delta ind-down ind-up)
5664 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5665 (setq beg org-last-indent-begin-marker
5666 end org-last-indent-end-marker)
5667 (org-beginning-of-item)
5668 (setq beg (move-marker org-last-indent-begin-marker (point)))
5669 (org-end-of-item)
5670 (setq end (move-marker org-last-indent-end-marker (point))))
5671 (goto-char beg)
5672 (setq tmp (org-item-indent-positions)
5673 ind (car tmp)
5674 ind-down (nth 2 tmp)
5675 ind-up (nth 1 tmp)
5676 delta (if (> arg 0)
5677 (if ind-down (- ind-down ind) 2)
5678 (if ind-up (- ind-up ind) -2)))
5679 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5680 (while (< (point) end)
5681 (beginning-of-line 1)
5682 (skip-chars-forward " \t") (setq ind1 (current-column))
5683 (delete-region (point-at-bol) (point))
5684 (or (eolp) (indent-to-column (+ ind1 delta)))
5685 (beginning-of-line 2))))
5686 (org-fix-bullet-type)
5687 (org-maybe-renumber-ordered-list-safe)
5688 (save-excursion
5689 (beginning-of-line 0)
5690 (condition-case nil (org-beginning-of-item) (error nil))
5691 (org-maybe-renumber-ordered-list-safe)))
5693 (defun org-item-indent-positions ()
5694 "Return indentation for plain list items.
5695 This returns a list with three values: The current indentation, the
5696 parent indentation and the indentation a child should habe.
5697 Assumes cursor in item line."
5698 (let* ((bolpos (point-at-bol))
5699 (ind (org-get-indentation))
5700 ind-down ind-up pos)
5701 (save-excursion
5702 (org-beginning-of-item-list)
5703 (skip-chars-backward "\n\r \t")
5704 (when (org-in-item-p)
5705 (org-beginning-of-item)
5706 (setq ind-up (org-get-indentation))))
5707 (setq pos (point))
5708 (save-excursion
5709 (cond
5710 ((and (condition-case nil (progn (org-previous-item) t)
5711 (error nil))
5712 (or (forward-char 1) t)
5713 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5714 (setq ind-down (org-get-indentation)))
5715 ((and (goto-char pos)
5716 (org-at-item-p))
5717 (goto-char (match-end 0))
5718 (skip-chars-forward " \t")
5719 (setq ind-down (current-column)))))
5720 (list ind ind-up ind-down)))
5722 ;;; The orgstruct minor mode
5724 ;; Define a minor mode which can be used in other modes in order to
5725 ;; integrate the org-mode structure editing commands.
5727 ;; This is really a hack, because the org-mode structure commands use
5728 ;; keys which normally belong to the major mode. Here is how it
5729 ;; works: The minor mode defines all the keys necessary to operate the
5730 ;; structure commands, but wraps the commands into a function which
5731 ;; tests if the cursor is currently at a headline or a plain list
5732 ;; item. If that is the case, the structure command is used,
5733 ;; temporarily setting many Org-mode variables like regular
5734 ;; expressions for filling etc. However, when any of those keys is
5735 ;; used at a different location, function uses `key-binding' to look
5736 ;; up if the key has an associated command in another currently active
5737 ;; keymap (minor modes, major mode, global), and executes that
5738 ;; command. There might be problems if any of the keys is otherwise
5739 ;; used as a prefix key.
5741 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5742 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5743 ;; addresses this by checking explicitly for both bindings.
5745 (defvar orgstruct-mode-map (make-sparse-keymap)
5746 "Keymap for the minor `orgstruct-mode'.")
5748 (defvar org-local-vars nil
5749 "List of local variables, for use by `orgstruct-mode'")
5751 ;;;###autoload
5752 (define-minor-mode orgstruct-mode
5753 "Toggle the minor more `orgstruct-mode'.
5754 This mode is for using Org-mode structure commands in other modes.
5755 The following key behave as if Org-mode was active, if the cursor
5756 is on a headline, or on a plain list item (both in the definition
5757 of Org-mode).
5759 M-up Move entry/item up
5760 M-down Move entry/item down
5761 M-left Promote
5762 M-right Demote
5763 M-S-up Move entry/item up
5764 M-S-down Move entry/item down
5765 M-S-left Promote subtree
5766 M-S-right Demote subtree
5767 M-q Fill paragraph and items like in Org-mode
5768 C-c ^ Sort entries
5769 C-c - Cycle list bullet
5770 TAB Cycle item visibility
5771 M-RET Insert new heading/item
5772 S-M-RET Insert new TODO heading / Chekbox item
5773 C-c C-c Set tags / toggle checkbox"
5774 nil " OrgStruct" nil
5775 (org-load-modules-maybe)
5776 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5778 ;;;###autoload
5779 (defun turn-on-orgstruct ()
5780 "Unconditionally turn on `orgstruct-mode'."
5781 (orgstruct-mode 1))
5783 ;;;###autoload
5784 (defun turn-on-orgstruct++ ()
5785 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5786 In addition to setting orgstruct-mode, this also exports all indentation and
5787 autofilling variables from org-mode into the buffer. Note that turning
5788 off orgstruct-mode will *not* remove these additional settings."
5789 (orgstruct-mode 1)
5790 (let (var val)
5791 (mapc
5792 (lambda (x)
5793 (when (string-match
5794 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5795 (symbol-name (car x)))
5796 (setq var (car x) val (nth 1 x))
5797 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5798 org-local-vars)))
5800 (defun orgstruct-error ()
5801 "Error when there is no default binding for a structure key."
5802 (interactive)
5803 (error "This key has no function outside structure elements"))
5805 (defun orgstruct-setup ()
5806 "Setup orgstruct keymaps."
5807 (let ((nfunc 0)
5808 (bindings
5809 (list
5810 '([(meta up)] org-metaup)
5811 '([(meta down)] org-metadown)
5812 '([(meta left)] org-metaleft)
5813 '([(meta right)] org-metaright)
5814 '([(meta shift up)] org-shiftmetaup)
5815 '([(meta shift down)] org-shiftmetadown)
5816 '([(meta shift left)] org-shiftmetaleft)
5817 '([(meta shift right)] org-shiftmetaright)
5818 '([(shift up)] org-shiftup)
5819 '([(shift down)] org-shiftdown)
5820 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5821 '("\M-q" fill-paragraph)
5822 '("\C-c^" org-sort)
5823 '("\C-c-" org-cycle-list-bullet)))
5824 elt key fun cmd)
5825 (while (setq elt (pop bindings))
5826 (setq nfunc (1+ nfunc))
5827 (setq key (org-key (car elt))
5828 fun (nth 1 elt)
5829 cmd (orgstruct-make-binding fun nfunc key))
5830 (org-defkey orgstruct-mode-map key cmd))
5832 ;; Special treatment needed for TAB and RET
5833 (org-defkey orgstruct-mode-map [(tab)]
5834 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5835 (org-defkey orgstruct-mode-map "\C-i"
5836 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5838 (org-defkey orgstruct-mode-map "\M-\C-m"
5839 (orgstruct-make-binding 'org-insert-heading 105
5840 "\M-\C-m" [(meta return)]))
5841 (org-defkey orgstruct-mode-map [(meta return)]
5842 (orgstruct-make-binding 'org-insert-heading 106
5843 [(meta return)] "\M-\C-m"))
5845 (org-defkey orgstruct-mode-map [(shift meta return)]
5846 (orgstruct-make-binding 'org-insert-todo-heading 107
5847 [(meta return)] "\M-\C-m"))
5849 (unless org-local-vars
5850 (setq org-local-vars (org-get-local-variables)))
5854 (defun orgstruct-make-binding (fun n &rest keys)
5855 "Create a function for binding in the structure minor mode.
5856 FUN is the command to call inside a table. N is used to create a unique
5857 command name. KEYS are keys that should be checked in for a command
5858 to execute outside of tables."
5859 (eval
5860 (list 'defun
5861 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5862 '(arg)
5863 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5864 "Outside of structure, run the binding of `"
5865 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5866 "'.")
5867 '(interactive "p")
5868 (list 'if
5869 '(org-context-p 'headline 'item)
5870 (list 'org-run-like-in-org-mode (list 'quote fun))
5871 (list 'let '(orgstruct-mode)
5872 (list 'call-interactively
5873 (append '(or)
5874 (mapcar (lambda (k)
5875 (list 'key-binding k))
5876 keys)
5877 '('orgstruct-error))))))))
5879 (defun org-context-p (&rest contexts)
5880 "Check if local context is and of CONTEXTS.
5881 Possible values in the list of contexts are `table', `headline', and `item'."
5882 (let ((pos (point)))
5883 (goto-char (point-at-bol))
5884 (prog1 (or (and (memq 'table contexts)
5885 (looking-at "[ \t]*|"))
5886 (and (memq 'headline contexts)
5887 (looking-at "\\*+"))
5888 (and (memq 'item contexts)
5889 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5890 (goto-char pos))))
5892 (defun org-get-local-variables ()
5893 "Return a list of all local variables in an org-mode buffer."
5894 (let (varlist)
5895 (with-current-buffer (get-buffer-create "*Org tmp*")
5896 (erase-buffer)
5897 (org-mode)
5898 (setq varlist (buffer-local-variables)))
5899 (kill-buffer "*Org tmp*")
5900 (delq nil
5901 (mapcar
5902 (lambda (x)
5903 (setq x
5904 (if (symbolp x)
5905 (list x)
5906 (list (car x) (list 'quote (cdr x)))))
5907 (if (string-match
5908 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5909 (symbol-name (car x)))
5910 x nil))
5911 varlist))))
5913 ;;;###autoload
5914 (defun org-run-like-in-org-mode (cmd)
5915 (org-load-modules-maybe)
5916 (unless org-local-vars
5917 (setq org-local-vars (org-get-local-variables)))
5918 (eval (list 'let org-local-vars
5919 (list 'call-interactively (list 'quote cmd)))))
5921 ;;;; Archiving
5923 (defun org-get-category (&optional pos)
5924 "Get the category applying to position POS."
5925 (get-text-property (or pos (point)) 'org-category))
5927 (defun org-refresh-category-properties ()
5928 "Refresh category text properties in the buffer."
5929 (let ((def-cat (cond
5930 ((null org-category)
5931 (if buffer-file-name
5932 (file-name-sans-extension
5933 (file-name-nondirectory buffer-file-name))
5934 "???"))
5935 ((symbolp org-category) (symbol-name org-category))
5936 (t org-category)))
5937 beg end cat pos optionp)
5938 (org-unmodified
5939 (save-excursion
5940 (save-restriction
5941 (widen)
5942 (goto-char (point-min))
5943 (put-text-property (point) (point-max) 'org-category def-cat)
5944 (while (re-search-forward
5945 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5946 (setq pos (match-end 0)
5947 optionp (equal (char-after (match-beginning 0)) ?#)
5948 cat (org-trim (match-string 2)))
5949 (if optionp
5950 (setq beg (point-at-bol) end (point-max))
5951 (org-back-to-heading t)
5952 (setq beg (point) end (org-end-of-subtree t t)))
5953 (put-text-property beg end 'org-category cat)
5954 (goto-char pos)))))))
5957 ;;;; Link Stuff
5959 ;;; Link abbreviations
5961 (defun org-link-expand-abbrev (link)
5962 "Apply replacements as defined in `org-link-abbrev-alist."
5963 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5964 (let* ((key (match-string 1 link))
5965 (as (or (assoc key org-link-abbrev-alist-local)
5966 (assoc key org-link-abbrev-alist)))
5967 (tag (and (match-end 2) (match-string 3 link)))
5968 rpl)
5969 (if (not as)
5970 link
5971 (setq rpl (cdr as))
5972 (cond
5973 ((symbolp rpl) (funcall rpl tag))
5974 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5975 (t (concat rpl tag)))))
5976 link))
5978 ;;; Storing and inserting links
5980 (defvar org-insert-link-history nil
5981 "Minibuffer history for links inserted with `org-insert-link'.")
5983 (defvar org-stored-links nil
5984 "Contains the links stored with `org-store-link'.")
5986 (defvar org-store-link-plist nil
5987 "Plist with info about the most recently link created with `org-store-link'.")
5989 (defvar org-link-protocols nil
5990 "Link protocols added to Org-mode using `org-add-link-type'.")
5992 (defvar org-store-link-functions nil
5993 "List of functions that are called to create and store a link.
5994 Each function will be called in turn until one returns a non-nil
5995 value. Each function should check if it is responsible for creating
5996 this link (for example by looking at the major mode).
5997 If not, it must exit and return nil.
5998 If yes, it should return a non-nil value after a calling
5999 `org-store-link-props' with a list of properties and values.
6000 Special properties are:
6002 :type The link prefix. like \"http\". This must be given.
6003 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6004 This is obligatory as well.
6005 :description Optional default description for the second pair
6006 of brackets in an Org-mode link. The user can still change
6007 this when inserting this link into an Org-mode buffer.
6009 In addition to these, any additional properties can be specified
6010 and then used in remember templates.")
6012 (defun org-add-link-type (type &optional follow export)
6013 "Add TYPE to the list of `org-link-types'.
6014 Re-compute all regular expressions depending on `org-link-types'
6016 FOLLOW and EXPORT are two functions.
6018 FOLLOW should take the link path as the single argument and do whatever
6019 is necessary to follow the link, for example find a file or display
6020 a mail message.
6022 EXPORT should format the link path for export to one of the export formats.
6023 It should be a function accepting three arguments:
6025 path the path of the link, the text after the prefix (like \"http:\")
6026 desc the description of the link, if any, nil if there was no descripton
6027 format the export format, a symbol like `html' or `latex'.
6029 The function may use the FORMAT information to return different values
6030 depending on the format. The return value will be put literally into
6031 the exported file.
6032 Org-mode has a built-in default for exporting links. If you are happy with
6033 this default, there is no need to define an export function for the link
6034 type. For a simple example of an export function, see `org-bbdb.el'."
6035 (add-to-list 'org-link-types type t)
6036 (org-make-link-regexps)
6037 (if (assoc type org-link-protocols)
6038 (setcdr (assoc type org-link-protocols) (list follow export))
6039 (push (list type follow export) org-link-protocols)))
6042 ;;;###autoload
6043 (defun org-store-link (arg)
6044 "\\<org-mode-map>Store an org-link to the current location.
6045 This link is added to `org-stored-links' and can later be inserted
6046 into an org-buffer with \\[org-insert-link].
6048 For some link types, a prefix arg is interpreted:
6049 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6050 For file links, arg negates `org-context-in-file-links'."
6051 (interactive "P")
6052 (org-load-modules-maybe)
6053 (setq org-store-link-plist nil) ; reset
6054 (let (link cpltxt desc description search txt)
6055 (cond
6057 ((run-hook-with-args-until-success 'org-store-link-functions)
6058 (setq link (plist-get org-store-link-plist :link)
6059 desc (or (plist-get org-store-link-plist :description) link)))
6061 ((eq major-mode 'calendar-mode)
6062 (let ((cd (calendar-cursor-to-date)))
6063 (setq link
6064 (format-time-string
6065 (car org-time-stamp-formats)
6066 (apply 'encode-time
6067 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6068 nil nil nil))))
6069 (org-store-link-props :type "calendar" :date cd)))
6071 ((eq major-mode 'w3-mode)
6072 (setq cpltxt (url-view-url t)
6073 link (org-make-link cpltxt))
6074 (org-store-link-props :type "w3" :url (url-view-url t)))
6076 ((eq major-mode 'w3m-mode)
6077 (setq cpltxt (or w3m-current-title w3m-current-url)
6078 link (org-make-link w3m-current-url))
6079 (org-store-link-props :type "w3m" :url (url-view-url t)))
6081 ((setq search (run-hook-with-args-until-success
6082 'org-create-file-search-functions))
6083 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6084 "::" search))
6085 (setq cpltxt (or description link)))
6087 ((eq major-mode 'image-mode)
6088 (setq cpltxt (concat "file:"
6089 (abbreviate-file-name buffer-file-name))
6090 link (org-make-link cpltxt))
6091 (org-store-link-props :type "image" :file buffer-file-name))
6093 ((eq major-mode 'dired-mode)
6094 ;; link to the file in the current line
6095 (setq cpltxt (concat "file:"
6096 (abbreviate-file-name
6097 (expand-file-name
6098 (dired-get-filename nil t))))
6099 link (org-make-link cpltxt)))
6101 ((and buffer-file-name (org-mode-p))
6102 ;; Just link to current headline
6103 (setq cpltxt (concat "file:"
6104 (abbreviate-file-name buffer-file-name)))
6105 ;; Add a context search string
6106 (when (org-xor org-context-in-file-links arg)
6107 ;; Check if we are on a target
6108 (if (org-in-regexp "<<\\(.*?\\)>>")
6109 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6110 (setq txt (cond
6111 ((org-on-heading-p) nil)
6112 ((org-region-active-p)
6113 (buffer-substring (region-beginning) (region-end)))
6114 (t (buffer-substring (point-at-bol) (point-at-eol)))))
6115 (when (or (null txt) (string-match "\\S-" txt))
6116 (setq cpltxt
6117 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6118 desc "NONE"))))
6119 (if (string-match "::\\'" cpltxt)
6120 (setq cpltxt (substring cpltxt 0 -2)))
6121 (setq link (org-make-link cpltxt)))
6123 ((buffer-file-name (buffer-base-buffer))
6124 ;; Just link to this file here.
6125 (setq cpltxt (concat "file:"
6126 (abbreviate-file-name
6127 (buffer-file-name (buffer-base-buffer)))))
6128 ;; Add a context string
6129 (when (org-xor org-context-in-file-links arg)
6130 (setq txt (if (org-region-active-p)
6131 (buffer-substring (region-beginning) (region-end))
6132 (buffer-substring (point-at-bol) (point-at-eol))))
6133 ;; Only use search option if there is some text.
6134 (when (string-match "\\S-" txt)
6135 (setq cpltxt
6136 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6137 desc "NONE")))
6138 (setq link (org-make-link cpltxt)))
6140 ((interactive-p)
6141 (error "Cannot link to a buffer which is not visiting a file"))
6143 (t (setq link nil)))
6145 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6146 (setq link (or link cpltxt)
6147 desc (or desc cpltxt))
6148 (if (equal desc "NONE") (setq desc nil))
6150 (if (and (interactive-p) link)
6151 (progn
6152 (setq org-stored-links
6153 (cons (list link desc) org-stored-links))
6154 (message "Stored: %s" (or desc link)))
6155 (and link (org-make-link-string link desc)))))
6157 (defun org-store-link-props (&rest plist)
6158 "Store link properties, extract names and addresses."
6159 (let (x adr)
6160 (when (setq x (plist-get plist :from))
6161 (setq adr (mail-extract-address-components x))
6162 (plist-put plist :fromname (car adr))
6163 (plist-put plist :fromaddress (nth 1 adr)))
6164 (when (setq x (plist-get plist :to))
6165 (setq adr (mail-extract-address-components x))
6166 (plist-put plist :toname (car adr))
6167 (plist-put plist :toaddress (nth 1 adr))))
6168 (let ((from (plist-get plist :from))
6169 (to (plist-get plist :to)))
6170 (when (and from to org-from-is-user-regexp)
6171 (plist-put plist :fromto
6172 (if (string-match org-from-is-user-regexp from)
6173 (concat "to %t")
6174 (concat "from %f")))))
6175 (setq org-store-link-plist plist))
6177 (defun org-add-link-props (&rest plist)
6178 "Add these properties to the link property list."
6179 (let (key value)
6180 (while plist
6181 (setq key (pop plist) value (pop plist))
6182 (setq org-store-link-plist
6183 (plist-put org-store-link-plist key value)))))
6185 (defun org-email-link-description (&optional fmt)
6186 "Return the description part of an email link.
6187 This takes information from `org-store-link-plist' and formats it
6188 according to FMT (default from `org-email-link-description-format')."
6189 (setq fmt (or fmt org-email-link-description-format))
6190 (let* ((p org-store-link-plist)
6191 (to (plist-get p :toaddress))
6192 (from (plist-get p :fromaddress))
6193 (table
6194 (list
6195 (cons "%c" (plist-get p :fromto))
6196 (cons "%F" (plist-get p :from))
6197 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6198 (cons "%T" (plist-get p :to))
6199 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6200 (cons "%s" (plist-get p :subject))
6201 (cons "%m" (plist-get p :message-id)))))
6202 (when (string-match "%c" fmt)
6203 ;; Check if the user wrote this message
6204 (if (and org-from-is-user-regexp from to
6205 (save-match-data (string-match org-from-is-user-regexp from)))
6206 (setq fmt (replace-match "to %t" t t fmt))
6207 (setq fmt (replace-match "from %f" t t fmt))))
6208 (org-replace-escapes fmt table)))
6210 (defun org-make-org-heading-search-string (&optional string heading)
6211 "Make search string for STRING or current headline."
6212 (interactive)
6213 (let ((s (or string (org-get-heading))))
6214 (unless (and string (not heading))
6215 ;; We are using a headline, clean up garbage in there.
6216 (if (string-match org-todo-regexp s)
6217 (setq s (replace-match "" t t s)))
6218 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6219 (setq s (replace-match "" t t s)))
6220 (setq s (org-trim s))
6221 (if (string-match (concat "^\\(" org-quote-string "\\|"
6222 org-comment-string "\\)") s)
6223 (setq s (replace-match "" t t s)))
6224 (while (string-match org-ts-regexp s)
6225 (setq s (replace-match "" t t s))))
6226 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6227 (setq s (replace-match " " t t s)))
6228 (or string (setq s (concat "*" s))) ; Add * for headlines
6229 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6231 (defun org-make-link (&rest strings)
6232 "Concatenate STRINGS."
6233 (apply 'concat strings))
6235 (defun org-make-link-string (link &optional description)
6236 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6237 (unless (string-match "\\S-" link)
6238 (error "Empty link"))
6239 (when (stringp description)
6240 ;; Remove brackets from the description, they are fatal.
6241 (while (string-match "\\[" description)
6242 (setq description (replace-match "{" t t description)))
6243 (while (string-match "\\]" description)
6244 (setq description (replace-match "}" t t description))))
6245 (when (equal (org-link-escape link) description)
6246 ;; No description needed, it is identical
6247 (setq description nil))
6248 (when (and (not description)
6249 (not (equal link (org-link-escape link))))
6250 (setq description link))
6251 (concat "[[" (org-link-escape link) "]"
6252 (if description (concat "[" description "]") "")
6253 "]"))
6255 (defconst org-link-escape-chars
6256 '((?\ . "%20")
6257 (?\[ . "%5B")
6258 (?\] . "%5D")
6259 (?\340 . "%E0") ; `a
6260 (?\342 . "%E2") ; ^a
6261 (?\347 . "%E7") ; ,c
6262 (?\350 . "%E8") ; `e
6263 (?\351 . "%E9") ; 'e
6264 (?\352 . "%EA") ; ^e
6265 (?\356 . "%EE") ; ^i
6266 (?\364 . "%F4") ; ^o
6267 (?\371 . "%F9") ; `u
6268 (?\373 . "%FB") ; ^u
6269 (?\; . "%3B")
6270 (?? . "%3F")
6271 (?= . "%3D")
6272 (?+ . "%2B")
6274 "Association list of escapes for some characters problematic in links.
6275 This is the list that is used for internal purposes.")
6277 (defconst org-link-escape-chars-browser
6278 '((?\ . "%20")) ; 32 for the SPC char
6279 "Association list of escapes for some characters problematic in links.
6280 This is the list that is used before handing over to the browser.")
6282 (defun org-link-escape (text &optional table)
6283 "Escape charaters in TEXT that are problematic for links."
6284 (setq table (or table org-link-escape-chars))
6285 (when text
6286 (let ((re (mapconcat (lambda (x) (regexp-quote
6287 (char-to-string (car x))))
6288 table "\\|")))
6289 (while (string-match re text)
6290 (setq text
6291 (replace-match
6292 (cdr (assoc (string-to-char (match-string 0 text))
6293 table))
6294 t t text)))
6295 text)))
6297 (defun org-link-unescape (text &optional table)
6298 "Reverse the action of `org-link-escape'."
6299 (setq table (or table org-link-escape-chars))
6300 (when text
6301 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6302 table "\\|")))
6303 (while (string-match re text)
6304 (setq text
6305 (replace-match
6306 (char-to-string (car (rassoc (match-string 0 text) table)))
6307 t t text)))
6308 text)))
6310 (defun org-xor (a b)
6311 "Exclusive or."
6312 (if a (not b) b))
6314 (defun org-get-header (header)
6315 "Find a header field in the current buffer."
6316 (save-excursion
6317 (goto-char (point-min))
6318 (let ((case-fold-search t) s)
6319 (cond
6320 ((eq header 'from)
6321 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6322 (setq s (match-string 1)))
6323 (while (string-match "\"" s)
6324 (setq s (replace-match "" t t s)))
6325 (if (string-match "[<(].*" s)
6326 (setq s (replace-match "" t t s))))
6327 ((eq header 'message-id)
6328 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6329 (setq s (match-string 1))))
6330 ((eq header 'subject)
6331 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6332 (setq s (match-string 1)))))
6333 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6334 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6335 s)))
6338 (defun org-fixup-message-id-for-http (s)
6339 "Replace special characters in a message id, so it can be used in an http query."
6340 (while (string-match "<" s)
6341 (setq s (replace-match "%3C" t t s)))
6342 (while (string-match ">" s)
6343 (setq s (replace-match "%3E" t t s)))
6344 (while (string-match "@" s)
6345 (setq s (replace-match "%40" t t s)))
6348 ;;;###autoload
6349 (defun org-insert-link-global ()
6350 "Insert a link like Org-mode does.
6351 This command can be called in any mode to insert a link in Org-mode syntax."
6352 (interactive)
6353 (org-load-modules-maybe)
6354 (org-run-like-in-org-mode 'org-insert-link))
6356 (defun org-insert-link (&optional complete-file)
6357 "Insert a link. At the prompt, enter the link.
6359 Completion can be used to select a link previously stored with
6360 `org-store-link'. When the empty string is entered (i.e. if you just
6361 press RET at the prompt), the link defaults to the most recently
6362 stored link. As SPC triggers completion in the minibuffer, you need to
6363 use M-SPC or C-q SPC to force the insertion of a space character.
6365 You will also be prompted for a description, and if one is given, it will
6366 be displayed in the buffer instead of the link.
6368 If there is already a link at point, this command will allow you to edit link
6369 and description parts.
6371 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
6372 selected using completion. The path to the file will be relative to
6373 the current directory if the file is in the current directory or a
6374 subdirectory. Otherwise, the link will be the absolute path as
6375 completed in the minibuffer (i.e. normally ~/path/to/file).
6377 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
6378 is in the current directory or below.
6379 With three \\[universal-argument] prefixes, negate the meaning of
6380 `org-keep-stored-link-after-insertion'."
6381 (interactive "P")
6382 (let* ((wcf (current-window-configuration))
6383 (region (if (org-region-active-p)
6384 (buffer-substring (region-beginning) (region-end))))
6385 (remove (and region (list (region-beginning) (region-end))))
6386 (desc region)
6387 tmphist ; byte-compile incorrectly complains about this
6388 link entry file)
6389 (cond
6390 ((org-in-regexp org-bracket-link-regexp 1)
6391 ;; We do have a link at point, and we are going to edit it.
6392 (setq remove (list (match-beginning 0) (match-end 0)))
6393 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6394 (setq link (read-string "Link: "
6395 (org-link-unescape
6396 (org-match-string-no-properties 1)))))
6397 ((or (org-in-regexp org-angle-link-re)
6398 (org-in-regexp org-plain-link-re))
6399 ;; Convert to bracket link
6400 (setq remove (list (match-beginning 0) (match-end 0))
6401 link (read-string "Link: "
6402 (org-remove-angle-brackets (match-string 0)))))
6403 ((equal complete-file '(4))
6404 ;; Completing read for file names.
6405 (setq file (read-file-name "File: "))
6406 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6407 (pwd1 (file-name-as-directory (abbreviate-file-name
6408 (expand-file-name ".")))))
6409 (cond
6410 ((equal complete-file '(16))
6411 (setq link (org-make-link
6412 "file:"
6413 (abbreviate-file-name (expand-file-name file)))))
6414 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6415 (setq link (org-make-link "file:" (match-string 1 file))))
6416 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6417 (expand-file-name file))
6418 (setq link (org-make-link
6419 "file:" (match-string 1 (expand-file-name file)))))
6420 (t (setq link (org-make-link "file:" file))))))
6422 ;; Read link, with completion for stored links.
6423 (with-output-to-temp-buffer "*Org Links*"
6424 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6425 (when org-stored-links
6426 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6427 (princ (mapconcat
6428 (lambda (x)
6429 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6430 (reverse org-stored-links) "\n"))))
6431 (let ((cw (selected-window)))
6432 (select-window (get-buffer-window "*Org Links*"))
6433 (shrink-window-if-larger-than-buffer)
6434 (setq truncate-lines t)
6435 (select-window cw))
6436 ;; Fake a link history, containing the stored links.
6437 (setq tmphist (append (mapcar 'car org-stored-links)
6438 org-insert-link-history))
6439 (unwind-protect
6440 (setq link (org-completing-read
6441 "Link: "
6442 (append
6443 (mapcar (lambda (x) (list (concat (car x) ":")))
6444 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6445 (mapcar (lambda (x) (list (concat x ":")))
6446 org-link-types))
6447 nil nil nil
6448 'tmphist
6449 (or (car (car org-stored-links)))))
6450 (set-window-configuration wcf)
6451 (kill-buffer "*Org Links*"))
6452 (setq entry (assoc link org-stored-links))
6453 (or entry (push link org-insert-link-history))
6454 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6455 (not org-keep-stored-link-after-insertion))
6456 (setq org-stored-links (delq (assoc link org-stored-links)
6457 org-stored-links)))
6458 (setq desc (or desc (nth 1 entry)))))
6460 (if (string-match org-plain-link-re link)
6461 ;; URL-like link, normalize the use of angular brackets.
6462 (setq link (org-make-link (org-remove-angle-brackets link))))
6464 ;; Check if we are linking to the current file with a search option
6465 ;; If yes, simplify the link by using only the search option.
6466 (when (and buffer-file-name
6467 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6468 (let* ((path (match-string 1 link))
6469 (case-fold-search nil)
6470 (search (match-string 2 link)))
6471 (save-match-data
6472 (if (equal (file-truename buffer-file-name) (file-truename path))
6473 ;; We are linking to this same file, with a search option
6474 (setq link search)))))
6476 ;; Check if we can/should use a relative path. If yes, simplify the link
6477 (when (string-match "\\<file:\\(.*\\)" link)
6478 (let* ((path (match-string 1 link))
6479 (origpath path)
6480 (case-fold-search nil))
6481 (cond
6482 ((eq org-link-file-path-type 'absolute)
6483 (setq path (abbreviate-file-name (expand-file-name path))))
6484 ((eq org-link-file-path-type 'noabbrev)
6485 (setq path (expand-file-name path)))
6486 ((eq org-link-file-path-type 'relative)
6487 (setq path (file-relative-name path)))
6489 (save-match-data
6490 (if (string-match (concat "^" (regexp-quote
6491 (file-name-as-directory
6492 (expand-file-name "."))))
6493 (expand-file-name path))
6494 ;; We are linking a file with relative path name.
6495 (setq path (substring (expand-file-name path)
6496 (match-end 0)))))))
6497 (setq link (concat "file:" path))
6498 (if (equal desc origpath)
6499 (setq desc path))))
6501 (setq desc (read-string "Description: " desc))
6502 (unless (string-match "\\S-" desc) (setq desc nil))
6503 (if remove (apply 'delete-region remove))
6504 (insert (org-make-link-string link desc))))
6506 (defun org-completing-read (&rest args)
6507 (let ((minibuffer-local-completion-map
6508 (copy-keymap minibuffer-local-completion-map)))
6509 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6510 (apply 'completing-read args)))
6512 ;;; Opening/following a link
6514 (defvar org-link-search-failed nil)
6516 (defun org-next-link ()
6517 "Move forward to the next link.
6518 If the link is in hidden text, expose it."
6519 (interactive)
6520 (when (and org-link-search-failed (eq this-command last-command))
6521 (goto-char (point-min))
6522 (message "Link search wrapped back to beginning of buffer"))
6523 (setq org-link-search-failed nil)
6524 (let* ((pos (point))
6525 (ct (org-context))
6526 (a (assoc :link ct)))
6527 (if a (goto-char (nth 2 a)))
6528 (if (re-search-forward org-any-link-re nil t)
6529 (progn
6530 (goto-char (match-beginning 0))
6531 (if (org-invisible-p) (org-show-context)))
6532 (goto-char pos)
6533 (setq org-link-search-failed t)
6534 (error "No further link found"))))
6536 (defun org-previous-link ()
6537 "Move backward to the previous link.
6538 If the link is in hidden text, expose it."
6539 (interactive)
6540 (when (and org-link-search-failed (eq this-command last-command))
6541 (goto-char (point-max))
6542 (message "Link search wrapped back to end of buffer"))
6543 (setq org-link-search-failed nil)
6544 (let* ((pos (point))
6545 (ct (org-context))
6546 (a (assoc :link ct)))
6547 (if a (goto-char (nth 1 a)))
6548 (if (re-search-backward org-any-link-re nil t)
6549 (progn
6550 (goto-char (match-beginning 0))
6551 (if (org-invisible-p) (org-show-context)))
6552 (goto-char pos)
6553 (setq org-link-search-failed t)
6554 (error "No further link found"))))
6556 (defun org-find-file-at-mouse (ev)
6557 "Open file link or URL at mouse."
6558 (interactive "e")
6559 (mouse-set-point ev)
6560 (org-open-at-point 'in-emacs))
6562 (defun org-open-at-mouse (ev)
6563 "Open file link or URL at mouse."
6564 (interactive "e")
6565 (mouse-set-point ev)
6566 (org-open-at-point))
6568 (defvar org-window-config-before-follow-link nil
6569 "The window configuration before following a link.
6570 This is saved in case the need arises to restore it.")
6572 (defvar org-open-link-marker (make-marker)
6573 "Marker pointing to the location where `org-open-at-point; was called.")
6575 ;;;###autoload
6576 (defun org-open-at-point-global ()
6577 "Follow a link like Org-mode does.
6578 This command can be called in any mode to follow a link that has
6579 Org-mode syntax."
6580 (interactive)
6581 (org-run-like-in-org-mode 'org-open-at-point))
6583 (defun org-open-at-point (&optional in-emacs)
6584 "Open link at or after point.
6585 If there is no link at point, this function will search forward up to
6586 the end of the current subtree.
6587 Normally, files will be opened by an appropriate application. If the
6588 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6589 (interactive "P")
6590 (org-load-modules-maybe)
6591 (move-marker org-open-link-marker (point))
6592 (setq org-window-config-before-follow-link (current-window-configuration))
6593 (org-remove-occur-highlights nil nil t)
6594 (if (org-at-timestamp-p t)
6595 (org-follow-timestamp-link)
6596 (let (type path link line search (pos (point)))
6597 (catch 'match
6598 (save-excursion
6599 (skip-chars-forward "^]\n\r")
6600 (when (org-in-regexp org-bracket-link-regexp)
6601 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6602 (while (string-match " *\n *" link)
6603 (setq link (replace-match " " t t link)))
6604 (setq link (org-link-expand-abbrev link))
6605 (if (string-match org-link-re-with-space2 link)
6606 (setq type (match-string 1 link) path (match-string 2 link))
6607 (setq type "thisfile" path link))
6608 (throw 'match t)))
6610 (when (get-text-property (point) 'org-linked-text)
6611 (setq type "thisfile"
6612 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6613 (1+ (point)) (point))
6614 path (buffer-substring
6615 (previous-single-property-change pos 'org-linked-text)
6616 (next-single-property-change pos 'org-linked-text)))
6617 (throw 'match t))
6619 (save-excursion
6620 (when (or (org-in-regexp org-angle-link-re)
6621 (org-in-regexp org-plain-link-re))
6622 (setq type (match-string 1) path (match-string 2))
6623 (throw 'match t)))
6624 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6625 (setq type "tree-match"
6626 path (match-string 1))
6627 (throw 'match t))
6628 (save-excursion
6629 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6630 (setq type "tags"
6631 path (match-string 1))
6632 (while (string-match ":" path)
6633 (setq path (replace-match "+" t t path)))
6634 (throw 'match t))))
6635 (unless path
6636 (error "No link found"))
6637 ;; Remove any trailing spaces in path
6638 (if (string-match " +\\'" path)
6639 (setq path (replace-match "" t t path)))
6641 (cond
6643 ((assoc type org-link-protocols)
6644 (funcall (nth 1 (assoc type org-link-protocols)) path))
6646 ((equal type "mailto")
6647 (let ((cmd (car org-link-mailto-program))
6648 (args (cdr org-link-mailto-program)) args1
6649 (address path) (subject "") a)
6650 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6651 (setq address (match-string 1 path)
6652 subject (org-link-escape (match-string 2 path))))
6653 (while args
6654 (cond
6655 ((not (stringp (car args))) (push (pop args) args1))
6656 (t (setq a (pop args))
6657 (if (string-match "%a" a)
6658 (setq a (replace-match address t t a)))
6659 (if (string-match "%s" a)
6660 (setq a (replace-match subject t t a)))
6661 (push a args1))))
6662 (apply cmd (nreverse args1))))
6664 ((member type '("http" "https" "ftp" "news"))
6665 (browse-url (concat type ":" (org-link-escape
6666 path org-link-escape-chars-browser))))
6668 ((member type '("message"))
6669 (browse-url (concat type ":" path)))
6671 ((string= type "tags")
6672 (org-tags-view in-emacs path))
6673 ((string= type "thisfile")
6674 (if in-emacs
6675 (switch-to-buffer-other-window
6676 (org-get-buffer-for-internal-link (current-buffer)))
6677 (org-mark-ring-push))
6678 (let ((cmd `(org-link-search
6679 ,path
6680 ,(cond ((equal in-emacs '(4)) 'occur)
6681 ((equal in-emacs '(16)) 'org-occur)
6682 (t nil))
6683 ,pos)))
6684 (condition-case nil (eval cmd)
6685 (error (progn (widen) (eval cmd))))))
6687 ((string= type "tree-match")
6688 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6690 ((string= type "file")
6691 (if (string-match "::\\([0-9]+\\)\\'" path)
6692 (setq line (string-to-number (match-string 1 path))
6693 path (substring path 0 (match-beginning 0)))
6694 (if (string-match "::\\(.+\\)\\'" path)
6695 (setq search (match-string 1 path)
6696 path (substring path 0 (match-beginning 0)))))
6697 (if (string-match "[*?{]" (file-name-nondirectory path))
6698 (dired path)
6699 (org-open-file path in-emacs line search)))
6701 ((string= type "news")
6702 (require 'org-gnus)
6703 (org-gnus-follow-link path))
6705 ((string= type "shell")
6706 (let ((cmd path))
6707 (if (or (not org-confirm-shell-link-function)
6708 (funcall org-confirm-shell-link-function
6709 (format "Execute \"%s\" in shell? "
6710 (org-add-props cmd nil
6711 'face 'org-warning))))
6712 (progn
6713 (message "Executing %s" cmd)
6714 (shell-command cmd))
6715 (error "Abort"))))
6717 ((string= type "elisp")
6718 (let ((cmd path))
6719 (if (or (not org-confirm-elisp-link-function)
6720 (funcall org-confirm-elisp-link-function
6721 (format "Execute \"%s\" as elisp? "
6722 (org-add-props cmd nil
6723 'face 'org-warning))))
6724 (message "%s => %s" cmd (eval (read cmd)))
6725 (error "Abort"))))
6728 (browse-url-at-point)))))
6729 (move-marker org-open-link-marker nil)
6730 (run-hook-with-args 'org-follow-link-hook))
6732 ;;; File search
6734 (defvar org-create-file-search-functions nil
6735 "List of functions to construct the right search string for a file link.
6736 These functions are called in turn with point at the location to
6737 which the link should point.
6739 A function in the hook should first test if it would like to
6740 handle this file type, for example by checking the major-mode or
6741 the file extension. If it decides not to handle this file, it
6742 should just return nil to give other functions a chance. If it
6743 does handle the file, it must return the search string to be used
6744 when following the link. The search string will be part of the
6745 file link, given after a double colon, and `org-open-at-point'
6746 will automatically search for it. If special measures must be
6747 taken to make the search successful, another function should be
6748 added to the companion hook `org-execute-file-search-functions',
6749 which see.
6751 A function in this hook may also use `setq' to set the variable
6752 `description' to provide a suggestion for the descriptive text to
6753 be used for this link when it gets inserted into an Org-mode
6754 buffer with \\[org-insert-link].")
6756 (defvar org-execute-file-search-functions nil
6757 "List of functions to execute a file search triggered by a link.
6759 Functions added to this hook must accept a single argument, the
6760 search string that was part of the file link, the part after the
6761 double colon. The function must first check if it would like to
6762 handle this search, for example by checking the major-mode or the
6763 file extension. If it decides not to handle this search, it
6764 should just return nil to give other functions a chance. If it
6765 does handle the search, it must return a non-nil value to keep
6766 other functions from trying.
6768 Each function can access the current prefix argument through the
6769 variable `current-prefix-argument'. Note that a single prefix is
6770 used to force opening a link in Emacs, so it may be good to only
6771 use a numeric or double prefix to guide the search function.
6773 In case this is needed, a function in this hook can also restore
6774 the window configuration before `org-open-at-point' was called using:
6776 (set-window-configuration org-window-config-before-follow-link)")
6778 (defun org-link-search (s &optional type avoid-pos)
6779 "Search for a link search option.
6780 If S is surrounded by forward slashes, it is interpreted as a
6781 regular expression. In org-mode files, this will create an `org-occur'
6782 sparse tree. In ordinary files, `occur' will be used to list matches.
6783 If the current buffer is in `dired-mode', grep will be used to search
6784 in all files. If AVOID-POS is given, ignore matches near that position."
6785 (let ((case-fold-search t)
6786 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6787 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6788 (append '(("") (" ") ("\t") ("\n"))
6789 org-emphasis-alist)
6790 "\\|") "\\)"))
6791 (pos (point))
6792 (pre "") (post "")
6793 words re0 re1 re2 re3 re4 re5 re2a reall)
6794 (cond
6795 ;; First check if there are any special
6796 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6797 ;; Now try the builtin stuff
6798 ((save-excursion
6799 (goto-char (point-min))
6800 (and
6801 (re-search-forward
6802 (concat "<<" (regexp-quote s0) ">>") nil t)
6803 (setq pos (match-beginning 0))))
6804 ;; There is an exact target for this
6805 (goto-char pos))
6806 ((string-match "^/\\(.*\\)/$" s)
6807 ;; A regular expression
6808 (cond
6809 ((org-mode-p)
6810 (org-occur (match-string 1 s)))
6811 ;;((eq major-mode 'dired-mode)
6812 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6813 (t (org-do-occur (match-string 1 s)))))
6815 ;; A normal search strings
6816 (when (equal (string-to-char s) ?*)
6817 ;; Anchor on headlines, post may include tags.
6818 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6819 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6820 s (substring s 1)))
6821 (remove-text-properties
6822 0 (length s)
6823 '(face nil mouse-face nil keymap nil fontified nil) s)
6824 ;; Make a series of regular expressions to find a match
6825 (setq words (org-split-string s "[ \n\r\t]+")
6826 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6827 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6828 "\\)" markers)
6829 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6830 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6831 re1 (concat pre re2 post)
6832 re3 (concat pre re4 post)
6833 re5 (concat pre ".*" re4)
6834 re2 (concat pre re2)
6835 re2a (concat pre re2a)
6836 re4 (concat pre re4)
6837 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6838 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6839 re5 "\\)"
6841 (cond
6842 ((eq type 'org-occur) (org-occur reall))
6843 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6844 (t (goto-char (point-min))
6845 (if (or (org-search-not-self 1 re0 nil t)
6846 (org-search-not-self 1 re1 nil t)
6847 (org-search-not-self 1 re2 nil t)
6848 (org-search-not-self 1 re2a nil t)
6849 (org-search-not-self 1 re3 nil t)
6850 (org-search-not-self 1 re4 nil t)
6851 (org-search-not-self 1 re5 nil t)
6853 (goto-char (match-beginning 1))
6854 (goto-char pos)
6855 (error "No match")))))
6857 ;; Normal string-search
6858 (goto-char (point-min))
6859 (if (search-forward s nil t)
6860 (goto-char (match-beginning 0))
6861 (error "No match"))))
6862 (and (org-mode-p) (org-show-context 'link-search))))
6864 (defun org-search-not-self (group &rest args)
6865 "Execute `re-search-forward', but only accept matches that do not
6866 enclose the position of `org-open-link-marker'."
6867 (let ((m org-open-link-marker))
6868 (catch 'exit
6869 (while (apply 're-search-forward args)
6870 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6871 (goto-char (match-end group))
6872 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6873 (> (match-beginning 0) (marker-position m))
6874 (< (match-end 0) (marker-position m)))
6875 (save-match-data
6876 (or (not (org-in-regexp
6877 org-bracket-link-analytic-regexp 1))
6878 (not (match-end 4)) ; no description
6879 (and (<= (match-beginning 4) (point))
6880 (>= (match-end 4) (point))))))
6881 (throw 'exit (point))))))))
6883 (defun org-get-buffer-for-internal-link (buffer)
6884 "Return a buffer to be used for displaying the link target of internal links."
6885 (cond
6886 ((not org-display-internal-link-with-indirect-buffer)
6887 buffer)
6888 ((string-match "(Clone)$" (buffer-name buffer))
6889 (message "Buffer is already a clone, not making another one")
6890 ;; we also do not modify visibility in this case
6891 buffer)
6892 (t ; make a new indirect buffer for displaying the link
6893 (let* ((bn (buffer-name buffer))
6894 (ibn (concat bn "(Clone)"))
6895 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6896 (with-current-buffer ib (org-overview))
6897 ib))))
6899 (defun org-do-occur (regexp &optional cleanup)
6900 "Call the Emacs command `occur'.
6901 If CLEANUP is non-nil, remove the printout of the regular expression
6902 in the *Occur* buffer. This is useful if the regex is long and not useful
6903 to read."
6904 (occur regexp)
6905 (when cleanup
6906 (let ((cwin (selected-window)) win beg end)
6907 (when (setq win (get-buffer-window "*Occur*"))
6908 (select-window win))
6909 (goto-char (point-min))
6910 (when (re-search-forward "match[a-z]+" nil t)
6911 (setq beg (match-end 0))
6912 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6913 (setq end (1- (match-beginning 0)))))
6914 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6915 (goto-char (point-min))
6916 (select-window cwin))))
6918 ;;; The mark ring for links jumps
6920 (defvar org-mark-ring nil
6921 "Mark ring for positions before jumps in Org-mode.")
6922 (defvar org-mark-ring-last-goto nil
6923 "Last position in the mark ring used to go back.")
6924 ;; Fill and close the ring
6925 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6926 (loop for i from 1 to org-mark-ring-length do
6927 (push (make-marker) org-mark-ring))
6928 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6929 org-mark-ring)
6931 (defun org-mark-ring-push (&optional pos buffer)
6932 "Put the current position or POS into the mark ring and rotate it."
6933 (interactive)
6934 (setq pos (or pos (point)))
6935 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6936 (move-marker (car org-mark-ring)
6937 (or pos (point))
6938 (or buffer (current-buffer)))
6939 (message "%s"
6940 (substitute-command-keys
6941 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6943 (defun org-mark-ring-goto (&optional n)
6944 "Jump to the previous position in the mark ring.
6945 With prefix arg N, jump back that many stored positions. When
6946 called several times in succession, walk through the entire ring.
6947 Org-mode commands jumping to a different position in the current file,
6948 or to another Org-mode file, automatically push the old position
6949 onto the ring."
6950 (interactive "p")
6951 (let (p m)
6952 (if (eq last-command this-command)
6953 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6954 (setq p org-mark-ring))
6955 (setq org-mark-ring-last-goto p)
6956 (setq m (car p))
6957 (switch-to-buffer (marker-buffer m))
6958 (goto-char m)
6959 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6961 (defun org-remove-angle-brackets (s)
6962 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6963 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6965 (defun org-add-angle-brackets (s)
6966 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6967 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6970 ;;; Following specific links
6972 (defun org-follow-timestamp-link ()
6973 (cond
6974 ((org-at-date-range-p t)
6975 (let ((org-agenda-start-on-weekday)
6976 (t1 (match-string 1))
6977 (t2 (match-string 2)))
6978 (setq t1 (time-to-days (org-time-string-to-time t1))
6979 t2 (time-to-days (org-time-string-to-time t2)))
6980 (org-agenda-list nil t1 (1+ (- t2 t1)))))
6981 ((org-at-timestamp-p t)
6982 (org-agenda-list nil (time-to-days (org-time-string-to-time
6983 (substring (match-string 1) 0 10)))
6985 (t (error "This should not happen"))))
6988 ;;; Following file links
6990 (defun org-open-file (path &optional in-emacs line search)
6991 "Open the file at PATH.
6992 First, this expands any special file name abbreviations. Then the
6993 configuration variable `org-file-apps' is checked if it contains an
6994 entry for this file type, and if yes, the corresponding command is launched.
6995 If no application is found, Emacs simply visits the file.
6996 With optional argument IN-EMACS, Emacs will visit the file.
6997 Optional LINE specifies a line to go to, optional SEARCH a string to
6998 search for. If LINE or SEARCH is given, the file will always be
6999 opened in Emacs.
7000 If the file does not exist, an error is thrown."
7001 (setq in-emacs (or in-emacs line search))
7002 (let* ((file (if (equal path "")
7003 buffer-file-name
7004 (substitute-in-file-name (expand-file-name path))))
7005 (apps (append org-file-apps (org-default-apps)))
7006 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7007 (dirp (if remp nil (file-directory-p file)))
7008 (dfile (downcase file))
7009 (old-buffer (current-buffer))
7010 (old-pos (point))
7011 (old-mode major-mode)
7012 ext cmd)
7013 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7014 (setq ext (match-string 1 dfile))
7015 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7016 (setq ext (match-string 1 dfile))))
7017 (if in-emacs
7018 (setq cmd 'emacs)
7019 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7020 (and dirp (cdr (assoc 'directory apps)))
7021 (cdr (assoc ext apps))
7022 (cdr (assoc t apps)))))
7023 (when (eq cmd 'mailcap)
7024 (require 'mailcap)
7025 (mailcap-parse-mailcaps)
7026 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7027 (command (mailcap-mime-info mime-type)))
7028 (if (stringp command)
7029 (setq cmd command)
7030 (setq cmd 'emacs))))
7031 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7032 (not (file-exists-p file))
7033 (not org-open-non-existing-files))
7034 (error "No such file: %s" file))
7035 (cond
7036 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7037 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7038 (while (string-match "['\"]%s['\"]" cmd)
7039 (setq cmd (replace-match "%s" t t cmd)))
7040 (while (string-match "%s" cmd)
7041 (setq cmd (replace-match
7042 (save-match-data (shell-quote-argument file))
7043 t t cmd)))
7044 (save-window-excursion
7045 (start-process-shell-command cmd nil cmd)))
7046 ((or (stringp cmd)
7047 (eq cmd 'emacs))
7048 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7049 (widen)
7050 (if line (goto-line line)
7051 (if search (org-link-search search))))
7052 ((consp cmd)
7053 (eval cmd))
7054 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7055 (and (org-mode-p) (eq old-mode 'org-mode)
7056 (or (not (equal old-buffer (current-buffer)))
7057 (not (equal old-pos (point))))
7058 (org-mark-ring-push old-pos old-buffer))))
7060 (defun org-default-apps ()
7061 "Return the default applications for this operating system."
7062 (cond
7063 ((eq system-type 'darwin)
7064 org-file-apps-defaults-macosx)
7065 ((eq system-type 'windows-nt)
7066 org-file-apps-defaults-windowsnt)
7067 (t org-file-apps-defaults-gnu)))
7069 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7070 (defun org-file-remote-p (file)
7071 "Test whether FILE specifies a location on a remote system.
7072 Return non-nil if the location is indeed remote.
7074 For example, the filename \"/user@host:/foo\" specifies a location
7075 on the system \"/user@host:\"."
7076 (cond ((fboundp 'file-remote-p)
7077 (file-remote-p file))
7078 ((fboundp 'tramp-handle-file-remote-p)
7079 (tramp-handle-file-remote-p file))
7080 ((and (boundp 'ange-ftp-name-format)
7081 (string-match (car ange-ftp-name-format) file))
7083 (t nil)))
7086 ;;;; Refiling
7088 (defun org-get-org-file ()
7089 "Read a filename, with default directory `org-directory'."
7090 (let ((default (or org-default-notes-file remember-data-file)))
7091 (read-file-name (format "File name [%s]: " default)
7092 (file-name-as-directory org-directory)
7093 default)))
7095 (defun org-notes-order-reversed-p ()
7096 "Check if the current file should receive notes in reversed order."
7097 (cond
7098 ((not org-reverse-note-order) nil)
7099 ((eq t org-reverse-note-order) t)
7100 ((not (listp org-reverse-note-order)) nil)
7101 (t (catch 'exit
7102 (let ((all org-reverse-note-order)
7103 entry)
7104 (while (setq entry (pop all))
7105 (if (string-match (car entry) buffer-file-name)
7106 (throw 'exit (cdr entry))))
7107 nil)))))
7109 (defvar org-refile-target-table nil
7110 "The list of refile targets, created by `org-refile'.")
7112 (defvar org-agenda-new-buffers nil
7113 "Buffers created to visit agenda files.")
7115 (defun org-get-refile-targets (&optional default-buffer)
7116 "Produce a table with refile targets."
7117 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7118 targets txt re files f desc descre)
7119 (with-current-buffer (or default-buffer (current-buffer))
7120 (while (setq entry (pop entries))
7121 (setq files (car entry) desc (cdr entry))
7122 (cond
7123 ((null files) (setq files (list (current-buffer))))
7124 ((eq files 'org-agenda-files)
7125 (setq files (org-agenda-files 'unrestricted)))
7126 ((and (symbolp files) (fboundp files))
7127 (setq files (funcall files)))
7128 ((and (symbolp files) (boundp files))
7129 (setq files (symbol-value files))))
7130 (if (stringp files) (setq files (list files)))
7131 (cond
7132 ((eq (car desc) :tag)
7133 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7134 ((eq (car desc) :todo)
7135 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7136 ((eq (car desc) :regexp)
7137 (setq descre (cdr desc)))
7138 ((eq (car desc) :level)
7139 (setq descre (concat "^\\*\\{" (number-to-string
7140 (if org-odd-levels-only
7141 (1- (* 2 (cdr desc)))
7142 (cdr desc)))
7143 "\\}[ \t]")))
7144 ((eq (car desc) :maxlevel)
7145 (setq descre (concat "^\\*\\{1," (number-to-string
7146 (if org-odd-levels-only
7147 (1- (* 2 (cdr desc)))
7148 (cdr desc)))
7149 "\\}[ \t]")))
7150 (t (error "Bad refiling target description %s" desc)))
7151 (while (setq f (pop files))
7152 (save-excursion
7153 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7154 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7155 (save-excursion
7156 (save-restriction
7157 (widen)
7158 (goto-char (point-min))
7159 (while (re-search-forward descre nil t)
7160 (goto-char (point-at-bol))
7161 (when (looking-at org-complex-heading-regexp)
7162 (setq txt (match-string 4)
7163 re (concat "^" (regexp-quote
7164 (buffer-substring (match-beginning 1)
7165 (match-end 4)))))
7166 (if (match-end 5) (setq re (concat re "[ \t]+"
7167 (regexp-quote
7168 (match-string 5)))))
7169 (setq re (concat re "[ \t]*$"))
7170 (when org-refile-use-outline-path
7171 (setq txt (mapconcat 'identity
7172 (append
7173 (if (eq org-refile-use-outline-path 'file)
7174 (list (file-name-nondirectory
7175 (buffer-file-name (buffer-base-buffer))))
7176 (if (eq org-refile-use-outline-path 'full-file-path)
7177 (list (buffer-file-name (buffer-base-buffer)))))
7178 (org-get-outline-path)
7179 (list txt))
7180 "/")))
7181 (push (list txt f re (point)) targets))
7182 (goto-char (point-at-eol))))))))
7183 (nreverse targets))))
7185 (defun org-get-outline-path ()
7186 "Return the outline path to the current entry, as a list."
7187 (let (rtn)
7188 (save-excursion
7189 (while (org-up-heading-safe)
7190 (when (looking-at org-complex-heading-regexp)
7191 (push (org-match-string-no-properties 4) rtn)))
7192 rtn)))
7194 (defvar org-refile-history nil
7195 "History for refiling operations.")
7197 (defun org-refile (&optional goto default-buffer)
7198 "Move the entry at point to another heading.
7199 The list of target headings is compiled using the information in
7200 `org-refile-targets', which see. This list is created before each use
7201 and will therefore always be up-to-date.
7203 At the target location, the entry is filed as a subitem of the target heading.
7204 Depending on `org-reverse-note-order', the new subitem will either be the
7205 first of the last subitem.
7207 With prefix arg GOTO, the command will only visit the target location,
7208 not actually move anything.
7209 With a double prefix `C-c C-c', go to the location where the last refiling
7210 operation has put the subtree."
7211 (interactive "P")
7212 (let* ((cbuf (current-buffer))
7213 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7214 pos it nbuf file re level reversed)
7215 (if (equal goto '(16))
7216 (org-refile-goto-last-stored)
7217 (when (setq it (org-refile-get-location
7218 (if goto "Goto: " "Refile to: ") default-buffer))
7219 (setq file (nth 1 it)
7220 re (nth 2 it)
7221 pos (nth 3 it))
7222 (setq nbuf (or (find-buffer-visiting file)
7223 (find-file-noselect file)))
7224 (if goto
7225 (progn
7226 (switch-to-buffer nbuf)
7227 (goto-char pos)
7228 (org-show-context 'org-goto))
7229 (org-copy-special)
7230 (save-excursion
7231 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7232 (find-file-noselect file))))
7233 (setq reversed (org-notes-order-reversed-p))
7234 (save-excursion
7235 (save-restriction
7236 (widen)
7237 (goto-char pos)
7238 (looking-at outline-regexp)
7239 (setq level (org-get-valid-level (funcall outline-level) 1))
7240 (goto-char
7241 (if reversed
7242 (outline-next-heading)
7243 (or (save-excursion (outline-get-next-sibling))
7244 (org-end-of-subtree t t)
7245 (point-max))))
7246 (bookmark-set "org-refile-last-stored")
7247 (org-paste-subtree level))))
7248 (org-cut-special)
7249 (message "Entry refiled to \"%s\"" (car it)))))))
7251 (defun org-refile-goto-last-stored ()
7252 "Go to the location where the last refile was stored."
7253 (interactive)
7254 (bookmark-jump "org-refile-last-stored")
7255 (message "This is the location of the last refile"))
7257 (defun org-refile-get-location (&optional prompt default-buffer)
7258 "Prompt the user for a refile location, using PROMPT."
7259 (let ((org-refile-targets org-refile-targets)
7260 (org-refile-use-outline-path org-refile-use-outline-path))
7261 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7262 (unless org-refile-target-table
7263 (error "No refile targets"))
7264 (let* ((cbuf (current-buffer))
7265 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7266 (fname (and filename (file-truename filename)))
7267 (tbl (mapcar
7268 (lambda (x)
7269 (if (not (equal fname (file-truename (nth 1 x))))
7270 (cons (concat (car x) " (" (file-name-nondirectory
7271 (nth 1 x)) ")")
7272 (cdr x))
7274 org-refile-target-table))
7275 (completion-ignore-case t))
7276 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7277 tbl)))
7279 ;;;; Dynamic blocks
7281 (defun org-find-dblock (name)
7282 "Find the first dynamic block with name NAME in the buffer.
7283 If not found, stay at current position and return nil."
7284 (let (pos)
7285 (save-excursion
7286 (goto-char (point-min))
7287 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7288 nil t)
7289 (match-beginning 0))))
7290 (if pos (goto-char pos))
7291 pos))
7293 (defconst org-dblock-start-re
7294 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7295 "Matches the startline of a dynamic block, with parameters.")
7297 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7298 "Matches the end of a dyhamic block.")
7300 (defun org-create-dblock (plist)
7301 "Create a dynamic block section, with parameters taken from PLIST.
7302 PLIST must containe a :name entry which is used as name of the block."
7303 (unless (bolp) (newline))
7304 (let ((name (plist-get plist :name)))
7305 (insert "#+BEGIN: " name)
7306 (while plist
7307 (if (eq (car plist) :name)
7308 (setq plist (cddr plist))
7309 (insert " " (prin1-to-string (pop plist)))))
7310 (insert "\n\n#+END:\n")
7311 (beginning-of-line -2)))
7313 (defun org-prepare-dblock ()
7314 "Prepare dynamic block for refresh.
7315 This empties the block, puts the cursor at the insert position and returns
7316 the property list including an extra property :name with the block name."
7317 (unless (looking-at org-dblock-start-re)
7318 (error "Not at a dynamic block"))
7319 (let* ((begdel (1+ (match-end 0)))
7320 (name (org-no-properties (match-string 1)))
7321 (params (append (list :name name)
7322 (read (concat "(" (match-string 3) ")")))))
7323 (unless (re-search-forward org-dblock-end-re nil t)
7324 (error "Dynamic block not terminated"))
7325 (setq params
7326 (append params
7327 (list :content (buffer-substring
7328 begdel (match-beginning 0)))))
7329 (delete-region begdel (match-beginning 0))
7330 (goto-char begdel)
7331 (open-line 1)
7332 params))
7334 (defun org-map-dblocks (&optional command)
7335 "Apply COMMAND to all dynamic blocks in the current buffer.
7336 If COMMAND is not given, use `org-update-dblock'."
7337 (let ((cmd (or command 'org-update-dblock))
7338 pos)
7339 (save-excursion
7340 (goto-char (point-min))
7341 (while (re-search-forward org-dblock-start-re nil t)
7342 (goto-char (setq pos (match-beginning 0)))
7343 (condition-case nil
7344 (funcall cmd)
7345 (error (message "Error during update of dynamic block")))
7346 (goto-char pos)
7347 (unless (re-search-forward org-dblock-end-re nil t)
7348 (error "Dynamic block not terminated"))))))
7350 (defun org-dblock-update (&optional arg)
7351 "User command for updating dynamic blocks.
7352 Update the dynamic block at point. With prefix ARG, update all dynamic
7353 blocks in the buffer."
7354 (interactive "P")
7355 (if arg
7356 (org-update-all-dblocks)
7357 (or (looking-at org-dblock-start-re)
7358 (org-beginning-of-dblock))
7359 (org-update-dblock)))
7361 (defun org-update-dblock ()
7362 "Update the dynamic block at point
7363 This means to empty the block, parse for parameters and then call
7364 the correct writing function."
7365 (save-window-excursion
7366 (let* ((pos (point))
7367 (line (org-current-line))
7368 (params (org-prepare-dblock))
7369 (name (plist-get params :name))
7370 (cmd (intern (concat "org-dblock-write:" name))))
7371 (message "Updating dynamic block `%s' at line %d..." name line)
7372 (funcall cmd params)
7373 (message "Updating dynamic block `%s' at line %d...done" name line)
7374 (goto-char pos))))
7376 (defun org-beginning-of-dblock ()
7377 "Find the beginning of the dynamic block at point.
7378 Error if there is no scuh block at point."
7379 (let ((pos (point))
7380 beg)
7381 (end-of-line 1)
7382 (if (and (re-search-backward org-dblock-start-re nil t)
7383 (setq beg (match-beginning 0))
7384 (re-search-forward org-dblock-end-re nil t)
7385 (> (match-end 0) pos))
7386 (goto-char beg)
7387 (goto-char pos)
7388 (error "Not in a dynamic block"))))
7390 (defun org-update-all-dblocks ()
7391 "Update all dynamic blocks in the buffer.
7392 This function can be used in a hook."
7393 (when (org-mode-p)
7394 (org-map-dblocks 'org-update-dblock)))
7397 ;;;; Completion
7399 (defconst org-additional-option-like-keywords
7400 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7401 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7402 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7404 (defun org-complete (&optional arg)
7405 "Perform completion on word at point.
7406 At the beginning of a headline, this completes TODO keywords as given in
7407 `org-todo-keywords'.
7408 If the current word is preceded by a backslash, completes the TeX symbols
7409 that are supported for HTML support.
7410 If the current word is preceded by \"#+\", completes special words for
7411 setting file options.
7412 In the line after \"#+STARTUP:, complete valid keywords.\"
7413 At all other locations, this simply calls the value of
7414 `org-completion-fallback-command'."
7415 (interactive "P")
7416 (org-without-partial-completion
7417 (catch 'exit
7418 (let* ((end (point))
7419 (beg1 (save-excursion
7420 (skip-chars-backward (org-re "[:alnum:]_@"))
7421 (point)))
7422 (beg (save-excursion
7423 (skip-chars-backward "a-zA-Z0-9_:$")
7424 (point)))
7425 (confirm (lambda (x) (stringp (car x))))
7426 (searchhead (equal (char-before beg) ?*))
7427 (tag (and (equal (char-before beg1) ?:)
7428 (equal (char-after (point-at-bol)) ?*)))
7429 (prop (and (equal (char-before beg1) ?:)
7430 (not (equal (char-after (point-at-bol)) ?*))))
7431 (texp (equal (char-before beg) ?\\))
7432 (link (equal (char-before beg) ?\[))
7433 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7434 beg)
7435 "#+"))
7436 (startup (string-match "^#\\+STARTUP:.*"
7437 (buffer-substring (point-at-bol) (point))))
7438 (completion-ignore-case opt)
7439 (type nil)
7440 (tbl nil)
7441 (table (cond
7442 (opt
7443 (setq type :opt)
7444 (require 'org-exp)
7445 (append
7446 (mapcar
7447 (lambda (x)
7448 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7449 (cons (match-string 2 x) (match-string 1 x)))
7450 (org-split-string (org-get-current-options) "\n"))
7451 (mapcar 'list org-additional-option-like-keywords)))
7452 (startup
7453 (setq type :startup)
7454 org-startup-options)
7455 (link (append org-link-abbrev-alist-local
7456 org-link-abbrev-alist))
7457 (texp
7458 (setq type :tex)
7459 org-html-entities)
7460 ((string-match "\\`\\*+[ \t]+\\'"
7461 (buffer-substring (point-at-bol) beg))
7462 (setq type :todo)
7463 (mapcar 'list org-todo-keywords-1))
7464 (searchhead
7465 (setq type :searchhead)
7466 (save-excursion
7467 (goto-char (point-min))
7468 (while (re-search-forward org-todo-line-regexp nil t)
7469 (push (list
7470 (org-make-org-heading-search-string
7471 (match-string 3) t))
7472 tbl)))
7473 tbl)
7474 (tag (setq type :tag beg beg1)
7475 (or org-tag-alist (org-get-buffer-tags)))
7476 (prop (setq type :prop beg beg1)
7477 (mapcar 'list (org-buffer-property-keys nil t t)))
7478 (t (progn
7479 (call-interactively org-completion-fallback-command)
7480 (throw 'exit nil)))))
7481 (pattern (buffer-substring-no-properties beg end))
7482 (completion (try-completion pattern table confirm)))
7483 (cond ((eq completion t)
7484 (if (not (assoc (upcase pattern) table))
7485 (message "Already complete")
7486 (if (and (equal type :opt)
7487 (not (member (car (assoc (upcase pattern) table))
7488 org-additional-option-like-keywords)))
7489 (insert (substring (cdr (assoc (upcase pattern) table))
7490 (length pattern)))
7491 (if (memq type '(:tag :prop)) (insert ":")))))
7492 ((null completion)
7493 (message "Can't find completion for \"%s\"" pattern)
7494 (ding))
7495 ((not (string= pattern completion))
7496 (delete-region beg end)
7497 (if (string-match " +$" completion)
7498 (setq completion (replace-match "" t t completion)))
7499 (insert completion)
7500 (if (get-buffer-window "*Completions*")
7501 (delete-window (get-buffer-window "*Completions*")))
7502 (if (assoc completion table)
7503 (if (eq type :todo) (insert " ")
7504 (if (memq type '(:tag :prop)) (insert ":"))))
7505 (if (and (equal type :opt) (assoc completion table))
7506 (message "%s" (substitute-command-keys
7507 "Press \\[org-complete] again to insert example settings"))))
7509 (message "Making completion list...")
7510 (let ((list (sort (all-completions pattern table confirm)
7511 'string<)))
7512 (with-output-to-temp-buffer "*Completions*"
7513 (condition-case nil
7514 ;; Protection needed for XEmacs and emacs 21
7515 (display-completion-list list pattern)
7516 (error (display-completion-list list)))))
7517 (message "Making completion list...%s" "done")))))))
7519 ;;;; TODO, DEADLINE, Comments
7521 (defun org-toggle-comment ()
7522 "Change the COMMENT state of an entry."
7523 (interactive)
7524 (save-excursion
7525 (org-back-to-heading)
7526 (let (case-fold-search)
7527 (if (looking-at (concat outline-regexp
7528 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7529 (replace-match "" t t nil 1)
7530 (if (looking-at outline-regexp)
7531 (progn
7532 (goto-char (match-end 0))
7533 (insert org-comment-string " ")))))))
7535 (defvar org-last-todo-state-is-todo nil
7536 "This is non-nil when the last TODO state change led to a TODO state.
7537 If the last change removed the TODO tag or switched to DONE, then
7538 this is nil.")
7540 (defvar org-setting-tags nil) ; dynamically skiped
7542 (defun org-parse-local-options (string var)
7543 "Parse STRING for startup setting relevant for variable VAR."
7544 (let ((rtn (symbol-value var))
7545 e opts)
7546 (save-match-data
7547 (if (or (not string) (not (string-match "\\S-" string)))
7549 (setq opts (delq nil (mapcar (lambda (x)
7550 (setq e (assoc x org-startup-options))
7551 (if (eq (nth 1 e) var) e nil))
7552 (org-split-string string "[ \t]+"))))
7553 (if (not opts)
7555 (setq rtn nil)
7556 (while (setq e (pop opts))
7557 (if (not (nth 3 e))
7558 (setq rtn (nth 2 e))
7559 (if (not (listp rtn)) (setq rtn nil))
7560 (push (nth 2 e) rtn)))
7561 rtn)))))
7563 (defvar org-blocker-hook nil
7564 "Hook for functions that are allowed to block a state change.
7566 Each function gets as its single argument a property list, see
7567 `org-trigger-hook' for more information about this list.
7569 If any of the functions in this hook returns nil, the state change
7570 is blocked.")
7572 (defvar org-trigger-hook nil
7573 "Hook for functions that are triggered by a state change.
7575 Each function gets as its single argument a property list with at least
7576 the following elements:
7578 (:type type-of-change :position pos-at-entry-start
7579 :from old-state :to new-state)
7581 Depending on the type, more properties may be present.
7583 This mechanism is currently implemented for:
7585 TODO state changes
7586 ------------------
7587 :type todo-state-change
7588 :from previous state (keyword as a string), or nil
7589 :to new state (keyword as a string), or nil")
7592 (defun org-todo (&optional arg)
7593 "Change the TODO state of an item.
7594 The state of an item is given by a keyword at the start of the heading,
7595 like
7596 *** TODO Write paper
7597 *** DONE Call mom
7599 The different keywords are specified in the variable `org-todo-keywords'.
7600 By default the available states are \"TODO\" and \"DONE\".
7601 So for this example: when the item starts with TODO, it is changed to DONE.
7602 When it starts with DONE, the DONE is removed. And when neither TODO nor
7603 DONE are present, add TODO at the beginning of the heading.
7605 With C-u prefix arg, use completion to determine the new state.
7606 With numeric prefix arg, switch to that state.
7608 For calling through lisp, arg is also interpreted in the following way:
7609 'none -> empty state
7610 \"\"(empty string) -> switch to empty state
7611 'done -> switch to DONE
7612 'nextset -> switch to the next set of keywords
7613 'previousset -> switch to the previous set of keywords
7614 \"WAITING\" -> switch to the specified keyword, but only if it
7615 really is a member of `org-todo-keywords'."
7616 (interactive "P")
7617 (save-excursion
7618 (catch 'exit
7619 (org-back-to-heading)
7620 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7621 (or (looking-at (concat " +" org-todo-regexp " *"))
7622 (looking-at " *"))
7623 (let* ((match-data (match-data))
7624 (startpos (point-at-bol))
7625 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7626 (org-log-done org-log-done)
7627 (org-log-repeat org-log-repeat)
7628 (org-todo-log-states org-todo-log-states)
7629 (this (match-string 1))
7630 (hl-pos (match-beginning 0))
7631 (head (org-get-todo-sequence-head this))
7632 (ass (assoc head org-todo-kwd-alist))
7633 (interpret (nth 1 ass))
7634 (done-word (nth 3 ass))
7635 (final-done-word (nth 4 ass))
7636 (last-state (or this ""))
7637 (completion-ignore-case t)
7638 (member (member this org-todo-keywords-1))
7639 (tail (cdr member))
7640 (state (cond
7641 ((and org-todo-key-trigger
7642 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7643 (and (not arg) org-use-fast-todo-selection
7644 (not (eq org-use-fast-todo-selection 'prefix)))))
7645 ;; Use fast selection
7646 (org-fast-todo-selection))
7647 ((and (equal arg '(4))
7648 (or (not org-use-fast-todo-selection)
7649 (not org-todo-key-trigger)))
7650 ;; Read a state with completion
7651 (completing-read "State: " (mapcar (lambda(x) (list x))
7652 org-todo-keywords-1)
7653 nil t))
7654 ((eq arg 'right)
7655 (if this
7656 (if tail (car tail) nil)
7657 (car org-todo-keywords-1)))
7658 ((eq arg 'left)
7659 (if (equal member org-todo-keywords-1)
7661 (if this
7662 (nth (- (length org-todo-keywords-1) (length tail) 2)
7663 org-todo-keywords-1)
7664 (org-last org-todo-keywords-1))))
7665 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7666 (setq arg nil))) ; hack to fall back to cycling
7667 (arg
7668 ;; user or caller requests a specific state
7669 (cond
7670 ((equal arg "") nil)
7671 ((eq arg 'none) nil)
7672 ((eq arg 'done) (or done-word (car org-done-keywords)))
7673 ((eq arg 'nextset)
7674 (or (car (cdr (member head org-todo-heads)))
7675 (car org-todo-heads)))
7676 ((eq arg 'previousset)
7677 (let ((org-todo-heads (reverse org-todo-heads)))
7678 (or (car (cdr (member head org-todo-heads)))
7679 (car org-todo-heads))))
7680 ((car (member arg org-todo-keywords-1)))
7681 ((nth (1- (prefix-numeric-value arg))
7682 org-todo-keywords-1))))
7683 ((null member) (or head (car org-todo-keywords-1)))
7684 ((equal this final-done-word) nil) ;; -> make empty
7685 ((null tail) nil) ;; -> first entry
7686 ((eq interpret 'sequence)
7687 (car tail))
7688 ((memq interpret '(type priority))
7689 (if (eq this-command last-command)
7690 (car tail)
7691 (if (> (length tail) 0)
7692 (or done-word (car org-done-keywords))
7693 nil)))
7694 (t nil)))
7695 (next (if state (concat " " state " ") " "))
7696 (change-plist (list :type 'todo-state-change :from this :to state
7697 :position startpos))
7698 dolog now-done-p)
7699 (when org-blocker-hook
7700 (unless (save-excursion
7701 (save-match-data
7702 (run-hook-with-args-until-failure
7703 'org-blocker-hook change-plist)))
7704 (if (interactive-p)
7705 (error "TODO state change from %s to %s blocked" this state)
7706 ;; fail silently
7707 (message "TODO state change from %s to %s blocked" this state)
7708 (throw 'exit nil))))
7709 (store-match-data match-data)
7710 (replace-match next t t)
7711 (unless (pos-visible-in-window-p hl-pos)
7712 (message "TODO state changed to %s" (org-trim next)))
7713 (unless head
7714 (setq head (org-get-todo-sequence-head state)
7715 ass (assoc head org-todo-kwd-alist)
7716 interpret (nth 1 ass)
7717 done-word (nth 3 ass)
7718 final-done-word (nth 4 ass)))
7719 (when (memq arg '(nextset previousset))
7720 (message "Keyword-Set %d/%d: %s"
7721 (- (length org-todo-sets) -1
7722 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7723 (length org-todo-sets)
7724 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7725 (setq org-last-todo-state-is-todo
7726 (not (member state org-done-keywords)))
7727 (setq now-done-p (and (member state org-done-keywords)
7728 (not (member this org-done-keywords))))
7729 (and logging (org-local-logging logging))
7730 (when (and (or org-todo-log-states org-log-done)
7731 (not (memq arg '(nextset previousset))))
7732 ;; we need to look at recording a time and note
7733 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7734 (nth 2 (assoc this org-todo-log-states))))
7735 (when (and state
7736 (member state org-not-done-keywords)
7737 (not (member this org-not-done-keywords)))
7738 ;; This is now a todo state and was not one before
7739 ;; If there was a CLOSED time stamp, get rid of it.
7740 (org-add-planning-info nil nil 'closed))
7741 (when (and now-done-p org-log-done)
7742 ;; It is now done, and it was not done before
7743 (org-add-planning-info 'closed (org-current-time))
7744 (if (and (not dolog) (eq 'note org-log-done))
7745 (org-add-log-setup 'done state 'findpos 'note)))
7746 (when (and state dolog)
7747 ;; This is a non-nil state, and we need to log it
7748 (org-add-log-setup 'state state 'findpos dolog)))
7749 ;; Fixup tag positioning
7750 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7751 (run-hooks 'org-after-todo-state-change-hook)
7752 (if (and arg (not (member state org-done-keywords)))
7753 (setq head (org-get-todo-sequence-head state)))
7754 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7755 ;; Do we need to trigger a repeat?
7756 (when now-done-p (org-auto-repeat-maybe state))
7757 ;; Fixup cursor location if close to the keyword
7758 (if (and (outline-on-heading-p)
7759 (not (bolp))
7760 (save-excursion (beginning-of-line 1)
7761 (looking-at org-todo-line-regexp))
7762 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7763 (progn
7764 (goto-char (or (match-end 2) (match-end 1)))
7765 (just-one-space)))
7766 (when org-trigger-hook
7767 (save-excursion
7768 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7770 (defun org-local-logging (value)
7771 "Get logging settings from a property VALUE."
7772 (let* (words w a)
7773 ;; directly set the variables, they are already local.
7774 (setq org-log-done nil
7775 org-log-repeat nil
7776 org-todo-log-states nil)
7777 (setq words (org-split-string value))
7778 (while (setq w (pop words))
7779 (cond
7780 ((setq a (assoc w org-startup-options))
7781 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7782 (set (nth 1 a) (nth 2 a))))
7783 ((setq a (org-extract-log-state-settings w))
7784 (and (member (car a) org-todo-keywords-1)
7785 (push a org-todo-log-states)))))))
7787 (defun org-get-todo-sequence-head (kwd)
7788 "Return the head of the TODO sequence to which KWD belongs.
7789 If KWD is not set, check if there is a text property remembering the
7790 right sequence."
7791 (let (p)
7792 (cond
7793 ((not kwd)
7794 (or (get-text-property (point-at-bol) 'org-todo-head)
7795 (progn
7796 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7797 nil (point-at-eol)))
7798 (get-text-property p 'org-todo-head))))
7799 ((not (member kwd org-todo-keywords-1))
7800 (car org-todo-keywords-1))
7801 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7803 (defun org-fast-todo-selection ()
7804 "Fast TODO keyword selection with single keys.
7805 Returns the new TODO keyword, or nil if no state change should occur."
7806 (let* ((fulltable org-todo-key-alist)
7807 (done-keywords org-done-keywords) ;; needed for the faces.
7808 (maxlen (apply 'max (mapcar
7809 (lambda (x)
7810 (if (stringp (car x)) (string-width (car x)) 0))
7811 fulltable)))
7812 (expert nil)
7813 (fwidth (+ maxlen 3 1 3))
7814 (ncol (/ (- (window-width) 4) fwidth))
7815 tg cnt e c tbl
7816 groups ingroup)
7817 (save-window-excursion
7818 (if expert
7819 (set-buffer (get-buffer-create " *Org todo*"))
7820 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7821 (erase-buffer)
7822 (org-set-local 'org-done-keywords done-keywords)
7823 (setq tbl fulltable cnt 0)
7824 (while (setq e (pop tbl))
7825 (cond
7826 ((equal e '(:startgroup))
7827 (push '() groups) (setq ingroup t)
7828 (when (not (= cnt 0))
7829 (setq cnt 0)
7830 (insert "\n"))
7831 (insert "{ "))
7832 ((equal e '(:endgroup))
7833 (setq ingroup nil cnt 0)
7834 (insert "}\n"))
7836 (setq tg (car e) c (cdr e))
7837 (if ingroup (push tg (car groups)))
7838 (setq tg (org-add-props tg nil 'face
7839 (org-get-todo-face tg)))
7840 (if (and (= cnt 0) (not ingroup)) (insert " "))
7841 (insert "[" c "] " tg (make-string
7842 (- fwidth 4 (length tg)) ?\ ))
7843 (when (= (setq cnt (1+ cnt)) ncol)
7844 (insert "\n")
7845 (if ingroup (insert " "))
7846 (setq cnt 0)))))
7847 (insert "\n")
7848 (goto-char (point-min))
7849 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7850 (fit-window-to-buffer))
7851 (message "[a-z..]:Set [SPC]:clear")
7852 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7853 (cond
7854 ((or (= c ?\C-g)
7855 (and (= c ?q) (not (rassoc c fulltable))))
7856 (setq quit-flag t))
7857 ((= c ?\ ) nil)
7858 ((setq e (rassoc c fulltable) tg (car e))
7860 (t (setq quit-flag t))))))
7862 (defun org-entry-is-todo-p ()
7863 (member (org-get-todo-state) org-not-done-keywords))
7865 (defun org-entry-is-done-p ()
7866 (member (org-get-todo-state) org-done-keywords))
7868 (defun org-get-todo-state ()
7869 (save-excursion
7870 (org-back-to-heading t)
7871 (and (looking-at org-todo-line-regexp)
7872 (match-end 2)
7873 (match-string 2))))
7875 (defun org-at-date-range-p (&optional inactive-ok)
7876 "Is the cursor inside a date range?"
7877 (interactive)
7878 (save-excursion
7879 (catch 'exit
7880 (let ((pos (point)))
7881 (skip-chars-backward "^[<\r\n")
7882 (skip-chars-backward "<[")
7883 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7884 (>= (match-end 0) pos)
7885 (throw 'exit t))
7886 (skip-chars-backward "^<[\r\n")
7887 (skip-chars-backward "<[")
7888 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
7889 (>= (match-end 0) pos)
7890 (throw 'exit t)))
7891 nil)))
7893 (defun org-get-repeat ()
7894 "Check if tere is a deadline/schedule with repeater in this entry."
7895 (save-match-data
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (if (re-search-forward
7899 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
7900 (match-string 1)))))
7902 (defvar org-last-changed-timestamp)
7903 (defvar org-log-post-message)
7904 (defvar org-log-note-purpose)
7905 (defvar org-log-note-how)
7906 (defun org-auto-repeat-maybe (done-word)
7907 "Check if the current headline contains a repeated deadline/schedule.
7908 If yes, set TODO state back to what it was and change the base date
7909 of repeating deadline/scheduled time stamps to new date.
7910 This function is run automatically after each state change to a DONE state."
7911 ;; last-state is dynamically scoped into this function
7912 (let* ((repeat (org-get-repeat))
7913 (aa (assoc last-state org-todo-kwd-alist))
7914 (interpret (nth 1 aa))
7915 (head (nth 2 aa))
7916 (whata '(("d" . day) ("m" . month) ("y" . year)))
7917 (msg "Entry repeats: ")
7918 (org-log-done nil)
7919 (org-todo-log-states nil)
7920 (nshiftmax 10) (nshift 0)
7921 re type n what ts mb0 time)
7922 (when repeat
7923 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
7924 (org-todo (if (eq interpret 'type) last-state head))
7925 (when org-log-repeat
7926 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
7927 (memq 'org-add-log-note post-command-hook))
7928 ;; OK, we are already setup for some record
7929 (if (eq org-log-repeat 'note)
7930 ;; make sure we take a note, not only a time stamp
7931 (setq org-log-note-how 'note))
7932 ;; Set up for taking a record
7933 (org-add-log-setup 'state (or done-word (car org-done-keywords))
7934 'findpos org-log-repeat)))
7935 (org-back-to-heading t)
7936 (org-add-planning-info nil nil 'closed)
7937 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
7938 org-deadline-time-regexp "\\)\\|\\("
7939 org-ts-regexp "\\)"))
7940 (while (re-search-forward
7941 re (save-excursion (outline-next-heading) (point)) t)
7942 (setq type (if (match-end 1) org-scheduled-string
7943 (if (match-end 3) org-deadline-string "Plain:"))
7944 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
7945 mb0 (match-beginning 0))
7946 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
7947 (setq n (string-to-number (match-string 2 ts))
7948 what (match-string 3 ts))
7949 (if (equal what "w") (setq n (* n 7) what "d"))
7950 ;; Preparation, see if we need to modify the start date for the change
7951 (when (match-end 1)
7952 (setq time (save-match-data (org-time-string-to-time ts)))
7953 (cond
7954 ((equal (match-string 1 ts) ".")
7955 ;; Shift starting date to today
7956 (org-timestamp-change
7957 (- (time-to-days (current-time)) (time-to-days time))
7958 'day))
7959 ((equal (match-string 1 ts) "+")
7960 (while (or (= nshift 0)
7961 (<= (time-to-days time) (time-to-days (current-time))))
7962 (when (= (incf nshift) nshiftmax)
7963 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
7964 (error "Abort")))
7965 (org-timestamp-change n (cdr (assoc what whata)))
7966 (org-at-timestamp-p t)
7967 (setq ts (match-string 1))
7968 (setq time (save-match-data (org-time-string-to-time ts))))
7969 (org-timestamp-change (- n) (cdr (assoc what whata)))
7970 ;; rematch, so that we have everything in place for the real shift
7971 (org-at-timestamp-p t)
7972 (setq ts (match-string 1))
7973 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
7974 (org-timestamp-change n (cdr (assoc what whata)))
7975 (setq msg (concat msg type org-last-changed-timestamp " "))))
7976 (setq org-log-post-message msg)
7977 (message "%s" msg))))
7979 (defun org-show-todo-tree (arg)
7980 "Make a compact tree which shows all headlines marked with TODO.
7981 The tree will show the lines where the regexp matches, and all higher
7982 headlines above the match.
7983 With a \\[universal-argument] prefix, also show the DONE entries.
7984 With a numeric prefix N, construct a sparse tree for the Nth element
7985 of `org-todo-keywords-1'."
7986 (interactive "P")
7987 (let ((case-fold-search nil)
7988 (kwd-re
7989 (cond ((null arg) org-not-done-regexp)
7990 ((equal arg '(4))
7991 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
7992 (mapcar 'list org-todo-keywords-1))))
7993 (concat "\\("
7994 (mapconcat 'identity (org-split-string kwd "|") "\\|")
7995 "\\)\\>")))
7996 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
7997 (regexp-quote (nth (1- (prefix-numeric-value arg))
7998 org-todo-keywords-1)))
7999 (t (error "Invalid prefix argument: %s" arg)))))
8000 (message "%d TODO entries found"
8001 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8003 (defun org-deadline (&optional remove)
8004 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8005 With argument REMOVE, remove any deadline from the item."
8006 (interactive "P")
8007 (if remove
8008 (progn
8009 (org-remove-timestamp-with-keyword org-deadline-string)
8010 (message "Item no longer has a deadline."))
8011 (org-add-planning-info 'deadline nil 'closed)))
8013 (defun org-schedule (&optional remove)
8014 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8015 With argument REMOVE, remove any scheduling date from the item."
8016 (interactive "P")
8017 (if remove
8018 (progn
8019 (org-remove-timestamp-with-keyword org-scheduled-string)
8020 (message "Item is no longer scheduled."))
8021 (org-add-planning-info 'scheduled nil 'closed)))
8023 (defun org-remove-timestamp-with-keyword (keyword)
8024 "Remove all time stamps with KEYWORD in the current entry."
8025 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8026 beg)
8027 (save-excursion
8028 (org-back-to-heading t)
8029 (setq beg (point))
8030 (org-end-of-subtree t t)
8031 (while (re-search-backward re beg t)
8032 (replace-match "")
8033 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8034 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8036 (defun org-add-planning-info (what &optional time &rest remove)
8037 "Insert new timestamp with keyword in the line directly after the headline.
8038 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8039 If non is given, the user is prompted for a date.
8040 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8041 be removed."
8042 (interactive)
8043 (let (org-time-was-given org-end-time-was-given ts
8044 end default-time default-input)
8046 (when (and (not time) (memq what '(scheduled deadline)))
8047 ;; Try to get a default date/time from existing timestamp
8048 (save-excursion
8049 (org-back-to-heading t)
8050 (setq end (save-excursion (outline-next-heading) (point)))
8051 (when (re-search-forward (if (eq what 'scheduled)
8052 org-scheduled-time-regexp
8053 org-deadline-time-regexp)
8054 end t)
8055 (setq ts (match-string 1)
8056 default-time
8057 (apply 'encode-time (org-parse-time-string ts))
8058 default-input (and ts (org-get-compact-tod ts))))))
8059 (when what
8060 ;; If necessary, get the time from the user
8061 (setq time (or time (org-read-date nil 'to-time nil nil
8062 default-time default-input))))
8064 (when (and org-insert-labeled-timestamps-at-point
8065 (member what '(scheduled deadline)))
8066 (insert
8067 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8068 (org-insert-time-stamp time org-time-was-given
8069 nil nil nil (list org-end-time-was-given))
8070 (setq what nil))
8071 (save-excursion
8072 (save-restriction
8073 (let (col list elt ts buffer-invisibility-spec)
8074 (org-back-to-heading t)
8075 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8076 (goto-char (match-end 1))
8077 (setq col (current-column))
8078 (goto-char (match-end 0))
8079 (if (eobp) (insert "\n") (forward-char 1))
8080 (if (and (not (looking-at outline-regexp))
8081 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8082 "[^\r\n]*"))
8083 (not (equal (match-string 1) org-clock-string)))
8084 (narrow-to-region (match-beginning 0) (match-end 0))
8085 (insert-before-markers "\n")
8086 (backward-char 1)
8087 (narrow-to-region (point) (point))
8088 (indent-to-column col))
8089 ;; Check if we have to remove something.
8090 (setq list (cons what remove))
8091 (while list
8092 (setq elt (pop list))
8093 (goto-char (point-min))
8094 (when (or (and (eq elt 'scheduled)
8095 (re-search-forward org-scheduled-time-regexp nil t))
8096 (and (eq elt 'deadline)
8097 (re-search-forward org-deadline-time-regexp nil t))
8098 (and (eq elt 'closed)
8099 (re-search-forward org-closed-time-regexp nil t)))
8100 (replace-match "")
8101 (if (looking-at "--+<[^>]+>") (replace-match ""))
8102 (if (looking-at " +") (replace-match ""))))
8103 (goto-char (point-max))
8104 (when what
8105 (insert
8106 (if (not (equal (char-before) ?\ )) " " "")
8107 (cond ((eq what 'scheduled) org-scheduled-string)
8108 ((eq what 'deadline) org-deadline-string)
8109 ((eq what 'closed) org-closed-string))
8110 " ")
8111 (setq ts (org-insert-time-stamp
8112 time
8113 (or org-time-was-given
8114 (and (eq what 'closed) org-log-done-with-time))
8115 (eq what 'closed)
8116 nil nil (list org-end-time-was-given)))
8117 (end-of-line 1))
8118 (goto-char (point-min))
8119 (widen)
8120 (if (looking-at "[ \t]+\r?\n")
8121 (replace-match ""))
8122 ts)))))
8124 (defvar org-log-note-marker (make-marker))
8125 (defvar org-log-note-purpose nil)
8126 (defvar org-log-note-state nil)
8127 (defvar org-log-note-how nil)
8128 (defvar org-log-note-window-configuration nil)
8129 (defvar org-log-note-return-to (make-marker))
8130 (defvar org-log-post-message nil
8131 "Message to be displayed after a log note has been stored.
8132 The auto-repeater uses this.")
8134 (defun org-add-note ()
8135 "Add a note to the current entry.
8136 This is done in the same way as adding a state change note."
8137 (interactive)
8138 (org-add-log-setup 'note nil t nil))
8140 (defun org-add-log-setup (&optional purpose state findpos how)
8141 "Set up the post command hook to take a note.
8142 If this is about to TODO state change, the new state is expected in STATE.
8143 When FINDPOS is non-nil, find the correct position for the note in
8144 the current entry. If not, assume that it can be inserted at point."
8145 (save-excursion
8146 (when findpos
8147 (org-back-to-heading t)
8148 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8149 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8150 "[^\r\n]*\\)?"))
8151 (goto-char (match-end 0))
8152 (unless org-log-states-order-reversed
8153 (and (= (char-after) ?\n) (forward-char 1))
8154 (org-skip-over-state-notes)
8155 (skip-chars-backward " \t\n\r")))
8156 (move-marker org-log-note-marker (point))
8157 (setq org-log-note-purpose purpose
8158 org-log-note-state state
8159 org-log-note-how how)
8160 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8162 (defun org-skip-over-state-notes ()
8163 "Skip past the list of State notes in an entry."
8164 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8165 (while (looking-at "[ \t]*- State")
8166 (condition-case nil
8167 (org-next-item)
8168 (error (org-end-of-item)))))
8170 (defun org-add-log-note (&optional purpose)
8171 "Pop up a window for taking a note, and add this note later at point."
8172 (remove-hook 'post-command-hook 'org-add-log-note)
8173 (setq org-log-note-window-configuration (current-window-configuration))
8174 (delete-other-windows)
8175 (move-marker org-log-note-return-to (point))
8176 (switch-to-buffer (marker-buffer org-log-note-marker))
8177 (goto-char org-log-note-marker)
8178 (org-switch-to-buffer-other-window "*Org Note*")
8179 (erase-buffer)
8180 (if (memq org-log-note-how '(time state))
8181 (org-store-log-note)
8182 (let ((org-inhibit-startup t)) (org-mode))
8183 (insert (format "# Insert note for %s.
8184 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8185 (cond
8186 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8187 ((eq org-log-note-purpose 'done) "closed todo item")
8188 ((eq org-log-note-purpose 'state)
8189 (format "state change to \"%s\"" org-log-note-state))
8190 ((eq org-log-note-purpose 'note)
8191 "this entry")
8192 (t (error "This should not happen")))))
8193 (org-set-local 'org-finish-function 'org-store-log-note)))
8195 (defvar org-note-abort nil) ; dynamically scoped
8196 (defun org-store-log-note ()
8197 "Finish taking a log note, and insert it to where it belongs."
8198 (let ((txt (buffer-string))
8199 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8200 lines ind)
8201 (kill-buffer (current-buffer))
8202 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8203 (setq txt (replace-match "" t t txt)))
8204 (if (string-match "\\s-+\\'" txt)
8205 (setq txt (replace-match "" t t txt)))
8206 (setq lines (org-split-string txt "\n"))
8207 (when (and note (string-match "\\S-" note))
8208 (setq note
8209 (org-replace-escapes
8210 note
8211 (list (cons "%u" (user-login-name))
8212 (cons "%U" user-full-name)
8213 (cons "%t" (format-time-string
8214 (org-time-stamp-format 'long 'inactive)
8215 (current-time)))
8216 (cons "%s" (if org-log-note-state
8217 (concat "\"" org-log-note-state "\"")
8218 "")))))
8219 (if lines (setq note (concat note " \\\\")))
8220 (push note lines))
8221 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8222 (when lines
8223 (save-excursion
8224 (set-buffer (marker-buffer org-log-note-marker))
8225 (save-excursion
8226 (goto-char org-log-note-marker)
8227 (move-marker org-log-note-marker nil)
8228 (end-of-line 1)
8229 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8230 (indent-relative nil)
8231 (insert "- " (pop lines))
8232 (org-indent-line-function)
8233 (beginning-of-line 1)
8234 (looking-at "[ \t]*")
8235 (setq ind (concat (match-string 0) " "))
8236 (end-of-line 1)
8237 (while lines (insert "\n" ind (pop lines)))))))
8238 (set-window-configuration org-log-note-window-configuration)
8239 (with-current-buffer (marker-buffer org-log-note-return-to)
8240 (goto-char org-log-note-return-to))
8241 (move-marker org-log-note-return-to nil)
8242 (and org-log-post-message (message "%s" org-log-post-message)))
8244 (defun org-sparse-tree (&optional arg)
8245 "Create a sparse tree, prompt for the details.
8246 This command can create sparse trees. You first need to select the type
8247 of match used to create the tree:
8249 t Show entries with a specific TODO keyword.
8250 T Show entries selected by a tags match.
8251 p Enter a property name and its value (both with completion on existing
8252 names/values) and show entries with that property.
8253 r Show entries matching a regular expression
8254 d Show deadlines due within `org-deadline-warning-days'."
8255 (interactive "P")
8256 (let (ans kwd value)
8257 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8258 (setq ans (read-char-exclusive))
8259 (cond
8260 ((equal ans ?d)
8261 (call-interactively 'org-check-deadlines))
8262 ((equal ans ?b)
8263 (call-interactively 'org-check-before-date))
8264 ((equal ans ?t)
8265 (org-show-todo-tree '(4)))
8266 ((equal ans ?T)
8267 (call-interactively 'org-tags-sparse-tree))
8268 ((member ans '(?p ?P))
8269 (setq kwd (completing-read "Property: "
8270 (mapcar 'list (org-buffer-property-keys))))
8271 (setq value (completing-read "Value: "
8272 (mapcar 'list (org-property-values kwd))))
8273 (unless (string-match "\\`{.*}\\'" value)
8274 (setq value (concat "\"" value "\"")))
8275 (org-tags-sparse-tree arg (concat kwd "=" value)))
8276 ((member ans '(?r ?R ?/))
8277 (call-interactively 'org-occur))
8278 (t (error "No such sparse tree command \"%c\"" ans)))))
8280 (defvar org-occur-highlights nil
8281 "List of overlays used for occur matches.")
8282 (make-variable-buffer-local 'org-occur-highlights)
8283 (defvar org-occur-parameters nil
8284 "Parameters of the active org-occur calls.
8285 This is a list, each call to org-occur pushes as cons cell,
8286 containing the regular expression and the callback, onto the list.
8287 The list can contain several entries if `org-occur' has been called
8288 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8289 will only contain one set of parameters. When the highlights are
8290 removed (for example with `C-c C-c', or with the next edit (depending
8291 on `org-remove-highlights-with-change'), this variable is emptied
8292 as well.")
8293 (make-variable-buffer-local 'org-occur-parameters)
8295 (defun org-occur (regexp &optional keep-previous callback)
8296 "Make a compact tree which shows all matches of REGEXP.
8297 The tree will show the lines where the regexp matches, and all higher
8298 headlines above the match. It will also show the heading after the match,
8299 to make sure editing the matching entry is easy.
8300 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8301 call to `org-occur' will be kept, to allow stacking of calls to this
8302 command.
8303 If CALLBACK is non-nil, it is a function which is called to confirm
8304 that the match should indeed be shown."
8305 (interactive "sRegexp: \nP")
8306 (unless keep-previous
8307 (org-remove-occur-highlights nil nil t))
8308 (push (cons regexp callback) org-occur-parameters)
8309 (let ((cnt 0))
8310 (save-excursion
8311 (goto-char (point-min))
8312 (if (or (not keep-previous) ; do not want to keep
8313 (not org-occur-highlights)) ; no previous matches
8314 ;; hide everything
8315 (org-overview))
8316 (while (re-search-forward regexp nil t)
8317 (when (or (not callback)
8318 (save-match-data (funcall callback)))
8319 (setq cnt (1+ cnt))
8320 (when org-highlight-sparse-tree-matches
8321 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8322 (org-show-context 'occur-tree))))
8323 (when org-remove-highlights-with-change
8324 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8325 nil 'local))
8326 (unless org-sparse-tree-open-archived-trees
8327 (org-hide-archived-subtrees (point-min) (point-max)))
8328 (run-hooks 'org-occur-hook)
8329 (if (interactive-p)
8330 (message "%d match(es) for regexp %s" cnt regexp))
8331 cnt))
8333 (defun org-show-context (&optional key)
8334 "Make sure point and context and visible.
8335 How much context is shown depends upon the variables
8336 `org-show-hierarchy-above', `org-show-following-heading'. and
8337 `org-show-siblings'."
8338 (let ((heading-p (org-on-heading-p t))
8339 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8340 (following-p (org-get-alist-option org-show-following-heading key))
8341 (entry-p (org-get-alist-option org-show-entry-below key))
8342 (siblings-p (org-get-alist-option org-show-siblings key)))
8343 (catch 'exit
8344 ;; Show heading or entry text
8345 (if (and heading-p (not entry-p))
8346 (org-flag-heading nil) ; only show the heading
8347 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8348 (org-show-hidden-entry))) ; show entire entry
8349 (when following-p
8350 ;; Show next sibling, or heading below text
8351 (save-excursion
8352 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8353 (org-flag-heading nil))))
8354 (when siblings-p (org-show-siblings))
8355 (when hierarchy-p
8356 ;; show all higher headings, possibly with siblings
8357 (save-excursion
8358 (while (and (condition-case nil
8359 (progn (org-up-heading-all 1) t)
8360 (error nil))
8361 (not (bobp)))
8362 (org-flag-heading nil)
8363 (when siblings-p (org-show-siblings))))))))
8365 (defun org-reveal (&optional siblings)
8366 "Show current entry, hierarchy above it, and the following headline.
8367 This can be used to show a consistent set of context around locations
8368 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8369 not t for the search context.
8371 With optional argument SIBLINGS, on each level of the hierarchy all
8372 siblings are shown. This repairs the tree structure to what it would
8373 look like when opened with hierarchical calls to `org-cycle'."
8374 (interactive "P")
8375 (let ((org-show-hierarchy-above t)
8376 (org-show-following-heading t)
8377 (org-show-siblings (if siblings t org-show-siblings)))
8378 (org-show-context nil)))
8380 (defun org-highlight-new-match (beg end)
8381 "Highlight from BEG to END and mark the highlight is an occur headline."
8382 (let ((ov (org-make-overlay beg end)))
8383 (org-overlay-put ov 'face 'secondary-selection)
8384 (push ov org-occur-highlights)))
8386 (defun org-remove-occur-highlights (&optional beg end noremove)
8387 "Remove the occur highlights from the buffer.
8388 BEG and END are ignored. If NOREMOVE is nil, remove this function
8389 from the `before-change-functions' in the current buffer."
8390 (interactive)
8391 (unless org-inhibit-highlight-removal
8392 (mapc 'org-delete-overlay org-occur-highlights)
8393 (setq org-occur-highlights nil)
8394 (setq org-occur-parameters nil)
8395 (unless noremove
8396 (remove-hook 'before-change-functions
8397 'org-remove-occur-highlights 'local))))
8399 ;;;; Priorities
8401 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8402 "Regular expression matching the priority indicator.")
8404 (defvar org-remove-priority-next-time nil)
8406 (defun org-priority-up ()
8407 "Increase the priority of the current item."
8408 (interactive)
8409 (org-priority 'up))
8411 (defun org-priority-down ()
8412 "Decrease the priority of the current item."
8413 (interactive)
8414 (org-priority 'down))
8416 (defun org-priority (&optional action)
8417 "Change the priority of an item by ARG.
8418 ACTION can be `set', `up', `down', or a character."
8419 (interactive)
8420 (setq action (or action 'set))
8421 (let (current new news have remove)
8422 (save-excursion
8423 (org-back-to-heading)
8424 (if (looking-at org-priority-regexp)
8425 (setq current (string-to-char (match-string 2))
8426 have t)
8427 (setq current org-default-priority))
8428 (cond
8429 ((or (eq action 'set) (integerp action))
8430 (if (integerp action)
8431 (setq new action)
8432 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
8433 (setq new (read-char-exclusive)))
8434 (if (and (= (upcase org-highest-priority) org-highest-priority)
8435 (= (upcase org-lowest-priority) org-lowest-priority))
8436 (setq new (upcase new)))
8437 (cond ((equal new ?\ ) (setq remove t))
8438 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8439 (error "Priority must be between `%c' and `%c'"
8440 org-highest-priority org-lowest-priority))))
8441 ((eq action 'up)
8442 (if (and (not have) (eq last-command this-command))
8443 (setq new org-lowest-priority)
8444 (setq new (if (and org-priority-start-cycle-with-default (not have))
8445 org-default-priority (1- current)))))
8446 ((eq action 'down)
8447 (if (and (not have) (eq last-command this-command))
8448 (setq new org-highest-priority)
8449 (setq new (if (and org-priority-start-cycle-with-default (not have))
8450 org-default-priority (1+ current)))))
8451 (t (error "Invalid action")))
8452 (if (or (< (upcase new) org-highest-priority)
8453 (> (upcase new) org-lowest-priority))
8454 (setq remove t))
8455 (setq news (format "%c" new))
8456 (if have
8457 (if remove
8458 (replace-match "" t t nil 1)
8459 (replace-match news t t nil 2))
8460 (if remove
8461 (error "No priority cookie found in line")
8462 (looking-at org-todo-line-regexp)
8463 (if (match-end 2)
8464 (progn
8465 (goto-char (match-end 2))
8466 (insert " [#" news "]"))
8467 (goto-char (match-beginning 3))
8468 (insert "[#" news "] ")))))
8469 (org-preserve-lc (org-set-tags nil 'align))
8470 (if remove
8471 (message "Priority removed")
8472 (message "Priority of current item set to %s" news))))
8475 (defun org-get-priority (s)
8476 "Find priority cookie and return priority."
8477 (save-match-data
8478 (if (not (string-match org-priority-regexp s))
8479 (* 1000 (- org-lowest-priority org-default-priority))
8480 (* 1000 (- org-lowest-priority
8481 (string-to-char (match-string 2 s)))))))
8483 ;;;; Tags
8485 (defun org-scan-tags (action matcher &optional todo-only)
8486 "Scan headline tags with inheritance and produce output ACTION.
8487 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8488 evaluated, testing if a given set of tags qualifies a headline for
8489 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8490 are included in the output."
8491 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8492 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8493 (org-re
8494 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8495 (props (list 'face nil
8496 'done-face 'org-done
8497 'undone-face nil
8498 'mouse-face 'highlight
8499 'org-not-done-regexp org-not-done-regexp
8500 'org-todo-regexp org-todo-regexp
8501 'keymap org-agenda-keymap
8502 'help-echo
8503 (format "mouse-2 or RET jump to org file %s"
8504 (abbreviate-file-name
8505 (or (buffer-file-name (buffer-base-buffer))
8506 (buffer-name (buffer-base-buffer)))))))
8507 (case-fold-search nil)
8508 lspos
8509 tags tags-list tags-alist (llast 0) rtn level category i txt
8510 todo marker entry priority)
8511 (save-excursion
8512 (goto-char (point-min))
8513 (when (eq action 'sparse-tree)
8514 (org-overview)
8515 (org-remove-occur-highlights))
8516 (while (re-search-forward re nil t)
8517 (catch :skip
8518 (setq todo (if (match-end 1) (match-string 2))
8519 tags (if (match-end 4) (match-string 4)))
8520 (goto-char (setq lspos (1+ (match-beginning 0))))
8521 (setq level (org-reduced-level (funcall outline-level))
8522 category (org-get-category))
8523 (setq i llast llast level)
8524 ;; remove tag lists from same and sublevels
8525 (while (>= i level)
8526 (when (setq entry (assoc i tags-alist))
8527 (setq tags-alist (delete entry tags-alist)))
8528 (setq i (1- i)))
8529 ;; add the next tags
8530 (when tags
8531 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8532 tags-alist
8533 (cons (cons level tags) tags-alist)))
8534 ;; compile tags for current headline
8535 (setq tags-list
8536 (if org-use-tag-inheritance
8537 (apply 'append (mapcar 'cdr tags-alist))
8538 tags))
8539 (when (and tags org-use-tag-inheritance
8540 (not (eq t org-use-tag-inheritance)))
8541 ;; selective inheritance, remove uninherited ones
8542 (setcdr (car tags-alist)
8543 (org-remove-uniherited-tags (cdar tags-alist))))
8544 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8545 (eval matcher)
8546 (or (not org-agenda-skip-archived-trees)
8547 (not (member org-archive-tag tags-list))))
8548 (and (eq action 'agenda) (org-agenda-skip))
8549 ;; list this headline
8551 (if (eq action 'sparse-tree)
8552 (progn
8553 (and org-highlight-sparse-tree-matches
8554 (org-get-heading) (match-end 0)
8555 (org-highlight-new-match
8556 (match-beginning 0) (match-beginning 1)))
8557 (org-show-context 'tags-tree))
8558 (setq txt (org-format-agenda-item
8560 (concat
8561 (if org-tags-match-list-sublevels
8562 (make-string (1- level) ?.) "")
8563 (org-get-heading))
8564 category tags-list)
8565 priority (org-get-priority txt))
8566 (goto-char lspos)
8567 (setq marker (org-agenda-new-marker))
8568 (org-add-props txt props
8569 'org-marker marker 'org-hd-marker marker 'org-category category
8570 'priority priority 'type "tagsmatch")
8571 (push txt rtn))
8572 ;; if we are to skip sublevels, jump to end of subtree
8573 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8574 (when (and (eq action 'sparse-tree)
8575 (not org-sparse-tree-open-archived-trees))
8576 (org-hide-archived-subtrees (point-min) (point-max)))
8577 (nreverse rtn)))
8579 (defun org-remove-uniherited-tags (tags)
8580 "Remove all tags that are not inherited from the list TAGS."
8581 (cond
8582 ((eq org-use-tag-inheritance t) tags)
8583 ((not org-use-tag-inheritance) nil)
8584 ((stringp org-use-tag-inheritance)
8585 (delq nil (mapcar
8586 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8587 tags)))
8588 ((listp org-use-tag-inheritance)
8589 (org-delete-all org-use-tag-inheritance tags))))
8591 (defvar todo-only) ;; dynamically scoped
8593 (defun org-tags-sparse-tree (&optional todo-only match)
8594 "Create a sparse tree according to tags string MATCH.
8595 MATCH can contain positive and negative selection of tags, like
8596 \"+WORK+URGENT-WITHBOSS\".
8597 If optional argument TODO_ONLY is non-nil, only select lines that are
8598 also TODO lines."
8599 (interactive "P")
8600 (org-prepare-agenda-buffers (list (current-buffer)))
8601 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8603 (defvar org-cached-props nil)
8604 (defun org-cached-entry-get (pom property)
8605 (if (or (eq t org-use-property-inheritance)
8606 (and (stringp org-use-property-inheritance)
8607 (string-match org-use-property-inheritance property))
8608 (and (listp org-use-property-inheritance)
8609 (member property org-use-property-inheritance)))
8610 ;; Caching is not possible, check it directly
8611 (org-entry-get pom property 'inherit)
8612 ;; Get all properties, so that we can do complicated checks easily
8613 (cdr (assoc property (or org-cached-props
8614 (setq org-cached-props
8615 (org-entry-properties pom)))))))
8617 (defun org-global-tags-completion-table (&optional files)
8618 "Return the list of all tags in all agenda buffer/files."
8619 (save-excursion
8620 (org-uniquify
8621 (delq nil
8622 (apply 'append
8623 (mapcar
8624 (lambda (file)
8625 (set-buffer (find-file-noselect file))
8626 (append (org-get-buffer-tags)
8627 (mapcar (lambda (x) (if (stringp (car-safe x))
8628 (list (car-safe x)) nil))
8629 org-tag-alist)))
8630 (if (and files (car files))
8631 files
8632 (org-agenda-files))))))))
8634 (defun org-make-tags-matcher (match)
8635 "Create the TAGS//TODO matcher form for the selection string MATCH."
8636 ;; todo-only is scoped dynamically into this function, and the function
8637 ;; may change it it the matcher asksk for it.
8638 (unless match
8639 ;; Get a new match request, with completion
8640 (let ((org-last-tags-completion-table
8641 (org-global-tags-completion-table)))
8642 (setq match (completing-read
8643 "Match: " 'org-tags-completion-function nil nil nil
8644 'org-tags-history))))
8646 ;; Parse the string and create a lisp form
8647 (let ((match0 match)
8648 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
8649 minus tag mm
8650 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8651 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
8652 (if (string-match "/+" match)
8653 ;; match contains also a todo-matching request
8654 (progn
8655 (setq tagsmatch (substring match 0 (match-beginning 0))
8656 todomatch (substring match (match-end 0)))
8657 (if (string-match "^!" todomatch)
8658 (setq todo-only t todomatch (substring todomatch 1)))
8659 (if (string-match "^\\s-*$" todomatch)
8660 (setq todomatch nil)))
8661 ;; only matching tags
8662 (setq tagsmatch match todomatch nil))
8664 ;; Make the tags matcher
8665 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8666 (setq tagsmatcher t)
8667 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8668 (while (setq term (pop orterms))
8669 (while (and (equal (substring term -1) "\\") orterms)
8670 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8671 (while (string-match re term)
8672 (setq minus (and (match-end 1)
8673 (equal (match-string 1 term) "-"))
8674 tag (match-string 2 term)
8675 re-p (equal (string-to-char tag) ?{)
8676 level-p (match-end 3)
8677 prop-p (match-end 4)
8678 mm (cond
8679 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8680 (level-p `(= level ,(string-to-number
8681 (match-string 3 term))))
8682 (prop-p
8683 (setq pn (match-string 4 term)
8684 pv (match-string 5 term)
8685 cat-p (equal pn "CATEGORY")
8686 re-p (equal (string-to-char pv) ?{)
8687 pv (substring pv 1 -1))
8688 (if (equal pn "CATEGORY")
8689 (setq gv '(get-text-property (point) 'org-category))
8690 (setq gv `(org-cached-entry-get nil ,pn)))
8691 (if re-p
8692 `(string-match ,pv (or ,gv ""))
8693 `(equal ,pv (or ,gv ""))))
8694 (t `(member ,(downcase tag) tags-list)))
8695 mm (if minus (list 'not mm) mm)
8696 term (substring term (match-end 0)))
8697 (push mm tagsmatcher))
8698 (push (if (> (length tagsmatcher) 1)
8699 (cons 'and tagsmatcher)
8700 (car tagsmatcher))
8701 orlist)
8702 (setq tagsmatcher nil))
8703 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8704 (setq tagsmatcher
8705 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8707 ;; Make the todo matcher
8708 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8709 (setq todomatcher t)
8710 (setq orterms (org-split-string todomatch "|") orlist nil)
8711 (while (setq term (pop orterms))
8712 (while (string-match re term)
8713 (setq minus (and (match-end 1)
8714 (equal (match-string 1 term) "-"))
8715 kwd (match-string 2 term)
8716 re-p (equal (string-to-char kwd) ?{)
8717 term (substring term (match-end 0))
8718 mm (if re-p
8719 `(string-match ,(substring kwd 1 -1) todo)
8720 (list 'equal 'todo kwd))
8721 mm (if minus (list 'not mm) mm))
8722 (push mm todomatcher))
8723 (push (if (> (length todomatcher) 1)
8724 (cons 'and todomatcher)
8725 (car todomatcher))
8726 orlist)
8727 (setq todomatcher nil))
8728 (setq todomatcher (if (> (length orlist) 1)
8729 (cons 'or orlist) (car orlist))))
8731 ;; Return the string and lisp forms of the matcher
8732 (setq matcher (if todomatcher
8733 (list 'and tagsmatcher todomatcher)
8734 tagsmatcher))
8735 (cons match0 matcher)))
8737 (defun org-match-any-p (re list)
8738 "Does re match any element of list?"
8739 (setq list (mapcar (lambda (x) (string-match re x)) list))
8740 (delq nil list))
8742 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8743 (defvar org-tags-overlay (org-make-overlay 1 1))
8744 (org-detach-overlay org-tags-overlay)
8746 (defun org-get-tags-at (&optional pos)
8747 "Get a list of all headline tags applicable at POS.
8748 POS defaults to point. If tags are inherited, the list contains
8749 the targets in the same sequence as the headlines appear, i.e.
8750 sthe tags of the current headline come last."
8751 (interactive)
8752 (let (tags ltags lastpos parent)
8753 (save-excursion
8754 (save-restriction
8755 (widen)
8756 (goto-char (or pos (point)))
8757 (save-match-data
8758 (condition-case nil
8759 (progn
8760 (org-back-to-heading t)
8761 (while (not (equal lastpos (point)))
8762 (setq lastpos (point))
8763 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8764 (setq ltags (org-split-string
8765 (org-match-string-no-properties 1) ":"))
8766 (setq tags (append (org-remove-uniherited-tags ltags)
8767 tags)))
8768 (or org-use-tag-inheritance (error ""))
8769 (org-up-heading-all 1)
8770 (setq parent t)))
8771 (error nil))))
8772 tags)))
8774 (defun org-toggle-tag (tag &optional onoff)
8775 "Toggle the tag TAG for the current line.
8776 If ONOFF is `on' or `off', don't toggle but set to this state."
8777 (unless (org-on-heading-p t) (error "Not on headling"))
8778 (let (res current)
8779 (save-excursion
8780 (beginning-of-line)
8781 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8782 (point-at-eol) t)
8783 (progn
8784 (setq current (match-string 1))
8785 (replace-match ""))
8786 (setq current ""))
8787 (setq current (nreverse (org-split-string current ":")))
8788 (cond
8789 ((eq onoff 'on)
8790 (setq res t)
8791 (or (member tag current) (push tag current)))
8792 ((eq onoff 'off)
8793 (or (not (member tag current)) (setq current (delete tag current))))
8794 (t (if (member tag current)
8795 (setq current (delete tag current))
8796 (setq res t)
8797 (push tag current))))
8798 (end-of-line 1)
8799 (if current
8800 (progn
8801 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8802 (org-set-tags nil t))
8803 (delete-horizontal-space))
8804 (run-hooks 'org-after-tags-change-hook))
8805 res))
8807 (defun org-align-tags-here (to-col)
8808 ;; Assumes that this is a headline
8809 (let ((pos (point)) (col (current-column)) tags)
8810 (beginning-of-line 1)
8811 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8812 (< pos (match-beginning 2)))
8813 (progn
8814 (setq tags (match-string 2))
8815 (goto-char (match-beginning 1))
8816 (insert " ")
8817 (delete-region (point) (1+ (match-end 0)))
8818 (backward-char 1)
8819 (move-to-column
8820 (max (1+ (current-column))
8821 (1+ col)
8822 (if (> to-col 0)
8823 to-col
8824 (- (abs to-col) (length tags))))
8826 (insert tags)
8827 (move-to-column (min (current-column) col) t))
8828 (goto-char pos))))
8830 (defun org-set-tags (&optional arg just-align)
8831 "Set the tags for the current headline.
8832 With prefix ARG, realign all tags in headings in the current buffer."
8833 (interactive "P")
8834 (let* ((re (concat "^" outline-regexp))
8835 (current (org-get-tags-string))
8836 (col (current-column))
8837 (org-setting-tags t)
8838 table current-tags inherited-tags ; computed below when needed
8839 tags p0 c0 c1 rpl)
8840 (if arg
8841 (save-excursion
8842 (goto-char (point-min))
8843 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8844 (while (re-search-forward re nil t)
8845 (org-set-tags nil t)
8846 (end-of-line 1)))
8847 (message "All tags realigned to column %d" org-tags-column))
8848 (if just-align
8849 (setq tags current)
8850 ;; Get a new set of tags from the user
8851 (save-excursion
8852 (setq table (or org-tag-alist (org-get-buffer-tags))
8853 org-last-tags-completion-table table
8854 current-tags (org-split-string current ":")
8855 inherited-tags (nreverse
8856 (nthcdr (length current-tags)
8857 (nreverse (org-get-tags-at))))
8858 tags
8859 (if (or (eq t org-use-fast-tag-selection)
8860 (and org-use-fast-tag-selection
8861 (delq nil (mapcar 'cdr table))))
8862 (org-fast-tag-selection
8863 current-tags inherited-tags table
8864 (if org-fast-tag-selection-include-todo org-todo-key-alist))
8865 (let ((org-add-colon-after-tag-completion t))
8866 (org-trim
8867 (org-without-partial-completion
8868 (completing-read "Tags: " 'org-tags-completion-function
8869 nil nil current 'org-tags-history)))))))
8870 (while (string-match "[-+&]+" tags)
8871 ;; No boolean logic, just a list
8872 (setq tags (replace-match ":" t t tags))))
8874 (if (string-match "\\`[\t ]*\\'" tags)
8875 (setq tags "")
8876 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8877 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8879 ;; Insert new tags at the correct column
8880 (beginning-of-line 1)
8881 (cond
8882 ((and (equal current "") (equal tags "")))
8883 ((re-search-forward
8884 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
8885 (point-at-eol) t)
8886 (if (equal tags "")
8887 (setq rpl "")
8888 (goto-char (match-beginning 0))
8889 (setq c0 (current-column) p0 (point)
8890 c1 (max (1+ c0) (if (> org-tags-column 0)
8891 org-tags-column
8892 (- (- org-tags-column) (length tags))))
8893 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
8894 (replace-match rpl t t)
8895 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
8896 tags)
8897 (t (error "Tags alignment failed")))
8898 (move-to-column col)
8899 (unless just-align
8900 (run-hooks 'org-after-tags-change-hook)))))
8902 (defun org-change-tag-in-region (beg end tag off)
8903 "Add or remove TAG for each entry in the region.
8904 This works in the agenda, and also in an org-mode buffer."
8905 (interactive
8906 (list (region-beginning) (region-end)
8907 (let ((org-last-tags-completion-table
8908 (if (org-mode-p)
8909 (org-get-buffer-tags)
8910 (org-global-tags-completion-table))))
8911 (completing-read
8912 "Tag: " 'org-tags-completion-function nil nil nil
8913 'org-tags-history))
8914 (progn
8915 (message "[s]et or [r]emove? ")
8916 (equal (read-char-exclusive) ?r))))
8917 (if (fboundp 'deactivate-mark) (deactivate-mark))
8918 (let ((agendap (equal major-mode 'org-agenda-mode))
8919 l1 l2 m buf pos newhead (cnt 0))
8920 (goto-char end)
8921 (setq l2 (1- (org-current-line)))
8922 (goto-char beg)
8923 (setq l1 (org-current-line))
8924 (loop for l from l1 to l2 do
8925 (goto-line l)
8926 (setq m (get-text-property (point) 'org-hd-marker))
8927 (when (or (and (org-mode-p) (org-on-heading-p))
8928 (and agendap m))
8929 (setq buf (if agendap (marker-buffer m) (current-buffer))
8930 pos (if agendap m (point)))
8931 (with-current-buffer buf
8932 (save-excursion
8933 (save-restriction
8934 (goto-char pos)
8935 (setq cnt (1+ cnt))
8936 (org-toggle-tag tag (if off 'off 'on))
8937 (setq newhead (org-get-heading)))))
8938 (and agendap (org-agenda-change-all-lines newhead m))))
8939 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
8941 (defun org-tags-completion-function (string predicate &optional flag)
8942 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8943 (confirm (lambda (x) (stringp (car x)))))
8944 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8945 (setq s1 (match-string 1 string)
8946 s2 (match-string 2 string))
8947 (setq s1 "" s2 string))
8948 (cond
8949 ((eq flag nil)
8950 ;; try completion
8951 (setq rtn (try-completion s2 ctable confirm))
8952 (if (stringp rtn)
8953 (setq rtn
8954 (concat s1 s2 (substring rtn (length s2))
8955 (if (and org-add-colon-after-tag-completion
8956 (assoc rtn ctable))
8957 ":" ""))))
8958 rtn)
8959 ((eq flag t)
8960 ;; all-completions
8961 (all-completions s2 ctable confirm)
8963 ((eq flag 'lambda)
8964 ;; exact match?
8965 (assoc s2 ctable)))
8968 (defun org-fast-tag-insert (kwd tags face &optional end)
8969 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8970 (insert (format "%-12s" (concat kwd ":"))
8971 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8972 (or end "")))
8974 (defun org-fast-tag-show-exit (flag)
8975 (save-excursion
8976 (goto-line 3)
8977 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
8978 (replace-match ""))
8979 (when flag
8980 (end-of-line 1)
8981 (move-to-column (- (window-width) 19) t)
8982 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
8984 (defun org-set-current-tags-overlay (current prefix)
8985 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
8986 (if (featurep 'xemacs)
8987 (org-overlay-display org-tags-overlay (concat prefix s)
8988 'secondary-selection)
8989 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
8990 (org-overlay-display org-tags-overlay (concat prefix s)))))
8992 (defun org-fast-tag-selection (current inherited table &optional todo-table)
8993 "Fast tag selection with single keys.
8994 CURRENT is the current list of tags in the headline, INHERITED is the
8995 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8996 possibly with grouping information. TODO-TABLE is a similar table with
8997 TODO keywords, should these have keys assigned to them.
8998 If the keys are nil, a-z are automatically assigned.
8999 Returns the new tags string, or nil to not change the current settings."
9000 (let* ((fulltable (append table todo-table))
9001 (maxlen (apply 'max (mapcar
9002 (lambda (x)
9003 (if (stringp (car x)) (string-width (car x)) 0))
9004 fulltable)))
9005 (buf (current-buffer))
9006 (expert (eq org-fast-tag-selection-single-key 'expert))
9007 (buffer-tags nil)
9008 (fwidth (+ maxlen 3 1 3))
9009 (ncol (/ (- (window-width) 4) fwidth))
9010 (i-face 'org-done)
9011 (c-face 'org-todo)
9012 tg cnt e c char c1 c2 ntable tbl rtn
9013 ov-start ov-end ov-prefix
9014 (exit-after-next org-fast-tag-selection-single-key)
9015 (done-keywords org-done-keywords)
9016 groups ingroup)
9017 (save-excursion
9018 (beginning-of-line 1)
9019 (if (looking-at
9020 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9021 (setq ov-start (match-beginning 1)
9022 ov-end (match-end 1)
9023 ov-prefix "")
9024 (setq ov-start (1- (point-at-eol))
9025 ov-end (1+ ov-start))
9026 (skip-chars-forward "^\n\r")
9027 (setq ov-prefix
9028 (concat
9029 (buffer-substring (1- (point)) (point))
9030 (if (> (current-column) org-tags-column)
9032 (make-string (- org-tags-column (current-column)) ?\ ))))))
9033 (org-move-overlay org-tags-overlay ov-start ov-end)
9034 (save-window-excursion
9035 (if expert
9036 (set-buffer (get-buffer-create " *Org tags*"))
9037 (delete-other-windows)
9038 (split-window-vertically)
9039 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9040 (erase-buffer)
9041 (org-set-local 'org-done-keywords done-keywords)
9042 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9043 (org-fast-tag-insert "Current" current c-face "\n\n")
9044 (org-fast-tag-show-exit exit-after-next)
9045 (org-set-current-tags-overlay current ov-prefix)
9046 (setq tbl fulltable char ?a cnt 0)
9047 (while (setq e (pop tbl))
9048 (cond
9049 ((equal e '(:startgroup))
9050 (push '() groups) (setq ingroup t)
9051 (when (not (= cnt 0))
9052 (setq cnt 0)
9053 (insert "\n"))
9054 (insert "{ "))
9055 ((equal e '(:endgroup))
9056 (setq ingroup nil cnt 0)
9057 (insert "}\n"))
9059 (setq tg (car e) c2 nil)
9060 (if (cdr e)
9061 (setq c (cdr e))
9062 ;; automatically assign a character.
9063 (setq c1 (string-to-char
9064 (downcase (substring
9065 tg (if (= (string-to-char tg) ?@) 1 0)))))
9066 (if (or (rassoc c1 ntable) (rassoc c1 table))
9067 (while (or (rassoc char ntable) (rassoc char table))
9068 (setq char (1+ char)))
9069 (setq c2 c1))
9070 (setq c (or c2 char)))
9071 (if ingroup (push tg (car groups)))
9072 (setq tg (org-add-props tg nil 'face
9073 (cond
9074 ((not (assoc tg table))
9075 (org-get-todo-face tg))
9076 ((member tg current) c-face)
9077 ((member tg inherited) i-face)
9078 (t nil))))
9079 (if (and (= cnt 0) (not ingroup)) (insert " "))
9080 (insert "[" c "] " tg (make-string
9081 (- fwidth 4 (length tg)) ?\ ))
9082 (push (cons tg c) ntable)
9083 (when (= (setq cnt (1+ cnt)) ncol)
9084 (insert "\n")
9085 (if ingroup (insert " "))
9086 (setq cnt 0)))))
9087 (setq ntable (nreverse ntable))
9088 (insert "\n")
9089 (goto-char (point-min))
9090 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9091 (fit-window-to-buffer))
9092 (setq rtn
9093 (catch 'exit
9094 (while t
9095 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9096 (if groups " [!] no groups" " [!]groups")
9097 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9098 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9099 (cond
9100 ((= c ?\r) (throw 'exit t))
9101 ((= c ?!)
9102 (setq groups (not groups))
9103 (goto-char (point-min))
9104 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9105 ((= c ?\C-c)
9106 (if (not expert)
9107 (org-fast-tag-show-exit
9108 (setq exit-after-next (not exit-after-next)))
9109 (setq expert nil)
9110 (delete-other-windows)
9111 (split-window-vertically)
9112 (org-switch-to-buffer-other-window " *Org tags*")
9113 (and (fboundp 'fit-window-to-buffer)
9114 (fit-window-to-buffer))))
9115 ((or (= c ?\C-g)
9116 (and (= c ?q) (not (rassoc c ntable))))
9117 (org-detach-overlay org-tags-overlay)
9118 (setq quit-flag t))
9119 ((= c ?\ )
9120 (setq current nil)
9121 (if exit-after-next (setq exit-after-next 'now)))
9122 ((= c ?\t)
9123 (condition-case nil
9124 (setq tg (completing-read
9125 "Tag: "
9126 (or buffer-tags
9127 (with-current-buffer buf
9128 (org-get-buffer-tags)))))
9129 (quit (setq tg "")))
9130 (when (string-match "\\S-" tg)
9131 (add-to-list 'buffer-tags (list tg))
9132 (if (member tg current)
9133 (setq current (delete tg current))
9134 (push tg current)))
9135 (if exit-after-next (setq exit-after-next 'now)))
9136 ((setq e (rassoc c todo-table) tg (car e))
9137 (with-current-buffer buf
9138 (save-excursion (org-todo tg)))
9139 (if exit-after-next (setq exit-after-next 'now)))
9140 ((setq e (rassoc c ntable) tg (car e))
9141 (if (member tg current)
9142 (setq current (delete tg current))
9143 (loop for g in groups do
9144 (if (member tg g)
9145 (mapc (lambda (x)
9146 (setq current (delete x current)))
9147 g)))
9148 (push tg current))
9149 (if exit-after-next (setq exit-after-next 'now))))
9151 ;; Create a sorted list
9152 (setq current
9153 (sort current
9154 (lambda (a b)
9155 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9156 (if (eq exit-after-next 'now) (throw 'exit t))
9157 (goto-char (point-min))
9158 (beginning-of-line 2)
9159 (delete-region (point) (point-at-eol))
9160 (org-fast-tag-insert "Current" current c-face)
9161 (org-set-current-tags-overlay current ov-prefix)
9162 (while (re-search-forward
9163 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9164 (setq tg (match-string 1))
9165 (add-text-properties
9166 (match-beginning 1) (match-end 1)
9167 (list 'face
9168 (cond
9169 ((member tg current) c-face)
9170 ((member tg inherited) i-face)
9171 (t (get-text-property (match-beginning 1) 'face))))))
9172 (goto-char (point-min)))))
9173 (org-detach-overlay org-tags-overlay)
9174 (if rtn
9175 (mapconcat 'identity current ":")
9176 nil))))
9178 (defun org-get-tags-string ()
9179 "Get the TAGS string in the current headline."
9180 (unless (org-on-heading-p t)
9181 (error "Not on a heading"))
9182 (save-excursion
9183 (beginning-of-line 1)
9184 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9185 (org-match-string-no-properties 1)
9186 "")))
9188 (defun org-get-tags ()
9189 "Get the list of tags specified in the current headline."
9190 (org-split-string (org-get-tags-string) ":"))
9192 (defun org-get-buffer-tags ()
9193 "Get a table of all tags used in the buffer, for completion."
9194 (let (tags)
9195 (save-excursion
9196 (goto-char (point-min))
9197 (while (re-search-forward
9198 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9199 (when (equal (char-after (point-at-bol 0)) ?*)
9200 (mapc (lambda (x) (add-to-list 'tags x))
9201 (org-split-string (org-match-string-no-properties 1) ":")))))
9202 (mapcar 'list tags)))
9205 ;;;; Properties
9207 ;;; Setting and retrieving properties
9209 (defconst org-special-properties
9210 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9211 "TIMESTAMP" "TIMESTAMP_IA")
9212 "The special properties valid in Org-mode.
9214 These are properties that are not defined in the property drawer,
9215 but in some other way.")
9217 (defconst org-default-properties
9218 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9219 "LOCATION" "LOGGING" "COLUMNS")
9220 "Some properties that are used by Org-mode for various purposes.
9221 Being in this list makes sure that they are offered for completion.")
9223 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9224 "Regular expression matching the first line of a property drawer.")
9226 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9227 "Regular expression matching the first line of a property drawer.")
9229 (defun org-property-action ()
9230 "Do an action on properties."
9231 (interactive)
9232 (let (c)
9233 (org-at-property-p)
9234 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9235 (setq c (read-char-exclusive))
9236 (cond
9237 ((equal c ?s)
9238 (call-interactively 'org-set-property))
9239 ((equal c ?d)
9240 (call-interactively 'org-delete-property))
9241 ((equal c ?D)
9242 (call-interactively 'org-delete-property-globally))
9243 ((equal c ?c)
9244 (call-interactively 'org-compute-property-at-point))
9245 (t (error "No such property action %c" c)))))
9247 (defun org-at-property-p ()
9248 "Is the cursor in a property line?"
9249 ;; FIXME: Does not check if we are actually in the drawer.
9250 ;; FIXME: also returns true on any drawers.....
9251 ;; This is used by C-c C-c for property action.
9252 (save-excursion
9253 (beginning-of-line 1)
9254 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9256 (defun org-get-property-block (&optional beg end force)
9257 "Return the (beg . end) range of the body of the property drawer.
9258 BEG and END can be beginning and end of subtree, if not given
9259 they will be found.
9260 If the drawer does not exist and FORCE is non-nil, create the drawer."
9261 (catch 'exit
9262 (save-excursion
9263 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9264 (end (or end (progn (outline-next-heading) (point)))))
9265 (goto-char beg)
9266 (if (re-search-forward org-property-start-re end t)
9267 (setq beg (1+ (match-end 0)))
9268 (if force
9269 (save-excursion
9270 (org-insert-property-drawer)
9271 (setq end (progn (outline-next-heading) (point))))
9272 (throw 'exit nil))
9273 (goto-char beg)
9274 (if (re-search-forward org-property-start-re end t)
9275 (setq beg (1+ (match-end 0)))))
9276 (if (re-search-forward org-property-end-re end t)
9277 (setq end (match-beginning 0))
9278 (or force (throw 'exit nil))
9279 (goto-char beg)
9280 (setq end beg)
9281 (org-indent-line-function)
9282 (insert ":END:\n"))
9283 (cons beg end)))))
9285 (defun org-entry-properties (&optional pom which)
9286 "Get all properties of the entry at point-or-marker POM.
9287 This includes the TODO keyword, the tags, time strings for deadline,
9288 scheduled, and clocking, and any additional properties defined in the
9289 entry. The return value is an alist, keys may occur multiple times
9290 if the property key was used several times.
9291 POM may also be nil, in which case the current entry is used.
9292 If WHICH is nil or `all', get all properties. If WHICH is
9293 `special' or `standard', only get that subclass."
9294 (setq which (or which 'all))
9295 (org-with-point-at pom
9296 (let ((clockstr (substring org-clock-string 0 -1))
9297 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9298 beg end range props sum-props key value string clocksum)
9299 (save-excursion
9300 (when (condition-case nil (org-back-to-heading t) (error nil))
9301 (setq beg (point))
9302 (setq sum-props (get-text-property (point) 'org-summaries))
9303 (setq clocksum (get-text-property (point) :org-clock-minutes))
9304 (outline-next-heading)
9305 (setq end (point))
9306 (when (memq which '(all special))
9307 ;; Get the special properties, like TODO and tags
9308 (goto-char beg)
9309 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9310 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9311 (when (looking-at org-priority-regexp)
9312 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9313 (when (and (setq value (org-get-tags-string))
9314 (string-match "\\S-" value))
9315 (push (cons "TAGS" value) props))
9316 (when (setq value (org-get-tags-at))
9317 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9318 props))
9319 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9320 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9321 string (if (equal key clockstr)
9322 (org-no-properties
9323 (org-trim
9324 (buffer-substring
9325 (match-beginning 3) (goto-char (point-at-eol)))))
9326 (substring (org-match-string-no-properties 3) 1 -1)))
9327 (unless key
9328 (if (= (char-after (match-beginning 3)) ?\[)
9329 (setq key "TIMESTAMP_IA")
9330 (setq key "TIMESTAMP")))
9331 (when (or (equal key clockstr) (not (assoc key props)))
9332 (push (cons key string) props)))
9336 (when (memq which '(all standard))
9337 ;; Get the standard properties, like :PORP: ...
9338 (setq range (org-get-property-block beg end))
9339 (when range
9340 (goto-char (car range))
9341 (while (re-search-forward
9342 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9343 (cdr range) t)
9344 (setq key (org-match-string-no-properties 1)
9345 value (org-trim (or (org-match-string-no-properties 2) "")))
9346 (unless (member key excluded)
9347 (push (cons key (or value "")) props)))))
9348 (if clocksum
9349 (push (cons "CLOCKSUM"
9350 (org-columns-number-to-string (/ (float clocksum) 60.)
9351 'add_times))
9352 props))
9353 (append sum-props (nreverse props)))))))
9355 (defun org-entry-get (pom property &optional inherit)
9356 "Get value of PROPERTY for entry at point-or-marker POM.
9357 If INHERIT is non-nil and the entry does not have the property,
9358 then also check higher levels of the hierarchy.
9359 If INHERIT is the symbol `selective', use inheritance only if the setting
9360 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9361 If the property is present but empty, the return value is the empty string.
9362 If the property is not present at all, nil is returned."
9363 (org-with-point-at pom
9364 (if (and inherit (if (eq inherit 'selective)
9365 (org-property-inherit-p property)
9367 (org-entry-get-with-inheritance property)
9368 (if (member property org-special-properties)
9369 ;; We need a special property. Use brute force, get all properties.
9370 (cdr (assoc property (org-entry-properties nil 'special)))
9371 (let ((range (org-get-property-block)))
9372 (if (and range
9373 (goto-char (car range))
9374 (re-search-forward
9375 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9376 (cdr range) t))
9377 ;; Found the property, return it.
9378 (if (match-end 1)
9379 (org-match-string-no-properties 1)
9380 "")))))))
9382 (defun org-property-or-variable-value (var &optional inherit)
9383 "Check if there is a property fixing the value of VAR.
9384 If yes, return this value. If not, return the current value of the variable."
9385 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9386 (if (and prop (stringp prop) (string-match "\\S-" prop))
9387 (read prop)
9388 (symbol-value var))))
9390 (defun org-entry-delete (pom property)
9391 "Delete the property PROPERTY from entry at point-or-marker POM."
9392 (org-with-point-at pom
9393 (if (member property org-special-properties)
9394 nil ; cannot delete these properties.
9395 (let ((range (org-get-property-block)))
9396 (if (and range
9397 (goto-char (car range))
9398 (re-search-forward
9399 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9400 (cdr range) t))
9401 (progn
9402 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9404 nil)))))
9406 ;; Multi-values properties are properties that contain multiple values
9407 ;; These values are assumed to be single words, separated by whitespace.
9408 (defun org-entry-add-to-multivalued-property (pom property value)
9409 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9410 (let* ((old (org-entry-get pom property))
9411 (values (and old (org-split-string old "[ \t]"))))
9412 (unless (member value values)
9413 (setq values (cons value values))
9414 (org-entry-put pom property
9415 (mapconcat 'identity values " ")))))
9417 (defun org-entry-remove-from-multivalued-property (pom property value)
9418 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9419 (let* ((old (org-entry-get pom property))
9420 (values (and old (org-split-string old "[ \t]"))))
9421 (when (member value values)
9422 (setq values (delete value values))
9423 (org-entry-put pom property
9424 (mapconcat 'identity values " ")))))
9426 (defun org-entry-member-in-multivalued-property (pom property value)
9427 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9428 (let* ((old (org-entry-get pom property))
9429 (values (and old (org-split-string old "[ \t]"))))
9430 (member value values)))
9432 (defvar org-entry-property-inherited-from (make-marker))
9434 (defun org-entry-get-with-inheritance (property)
9435 "Get entry property, and search higher levels if not present."
9436 (let (tmp)
9437 (save-excursion
9438 (save-restriction
9439 (widen)
9440 (catch 'ex
9441 (while t
9442 (when (setq tmp (org-entry-get nil property))
9443 (org-back-to-heading t)
9444 (move-marker org-entry-property-inherited-from (point))
9445 (throw 'ex tmp))
9446 (or (org-up-heading-safe) (throw 'ex nil)))))
9447 (or tmp (cdr (assoc property org-local-properties))
9448 (cdr (assoc property org-global-properties))))))
9450 (defun org-entry-put (pom property value)
9451 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9452 (org-with-point-at pom
9453 (org-back-to-heading t)
9454 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9455 range)
9456 (cond
9457 ((equal property "TODO")
9458 (when (and (stringp value) (string-match "\\S-" value)
9459 (not (member value org-todo-keywords-1)))
9460 (error "\"%s\" is not a valid TODO state" value))
9461 (if (or (not value)
9462 (not (string-match "\\S-" value)))
9463 (setq value 'none))
9464 (org-todo value)
9465 (org-set-tags nil 'align))
9466 ((equal property "PRIORITY")
9467 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9468 (string-to-char value) ?\ ))
9469 (org-set-tags nil 'align))
9470 ((equal property "SCHEDULED")
9471 (if (re-search-forward org-scheduled-time-regexp end t)
9472 (cond
9473 ((eq value 'earlier) (org-timestamp-change -1 'day))
9474 ((eq value 'later) (org-timestamp-change 1 'day))
9475 (t (call-interactively 'org-schedule)))
9476 (call-interactively 'org-schedule)))
9477 ((equal property "DEADLINE")
9478 (if (re-search-forward org-deadline-time-regexp end t)
9479 (cond
9480 ((eq value 'earlier) (org-timestamp-change -1 'day))
9481 ((eq value 'later) (org-timestamp-change 1 'day))
9482 (t (call-interactively 'org-deadline)))
9483 (call-interactively 'org-deadline)))
9484 ((member property org-special-properties)
9485 (error "The %s property can not yet be set with `org-entry-put'"
9486 property))
9487 (t ; a non-special property
9488 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9489 (setq range (org-get-property-block beg end 'force))
9490 (goto-char (car range))
9491 (if (re-search-forward
9492 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9493 (progn
9494 (delete-region (match-beginning 1) (match-end 1))
9495 (goto-char (match-beginning 1)))
9496 (goto-char (cdr range))
9497 (insert "\n")
9498 (backward-char 1)
9499 (org-indent-line-function)
9500 (insert ":" property ":"))
9501 (and value (insert " " value))
9502 (org-indent-line-function)))))))
9504 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9505 "Get all property keys in the current buffer.
9506 With INCLUDE-SPECIALS, also list the special properties that relect things
9507 like tags and TODO state.
9508 With INCLUDE-DEFAULTS, also include properties that has special meaning
9509 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9510 With INCLUDE-COLUMNS, also include property names given in COLUMN
9511 formats in the current buffer."
9512 (let (rtn range cfmt cols s p)
9513 (save-excursion
9514 (save-restriction
9515 (widen)
9516 (goto-char (point-min))
9517 (while (re-search-forward org-property-start-re nil t)
9518 (setq range (org-get-property-block))
9519 (goto-char (car range))
9520 (while (re-search-forward
9521 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9522 (cdr range) t)
9523 (add-to-list 'rtn (org-match-string-no-properties 1)))
9524 (outline-next-heading))))
9526 (when include-specials
9527 (setq rtn (append org-special-properties rtn)))
9529 (when include-defaults
9530 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9532 (when include-columns
9533 (save-excursion
9534 (save-restriction
9535 (widen)
9536 (goto-char (point-min))
9537 (while (re-search-forward
9538 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9539 nil t)
9540 (setq cfmt (match-string 2) s 0)
9541 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9542 cfmt s)
9543 (setq s (match-end 0)
9544 p (match-string 1 cfmt))
9545 (unless (or (equal p "ITEM")
9546 (member p org-special-properties))
9547 (add-to-list 'rtn (match-string 1 cfmt))))))))
9549 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9551 (defun org-property-values (key)
9552 "Return a list of all values of property KEY."
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (point-min))
9557 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9558 values)
9559 (while (re-search-forward re nil t)
9560 (add-to-list 'values (org-trim (match-string 1))))
9561 (delete "" values)))))
9563 (defun org-insert-property-drawer ()
9564 "Insert a property drawer into the current entry."
9565 (interactive)
9566 (org-back-to-heading t)
9567 (looking-at outline-regexp)
9568 (let ((indent (- (match-end 0)(match-beginning 0)))
9569 (beg (point))
9570 (re (concat "^[ \t]*" org-keyword-time-regexp))
9571 end hiddenp)
9572 (outline-next-heading)
9573 (setq end (point))
9574 (goto-char beg)
9575 (while (re-search-forward re end t))
9576 (setq hiddenp (org-invisible-p))
9577 (end-of-line 1)
9578 (and (equal (char-after) ?\n) (forward-char 1))
9579 (org-skip-over-state-notes)
9580 (skip-chars-backward " \t\n\r")
9581 (if (eq (char-before) ?*) (forward-char 1))
9582 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9583 (beginning-of-line 0)
9584 (indent-to-column indent)
9585 (beginning-of-line 2)
9586 (indent-to-column indent)
9587 (beginning-of-line 0)
9588 (if hiddenp
9589 (save-excursion
9590 (org-back-to-heading t)
9591 (hide-entry))
9592 (org-flag-drawer t))))
9594 (defun org-set-property (property value)
9595 "In the current entry, set PROPERTY to VALUE.
9596 When called interactively, this will prompt for a property name, offering
9597 completion on existing and default properties. And then it will prompt
9598 for a value, offering competion either on allowed values (via an inherited
9599 xxx_ALL property) or on existing values in other instances of this property
9600 in the current file."
9601 (interactive
9602 (let* ((prop (completing-read
9603 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9604 (cur (org-entry-get nil prop))
9605 (allowed (org-property-get-allowed-values nil prop 'table))
9606 (existing (mapcar 'list (org-property-values prop)))
9607 (val (if allowed
9608 (completing-read "Value: " allowed nil 'req-match)
9609 (completing-read
9610 (concat "Value" (if (and cur (string-match "\\S-" cur))
9611 (concat "[" cur "]") "")
9612 ": ")
9613 existing nil nil "" nil cur))))
9614 (list prop (if (equal val "") cur val))))
9615 (unless (equal (org-entry-get nil property) value)
9616 (org-entry-put nil property value)))
9618 (defun org-delete-property (property)
9619 "In the current entry, delete PROPERTY."
9620 (interactive
9621 (let* ((prop (completing-read
9622 "Property: " (org-entry-properties nil 'standard))))
9623 (list prop)))
9624 (message "Property %s %s" property
9625 (if (org-entry-delete nil property)
9626 "deleted"
9627 "was not present in the entry")))
9629 (defun org-delete-property-globally (property)
9630 "Remove PROPERTY globally, from all entries."
9631 (interactive
9632 (let* ((prop (completing-read
9633 "Globally remove property: "
9634 (mapcar 'list (org-buffer-property-keys)))))
9635 (list prop)))
9636 (save-excursion
9637 (save-restriction
9638 (widen)
9639 (goto-char (point-min))
9640 (let ((cnt 0))
9641 (while (re-search-forward
9642 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9643 nil t)
9644 (setq cnt (1+ cnt))
9645 (replace-match ""))
9646 (message "Property \"%s\" removed from %d entries" property cnt)))))
9648 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9650 (defun org-compute-property-at-point ()
9651 "Compute the property at point.
9652 This looks for an enclosing column format, extracts the operator and
9653 then applies it to the proerty in the column format's scope."
9654 (interactive)
9655 (unless (org-at-property-p)
9656 (error "Not at a property"))
9657 (let ((prop (org-match-string-no-properties 2)))
9658 (org-columns-get-format-and-top-level)
9659 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9660 (error "No operator defined for property %s" prop))
9661 (org-columns-compute prop)))
9663 (defun org-property-get-allowed-values (pom property &optional table)
9664 "Get allowed values for the property PROPERTY.
9665 When TABLE is non-nil, return an alist that can directly be used for
9666 completion."
9667 (let (vals)
9668 (cond
9669 ((equal property "TODO")
9670 (setq vals (org-with-point-at pom
9671 (append org-todo-keywords-1 '("")))))
9672 ((equal property "PRIORITY")
9673 (let ((n org-lowest-priority))
9674 (while (>= n org-highest-priority)
9675 (push (char-to-string n) vals)
9676 (setq n (1- n)))))
9677 ((member property org-special-properties))
9679 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9681 (when (and vals (string-match "\\S-" vals))
9682 (setq vals (car (read-from-string (concat "(" vals ")"))))
9683 (setq vals (mapcar (lambda (x)
9684 (cond ((stringp x) x)
9685 ((numberp x) (number-to-string x))
9686 ((symbolp x) (symbol-name x))
9687 (t "???")))
9688 vals)))))
9689 (if table (mapcar 'list vals) vals)))
9691 (defun org-property-previous-allowed-value (&optional previous)
9692 "Switch to the next allowed value for this property."
9693 (interactive)
9694 (org-property-next-allowed-value t))
9696 (defun org-property-next-allowed-value (&optional previous)
9697 "Switch to the next allowed value for this property."
9698 (interactive)
9699 (unless (org-at-property-p)
9700 (error "Not at a property"))
9701 (let* ((key (match-string 2))
9702 (value (match-string 3))
9703 (allowed (or (org-property-get-allowed-values (point) key)
9704 (and (member value '("[ ]" "[-]" "[X]"))
9705 '("[ ]" "[X]"))))
9706 nval)
9707 (unless allowed
9708 (error "Allowed values for this property have not been defined"))
9709 (if previous (setq allowed (reverse allowed)))
9710 (if (member value allowed)
9711 (setq nval (car (cdr (member value allowed)))))
9712 (setq nval (or nval (car allowed)))
9713 (if (equal nval value)
9714 (error "Only one allowed value for this property"))
9715 (org-at-property-p)
9716 (replace-match (concat " :" key ": " nval) t t)
9717 (org-indent-line-function)
9718 (beginning-of-line 1)
9719 (skip-chars-forward " \t")))
9721 (defun org-find-entry-with-id (ident)
9722 "Locate the entry that contains the ID property with exact value IDENT.
9723 IDENT can be a string, a symbol or a number, this function will search for
9724 the string representation of it.
9725 Return the position where this entry starts, or nil if there is no such entry."
9726 (let ((id (cond
9727 ((stringp ident) ident)
9728 ((symbol-name ident) (symbol-name ident))
9729 ((numberp ident) (number-to-string ident))
9730 (t (error "IDENT %s must be a string, symbol or number" ident))))
9731 (case-fold-search nil))
9732 (save-excursion
9733 (save-restriction
9734 (widen)
9735 (goto-char (point-min))
9736 (when (re-search-forward
9737 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9738 nil t)
9739 (org-back-to-heading)
9740 (point))))))
9742 ;;;; Timestamps
9744 (defvar org-last-changed-timestamp nil)
9745 (defvar org-time-was-given) ; dynamically scoped parameter
9746 (defvar org-end-time-was-given) ; dynamically scoped parameter
9747 (defvar org-ts-what) ; dynamically scoped parameter
9749 (defun org-time-stamp (arg)
9750 "Prompt for a date/time and insert a time stamp.
9751 If the user specifies a time like HH:MM, or if this command is called
9752 with a prefix argument, the time stamp will contain date and time.
9753 Otherwise, only the date will be included. All parts of a date not
9754 specified by the user will be filled in from the current date/time.
9755 So if you press just return without typing anything, the time stamp
9756 will represent the current date/time. If there is already a timestamp
9757 at the cursor, it will be modified."
9758 (interactive "P")
9759 (let* ((ts nil)
9760 (default-time
9761 ;; Default time is either today, or, when entering a range,
9762 ;; the range start.
9763 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9764 (save-excursion
9765 (re-search-backward
9766 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9767 (- (point) 20) t)))
9768 (apply 'encode-time (org-parse-time-string (match-string 1)))
9769 (current-time)))
9770 (default-input (and ts (org-get-compact-tod ts)))
9771 org-time-was-given org-end-time-was-given time)
9772 (cond
9773 ((and (org-at-timestamp-p)
9774 (eq last-command 'org-time-stamp)
9775 (eq this-command 'org-time-stamp))
9776 (insert "--")
9777 (setq time (let ((this-command this-command))
9778 (org-read-date arg 'totime nil nil default-time default-input)))
9779 (org-insert-time-stamp time (or org-time-was-given arg)))
9780 ((org-at-timestamp-p)
9781 (setq time (let ((this-command this-command))
9782 (org-read-date arg 'totime nil nil default-time default-input)))
9783 (when (org-at-timestamp-p) ; just to get the match data
9784 (replace-match "")
9785 (setq org-last-changed-timestamp
9786 (org-insert-time-stamp
9787 time (or org-time-was-given arg)
9788 nil nil nil (list org-end-time-was-given))))
9789 (message "Timestamp updated"))
9791 (setq time (let ((this-command this-command))
9792 (org-read-date arg 'totime nil nil default-time default-input)))
9793 (org-insert-time-stamp time (or org-time-was-given arg)
9794 nil nil nil (list org-end-time-was-given))))))
9796 ;; FIXME: can we use this for something else, like computing time differences?
9797 (defun org-get-compact-tod (s)
9798 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9799 (let* ((t1 (match-string 1 s))
9800 (h1 (string-to-number (match-string 2 s)))
9801 (m1 (string-to-number (match-string 3 s)))
9802 (t2 (and (match-end 4) (match-string 5 s)))
9803 (h2 (and t2 (string-to-number (match-string 6 s))))
9804 (m2 (and t2 (string-to-number (match-string 7 s))))
9805 dh dm)
9806 (if (not t2)
9808 (setq dh (- h2 h1) dm (- m2 m1))
9809 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9810 (concat t1 "+" (number-to-string dh)
9811 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9813 (defun org-time-stamp-inactive (&optional arg)
9814 "Insert an inactive time stamp.
9815 An inactive time stamp is enclosed in square brackets instead of angle
9816 brackets. It is inactive in the sense that it does not trigger agenda entries,
9817 does not link to the calendar and cannot be changed with the S-cursor keys.
9818 So these are more for recording a certain time/date."
9819 (interactive "P")
9820 (let (org-time-was-given org-end-time-was-given time)
9821 (setq time (org-read-date arg 'totime))
9822 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9823 nil nil (list org-end-time-was-given))))
9825 (defvar org-date-ovl (org-make-overlay 1 1))
9826 (org-overlay-put org-date-ovl 'face 'org-warning)
9827 (org-detach-overlay org-date-ovl)
9829 (defvar org-ans1) ; dynamically scoped parameter
9830 (defvar org-ans2) ; dynamically scoped parameter
9832 (defvar org-plain-time-of-day-regexp) ; defined below
9834 (defvar org-read-date-overlay nil)
9835 (defvar org-dcst nil) ; dynamically scoped
9837 (defun org-read-date (&optional with-time to-time from-string prompt
9838 default-time default-input)
9839 "Read a date, possibly a time, and make things smooth for the user.
9840 The prompt will suggest to enter an ISO date, but you can also enter anything
9841 which will at least partially be understood by `parse-time-string'.
9842 Unrecognized parts of the date will default to the current day, month, year,
9843 hour and minute. If this command is called to replace a timestamp at point,
9844 of to enter the second timestamp of a range, the default time is taken from the
9845 existing stamp. For example,
9846 3-2-5 --> 2003-02-05
9847 feb 15 --> currentyear-02-15
9848 sep 12 9 --> 2009-09-12
9849 12:45 --> today 12:45
9850 22 sept 0:34 --> currentyear-09-22 0:34
9851 12 --> currentyear-currentmonth-12
9852 Fri --> nearest Friday (today or later)
9853 etc.
9855 Furthermore you can specify a relative date by giving, as the *first* thing
9856 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
9857 change in days weeks, months, years.
9858 With a single plus or minus, the date is relative to today. With a double
9859 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
9860 +4d --> four days from today
9861 +4 --> same as above
9862 +2w --> two weeks from today
9863 ++5 --> five days from default date
9865 The function understands only English month and weekday abbreviations,
9866 but this can be configured with the variables `parse-time-months' and
9867 `parse-time-weekdays'.
9869 While prompting, a calendar is popped up - you can also select the
9870 date with the mouse (button 1). The calendar shows a period of three
9871 months. To scroll it to other months, use the keys `>' and `<'.
9872 If you don't like the calendar, turn it off with
9873 \(setq org-read-date-popup-calendar nil)
9875 With optional argument TO-TIME, the date will immediately be converted
9876 to an internal time.
9877 With an optional argument WITH-TIME, the prompt will suggest to also
9878 insert a time. Note that when WITH-TIME is not set, you can still
9879 enter a time, and this function will inform the calling routine about
9880 this change. The calling routine may then choose to change the format
9881 used to insert the time stamp into the buffer to include the time.
9882 With optional argument FROM-STRING, read from this string instead from
9883 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
9884 the time/date that is used for everything that is not specified by the
9885 user."
9886 (require 'parse-time)
9887 (let* ((org-time-stamp-rounding-minutes
9888 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
9889 (org-dcst org-display-custom-times)
9890 (ct (org-current-time))
9891 (def (or default-time ct))
9892 (defdecode (decode-time def))
9893 (dummy (progn
9894 (when (< (nth 2 defdecode) org-extend-today-until)
9895 (setcar (nthcdr 2 defdecode) -1)
9896 (setcar (nthcdr 1 defdecode) 59)
9897 (setq def (apply 'encode-time defdecode)
9898 defdecode (decode-time def)))))
9899 (calendar-move-hook nil)
9900 (calendar-view-diary-initially-flag nil)
9901 (view-diary-entries-initially nil)
9902 (calendar-view-holidays-initially-flag nil)
9903 (view-calendar-holidays-initially nil)
9904 (timestr (format-time-string
9905 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
9906 (prompt (concat (if prompt (concat prompt " ") "")
9907 (format "Date+time [%s]: " timestr)))
9908 ans (org-ans0 "") org-ans1 org-ans2 final)
9910 (cond
9911 (from-string (setq ans from-string))
9912 (org-read-date-popup-calendar
9913 (save-excursion
9914 (save-window-excursion
9915 (calendar)
9916 (calendar-forward-day (- (time-to-days def)
9917 (calendar-absolute-from-gregorian
9918 (calendar-current-date))))
9919 (org-eval-in-calendar nil t)
9920 (let* ((old-map (current-local-map))
9921 (map (copy-keymap calendar-mode-map))
9922 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
9923 (org-defkey map (kbd "RET") 'org-calendar-select)
9924 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
9925 'org-calendar-select-mouse)
9926 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
9927 'org-calendar-select-mouse)
9928 (org-defkey minibuffer-local-map [(meta shift left)]
9929 (lambda () (interactive)
9930 (org-eval-in-calendar '(calendar-backward-month 1))))
9931 (org-defkey minibuffer-local-map [(meta shift right)]
9932 (lambda () (interactive)
9933 (org-eval-in-calendar '(calendar-forward-month 1))))
9934 (org-defkey minibuffer-local-map [(meta shift up)]
9935 (lambda () (interactive)
9936 (org-eval-in-calendar '(calendar-backward-year 1))))
9937 (org-defkey minibuffer-local-map [(meta shift down)]
9938 (lambda () (interactive)
9939 (org-eval-in-calendar '(calendar-forward-year 1))))
9940 (org-defkey minibuffer-local-map [(shift up)]
9941 (lambda () (interactive)
9942 (org-eval-in-calendar '(calendar-backward-week 1))))
9943 (org-defkey minibuffer-local-map [(shift down)]
9944 (lambda () (interactive)
9945 (org-eval-in-calendar '(calendar-forward-week 1))))
9946 (org-defkey minibuffer-local-map [(shift left)]
9947 (lambda () (interactive)
9948 (org-eval-in-calendar '(calendar-backward-day 1))))
9949 (org-defkey minibuffer-local-map [(shift right)]
9950 (lambda () (interactive)
9951 (org-eval-in-calendar '(calendar-forward-day 1))))
9952 (org-defkey minibuffer-local-map ">"
9953 (lambda () (interactive)
9954 (org-eval-in-calendar '(scroll-calendar-left 1))))
9955 (org-defkey minibuffer-local-map "<"
9956 (lambda () (interactive)
9957 (org-eval-in-calendar '(scroll-calendar-right 1))))
9958 (unwind-protect
9959 (progn
9960 (use-local-map map)
9961 (add-hook 'post-command-hook 'org-read-date-display)
9962 (setq org-ans0 (read-string prompt default-input nil nil))
9963 ;; org-ans0: from prompt
9964 ;; org-ans1: from mouse click
9965 ;; org-ans2: from calendar motion
9966 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
9967 (remove-hook 'post-command-hook 'org-read-date-display)
9968 (use-local-map old-map)
9969 (when org-read-date-overlay
9970 (org-delete-overlay org-read-date-overlay)
9971 (setq org-read-date-overlay nil)))))))
9973 (t ; Naked prompt only
9974 (unwind-protect
9975 (setq ans (read-string prompt default-input nil timestr))
9976 (when org-read-date-overlay
9977 (org-delete-overlay org-read-date-overlay)
9978 (setq org-read-date-overlay nil)))))
9980 (setq final (org-read-date-analyze ans def defdecode))
9982 (if to-time
9983 (apply 'encode-time final)
9984 (if (and (boundp 'org-time-was-given) org-time-was-given)
9985 (format "%04d-%02d-%02d %02d:%02d"
9986 (nth 5 final) (nth 4 final) (nth 3 final)
9987 (nth 2 final) (nth 1 final))
9988 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
9989 (defvar def)
9990 (defvar defdecode)
9991 (defvar with-time)
9992 (defun org-read-date-display ()
9993 "Display the currrent date prompt interpretation in the minibuffer."
9994 (when org-read-date-display-live
9995 (when org-read-date-overlay
9996 (org-delete-overlay org-read-date-overlay))
9997 (let ((p (point)))
9998 (end-of-line 1)
9999 (while (not (equal (buffer-substring
10000 (max (point-min) (- (point) 4)) (point))
10001 " "))
10002 (insert " "))
10003 (goto-char p))
10004 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10005 " " (or org-ans1 org-ans2)))
10006 (org-end-time-was-given nil)
10007 (f (org-read-date-analyze ans def defdecode))
10008 (fmts (if org-dcst
10009 org-time-stamp-custom-formats
10010 org-time-stamp-formats))
10011 (fmt (if (or with-time
10012 (and (boundp 'org-time-was-given) org-time-was-given))
10013 (cdr fmts)
10014 (car fmts)))
10015 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10016 (when (and org-end-time-was-given
10017 (string-match org-plain-time-of-day-regexp txt))
10018 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10019 org-end-time-was-given
10020 (substring txt (match-end 0)))))
10021 (setq org-read-date-overlay
10022 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10023 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10025 (defun org-read-date-analyze (ans def defdecode)
10026 "Analyze the combined answer of the date prompt."
10027 ;; FIXME: cleanup and comment
10028 (let (delta deltan deltaw deltadef year month day
10029 hour minute second wday pm h2 m2 tl wday1
10030 iso-year iso-weekday iso-week iso-year iso-date)
10032 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10033 (setq ans (replace-match "" t t ans)
10034 deltan (car delta)
10035 deltaw (nth 1 delta)
10036 deltadef (nth 2 delta)))
10038 ;; Check if there is an iso week date in there
10039 ;; If yes, sore the info and ostpone interpreting it until the rest
10040 ;; of the parsing is done
10041 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10042 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10043 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10044 iso-week (string-to-number (match-string 2 ans)))
10045 (setq ans (replace-match "" t t ans)))
10047 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10048 (when (string-match
10049 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10050 (setq year (if (match-end 2)
10051 (string-to-number (match-string 2 ans))
10052 (string-to-number (format-time-string "%Y")))
10053 month (string-to-number (match-string 3 ans))
10054 day (string-to-number (match-string 4 ans)))
10055 (if (< year 100) (setq year (+ 2000 year)))
10056 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10057 t nil ans)))
10058 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10059 ;; If there is a time with am/pm, and *no* time without it, we convert
10060 ;; so that matching will be successful.
10061 (loop for i from 1 to 2 do ; twice, for end time as well
10062 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10063 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10064 (setq hour (string-to-number (match-string 1 ans))
10065 minute (if (match-end 3)
10066 (string-to-number (match-string 3 ans))
10068 pm (equal ?p
10069 (string-to-char (downcase (match-string 4 ans)))))
10070 (if (and (= hour 12) (not pm))
10071 (setq hour 0)
10072 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10073 (setq ans (replace-match (format "%02d:%02d" hour minute)
10074 t t ans))))
10076 ;; Check if a time range is given as a duration
10077 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10078 (setq hour (string-to-number (match-string 1 ans))
10079 h2 (+ hour (string-to-number (match-string 3 ans)))
10080 minute (string-to-number (match-string 2 ans))
10081 m2 (+ minute (if (match-end 5) (string-to-number
10082 (match-string 5 ans))0)))
10083 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10084 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10085 t t ans)))
10087 ;; Check if there is a time range
10088 (when (boundp 'org-end-time-was-given)
10089 (setq org-time-was-given nil)
10090 (when (and (string-match org-plain-time-of-day-regexp ans)
10091 (match-end 8))
10092 (setq org-end-time-was-given (match-string 8 ans))
10093 (setq ans (concat (substring ans 0 (match-beginning 7))
10094 (substring ans (match-end 7))))))
10096 (setq tl (parse-time-string ans)
10097 day (or (nth 3 tl) (nth 3 defdecode))
10098 month (or (nth 4 tl)
10099 (if (and org-read-date-prefer-future
10100 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10101 (1+ (nth 4 defdecode))
10102 (nth 4 defdecode)))
10103 year (or (nth 5 tl)
10104 (if (and org-read-date-prefer-future
10105 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10106 (1+ (nth 5 defdecode))
10107 (nth 5 defdecode)))
10108 hour (or (nth 2 tl) (nth 2 defdecode))
10109 minute (or (nth 1 tl) (nth 1 defdecode))
10110 second (or (nth 0 tl) 0)
10111 wday (nth 6 tl))
10113 ;; Special date definitions below
10114 (cond
10115 (iso-week
10116 ;; There was an iso week
10117 (setq year (or iso-year year)
10118 day (or iso-weekday wday 1)
10119 wday nil ; to make sure that the trigger below does not match
10120 iso-date (calendar-gregorian-from-absolute
10121 (calendar-absolute-from-iso
10122 (list iso-week day year))))
10123 ; FIXME: Should we also push ISO weeks into the future?
10124 ; (when (and org-read-date-prefer-future
10125 ; (not iso-year)
10126 ; (< (calendar-absolute-from-gregorian iso-date)
10127 ; (time-to-days (current-time))))
10128 ; (setq year (1+ year)
10129 ; iso-date (calendar-gregorian-from-absolute
10130 ; (calendar-absolute-from-iso
10131 ; (list iso-week day year)))))
10132 (setq month (car iso-date)
10133 year (nth 2 iso-date)
10134 day (nth 1 iso-date)))
10135 (deltan
10136 (unless deltadef
10137 (let ((now (decode-time (current-time))))
10138 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10139 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10140 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10141 ((equal deltaw "m") (setq month (+ month deltan)))
10142 ((equal deltaw "y") (setq year (+ year deltan)))))
10143 ((and wday (not (nth 3 tl)))
10144 ;; Weekday was given, but no day, so pick that day in the week
10145 ;; on or after the derived date.
10146 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10147 (unless (equal wday wday1)
10148 (setq day (+ day (% (- wday wday1 -7) 7))))))
10149 (if (and (boundp 'org-time-was-given)
10150 (nth 2 tl))
10151 (setq org-time-was-given t))
10152 (if (< year 100) (setq year (+ 2000 year)))
10153 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10154 (list second minute hour day month year)))
10156 (defvar parse-time-weekdays)
10158 (defun org-read-date-get-relative (s today default)
10159 "Check string S for special relative date string.
10160 TODAY and DEFAULT are internal times, for today and for a default.
10161 Return shift list (N what def-flag)
10162 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10163 N is the number of WHATs to shift.
10164 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10165 the DEFAULT date rather than TODAY."
10166 (when (string-match
10167 (concat
10168 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10169 "\\([0-9]+\\)?"
10170 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10171 "\\([ \t]\\|$\\)") s)
10172 (let* ((dir (if (match-end 1)
10173 (string-to-char (substring (match-string 1 s) -1))
10174 ?+))
10175 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10176 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10177 (what (if (match-end 3) (match-string 3 s) "d"))
10178 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10179 (date (if rel default today))
10180 (wday (nth 6 (decode-time date)))
10181 delta)
10182 (if wday1
10183 (progn
10184 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10185 (if (= dir ?-) (setq delta (- delta 7)))
10186 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10187 (list delta "d" rel))
10188 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10190 (defun org-eval-in-calendar (form &optional keepdate)
10191 "Eval FORM in the calendar window and return to current window.
10192 Also, store the cursor date in variable org-ans2."
10193 (let ((sw (selected-window)))
10194 (select-window (get-buffer-window "*Calendar*"))
10195 (eval form)
10196 (when (and (not keepdate) (calendar-cursor-to-date))
10197 (let* ((date (calendar-cursor-to-date))
10198 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10199 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10200 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10201 (select-window sw)))
10203 ; ;; Update the prompt to show new default date
10204 ; (save-excursion
10205 ; (goto-char (point-min))
10206 ; (when (and org-ans2
10207 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10208 ; (get-text-property (match-end 0) 'field))
10209 ; (let ((inhibit-read-only t))
10210 ; (replace-match (concat "[" org-ans2 "]") t t)
10211 ; (add-text-properties (point-min) (1+ (match-end 0))
10212 ; (text-properties-at (1+ (point-min)))))))))
10214 (defun org-calendar-select ()
10215 "Return to `org-read-date' with the date currently selected.
10216 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10217 (interactive)
10218 (when (calendar-cursor-to-date)
10219 (let* ((date (calendar-cursor-to-date))
10220 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10221 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10222 (if (active-minibuffer-window) (exit-minibuffer))))
10224 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10225 "Insert a date stamp for the date given by the internal TIME.
10226 WITH-HM means, use the stamp format that includes the time of the day.
10227 INACTIVE means use square brackets instead of angular ones, so that the
10228 stamp will not contribute to the agenda.
10229 PRE and POST are optional strings to be inserted before and after the
10230 stamp.
10231 The command returns the inserted time stamp."
10232 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10233 stamp)
10234 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10235 (insert-before-markers (or pre ""))
10236 (insert-before-markers (setq stamp (format-time-string fmt time)))
10237 (when (listp extra)
10238 (setq extra (car extra))
10239 (if (and (stringp extra)
10240 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10241 (setq extra (format "-%02d:%02d"
10242 (string-to-number (match-string 1 extra))
10243 (string-to-number (match-string 2 extra))))
10244 (setq extra nil)))
10245 (when extra
10246 (backward-char 1)
10247 (insert-before-markers extra)
10248 (forward-char 1))
10249 (insert-before-markers (or post ""))
10250 stamp))
10252 (defun org-toggle-time-stamp-overlays ()
10253 "Toggle the use of custom time stamp formats."
10254 (interactive)
10255 (setq org-display-custom-times (not org-display-custom-times))
10256 (unless org-display-custom-times
10257 (let ((p (point-min)) (bmp (buffer-modified-p)))
10258 (while (setq p (next-single-property-change p 'display))
10259 (if (and (get-text-property p 'display)
10260 (eq (get-text-property p 'face) 'org-date))
10261 (remove-text-properties
10262 p (setq p (next-single-property-change p 'display))
10263 '(display t))))
10264 (set-buffer-modified-p bmp)))
10265 (if (featurep 'xemacs)
10266 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10267 (org-restart-font-lock)
10268 (setq org-table-may-need-update t)
10269 (if org-display-custom-times
10270 (message "Time stamps are overlayed with custom format")
10271 (message "Time stamp overlays removed")))
10273 (defun org-display-custom-time (beg end)
10274 "Overlay modified time stamp format over timestamp between BED and END."
10275 (let* ((ts (buffer-substring beg end))
10276 t1 w1 with-hm tf time str w2 (off 0))
10277 (save-match-data
10278 (setq t1 (org-parse-time-string ts t))
10279 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10280 (setq off (- (match-end 0) (match-beginning 0)))))
10281 (setq end (- end off))
10282 (setq w1 (- end beg)
10283 with-hm (and (nth 1 t1) (nth 2 t1))
10284 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10285 time (org-fix-decoded-time t1)
10286 str (org-add-props
10287 (format-time-string
10288 (substring tf 1 -1) (apply 'encode-time time))
10289 nil 'mouse-face 'highlight)
10290 w2 (length str))
10291 (if (not (= w2 w1))
10292 (add-text-properties (1+ beg) (+ 2 beg)
10293 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10294 (if (featurep 'xemacs)
10295 (progn
10296 (put-text-property beg end 'invisible t)
10297 (put-text-property beg end 'end-glyph (make-glyph str)))
10298 (put-text-property beg end 'display str))))
10300 (defun org-translate-time (string)
10301 "Translate all timestamps in STRING to custom format.
10302 But do this only if the variable `org-display-custom-times' is set."
10303 (when org-display-custom-times
10304 (save-match-data
10305 (let* ((start 0)
10306 (re org-ts-regexp-both)
10307 t1 with-hm inactive tf time str beg end)
10308 (while (setq start (string-match re string start))
10309 (setq beg (match-beginning 0)
10310 end (match-end 0)
10311 t1 (save-match-data
10312 (org-parse-time-string (substring string beg end) t))
10313 with-hm (and (nth 1 t1) (nth 2 t1))
10314 inactive (equal (substring string beg (1+ beg)) "[")
10315 tf (funcall (if with-hm 'cdr 'car)
10316 org-time-stamp-custom-formats)
10317 time (org-fix-decoded-time t1)
10318 str (format-time-string
10319 (concat
10320 (if inactive "[" "<") (substring tf 1 -1)
10321 (if inactive "]" ">"))
10322 (apply 'encode-time time))
10323 string (replace-match str t t string)
10324 start (+ start (length str)))))))
10325 string)
10327 (defun org-fix-decoded-time (time)
10328 "Set 0 instead of nil for the first 6 elements of time.
10329 Don't touch the rest."
10330 (let ((n 0))
10331 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10333 (defun org-days-to-time (timestamp-string)
10334 "Difference between TIMESTAMP-STRING and now in days."
10335 (- (time-to-days (org-time-string-to-time timestamp-string))
10336 (time-to-days (current-time))))
10338 (defun org-deadline-close (timestamp-string &optional ndays)
10339 "Is the time in TIMESTAMP-STRING close to the current date?"
10340 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10341 (and (< (org-days-to-time timestamp-string) ndays)
10342 (not (org-entry-is-done-p))))
10344 (defun org-get-wdays (ts)
10345 "Get the deadline lead time appropriate for timestring TS."
10346 (cond
10347 ((<= org-deadline-warning-days 0)
10348 ;; 0 or negative, enforce this value no matter what
10349 (- org-deadline-warning-days))
10350 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10351 ;; lead time is specified.
10352 (floor (* (string-to-number (match-string 1 ts))
10353 (cdr (assoc (match-string 2 ts)
10354 '(("d" . 1) ("w" . 7)
10355 ("m" . 30.4) ("y" . 365.25)))))))
10356 ;; go for the default.
10357 (t org-deadline-warning-days)))
10359 (defun org-calendar-select-mouse (ev)
10360 "Return to `org-read-date' with the date currently selected.
10361 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10362 (interactive "e")
10363 (mouse-set-point ev)
10364 (when (calendar-cursor-to-date)
10365 (let* ((date (calendar-cursor-to-date))
10366 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10367 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10368 (if (active-minibuffer-window) (exit-minibuffer))))
10370 (defun org-check-deadlines (ndays)
10371 "Check if there are any deadlines due or past due.
10372 A deadline is considered due if it happens within `org-deadline-warning-days'
10373 days from today's date. If the deadline appears in an entry marked DONE,
10374 it is not shown. The prefix arg NDAYS can be used to test that many
10375 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10376 (interactive "P")
10377 (let* ((org-warn-days
10378 (cond
10379 ((equal ndays '(4)) 100000)
10380 (ndays (prefix-numeric-value ndays))
10381 (t (abs org-deadline-warning-days))))
10382 (case-fold-search nil)
10383 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10384 (callback
10385 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10387 (message "%d deadlines past-due or due within %d days"
10388 (org-occur regexp nil callback)
10389 org-warn-days)))
10391 (defun org-check-before-date (date)
10392 "Check if there are deadlines or scheduled entries before DATE."
10393 (interactive (list (org-read-date)))
10394 (let ((case-fold-search nil)
10395 (regexp (concat "\\<\\(" org-deadline-string
10396 "\\|" org-scheduled-string
10397 "\\) *<\\([^>]+\\)>"))
10398 (callback
10399 (lambda () (time-less-p
10400 (org-time-string-to-time (match-string 2))
10401 (org-time-string-to-time date)))))
10402 (message "%d entries before %s"
10403 (org-occur regexp nil callback) date)))
10405 (defun org-evaluate-time-range (&optional to-buffer)
10406 "Evaluate a time range by computing the difference between start and end.
10407 Normally the result is just printed in the echo area, but with prefix arg
10408 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10409 If the time range is actually in a table, the result is inserted into the
10410 next column.
10411 For time difference computation, a year is assumed to be exactly 365
10412 days in order to avoid rounding problems."
10413 (interactive "P")
10415 (org-clock-update-time-maybe)
10416 (save-excursion
10417 (unless (org-at-date-range-p t)
10418 (goto-char (point-at-bol))
10419 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10420 (if (not (org-at-date-range-p t))
10421 (error "Not at a time-stamp range, and none found in current line")))
10422 (let* ((ts1 (match-string 1))
10423 (ts2 (match-string 2))
10424 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10425 (match-end (match-end 0))
10426 (time1 (org-time-string-to-time ts1))
10427 (time2 (org-time-string-to-time ts2))
10428 (t1 (time-to-seconds time1))
10429 (t2 (time-to-seconds time2))
10430 (diff (abs (- t2 t1)))
10431 (negative (< (- t2 t1) 0))
10432 ;; (ys (floor (* 365 24 60 60)))
10433 (ds (* 24 60 60))
10434 (hs (* 60 60))
10435 (fy "%dy %dd %02d:%02d")
10436 (fy1 "%dy %dd")
10437 (fd "%dd %02d:%02d")
10438 (fd1 "%dd")
10439 (fh "%02d:%02d")
10440 y d h m align)
10441 (if havetime
10442 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10444 d (floor (/ diff ds)) diff (mod diff ds)
10445 h (floor (/ diff hs)) diff (mod diff hs)
10446 m (floor (/ diff 60)))
10447 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10449 d (floor (+ (/ diff ds) 0.5))
10450 h 0 m 0))
10451 (if (not to-buffer)
10452 (message "%s" (org-make-tdiff-string y d h m))
10453 (if (org-at-table-p)
10454 (progn
10455 (goto-char match-end)
10456 (setq align t)
10457 (and (looking-at " *|") (goto-char (match-end 0))))
10458 (goto-char match-end))
10459 (if (looking-at
10460 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10461 (replace-match ""))
10462 (if negative (insert " -"))
10463 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10464 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10465 (insert " " (format fh h m))))
10466 (if align (org-table-align))
10467 (message "Time difference inserted")))))
10469 (defun org-make-tdiff-string (y d h m)
10470 (let ((fmt "")
10471 (l nil))
10472 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10473 l (push y l)))
10474 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10475 l (push d l)))
10476 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10477 l (push h l)))
10478 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10479 l (push m l)))
10480 (apply 'format fmt (nreverse l))))
10482 (defun org-time-string-to-time (s)
10483 (apply 'encode-time (org-parse-time-string s)))
10485 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10486 "Convert a time stamp to an absolute day number.
10487 If there is a specifyer for a cyclic time stamp, get the closest date to
10488 DAYNR.
10489 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10490 (cond
10491 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10492 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10493 daynr
10494 (+ daynr 1000)))
10495 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10496 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10497 (time-to-days (current-time))) (match-string 0 s)
10498 prefer show-all))
10499 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10501 (defun org-days-to-iso-week (days)
10502 "Return the iso week number."
10503 (require 'cal-iso)
10504 (car (calendar-iso-from-absolute days)))
10506 (defun org-small-year-to-year (year)
10507 "Convert 2-digit years into 4-digit years.
10508 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10509 The year 2000 cannot be abbreviated. Any year lager than 99
10510 is retrned unchanged."
10511 (if (< year 38)
10512 (setq year (+ 2000 year))
10513 (if (< year 100)
10514 (setq year (+ 1900 year))))
10515 year)
10517 (defun org-time-from-absolute (d)
10518 "Return the time corresponding to date D.
10519 D may be an absolute day number, or a calendar-type list (month day year)."
10520 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10521 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10523 (defun org-calendar-holiday ()
10524 "List of holidays, for Diary display in Org-mode."
10525 (require 'holidays)
10526 (let ((hl (funcall
10527 (if (fboundp 'calendar-check-holidays)
10528 'calendar-check-holidays 'check-calendar-holidays) date)))
10529 (if hl (mapconcat 'identity hl "; "))))
10531 (defun org-diary-sexp-entry (sexp entry date)
10532 "Process a SEXP diary ENTRY for DATE."
10533 (require 'diary-lib)
10534 (let ((result (if calendar-debug-sexp
10535 (let ((stack-trace-on-error t))
10536 (eval (car (read-from-string sexp))))
10537 (condition-case nil
10538 (eval (car (read-from-string sexp)))
10539 (error
10540 (beep)
10541 (message "Bad sexp at line %d in %s: %s"
10542 (org-current-line)
10543 (buffer-file-name) sexp)
10544 (sleep-for 2))))))
10545 (cond ((stringp result) result)
10546 ((and (consp result)
10547 (stringp (cdr result))) (cdr result))
10548 (result entry)
10549 (t nil))))
10551 (defun org-diary-to-ical-string (frombuf)
10552 "Get iCalendar entries from diary entries in buffer FROMBUF.
10553 This uses the icalendar.el library."
10554 (let* ((tmpdir (if (featurep 'xemacs)
10555 (temp-directory)
10556 temporary-file-directory))
10557 (tmpfile (make-temp-name
10558 (expand-file-name "orgics" tmpdir)))
10559 buf rtn b e)
10560 (save-excursion
10561 (set-buffer frombuf)
10562 (icalendar-export-region (point-min) (point-max) tmpfile)
10563 (setq buf (find-buffer-visiting tmpfile))
10564 (set-buffer buf)
10565 (goto-char (point-min))
10566 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10567 (setq b (match-beginning 0)))
10568 (goto-char (point-max))
10569 (if (re-search-backward "^END:VEVENT" nil t)
10570 (setq e (match-end 0)))
10571 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10572 (kill-buffer buf)
10573 (kill-buffer frombuf)
10574 (delete-file tmpfile)
10575 rtn))
10577 (defun org-closest-date (start current change prefer show-all)
10578 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10579 When PREFER is `past' return a date that is either CURRENT or past.
10580 When PREFER is `future', return a date that is either CURRENT or future.
10581 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10582 ;; Make the proper lists from the dates
10583 (catch 'exit
10584 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10585 dn dw sday cday n1 n2
10586 d m y y1 y2 date1 date2 nmonths nm ny m2)
10588 (setq start (org-date-to-gregorian start)
10589 current (org-date-to-gregorian
10590 (if show-all
10591 current
10592 (time-to-days (current-time))))
10593 sday (calendar-absolute-from-gregorian start)
10594 cday (calendar-absolute-from-gregorian current))
10596 (if (<= cday sday) (throw 'exit sday))
10598 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10599 (setq dn (string-to-number (match-string 1 change))
10600 dw (cdr (assoc (match-string 2 change) a1)))
10601 (error "Invalid change specifyer: %s" change))
10602 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10603 (cond
10604 ((eq dw 'day)
10605 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10606 n2 (+ n1 dn)))
10607 ((eq dw 'year)
10608 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10609 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10610 (setq date1 (list m d y1)
10611 n1 (calendar-absolute-from-gregorian date1)
10612 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10613 n2 (calendar-absolute-from-gregorian date2)))
10614 ((eq dw 'month)
10615 ;; approx number of month between the tow dates
10616 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10617 ;; How often does dn fit in there?
10618 (setq d (nth 1 start) m (car start) y (nth 2 start)
10619 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10620 m (+ m nm)
10621 ny (floor (/ m 12))
10622 y (+ y ny)
10623 m (- m (* ny 12)))
10624 (while (> m 12) (setq m (- m 12) y (1+ y)))
10625 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10626 (setq m2 (+ m dn) y2 y)
10627 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10628 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10629 (while (< n2 cday)
10630 (setq n1 n2 m m2 y y2)
10631 (setq m2 (+ m dn) y2 y)
10632 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10633 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10635 (if show-all
10636 (cond
10637 ((eq prefer 'past) n1)
10638 ((eq prefer 'future) (if (= cday n1) n1 n2))
10639 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10640 (cond
10641 ((eq prefer 'past) n1)
10642 ((eq prefer 'future) (if (= cday n1) n1 n2))
10643 (t (if (= cday n1) n1 n2)))))))
10645 (defun org-date-to-gregorian (date)
10646 "Turn any specification of DATE into a gregorian date for the calendar."
10647 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10648 ((and (listp date) (= (length date) 3)) date)
10649 ((stringp date)
10650 (setq date (org-parse-time-string date))
10651 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10652 ((listp date)
10653 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10655 (defun org-parse-time-string (s &optional nodefault)
10656 "Parse the standard Org-mode time string.
10657 This should be a lot faster than the normal `parse-time-string'.
10658 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10659 hour and minute fields will be nil if not given."
10660 (if (string-match org-ts-regexp0 s)
10661 (list 0
10662 (if (or (match-beginning 8) (not nodefault))
10663 (string-to-number (or (match-string 8 s) "0")))
10664 (if (or (match-beginning 7) (not nodefault))
10665 (string-to-number (or (match-string 7 s) "0")))
10666 (string-to-number (match-string 4 s))
10667 (string-to-number (match-string 3 s))
10668 (string-to-number (match-string 2 s))
10669 nil nil nil)
10670 (make-list 9 0)))
10672 (defun org-timestamp-up (&optional arg)
10673 "Increase the date item at the cursor by one.
10674 If the cursor is on the year, change the year. If it is on the month or
10675 the day, change that.
10676 With prefix ARG, change by that many units."
10677 (interactive "p")
10678 (org-timestamp-change (prefix-numeric-value arg)))
10680 (defun org-timestamp-down (&optional arg)
10681 "Decrease the date item at the cursor by one.
10682 If the cursor is on the year, change the year. If it is on the month or
10683 the day, change that.
10684 With prefix ARG, change by that many units."
10685 (interactive "p")
10686 (org-timestamp-change (- (prefix-numeric-value arg))))
10688 (defun org-timestamp-up-day (&optional arg)
10689 "Increase the date in the time stamp by one day.
10690 With prefix ARG, change that many days."
10691 (interactive "p")
10692 (if (and (not (org-at-timestamp-p t))
10693 (org-on-heading-p))
10694 (org-todo 'up)
10695 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10697 (defun org-timestamp-down-day (&optional arg)
10698 "Decrease the date in the time stamp by one day.
10699 With prefix ARG, change that many days."
10700 (interactive "p")
10701 (if (and (not (org-at-timestamp-p t))
10702 (org-on-heading-p))
10703 (org-todo 'down)
10704 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10706 (defun org-at-timestamp-p (&optional inactive-ok)
10707 "Determine if the cursor is in or at a timestamp."
10708 (interactive)
10709 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10710 (pos (point))
10711 (ans (or (looking-at tsr)
10712 (save-excursion
10713 (skip-chars-backward "^[<\n\r\t")
10714 (if (> (point) (point-min)) (backward-char 1))
10715 (and (looking-at tsr)
10716 (> (- (match-end 0) pos) -1))))))
10717 (and ans
10718 (boundp 'org-ts-what)
10719 (setq org-ts-what
10720 (cond
10721 ((= pos (match-beginning 0)) 'bracket)
10722 ((= pos (1- (match-end 0))) 'bracket)
10723 ((org-pos-in-match-range pos 2) 'year)
10724 ((org-pos-in-match-range pos 3) 'month)
10725 ((org-pos-in-match-range pos 7) 'hour)
10726 ((org-pos-in-match-range pos 8) 'minute)
10727 ((or (org-pos-in-match-range pos 4)
10728 (org-pos-in-match-range pos 5)) 'day)
10729 ((and (> pos (or (match-end 8) (match-end 5)))
10730 (< pos (match-end 0)))
10731 (- pos (or (match-end 8) (match-end 5))))
10732 (t 'day))))
10733 ans))
10735 (defun org-toggle-timestamp-type ()
10736 "Toggle the type (<active> or [inactive]) of a time stamp."
10737 (interactive)
10738 (when (org-at-timestamp-p t)
10739 (save-excursion
10740 (goto-char (match-beginning 0))
10741 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10742 (goto-char (1- (match-end 0)))
10743 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10744 (message "Timestamp is now %sactive"
10745 (if (equal (char-before) ?>) "in" ""))))
10747 (defun org-timestamp-change (n &optional what)
10748 "Change the date in the time stamp at point.
10749 The date will be changed by N times WHAT. WHAT can be `day', `month',
10750 `year', `minute', `second'. If WHAT is not given, the cursor position
10751 in the timestamp determines what will be changed."
10752 (let ((pos (point))
10753 with-hm inactive
10754 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10755 org-ts-what
10756 extra rem
10757 ts time time0)
10758 (if (not (org-at-timestamp-p t))
10759 (error "Not at a timestamp"))
10760 (if (and (not what) (eq org-ts-what 'bracket))
10761 (org-toggle-timestamp-type)
10762 (if (and (not what) (not (eq org-ts-what 'day))
10763 org-display-custom-times
10764 (get-text-property (point) 'display)
10765 (not (get-text-property (1- (point)) 'display)))
10766 (setq org-ts-what 'day))
10767 (setq org-ts-what (or what org-ts-what)
10768 inactive (= (char-after (match-beginning 0)) ?\[)
10769 ts (match-string 0))
10770 (replace-match "")
10771 (if (string-match
10772 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10774 (setq extra (match-string 1 ts)))
10775 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10776 (setq with-hm t))
10777 (setq time0 (org-parse-time-string ts))
10778 (when (and (eq org-ts-what 'minute)
10779 (eq current-prefix-arg nil))
10780 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10781 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10782 (setcar (cdr time0) (+ (nth 1 time0)
10783 (if (> n 0) (- rem) (- dm rem))))))
10784 (setq time
10785 (encode-time (or (car time0) 0)
10786 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10787 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10788 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10789 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10790 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10791 (nthcdr 6 time0)))
10792 (when (integerp org-ts-what)
10793 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10794 (if (eq what 'calendar)
10795 (let ((cal-date (org-get-date-from-calendar)))
10796 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10797 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10798 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10799 (setcar time0 (or (car time0) 0))
10800 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10801 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10802 (setq time (apply 'encode-time time0))))
10803 (setq org-last-changed-timestamp
10804 (org-insert-time-stamp time with-hm inactive nil nil extra))
10805 (org-clock-update-time-maybe)
10806 (goto-char pos)
10807 ;; Try to recenter the calendar window, if any
10808 (if (and org-calendar-follow-timestamp-change
10809 (get-buffer-window "*Calendar*" t)
10810 (memq org-ts-what '(day month year)))
10811 (org-recenter-calendar (time-to-days time))))))
10813 (defun org-modify-ts-extra (s pos n dm)
10814 "Change the different parts of the lead-time and repeat fields in timestamp."
10815 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10816 ng h m new rem)
10817 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10818 (cond
10819 ((or (org-pos-in-match-range pos 2)
10820 (org-pos-in-match-range pos 3))
10821 (setq m (string-to-number (match-string 3 s))
10822 h (string-to-number (match-string 2 s)))
10823 (if (org-pos-in-match-range pos 2)
10824 (setq h (+ h n))
10825 (setq n (* dm (org-no-warnings (signum n))))
10826 (when (not (= 0 (setq rem (% m dm))))
10827 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10828 (setq m (+ m n)))
10829 (if (< m 0) (setq m (+ m 60) h (1- h)))
10830 (if (> m 59) (setq m (- m 60) h (1+ h)))
10831 (setq h (min 24 (max 0 h)))
10832 (setq ng 1 new (format "-%02d:%02d" h m)))
10833 ((org-pos-in-match-range pos 6)
10834 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10835 ((org-pos-in-match-range pos 5)
10836 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10838 ((org-pos-in-match-range pos 9)
10839 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10840 ((org-pos-in-match-range pos 8)
10841 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10843 (when ng
10844 (setq s (concat
10845 (substring s 0 (match-beginning ng))
10847 (substring s (match-end ng))))))
10850 (defun org-recenter-calendar (date)
10851 "If the calendar is visible, recenter it to DATE."
10852 (let* ((win (selected-window))
10853 (cwin (get-buffer-window "*Calendar*" t))
10854 (calendar-move-hook nil))
10855 (when cwin
10856 (select-window cwin)
10857 (calendar-goto-date (if (listp date) date
10858 (calendar-gregorian-from-absolute date)))
10859 (select-window win))))
10861 (defun org-goto-calendar (&optional arg)
10862 "Go to the Emacs calendar at the current date.
10863 If there is a time stamp in the current line, go to that date.
10864 A prefix ARG can be used to force the current date."
10865 (interactive "P")
10866 (let ((tsr org-ts-regexp) diff
10867 (calendar-move-hook nil)
10868 (calendar-view-holidays-initially-flag nil)
10869 (view-calendar-holidays-initially nil)
10870 (calendar-view-diary-initially-flag nil)
10871 (view-diary-entries-initially nil))
10872 (if (or (org-at-timestamp-p)
10873 (save-excursion
10874 (beginning-of-line 1)
10875 (looking-at (concat ".*" tsr))))
10876 (let ((d1 (time-to-days (current-time)))
10877 (d2 (time-to-days
10878 (org-time-string-to-time (match-string 1)))))
10879 (setq diff (- d2 d1))))
10880 (calendar)
10881 (calendar-goto-today)
10882 (if (and diff (not arg)) (calendar-forward-day diff))))
10884 (defun org-get-date-from-calendar ()
10885 "Return a list (month day year) of date at point in calendar."
10886 (with-current-buffer "*Calendar*"
10887 (save-match-data
10888 (calendar-cursor-to-date))))
10890 (defun org-date-from-calendar ()
10891 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
10892 If there is already a time stamp at the cursor position, update it."
10893 (interactive)
10894 (if (org-at-timestamp-p t)
10895 (org-timestamp-change 0 'calendar)
10896 (let ((cal-date (org-get-date-from-calendar)))
10897 (org-insert-time-stamp
10898 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
10900 (defun org-minutes-to-hours (m)
10901 "Compute H:MM from a number of minutes."
10902 (let ((h (/ m 60)))
10903 (setq m (- m (* 60 h)))
10904 (format "%d:%02d" h m)))
10907 ;;;; Agenda files
10909 ;;;###autoload
10910 (defun org-iswitchb (&optional arg)
10911 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
10912 With a prefix argument, restrict available to files.
10913 With two prefix arguments, restrict available buffers to agenda files.
10915 Due to some yet unresolved reason, global function
10916 `iswitchb-mode' needs to be active for this function to work."
10917 (interactive "P")
10918 (require 'iswitchb)
10919 (let ((enabled iswitchb-mode) blist)
10920 (or enabled (iswitchb-mode 1))
10921 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
10922 ((equal arg '(16)) (org-buffer-list 'agenda))
10923 (t (org-buffer-list))))
10924 (unwind-protect
10925 (let ((iswitchb-make-buflist-hook
10926 (lambda ()
10927 (setq iswitchb-temp-buflist
10928 (mapcar 'buffer-name blist)))))
10929 (switch-to-buffer
10930 (iswitchb-read-buffer
10931 "Switch-to: " nil t))
10932 (or enabled (iswitchb-mode -1))))))
10934 (defun org-buffer-list (&optional predicate tmp)
10935 "Return a list of Org buffers.
10936 PREDICATE can be either 'export, 'files or 'agenda.
10938 'export restrict the list to Export buffers.
10939 'files restrict the list to buffers visiting Org files.
10940 'agenda restrict the list to buffers visiting agenda files.
10942 If TMP is non-nil, don't include temporary buffers."
10943 (let (filter blist)
10944 (setq filter
10945 (cond ((eq predicate 'files) "\.org$")
10946 ((eq predicate 'export) "\*Org .*Export")
10947 (t "\*Org \\|\.org$")))
10948 (setq blist
10949 (mapcar
10950 (lambda(b)
10951 (let ((bname (buffer-name b))
10952 (bfile (buffer-file-name b)))
10953 (if (and (string-match filter bname)
10954 (if (eq predicate 'agenda)
10955 (member bfile
10956 (mapcar (lambda(f) (file-truename f))
10957 org-agenda-files)) t)
10958 (if tmp (not (string-match "tmp" bname)) t)) b)))
10959 (buffer-list)))
10960 (delete nil blist)))
10962 (defun org-agenda-files (&optional unrestricted)
10963 "Get the list of agenda files.
10964 Optional UNRESTRICTED means return the full list even if a restriction
10965 is currently in place."
10966 (let ((files
10967 (cond
10968 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
10969 ((stringp org-agenda-files) (org-read-agenda-file-list))
10970 ((listp org-agenda-files) org-agenda-files)
10971 (t (error "Invalid value of `org-agenda-files'")))))
10972 (setq files (apply 'append
10973 (mapcar (lambda (f)
10974 (if (file-directory-p f)
10975 (directory-files f t
10976 org-agenda-file-regexp)
10977 (list f)))
10978 files)))
10979 (if org-agenda-skip-unavailable-files
10980 (delq nil
10981 (mapcar (function
10982 (lambda (file)
10983 (and (file-readable-p file) file)))
10984 files))
10985 files))) ; `org-check-agenda-file' will remove them from the list
10987 (defun org-edit-agenda-file-list ()
10988 "Edit the list of agenda files.
10989 Depending on setup, this either uses customize to edit the variable
10990 `org-agenda-files', or it visits the file that is holding the list. In the
10991 latter case, the buffer is set up in a way that saving it automatically kills
10992 the buffer and restores the previous window configuration."
10993 (interactive)
10994 (if (stringp org-agenda-files)
10995 (let ((cw (current-window-configuration)))
10996 (find-file org-agenda-files)
10997 (org-set-local 'org-window-configuration cw)
10998 (org-add-hook 'after-save-hook
10999 (lambda ()
11000 (set-window-configuration
11001 (prog1 org-window-configuration
11002 (kill-buffer (current-buffer))))
11003 (org-install-agenda-files-menu)
11004 (message "New agenda file list installed"))
11005 nil 'local)
11006 (message "%s" (substitute-command-keys
11007 "Edit list and finish with \\[save-buffer]")))
11008 (customize-variable 'org-agenda-files)))
11010 (defun org-store-new-agenda-file-list (list)
11011 "Set new value for the agenda file list and save it correcly."
11012 (if (stringp org-agenda-files)
11013 (let ((f org-agenda-files) b)
11014 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11015 (with-temp-file f
11016 (insert (mapconcat 'identity list "\n") "\n")))
11017 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11018 (setq org-agenda-files list)
11019 (customize-save-variable 'org-agenda-files org-agenda-files))))
11021 (defun org-read-agenda-file-list ()
11022 "Read the list of agenda files from a file."
11023 (when (stringp org-agenda-files)
11024 (with-temp-buffer
11025 (insert-file-contents org-agenda-files)
11026 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11029 ;;;###autoload
11030 (defun org-cycle-agenda-files ()
11031 "Cycle through the files in `org-agenda-files'.
11032 If the current buffer visits an agenda file, find the next one in the list.
11033 If the current buffer does not, find the first agenda file."
11034 (interactive)
11035 (let* ((fs (org-agenda-files t))
11036 (files (append fs (list (car fs))))
11037 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11038 file)
11039 (unless files (error "No agenda files"))
11040 (catch 'exit
11041 (while (setq file (pop files))
11042 (if (equal (file-truename file) tcf)
11043 (when (car files)
11044 (find-file (car files))
11045 (throw 'exit t))))
11046 (find-file (car fs)))
11047 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11049 (defun org-agenda-file-to-front (&optional to-end)
11050 "Move/add the current file to the top of the agenda file list.
11051 If the file is not present in the list, it is added to the front. If it is
11052 present, it is moved there. With optional argument TO-END, add/move to the
11053 end of the list."
11054 (interactive "P")
11055 (let ((org-agenda-skip-unavailable-files nil)
11056 (file-alist (mapcar (lambda (x)
11057 (cons (file-truename x) x))
11058 (org-agenda-files t)))
11059 (ctf (file-truename buffer-file-name))
11060 x had)
11061 (setq x (assoc ctf file-alist) had x)
11063 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11064 (if to-end
11065 (setq file-alist (append (delq x file-alist) (list x)))
11066 (setq file-alist (cons x (delq x file-alist))))
11067 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11068 (org-install-agenda-files-menu)
11069 (message "File %s to %s of agenda file list"
11070 (if had "moved" "added") (if to-end "end" "front"))))
11072 (defun org-remove-file (&optional file)
11073 "Remove current file from the list of files in variable `org-agenda-files'.
11074 These are the files which are being checked for agenda entries.
11075 Optional argument FILE means, use this file instead of the current."
11076 (interactive)
11077 (let* ((org-agenda-skip-unavailable-files nil)
11078 (file (or file buffer-file-name))
11079 (true-file (file-truename file))
11080 (afile (abbreviate-file-name file))
11081 (files (delq nil (mapcar
11082 (lambda (x)
11083 (if (equal true-file
11084 (file-truename x))
11085 nil x))
11086 (org-agenda-files t)))))
11087 (if (not (= (length files) (length (org-agenda-files t))))
11088 (progn
11089 (org-store-new-agenda-file-list files)
11090 (org-install-agenda-files-menu)
11091 (message "Removed file: %s" afile))
11092 (message "File was not in list: %s (not removed)" afile))))
11094 (defun org-file-menu-entry (file)
11095 (vector file (list 'find-file file) t))
11097 (defun org-check-agenda-file (file)
11098 "Make sure FILE exists. If not, ask user what to do."
11099 (when (not (file-exists-p file))
11100 (message "non-existent file %s. [R]emove from list or [A]bort?"
11101 (abbreviate-file-name file))
11102 (let ((r (downcase (read-char-exclusive))))
11103 (cond
11104 ((equal r ?r)
11105 (org-remove-file file)
11106 (throw 'nextfile t))
11107 (t (error "Abort"))))))
11109 (defun org-get-agenda-file-buffer (file)
11110 "Get a buffer visiting FILE. If the buffer needs to be created, add
11111 it to the list of buffers which might be released later."
11112 (let ((buf (org-find-base-buffer-visiting file)))
11113 (if buf
11114 buf ; just return it
11115 ;; Make a new buffer and remember it
11116 (setq buf (find-file-noselect file))
11117 (if buf (push buf org-agenda-new-buffers))
11118 buf)))
11120 (defun org-release-buffers (blist)
11121 "Release all buffers in list, asking the user for confirmation when needed.
11122 When a buffer is unmodified, it is just killed. When modified, it is saved
11123 \(if the user agrees) and then killed."
11124 (let (buf file)
11125 (while (setq buf (pop blist))
11126 (setq file (buffer-file-name buf))
11127 (when (and (buffer-modified-p buf)
11128 file
11129 (y-or-n-p (format "Save file %s? " file)))
11130 (with-current-buffer buf (save-buffer)))
11131 (kill-buffer buf))))
11133 (defun org-prepare-agenda-buffers (files)
11134 "Create buffers for all agenda files, protect archived trees and comments."
11135 (interactive)
11136 (let ((pa '(:org-archived t))
11137 (pc '(:org-comment t))
11138 (pall '(:org-archived t :org-comment t))
11139 (inhibit-read-only t)
11140 (rea (concat ":" org-archive-tag ":"))
11141 bmp file re)
11142 (save-excursion
11143 (save-restriction
11144 (while (setq file (pop files))
11145 (if (bufferp file)
11146 (set-buffer file)
11147 (org-check-agenda-file file)
11148 (set-buffer (org-get-agenda-file-buffer file)))
11149 (widen)
11150 (setq bmp (buffer-modified-p))
11151 (org-refresh-category-properties)
11152 (setq org-todo-keywords-for-agenda
11153 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11154 (setq org-done-keywords-for-agenda
11155 (append org-done-keywords-for-agenda org-done-keywords))
11156 (save-excursion
11157 (remove-text-properties (point-min) (point-max) pall)
11158 (when org-agenda-skip-archived-trees
11159 (goto-char (point-min))
11160 (while (re-search-forward rea nil t)
11161 (if (org-on-heading-p t)
11162 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11163 (goto-char (point-min))
11164 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11165 (while (re-search-forward re nil t)
11166 (add-text-properties
11167 (match-beginning 0) (org-end-of-subtree t) pc)))
11168 (set-buffer-modified-p bmp))))))
11170 ;;;; Embedded LaTeX
11172 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11173 "Keymap for the minor `org-cdlatex-mode'.")
11175 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11176 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11177 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11178 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11179 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11181 (defvar org-cdlatex-texmathp-advice-is-done nil
11182 "Flag remembering if we have applied the advice to texmathp already.")
11184 (define-minor-mode org-cdlatex-mode
11185 "Toggle the minor `org-cdlatex-mode'.
11186 This mode supports entering LaTeX environment and math in LaTeX fragments
11187 in Org-mode.
11188 \\{org-cdlatex-mode-map}"
11189 nil " OCDL" nil
11190 (when org-cdlatex-mode (require 'cdlatex))
11191 (unless org-cdlatex-texmathp-advice-is-done
11192 (setq org-cdlatex-texmathp-advice-is-done t)
11193 (defadvice texmathp (around org-math-always-on activate)
11194 "Always return t in org-mode buffers.
11195 This is because we want to insert math symbols without dollars even outside
11196 the LaTeX math segments. If Orgmode thinks that point is actually inside
11197 en embedded LaTeX fragement, let texmathp do its job.
11198 \\[org-cdlatex-mode-map]"
11199 (interactive)
11200 (let (p)
11201 (cond
11202 ((not (org-mode-p)) ad-do-it)
11203 ((eq this-command 'cdlatex-math-symbol)
11204 (setq ad-return-value t
11205 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11207 (let ((p (org-inside-LaTeX-fragment-p)))
11208 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11209 (setq ad-return-value t
11210 texmathp-why '("Org-mode embedded math" . 0))
11211 (if p ad-do-it)))))))))
11213 (defun turn-on-org-cdlatex ()
11214 "Unconditionally turn on `org-cdlatex-mode'."
11215 (org-cdlatex-mode 1))
11217 (defun org-inside-LaTeX-fragment-p ()
11218 "Test if point is inside a LaTeX fragment.
11219 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11220 sequence appearing also before point.
11221 Even though the matchers for math are configurable, this function assumes
11222 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11223 delimiters are skipped when they have been removed by customization.
11224 The return value is nil, or a cons cell with the delimiter and
11225 and the position of this delimiter.
11227 This function does a reasonably good job, but can locally be fooled by
11228 for example currency specifications. For example it will assume being in
11229 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11230 fragments that are properly closed, but during editing, we have to live
11231 with the uncertainty caused by missing closing delimiters. This function
11232 looks only before point, not after."
11233 (catch 'exit
11234 (let ((pos (point))
11235 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11236 (lim (progn
11237 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11238 (point)))
11239 dd-on str (start 0) m re)
11240 (goto-char pos)
11241 (when dodollar
11242 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11243 re (nth 1 (assoc "$" org-latex-regexps)))
11244 (while (string-match re str start)
11245 (cond
11246 ((= (match-end 0) (length str))
11247 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11248 ((= (match-end 0) (- (length str) 5))
11249 (throw 'exit nil))
11250 (t (setq start (match-end 0))))))
11251 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11252 (goto-char pos)
11253 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11254 (and (match-beginning 2) (throw 'exit nil))
11255 ;; count $$
11256 (while (re-search-backward "\\$\\$" lim t)
11257 (setq dd-on (not dd-on)))
11258 (goto-char pos)
11259 (if dd-on (cons "$$" m))))))
11262 (defun org-try-cdlatex-tab ()
11263 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11264 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11265 - inside a LaTeX fragment, or
11266 - after the first word in a line, where an abbreviation expansion could
11267 insert a LaTeX environment."
11268 (when org-cdlatex-mode
11269 (cond
11270 ((save-excursion
11271 (skip-chars-backward "a-zA-Z0-9*")
11272 (skip-chars-backward " \t")
11273 (bolp))
11274 (cdlatex-tab) t)
11275 ((org-inside-LaTeX-fragment-p)
11276 (cdlatex-tab) t)
11277 (t nil))))
11279 (defun org-cdlatex-underscore-caret (&optional arg)
11280 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11281 Revert to the normal definition outside of these fragments."
11282 (interactive "P")
11283 (if (org-inside-LaTeX-fragment-p)
11284 (call-interactively 'cdlatex-sub-superscript)
11285 (let (org-cdlatex-mode)
11286 (call-interactively (key-binding (vector last-input-event))))))
11288 (defun org-cdlatex-math-modify (&optional arg)
11289 "Execute `cdlatex-math-modify' in LaTeX fragments.
11290 Revert to the normal definition outside of these fragments."
11291 (interactive "P")
11292 (if (org-inside-LaTeX-fragment-p)
11293 (call-interactively 'cdlatex-math-modify)
11294 (let (org-cdlatex-mode)
11295 (call-interactively (key-binding (vector last-input-event))))))
11297 (defvar org-latex-fragment-image-overlays nil
11298 "List of overlays carrying the images of latex fragments.")
11299 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11301 (defun org-remove-latex-fragment-image-overlays ()
11302 "Remove all overlays with LaTeX fragment images in current buffer."
11303 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11304 (setq org-latex-fragment-image-overlays nil))
11306 (defun org-preview-latex-fragment (&optional subtree)
11307 "Preview the LaTeX fragment at point, or all locally or globally.
11308 If the cursor is in a LaTeX fragment, create the image and overlay
11309 it over the source code. If there is no fragment at point, display
11310 all fragments in the current text, from one headline to the next. With
11311 prefix SUBTREE, display all fragments in the current subtree. With a
11312 double prefix `C-u C-u', or when the cursor is before the first headline,
11313 display all fragments in the buffer.
11314 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11315 (interactive "P")
11316 (org-remove-latex-fragment-image-overlays)
11317 (save-excursion
11318 (save-restriction
11319 (let (beg end at msg)
11320 (cond
11321 ((or (equal subtree '(16))
11322 (not (save-excursion
11323 (re-search-backward (concat "^" outline-regexp) nil t))))
11324 (setq beg (point-min) end (point-max)
11325 msg "Creating images for buffer...%s"))
11326 ((equal subtree '(4))
11327 (org-back-to-heading)
11328 (setq beg (point) end (org-end-of-subtree t)
11329 msg "Creating images for subtree...%s"))
11331 (if (setq at (org-inside-LaTeX-fragment-p))
11332 (goto-char (max (point-min) (- (cdr at) 2)))
11333 (org-back-to-heading))
11334 (setq beg (point) end (progn (outline-next-heading) (point))
11335 msg (if at "Creating image...%s"
11336 "Creating images for entry...%s"))))
11337 (message msg "")
11338 (narrow-to-region beg end)
11339 (goto-char beg)
11340 (org-format-latex
11341 (concat "ltxpng/" (file-name-sans-extension
11342 (file-name-nondirectory
11343 buffer-file-name)))
11344 default-directory 'overlays msg at 'forbuffer)
11345 (message msg "done. Use `C-c C-c' to remove images.")))))
11347 (defvar org-latex-regexps
11348 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11349 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11350 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11351 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11352 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11353 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11354 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11355 "Regular expressions for matching embedded LaTeX.")
11357 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11358 "Replace LaTeX fragments with links to an image, and produce images."
11359 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11360 (let* ((prefixnodir (file-name-nondirectory prefix))
11361 (absprefix (expand-file-name prefix dir))
11362 (todir (file-name-directory absprefix))
11363 (opt org-format-latex-options)
11364 (matchers (plist-get opt :matchers))
11365 (re-list org-latex-regexps)
11366 (cnt 0) txt link beg end re e checkdir
11367 m n block linkfile movefile ov)
11368 ;; Check if there are old images files with this prefix, and remove them
11369 (when (file-directory-p todir)
11370 (mapc 'delete-file
11371 (directory-files
11372 todir 'full
11373 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11374 ;; Check the different regular expressions
11375 (while (setq e (pop re-list))
11376 (setq m (car e) re (nth 1 e) n (nth 2 e)
11377 block (if (nth 3 e) "\n\n" ""))
11378 (when (member m matchers)
11379 (goto-char (point-min))
11380 (while (re-search-forward re nil t)
11381 (when (or (not at) (equal (cdr at) (match-beginning n)))
11382 (setq txt (match-string n)
11383 beg (match-beginning n) end (match-end n)
11384 cnt (1+ cnt)
11385 linkfile (format "%s_%04d.png" prefix cnt)
11386 movefile (format "%s_%04d.png" absprefix cnt)
11387 link (concat block "[[file:" linkfile "]]" block))
11388 (if msg (message msg cnt))
11389 (goto-char beg)
11390 (unless checkdir ; make sure the directory exists
11391 (setq checkdir t)
11392 (or (file-directory-p todir) (make-directory todir)))
11393 (org-create-formula-image
11394 txt movefile opt forbuffer)
11395 (if overlays
11396 (progn
11397 (setq ov (org-make-overlay beg end))
11398 (if (featurep 'xemacs)
11399 (progn
11400 (org-overlay-put ov 'invisible t)
11401 (org-overlay-put
11402 ov 'end-glyph
11403 (make-glyph (vector 'png :file movefile))))
11404 (org-overlay-put
11405 ov 'display
11406 (list 'image :type 'png :file movefile :ascent 'center)))
11407 (push ov org-latex-fragment-image-overlays)
11408 (goto-char end))
11409 (delete-region beg end)
11410 (insert link))))))))
11412 ;; This function borrows from Ganesh Swami's latex2png.el
11413 (defun org-create-formula-image (string tofile options buffer)
11414 (let* ((tmpdir (if (featurep 'xemacs)
11415 (temp-directory)
11416 temporary-file-directory))
11417 (texfilebase (make-temp-name
11418 (expand-file-name "orgtex" tmpdir)))
11419 (texfile (concat texfilebase ".tex"))
11420 (dvifile (concat texfilebase ".dvi"))
11421 (pngfile (concat texfilebase ".png"))
11422 (fnh (face-attribute 'default :height nil))
11423 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11424 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11425 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11426 "Black"))
11427 (bg (or (plist-get options (if buffer :background :html-background))
11428 "Transparent")))
11429 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11430 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11431 (with-temp-file texfile
11432 (insert org-format-latex-header
11433 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11434 (let ((dir default-directory))
11435 (condition-case nil
11436 (progn
11437 (cd tmpdir)
11438 (call-process "latex" nil nil nil texfile))
11439 (error nil))
11440 (cd dir))
11441 (if (not (file-exists-p dvifile))
11442 (progn (message "Failed to create dvi file from %s" texfile) nil)
11443 (call-process "dvipng" nil nil nil
11444 "-E" "-fg" fg "-bg" bg
11445 "-D" dpi
11446 ;;"-x" scale "-y" scale
11447 "-T" "tight"
11448 "-o" pngfile
11449 dvifile)
11450 (if (not (file-exists-p pngfile))
11451 (progn (message "Failed to create png file from %s" texfile) nil)
11452 ;; Use the requested file name and clean up
11453 (copy-file pngfile tofile 'replace)
11454 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11455 (delete-file (concat texfilebase e)))
11456 pngfile))))
11458 (defun org-dvipng-color (attr)
11459 "Return an rgb color specification for dvipng."
11460 (apply 'format "rgb %s %s %s"
11461 (mapcar 'org-normalize-color
11462 (color-values (face-attribute 'default attr nil)))))
11464 (defun org-normalize-color (value)
11465 "Return string to be used as color value for an RGB component."
11466 (format "%g" (/ value 65535.0)))
11469 ;;;; Key bindings
11471 ;; Make `C-c C-x' a prefix key
11472 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11474 ;; TAB key with modifiers
11475 (org-defkey org-mode-map "\C-i" 'org-cycle)
11476 (org-defkey org-mode-map [(tab)] 'org-cycle)
11477 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11478 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11479 (org-defkey org-mode-map "\M-\t" 'org-complete)
11480 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11481 ;; The following line is necessary under Suse GNU/Linux
11482 (unless (featurep 'xemacs)
11483 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11484 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11485 (define-key org-mode-map [backtab] 'org-shifttab)
11487 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11488 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11489 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11491 ;; Cursor keys with modifiers
11492 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11493 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11494 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11495 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11497 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11498 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11499 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11500 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11502 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11503 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11504 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11505 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11507 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11508 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11510 ;;; Extra keys for tty access.
11511 ;; We only set them when really needed because otherwise the
11512 ;; menus don't show the simple keys
11514 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11515 (not window-system))
11516 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11517 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11518 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11519 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11520 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11521 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11522 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11523 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11524 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11525 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11526 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11527 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11528 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11529 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11530 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11531 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11532 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11533 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11534 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11535 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11536 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11537 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11539 ;; All the other keys
11541 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11542 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11543 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11544 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11545 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11546 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11547 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11548 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-attic-sibling)
11549 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11550 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11551 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11552 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11553 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11554 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11555 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11556 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11557 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11558 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11559 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11560 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11561 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11562 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11563 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11564 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11565 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11566 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11567 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11568 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11569 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11570 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11571 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11572 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11573 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11574 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11575 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11576 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11577 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11578 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11579 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11580 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11581 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11582 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11583 (org-defkey org-mode-map "\C-c^" 'org-sort)
11584 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11585 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11586 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11587 (org-defkey org-mode-map "\C-m" 'org-return)
11588 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11589 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11590 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11591 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11592 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11593 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11594 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11595 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11596 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11597 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11598 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11599 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11600 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11601 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11602 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11603 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11605 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11606 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11607 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11608 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11610 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11611 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11612 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11613 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11614 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11615 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11616 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11617 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11618 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11619 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11620 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11621 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11623 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11625 (when (featurep 'xemacs)
11626 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11628 (defvar org-table-auto-blank-field) ; defined in org-table.el
11629 (defun org-self-insert-command (N)
11630 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11631 If the cursor is in a table looking at whitespace, the whitespace is
11632 overwritten, and the table is not marked as requiring realignment."
11633 (interactive "p")
11634 (if (and (org-table-p)
11635 (progn
11636 ;; check if we blank the field, and if that triggers align
11637 (and (featurep 'org-table) org-table-auto-blank-field
11638 (member last-command
11639 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11640 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11641 ;; got extra space, this field does not determine column width
11642 (let (org-table-may-need-update) (org-table-blank-field))
11643 ;; no extra space, this field may determine column width
11644 (org-table-blank-field)))
11646 (eq N 1)
11647 (looking-at "[^|\n]* |"))
11648 (let (org-table-may-need-update)
11649 (goto-char (1- (match-end 0)))
11650 (delete-backward-char 1)
11651 (goto-char (match-beginning 0))
11652 (self-insert-command N))
11653 (setq org-table-may-need-update t)
11654 (self-insert-command N)
11655 (org-fix-tags-on-the-fly)))
11657 (defun org-fix-tags-on-the-fly ()
11658 (when (and (equal (char-after (point-at-bol)) ?*)
11659 (org-on-heading-p))
11660 (org-align-tags-here org-tags-column)))
11662 (defun org-delete-backward-char (N)
11663 "Like `delete-backward-char', insert whitespace at field end in tables.
11664 When deleting backwards, in tables this function will insert whitespace in
11665 front of the next \"|\" separator, to keep the table aligned. The table will
11666 still be marked for re-alignment if the field did fill the entire column,
11667 because, in this case the deletion might narrow the column."
11668 (interactive "p")
11669 (if (and (org-table-p)
11670 (eq N 1)
11671 (string-match "|" (buffer-substring (point-at-bol) (point)))
11672 (looking-at ".*?|"))
11673 (let ((pos (point))
11674 (noalign (looking-at "[^|\n\r]* |"))
11675 (c org-table-may-need-update))
11676 (backward-delete-char N)
11677 (skip-chars-forward "^|")
11678 (insert " ")
11679 (goto-char (1- pos))
11680 ;; noalign: if there were two spaces at the end, this field
11681 ;; does not determine the width of the column.
11682 (if noalign (setq org-table-may-need-update c)))
11683 (backward-delete-char N)
11684 (org-fix-tags-on-the-fly)))
11686 (defun org-delete-char (N)
11687 "Like `delete-char', but insert whitespace at field end in tables.
11688 When deleting characters, in tables this function will insert whitespace in
11689 front of the next \"|\" separator, to keep the table aligned. The table will
11690 still be marked for re-alignment if the field did fill the entire column,
11691 because, in this case the deletion might narrow the column."
11692 (interactive "p")
11693 (if (and (org-table-p)
11694 (not (bolp))
11695 (not (= (char-after) ?|))
11696 (eq N 1))
11697 (if (looking-at ".*?|")
11698 (let ((pos (point))
11699 (noalign (looking-at "[^|\n\r]* |"))
11700 (c org-table-may-need-update))
11701 (replace-match (concat
11702 (substring (match-string 0) 1 -1)
11703 " |"))
11704 (goto-char pos)
11705 ;; noalign: if there were two spaces at the end, this field
11706 ;; does not determine the width of the column.
11707 (if noalign (setq org-table-may-need-update c)))
11708 (delete-char N))
11709 (delete-char N)
11710 (org-fix-tags-on-the-fly)))
11712 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11713 (put 'org-self-insert-command 'delete-selection t)
11714 (put 'orgtbl-self-insert-command 'delete-selection t)
11715 (put 'org-delete-char 'delete-selection 'supersede)
11716 (put 'org-delete-backward-char 'delete-selection 'supersede)
11718 ;; Make `flyspell-mode' delay after some commands
11719 (put 'org-self-insert-command 'flyspell-delayed t)
11720 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11721 (put 'org-delete-char 'flyspell-delayed t)
11722 (put 'org-delete-backward-char 'flyspell-delayed t)
11724 ;; Make pabbrev-mode expand after org-mode commands
11725 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11726 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11728 ;; How to do this: Measure non-white length of current string
11729 ;; If equal to column width, we should realign.
11731 (defun org-remap (map &rest commands)
11732 "In MAP, remap the functions given in COMMANDS.
11733 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11734 (let (new old)
11735 (while commands
11736 (setq old (pop commands) new (pop commands))
11737 (if (fboundp 'command-remapping)
11738 (org-defkey map (vector 'remap old) new)
11739 (substitute-key-definition old new map global-map)))))
11741 (when (eq org-enable-table-editor 'optimized)
11742 ;; If the user wants maximum table support, we need to hijack
11743 ;; some standard editing functions
11744 (org-remap org-mode-map
11745 'self-insert-command 'org-self-insert-command
11746 'delete-char 'org-delete-char
11747 'delete-backward-char 'org-delete-backward-char)
11748 (org-defkey org-mode-map "|" 'org-force-self-insert))
11750 (defun org-shiftcursor-error ()
11751 "Throw an error because Shift-Cursor command was applied in wrong context."
11752 (error "This command is active in special context like tables, headlines or timestamps"))
11754 (defun org-shifttab (&optional arg)
11755 "Global visibility cycling or move to previous table field.
11756 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11757 on context.
11758 See the individual commands for more information."
11759 (interactive "P")
11760 (cond
11761 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11762 (arg (message "Content view to level: ")
11763 (org-content (prefix-numeric-value arg))
11764 (setq org-cycle-global-status 'overview))
11765 (t (call-interactively 'org-global-cycle))))
11767 (defun org-shiftmetaleft ()
11768 "Promote subtree or delete table column.
11769 Calls `org-promote-subtree', `org-outdent-item',
11770 or `org-table-delete-column', depending on context.
11771 See the individual commands for more information."
11772 (interactive)
11773 (cond
11774 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11775 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11776 ((org-at-item-p) (call-interactively 'org-outdent-item))
11777 (t (org-shiftcursor-error))))
11779 (defun org-shiftmetaright ()
11780 "Demote subtree or insert table column.
11781 Calls `org-demote-subtree', `org-indent-item',
11782 or `org-table-insert-column', depending on context.
11783 See the individual commands for more information."
11784 (interactive)
11785 (cond
11786 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11787 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11788 ((org-at-item-p) (call-interactively 'org-indent-item))
11789 (t (org-shiftcursor-error))))
11791 (defun org-shiftmetaup (&optional arg)
11792 "Move subtree up or kill table row.
11793 Calls `org-move-subtree-up' or `org-table-kill-row' or
11794 `org-move-item-up' depending on context. See the individual commands
11795 for more information."
11796 (interactive "P")
11797 (cond
11798 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11799 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11800 ((org-at-item-p) (call-interactively 'org-move-item-up))
11801 (t (org-shiftcursor-error))))
11802 (defun org-shiftmetadown (&optional arg)
11803 "Move subtree down or insert table row.
11804 Calls `org-move-subtree-down' or `org-table-insert-row' or
11805 `org-move-item-down', depending on context. See the individual
11806 commands for more information."
11807 (interactive "P")
11808 (cond
11809 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11810 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11811 ((org-at-item-p) (call-interactively 'org-move-item-down))
11812 (t (org-shiftcursor-error))))
11814 (defun org-metaleft (&optional arg)
11815 "Promote heading or move table column to left.
11816 Calls `org-do-promote' or `org-table-move-column', depending on context.
11817 With no specific context, calls the Emacs default `backward-word'.
11818 See the individual commands for more information."
11819 (interactive "P")
11820 (cond
11821 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11822 ((or (org-on-heading-p) (org-region-active-p))
11823 (call-interactively 'org-do-promote))
11824 ((org-at-item-p) (call-interactively 'org-outdent-item))
11825 (t (call-interactively 'backward-word))))
11827 (defun org-metaright (&optional arg)
11828 "Demote subtree or move table column to right.
11829 Calls `org-do-demote' or `org-table-move-column', depending on context.
11830 With no specific context, calls the Emacs default `forward-word'.
11831 See the individual commands for more information."
11832 (interactive "P")
11833 (cond
11834 ((org-at-table-p) (call-interactively 'org-table-move-column))
11835 ((or (org-on-heading-p) (org-region-active-p))
11836 (call-interactively 'org-do-demote))
11837 ((org-at-item-p) (call-interactively 'org-indent-item))
11838 (t (call-interactively 'forward-word))))
11840 (defun org-metaup (&optional arg)
11841 "Move subtree up or move table row up.
11842 Calls `org-move-subtree-up' or `org-table-move-row' or
11843 `org-move-item-up', depending on context. See the individual commands
11844 for more information."
11845 (interactive "P")
11846 (cond
11847 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
11848 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11849 ((org-at-item-p) (call-interactively 'org-move-item-up))
11850 (t (transpose-lines 1) (beginning-of-line -1))))
11852 (defun org-metadown (&optional arg)
11853 "Move subtree down or move table row down.
11854 Calls `org-move-subtree-down' or `org-table-move-row' or
11855 `org-move-item-down', depending on context. See the individual
11856 commands for more information."
11857 (interactive "P")
11858 (cond
11859 ((org-at-table-p) (call-interactively 'org-table-move-row))
11860 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11861 ((org-at-item-p) (call-interactively 'org-move-item-down))
11862 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
11864 (defun org-shiftup (&optional arg)
11865 "Increase item in timestamp or increase priority of current headline.
11866 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
11867 depending on context. See the individual commands for more information."
11868 (interactive "P")
11869 (cond
11870 ((org-at-timestamp-p t)
11871 (call-interactively (if org-edit-timestamp-down-means-later
11872 'org-timestamp-down 'org-timestamp-up)))
11873 ((org-on-heading-p) (call-interactively 'org-priority-up))
11874 ((org-at-item-p) (call-interactively 'org-previous-item))
11875 ((org-clocktable-try-shift 'up arg))
11876 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
11878 (defun org-shiftdown (&optional arg)
11879 "Decrease item in timestamp or decrease priority of current headline.
11880 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
11881 depending on context. See the individual commands for more information."
11882 (interactive "P")
11883 (cond
11884 ((org-at-timestamp-p t)
11885 (call-interactively (if org-edit-timestamp-down-means-later
11886 'org-timestamp-up 'org-timestamp-down)))
11887 ((org-on-heading-p) (call-interactively 'org-priority-down))
11888 ((org-clocktable-try-shift 'down arg))
11889 (t (call-interactively 'org-next-item))))
11891 (defun org-shiftright (&optional arg)
11892 "Next TODO keyword or timestamp one day later, depending on context."
11893 (interactive "P")
11894 (cond
11895 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
11896 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
11897 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
11898 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
11899 ((org-clocktable-try-shift 'right arg))
11900 (t (org-shiftcursor-error))))
11902 (defun org-shiftleft (&optional arg)
11903 "Previous TODO keyword or timestamp one day earlier, depending on context."
11904 (interactive "P")
11905 (cond
11906 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
11907 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
11908 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
11909 ((org-at-property-p)
11910 (call-interactively 'org-property-previous-allowed-value))
11911 ((org-clocktable-try-shift 'left arg))
11912 (t (org-shiftcursor-error))))
11914 (defun org-shiftcontrolright ()
11915 "Switch to next TODO set."
11916 (interactive)
11917 (cond
11918 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
11919 (t (org-shiftcursor-error))))
11921 (defun org-shiftcontrolleft ()
11922 "Switch to previous TODO set."
11923 (interactive)
11924 (cond
11925 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
11926 (t (org-shiftcursor-error))))
11928 (defun org-ctrl-c-ret ()
11929 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
11930 (interactive)
11931 (cond
11932 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
11933 (t (call-interactively 'org-insert-heading))))
11935 (defun org-copy-special ()
11936 "Copy region in table or copy current subtree.
11937 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11938 See the individual commands for more information."
11939 (interactive)
11940 (call-interactively
11941 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11943 (defun org-cut-special ()
11944 "Cut region in table or cut current subtree.
11945 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11946 See the individual commands for more information."
11947 (interactive)
11948 (call-interactively
11949 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11951 (defun org-paste-special (arg)
11952 "Paste rectangular region into table, or past subtree relative to level.
11953 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11954 See the individual commands for more information."
11955 (interactive "P")
11956 (if (org-at-table-p)
11957 (org-table-paste-rectangle)
11958 (org-paste-subtree arg)))
11960 (defun org-ctrl-c-ctrl-c (&optional arg)
11961 "Set tags in headline, or update according to changed information at point.
11963 This command does many different things, depending on context:
11965 - If the cursor is in a headline, prompt for tags and insert them
11966 into the current line, aligned to `org-tags-column'. When called
11967 with prefix arg, realign all tags in the current buffer.
11969 - If the cursor is in one of the special #+KEYWORD lines, this
11970 triggers scanning the buffer for these lines and updating the
11971 information.
11973 - If the cursor is inside a table, realign the table. This command
11974 works even if the automatic table editor has been turned off.
11976 - If the cursor is on a #+TBLFM line, re-apply the formulas to
11977 the entire table.
11979 - If the cursor is a the beginning of a dynamic block, update it.
11981 - If the cursor is inside a table created by the table.el package,
11982 activate that table.
11984 - If the current buffer is a remember buffer, close note and file it.
11985 with a prefix argument, file it without further interaction to the default
11986 location.
11988 - If the cursor is on a <<<target>>>, update radio targets and corresponding
11989 links in this buffer.
11991 - If the cursor is on a numbered item in a plain list, renumber the
11992 ordered list.
11994 - If the cursor is on a checkbox, toggle it."
11995 (interactive "P")
11996 (let ((org-enable-table-editor t))
11997 (cond
11998 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
11999 org-occur-highlights
12000 org-latex-fragment-image-overlays)
12001 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12002 (org-remove-occur-highlights)
12003 (org-remove-latex-fragment-image-overlays)
12004 (message "Temporary highlights/overlays removed from current buffer"))
12005 ((and (local-variable-p 'org-finish-function (current-buffer))
12006 (fboundp org-finish-function))
12007 (funcall org-finish-function))
12008 ((org-at-property-p)
12009 (call-interactively 'org-property-action))
12010 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12011 ((org-on-heading-p) (call-interactively 'org-set-tags))
12012 ((org-at-table.el-p)
12013 (require 'table)
12014 (beginning-of-line 1)
12015 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12016 (call-interactively 'table-recognize-table))
12017 ((org-at-table-p)
12018 (org-table-maybe-eval-formula)
12019 (if arg
12020 (call-interactively 'org-table-recalculate)
12021 (org-table-maybe-recalculate-line))
12022 (call-interactively 'org-table-align))
12023 ((org-at-item-checkbox-p)
12024 (call-interactively 'org-toggle-checkbox))
12025 ((org-at-item-p)
12026 (call-interactively 'org-maybe-renumber-ordered-list))
12027 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12028 ;; Dynamic block
12029 (beginning-of-line 1)
12030 (org-update-dblock))
12031 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12032 (cond
12033 ((equal (match-string 1) "TBLFM")
12034 ;; Recalculate the table before this line
12035 (save-excursion
12036 (beginning-of-line 1)
12037 (skip-chars-backward " \r\n\t")
12038 (if (org-at-table-p)
12039 (org-call-with-arg 'org-table-recalculate t))))
12041 (call-interactively 'org-mode-restart))))
12042 (t (error "C-c C-c can do nothing useful at this location.")))))
12044 (defun org-mode-restart ()
12045 "Restart Org-mode, to scan again for special lines.
12046 Also updates the keyword regular expressions."
12047 (interactive)
12048 (let ((org-inhibit-startup t)) (org-mode))
12049 (message "Org-mode restarted to refresh keyword and special line setup"))
12051 (defun org-kill-note-or-show-branches ()
12052 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12053 (interactive)
12054 (if (not org-finish-function)
12055 (call-interactively 'show-branches)
12056 (let ((org-note-abort t))
12057 (funcall org-finish-function))))
12059 (defun org-return (&optional indent)
12060 "Goto next table row or insert a newline.
12061 Calls `org-table-next-row' or `newline', depending on context.
12062 See the individual commands for more information."
12063 (interactive)
12064 (cond
12065 ((bobp) (if indent (newline-and-indent) (newline)))
12066 ((and (org-at-heading-p)
12067 (looking-at
12068 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12069 (org-show-entry)
12070 (end-of-line 1)
12071 (newline))
12072 ((org-at-table-p)
12073 (org-table-justify-field-maybe)
12074 (call-interactively 'org-table-next-row))
12075 (t (if indent (newline-and-indent) (newline)))))
12077 (defun org-return-indent ()
12078 "Goto next table row or insert a newline and indent.
12079 Calls `org-table-next-row' or `newline-and-indent', depending on
12080 context. See the individual commands for more information."
12081 (interactive)
12082 (org-return t))
12084 (defun org-ctrl-c-star ()
12085 "Compute table, or change heading status of lines.
12086 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12087 depending on context. This will also turn a plain list item or a normal
12088 line into a subheading."
12089 (interactive)
12090 (cond
12091 ((org-at-table-p)
12092 (call-interactively 'org-table-recalculate))
12093 ((org-region-active-p)
12094 ;; Convert all lines in region to list items
12095 (call-interactively 'org-toggle-region-headings))
12096 ((org-on-heading-p)
12097 (org-toggle-region-headings (point-at-bol)
12098 (min (1+ (point-at-eol)) (point-max))))
12099 ((org-at-item-p)
12100 ;; Convert to heading
12101 (let ((level (save-match-data
12102 (save-excursion
12103 (condition-case nil
12104 (progn
12105 (org-back-to-heading t)
12106 (funcall outline-level))
12107 (error 0))))))
12108 (replace-match
12109 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12110 (t (org-toggle-region-headings (point-at-bol)
12111 (min (1+ (point-at-eol)) (point-max))))))
12113 (defun org-ctrl-c-minus ()
12114 "Insert separator line in table or modify bullet status of line.
12115 Also turns a plain line or a region of lines into list items.
12116 Calls `org-table-insert-hline', `org-toggle-region-items', or
12117 `org-cycle-list-bullet', depending on context."
12118 (interactive)
12119 (cond
12120 ((org-at-table-p)
12121 (call-interactively 'org-table-insert-hline))
12122 ((org-on-heading-p)
12123 ;; Convert to item
12124 (save-excursion
12125 (beginning-of-line 1)
12126 (if (looking-at "\\*+ ")
12127 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12128 ((org-region-active-p)
12129 ;; Convert all lines in region to list items
12130 (call-interactively 'org-toggle-region-items))
12131 ((org-in-item-p)
12132 (call-interactively 'org-cycle-list-bullet))
12133 (t (org-toggle-region-items (point-at-bol)
12134 (min (1+ (point-at-eol)) (point-max))))))
12136 (defun org-toggle-region-items (beg end)
12137 "Convert all lines in region to list items.
12138 If the first line is already an item, convert all list items in the region
12139 to normal lines."
12140 (interactive "r")
12141 (let (l2 l)
12142 (save-excursion
12143 (goto-char end)
12144 (setq l2 (org-current-line))
12145 (goto-char beg)
12146 (beginning-of-line 1)
12147 (setq l (1- (org-current-line)))
12148 (if (org-at-item-p)
12149 ;; We already have items, de-itemize
12150 (while (< (setq l (1+ l)) l2)
12151 (when (org-at-item-p)
12152 (goto-char (match-beginning 2))
12153 (delete-region (match-beginning 2) (match-end 2))
12154 (and (looking-at "[ \t]+") (replace-match "")))
12155 (beginning-of-line 2))
12156 (while (< (setq l (1+ l)) l2)
12157 (unless (org-at-item-p)
12158 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12159 (replace-match "\\1- \\2")))
12160 (beginning-of-line 2))))))
12162 (defun org-toggle-region-headings (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-on-heading-p)
12175 ;; We already have headlines, de-star them
12176 (while (< (setq l (1+ l)) l2)
12177 (when (org-on-heading-p t)
12178 (and (looking-at outline-regexp) (replace-match "")))
12179 (beginning-of-line 2))
12180 (let* ((stars (save-excursion
12181 (re-search-backward org-complex-heading-regexp nil t)
12182 (or (match-string 1) "*")))
12183 (add-stars (if org-odd-levels-only "**" "*"))
12184 (rpl (concat stars add-stars " \\2")))
12185 (while (< (setq l (1+ l)) l2)
12186 (unless (org-on-heading-p)
12187 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12188 (replace-match rpl)))
12189 (beginning-of-line 2)))))))
12191 (defun org-meta-return (&optional arg)
12192 "Insert a new heading or wrap a region in a table.
12193 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12194 See the individual commands for more information."
12195 (interactive "P")
12196 (cond
12197 ((org-at-table-p)
12198 (call-interactively 'org-table-wrap-region))
12199 (t (call-interactively 'org-insert-heading))))
12201 ;;; Menu entries
12203 ;; Define the Org-mode menus
12204 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12205 '("Tbl"
12206 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12207 ["Next Field" org-cycle (org-at-table-p)]
12208 ["Previous Field" org-shifttab (org-at-table-p)]
12209 ["Next Row" org-return (org-at-table-p)]
12210 "--"
12211 ["Blank Field" org-table-blank-field (org-at-table-p)]
12212 ["Edit Field" org-table-edit-field (org-at-table-p)]
12213 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12214 "--"
12215 ("Column"
12216 ["Move Column Left" org-metaleft (org-at-table-p)]
12217 ["Move Column Right" org-metaright (org-at-table-p)]
12218 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12219 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12220 ("Row"
12221 ["Move Row Up" org-metaup (org-at-table-p)]
12222 ["Move Row Down" org-metadown (org-at-table-p)]
12223 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12224 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12225 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12226 "--"
12227 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12228 ("Rectangle"
12229 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12230 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12231 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12232 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12233 "--"
12234 ("Calculate"
12235 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12236 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12237 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12238 "--"
12239 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12240 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12241 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12242 "--"
12243 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12244 "--"
12245 ["Sum Column/Rectangle" org-table-sum
12246 (or (org-at-table-p) (org-region-active-p))]
12247 ["Which Column?" org-table-current-column (org-at-table-p)])
12248 ["Debug Formulas"
12249 org-table-toggle-formula-debugger
12250 :style toggle :selected org-table-formula-debug]
12251 ["Show Col/Row Numbers"
12252 org-table-toggle-coordinate-overlays
12253 :style toggle :selected org-table-overlay-coordinates]
12254 "--"
12255 ["Create" org-table-create (and (not (org-at-table-p))
12256 org-enable-table-editor)]
12257 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12258 ["Import from File" org-table-import (not (org-at-table-p))]
12259 ["Export to File" org-table-export (org-at-table-p)]
12260 "--"
12261 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12263 (easy-menu-define org-org-menu org-mode-map "Org menu"
12264 '("Org"
12265 ("Show/Hide"
12266 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))
12267 :help "Cycle subtree visibility: folded->children->all->folded"]
12268 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))
12269 :help "Cycle global visibility: overview->content->all"]
12270 ["Sparse Tree..." org-sparse-tree
12271 :help "Create sparse trees using different search criteria"]
12272 ["Reveal Context" org-reveal :active t
12273 :help "Show hidden context around point, including the outline hierarchy"]
12274 ["Show All" show-all :active t
12275 :help "Show all text in the buffer, including drawers"]
12276 "--"
12277 ["Subtree to indirect buffer" org-tree-to-indirect-buffer :active t
12278 :help "Open the subtree at point in a separate window, using an indirect buffer"])
12279 "--"
12280 ["New Heading" org-insert-heading t]
12281 ("Navigate Headings"
12282 ["Up" outline-up-heading t]
12283 ["Next" outline-next-visible-heading t]
12284 ["Previous" outline-previous-visible-heading t]
12285 ["Next Same Level" outline-forward-same-level t]
12286 ["Previous Same Level" outline-backward-same-level t]
12287 "--"
12288 ["Jump" org-goto t])
12289 ("Edit Structure"
12290 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12291 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12292 "--"
12293 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12294 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12295 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12296 "--"
12297 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12298 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12299 ["Demote Heading" org-metaright (not (org-at-table-p))]
12300 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12301 "--"
12302 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12303 "--"
12304 ["Convert to odd levels" org-convert-to-odd-levels t]
12305 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12306 ("Editing"
12307 ["Emphasis..." org-emphasize t])
12308 ("Archive"
12309 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12310 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12311 ; :active t :keys "C-u C-c C-x C-a"]
12312 ["Sparse trees open ARCHIVE trees"
12313 (setq org-sparse-tree-open-archived-trees
12314 (not org-sparse-tree-open-archived-trees))
12315 :style toggle :selected org-sparse-tree-open-archived-trees]
12316 ["Cycling opens ARCHIVE trees"
12317 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12318 :style toggle :selected org-cycle-open-archived-trees]
12319 ["Agenda includes ARCHIVE trees"
12320 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12321 :style toggle :selected (not org-agenda-skip-archived-trees)]
12322 "--"
12323 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12324 ; ["Check and Move Children" (org-archive-subtree '(4))
12325 ; :active t :keys "C-u C-c C-x C-s"]
12327 "--"
12328 ("TODO Lists"
12329 ["TODO/DONE/-" org-todo t]
12330 ("Select keyword"
12331 ["Next keyword" org-shiftright (org-on-heading-p)]
12332 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12333 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12334 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12335 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12336 ["Show TODO Tree" org-show-todo-tree t]
12337 ["Global TODO list" org-todo-list t]
12338 "--"
12339 ["Set Priority" org-priority t]
12340 ["Priority Up" org-shiftup t]
12341 ["Priority Down" org-shiftdown t])
12342 ("TAGS and Properties"
12343 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12344 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12345 "--"
12346 ["Set property" 'org-set-property t]
12347 ["Column view of properties" org-columns t]
12348 ["Insert Column View DBlock" org-insert-columns-dblock t])
12349 ("Dates and Scheduling"
12350 ["Timestamp" org-time-stamp t]
12351 ["Timestamp (inactive)" org-time-stamp-inactive t]
12352 ("Change Date"
12353 ["1 Day Later" org-shiftright t]
12354 ["1 Day Earlier" org-shiftleft t]
12355 ["1 ... Later" org-shiftup t]
12356 ["1 ... Earlier" org-shiftdown t])
12357 ["Compute Time Range" org-evaluate-time-range t]
12358 ["Schedule Item" org-schedule t]
12359 ["Deadline" org-deadline t]
12360 "--"
12361 ["Custom time format" org-toggle-time-stamp-overlays
12362 :style radio :selected org-display-custom-times]
12363 "--"
12364 ["Goto Calendar" org-goto-calendar t]
12365 ["Date from Calendar" org-date-from-calendar t])
12366 ("Logging work"
12367 ["Clock in" org-clock-in t]
12368 ["Clock out" org-clock-out t]
12369 ["Clock cancel" org-clock-cancel t]
12370 ["Goto running clock" org-clock-goto t]
12371 ["Display times" org-clock-display t]
12372 ["Create clock table" org-clock-report t]
12373 "--"
12374 ["Record DONE time"
12375 (progn (setq org-log-done (not org-log-done))
12376 (message "Switching to %s will %s record a timestamp"
12377 (car org-done-keywords)
12378 (if org-log-done "automatically" "not")))
12379 :style toggle :selected org-log-done])
12380 "--"
12381 ["Agenda Command..." org-agenda t]
12382 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12383 ("File List for Agenda")
12384 ("Special views current file"
12385 ["TODO Tree" org-show-todo-tree t]
12386 ["Check Deadlines" org-check-deadlines t]
12387 ["Timeline" org-timeline t]
12388 ["Tags Tree" org-tags-sparse-tree t])
12389 "--"
12390 ("Hyperlinks"
12391 ["Store Link (Global)" org-store-link t]
12392 ["Insert Link" org-insert-link t]
12393 ["Follow Link" org-open-at-point t]
12394 "--"
12395 ["Next link" org-next-link :help "Move forward to next link in the buffer"]
12396 ["Previous link" org-previous-link t]
12397 "--"
12398 ["Descriptive Links"
12399 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12400 :style radio :help "Hide link part of links, only show the description"
12401 :selected (member '(org-link) buffer-invisibility-spec)]
12402 ["Literal Links"
12403 (progn
12404 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12405 :style radio :help "Show full links without hiding anything"
12406 :selected (not (member '(org-link) buffer-invisibility-spec))])
12407 "--"
12408 ["Export/Publish..." org-export t]
12409 ("LaTeX"
12410 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12411 :selected org-cdlatex-mode]
12412 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12413 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12414 ["Modify math symbol" org-cdlatex-math-modify
12415 (org-inside-LaTeX-fragment-p)]
12416 ["Export LaTeX fragments as images"
12417 (if (featurep 'org-exp)
12418 (setq org-export-with-LaTeX-fragments
12419 (not org-export-with-LaTeX-fragments))
12420 (require 'org-exp))
12421 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12422 org-export-with-LaTeX-fragments)])
12423 "--"
12424 ("Documentation"
12425 ["Show Version" org-version t]
12426 ["Info Documentation" org-info t])
12427 ("Customize"
12428 ["Browse Org Group" org-customize t]
12429 "--"
12430 ["Expand This Menu" org-create-customize-menu
12431 (fboundp 'customize-menu-create)])
12432 "--"
12433 ["Refresh setup" org-mode-restart t]
12436 (defun org-info (&optional node)
12437 "Read documentation for Org-mode in the info system.
12438 With optional NODE, go directly to that node."
12439 (interactive)
12440 (info (format "(org)%s" (or node ""))))
12442 (defun org-install-agenda-files-menu ()
12443 (let ((bl (buffer-list)))
12444 (save-excursion
12445 (while bl
12446 (set-buffer (pop bl))
12447 (if (org-mode-p) (setq bl nil)))
12448 (when (org-mode-p)
12449 (easy-menu-change
12450 '("Org") "File List for Agenda"
12451 (append
12452 (list
12453 ["Edit File List" (org-edit-agenda-file-list) t]
12454 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12455 ["Remove Current File from List" org-remove-file t]
12456 ["Cycle through agenda files" org-cycle-agenda-files t]
12457 ["Occur in all agenda files" org-occur-in-agenda-files t]
12458 "--")
12459 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12461 ;;;; Documentation
12463 (defun org-customize ()
12464 "Call the customize function with org as argument."
12465 (interactive)
12466 (customize-browse 'org))
12468 (defun org-create-customize-menu ()
12469 "Create a full customization menu for Org-mode, insert it into the menu."
12470 (interactive)
12471 (if (fboundp 'customize-menu-create)
12472 (progn
12473 (easy-menu-change
12474 '("Org") "Customize"
12475 `(["Browse Org group" org-customize t]
12476 "--"
12477 ,(customize-menu-create 'org)
12478 ["Set" Custom-set t]
12479 ["Save" Custom-save t]
12480 ["Reset to Current" Custom-reset-current t]
12481 ["Reset to Saved" Custom-reset-saved t]
12482 ["Reset to Standard Settings" Custom-reset-standard t]))
12483 (message "\"Org\"-menu now contains full customization menu"))
12484 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12486 ;;;; Miscellaneous stuff
12488 ;;; Generally useful functions
12490 (defun org-plist-delete (plist property)
12491 "Delete PROPERTY from PLIST.
12492 This is in contrast to merely setting it to 0."
12493 (let (p)
12494 (while plist
12495 (if (not (eq property (car plist)))
12496 (setq p (plist-put p (car plist) (nth 1 plist))))
12497 (setq plist (cddr plist)))
12500 (defun org-force-self-insert (N)
12501 "Needed to enforce self-insert under remapping."
12502 (interactive "p")
12503 (self-insert-command N))
12505 (defun org-string-width (s)
12506 "Compute width of string, ignoring invisible characters.
12507 This ignores character with invisibility property `org-link', and also
12508 characters with property `org-cwidth', because these will become invisible
12509 upon the next fontification round."
12510 (let (b l)
12511 (when (or (eq t buffer-invisibility-spec)
12512 (assq 'org-link buffer-invisibility-spec))
12513 (while (setq b (text-property-any 0 (length s)
12514 'invisible 'org-link s))
12515 (setq s (concat (substring s 0 b)
12516 (substring s (or (next-single-property-change
12517 b 'invisible s) (length s)))))))
12518 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12519 (setq s (concat (substring s 0 b)
12520 (substring s (or (next-single-property-change
12521 b 'org-cwidth s) (length s))))))
12522 (setq l (string-width s) b -1)
12523 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12524 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12528 (defun org-trim (s)
12529 "Remove whitespace at beginning and end of string."
12530 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12531 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12534 (defun org-wrap (string &optional width lines)
12535 "Wrap string to either a number of lines, or a width in characters.
12536 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12537 that costs. If there is a word longer than WIDTH, the text is actually
12538 wrapped to the length of that word.
12539 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12540 many lines, whatever width that takes.
12541 The return value is a list of lines, without newlines at the end."
12542 (let* ((words (org-split-string string "[ \t\n]+"))
12543 (maxword (apply 'max (mapcar 'org-string-width words)))
12544 w ll)
12545 (cond (width
12546 (org-do-wrap words (max maxword width)))
12547 (lines
12548 (setq w maxword)
12549 (setq ll (org-do-wrap words maxword))
12550 (if (<= (length ll) lines)
12552 (setq ll words)
12553 (while (> (length ll) lines)
12554 (setq w (1+ w))
12555 (setq ll (org-do-wrap words w)))
12556 ll))
12557 (t (error "Cannot wrap this")))))
12559 (defun org-do-wrap (words width)
12560 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12561 (let (lines line)
12562 (while words
12563 (setq line (pop words))
12564 (while (and words (< (+ (length line) (length (car words))) width))
12565 (setq line (concat line " " (pop words))))
12566 (setq lines (push line lines)))
12567 (nreverse lines)))
12569 (defun org-split-string (string &optional separators)
12570 "Splits STRING into substrings at SEPARATORS.
12571 No empty strings are returned if there are matches at the beginning
12572 and end of string."
12573 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12574 (start 0)
12575 notfirst
12576 (list nil))
12577 (while (and (string-match rexp string
12578 (if (and notfirst
12579 (= start (match-beginning 0))
12580 (< start (length string)))
12581 (1+ start) start))
12582 (< (match-beginning 0) (length string)))
12583 (setq notfirst t)
12584 (or (eq (match-beginning 0) 0)
12585 (and (eq (match-beginning 0) (match-end 0))
12586 (eq (match-beginning 0) start))
12587 (setq list
12588 (cons (substring string start (match-beginning 0))
12589 list)))
12590 (setq start (match-end 0)))
12591 (or (eq start (length string))
12592 (setq list
12593 (cons (substring string start)
12594 list)))
12595 (nreverse list)))
12597 (defun org-context ()
12598 "Return a list of contexts of the current cursor position.
12599 If several contexts apply, all are returned.
12600 Each context entry is a list with a symbol naming the context, and
12601 two positions indicating start and end of the context. Possible
12602 contexts are:
12604 :headline anywhere in a headline
12605 :headline-stars on the leading stars in a headline
12606 :todo-keyword on a TODO keyword (including DONE) in a headline
12607 :tags on the TAGS in a headline
12608 :priority on the priority cookie in a headline
12609 :item on the first line of a plain list item
12610 :item-bullet on the bullet/number of a plain list item
12611 :checkbox on the checkbox in a plain list item
12612 :table in an org-mode table
12613 :table-special on a special filed in a table
12614 :table-table in a table.el table
12615 :link on a hyperlink
12616 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12617 :target on a <<target>>
12618 :radio-target on a <<<radio-target>>>
12619 :latex-fragment on a LaTeX fragment
12620 :latex-preview on a LaTeX fragment with overlayed preview image
12622 This function expects the position to be visible because it uses font-lock
12623 faces as a help to recognize the following contexts: :table-special, :link,
12624 and :keyword."
12625 (let* ((f (get-text-property (point) 'face))
12626 (faces (if (listp f) f (list f)))
12627 (p (point)) clist o)
12628 ;; First the large context
12629 (cond
12630 ((org-on-heading-p t)
12631 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12632 (when (progn
12633 (beginning-of-line 1)
12634 (looking-at org-todo-line-tags-regexp))
12635 (push (org-point-in-group p 1 :headline-stars) clist)
12636 (push (org-point-in-group p 2 :todo-keyword) clist)
12637 (push (org-point-in-group p 4 :tags) clist))
12638 (goto-char p)
12639 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12640 (if (looking-at "\\[#[A-Z0-9]\\]")
12641 (push (org-point-in-group p 0 :priority) clist)))
12643 ((org-at-item-p)
12644 (push (org-point-in-group p 2 :item-bullet) clist)
12645 (push (list :item (point-at-bol)
12646 (save-excursion (org-end-of-item) (point)))
12647 clist)
12648 (and (org-at-item-checkbox-p)
12649 (push (org-point-in-group p 0 :checkbox) clist)))
12651 ((org-at-table-p)
12652 (push (list :table (org-table-begin) (org-table-end)) clist)
12653 (if (memq 'org-formula faces)
12654 (push (list :table-special
12655 (previous-single-property-change p 'face)
12656 (next-single-property-change p 'face)) clist)))
12657 ((org-at-table-p 'any)
12658 (push (list :table-table) clist)))
12659 (goto-char p)
12661 ;; Now the small context
12662 (cond
12663 ((org-at-timestamp-p)
12664 (push (org-point-in-group p 0 :timestamp) clist))
12665 ((memq 'org-link faces)
12666 (push (list :link
12667 (previous-single-property-change p 'face)
12668 (next-single-property-change p 'face)) clist))
12669 ((memq 'org-special-keyword faces)
12670 (push (list :keyword
12671 (previous-single-property-change p 'face)
12672 (next-single-property-change p 'face)) clist))
12673 ((org-on-target-p)
12674 (push (org-point-in-group p 0 :target) clist)
12675 (goto-char (1- (match-beginning 0)))
12676 (if (looking-at org-radio-target-regexp)
12677 (push (org-point-in-group p 0 :radio-target) clist))
12678 (goto-char p))
12679 ((setq o (car (delq nil
12680 (mapcar
12681 (lambda (x)
12682 (if (memq x org-latex-fragment-image-overlays) x))
12683 (org-overlays-at (point))))))
12684 (push (list :latex-fragment
12685 (org-overlay-start o) (org-overlay-end o)) clist)
12686 (push (list :latex-preview
12687 (org-overlay-start o) (org-overlay-end o)) clist))
12688 ((org-inside-LaTeX-fragment-p)
12689 ;; FIXME: positions wrong.
12690 (push (list :latex-fragment (point) (point)) clist)))
12692 (setq clist (nreverse (delq nil clist)))
12693 clist))
12695 ;; FIXME: Compare with at-regexp-p Do we need both?
12696 (defun org-in-regexp (re &optional nlines visually)
12697 "Check if point is inside a match of regexp.
12698 Normally only the current line is checked, but you can include NLINES extra
12699 lines both before and after point into the search.
12700 If VISUALLY is set, require that the cursor is not after the match but
12701 really on, so that the block visually is on the match."
12702 (catch 'exit
12703 (let ((pos (point))
12704 (eol (point-at-eol (+ 1 (or nlines 0))))
12705 (inc (if visually 1 0)))
12706 (save-excursion
12707 (beginning-of-line (- 1 (or nlines 0)))
12708 (while (re-search-forward re eol t)
12709 (if (and (<= (match-beginning 0) pos)
12710 (>= (+ inc (match-end 0)) pos))
12711 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12713 (defun org-at-regexp-p (regexp)
12714 "Is point inside a match of REGEXP in the current line?"
12715 (catch 'exit
12716 (save-excursion
12717 (let ((pos (point)) (end (point-at-eol)))
12718 (beginning-of-line 1)
12719 (while (re-search-forward regexp end t)
12720 (if (and (<= (match-beginning 0) pos)
12721 (>= (match-end 0) pos))
12722 (throw 'exit t)))
12723 nil))))
12725 (defun org-occur-in-agenda-files (regexp &optional nlines)
12726 "Call `multi-occur' with buffers for all agenda files."
12727 (interactive "sOrg-files matching: \np")
12728 (let* ((files (org-agenda-files))
12729 (tnames (mapcar 'file-truename files))
12730 (extra org-agenda-text-search-extra-files)
12732 (while (setq f (pop extra))
12733 (unless (member (file-truename f) tnames)
12734 (add-to-list 'files f 'append)
12735 (add-to-list 'tnames (file-truename f) 'append)))
12736 (multi-occur
12737 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12738 regexp)))
12740 (if (boundp 'occur-mode-find-occurrence-hook)
12741 ;; Emacs 23
12742 (add-hook 'occur-mode-find-occurrence-hook
12743 (lambda ()
12744 (when (org-mode-p)
12745 (org-reveal))))
12746 ;; Emacs 22
12747 (defadvice occur-mode-goto-occurrence
12748 (after org-occur-reveal activate)
12749 (and (org-mode-p) (org-reveal)))
12750 (defadvice occur-mode-goto-occurrence-other-window
12751 (after org-occur-reveal activate)
12752 (and (org-mode-p) (org-reveal)))
12753 (defadvice occur-mode-display-occurrence
12754 (after org-occur-reveal activate)
12755 (when (org-mode-p)
12756 (let ((pos (occur-mode-find-occurrence)))
12757 (with-current-buffer (marker-buffer pos)
12758 (save-excursion
12759 (goto-char pos)
12760 (org-reveal)))))))
12762 (defun org-uniquify (list)
12763 "Remove duplicate elements from LIST."
12764 (let (res)
12765 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12766 res))
12768 (defun org-delete-all (elts list)
12769 "Remove all elements in ELTS from LIST."
12770 (while elts
12771 (setq list (delete (pop elts) list)))
12772 list)
12774 (defun org-back-over-empty-lines ()
12775 "Move backwards over witespace, to the beginning of the first empty line.
12776 Returns the number of empty lines passed."
12777 (let ((pos (point)))
12778 (skip-chars-backward " \t\n\r")
12779 (beginning-of-line 2)
12780 (goto-char (min (point) pos))
12781 (count-lines (point) pos)))
12783 (defun org-skip-whitespace ()
12784 (skip-chars-forward " \t\n\r"))
12786 (defun org-point-in-group (point group &optional context)
12787 "Check if POINT is in match-group GROUP.
12788 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12789 match. If the match group does ot exist or point is not inside it,
12790 return nil."
12791 (and (match-beginning group)
12792 (>= point (match-beginning group))
12793 (<= point (match-end group))
12794 (if context
12795 (list context (match-beginning group) (match-end group))
12796 t)))
12798 (defun org-switch-to-buffer-other-window (&rest args)
12799 "Switch to buffer in a second window on the current frame.
12800 In particular, do not allow pop-up frames."
12801 (let (pop-up-frames special-display-buffer-names special-display-regexps
12802 special-display-function)
12803 (apply 'switch-to-buffer-other-window args)))
12805 (defun org-combine-plists (&rest plists)
12806 "Create a single property list from all plists in PLISTS.
12807 The process starts by copying the first list, and then setting properties
12808 from the other lists. Settings in the last list are the most significant
12809 ones and overrule settings in the other lists."
12810 (let ((rtn (copy-sequence (pop plists)))
12811 p v ls)
12812 (while plists
12813 (setq ls (pop plists))
12814 (while ls
12815 (setq p (pop ls) v (pop ls))
12816 (setq rtn (plist-put rtn p v))))
12817 rtn))
12819 (defun org-move-line-down (arg)
12820 "Move the current line down. With prefix argument, move it past ARG lines."
12821 (interactive "p")
12822 (let ((col (current-column))
12823 beg end pos)
12824 (beginning-of-line 1) (setq beg (point))
12825 (beginning-of-line 2) (setq end (point))
12826 (beginning-of-line (+ 1 arg))
12827 (setq pos (move-marker (make-marker) (point)))
12828 (insert (delete-and-extract-region beg end))
12829 (goto-char pos)
12830 (move-to-column col)))
12832 (defun org-move-line-up (arg)
12833 "Move the current line up. With prefix argument, move it past ARG lines."
12834 (interactive "p")
12835 (let ((col (current-column))
12836 beg end pos)
12837 (beginning-of-line 1) (setq beg (point))
12838 (beginning-of-line 2) (setq end (point))
12839 (beginning-of-line (- arg))
12840 (setq pos (move-marker (make-marker) (point)))
12841 (insert (delete-and-extract-region beg end))
12842 (goto-char pos)
12843 (move-to-column col)))
12845 (defun org-replace-escapes (string table)
12846 "Replace %-escapes in STRING with values in TABLE.
12847 TABLE is an association list with keys like \"%a\" and string values.
12848 The sequences in STRING may contain normal field width and padding information,
12849 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
12850 so values can contain further %-escapes if they are define later in TABLE."
12851 (let ((case-fold-search nil)
12852 e re rpl)
12853 (while (setq e (pop table))
12854 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
12855 (while (string-match re string)
12856 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
12857 (cdr e)))
12858 (setq string (replace-match rpl t t string))))
12859 string))
12862 (defun org-sublist (list start end)
12863 "Return a section of LIST, from START to END.
12864 Counting starts at 1."
12865 (let (rtn (c start))
12866 (setq list (nthcdr (1- start) list))
12867 (while (and list (<= c end))
12868 (push (pop list) rtn)
12869 (setq c (1+ c)))
12870 (nreverse rtn)))
12872 (defun org-find-base-buffer-visiting (file)
12873 "Like `find-buffer-visiting' but alway return the base buffer and
12874 not an indirect buffer."
12875 (let ((buf (find-buffer-visiting file)))
12876 (if buf
12877 (or (buffer-base-buffer buf) buf)
12878 nil)))
12880 (defun org-image-file-name-regexp ()
12881 "Return regexp matching the file names of images."
12882 (if (fboundp 'image-file-name-regexp)
12883 (image-file-name-regexp)
12884 (let ((image-file-name-extensions
12885 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12886 "xbm" "xpm" "pbm" "pgm" "ppm")))
12887 (concat "\\."
12888 (regexp-opt (nconc (mapcar 'upcase
12889 image-file-name-extensions)
12890 image-file-name-extensions)
12892 "\\'"))))
12894 (defun org-file-image-p (file)
12895 "Return non-nil if FILE is an image."
12896 (save-match-data
12897 (string-match (org-image-file-name-regexp) file)))
12899 ;;; Paragraph filling stuff.
12900 ;; We want this to be just right, so use the full arsenal.
12902 (defun org-indent-line-function ()
12903 "Indent line like previous, but further if previous was headline or item."
12904 (interactive)
12905 (let* ((pos (point))
12906 (itemp (org-at-item-p))
12907 column bpos bcol tpos tcol bullet btype bullet-type)
12908 ;; Find the previous relevant line
12909 (beginning-of-line 1)
12910 (cond
12911 ((looking-at "#") (setq column 0))
12912 ((looking-at "\\*+ ") (setq column 0))
12914 (beginning-of-line 0)
12915 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
12916 (beginning-of-line 0))
12917 (cond
12918 ((looking-at "\\*+[ \t]+")
12919 (goto-char (match-end 0))
12920 (setq column (current-column)))
12921 ((org-in-item-p)
12922 (org-beginning-of-item)
12923 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12924 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
12925 (setq bpos (match-beginning 1) tpos (match-end 0)
12926 bcol (progn (goto-char bpos) (current-column))
12927 tcol (progn (goto-char tpos) (current-column))
12928 bullet (match-string 1)
12929 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
12930 (if (not itemp)
12931 (setq column tcol)
12932 (goto-char pos)
12933 (beginning-of-line 1)
12934 (if (looking-at "\\S-")
12935 (progn
12936 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
12937 (setq bullet (match-string 1)
12938 btype (if (string-match "[0-9]" bullet) "n" bullet))
12939 (setq column (if (equal btype bullet-type) bcol tcol)))
12940 (setq column (org-get-indentation)))))
12941 (t (setq column (org-get-indentation))))))
12942 (goto-char pos)
12943 (if (<= (current-column) (current-indentation))
12944 (indent-line-to column)
12945 (save-excursion (indent-line-to column)))
12946 (setq column (current-column))
12947 (beginning-of-line 1)
12948 (if (looking-at
12949 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
12950 (replace-match (concat "\\1" (format org-property-format
12951 (match-string 2) (match-string 3)))
12952 t nil))
12953 (move-to-column column)))
12955 (defun org-set-autofill-regexps ()
12956 (interactive)
12957 ;; In the paragraph separator we include headlines, because filling
12958 ;; text in a line directly attached to a headline would otherwise
12959 ;; fill the headline as well.
12960 (org-set-local 'comment-start-skip "^#+[ \t]*")
12961 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
12962 ;; The paragraph starter includes hand-formatted lists.
12963 (org-set-local 'paragraph-start
12964 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12965 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12966 ;; But only if the user has not turned off tables or fixed-width regions
12967 (org-set-local
12968 'auto-fill-inhibit-regexp
12969 (concat "\\*+ \\|#\\+"
12970 "\\|[ \t]*" org-keyword-time-regexp
12971 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12972 (concat
12973 "\\|[ \t]*["
12974 (if org-enable-table-editor "|" "")
12975 (if org-enable-fixed-width-editor ":" "")
12976 "]"))))
12977 ;; We use our own fill-paragraph function, to make sure that tables
12978 ;; and fixed-width regions are not wrapped. That function will pass
12979 ;; through to `fill-paragraph' when appropriate.
12980 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
12981 ; Adaptive filling: To get full control, first make sure that
12982 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
12983 (org-set-local 'adaptive-fill-regexp "\000")
12984 (org-set-local 'adaptive-fill-function
12985 'org-adaptive-fill-function)
12986 (org-set-local
12987 'align-mode-rules-list
12988 '((org-in-buffer-settings
12989 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
12990 (modes . '(org-mode))))))
12992 (defun org-fill-paragraph (&optional justify)
12993 "Re-align a table, pass through to fill-paragraph if no table."
12994 (let ((table-p (org-at-table-p))
12995 (table.el-p (org-at-table.el-p)))
12996 (cond ((and (equal (char-after (point-at-bol)) ?*)
12997 (save-excursion (goto-char (point-at-bol))
12998 (looking-at outline-regexp)))
12999 t) ; skip headlines
13000 (table.el-p t) ; skip table.el tables
13001 (table-p (org-table-align) t) ; align org-mode tables
13002 (t nil)))) ; call paragraph-fill
13004 ;; For reference, this is the default value of adaptive-fill-regexp
13005 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13007 (defun org-adaptive-fill-function ()
13008 "Return a fill prefix for org-mode files.
13009 In particular, this makes sure hanging paragraphs for hand-formatted lists
13010 work correctly."
13011 (cond ((looking-at "#[ \t]+")
13012 (match-string 0))
13013 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13014 (save-excursion
13015 (goto-char (match-end 0))
13016 (make-string (current-column) ?\ )))
13017 (t nil)))
13019 ;;; Other stuff.
13021 (defun org-toggle-fixed-width-section (arg)
13022 "Toggle the fixed-width export.
13023 If there is no active region, the QUOTE keyword at the current headline is
13024 inserted or removed. When present, it causes the text between this headline
13025 and the next to be exported as fixed-width text, and unmodified.
13026 If there is an active region, this command adds or removes a colon as the
13027 first character of this line. If the first character of a line is a colon,
13028 this line is also exported in fixed-width font."
13029 (interactive "P")
13030 (let* ((cc 0)
13031 (regionp (org-region-active-p))
13032 (beg (if regionp (region-beginning) (point)))
13033 (end (if regionp (region-end)))
13034 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13035 (case-fold-search nil)
13036 (re "[ \t]*\\(:\\)")
13037 off)
13038 (if regionp
13039 (save-excursion
13040 (goto-char beg)
13041 (setq cc (current-column))
13042 (beginning-of-line 1)
13043 (setq off (looking-at re))
13044 (while (> nlines 0)
13045 (setq nlines (1- nlines))
13046 (beginning-of-line 1)
13047 (cond
13048 (arg
13049 (move-to-column cc t)
13050 (insert ":\n")
13051 (forward-line -1))
13052 ((and off (looking-at re))
13053 (replace-match "" t t nil 1))
13054 ((not off) (move-to-column cc t) (insert ":")))
13055 (forward-line 1)))
13056 (save-excursion
13057 (org-back-to-heading)
13058 (if (looking-at (concat outline-regexp
13059 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13060 (replace-match "" t t nil 1)
13061 (if (looking-at outline-regexp)
13062 (progn
13063 (goto-char (match-end 0))
13064 (insert org-quote-string " "))))))))
13066 ;;;; Functions extending outline functionality
13068 (defun org-beginning-of-line (&optional arg)
13069 "Go to the beginning of the current line. If that is invisible, continue
13070 to a visible line beginning. This makes the function of C-a more intuitive.
13071 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13072 first attempt, and only move to after the tags when the cursor is already
13073 beyond the end of the headline."
13074 (interactive "P")
13075 (let ((pos (point)))
13076 (beginning-of-line 1)
13077 (if (bobp)
13079 (backward-char 1)
13080 (if (org-invisible-p)
13081 (while (and (not (bobp)) (org-invisible-p))
13082 (backward-char 1)
13083 (beginning-of-line 1))
13084 (forward-char 1)))
13085 (when org-special-ctrl-a/e
13086 (cond
13087 ((and (looking-at org-todo-line-regexp)
13088 (= (char-after (match-end 1)) ?\ ))
13089 (goto-char
13090 (if (eq org-special-ctrl-a/e t)
13091 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13092 ((= pos (point)) (match-beginning 3))
13093 (t (point)))
13094 (cond ((> pos (point)) (point))
13095 ((not (eq last-command this-command)) (point))
13096 (t (match-beginning 3))))))
13097 ((org-at-item-p)
13098 (goto-char
13099 (if (eq org-special-ctrl-a/e t)
13100 (cond ((> pos (match-end 4)) (match-end 4))
13101 ((= pos (point)) (match-end 4))
13102 (t (point)))
13103 (cond ((> pos (point)) (point))
13104 ((not (eq last-command this-command)) (point))
13105 (t (match-end 4))))))))))
13107 (defun org-end-of-line (&optional arg)
13108 "Go to the end of the line.
13109 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13110 first attempt, and only move to after the tags when the cursor is already
13111 beyond the end of the headline."
13112 (interactive "P")
13113 (if (or (not org-special-ctrl-a/e)
13114 (not (org-on-heading-p)))
13115 (end-of-line arg)
13116 (let ((pos (point)))
13117 (beginning-of-line 1)
13118 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13119 (if (eq org-special-ctrl-a/e t)
13120 (if (or (< pos (match-beginning 1))
13121 (= pos (match-end 0)))
13122 (goto-char (match-beginning 1))
13123 (goto-char (match-end 0)))
13124 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13125 (goto-char (match-end 0))
13126 (goto-char (match-beginning 1))))
13127 (end-of-line arg)))))
13129 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13130 (define-key org-mode-map "\C-e" 'org-end-of-line)
13132 (defun org-kill-line (&optional arg)
13133 "Kill line, to tags or end of line."
13134 (interactive "P")
13135 (cond
13136 ((or (not org-special-ctrl-k)
13137 (bolp)
13138 (not (org-on-heading-p)))
13139 (call-interactively 'kill-line))
13140 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13141 (kill-region (point) (match-beginning 1))
13142 (org-set-tags nil t))
13143 (t (kill-region (point) (point-at-eol)))))
13145 (define-key org-mode-map "\C-k" 'org-kill-line)
13147 (defun org-invisible-p ()
13148 "Check if point is at a character currently not visible."
13149 ;; Early versions of noutline don't have `outline-invisible-p'.
13150 (if (fboundp 'outline-invisible-p)
13151 (outline-invisible-p)
13152 (get-char-property (point) 'invisible)))
13154 (defun org-invisible-p2 ()
13155 "Check if point is at a character currently not visible."
13156 (save-excursion
13157 (if (and (eolp) (not (bobp))) (backward-char 1))
13158 ;; Early versions of noutline don't have `outline-invisible-p'.
13159 (if (fboundp 'outline-invisible-p)
13160 (outline-invisible-p)
13161 (get-char-property (point) 'invisible))))
13163 (defalias 'org-back-to-heading 'outline-back-to-heading)
13164 (defalias 'org-on-heading-p 'outline-on-heading-p)
13165 (defalias 'org-at-heading-p 'outline-on-heading-p)
13166 (defun org-at-heading-or-item-p ()
13167 (or (org-on-heading-p) (org-at-item-p)))
13169 (defun org-on-target-p ()
13170 (or (org-in-regexp org-radio-target-regexp)
13171 (org-in-regexp org-target-regexp)))
13173 (defun org-up-heading-all (arg)
13174 "Move to the heading line of which the present line is a subheading.
13175 This function considers both visible and invisible heading lines.
13176 With argument, move up ARG levels."
13177 (if (fboundp 'outline-up-heading-all)
13178 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13179 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13181 (defun org-up-heading-safe ()
13182 "Move to the heading line of which the present line is a subheading.
13183 This version will not throw an error. It will return the level of the
13184 headline found, or nil if no higher level is found."
13185 (let ((pos (point)) start-level level
13186 (re (concat "^" outline-regexp)))
13187 (catch 'exit
13188 (outline-back-to-heading t)
13189 (setq start-level (funcall outline-level))
13190 (if (equal start-level 1) (throw 'exit nil))
13191 (while (re-search-backward re nil t)
13192 (setq level (funcall outline-level))
13193 (if (< level start-level) (throw 'exit level)))
13194 nil)))
13196 (defun org-first-sibling-p ()
13197 "Is this heading the first child of its parents?"
13198 (interactive)
13199 (let ((re (concat "^" outline-regexp))
13200 level l)
13201 (unless (org-at-heading-p t)
13202 (error "Not at a heading"))
13203 (setq level (funcall outline-level))
13204 (save-excursion
13205 (if (not (re-search-backward re nil t))
13207 (setq l (funcall outline-level))
13208 (< l level)))))
13210 (defun org-goto-sibling (&optional previous)
13211 "Goto the next sibling, even if it is invisible.
13212 When PREVIOUS is set, go to the previous sibling instead. Returns t
13213 when a sibling was found. When none is found, return nil and don't
13214 move point."
13215 (let ((fun (if previous 're-search-backward 're-search-forward))
13216 (pos (point))
13217 (re (concat "^" outline-regexp))
13218 level l)
13219 (when (condition-case nil (org-back-to-heading t) (error nil))
13220 (setq level (funcall outline-level))
13221 (catch 'exit
13222 (or previous (forward-char 1))
13223 (while (funcall fun re nil t)
13224 (setq l (funcall outline-level))
13225 (when (< l level) (goto-char pos) (throw 'exit nil))
13226 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13227 (goto-char pos)
13228 nil))))
13230 (defun org-show-siblings ()
13231 "Show all siblings of the current headline."
13232 (save-excursion
13233 (while (org-goto-sibling) (org-flag-heading nil)))
13234 (save-excursion
13235 (while (org-goto-sibling 'previous)
13236 (org-flag-heading nil))))
13238 (defun org-show-hidden-entry ()
13239 "Show an entry where even the heading is hidden."
13240 (save-excursion
13241 (org-show-entry)))
13243 (defun org-flag-heading (flag &optional entry)
13244 "Flag the current heading. FLAG non-nil means make invisible.
13245 When ENTRY is non-nil, show the entire entry."
13246 (save-excursion
13247 (org-back-to-heading t)
13248 ;; Check if we should show the entire entry
13249 (if entry
13250 (progn
13251 (org-show-entry)
13252 (save-excursion
13253 (and (outline-next-heading)
13254 (org-flag-heading nil))))
13255 (outline-flag-region (max (point-min) (1- (point)))
13256 (save-excursion (outline-end-of-heading) (point))
13257 flag))))
13259 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13260 ;; This is an exact copy of the original function, but it uses
13261 ;; `org-back-to-heading', to make it work also in invisible
13262 ;; trees. And is uses an invisible-OK argument.
13263 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13264 (org-back-to-heading invisible-OK)
13265 (let ((first t)
13266 (level (funcall outline-level)))
13267 (while (and (not (eobp))
13268 (or first (> (funcall outline-level) level)))
13269 (setq first nil)
13270 (outline-next-heading))
13271 (unless to-heading
13272 (if (memq (preceding-char) '(?\n ?\^M))
13273 (progn
13274 ;; Go to end of line before heading
13275 (forward-char -1)
13276 (if (memq (preceding-char) '(?\n ?\^M))
13277 ;; leave blank line before heading
13278 (forward-char -1))))))
13279 (point))
13281 (defun org-show-subtree ()
13282 "Show everything after this heading at deeper levels."
13283 (outline-flag-region
13284 (point)
13285 (save-excursion
13286 (outline-end-of-subtree) (outline-next-heading) (point))
13287 nil))
13289 (defun org-show-entry ()
13290 "Show the body directly following this heading.
13291 Show the heading too, if it is currently invisible."
13292 (interactive)
13293 (save-excursion
13294 (condition-case nil
13295 (progn
13296 (org-back-to-heading t)
13297 (outline-flag-region
13298 (max (point-min) (1- (point)))
13299 (save-excursion
13300 (re-search-forward
13301 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13302 (or (match-beginning 1) (point-max)))
13303 nil))
13304 (error nil))))
13306 (defun org-make-options-regexp (kwds)
13307 "Make a regular expression for keyword lines."
13308 (concat
13310 "#?[ \t]*\\+\\("
13311 (mapconcat 'regexp-quote kwds "\\|")
13312 "\\):[ \t]*"
13313 "\\(.+\\)"))
13315 ;; Make isearch reveal the necessary context
13316 (defun org-isearch-end ()
13317 "Reveal context after isearch exits."
13318 (when isearch-success ; only if search was successful
13319 (if (featurep 'xemacs)
13320 ;; Under XEmacs, the hook is run in the correct place,
13321 ;; we directly show the context.
13322 (org-show-context 'isearch)
13323 ;; In Emacs the hook runs *before* restoring the overlays.
13324 ;; So we have to use a one-time post-command-hook to do this.
13325 ;; (Emacs 22 has a special variable, see function `org-mode')
13326 (unless (and (boundp 'isearch-mode-end-hook-quit)
13327 isearch-mode-end-hook-quit)
13328 ;; Only when the isearch was not quitted.
13329 (org-add-hook 'post-command-hook 'org-isearch-post-command
13330 'append 'local)))))
13332 (defun org-isearch-post-command ()
13333 "Remove self from hook, and show context."
13334 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13335 (org-show-context 'isearch))
13338 ;;;; Integration with and fixes for other packages
13340 ;;; Imenu support
13342 (defvar org-imenu-markers nil
13343 "All markers currently used by Imenu.")
13344 (make-variable-buffer-local 'org-imenu-markers)
13346 (defun org-imenu-new-marker (&optional pos)
13347 "Return a new marker for use by Imenu, and remember the marker."
13348 (let ((m (make-marker)))
13349 (move-marker m (or pos (point)))
13350 (push m org-imenu-markers)
13353 (defun org-imenu-get-tree ()
13354 "Produce the index for Imenu."
13355 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13356 (setq org-imenu-markers nil)
13357 (let* ((n org-imenu-depth)
13358 (re (concat "^" outline-regexp))
13359 (subs (make-vector (1+ n) nil))
13360 (last-level 0)
13361 m tree level head)
13362 (save-excursion
13363 (save-restriction
13364 (widen)
13365 (goto-char (point-max))
13366 (while (re-search-backward re nil t)
13367 (setq level (org-reduced-level (funcall outline-level)))
13368 (when (<= level n)
13369 (looking-at org-complex-heading-regexp)
13370 (setq head (org-match-string-no-properties 4)
13371 m (org-imenu-new-marker))
13372 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13373 (if (>= level last-level)
13374 (push (cons head m) (aref subs level))
13375 (push (cons head (aref subs (1+ level))) (aref subs level))
13376 (loop for i from (1+ level) to n do (aset subs i nil)))
13377 (setq last-level level)))))
13378 (aref subs 1)))
13380 (eval-after-load "imenu"
13381 '(progn
13382 (add-hook 'imenu-after-jump-hook
13383 (lambda () (org-show-context 'org-goto)))))
13385 ;; Speedbar support
13387 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13388 "Overlay marking the agenda restriction line in speedbar.")
13389 (org-overlay-put org-speedbar-restriction-lock-overlay
13390 'face 'org-agenda-restriction-lock)
13391 (org-overlay-put org-speedbar-restriction-lock-overlay
13392 'help-echo "Agendas are currently limited to this item.")
13393 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13395 (defun org-speedbar-set-agenda-restriction ()
13396 "Restrict future agenda commands to the location at point in speedbar.
13397 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13398 (interactive)
13399 (require 'org-agenda)
13400 (let (p m tp np dir txt w)
13401 (cond
13402 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13403 'org-imenu t))
13404 (setq m (get-text-property p 'org-imenu-marker))
13405 (save-excursion
13406 (save-restriction
13407 (set-buffer (marker-buffer m))
13408 (goto-char m)
13409 (org-agenda-set-restriction-lock 'subtree))))
13410 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13411 'speedbar-function 'speedbar-find-file))
13412 (setq tp (previous-single-property-change
13413 (1+ p) 'speedbar-function)
13414 np (next-single-property-change
13415 tp 'speedbar-function)
13416 dir (speedbar-line-directory)
13417 txt (buffer-substring-no-properties (or tp (point-min))
13418 (or np (point-max))))
13419 (save-excursion
13420 (save-restriction
13421 (set-buffer (find-file-noselect
13422 (let ((default-directory dir))
13423 (expand-file-name txt))))
13424 (unless (org-mode-p)
13425 (error "Cannot restrict to non-Org-mode file"))
13426 (org-agenda-set-restriction-lock 'file))))
13427 (t (error "Don't know how to restrict Org-mode's agenda")))
13428 (org-move-overlay org-speedbar-restriction-lock-overlay
13429 (point-at-bol) (point-at-eol))
13430 (setq current-prefix-arg nil)
13431 (org-agenda-maybe-redo)))
13433 (eval-after-load "speedbar"
13434 '(progn
13435 (speedbar-add-supported-extension ".org")
13436 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13437 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13438 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13439 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13440 (add-hook 'speedbar-visiting-tag-hook
13441 (lambda () (org-show-context 'org-goto)))))
13444 ;;; Fixes and Hacks for problems with other packages
13446 ;; Make flyspell not check words in links, to not mess up our keymap
13447 (defun org-mode-flyspell-verify ()
13448 "Don't let flyspell put overlays at active buttons."
13449 (not (get-text-property (point) 'keymap)))
13451 ;; Make `bookmark-jump' show the jump location if it was hidden.
13452 (eval-after-load "bookmark"
13453 '(if (boundp 'bookmark-after-jump-hook)
13454 ;; We can use the hook
13455 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13456 ;; Hook not available, use advice
13457 (defadvice bookmark-jump (after org-make-visible activate)
13458 "Make the position visible."
13459 (org-bookmark-jump-unhide))))
13461 (defun org-bookmark-jump-unhide ()
13462 "Unhide the current position, to show the bookmark location."
13463 (and (org-mode-p)
13464 (or (org-invisible-p)
13465 (save-excursion (goto-char (max (point-min) (1- (point))))
13466 (org-invisible-p)))
13467 (org-show-context 'bookmark-jump)))
13469 ;; Make session.el ignore our circular variable
13470 (eval-after-load "session"
13471 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13473 ;;;; Experimental code
13475 (defun org-closed-in-range ()
13476 "Sparse tree of items closed in a certain time range.
13477 Still experimental, may disappear in the future."
13478 (interactive)
13479 ;; Get the time interval from the user.
13480 (let* ((time1 (time-to-seconds
13481 (org-read-date nil 'to-time nil "Starting date: ")))
13482 (time2 (time-to-seconds
13483 (org-read-date nil 'to-time nil "End date:")))
13484 ;; callback function
13485 (callback (lambda ()
13486 (let ((time
13487 (time-to-seconds
13488 (apply 'encode-time
13489 (org-parse-time-string
13490 (match-string 1))))))
13491 ;; check if time in interval
13492 (and (>= time time1) (<= time time2))))))
13493 ;; make tree, check each match with the callback
13494 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13497 ;;;; Finish up
13499 (provide 'org)
13501 (run-hooks 'org-load-hook)
13503 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13504 ;;; org.el ends here
13506 (defun org-open-link-from-string (s &optional arg)
13507 "Open a link in the string S, as if it was in Org-mode."
13508 (interactive)
13509 (with-temp-buffer
13510 (let ((org-inhibit-startup t))
13511 (org-mode)
13512 (insert s)
13513 (goto-char (point-min))
13514 (org-open-at-point arg))))