Implement EXPORT_TITLE property.
[org-mode.git] / lisp / org.el
blob41312edf7a9c7ae4799aa0ba16c25b9c1d45d49e
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.03
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 of the License, or
15 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.03"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " id: Global id's for identifying entries" org-id)
165 (const :tag " info: Links to Info nodes" org-info)
166 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
167 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
168 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
169 (const :tag " mew Links to Mew folders/messages" org-mew)
170 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
171 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
172 (const :tag " vm: Links to VM folders/messages" org-vm)
173 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
174 (const :tag " mouse: Additional mouse support" org-mouse)
176 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
177 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
178 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
179 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
180 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
181 (const :tag "C eval: Include command output as text" org-eval)
182 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
183 (const :tag "C id: Global id's for identifying entries" org-id)
184 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
185 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
186 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
187 (const :tag "C mtags: Support for muse-like tags" org-mtags)
188 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
189 (const :tag "C registry: A registry for Org links" org-registry)
190 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
191 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
192 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
193 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
194 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
197 (defgroup org-startup nil
198 "Options concerning startup of Org-mode."
199 :tag "Org Startup"
200 :group 'org)
202 (defcustom org-startup-folded t
203 "Non-nil means, entering Org-mode will switch to OVERVIEW.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
207 #+STARTUP: fold
208 #+STARTUP: nofold
209 #+STARTUP: content"
210 :group 'org-startup
211 :type '(choice
212 (const :tag "nofold: show all" nil)
213 (const :tag "fold: overview" t)
214 (const :tag "content: all headlines" content)))
216 (defcustom org-startup-truncated t
217 "Non-nil means, entering Org-mode will set `truncate-lines'.
218 This is useful since some lines containing links can be very long and
219 uninteresting. Also tables look terrible when wrapped."
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-startup-align-all-tables nil
224 "Non-nil means, align all tables when visiting a file.
225 This is useful when the column width in tables is forced with <N> cookies
226 in table fields. Such tables will look correct only after the first re-align.
227 This can also be configured on a per-file basis by adding one of
228 the following lines anywhere in the buffer:
229 #+STARTUP: align
230 #+STARTUP: noalign"
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-insert-mode-line-in-empty-file nil
235 "Non-nil means insert the first line setting Org-mode in empty files.
236 When the function `org-mode' is called interactively in an empty file, this
237 normally means that the file name does not automatically trigger Org-mode.
238 To ensure that the file will always be in Org-mode in the future, a
239 line enforcing Org-mode will be inserted into the buffer, if this option
240 has been set."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-replace-disputed-keys nil
245 "Non-nil means use alternative key bindings for some keys.
246 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
247 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
248 If you want to use Org-mode together with one of these other modes,
249 or more generally if you would like to move some Org-mode commands to
250 other keys, set this variable and configure the keys with the variable
251 `org-disputed-keys'.
253 This option is only relevant at load-time of Org-mode, and must be set
254 *before* org.el is loaded. Changing it requires a restart of Emacs to
255 become effective."
256 :group 'org-startup
257 :type 'boolean)
259 (if (fboundp 'defvaralias)
260 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
262 (defcustom org-disputed-keys
263 '(([(shift up)] . [(meta p)])
264 ([(shift down)] . [(meta n)])
265 ([(shift left)] . [(meta -)])
266 ([(shift right)] . [(meta +)])
267 ([(control shift right)] . [(meta shift +)])
268 ([(control shift left)] . [(meta shift -)]))
269 "Keys for which Org-mode and other modes compete.
270 This is an alist, cars are the default keys, second element specifies
271 the alternative to use when `org-replace-disputed-keys' is t.
273 Keys can be specified in any syntax supported by `define-key'.
274 The value of this option takes effect only at Org-mode's startup,
275 therefore you'll have to restart Emacs to apply it after changing."
276 :group 'org-startup
277 :type 'alist)
279 (defun org-key (key)
280 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
281 Or return the original if not disputed."
282 (if org-replace-disputed-keys
283 (let* ((nkey (key-description key))
284 (x (org-find-if (lambda (x)
285 (equal (key-description (car x)) nkey))
286 org-disputed-keys)))
287 (if x (cdr x) key))
288 key))
290 (defun org-find-if (predicate seq)
291 (catch 'exit
292 (while seq
293 (if (funcall predicate (car seq))
294 (throw 'exit (car seq))
295 (pop seq)))))
297 (defun org-defkey (keymap key def)
298 "Define a key, possibly translated, as returned by `org-key'."
299 (define-key keymap (org-key key) def))
301 (defcustom org-ellipsis nil
302 "The ellipsis to use in the Org-mode outline.
303 When nil, just use the standard three dots. When a string, use that instead,
304 When a face, use the standart 3 dots, but with the specified face.
305 The change affects only Org-mode (which will then use its own display table).
306 Changing this requires executing `M-x org-mode' in a buffer to become
307 effective."
308 :group 'org-startup
309 :type '(choice (const :tag "Default" nil)
310 (face :tag "Face" :value org-warning)
311 (string :tag "String" :value "...#")))
313 (defvar org-display-table nil
314 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
316 (defgroup org-keywords nil
317 "Keywords in Org-mode."
318 :tag "Org Keywords"
319 :group 'org)
321 (defcustom org-deadline-string "DEADLINE:"
322 "String to mark deadline entries.
323 A deadline is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-deadline].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-scheduled-string "SCHEDULED:"
331 "String to mark scheduled TODO entries.
332 A schedule is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-schedule].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-closed-string "CLOSED:"
340 "String used as the prefix for timestamps logging closing a TODO entry."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-clock-string "CLOCK:"
345 "String used as prefix for timestamps clocking work hours on an item."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-comment-string "COMMENT"
350 "Entries starting with this keyword will never be exported.
351 An entry can be toggled between COMMENT and normal with
352 \\[org-toggle-comment].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-quote-string "QUOTE"
358 "Entries starting with this keyword will be exported in fixed-width font.
359 Quoting applies only to the text in the entry following the headline, and does
360 not extend beyond the next headline, even if that is lower level.
361 An entry can be toggled between QUOTE and normal with
362 \\[org-toggle-fixed-width-section]."
363 :group 'org-keywords
364 :type 'string)
366 (defconst org-repeat-re
367 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
368 "Regular expression for specifying repeated events.
369 After a match, group 1 contains the repeat expression.")
371 (defgroup org-structure nil
372 "Options concerning the general structure of Org-mode files."
373 :tag "Org Structure"
374 :group 'org)
376 (defgroup org-reveal-location nil
377 "Options about how to make context of a location visible."
378 :tag "Org Reveal Location"
379 :group 'org-structure)
381 (defconst org-context-choice
382 '(choice
383 (const :tag "Always" t)
384 (const :tag "Never" nil)
385 (repeat :greedy t :tag "Individual contexts"
386 (cons
387 (choice :tag "Context"
388 (const agenda)
389 (const org-goto)
390 (const occur-tree)
391 (const tags-tree)
392 (const link-search)
393 (const mark-goto)
394 (const bookmark-jump)
395 (const isearch)
396 (const default))
397 (boolean))))
398 "Contexts for the reveal options.")
400 (defcustom org-show-hierarchy-above '((default . t))
401 "Non-nil means, show full hierarchy when revealing a location.
402 Org-mode often shows locations in an org-mode file which might have
403 been invisible before. When this is set, the hierarchy of headings
404 above the exposed location is shown.
405 Turning this off for example for sparse trees makes them very compact.
406 Instead of t, this can also be an alist specifying this option for different
407 contexts. Valid contexts are
408 agenda when exposing an entry from the agenda
409 org-goto when using the command `org-goto' on key C-c C-j
410 occur-tree when using the command `org-occur' on key C-c /
411 tags-tree when constructing a sparse tree based on tags matches
412 link-search when exposing search matches associated with a link
413 mark-goto when exposing the jump goal of a mark
414 bookmark-jump when exposing a bookmark location
415 isearch when exiting from an incremental search
416 default default for all contexts not set explicitly"
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defcustom org-show-following-heading '((default . nil))
421 "Non-nil means, show following heading when revealing a location.
422 Org-mode often shows locations in an org-mode file which might have
423 been invisible before. When this is set, the heading following the
424 match is shown.
425 Turning this off for example for sparse trees makes them very compact,
426 but makes it harder to edit the location of the match. In such a case,
427 use the command \\[org-reveal] to show more context.
428 Instead of t, this can also be an alist specifying this option for different
429 contexts. See `org-show-hierarchy-above' for valid contexts."
430 :group 'org-reveal-location
431 :type org-context-choice)
433 (defcustom org-show-siblings '((default . nil) (isearch t))
434 "Non-nil means, show all sibling heading when revealing a location.
435 Org-mode often shows locations in an org-mode file which might have
436 been invisible before. When this is set, the sibling of the current entry
437 heading are all made visible. If `org-show-hierarchy-above' is t,
438 the same happens on each level of the hierarchy above the current entry.
440 By default this is on for the isearch context, off for all other contexts.
441 Turning this off for example for sparse trees makes them very compact,
442 but makes it harder to edit the location of the match. In such a case,
443 use the command \\[org-reveal] to show more context.
444 Instead of t, this can also be an alist specifying this option for different
445 contexts. See `org-show-hierarchy-above' for valid contexts."
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-entry-below '((default . nil))
450 "Non-nil means, show the entry below a headline when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the text below the headline that is
453 exposed is also shown.
455 By default this is off for all contexts.
456 Instead of t, this can also be an alist specifying this option for different
457 contexts. See `org-show-hierarchy-above' for valid contexts."
458 :group 'org-reveal-location
459 :type org-context-choice)
461 (defcustom org-indirect-buffer-display 'other-window
462 "How should indirect tree buffers be displayed?
463 This applies to indirect buffers created with the commands
464 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
465 Valid values are:
466 current-window Display in the current window
467 other-window Just display in another window.
468 dedicated-frame Create one new frame, and re-use it each time.
469 new-frame Make a new frame each time. Note that in this case
470 previously-made indirect buffers are kept, and you need to
471 kill these buffers yourself."
472 :group 'org-structure
473 :group 'org-agenda-windows
474 :type '(choice
475 (const :tag "In current window" current-window)
476 (const :tag "In current frame, other window" other-window)
477 (const :tag "Each time a new frame" new-frame)
478 (const :tag "One dedicated frame" dedicated-frame)))
480 (defgroup org-cycle nil
481 "Options concerning visibility cycling in Org-mode."
482 :tag "Org Cycle"
483 :group 'org-structure)
485 (defcustom org-drawers '("PROPERTIES" "CLOCK")
486 "Names of drawers. Drawers are not opened by cycling on the headline above.
487 Drawers only open with a TAB on the drawer line itself. A drawer looks like
488 this:
489 :DRAWERNAME:
490 .....
491 :END:
492 The drawer \"PROPERTIES\" is special for capturing properties through
493 the property API.
495 Drawers can be defined on the per-file basis with a line like:
497 #+DRAWERS: HIDDEN STATE PROPERTIES"
498 :group 'org-structure
499 :type '(repeat (string :tag "Drawer Name")))
501 (defcustom org-cycle-global-at-bob nil
502 "Cycle globally if cursor is at beginning of buffer and not at a headline.
503 This makes it possible to do global cycling without having to use S-TAB or
504 C-u TAB. For this special case to work, the first line of the buffer
505 must not be a headline - it may be empty ot some other text. When used in
506 this way, `org-cycle-hook' is disables temporarily, to make sure the
507 cursor stays at the beginning of the buffer.
508 When this option is nil, don't do anything special at the beginning
509 of the buffer."
510 :group 'org-cycle
511 :type 'boolean)
513 (defcustom org-cycle-emulate-tab t
514 "Where should `org-cycle' emulate TAB.
515 nil Never
516 white Only in completely white lines
517 whitestart Only at the beginning of lines, before the first non-white char
518 t Everywhere except in headlines
519 exc-hl-bol Everywhere except at the start of a headline
520 If TAB is used in a place where it does not emulate TAB, the current subtree
521 visibility is cycled."
522 :group 'org-cycle
523 :type '(choice (const :tag "Never" nil)
524 (const :tag "Only in completely white lines" white)
525 (const :tag "Before first char in a line" whitestart)
526 (const :tag "Everywhere except in headlines" t)
527 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
530 (defcustom org-cycle-separator-lines 2
531 "Number of empty lines needed to keep an empty line between collapsed trees.
532 If you leave an empty line between the end of a subtree and the following
533 headline, this empty line is hidden when the subtree is folded.
534 Org-mode will leave (exactly) one empty line visible if the number of
535 empty lines is equal or larger to the number given in this variable.
536 So the default 2 means, at least 2 empty lines after the end of a subtree
537 are needed to produce free space between a collapsed subtree and the
538 following headline.
540 Special case: when 0, never leave empty lines in collapsed view."
541 :group 'org-cycle
542 :type 'integer)
544 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
545 org-cycle-hide-drawers
546 org-cycle-show-empty-lines
547 org-optimize-window-after-visibility-change)
548 "Hook that is run after `org-cycle' has changed the buffer visibility.
549 The function(s) in this hook must accept a single argument which indicates
550 the new state that was set by the most recent `org-cycle' command. The
551 argument is a symbol. After a global state change, it can have the values
552 `overview', `content', or `all'. After a local state change, it can have
553 the values `folded', `children', or `subtree'."
554 :group 'org-cycle
555 :type 'hook)
557 (defgroup org-edit-structure nil
558 "Options concerning structure editing in Org-mode."
559 :tag "Org Edit Structure"
560 :group 'org-structure)
562 (defcustom org-odd-levels-only nil
563 "Non-nil means, skip even levels and only use odd levels for the outline.
564 This has the effect that two stars are being added/taken away in
565 promotion/demotion commands. It also influences how levels are
566 handled by the exporters.
567 Changing it requires restart of `font-lock-mode' to become effective
568 for fontification also in regions already fontified.
569 You may also set this on a per-file basis by adding one of the following
570 lines to the buffer:
572 #+STARTUP: odd
573 #+STARTUP: oddeven"
574 :group 'org-edit-structure
575 :group 'org-font-lock
576 :type 'boolean)
578 (defcustom org-adapt-indentation t
579 "Non-nil means, adapt indentation when promoting and demoting.
580 When this is set and the *entire* text in an entry is indented, the
581 indentation is increased by one space in a demotion command, and
582 decreased by one in a promotion command. If any line in the entry
583 body starts at column 0, indentation is not changed at all."
584 :group 'org-edit-structure
585 :type 'boolean)
587 (defcustom org-special-ctrl-a/e nil
588 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
589 When t, `C-a' will bring back the cursor to the beginning of the
590 headline text, i.e. after the stars and after a possible TODO keyword.
591 In an item, this will be the position after the bullet.
592 When the cursor is already at that position, another `C-a' will bring
593 it to the beginning of the line.
594 `C-e' will jump to the end of the headline, ignoring the presence of tags
595 in the headline. A second `C-e' will then jump to the true end of the
596 line, after any tags.
597 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
598 and only a directly following, identical keypress will bring the cursor
599 to the special positions."
600 :group 'org-edit-structure
601 :type '(choice
602 (const :tag "off" nil)
603 (const :tag "after bullet first" t)
604 (const :tag "border first" reversed)))
606 (if (fboundp 'defvaralias)
607 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
609 (defcustom org-special-ctrl-k nil
610 "Non-nil means `C-k' will behave specially in headlines.
611 When nil, `C-k' will call the default `kill-line' command.
612 When t, the following will happen while the cursor is in the headline:
614 - When the cursor is at the beginning of a headline, kill the entire
615 line and possible the folded subtree below the line.
616 - When in the middle of the headline text, kill the headline up to the tags.
617 - When after the headline text, kill the tags."
618 :group 'org-edit-structure
619 :type 'boolean)
621 (defcustom org-M-RET-may-split-line '((default . t))
622 "Non-nil means, M-RET will split the line at the cursor position.
623 When nil, it will go to the end of the line before making a
624 new line.
625 You may also set this option in a different way for different
626 contexts. Valid contexts are:
628 headline when creating a new headline
629 item when creating a new item
630 table in a table field
631 default the value to be used for all contexts not explicitly
632 customized"
633 :group 'org-structure
634 :group 'org-table
635 :type '(choice
636 (const :tag "Always" t)
637 (const :tag "Never" nil)
638 (repeat :greedy t :tag "Individual contexts"
639 (cons
640 (choice :tag "Context"
641 (const headline)
642 (const item)
643 (const table)
644 (const default))
645 (boolean)))))
648 (defcustom org-blank-before-new-entry '((heading . nil)
649 (plain-list-item . nil))
650 "Should `org-insert-heading' leave a blank line before new heading/item?
651 The value is an alist, with `heading' and `plain-list-item' as car,
652 and a boolean flag as cdr."
653 :group 'org-edit-structure
654 :type '(list
655 (cons (const heading) (boolean))
656 (cons (const plain-list-item) (boolean))))
658 (defcustom org-insert-heading-hook nil
659 "Hook being run after inserting a new heading."
660 :group 'org-edit-structure
661 :type 'hook)
663 (defcustom org-enable-fixed-width-editor t
664 "Non-nil means, lines starting with \":\" are treated as fixed-width.
665 This currently only means, they are never auto-wrapped.
666 When nil, such lines will be treated like ordinary lines.
667 See also the QUOTE keyword."
668 :group 'org-edit-structure
669 :type 'boolean)
671 (defcustom org-goto-auto-isearch t
672 "Non-nil means, typing characters in org-goto starts incremental search."
673 :group 'org-edit-structure
674 :type 'boolean)
676 (defgroup org-sparse-trees nil
677 "Options concerning sparse trees in Org-mode."
678 :tag "Org Sparse Trees"
679 :group 'org-structure)
681 (defcustom org-highlight-sparse-tree-matches t
682 "Non-nil means, highlight all matches that define a sparse tree.
683 The highlights will automatically disappear the next time the buffer is
684 changed by an edit command."
685 :group 'org-sparse-trees
686 :type 'boolean)
688 (defcustom org-remove-highlights-with-change t
689 "Non-nil means, any change to the buffer will remove temporary highlights.
690 Such highlights are created by `org-occur' and `org-clock-display'.
691 When nil, `C-c C-c needs to be used to get rid of the highlights.
692 The highlights created by `org-preview-latex-fragment' always need
693 `C-c C-c' to be removed."
694 :group 'org-sparse-trees
695 :group 'org-time
696 :type 'boolean)
699 (defcustom org-occur-hook '(org-first-headline-recenter)
700 "Hook that is run after `org-occur' has constructed a sparse tree.
701 This can be used to recenter the window to show as much of the structure
702 as possible."
703 :group 'org-sparse-trees
704 :type 'hook)
706 (defgroup org-plain-lists nil
707 "Options concerning plain lists in Org-mode."
708 :tag "Org Plain lists"
709 :group 'org-structure)
711 (defcustom org-cycle-include-plain-lists nil
712 "Non-nil means, include plain lists into visibility cycling.
713 This means that during cycling, plain list items will *temporarily* be
714 interpreted as outline headlines with a level given by 1000+i where i is the
715 indentation of the bullet. In all other operations, plain list items are
716 not seen as headlines. For example, you cannot assign a TODO keyword to
717 such an item."
718 :group 'org-plain-lists
719 :type 'boolean)
721 (defcustom org-plain-list-ordered-item-terminator t
722 "The character that makes a line with leading number an ordered list item.
723 Valid values are ?. and ?\). To get both terminators, use t. While
724 ?. may look nicer, it creates the danger that a line with leading
725 number may be incorrectly interpreted as an item. ?\) therefore is
726 the safe choice."
727 :group 'org-plain-lists
728 :type '(choice (const :tag "dot like in \"2.\"" ?.)
729 (const :tag "paren like in \"2)\"" ?\))
730 (const :tab "both" t)))
732 (defcustom org-empty-line-terminates-plain-lists nil
733 "Non-nil means, an empty line ends all plain list levels.
734 When nil, empty lines are part of the preceeding item."
735 :group 'org-plain-lists
736 :type 'boolean)
738 (defcustom org-auto-renumber-ordered-lists t
739 "Non-nil means, automatically renumber ordered plain lists.
740 Renumbering happens when the sequence have been changed with
741 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
742 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
743 :group 'org-plain-lists
744 :type 'boolean)
746 (defcustom org-provide-checkbox-statistics t
747 "Non-nil means, update checkbox statistics after insert and toggle.
748 When this is set, checkbox statistics is updated each time you either insert
749 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
750 with \\[org-ctrl-c-ctrl-c\\]."
751 :group 'org-plain-lists
752 :type 'boolean)
754 (defcustom org-description-max-indent 20
755 "Maximum indentation for the second line of a description list.
756 When the indentation would be larger than this, it will become
757 5 characters instead."
758 :group 'org-plain-lists
759 :type 'integer)
761 (defgroup org-imenu-and-speedbar nil
762 "Options concerning imenu and speedbar in Org-mode."
763 :tag "Org Imenu and Speedbar"
764 :group 'org-structure)
766 (defcustom org-imenu-depth 2
767 "The maximum level for Imenu access to Org-mode headlines.
768 This also applied for speedbar access."
769 :group 'org-imenu-and-speedbar
770 :type 'number)
772 (defgroup org-table nil
773 "Options concerning tables in Org-mode."
774 :tag "Org Table"
775 :group 'org)
777 (defcustom org-enable-table-editor 'optimized
778 "Non-nil means, lines starting with \"|\" are handled by the table editor.
779 When nil, such lines will be treated like ordinary lines.
781 When equal to the symbol `optimized', the table editor will be optimized to
782 do the following:
783 - Automatic overwrite mode in front of whitespace in table fields.
784 This makes the structure of the table stay in tact as long as the edited
785 field does not exceed the column width.
786 - Minimize the number of realigns. Normally, the table is aligned each time
787 TAB or RET are pressed to move to another field. With optimization this
788 happens only if changes to a field might have changed the column width.
789 Optimization requires replacing the functions `self-insert-command',
790 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
791 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
792 very good at guessing when a re-align will be necessary, but you can always
793 force one with \\[org-ctrl-c-ctrl-c].
795 If you would like to use the optimized version in Org-mode, but the
796 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
798 This variable can be used to turn on and off the table editor during a session,
799 but in order to toggle optimization, a restart is required.
801 See also the variable `org-table-auto-blank-field'."
802 :group 'org-table
803 :type '(choice
804 (const :tag "off" nil)
805 (const :tag "on" t)
806 (const :tag "on, optimized" optimized)))
808 (defcustom org-table-tab-recognizes-table.el t
809 "Non-nil means, TAB will automatically notice a table.el table.
810 When it sees such a table, it moves point into it and - if necessary -
811 calls `table-recognize-table'."
812 :group 'org-table-editing
813 :type 'boolean)
815 (defgroup org-link nil
816 "Options concerning links in Org-mode."
817 :tag "Org Link"
818 :group 'org)
820 (defvar org-link-abbrev-alist-local nil
821 "Buffer-local version of `org-link-abbrev-alist', which see.
822 The value of this is taken from the #+LINK lines.")
823 (make-variable-buffer-local 'org-link-abbrev-alist-local)
825 (defcustom org-link-abbrev-alist nil
826 "Alist of link abbreviations.
827 The car of each element is a string, to be replaced at the start of a link.
828 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
829 links in Org-mode buffers can have an optional tag after a double colon, e.g.
831 [[linkkey:tag][description]]
833 If REPLACE is a string, the tag will simply be appended to create the link.
834 If the string contains \"%s\", the tag will be inserted there.
836 REPLACE may also be a function that will be called with the tag as the
837 only argument to create the link, which should be returned as a string.
839 See the manual for examples."
840 :group 'org-link
841 :type 'alist)
843 (defcustom org-descriptive-links t
844 "Non-nil means, hide link part and only show description of bracket links.
845 Bracket links are like [[link][descritpion]]. This variable sets the initial
846 state in new org-mode buffers. The setting can then be toggled on a
847 per-buffer basis from the Org->Hyperlinks menu."
848 :group 'org-link
849 :type 'boolean)
851 (defcustom org-link-file-path-type 'adaptive
852 "How the path name in file links should be stored.
853 Valid values are:
855 relative Relative to the current directory, i.e. the directory of the file
856 into which the link is being inserted.
857 absolute Absolute path, if possible with ~ for home directory.
858 noabbrev Absolute path, no abbreviation of home directory.
859 adaptive Use relative path for files in the current directory and sub-
860 directories of it. For other files, use an absolute path."
861 :group 'org-link
862 :type '(choice
863 (const relative)
864 (const absolute)
865 (const noabbrev)
866 (const adaptive)))
868 (defcustom org-activate-links '(bracket angle plain radio tag date)
869 "Types of links that should be activated in Org-mode files.
870 This is a list of symbols, each leading to the activation of a certain link
871 type. In principle, it does not hurt to turn on most link types - there may
872 be a small gain when turning off unused link types. The types are:
874 bracket The recommended [[link][description]] or [[link]] links with hiding.
875 angular Links in angular brackes that may contain whitespace like
876 <bbdb:Carsten Dominik>.
877 plain Plain links in normal text, no whitespace, like http://google.com.
878 radio Text that is matched by a radio target, see manual for details.
879 tag Tag settings in a headline (link to tag search).
880 date Time stamps (link to calendar).
882 Changing this variable requires a restart of Emacs to become effective."
883 :group 'org-link
884 :type '(set (const :tag "Double bracket links (new style)" bracket)
885 (const :tag "Angular bracket links (old style)" angular)
886 (const :tag "Plain text links" plain)
887 (const :tag "Radio target matches" radio)
888 (const :tag "Tags" tag)
889 (const :tag "Timestamps" date)))
891 (defcustom org-make-link-description-function nil
892 "Function to use to generate link descriptions from links. If
893 nil the link location will be used. This function must take two
894 parameters; the first is the link and the second the description
895 org-insert-link has generated, and should return the description
896 to use."
897 :group 'org-link
898 :type 'function)
900 (defgroup org-link-store nil
901 "Options concerning storing links in Org-mode."
902 :tag "Org Store Link"
903 :group 'org-link)
905 (defcustom org-email-link-description-format "Email %c: %.30s"
906 "Format of the description part of a link to an email or usenet message.
907 The following %-excapes will be replaced by corresponding information:
909 %F full \"From\" field
910 %f name, taken from \"From\" field, address if no name
911 %T full \"To\" field
912 %t first name in \"To\" field, address if no name
913 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
914 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
915 %s subject
916 %m message-id.
918 You may use normal field width specification between the % and the letter.
919 This is for example useful to limit the length of the subject.
921 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
922 :group 'org-link-store
923 :type 'string)
925 (defcustom org-from-is-user-regexp
926 (let (r1 r2)
927 (when (and user-mail-address (not (string= user-mail-address "")))
928 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
929 (when (and user-full-name (not (string= user-full-name "")))
930 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
931 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
932 "Regexp mached against the \"From:\" header of an email or usenet message.
933 It should match if the message is from the user him/herself."
934 :group 'org-link-store
935 :type 'regexp)
937 (defcustom org-context-in-file-links t
938 "Non-nil means, file links from `org-store-link' contain context.
939 A search string will be added to the file name with :: as separator and
940 used to find the context when the link is activated by the command
941 `org-open-at-point'.
942 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
943 negates this setting for the duration of the command."
944 :group 'org-link-store
945 :type 'boolean)
947 (defcustom org-keep-stored-link-after-insertion nil
948 "Non-nil means, keep link in list for entire session.
950 The command `org-store-link' adds a link pointing to the current
951 location to an internal list. These links accumulate during a session.
952 The command `org-insert-link' can be used to insert links into any
953 Org-mode file (offering completion for all stored links). When this
954 option is nil, every link which has been inserted once using \\[org-insert-link]
955 will be removed from the list, to make completing the unused links
956 more efficient."
957 :group 'org-link-store
958 :type 'boolean)
960 (defgroup org-link-follow nil
961 "Options concerning following links in Org-mode."
962 :tag "Org Follow Link"
963 :group 'org-link)
965 (defcustom org-follow-link-hook nil
966 "Hook that is run after a link has been followed."
967 :group 'org-link-follow
968 :type 'hook)
970 (defcustom org-tab-follows-link nil
971 "Non-nil means, on links TAB will follow the link.
972 Needs to be set before org.el is loaded."
973 :group 'org-link-follow
974 :type 'boolean)
976 (defcustom org-return-follows-link nil
977 "Non-nil means, on links RET will follow the link.
978 Needs to be set before org.el is loaded."
979 :group 'org-link-follow
980 :type 'boolean)
982 (defcustom org-mouse-1-follows-link
983 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
984 "Non-nil means, mouse-1 on a link will follow the link.
985 A longer mouse click will still set point. Does not work on XEmacs.
986 Needs to be set before org.el is loaded."
987 :group 'org-link-follow
988 :type 'boolean)
990 (defcustom org-mark-ring-length 4
991 "Number of different positions to be recorded in the ring
992 Changing this requires a restart of Emacs to work correctly."
993 :group 'org-link-follow
994 :type 'interger)
996 (defcustom org-link-frame-setup
997 '((vm . vm-visit-folder-other-frame)
998 (gnus . gnus-other-frame)
999 (file . find-file-other-window))
1000 "Setup the frame configuration for following links.
1001 When following a link with Emacs, it may often be useful to display
1002 this link in another window or frame. This variable can be used to
1003 set this up for the different types of links.
1004 For VM, use any of
1005 `vm-visit-folder'
1006 `vm-visit-folder-other-frame'
1007 For Gnus, use any of
1008 `gnus'
1009 `gnus-other-frame'
1010 For FILE, use any of
1011 `find-file'
1012 `find-file-other-window'
1013 `find-file-other-frame'
1014 For the calendar, use the variable `calendar-setup'.
1015 For BBDB, it is currently only possible to display the matches in
1016 another window."
1017 :group 'org-link-follow
1018 :type '(list
1019 (cons (const vm)
1020 (choice
1021 (const vm-visit-folder)
1022 (const vm-visit-folder-other-window)
1023 (const vm-visit-folder-other-frame)))
1024 (cons (const gnus)
1025 (choice
1026 (const gnus)
1027 (const gnus-other-frame)))
1028 (cons (const file)
1029 (choice
1030 (const find-file)
1031 (const find-file-other-window)
1032 (const find-file-other-frame)))))
1034 (defcustom org-display-internal-link-with-indirect-buffer nil
1035 "Non-nil means, use indirect buffer to display infile links.
1036 Activating internal links (from one location in a file to another location
1037 in the same file) normally just jumps to the location. When the link is
1038 activated with a C-u prefix (or with mouse-3), the link is displayed in
1039 another window. When this option is set, the other window actually displays
1040 an indirect buffer clone of the current buffer, to avoid any visibility
1041 changes to the current buffer."
1042 :group 'org-link-follow
1043 :type 'boolean)
1045 (defcustom org-open-non-existing-files nil
1046 "Non-nil means, `org-open-file' will open non-existing files.
1047 When nil, an error will be generated."
1048 :group 'org-link-follow
1049 :type 'boolean)
1051 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1052 "Function and arguments to call for following mailto links.
1053 This is a list with the first element being a lisp function, and the
1054 remaining elements being arguments to the function. In string arguments,
1055 %a will be replaced by the address, and %s will be replaced by the subject
1056 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1057 :group 'org-link-follow
1058 :type '(choice
1059 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1060 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1061 (const :tag "message-mail" (message-mail "%a" "%s"))
1062 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1064 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1065 "Non-nil means, ask for confirmation before executing shell links.
1066 Shell links can be dangerous: just think about a link
1068 [[shell:rm -rf ~/*][Google Search]]
1070 This link would show up in your Org-mode document as \"Google Search\",
1071 but really it would remove your entire home directory.
1072 Therefore we advise against setting this variable to nil.
1073 Just change it to `y-or-n-p' of you want to confirm with a
1074 single keystroke rather than having to type \"yes\"."
1075 :group 'org-link-follow
1076 :type '(choice
1077 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1078 (const :tag "with y-or-n (faster)" y-or-n-p)
1079 (const :tag "no confirmation (dangerous)" nil)))
1081 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1082 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1083 Elisp links can be dangerous: just think about a link
1085 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1087 This link would show up in your Org-mode document as \"Google Search\",
1088 but really it would remove your entire home directory.
1089 Therefore we advise against setting this variable to nil.
1090 Just change it to `y-or-n-p' of you want to confirm with a
1091 single keystroke rather than having to type \"yes\"."
1092 :group 'org-link-follow
1093 :type '(choice
1094 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1095 (const :tag "with y-or-n (faster)" y-or-n-p)
1096 (const :tag "no confirmation (dangerous)" nil)))
1098 (defconst org-file-apps-defaults-gnu
1099 '((remote . emacs)
1100 (t . mailcap))
1101 "Default file applications on a UNIX or GNU/Linux system.
1102 See `org-file-apps'.")
1104 (defconst org-file-apps-defaults-macosx
1105 '((remote . emacs)
1106 (t . "open %s")
1107 ("ps" . "gv %s")
1108 ("ps.gz" . "gv %s")
1109 ("eps" . "gv %s")
1110 ("eps.gz" . "gv %s")
1111 ("dvi" . "xdvi %s")
1112 ("fig" . "xfig %s"))
1113 "Default file applications on a MacOS X system.
1114 The system \"open\" is known as a default, but we use X11 applications
1115 for some files for which the OS does not have a good default.
1116 See `org-file-apps'.")
1118 (defconst org-file-apps-defaults-windowsnt
1119 (list
1120 '(remote . emacs)
1121 (cons t
1122 (list (if (featurep 'xemacs)
1123 'mswindows-shell-execute
1124 'w32-shell-execute)
1125 "open" 'file)))
1126 "Default file applications on a Windows NT system.
1127 The system \"open\" is used for most files.
1128 See `org-file-apps'.")
1130 (defcustom org-file-apps
1132 ("txt" . emacs)
1133 ("tex" . emacs)
1134 ("ltx" . emacs)
1135 ("org" . emacs)
1136 ("el" . emacs)
1137 ("bib" . emacs)
1139 "External applications for opening `file:path' items in a document.
1140 Org-mode uses system defaults for different file types, but
1141 you can use this variable to set the application for a given file
1142 extension. The entries in this list are cons cells where the car identifies
1143 files and the cdr the corresponding command. Possible values for the
1144 file identifier are
1145 \"ext\" A string identifying an extension
1146 `directory' Matches a directory
1147 `remote' Matches a remote file, accessible through tramp or efs.
1148 Remote files most likely should be visited through Emacs
1149 because external applications cannot handle such paths.
1150 t Default for all remaining files
1152 Possible values for the command are:
1153 `emacs' The file will be visited by the current Emacs process.
1154 `default' Use the default application for this file type.
1155 string A command to be executed by a shell; %s will be replaced
1156 by the path to the file.
1157 sexp A Lisp form which will be evaluated. The file path will
1158 be available in the Lisp variable `file'.
1159 For more examples, see the system specific constants
1160 `org-file-apps-defaults-macosx'
1161 `org-file-apps-defaults-windowsnt'
1162 `org-file-apps-defaults-gnu'."
1163 :group 'org-link-follow
1164 :type '(repeat
1165 (cons (choice :value ""
1166 (string :tag "Extension")
1167 (const :tag "Default for unrecognized files" t)
1168 (const :tag "Remote file" remote)
1169 (const :tag "Links to a directory" directory))
1170 (choice :value ""
1171 (const :tag "Visit with Emacs" emacs)
1172 (const :tag "Use system default" default)
1173 (string :tag "Command")
1174 (sexp :tag "Lisp form")))))
1176 (defgroup org-refile nil
1177 "Options concerning refiling entries in Org-mode."
1178 :tag "Org Remember"
1179 :group 'org)
1181 (defcustom org-directory "~/org"
1182 "Directory with org files.
1183 This directory will be used as default to prompt for org files.
1184 Used by the hooks for remember.el."
1185 :group 'org-refile
1186 :group 'org-remember
1187 :type 'directory)
1189 (defcustom org-default-notes-file "~/.notes"
1190 "Default target for storing notes.
1191 Used by the hooks for remember.el. This can be a string, or nil to mean
1192 the value of `remember-data-file'.
1193 You can set this on a per-template basis with the variable
1194 `org-remember-templates'."
1195 :group 'org-refile
1196 :group 'org-remember
1197 :type '(choice
1198 (const :tag "Default from remember-data-file" nil)
1199 file))
1201 (defcustom org-goto-interface 'outline
1202 "The default interface to be used for `org-goto'.
1203 Allowed vaues are:
1204 outline The interface shows an outline of the relevant file
1205 and the correct heading is found by moving through
1206 the outline or by searching with incremental search.
1207 outline-path-completion Headlines in the current buffer are offered via
1208 completion."
1209 :group 'org-refile
1210 :type '(choice
1211 (const :tag "Outline" outline)
1212 (const :tag "Outline-path-completion" outline-path-completion)))
1214 (defcustom org-reverse-note-order nil
1215 "Non-nil means, store new notes at the beginning of a file or entry.
1216 When nil, new notes will be filed to the end of a file or entry.
1217 This can also be a list with cons cells of regular expressions that
1218 are matched against file names, and values."
1219 :group 'org-remember
1220 :type '(choice
1221 (const :tag "Reverse always" t)
1222 (const :tag "Reverse never" nil)
1223 (repeat :tag "By file name regexp"
1224 (cons regexp boolean))))
1226 (defcustom org-refile-targets nil
1227 "Targets for refiling entries with \\[org-refile].
1228 This is list of cons cells. Each cell contains:
1229 - a specification of the files to be considered, either a list of files,
1230 or a symbol whose function or variable value will be used to retrieve
1231 a file name or a list of file names. Nil means, refile to a different
1232 heading in the current buffer.
1233 - A specification of how to find candidate refile targets. This may be
1234 any of
1235 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1236 This tag has to be present in all target headlines, inheritance will
1237 not be considered.
1238 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1239 todo keyword.
1240 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1241 headlines that are refiling targets.
1242 - a cons cell (:level . N). Any headline of level N is considered a target.
1243 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1244 :group 'org-remember
1245 :type '(repeat
1246 (cons
1247 (choice :value org-agenda-files
1248 (const :tag "All agenda files" org-agenda-files)
1249 (const :tag "Current buffer" nil)
1250 (function) (variable) (file))
1251 (choice :tag "Identify target headline by"
1252 (cons :tag "Specific tag" (const :tag) (string))
1253 (cons :tag "TODO keyword" (const :todo) (string))
1254 (cons :tag "Regular expression" (const :regexp) (regexp))
1255 (cons :tag "Level number" (const :level) (integer))
1256 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1258 (defcustom org-refile-use-outline-path nil
1259 "Non-nil means, provide refile targets as paths.
1260 So a level 3 headline will be available as level1/level2/level3.
1261 When the value is `file', also include the file name (without directory)
1262 into the path. When `full-file-path', include the full file path."
1263 :group 'org-remember
1264 :type '(choice
1265 (const :tag "Not" nil)
1266 (const :tag "Yes" t)
1267 (const :tag "Start with file name" file)
1268 (const :tag "Start with full file path" full-file-path)))
1270 (defgroup org-todo nil
1271 "Options concerning TODO items in Org-mode."
1272 :tag "Org TODO"
1273 :group 'org)
1275 (defgroup org-progress nil
1276 "Options concerning Progress logging in Org-mode."
1277 :tag "Org Progress"
1278 :group 'org-time)
1280 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1281 "List of TODO entry keyword sequences and their interpretation.
1282 \\<org-mode-map>This is a list of sequences.
1284 Each sequence starts with a symbol, either `sequence' or `type',
1285 indicating if the keywords should be interpreted as a sequence of
1286 action steps, or as different types of TODO items. The first
1287 keywords are states requiring action - these states will select a headline
1288 for inclusion into the global TODO list Org-mode produces. If one of
1289 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1290 signify that no further action is necessary. If \"|\" is not found,
1291 the last keyword is treated as the only DONE state of the sequence.
1293 The command \\[org-todo] cycles an entry through these states, and one
1294 additional state where no keyword is present. For details about this
1295 cycling, see the manual.
1297 TODO keywords and interpretation can also be set on a per-file basis with
1298 the special #+SEQ_TODO and #+TYP_TODO lines.
1300 Each keyword can optionally specify a character for fast state selection
1301 \(in combination with the variable `org-use-fast-todo-selection')
1302 and specifiers for state change logging, using the same syntax
1303 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1304 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1305 indicates to record a time stamp each time this state is selected.
1307 Each keyword may also specify if a timestamp or a note should be
1308 recorded when entering or leaving the state, by adding additional
1309 characters in the parenthesis after the keyword. This looks like this:
1310 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1311 record only the time of the state change. With X and Y being either
1312 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1313 Y when leaving the state if and only if the *target* state does not
1314 define X. You may omit any of the fast-selection key or X or /Y,
1315 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1317 For backward compatibility, this variable may also be just a list
1318 of keywords - in this case the interptetation (sequence or type) will be
1319 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1320 :group 'org-todo
1321 :group 'org-keywords
1322 :type '(choice
1323 (repeat :tag "Old syntax, just keywords"
1324 (string :tag "Keyword"))
1325 (repeat :tag "New syntax"
1326 (cons
1327 (choice
1328 :tag "Interpretation"
1329 (const :tag "Sequence (cycling hits every state)" sequence)
1330 (const :tag "Type (cycling directly to DONE)" type))
1331 (repeat
1332 (string :tag "Keyword"))))))
1334 (defvar org-todo-keywords-1 nil
1335 "All TODO and DONE keywords active in a buffer.")
1336 (make-variable-buffer-local 'org-todo-keywords-1)
1337 (defvar org-todo-keywords-for-agenda nil)
1338 (defvar org-done-keywords-for-agenda nil)
1339 (defvar org-agenda-contributing-files nil)
1340 (defvar org-not-done-keywords nil)
1341 (make-variable-buffer-local 'org-not-done-keywords)
1342 (defvar org-done-keywords nil)
1343 (make-variable-buffer-local 'org-done-keywords)
1344 (defvar org-todo-heads nil)
1345 (make-variable-buffer-local 'org-todo-heads)
1346 (defvar org-todo-sets nil)
1347 (make-variable-buffer-local 'org-todo-sets)
1348 (defvar org-todo-log-states nil)
1349 (make-variable-buffer-local 'org-todo-log-states)
1350 (defvar org-todo-kwd-alist nil)
1351 (make-variable-buffer-local 'org-todo-kwd-alist)
1352 (defvar org-todo-key-alist nil)
1353 (make-variable-buffer-local 'org-todo-key-alist)
1354 (defvar org-todo-key-trigger nil)
1355 (make-variable-buffer-local 'org-todo-key-trigger)
1357 (defcustom org-todo-interpretation 'sequence
1358 "Controls how TODO keywords are interpreted.
1359 This variable is in principle obsolete and is only used for
1360 backward compatibility, if the interpretation of todo keywords is
1361 not given already in `org-todo-keywords'. See that variable for
1362 more information."
1363 :group 'org-todo
1364 :group 'org-keywords
1365 :type '(choice (const sequence)
1366 (const type)))
1368 (defcustom org-use-fast-todo-selection 'prefix
1369 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1370 This variable describes if and under what circumstances the cycling
1371 mechanism for TODO keywords will be replaced by a single-key, direct
1372 selection scheme.
1374 When nil, fast selection is never used.
1376 When the symbol `prefix', it will be used when `org-todo' is called with
1377 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1378 in an agenda buffer.
1380 When t, fast selection is used by default. In this case, the prefix
1381 argument forces cycling instead.
1383 In all cases, the special interface is only used if access keys have actually
1384 been assigned by the user, i.e. if keywords in the configuration are followed
1385 by a letter in parenthesis, like TODO(t)."
1386 :group 'org-todo
1387 :type '(choice
1388 (const :tag "Never" nil)
1389 (const :tag "By default" t)
1390 (const :tag "Only with C-u C-c C-t" prefix)))
1392 (defcustom org-provide-todo-statistics t
1393 "Non-nil means, update todo statistics after insert and toggle.
1394 When this is set, todo statistics is updated in the parent of the current
1395 entry each time a todo state is changed."
1396 :group 'org-todo
1397 :type 'boolean)
1399 (defcustom org-after-todo-state-change-hook nil
1400 "Hook which is run after the state of a TODO item was changed.
1401 The new state (a string with a TODO keyword, or nil) is available in the
1402 Lisp variable `state'."
1403 :group 'org-todo
1404 :type 'hook)
1406 (defcustom org-log-done nil
1407 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1408 When equal to the list (done), also prompt for a closing note.
1409 This can also be configured on a per-file basis by adding one of
1410 the following lines anywhere in the buffer:
1412 #+STARTUP: logdone
1413 #+STARTUP: lognotedone
1414 #+STARTUP: nologdone"
1415 :group 'org-todo
1416 :group 'org-progress
1417 :type '(choice
1418 (const :tag "No logging" nil)
1419 (const :tag "Record CLOSED timestamp" time)
1420 (const :tag "Record CLOSED timestamp with closing note." note)))
1422 ;; Normalize old uses of org-log-done.
1423 (cond
1424 ((eq org-log-done t) (setq org-log-done 'time))
1425 ((and (listp org-log-done) (memq 'done org-log-done))
1426 (setq org-log-done 'note)))
1428 (defcustom org-log-note-clock-out nil
1429 "Non-nil means, recored a note when clocking out of an item.
1430 This can also be configured on a per-file basis by adding one of
1431 the following lines anywhere in the buffer:
1433 #+STARTUP: lognoteclock-out
1434 #+STARTUP: nolognoteclock-out"
1435 :group 'org-todo
1436 :group 'org-progress
1437 :type 'boolean)
1439 (defcustom org-log-done-with-time t
1440 "Non-nil means, the CLOSED time stamp will contain date and time.
1441 When nil, only the date will be recorded."
1442 :group 'org-progress
1443 :type 'boolean)
1445 (defcustom org-log-note-headings
1446 '((done . "CLOSING NOTE %t")
1447 (state . "State %-12s %t")
1448 (note . "Note taken on %t")
1449 (clock-out . ""))
1450 "Headings for notes added to entries.
1451 The value is an alist, with the car being a symbol indicating the note
1452 context, and the cdr is the heading to be used. The heading may also be the
1453 empty string.
1454 %t in the heading will be replaced by a time stamp.
1455 %s will be replaced by the new TODO state, in double quotes.
1456 %u will be replaced by the user name.
1457 %U will be replaced by the full user name."
1458 :group 'org-todo
1459 :group 'org-progress
1460 :type '(list :greedy t
1461 (cons (const :tag "Heading when closing an item" done) string)
1462 (cons (const :tag
1463 "Heading when changing todo state (todo sequence only)"
1464 state) string)
1465 (cons (const :tag "Heading when just taking a note" note) string)
1466 (cons (const :tag "Heading when clocking out" clock-out) string)))
1468 (unless (assq 'note org-log-note-headings)
1469 (push '(note . "%t") org-log-note-headings))
1471 (defcustom org-log-states-order-reversed t
1472 "Non-nil means, the latest state change note will be directly after heading.
1473 When nil, the notes will be orderer according to time."
1474 :group 'org-todo
1475 :group 'org-progress
1476 :type 'boolean)
1478 (defcustom org-log-repeat 'time
1479 "Non-nil means, record moving through the DONE state when triggering repeat.
1480 An auto-repeating tasks is immediately switched back to TODO when marked
1481 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1482 the TODO keyword definition, or recording a closing note by setting
1483 `org-log-done', there will be no record of the task moving through DONE.
1484 This variable forces taking a note anyway. Possible values are:
1486 nil Don't force a record
1487 time Record a time stamp
1488 note Record a note
1490 This option can also be set with on a per-file-basis with
1492 #+STARTUP: logrepeat
1493 #+STARTUP: lognoterepeat
1494 #+STARTUP: nologrepeat
1496 You can have local logging settings for a subtree by setting the LOGGING
1497 property to one or more of these keywords."
1498 :group 'org-todo
1499 :group 'org-progress
1500 :type '(choice
1501 (const :tag "Don't force a record" nil)
1502 (const :tag "Force recording the DONE state" time)
1503 (const :tag "Force recording a note with the DONE state" note)))
1506 (defgroup org-priorities nil
1507 "Priorities in Org-mode."
1508 :tag "Org Priorities"
1509 :group 'org-todo)
1511 (defcustom org-highest-priority ?A
1512 "The highest priority of TODO items. A character like ?A, ?B etc.
1513 Must have a smaller ASCII number than `org-lowest-priority'."
1514 :group 'org-priorities
1515 :type 'character)
1517 (defcustom org-lowest-priority ?C
1518 "The lowest priority of TODO items. A character like ?A, ?B etc.
1519 Must have a larger ASCII number than `org-highest-priority'."
1520 :group 'org-priorities
1521 :type 'character)
1523 (defcustom org-default-priority ?B
1524 "The default priority of TODO items.
1525 This is the priority an item get if no explicit priority is given."
1526 :group 'org-priorities
1527 :type 'character)
1529 (defcustom org-priority-start-cycle-with-default t
1530 "Non-nil means, start with default priority when starting to cycle.
1531 When this is nil, the first step in the cycle will be (depending on the
1532 command used) one higher or lower that the default priority."
1533 :group 'org-priorities
1534 :type 'boolean)
1536 (defgroup org-time nil
1537 "Options concerning time stamps and deadlines in Org-mode."
1538 :tag "Org Time"
1539 :group 'org)
1541 (defcustom org-insert-labeled-timestamps-at-point nil
1542 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1543 When nil, these labeled time stamps are forces into the second line of an
1544 entry, just after the headline. When scheduling from the global TODO list,
1545 the time stamp will always be forced into the second line."
1546 :group 'org-time
1547 :type 'boolean)
1549 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1550 "Formats for `format-time-string' which are used for time stamps.
1551 It is not recommended to change this constant.")
1553 (defcustom org-time-stamp-rounding-minutes '(0 5)
1554 "Number of minutes to round time stamps to.
1555 These are two values, the first applies when first creating a time stamp.
1556 The second applies when changing it with the commands `S-up' and `S-down'.
1557 When changing the time stamp, this means that it will change in steps
1558 of N minutes, as given by the second value.
1560 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1561 numbers should be factors of 60, so for example 5, 10, 15.
1563 When this is larger than 1, you can still force an exact time-stamp by using
1564 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1565 and by using a prefix arg to `S-up/down' to specify the exact number
1566 of minutes to shift."
1567 :group 'org-time
1568 :get '(lambda (var) ; Make sure all entries have 5 elements
1569 (if (integerp (default-value var))
1570 (list (default-value var) 5)
1571 (default-value var)))
1572 :type '(list
1573 (integer :tag "when inserting times")
1574 (integer :tag "when modifying times")))
1576 ;; Normalize old customizations of this variable.
1577 (when (integerp org-time-stamp-rounding-minutes)
1578 (setq org-time-stamp-rounding-minutes
1579 (list org-time-stamp-rounding-minutes
1580 org-time-stamp-rounding-minutes)))
1582 (defcustom org-display-custom-times nil
1583 "Non-nil means, overlay custom formats over all time stamps.
1584 The formats are defined through the variable `org-time-stamp-custom-formats'.
1585 To turn this on on a per-file basis, insert anywhere in the file:
1586 #+STARTUP: customtime"
1587 :group 'org-time
1588 :set 'set-default
1589 :type 'sexp)
1590 (make-variable-buffer-local 'org-display-custom-times)
1592 (defcustom org-time-stamp-custom-formats
1593 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1594 "Custom formats for time stamps. See `format-time-string' for the syntax.
1595 These are overlayed over the default ISO format if the variable
1596 `org-display-custom-times' is set. Time like %H:%M should be at the
1597 end of the second format."
1598 :group 'org-time
1599 :type 'sexp)
1601 (defun org-time-stamp-format (&optional long inactive)
1602 "Get the right format for a time string."
1603 (let ((f (if long (cdr org-time-stamp-formats)
1604 (car org-time-stamp-formats))))
1605 (if inactive
1606 (concat "[" (substring f 1 -1) "]")
1607 f)))
1609 (defcustom org-time-clocksum-format "%d:%02d"
1610 "The format string used when creating CLOCKSUM lines, or when
1611 org-mode generates a time duration."
1612 :group 'org-time
1613 :type 'string)
1615 (defcustom org-deadline-warning-days 14
1616 "No. of days before expiration during which a deadline becomes active.
1617 This variable governs the display in sparse trees and in the agenda.
1618 When 0 or negative, it means use this number (the absolute value of it)
1619 even if a deadline has a different individual lead time specified."
1620 :group 'org-time
1621 :group 'org-agenda-daily/weekly
1622 :type 'number)
1624 (defcustom org-read-date-prefer-future t
1625 "Non-nil means, assume future for incomplete date input from user.
1626 This affects the following situations:
1627 1. The user gives a day, but no month.
1628 For example, if today is the 15th, and you enter \"3\", Org-mode will
1629 read this as the third of *next* month. However, if you enter \"17\",
1630 it will be considered as *this* month.
1631 2. The user gives a month but not a year.
1632 For example, if it is april and you enter \"feb 2\", this will be read
1633 as feb 2, *next* year. \"May 5\", however, will be this year.
1635 Currently this does not work for ISO week specifications.
1637 When this option is nil, the current month and year will always be used
1638 as defaults."
1639 :group 'org-time
1640 :type 'boolean)
1642 (defcustom org-read-date-display-live t
1643 "Non-nil means, display current interpretation of date prompt live.
1644 This display will be in an overlay, in the minibuffer."
1645 :group 'org-time
1646 :type 'boolean)
1648 (defcustom org-read-date-popup-calendar t
1649 "Non-nil means, pop up a calendar when prompting for a date.
1650 In the calendar, the date can be selected with mouse-1. However, the
1651 minibuffer will also be active, and you can simply enter the date as well.
1652 When nil, only the minibuffer will be available."
1653 :group 'org-time
1654 :type 'boolean)
1655 (if (fboundp 'defvaralias)
1656 (defvaralias 'org-popup-calendar-for-date-prompt
1657 'org-read-date-popup-calendar))
1659 (defcustom org-extend-today-until 0
1660 "The hour when your day really ends.
1661 This has influence for the following applications:
1662 - When switching the agenda to \"today\". It it is still earlier than
1663 the time given here, the day recognized as TODAY is actually yesterday.
1664 - When a date is read from the user and it is still before the time given
1665 here, the current date and time will be assumed to be yesterday, 23:59.
1667 FIXME:
1668 IMPORTANT: This is still a very experimental feature, it may disappear
1669 again or it may be extended to mean more things."
1670 :group 'org-time
1671 :type 'number)
1673 (defcustom org-edit-timestamp-down-means-later nil
1674 "Non-nil means, S-down will increase the time in a time stamp.
1675 When nil, S-up will increase."
1676 :group 'org-time
1677 :type 'boolean)
1679 (defcustom org-calendar-follow-timestamp-change t
1680 "Non-nil means, make the calendar window follow timestamp changes.
1681 When a timestamp is modified and the calendar window is visible, it will be
1682 moved to the new date."
1683 :group 'org-time
1684 :type 'boolean)
1686 (defgroup org-tags nil
1687 "Options concerning tags in Org-mode."
1688 :tag "Org Tags"
1689 :group 'org)
1691 (defcustom org-tag-alist nil
1692 "List of tags allowed in Org-mode files.
1693 When this list is nil, Org-mode will base TAG input on what is already in the
1694 buffer.
1695 The value of this variable is an alist, the car of each entry must be a
1696 keyword as a string, the cdr may be a character that is used to select
1697 that tag through the fast-tag-selection interface.
1698 See the manual for details."
1699 :group 'org-tags
1700 :type '(repeat
1701 (choice
1702 (cons (string :tag "Tag name")
1703 (character :tag "Access char"))
1704 (const :tag "Start radio group" (:startgroup))
1705 (const :tag "End radio group" (:endgroup)))))
1707 (defvar org-file-tags nil
1708 "List of tags that can be inherited by all entries in the file.
1709 The tags will be inherited if the variable `org-use-tag-inheritance'
1710 says they should be.
1711 This variable is populated from #+TAG lines.")
1713 (defcustom org-use-fast-tag-selection 'auto
1714 "Non-nil means, use fast tag selection scheme.
1715 This is a special interface to select and deselect tags with single keys.
1716 When nil, fast selection is never used.
1717 When the symbol `auto', fast selection is used if and only if selection
1718 characters for tags have been configured, either through the variable
1719 `org-tag-alist' or through a #+TAGS line in the buffer.
1720 When t, fast selection is always used and selection keys are assigned
1721 automatically if necessary."
1722 :group 'org-tags
1723 :type '(choice
1724 (const :tag "Always" t)
1725 (const :tag "Never" nil)
1726 (const :tag "When selection characters are configured" 'auto)))
1728 (defcustom org-fast-tag-selection-single-key nil
1729 "Non-nil means, fast tag selection exits after first change.
1730 When nil, you have to press RET to exit it.
1731 During fast tag selection, you can toggle this flag with `C-c'.
1732 This variable can also have the value `expert'. In this case, the window
1733 displaying the tags menu is not even shown, until you press C-c again."
1734 :group 'org-tags
1735 :type '(choice
1736 (const :tag "No" nil)
1737 (const :tag "Yes" t)
1738 (const :tag "Expert" expert)))
1740 (defvar org-fast-tag-selection-include-todo nil
1741 "Non-nil means, fast tags selection interface will also offer TODO states.
1742 This is an undocumented feature, you should not rely on it.")
1744 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1745 "The column to which tags should be indented in a headline.
1746 If this number is positive, it specifies the column. If it is negative,
1747 it means that the tags should be flushright to that column. For example,
1748 -80 works well for a normal 80 character screen."
1749 :group 'org-tags
1750 :type 'integer)
1752 (defcustom org-auto-align-tags t
1753 "Non-nil means, realign tags after pro/demotion of TODO state change.
1754 These operations change the length of a headline and therefore shift
1755 the tags around. With this options turned on, after each such operation
1756 the tags are again aligned to `org-tags-column'."
1757 :group 'org-tags
1758 :type 'boolean)
1760 (defcustom org-use-tag-inheritance t
1761 "Non-nil means, tags in levels apply also for sublevels.
1762 When nil, only the tags directly given in a specific line apply there.
1763 If this option is t, a match early-on in a tree can lead to a large
1764 number of matches in the subtree. If you only want to see the first
1765 match in a tree during a search, check out the variable
1766 `org-tags-match-list-sublevels'.
1768 This may also be a list of tags that should be inherited, or a regexp that
1769 matches tags that should be inherited."
1770 :group 'org-tags
1771 :type '(choice
1772 (const :tag "Not" nil)
1773 (const :tag "Always" t)
1774 (repeat :tag "Specific tags" (string :tag "Tag"))
1775 (regexp :tag "Tags matched by regexp")))
1777 (defun org-tag-inherit-p (tag)
1778 "Check if TAG is one that should be inherited."
1779 (cond
1780 ((eq org-use-tag-inheritance t) t)
1781 ((not org-use-tag-inheritance) nil)
1782 ((stringp org-use-tag-inheritance)
1783 (string-match org-use-tag-inheritance tag))
1784 ((listp org-use-tag-inheritance)
1785 (member tag org-use-tag-inheritance))
1786 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1788 (defcustom org-tags-match-list-sublevels t
1789 "Non-nil means list also sublevels of headlines matching tag search.
1790 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1791 the sublevels of a headline matching a tag search often also match
1792 the same search. Listing all of them can create very long lists.
1793 Setting this variable to nil causes subtrees of a match to be skipped.
1794 This option is off by default, because inheritance in on. If you turn
1795 inheritance off, you very likely want to turn this option on.
1797 As a special case, if the tag search is restricted to TODO items, the
1798 value of this variable is ignored and sublevels are always checked, to
1799 make sure all corresponding TODO items find their way into the list."
1800 :group 'org-tags
1801 :type 'boolean)
1803 (defvar org-tags-history nil
1804 "History of minibuffer reads for tags.")
1805 (defvar org-last-tags-completion-table nil
1806 "The last used completion table for tags.")
1807 (defvar org-after-tags-change-hook nil
1808 "Hook that is run after the tags in a line have changed.")
1810 (defgroup org-properties nil
1811 "Options concerning properties in Org-mode."
1812 :tag "Org Properties"
1813 :group 'org)
1815 (defcustom org-property-format "%-10s %s"
1816 "How property key/value pairs should be formatted by `indent-line'.
1817 When `indent-line' hits a property definition, it will format the line
1818 according to this format, mainly to make sure that the values are
1819 lined-up with respect to each other."
1820 :group 'org-properties
1821 :type 'string)
1823 (defcustom org-use-property-inheritance nil
1824 "Non-nil means, properties apply also for sublevels.
1826 This setting is chiefly used during property searches. Turning it on can
1827 cause significant overhead when doing a search, which is why it is not
1828 on by default.
1830 When nil, only the properties directly given in the current entry count.
1831 When t, every property is inherited. The value may also be a list of
1832 properties that should have inheritance, or a regular expression matching
1833 properties that should be inherited.
1835 However, note that some special properties use inheritance under special
1836 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1837 and the properties ending in \"_ALL\" when they are used as descriptor
1838 for valid values of a property.
1840 Note for programmers:
1841 When querying an entry with `org-entry-get', you can control if inheritance
1842 should be used. By default, `org-entry-get' looks only at the local
1843 properties. You can request inheritance by setting the inherit argument
1844 to t (to force inheritance) or to `selective' (to respect the setting
1845 in this variable)."
1846 :group 'org-properties
1847 :type '(choice
1848 (const :tag "Not" nil)
1849 (const :tag "Always" t)
1850 (repeat :tag "Specific properties" (string :tag "Property"))
1851 (regexp :tag "Properties matched by regexp")))
1853 (defun org-property-inherit-p (property)
1854 "Check if PROPERTY is one that should be inherited."
1855 (cond
1856 ((eq org-use-property-inheritance t) t)
1857 ((not org-use-property-inheritance) nil)
1858 ((stringp org-use-property-inheritance)
1859 (string-match org-use-property-inheritance property))
1860 ((listp org-use-property-inheritance)
1861 (member property org-use-property-inheritance))
1862 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1864 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1865 "The default column format, if no other format has been defined.
1866 This variable can be set on the per-file basis by inserting a line
1868 #+COLUMNS: %25ITEM ....."
1869 :group 'org-properties
1870 :type 'string)
1872 (defcustom org-effort-property "Effort"
1873 "The property that is being used to keep track of effort estimates.
1874 Effort estimates given in this property need to have the format H:MM."
1875 :group 'org-properties
1876 :group 'org-progress
1877 :type '(string :tag "Property"))
1879 (defconst org-global-properties-fixed
1880 '(("VISIBILITY_ALL" . "folded children content all"))
1881 "List of property/value pairs that can be inherited by any entry.
1882 These are fixed values, for the preset properties.")
1885 (defcustom org-global-properties nil
1886 "List of property/value pairs that can be inherited by any entry.
1887 You can set buffer-local values for this by adding lines like
1889 #+PROPERTY: NAME VALUE"
1890 :group 'org-properties
1891 :type '(repeat
1892 (cons (string :tag "Property")
1893 (string :tag "Value"))))
1895 (defvar org-file-properties nil
1896 "List of property/value pairs that can be inherited by any entry.
1897 Valid for the current buffer.
1898 This variable is populated from #+PROPERTY lines.")
1900 (defgroup org-agenda nil
1901 "Options concerning agenda views in Org-mode."
1902 :tag "Org Agenda"
1903 :group 'org)
1905 (defvar org-category nil
1906 "Variable used by org files to set a category for agenda display.
1907 Such files should use a file variable to set it, for example
1909 # -*- mode: org; org-category: \"ELisp\"
1911 or contain a special line
1913 #+CATEGORY: ELisp
1915 If the file does not specify a category, then file's base name
1916 is used instead.")
1917 (make-variable-buffer-local 'org-category)
1919 (defcustom org-agenda-files nil
1920 "The files to be used for agenda display.
1921 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1922 \\[org-remove-file]. You can also use customize to edit the list.
1924 If an entry is a directory, all files in that directory that are matched by
1925 `org-agenda-file-regexp' will be part of the file list.
1927 If the value of the variable is not a list but a single file name, then
1928 the list of agenda files is actually stored and maintained in that file, one
1929 agenda file per line."
1930 :group 'org-agenda
1931 :type '(choice
1932 (repeat :tag "List of files and directories" file)
1933 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1935 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1936 "Regular expression to match files for `org-agenda-files'.
1937 If any element in the list in that variable contains a directory instead
1938 of a normal file, all files in that directory that are matched by this
1939 regular expression will be included."
1940 :group 'org-agenda
1941 :type 'regexp)
1943 (defcustom org-agenda-text-search-extra-files nil
1944 "List of extra files to be searched by text search commands.
1945 These files will be search in addition to the agenda files by the
1946 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1947 Note that these files will only be searched for text search commands,
1948 not for the other agenda views like todo lists, tag searches or the weekly
1949 agenda. This variable is intended to list notes and possibly archive files
1950 that should also be searched by these two commands.
1951 In fact, if the first element in the list is the symbol `agenda-archives',
1952 than all archive files of all agenda files will be added to the search
1953 scope."
1954 :group 'org-agenda
1955 :type '(set :greedy t
1956 (const :tag "Agenda Archives" agenda-archives)
1957 (repeat :inline t (file))))
1959 (if (fboundp 'defvaralias)
1960 (defvaralias 'org-agenda-multi-occur-extra-files
1961 'org-agenda-text-search-extra-files))
1963 (defcustom org-agenda-skip-unavailable-files nil
1964 "t means to just skip non-reachable files in `org-agenda-files'.
1965 Nil means to remove them, after a query, from the list."
1966 :group 'org-agenda
1967 :type 'boolean)
1969 (defcustom org-calendar-to-agenda-key [?c]
1970 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1971 The command `org-calendar-goto-agenda' will be bound to this key. The
1972 default is the character `c' because then `c' can be used to switch back and
1973 forth between agenda and calendar."
1974 :group 'org-agenda
1975 :type 'sexp)
1977 (eval-after-load "calendar"
1978 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1979 'org-calendar-goto-agenda))
1981 (defgroup org-latex nil
1982 "Options for embedding LaTeX code into Org-mode."
1983 :tag "Org LaTeX"
1984 :group 'org)
1986 (defcustom org-format-latex-options
1987 '(:foreground default :background default :scale 1.0
1988 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1989 :matchers ("begin" "$" "$$" "\\(" "\\["))
1990 "Options for creating images from LaTeX fragments.
1991 This is a property list with the following properties:
1992 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
1993 `default' means use the foreground of the default face.
1994 :background the background color, or \"Transparent\".
1995 `default' means use the background of the default face.
1996 :scale a scaling factor for the size of the images.
1997 :html-foreground, :html-background, :html-scale
1998 the same numbers for HTML export.
1999 :matchers a list indicating which matchers should be used to
2000 find LaTeX fragments. Valid members of this list are:
2001 \"begin\" find environments
2002 \"$\" find math expressions surrounded by $...$
2003 \"$$\" find math expressions surrounded by $$....$$
2004 \"\\(\" find math expressions surrounded by \\(...\\)
2005 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2006 :group 'org-latex
2007 :type 'plist)
2009 (defcustom org-format-latex-header "\\documentclass{article}
2010 \\usepackage{fullpage} % do not remove
2011 \\usepackage{amssymb}
2012 \\usepackage[usenames]{color}
2013 \\usepackage{amsmath}
2014 \\usepackage{latexsym}
2015 \\usepackage[mathscr]{eucal}
2016 \\pagestyle{empty} % do not remove"
2017 "The document header used for processing LaTeX fragments."
2018 :group 'org-latex
2019 :type 'string)
2022 (defgroup org-font-lock nil
2023 "Font-lock settings for highlighting in Org-mode."
2024 :tag "Org Font Lock"
2025 :group 'org)
2027 (defcustom org-level-color-stars-only nil
2028 "Non-nil means fontify only the stars in each headline.
2029 When nil, the entire headline is fontified.
2030 Changing it requires restart of `font-lock-mode' to become effective
2031 also in regions already fontified."
2032 :group 'org-font-lock
2033 :type 'boolean)
2035 (defcustom org-hide-leading-stars nil
2036 "Non-nil means, hide the first N-1 stars in a headline.
2037 This works by using the face `org-hide' for these stars. This
2038 face is white for a light background, and black for a dark
2039 background. You may have to customize the face `org-hide' to
2040 make this work.
2041 Changing it requires restart of `font-lock-mode' to become effective
2042 also in regions already fontified.
2043 You may also set this on a per-file basis by adding one of the following
2044 lines to the buffer:
2046 #+STARTUP: hidestars
2047 #+STARTUP: showstars"
2048 :group 'org-font-lock
2049 :type 'boolean)
2051 (defcustom org-fontify-done-headline nil
2052 "Non-nil means, change the face of a headline if it is marked DONE.
2053 Normally, only the TODO/DONE keyword indicates the state of a headline.
2054 When this is non-nil, the headline after the keyword is set to the
2055 `org-headline-done' as an additional indication."
2056 :group 'org-font-lock
2057 :type 'boolean)
2059 (defcustom org-fontify-emphasized-text t
2060 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2061 Changing this variable requires a restart of Emacs to take effect."
2062 :group 'org-font-lock
2063 :type 'boolean)
2065 (defcustom org-highlight-latex-fragments-and-specials nil
2066 "Non-nil means, fontify what is treated specially by the exporters."
2067 :group 'org-font-lock
2068 :type 'boolean)
2070 (defcustom org-hide-emphasis-markers nil
2071 "Non-nil mean font-lock should hide the emphasis marker characters."
2072 :group 'org-font-lock
2073 :type 'boolean)
2075 (defvar org-emph-re nil
2076 "Regular expression for matching emphasis.")
2077 (defvar org-verbatim-re nil
2078 "Regular expression for matching verbatim text.")
2079 (defvar org-emphasis-regexp-components) ; defined just below
2080 (defvar org-emphasis-alist) ; defined just below
2081 (defun org-set-emph-re (var val)
2082 "Set variable and compute the emphasis regular expression."
2083 (set var val)
2084 (when (and (boundp 'org-emphasis-alist)
2085 (boundp 'org-emphasis-regexp-components)
2086 org-emphasis-alist org-emphasis-regexp-components)
2087 (let* ((e org-emphasis-regexp-components)
2088 (pre (car e))
2089 (post (nth 1 e))
2090 (border (nth 2 e))
2091 (body (nth 3 e))
2092 (nl (nth 4 e))
2093 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2094 (body1 (concat body "*?"))
2095 (markers (mapconcat 'car org-emphasis-alist ""))
2096 (vmarkers (mapconcat
2097 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2098 org-emphasis-alist "")))
2099 ;; make sure special characters appear at the right position in the class
2100 (if (string-match "\\^" markers)
2101 (setq markers (concat (replace-match "" t t markers) "^")))
2102 (if (string-match "-" markers)
2103 (setq markers (concat (replace-match "" t t markers) "-")))
2104 (if (string-match "\\^" vmarkers)
2105 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2106 (if (string-match "-" vmarkers)
2107 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2108 (if (> nl 0)
2109 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2110 (int-to-string nl) "\\}")))
2111 ;; Make the regexp
2112 (setq org-emph-re
2113 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2114 "\\("
2115 "\\([" markers "]\\)"
2116 "\\("
2117 "[^" border "]\\|"
2118 "[^" border (if (and nil stacked) markers) "]"
2119 body1
2120 "[^" border (if (and nil stacked) markers) "]"
2121 "\\)"
2122 "\\3\\)"
2123 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2124 (setq org-verbatim-re
2125 (concat "\\([" pre "]\\|^\\)"
2126 "\\("
2127 "\\([" vmarkers "]\\)"
2128 "\\("
2129 "[^" border "]\\|"
2130 "[^" border "]"
2131 body1
2132 "[^" border "]"
2133 "\\)"
2134 "\\3\\)"
2135 "\\([" post "]\\|$\\)")))))
2137 (defcustom org-emphasis-regexp-components
2138 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2139 "Components used to build the regular expression for emphasis.
2140 This is a list with 6 entries. Terminology: In an emphasis string
2141 like \" *strong word* \", we call the initial space PREMATCH, the final
2142 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2143 and \"trong wor\" is the body. The different components in this variable
2144 specify what is allowed/forbidden in each part:
2146 pre Chars allowed as prematch. Beginning of line will be allowed too.
2147 post Chars allowed as postmatch. End of line will be allowed too.
2148 border The chars *forbidden* as border characters.
2149 body-regexp A regexp like \".\" to match a body character. Don't use
2150 non-shy groups here, and don't allow newline here.
2151 newline The maximum number of newlines allowed in an emphasis exp.
2153 Use customize to modify this, or restart Emacs after changing it."
2154 :group 'org-font-lock
2155 :set 'org-set-emph-re
2156 :type '(list
2157 (sexp :tag "Allowed chars in pre ")
2158 (sexp :tag "Allowed chars in post ")
2159 (sexp :tag "Forbidden chars in border ")
2160 (sexp :tag "Regexp for body ")
2161 (integer :tag "number of newlines allowed")
2162 (option (boolean :tag "Stacking (DISABLED) "))))
2164 (defcustom org-emphasis-alist
2165 `(("*" bold "<b>" "</b>")
2166 ("/" italic "<i>" "</i>")
2167 ("_" underline "<u>" "</u>")
2168 ("=" org-code "<code>" "</code>" verbatim)
2169 ("~" org-verbatim "" "" verbatim)
2170 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2171 "<del>" "</del>")
2173 "Special syntax for emphasized text.
2174 Text starting and ending with a special character will be emphasized, for
2175 example *bold*, _underlined_ and /italic/. This variable sets the marker
2176 characters, the face to be used by font-lock for highlighting in Org-mode
2177 Emacs buffers, and the HTML tags to be used for this.
2178 Use customize to modify this, or restart Emacs after changing it."
2179 :group 'org-font-lock
2180 :set 'org-set-emph-re
2181 :type '(repeat
2182 (list
2183 (string :tag "Marker character")
2184 (choice
2185 (face :tag "Font-lock-face")
2186 (plist :tag "Face property list"))
2187 (string :tag "HTML start tag")
2188 (string :tag "HTML end tag")
2189 (option (const verbatim)))))
2191 ;;; Miscellaneous options
2193 (defgroup org-completion nil
2194 "Completion in Org-mode."
2195 :tag "Org Completion"
2196 :group 'org)
2198 (defcustom org-completion-fallback-command 'hippie-expand
2199 "The expansion command called by \\[org-complete] in normal context.
2200 Normal means, no org-mode-specific context."
2201 :group 'org-completion
2202 :type 'function)
2204 ;;; Functions and variables from ther packages
2205 ;; Declared here to avoid compiler warnings
2207 ;; XEmacs only
2208 (defvar outline-mode-menu-heading)
2209 (defvar outline-mode-menu-show)
2210 (defvar outline-mode-menu-hide)
2211 (defvar zmacs-regions) ; XEmacs regions
2213 ;; Emacs only
2214 (defvar mark-active)
2216 ;; Various packages
2217 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2218 (declare-function calendar-forward-day "cal-move" (arg))
2219 (declare-function calendar-goto-date "cal-move" (date))
2220 (declare-function calendar-goto-today "cal-move" ())
2221 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2222 (defvar calc-embedded-close-formula)
2223 (defvar calc-embedded-open-formula)
2224 (declare-function cdlatex-tab "ext:cdlatex" ())
2225 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2226 (defvar font-lock-unfontify-region-function)
2227 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2228 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2229 (defvar iswitchb-temp-buflist)
2230 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2231 (declare-function org-agenda-skip "org-agenda" ())
2232 (declare-function org-format-agenda-item "org-agenda"
2233 (extra txt &optional category tags dotime noprefix remove-re))
2234 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2235 (declare-function org-agenda-change-all-lines "org-agenda"
2236 (newhead hdmarker &optional fixface))
2237 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2238 (declare-function org-agenda-maybe-redo "org-agenda" ())
2239 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2240 (beg end))
2241 (declare-function parse-time-string "parse-time" (string))
2242 (declare-function remember "remember" (&optional initial))
2243 (declare-function remember-buffer-desc "remember" ())
2244 (declare-function remember-finalize "remember" ())
2245 (defvar remember-save-after-remembering)
2246 (defvar remember-data-file)
2247 (defvar remember-register)
2248 (defvar remember-buffer)
2249 (defvar remember-handler-functions)
2250 (defvar remember-annotation-functions)
2251 (defvar texmathp-why)
2252 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2253 (declare-function table--at-cell-p "table" (position &optional object at-column))
2255 (defvar w3m-current-url)
2256 (defvar w3m-current-title)
2258 (defvar org-latex-regexps)
2260 ;;; Autoload and prepare some org modules
2262 ;; Some table stuff that needs to be defined here, because it is used
2263 ;; by the functions setting up org-mode or checking for table context.
2265 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2266 "Detects an org-type or table-type table.")
2267 (defconst org-table-line-regexp "^[ \t]*|"
2268 "Detects an org-type table line.")
2269 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2270 "Detects an org-type table line.")
2271 (defconst org-table-hline-regexp "^[ \t]*|-"
2272 "Detects an org-type table hline.")
2273 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2274 "Detects a table-type table hline.")
2275 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2276 "Searching from within a table (any type) this finds the first line
2277 outside the table.")
2279 ;; Autoload the functions in org-table.el that are needed by functions here.
2281 (eval-and-compile
2282 (org-autoload "org-table"
2283 '(org-table-align org-table-begin org-table-blank-field
2284 org-table-convert org-table-convert-region org-table-copy-down
2285 org-table-copy-region org-table-create
2286 org-table-create-or-convert-from-region
2287 org-table-create-with-table.el org-table-current-dline
2288 org-table-cut-region org-table-delete-column org-table-edit-field
2289 org-table-edit-formulas org-table-end org-table-eval-formula
2290 org-table-export org-table-field-info
2291 org-table-get-stored-formulas org-table-goto-column
2292 org-table-hline-and-move org-table-import org-table-insert-column
2293 org-table-insert-hline org-table-insert-row org-table-iterate
2294 org-table-justify-field-maybe org-table-kill-row
2295 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2296 org-table-move-column org-table-move-column-left
2297 org-table-move-column-right org-table-move-row
2298 org-table-move-row-down org-table-move-row-up
2299 org-table-next-field org-table-next-row org-table-paste-rectangle
2300 org-table-previous-field org-table-recalculate
2301 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2302 org-table-toggle-coordinate-overlays
2303 org-table-toggle-formula-debugger org-table-wrap-region
2304 orgtbl-mode turn-on-orgtbl)))
2306 (defun org-at-table-p (&optional table-type)
2307 "Return t if the cursor is inside an org-type table.
2308 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2309 (if org-enable-table-editor
2310 (save-excursion
2311 (beginning-of-line 1)
2312 (looking-at (if table-type org-table-any-line-regexp
2313 org-table-line-regexp)))
2314 nil))
2315 (defsubst org-table-p () (org-at-table-p))
2317 (defun org-at-table.el-p ()
2318 "Return t if and only if we are at a table.el table."
2319 (and (org-at-table-p 'any)
2320 (save-excursion
2321 (goto-char (org-table-begin 'any))
2322 (looking-at org-table1-hline-regexp))))
2323 (defun org-table-recognize-table.el ()
2324 "If there is a table.el table nearby, recognize it and move into it."
2325 (if org-table-tab-recognizes-table.el
2326 (if (org-at-table.el-p)
2327 (progn
2328 (beginning-of-line 1)
2329 (if (looking-at org-table-dataline-regexp)
2331 (if (looking-at org-table1-hline-regexp)
2332 (progn
2333 (beginning-of-line 2)
2334 (if (looking-at org-table-any-border-regexp)
2335 (beginning-of-line -1)))))
2336 (if (re-search-forward "|" (org-table-end t) t)
2337 (progn
2338 (require 'table)
2339 (if (table--at-cell-p (point))
2341 (message "recognizing table.el table...")
2342 (table-recognize-table)
2343 (message "recognizing table.el table...done")))
2344 (error "This should not happen..."))
2346 nil)
2347 nil))
2349 (defun org-at-table-hline-p ()
2350 "Return t if the cursor is inside a hline in a table."
2351 (if org-enable-table-editor
2352 (save-excursion
2353 (beginning-of-line 1)
2354 (looking-at org-table-hline-regexp))
2355 nil))
2357 (defvar org-table-clean-did-remove-column nil)
2359 (defun org-table-map-tables (function)
2360 "Apply FUNCTION to the start of all tables in the buffer."
2361 (save-excursion
2362 (save-restriction
2363 (widen)
2364 (goto-char (point-min))
2365 (while (re-search-forward org-table-any-line-regexp nil t)
2366 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2367 (beginning-of-line 1)
2368 (if (looking-at org-table-line-regexp)
2369 (save-excursion (funcall function)))
2370 (re-search-forward org-table-any-border-regexp nil 1))))
2371 (message "Mapping tables: done"))
2373 ;; Declare and autoload functions from org-exp.el
2375 (declare-function org-default-export-plist "org-exp")
2376 (declare-function org-infile-export-plist "org-exp")
2377 (declare-function org-get-current-options "org-exp")
2378 (eval-and-compile
2379 (org-autoload "org-exp"
2380 '(org-export org-export-as-ascii org-export-visible
2381 org-insert-export-options-template org-export-as-html-and-open
2382 org-export-as-html-batch org-export-as-html-to-buffer
2383 org-replace-region-by-html org-export-region-as-html
2384 org-export-as-html org-export-icalendar-this-file
2385 org-export-icalendar-all-agenda-files
2386 org-table-clean-before-export
2387 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2389 ;; Declare and autoload functions from org-exp.el
2391 (eval-and-compile
2392 (org-autoload "org-exp"
2393 '(org-agenda org-agenda-list org-search-view
2394 org-todo-list org-tags-view org-agenda-list-stuck-projects
2395 org-diary org-agenda-to-appt)))
2397 ;; Autoload org-remember
2399 (eval-and-compile
2400 (org-autoload "org-remember"
2401 '(org-remember-insinuate org-remember-annotation
2402 org-remember-apply-template org-remember org-remember-handler)))
2404 ;; Autoload org-clock.el
2407 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2408 (beg end))
2409 (declare-function org-update-mode-line "org-clock" ())
2410 (defvar org-clock-start-time)
2411 (defvar org-clock-marker (make-marker)
2412 "Marker recording the last clock-in.")
2414 (eval-and-compile
2415 (org-autoload
2416 "org-clock"
2417 '(org-clock-in org-clock-out org-clock-cancel
2418 org-clock-goto org-clock-sum org-clock-display
2419 org-remove-clock-overlays org-clock-report
2420 org-clocktable-shift org-dblock-write:clocktable
2421 org-get-clocktable)))
2423 (defun org-clock-update-time-maybe ()
2424 "If this is a CLOCK line, update it and return t.
2425 Otherwise, return nil."
2426 (interactive)
2427 (save-excursion
2428 (beginning-of-line 1)
2429 (skip-chars-forward " \t")
2430 (when (looking-at org-clock-string)
2431 (let ((re (concat "[ \t]*" org-clock-string
2432 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2433 "\\([ \t]*=>.*\\)?\\)?"))
2434 ts te h m s)
2435 (cond
2436 ((not (looking-at re))
2437 nil)
2438 ((not (match-end 2))
2439 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2440 (> org-clock-marker (point))
2441 (<= org-clock-marker (point-at-eol)))
2442 ;; The clock is running here
2443 (setq org-clock-start-time
2444 (apply 'encode-time
2445 (org-parse-time-string (match-string 1))))
2446 (org-update-mode-line)))
2448 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2449 (end-of-line 1)
2450 (setq ts (match-string 1)
2451 te (match-string 3))
2452 (setq s (- (time-to-seconds
2453 (apply 'encode-time (org-parse-time-string te)))
2454 (time-to-seconds
2455 (apply 'encode-time (org-parse-time-string ts))))
2456 h (floor (/ s 3600))
2457 s (- s (* 3600 h))
2458 m (floor (/ s 60))
2459 s (- s (* 60 s)))
2460 (insert " => " (format "%2d:%02d" h m))
2461 t))))))
2463 (defun org-check-running-clock ()
2464 "Check if the current buffer contains the running clock.
2465 If yes, offer to stop it and to save the buffer with the changes."
2466 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2467 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2468 (buffer-name))))
2469 (org-clock-out)
2470 (when (y-or-n-p "Save changed buffer?")
2471 (save-buffer))))
2473 (defun org-clocktable-try-shift (dir n)
2474 "Check if this line starts a clock table, if yes, shift the time block."
2475 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2476 (org-clocktable-shift dir n)))
2478 ;; Autoload archiving code
2479 ;; The stuff that is needed for cycling and tags has to be defined here.
2481 (defgroup org-archive nil
2482 "Options concerning archiving in Org-mode."
2483 :tag "Org Archive"
2484 :group 'org-structure)
2486 (defcustom org-archive-location "%s_archive::"
2487 "The location where subtrees should be archived.
2489 Otherwise, the value of this variable is a string, consisting of two
2490 parts, separated by a double-colon.
2492 The first part is a file name - when omitted, archiving happens in the same
2493 file. %s will be replaced by the current file name (without directory part).
2494 Archiving to a different file is useful to keep archived entries from
2495 contributing to the Org-mode Agenda.
2497 The part after the double colon is a headline. The archived entries will be
2498 filed under that headline. When omitted, the subtrees are simply filed away
2499 at the end of the file, as top-level entries.
2501 Here are a few examples:
2502 \"%s_archive::\"
2503 If the current file is Projects.org, archive in file
2504 Projects.org_archive, as top-level trees. This is the default.
2506 \"::* Archived Tasks\"
2507 Archive in the current file, under the top-level headline
2508 \"* Archived Tasks\".
2510 \"~/org/archive.org::\"
2511 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2513 \"basement::** Finished Tasks\"
2514 Archive in file ./basement (relative path), as level 3 trees
2515 below the level 2 heading \"** Finished Tasks\".
2517 You may set this option on a per-file basis by adding to the buffer a
2518 line like
2520 #+ARCHIVE: basement::** Finished Tasks
2522 You may also define it locally for a subtree by setting an ARCHIVE property
2523 in the entry. If such a property is found in an entry, or anywhere up
2524 the hierarchy, it will be used."
2525 :group 'org-archive
2526 :type 'string)
2528 (defcustom org-archive-tag "ARCHIVE"
2529 "The tag that marks a subtree as archived.
2530 An archived subtree does not open during visibility cycling, and does
2531 not contribute to the agenda listings.
2532 After changing this, font-lock must be restarted in the relevant buffers to
2533 get the proper fontification."
2534 :group 'org-archive
2535 :group 'org-keywords
2536 :type 'string)
2538 (defcustom org-agenda-skip-archived-trees t
2539 "Non-nil means, the agenda will skip any items located in archived trees.
2540 An archived tree is a tree marked with the tag ARCHIVE."
2541 :group 'org-archive
2542 :group 'org-agenda-skip
2543 :type 'boolean)
2545 (defcustom org-cycle-open-archived-trees nil
2546 "Non-nil means, `org-cycle' will open archived trees.
2547 An archived tree is a tree marked with the tag ARCHIVE.
2548 When nil, archived trees will stay folded. You can still open them with
2549 normal outline commands like `show-all', but not with the cycling commands."
2550 :group 'org-archive
2551 :group 'org-cycle
2552 :type 'boolean)
2554 (defcustom org-sparse-tree-open-archived-trees nil
2555 "Non-nil means sparse tree construction shows matches in archived trees.
2556 When nil, matches in these trees are highlighted, but the trees are kept in
2557 collapsed state."
2558 :group 'org-archive
2559 :group 'org-sparse-trees
2560 :type 'boolean)
2562 (defun org-cycle-hide-archived-subtrees (state)
2563 "Re-hide all archived subtrees after a visibility state change."
2564 (when (and (not org-cycle-open-archived-trees)
2565 (not (memq state '(overview folded))))
2566 (save-excursion
2567 (let* ((globalp (memq state '(contents all)))
2568 (beg (if globalp (point-min) (point)))
2569 (end (if globalp (point-max) (org-end-of-subtree t))))
2570 (org-hide-archived-subtrees beg end)
2571 (goto-char beg)
2572 (if (looking-at (concat ".*:" org-archive-tag ":"))
2573 (message "%s" (substitute-command-keys
2574 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2576 (defun org-force-cycle-archived ()
2577 "Cycle subtree even if it is archived."
2578 (interactive)
2579 (setq this-command 'org-cycle)
2580 (let ((org-cycle-open-archived-trees t))
2581 (call-interactively 'org-cycle)))
2583 (defun org-hide-archived-subtrees (beg end)
2584 "Re-hide all archived subtrees after a visibility state change."
2585 (save-excursion
2586 (let* ((re (concat ":" org-archive-tag ":")))
2587 (goto-char beg)
2588 (while (re-search-forward re end t)
2589 (and (org-on-heading-p) (hide-subtree))
2590 (org-end-of-subtree t)))))
2592 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2594 (eval-and-compile
2595 (org-autoload "org-archive"
2596 '(org-add-archive-files org-archive-subtree
2597 org-archive-to-archive-sibling org-toggle-archive-tag)))
2599 ;; Autoload Column View Code
2601 (declare-function org-columns-number-to-string "org-colview")
2602 (declare-function org-columns-get-format-and-top-level "org-colview")
2603 (declare-function org-columns-compute "org-colview")
2605 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2606 '(org-columns-number-to-string org-columns-get-format-and-top-level
2607 org-columns-compute org-agenda-columns org-columns-remove-overlays
2608 org-columns org-insert-columns-dblock))
2610 ;; Autoload ID code
2612 (org-autoload "org-id"
2613 '(org-id-get-create org-id-new org-id-copy org-id-get
2614 org-id-get-with-outline-path-completion
2615 org-id-get-with-outline-drilling
2616 org-id-goto org-id-find))
2618 ;;; Variables for pre-computed regular expressions, all buffer local
2620 (defvar org-drawer-regexp nil
2621 "Matches first line of a hidden block.")
2622 (make-variable-buffer-local 'org-drawer-regexp)
2623 (defvar org-todo-regexp nil
2624 "Matches any of the TODO state keywords.")
2625 (make-variable-buffer-local 'org-todo-regexp)
2626 (defvar org-not-done-regexp nil
2627 "Matches any of the TODO state keywords except the last one.")
2628 (make-variable-buffer-local 'org-not-done-regexp)
2629 (defvar org-todo-line-regexp nil
2630 "Matches a headline and puts TODO state into group 2 if present.")
2631 (make-variable-buffer-local 'org-todo-line-regexp)
2632 (defvar org-complex-heading-regexp nil
2633 "Matches a headline and puts everything into groups:
2634 group 1: the stars
2635 group 2: The todo keyword, maybe
2636 group 3: Priority cookie
2637 group 4: True headline
2638 group 5: Tags")
2639 (make-variable-buffer-local 'org-complex-heading-regexp)
2640 (defvar org-todo-line-tags-regexp nil
2641 "Matches a headline and puts TODO state into group 2 if present.
2642 Also put tags into group 4 if tags are present.")
2643 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2644 (defvar org-nl-done-regexp nil
2645 "Matches newline followed by a headline with the DONE keyword.")
2646 (make-variable-buffer-local 'org-nl-done-regexp)
2647 (defvar org-looking-at-done-regexp nil
2648 "Matches the DONE keyword a point.")
2649 (make-variable-buffer-local 'org-looking-at-done-regexp)
2650 (defvar org-ds-keyword-length 12
2651 "Maximum length of the Deadline and SCHEDULED keywords.")
2652 (make-variable-buffer-local 'org-ds-keyword-length)
2653 (defvar org-deadline-regexp nil
2654 "Matches the DEADLINE keyword.")
2655 (make-variable-buffer-local 'org-deadline-regexp)
2656 (defvar org-deadline-time-regexp nil
2657 "Matches the DEADLINE keyword together with a time stamp.")
2658 (make-variable-buffer-local 'org-deadline-time-regexp)
2659 (defvar org-deadline-line-regexp nil
2660 "Matches the DEADLINE keyword and the rest of the line.")
2661 (make-variable-buffer-local 'org-deadline-line-regexp)
2662 (defvar org-scheduled-regexp nil
2663 "Matches the SCHEDULED keyword.")
2664 (make-variable-buffer-local 'org-scheduled-regexp)
2665 (defvar org-scheduled-time-regexp nil
2666 "Matches the SCHEDULED keyword together with a time stamp.")
2667 (make-variable-buffer-local 'org-scheduled-time-regexp)
2668 (defvar org-closed-time-regexp nil
2669 "Matches the CLOSED keyword together with a time stamp.")
2670 (make-variable-buffer-local 'org-closed-time-regexp)
2672 (defvar org-keyword-time-regexp nil
2673 "Matches any of the 4 keywords, together with the time stamp.")
2674 (make-variable-buffer-local 'org-keyword-time-regexp)
2675 (defvar org-keyword-time-not-clock-regexp nil
2676 "Matches any of the 3 keywords, together with the time stamp.")
2677 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2678 (defvar org-maybe-keyword-time-regexp nil
2679 "Matches a timestamp, possibly preceeded by a keyword.")
2680 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2681 (defvar org-planning-or-clock-line-re nil
2682 "Matches a line with planning or clock info.")
2683 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2685 (defconst org-plain-time-of-day-regexp
2686 (concat
2687 "\\(\\<[012]?[0-9]"
2688 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2689 "\\(--?"
2690 "\\(\\<[012]?[0-9]"
2691 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2692 "\\)?")
2693 "Regular expression to match a plain time or time range.
2694 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2695 groups carry important information:
2696 0 the full match
2697 1 the first time, range or not
2698 8 the second time, if it is a range.")
2700 (defconst org-plain-time-extension-regexp
2701 (concat
2702 "\\(\\<[012]?[0-9]"
2703 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2704 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2705 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2706 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2707 groups carry important information:
2708 0 the full match
2709 7 hours of duration
2710 9 minutes of duration")
2712 (defconst org-stamp-time-of-day-regexp
2713 (concat
2714 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2715 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2716 "\\(--?"
2717 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2718 "Regular expression to match a timestamp time or time range.
2719 After a match, the following groups carry important information:
2720 0 the full match
2721 1 date plus weekday, for backreferencing to make sure both times on same day
2722 2 the first time, range or not
2723 4 the second time, if it is a range.")
2725 (defconst org-startup-options
2726 '(("fold" org-startup-folded t)
2727 ("overview" org-startup-folded t)
2728 ("nofold" org-startup-folded nil)
2729 ("showall" org-startup-folded nil)
2730 ("content" org-startup-folded content)
2731 ("hidestars" org-hide-leading-stars t)
2732 ("showstars" org-hide-leading-stars nil)
2733 ("odd" org-odd-levels-only t)
2734 ("oddeven" org-odd-levels-only nil)
2735 ("align" org-startup-align-all-tables t)
2736 ("noalign" org-startup-align-all-tables nil)
2737 ("customtime" org-display-custom-times t)
2738 ("logdone" org-log-done time)
2739 ("lognotedone" org-log-done note)
2740 ("nologdone" org-log-done nil)
2741 ("lognoteclock-out" org-log-note-clock-out t)
2742 ("nolognoteclock-out" org-log-note-clock-out nil)
2743 ("logrepeat" org-log-repeat state)
2744 ("lognoterepeat" org-log-repeat note)
2745 ("nologrepeat" org-log-repeat nil)
2746 ("constcgs" constants-unit-system cgs)
2747 ("constSI" constants-unit-system SI))
2748 "Variable associated with STARTUP options for org-mode.
2749 Each element is a list of three items: The startup options as written
2750 in the #+STARTUP line, the corresponding variable, and the value to
2751 set this variable to if the option is found. An optional forth element PUSH
2752 means to push this value onto the list in the variable.")
2754 (defun org-set-regexps-and-options ()
2755 "Precompute regular expressions for current buffer."
2756 (when (org-mode-p)
2757 (org-set-local 'org-todo-kwd-alist nil)
2758 (org-set-local 'org-todo-key-alist nil)
2759 (org-set-local 'org-todo-key-trigger nil)
2760 (org-set-local 'org-todo-keywords-1 nil)
2761 (org-set-local 'org-done-keywords nil)
2762 (org-set-local 'org-todo-heads nil)
2763 (org-set-local 'org-todo-sets nil)
2764 (org-set-local 'org-todo-log-states nil)
2765 (let ((re (org-make-options-regexp
2766 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2767 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2768 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2769 (splitre "[ \t]+")
2770 kwds kws0 kwsa key log value cat arch tags const links hw dws
2771 tail sep kws1 prio props ftags drawers
2772 ext-setup-or-nil setup-contents (start 0))
2773 (save-excursion
2774 (save-restriction
2775 (widen)
2776 (goto-char (point-min))
2777 (while (or (and ext-setup-or-nil
2778 (string-match re ext-setup-or-nil start)
2779 (setq start (match-end 0)))
2780 (and (setq ext-setup-or-nil nil start 0)
2781 (re-search-forward re nil t)))
2782 (setq key (upcase (match-string 1 ext-setup-or-nil))
2783 value (org-match-string-no-properties 2 ext-setup-or-nil))
2784 (cond
2785 ((equal key "CATEGORY")
2786 (if (string-match "[ \t]+$" value)
2787 (setq value (replace-match "" t t value)))
2788 (setq cat value))
2789 ((member key '("SEQ_TODO" "TODO"))
2790 (push (cons 'sequence (org-split-string value splitre)) kwds))
2791 ((equal key "TYP_TODO")
2792 (push (cons 'type (org-split-string value splitre)) kwds))
2793 ((equal key "TAGS")
2794 (setq tags (append tags (org-split-string value splitre))))
2795 ((equal key "COLUMNS")
2796 (org-set-local 'org-columns-default-format value))
2797 ((equal key "LINK")
2798 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2799 (push (cons (match-string 1 value)
2800 (org-trim (match-string 2 value)))
2801 links)))
2802 ((equal key "PRIORITIES")
2803 (setq prio (org-split-string value " +")))
2804 ((equal key "PROPERTY")
2805 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2806 (push (cons (match-string 1 value) (match-string 2 value))
2807 props)))
2808 ((equal key "FILETAGS")
2809 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2810 (setq ftags
2811 (append
2812 ftags
2813 (apply 'append
2814 (mapcar (lambda (x) (org-split-string x ":"))
2815 (org-split-string value)))))))
2816 ((equal key "DRAWERS")
2817 (setq drawers (org-split-string value splitre)))
2818 ((equal key "CONSTANTS")
2819 (setq const (append const (org-split-string value splitre))))
2820 ((equal key "STARTUP")
2821 (let ((opts (org-split-string value splitre))
2822 l var val)
2823 (while (setq l (pop opts))
2824 (when (setq l (assoc l org-startup-options))
2825 (setq var (nth 1 l) val (nth 2 l))
2826 (if (not (nth 3 l))
2827 (set (make-local-variable var) val)
2828 (if (not (listp (symbol-value var)))
2829 (set (make-local-variable var) nil))
2830 (set (make-local-variable var) (symbol-value var))
2831 (add-to-list var val))))))
2832 ((equal key "ARCHIVE")
2833 (string-match " *$" value)
2834 (setq arch (replace-match "" t t value))
2835 (remove-text-properties 0 (length arch)
2836 '(face t fontified t) arch))
2837 ((equal key "SETUPFILE")
2838 (setq setup-contents (org-file-contents
2839 (expand-file-name
2840 (org-remove-double-quotes value))
2841 'noerror))
2842 (if (not ext-setup-or-nil)
2843 (setq ext-setup-or-nil setup-contents start 0)
2844 (setq ext-setup-or-nil
2845 (concat (substring ext-setup-or-nil 0 start)
2846 "\n" setup-contents "\n"
2847 (substring ext-setup-or-nil start)))))
2848 ))))
2849 (when cat
2850 (org-set-local 'org-category (intern cat))
2851 (push (cons "CATEGORY" cat) props))
2852 (when prio
2853 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2854 (setq prio (mapcar 'string-to-char prio))
2855 (org-set-local 'org-highest-priority (nth 0 prio))
2856 (org-set-local 'org-lowest-priority (nth 1 prio))
2857 (org-set-local 'org-default-priority (nth 2 prio)))
2858 (and props (org-set-local 'org-file-properties (nreverse props)))
2859 (and ftags (org-set-local 'org-file-tags ftags))
2860 (and drawers (org-set-local 'org-drawers drawers))
2861 (and arch (org-set-local 'org-archive-location arch))
2862 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2863 ;; Process the TODO keywords
2864 (unless kwds
2865 ;; Use the global values as if they had been given locally.
2866 (setq kwds (default-value 'org-todo-keywords))
2867 (if (stringp (car kwds))
2868 (setq kwds (list (cons org-todo-interpretation
2869 (default-value 'org-todo-keywords)))))
2870 (setq kwds (reverse kwds)))
2871 (setq kwds (nreverse kwds))
2872 (let (inter kws kw)
2873 (while (setq kws (pop kwds))
2874 (setq inter (pop kws) sep (member "|" kws)
2875 kws0 (delete "|" (copy-sequence kws))
2876 kwsa nil
2877 kws1 (mapcar
2878 (lambda (x)
2879 ;; 1 2
2880 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2881 (progn
2882 (setq kw (match-string 1 x)
2883 key (and (match-end 2) (match-string 2 x))
2884 log (org-extract-log-state-settings x))
2885 (push (cons kw (and key (string-to-char key))) kwsa)
2886 (and log (push log org-todo-log-states))
2888 (error "Invalid TODO keyword %s" x)))
2889 kws0)
2890 kwsa (if kwsa (append '((:startgroup))
2891 (nreverse kwsa)
2892 '((:endgroup))))
2893 hw (car kws1)
2894 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2895 tail (list inter hw (car dws) (org-last dws)))
2896 (add-to-list 'org-todo-heads hw 'append)
2897 (push kws1 org-todo-sets)
2898 (setq org-done-keywords (append org-done-keywords dws nil))
2899 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2900 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2901 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2902 (setq org-todo-sets (nreverse org-todo-sets)
2903 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2904 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2905 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2906 ;; Process the constants
2907 (when const
2908 (let (e cst)
2909 (while (setq e (pop const))
2910 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2911 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2912 (setq org-table-formula-constants-local cst)))
2914 ;; Process the tags.
2915 (when tags
2916 (let (e tgs)
2917 (while (setq e (pop tags))
2918 (cond
2919 ((equal e "{") (push '(:startgroup) tgs))
2920 ((equal e "}") (push '(:endgroup) tgs))
2921 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2922 (push (cons (match-string 1 e)
2923 (string-to-char (match-string 2 e)))
2924 tgs))
2925 (t (push (list e) tgs))))
2926 (org-set-local 'org-tag-alist nil)
2927 (while (setq e (pop tgs))
2928 (or (and (stringp (car e))
2929 (assoc (car e) org-tag-alist))
2930 (push e org-tag-alist))))))
2932 ;; Compute the regular expressions and other local variables
2933 (if (not org-done-keywords)
2934 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2935 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2936 (length org-scheduled-string)
2937 (length org-clock-string)
2938 (length org-closed-string)))
2939 org-drawer-regexp
2940 (concat "^[ \t]*:\\("
2941 (mapconcat 'regexp-quote org-drawers "\\|")
2942 "\\):[ \t]*$")
2943 org-not-done-keywords
2944 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2945 org-todo-regexp
2946 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2947 "\\|") "\\)\\>")
2948 org-not-done-regexp
2949 (concat "\\<\\("
2950 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2951 "\\)\\>")
2952 org-todo-line-regexp
2953 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2954 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2955 "\\)\\>\\)?[ \t]*\\(.*\\)")
2956 org-complex-heading-regexp
2957 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2958 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2959 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2960 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2961 org-nl-done-regexp
2962 (concat "\n\\*+[ \t]+"
2963 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2964 "\\)" "\\>")
2965 org-todo-line-tags-regexp
2966 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2967 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2968 (org-re
2969 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2970 org-looking-at-done-regexp
2971 (concat "^" "\\(?:"
2972 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2973 "\\>")
2974 org-deadline-regexp (concat "\\<" org-deadline-string)
2975 org-deadline-time-regexp
2976 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2977 org-deadline-line-regexp
2978 (concat "\\<\\(" org-deadline-string "\\).*")
2979 org-scheduled-regexp
2980 (concat "\\<" org-scheduled-string)
2981 org-scheduled-time-regexp
2982 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2983 org-closed-time-regexp
2984 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2985 org-keyword-time-regexp
2986 (concat "\\<\\(" org-scheduled-string
2987 "\\|" org-deadline-string
2988 "\\|" org-closed-string
2989 "\\|" org-clock-string "\\)"
2990 " *[[<]\\([^]>]+\\)[]>]")
2991 org-keyword-time-not-clock-regexp
2992 (concat "\\<\\(" org-scheduled-string
2993 "\\|" org-deadline-string
2994 "\\|" org-closed-string
2995 "\\)"
2996 " *[[<]\\([^]>]+\\)[]>]")
2997 org-maybe-keyword-time-regexp
2998 (concat "\\(\\<\\(" org-scheduled-string
2999 "\\|" org-deadline-string
3000 "\\|" org-closed-string
3001 "\\|" org-clock-string "\\)\\)?"
3002 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3003 org-planning-or-clock-line-re
3004 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3005 "\\|" org-deadline-string
3006 "\\|" org-closed-string "\\|" org-clock-string
3007 "\\)\\>\\)")
3009 (org-compute-latex-and-specials-regexp)
3010 (org-set-font-lock-defaults)))
3012 (defun org-file-contents (file &optional noerror)
3013 "Return the contents of FILE, as a string."
3014 (if (or (not file)
3015 (not (file-readable-p file)))
3016 (if noerror
3017 (progn
3018 (message "Cannot read file %s" file)
3019 (ding) (sit-for 2)
3021 (error "Cannot read file %s" file))
3022 (with-temp-buffer
3023 (insert-file-contents file)
3024 (buffer-string))))
3026 (defun org-extract-log-state-settings (x)
3027 "Extract the log state setting from a TODO keyword string.
3028 This will extract info from a string like \"WAIT(w@/!)\"."
3029 (let (kw key log1 log2)
3030 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3031 (setq kw (match-string 1 x)
3032 key (and (match-end 2) (match-string 2 x))
3033 log1 (and (match-end 3) (match-string 3 x))
3034 log2 (and (match-end 4) (match-string 4 x)))
3035 (and (or log1 log2)
3036 (list kw
3037 (and log1 (if (equal log1 "!") 'time 'note))
3038 (and log2 (if (equal log2 "!") 'time 'note)))))))
3040 (defun org-remove-keyword-keys (list)
3041 "Remove a pair of parenthesis at the end of each string in LIST."
3042 (mapcar (lambda (x)
3043 (if (string-match "(.*)$" x)
3044 (substring x 0 (match-beginning 0))
3046 list))
3048 ;; FIXME: this could be done much better, using second characters etc.
3049 (defun org-assign-fast-keys (alist)
3050 "Assign fast keys to a keyword-key alist.
3051 Respect keys that are already there."
3052 (let (new e k c c1 c2 (char ?a))
3053 (while (setq e (pop alist))
3054 (cond
3055 ((equal e '(:startgroup)) (push e new))
3056 ((equal e '(:endgroup)) (push e new))
3058 (setq k (car e) c2 nil)
3059 (if (cdr e)
3060 (setq c (cdr e))
3061 ;; automatically assign a character.
3062 (setq c1 (string-to-char
3063 (downcase (substring
3064 k (if (= (string-to-char k) ?@) 1 0)))))
3065 (if (or (rassoc c1 new) (rassoc c1 alist))
3066 (while (or (rassoc char new) (rassoc char alist))
3067 (setq char (1+ char)))
3068 (setq c2 c1))
3069 (setq c (or c2 char)))
3070 (push (cons k c) new))))
3071 (nreverse new)))
3073 ;;; Some variables used in various places
3075 (defvar org-window-configuration nil
3076 "Used in various places to store a window configuration.")
3077 (defvar org-finish-function nil
3078 "Function to be called when `C-c C-c' is used.
3079 This is for getting out of special buffers like remember.")
3082 ;; FIXME: Occasionally check by commenting these, to make sure
3083 ;; no other functions uses these, forgetting to let-bind them.
3084 (defvar entry)
3085 (defvar state)
3086 (defvar last-state)
3087 (defvar date)
3088 (defvar description)
3090 ;; Defined somewhere in this file, but used before definition.
3091 (defvar org-html-entities)
3092 (defvar org-struct-menu)
3093 (defvar org-org-menu)
3094 (defvar org-tbl-menu)
3095 (defvar org-agenda-keymap)
3097 ;;;; Define the Org-mode
3099 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3100 (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."))
3103 ;; We use a before-change function to check if a table might need
3104 ;; an update.
3105 (defvar org-table-may-need-update t
3106 "Indicates that a table might need an update.
3107 This variable is set by `org-before-change-function'.
3108 `org-table-align' sets it back to nil.")
3109 (defun org-before-change-function (beg end)
3110 "Every change indicates that a table might need an update."
3111 (setq org-table-may-need-update t))
3112 (defvar org-mode-map)
3113 (defvar org-mode-hook nil)
3114 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3115 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3116 (defvar org-table-buffer-is-an nil)
3117 (defconst org-outline-regexp "\\*+ ")
3119 ;;;###autoload
3120 (define-derived-mode org-mode outline-mode "Org"
3121 "Outline-based notes management and organizer, alias
3122 \"Carsten's outline-mode for keeping track of everything.\"
3124 Org-mode develops organizational tasks around a NOTES file which
3125 contains information about projects as plain text. Org-mode is
3126 implemented on top of outline-mode, which is ideal to keep the content
3127 of large files well structured. It supports ToDo items, deadlines and
3128 time stamps, which magically appear in the diary listing of the Emacs
3129 calendar. Tables are easily created with a built-in table editor.
3130 Plain text URL-like links connect to websites, emails (VM), Usenet
3131 messages (Gnus), BBDB entries, and any files related to the project.
3132 For printing and sharing of notes, an Org-mode file (or a part of it)
3133 can be exported as a structured ASCII or HTML file.
3135 The following commands are available:
3137 \\{org-mode-map}"
3139 ;; Get rid of Outline menus, they are not needed
3140 ;; Need to do this here because define-derived-mode sets up
3141 ;; the keymap so late. Still, it is a waste to call this each time
3142 ;; we switch another buffer into org-mode.
3143 (if (featurep 'xemacs)
3144 (when (boundp 'outline-mode-menu-heading)
3145 ;; Assume this is Greg's port, it used easymenu
3146 (easy-menu-remove outline-mode-menu-heading)
3147 (easy-menu-remove outline-mode-menu-show)
3148 (easy-menu-remove outline-mode-menu-hide))
3149 (define-key org-mode-map [menu-bar headings] 'undefined)
3150 (define-key org-mode-map [menu-bar hide] 'undefined)
3151 (define-key org-mode-map [menu-bar show] 'undefined))
3153 (org-load-modules-maybe)
3154 (easy-menu-add org-org-menu)
3155 (easy-menu-add org-tbl-menu)
3156 (org-install-agenda-files-menu)
3157 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3158 (org-add-to-invisibility-spec '(org-cwidth))
3159 (when (featurep 'xemacs)
3160 (org-set-local 'line-move-ignore-invisible t))
3161 (org-set-local 'outline-regexp org-outline-regexp)
3162 (org-set-local 'outline-level 'org-outline-level)
3163 (when (and org-ellipsis
3164 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3165 (fboundp 'make-glyph-code))
3166 (unless org-display-table
3167 (setq org-display-table (make-display-table)))
3168 (set-display-table-slot
3169 org-display-table 4
3170 (vconcat (mapcar
3171 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3172 org-ellipsis)))
3173 (if (stringp org-ellipsis) org-ellipsis "..."))))
3174 (setq buffer-display-table org-display-table))
3175 (org-set-regexps-and-options)
3176 ;; Calc embedded
3177 (org-set-local 'calc-embedded-open-mode "# ")
3178 (modify-syntax-entry ?# "<")
3179 (modify-syntax-entry ?@ "w")
3180 (if org-startup-truncated (setq truncate-lines t))
3181 (org-set-local 'font-lock-unfontify-region-function
3182 'org-unfontify-region)
3183 ;; Activate before-change-function
3184 (org-set-local 'org-table-may-need-update t)
3185 (org-add-hook 'before-change-functions 'org-before-change-function nil
3186 'local)
3187 ;; Check for running clock before killing a buffer
3188 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3189 ;; Paragraphs and auto-filling
3190 (org-set-autofill-regexps)
3191 (setq indent-line-function 'org-indent-line-function)
3192 (org-update-radio-target-regexp)
3194 ;; Comment characters
3195 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3196 (org-set-local 'comment-padding " ")
3198 ;; Align options lines
3199 (org-set-local
3200 'align-mode-rules-list
3201 '((org-in-buffer-settings
3202 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3203 (modes . '(org-mode)))))
3205 ;; Imenu
3206 (org-set-local 'imenu-create-index-function
3207 'org-imenu-get-tree)
3209 ;; Make isearch reveal context
3210 (if (or (featurep 'xemacs)
3211 (not (boundp 'outline-isearch-open-invisible-function)))
3212 ;; Emacs 21 and XEmacs make use of the hook
3213 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3214 ;; Emacs 22 deals with this through a special variable
3215 (org-set-local 'outline-isearch-open-invisible-function
3216 (lambda (&rest ignore) (org-show-context 'isearch))))
3218 ;; If empty file that did not turn on org-mode automatically, make it to.
3219 (if (and org-insert-mode-line-in-empty-file
3220 (interactive-p)
3221 (= (point-min) (point-max)))
3222 (insert "# -*- mode: org -*-\n\n"))
3224 (unless org-inhibit-startup
3225 (when org-startup-align-all-tables
3226 (let ((bmp (buffer-modified-p)))
3227 (org-table-map-tables 'org-table-align)
3228 (set-buffer-modified-p bmp)))
3229 (org-set-startup-visibility)))
3231 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3233 (defun org-current-time ()
3234 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3235 (if (> (car org-time-stamp-rounding-minutes) 1)
3236 (let ((r (car org-time-stamp-rounding-minutes))
3237 (time (decode-time)))
3238 (apply 'encode-time
3239 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3240 (nthcdr 2 time))))
3241 (current-time)))
3243 ;;;; Font-Lock stuff, including the activators
3245 (defvar org-mouse-map (make-sparse-keymap))
3246 (org-defkey org-mouse-map
3247 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3248 (org-defkey org-mouse-map
3249 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3250 (when org-mouse-1-follows-link
3251 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3252 (when org-tab-follows-link
3253 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3254 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3255 (when org-return-follows-link
3256 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3257 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3259 (require 'font-lock)
3261 (defconst org-non-link-chars "]\t\n\r<>")
3262 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3263 "shell" "elisp"))
3264 (defvar org-link-types-re nil
3265 "Matches a link that has a url-like prefix like \"http:\"")
3266 (defvar org-link-re-with-space nil
3267 "Matches a link with spaces, optional angular brackets around it.")
3268 (defvar org-link-re-with-space2 nil
3269 "Matches a link with spaces, optional angular brackets around it.")
3270 (defvar org-angle-link-re nil
3271 "Matches link with angular brackets, spaces are allowed.")
3272 (defvar org-plain-link-re nil
3273 "Matches plain link, without spaces.")
3274 (defvar org-bracket-link-regexp nil
3275 "Matches a link in double brackets.")
3276 (defvar org-bracket-link-analytic-regexp nil
3277 "Regular expression used to analyze links.
3278 Here is what the match groups contain after a match:
3279 1: http:
3280 2: http
3281 3: path
3282 4: [desc]
3283 5: desc")
3284 (defvar org-any-link-re nil
3285 "Regular expression matching any link.")
3287 (defun org-make-link-regexps ()
3288 "Update the link regular expressions.
3289 This should be called after the variable `org-link-types' has changed."
3290 (setq org-link-types-re
3291 (concat
3292 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3293 org-link-re-with-space
3294 (concat
3295 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3296 "\\([^" org-non-link-chars " ]"
3297 "[^" org-non-link-chars "]*"
3298 "[^" org-non-link-chars " ]\\)>?")
3299 org-link-re-with-space2
3300 (concat
3301 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3302 "\\([^" org-non-link-chars " ]"
3303 "[^]\t\n\r]*"
3304 "[^" org-non-link-chars " ]\\)>?")
3305 org-angle-link-re
3306 (concat
3307 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3308 "\\([^" org-non-link-chars " ]"
3309 "[^" org-non-link-chars "]*"
3310 "\\)>")
3311 org-plain-link-re
3312 (concat
3313 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3314 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3315 org-bracket-link-regexp
3316 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3317 org-bracket-link-analytic-regexp
3318 (concat
3319 "\\[\\["
3320 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3321 "\\([^]]+\\)"
3322 "\\]"
3323 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3324 "\\]")
3325 org-any-link-re
3326 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3327 org-angle-link-re "\\)\\|\\("
3328 org-plain-link-re "\\)")))
3330 (org-make-link-regexps)
3332 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3333 "Regular expression for fast time stamp matching.")
3334 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3335 "Regular expression for fast time stamp matching.")
3336 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3337 "Regular expression matching time strings for analysis.
3338 This one does not require the space after the date, so it can be used
3339 on a string that terminates immediately after the date.")
3340 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3341 "Regular expression matching time strings for analysis.")
3342 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3343 "Regular expression matching time stamps, with groups.")
3344 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3345 "Regular expression matching time stamps (also [..]), with groups.")
3346 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3347 "Regular expression matching a time stamp range.")
3348 (defconst org-tr-regexp-both
3349 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3350 "Regular expression matching a time stamp range.")
3351 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3352 org-ts-regexp "\\)?")
3353 "Regular expression matching a time stamp or time stamp range.")
3354 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3355 org-ts-regexp-both "\\)?")
3356 "Regular expression matching a time stamp or time stamp range.
3357 The time stamps may be either active or inactive.")
3359 (defvar org-emph-face nil)
3361 (defun org-do-emphasis-faces (limit)
3362 "Run through the buffer and add overlays to links."
3363 (let (rtn)
3364 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3365 (if (not (= (char-after (match-beginning 3))
3366 (char-after (match-beginning 4))))
3367 (progn
3368 (setq rtn t)
3369 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3370 'face
3371 (nth 1 (assoc (match-string 3)
3372 org-emphasis-alist)))
3373 (add-text-properties (match-beginning 2) (match-end 2)
3374 '(font-lock-multiline t))
3375 (when org-hide-emphasis-markers
3376 (add-text-properties (match-end 4) (match-beginning 5)
3377 '(invisible org-link))
3378 (add-text-properties (match-beginning 3) (match-end 3)
3379 '(invisible org-link)))))
3380 (backward-char 1))
3381 rtn))
3383 (defun org-emphasize (&optional char)
3384 "Insert or change an emphasis, i.e. a font like bold or italic.
3385 If there is an active region, change that region to a new emphasis.
3386 If there is no region, just insert the marker characters and position
3387 the cursor between them.
3388 CHAR should be either the marker character, or the first character of the
3389 HTML tag associated with that emphasis. If CHAR is a space, the means
3390 to remove the emphasis of the selected region.
3391 If char is not given (for example in an interactive call) it
3392 will be prompted for."
3393 (interactive)
3394 (let ((eal org-emphasis-alist) e det
3395 (erc org-emphasis-regexp-components)
3396 (prompt "")
3397 (string "") beg end move tag c s)
3398 (if (org-region-active-p)
3399 (setq beg (region-beginning) end (region-end)
3400 string (buffer-substring beg end))
3401 (setq move t))
3403 (while (setq e (pop eal))
3404 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3405 c (aref tag 0))
3406 (push (cons c (string-to-char (car e))) det)
3407 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3408 (substring tag 1)))))
3409 (unless char
3410 (message "%s" (concat "Emphasis marker or tag:" prompt))
3411 (setq char (read-char-exclusive)))
3412 (setq char (or (cdr (assoc char det)) char))
3413 (if (equal char ?\ )
3414 (setq s "" move nil)
3415 (unless (assoc (char-to-string char) org-emphasis-alist)
3416 (error "No such emphasis marker: \"%c\"" char))
3417 (setq s (char-to-string char)))
3418 (while (and (> (length string) 1)
3419 (equal (substring string 0 1) (substring string -1))
3420 (assoc (substring string 0 1) org-emphasis-alist))
3421 (setq string (substring string 1 -1)))
3422 (setq string (concat s string s))
3423 (if beg (delete-region beg end))
3424 (unless (or (bolp)
3425 (string-match (concat "[" (nth 0 erc) "\n]")
3426 (char-to-string (char-before (point)))))
3427 (insert " "))
3428 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3429 (char-to-string (char-after (point))))
3430 (insert " ") (backward-char 1))
3431 (insert string)
3432 (and move (backward-char 1))))
3434 (defconst org-nonsticky-props
3435 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3438 (defun org-activate-plain-links (limit)
3439 "Run through the buffer and add overlays to links."
3440 (catch 'exit
3441 (let (f)
3442 (while (re-search-forward org-plain-link-re limit t)
3443 (setq f (get-text-property (match-beginning 0) 'face))
3444 (if (or (eq f 'org-tag)
3445 (and (listp f) (memq 'org-tag f)))
3447 (add-text-properties (match-beginning 0) (match-end 0)
3448 (list 'mouse-face 'highlight
3449 'rear-nonsticky org-nonsticky-props
3450 'keymap org-mouse-map
3452 (throw 'exit t))))))
3454 (defun org-activate-code (limit)
3455 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3456 (unless (get-text-property (match-beginning 1) 'face)
3457 (remove-text-properties (match-beginning 0) (match-end 0)
3458 '(display t invisible t intangible t))
3459 t)))
3461 (defun org-activate-angle-links (limit)
3462 "Run through the buffer and add overlays to links."
3463 (if (re-search-forward org-angle-link-re limit t)
3464 (progn
3465 (add-text-properties (match-beginning 0) (match-end 0)
3466 (list 'mouse-face 'highlight
3467 'rear-nonsticky org-nonsticky-props
3468 'keymap org-mouse-map
3470 t)))
3472 (defun org-activate-bracket-links (limit)
3473 "Run through the buffer and add overlays to bracketed links."
3474 (if (re-search-forward org-bracket-link-regexp limit t)
3475 (let* ((help (concat "LINK: "
3476 (org-match-string-no-properties 1)))
3477 ;; FIXME: above we should remove the escapes.
3478 ;; but that requires another match, protecting match data,
3479 ;; a lot of overhead for font-lock.
3480 (ip (org-maybe-intangible
3481 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3482 'keymap org-mouse-map 'mouse-face 'highlight
3483 'font-lock-multiline t 'help-echo help)))
3484 (vp (list 'rear-nonsticky org-nonsticky-props
3485 'keymap org-mouse-map 'mouse-face 'highlight
3486 ' font-lock-multiline t 'help-echo help)))
3487 ;; We need to remove the invisible property here. Table narrowing
3488 ;; may have made some of this invisible.
3489 (remove-text-properties (match-beginning 0) (match-end 0)
3490 '(invisible nil))
3491 (if (match-end 3)
3492 (progn
3493 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3494 (add-text-properties (match-beginning 3) (match-end 3) vp)
3495 (add-text-properties (match-end 3) (match-end 0) ip))
3496 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3497 (add-text-properties (match-beginning 1) (match-end 1) vp)
3498 (add-text-properties (match-end 1) (match-end 0) ip))
3499 t)))
3501 (defun org-activate-dates (limit)
3502 "Run through the buffer and add overlays to dates."
3503 (if (re-search-forward org-tsr-regexp-both limit t)
3504 (progn
3505 (add-text-properties (match-beginning 0) (match-end 0)
3506 (list 'mouse-face 'highlight
3507 'rear-nonsticky org-nonsticky-props
3508 'keymap org-mouse-map))
3509 (when org-display-custom-times
3510 (if (match-end 3)
3511 (org-display-custom-time (match-beginning 3) (match-end 3)))
3512 (org-display-custom-time (match-beginning 1) (match-end 1)))
3513 t)))
3515 (defvar org-target-link-regexp nil
3516 "Regular expression matching radio targets in plain text.")
3517 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3518 "Regular expression matching a link target.")
3519 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3520 "Regular expression matching a radio target.")
3521 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3522 "Regular expression matching any target.")
3524 (defun org-activate-target-links (limit)
3525 "Run through the buffer and add overlays to target matches."
3526 (when org-target-link-regexp
3527 (let ((case-fold-search t))
3528 (if (re-search-forward org-target-link-regexp limit t)
3529 (progn
3530 (add-text-properties (match-beginning 0) (match-end 0)
3531 (list 'mouse-face 'highlight
3532 'rear-nonsticky org-nonsticky-props
3533 'keymap org-mouse-map
3534 'help-echo "Radio target link"
3535 'org-linked-text t))
3536 t)))))
3538 (defun org-update-radio-target-regexp ()
3539 "Find all radio targets in this file and update the regular expression."
3540 (interactive)
3541 (when (memq 'radio org-activate-links)
3542 (setq org-target-link-regexp
3543 (org-make-target-link-regexp (org-all-targets 'radio)))
3544 (org-restart-font-lock)))
3546 (defun org-hide-wide-columns (limit)
3547 (let (s e)
3548 (setq s (text-property-any (point) (or limit (point-max))
3549 'org-cwidth t))
3550 (when s
3551 (setq e (next-single-property-change s 'org-cwidth))
3552 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3553 (goto-char e)
3554 t)))
3556 (defvar org-latex-and-specials-regexp nil
3557 "Regular expression for highlighting export special stuff.")
3558 (defvar org-match-substring-regexp)
3559 (defvar org-match-substring-with-braces-regexp)
3560 (defvar org-export-html-special-string-regexps)
3562 (defun org-compute-latex-and-specials-regexp ()
3563 "Compute regular expression for stuff treated specially by exporters."
3564 (if (not org-highlight-latex-fragments-and-specials)
3565 (org-set-local 'org-latex-and-specials-regexp nil)
3566 (require 'org-exp)
3567 (let*
3568 ((matchers (plist-get org-format-latex-options :matchers))
3569 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3570 org-latex-regexps)))
3571 (options (org-combine-plists (org-default-export-plist)
3572 (org-infile-export-plist)))
3573 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3574 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3575 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3576 (org-export-html-expand (plist-get options :expand-quoted-html))
3577 (org-export-with-special-strings (plist-get options :special-strings))
3578 (re-sub
3579 (cond
3580 ((equal org-export-with-sub-superscripts '{})
3581 (list org-match-substring-with-braces-regexp))
3582 (org-export-with-sub-superscripts
3583 (list org-match-substring-regexp))
3584 (t nil)))
3585 (re-latex
3586 (if org-export-with-LaTeX-fragments
3587 (mapcar (lambda (x) (nth 1 x)) latexs)))
3588 (re-macros
3589 (if org-export-with-TeX-macros
3590 (list (concat "\\\\"
3591 (regexp-opt
3592 (append (mapcar 'car org-html-entities)
3593 (if (boundp 'org-latex-entities)
3594 org-latex-entities nil))
3595 'words))) ; FIXME
3597 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3598 (re-special (if org-export-with-special-strings
3599 (mapcar (lambda (x) (car x))
3600 org-export-html-special-string-regexps)))
3601 (re-rest
3602 (delq nil
3603 (list
3604 (if org-export-html-expand "@<[^>\n]+>")
3605 ))))
3606 (org-set-local
3607 'org-latex-and-specials-regexp
3608 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3609 re-rest) "\\|")))))
3611 (defun org-do-latex-and-special-faces (limit)
3612 "Run through the buffer and add overlays to links."
3613 (when org-latex-and-specials-regexp
3614 (let (rtn d)
3615 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3616 limit t))
3617 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3618 'face))
3619 '(org-code org-verbatim underline)))
3620 (progn
3621 (setq rtn t
3622 d (cond ((member (char-after (1+ (match-beginning 0)))
3623 '(?_ ?^)) 1)
3624 (t 0)))
3625 (font-lock-prepend-text-property
3626 (+ d (match-beginning 0)) (match-end 0)
3627 'face 'org-latex-and-export-specials)
3628 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3629 '(font-lock-multiline t)))))
3630 rtn)))
3632 (defun org-restart-font-lock ()
3633 "Restart font-lock-mode, to force refontification."
3634 (when (and (boundp 'font-lock-mode) font-lock-mode)
3635 (font-lock-mode -1)
3636 (font-lock-mode 1)))
3638 (defun org-all-targets (&optional radio)
3639 "Return a list of all targets in this file.
3640 With optional argument RADIO, only find radio targets."
3641 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3642 rtn)
3643 (save-excursion
3644 (goto-char (point-min))
3645 (while (re-search-forward re nil t)
3646 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3647 rtn)))
3649 (defun org-make-target-link-regexp (targets)
3650 "Make regular expression matching all strings in TARGETS.
3651 The regular expression finds the targets also if there is a line break
3652 between words."
3653 (and targets
3654 (concat
3655 "\\<\\("
3656 (mapconcat
3657 (lambda (x)
3658 (while (string-match " +" x)
3659 (setq x (replace-match "\\s-+" t t x)))
3661 targets
3662 "\\|")
3663 "\\)\\>")))
3665 (defun org-activate-tags (limit)
3666 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3667 (progn
3668 (add-text-properties (match-beginning 1) (match-end 1)
3669 (list 'mouse-face 'highlight
3670 'rear-nonsticky org-nonsticky-props
3671 'keymap org-mouse-map))
3672 t)))
3674 (defun org-outline-level ()
3675 (save-excursion
3676 (looking-at outline-regexp)
3677 (if (match-beginning 1)
3678 (+ (org-get-string-indentation (match-string 1)) 1000)
3679 (1- (- (match-end 0) (match-beginning 0))))))
3681 (defvar org-font-lock-keywords nil)
3683 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3684 "Regular expression matching a property line.")
3686 (defvar org-font-lock-hook nil
3687 "Functions to be called for special font lock stuff.")
3689 (defun org-font-lock-hook (limit)
3690 (run-hook-with-args 'org-font-lock-hook limit))
3692 (defun org-set-font-lock-defaults ()
3693 (let* ((em org-fontify-emphasized-text)
3694 (lk org-activate-links)
3695 (org-font-lock-extra-keywords
3696 (list
3697 ;; Call the hook
3698 '(org-font-lock-hook)
3699 ;; Headlines
3700 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3701 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3702 ;; Table lines
3703 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3704 (1 'org-table t))
3705 ;; Table internals
3706 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3707 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3708 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3709 ;; Drawers
3710 (list org-drawer-regexp '(0 'org-special-keyword t))
3711 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3712 ;; Properties
3713 (list org-property-re
3714 '(1 'org-special-keyword t)
3715 '(3 'org-property-value t))
3716 (if org-format-transports-properties-p
3717 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3718 ;; Links
3719 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3720 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3721 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3722 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3723 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3724 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3725 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3726 '(org-hide-wide-columns (0 nil append))
3727 ;; TODO lines
3728 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3729 '(1 (org-get-todo-face 1) t))
3730 ;; DONE
3731 (if org-fontify-done-headline
3732 (list (concat "^[*]+ +\\<\\("
3733 (mapconcat 'regexp-quote org-done-keywords "\\|")
3734 "\\)\\(.*\\)")
3735 '(2 'org-headline-done t))
3736 nil)
3737 ;; Priorities
3738 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3739 ;; Special keywords
3740 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3741 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3742 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3743 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3744 ;; Emphasis
3745 (if em
3746 (if (featurep 'xemacs)
3747 '(org-do-emphasis-faces (0 nil append))
3748 '(org-do-emphasis-faces)))
3749 ;; Checkboxes
3750 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3751 2 'bold prepend)
3752 (if org-provide-checkbox-statistics
3753 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3754 (0 (org-get-checkbox-statistics-face) t)))
3755 ;; Description list items
3756 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3757 2 'bold prepend)
3758 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3759 '(1 'org-archived prepend))
3760 ;; Specials
3761 '(org-do-latex-and-special-faces)
3762 ;; Code
3763 '(org-activate-code (1 'org-code t))
3764 ;; COMMENT
3765 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3766 "\\|" org-quote-string "\\)\\>")
3767 '(1 'org-special-keyword t))
3768 '("^#.*" (0 'font-lock-comment-face t))
3770 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3771 ;; Now set the full font-lock-keywords
3772 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3773 (org-set-local 'font-lock-defaults
3774 '(org-font-lock-keywords t nil nil backward-paragraph))
3775 (kill-local-variable 'font-lock-keywords) nil))
3777 (defvar org-m nil)
3778 (defvar org-l nil)
3779 (defvar org-f nil)
3780 (defun org-get-level-face (n)
3781 "Get the right face for match N in font-lock matching of healdines."
3782 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3783 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3784 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3785 (cond
3786 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3787 ((eq n 2) org-f)
3788 (t (if org-level-color-stars-only nil org-f))))
3790 (defun org-get-todo-face (kwd)
3791 "Get the right face for a TODO keyword KWD.
3792 If KWD is a number, get the corresponding match group."
3793 (if (numberp kwd) (setq kwd (match-string kwd)))
3794 (or (cdr (assoc kwd org-todo-keyword-faces))
3795 (and (member kwd org-done-keywords) 'org-done)
3796 'org-todo))
3798 (defun org-unfontify-region (beg end &optional maybe_loudly)
3799 "Remove fontification and activation overlays from links."
3800 (font-lock-default-unfontify-region beg end)
3801 (let* ((buffer-undo-list t)
3802 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3803 (inhibit-modification-hooks t)
3804 deactivate-mark buffer-file-name buffer-file-truename)
3805 (remove-text-properties beg end
3806 '(mouse-face t keymap t org-linked-text t
3807 invisible t intangible t))))
3809 ;;;; Visibility cycling, including org-goto and indirect buffer
3811 ;;; Cycling
3813 (defvar org-cycle-global-status nil)
3814 (make-variable-buffer-local 'org-cycle-global-status)
3815 (defvar org-cycle-subtree-status nil)
3816 (make-variable-buffer-local 'org-cycle-subtree-status)
3818 ;;;###autoload
3819 (defun org-cycle (&optional arg)
3820 "Visibility cycling for Org-mode.
3822 - When this function is called with a prefix argument, rotate the entire
3823 buffer through 3 states (global cycling)
3824 1. OVERVIEW: Show only top-level headlines.
3825 2. CONTENTS: Show all headlines of all levels, but no body text.
3826 3. SHOW ALL: Show everything.
3827 When called with two C-c C-u prefixes, switch to the startup visibility,
3828 determined by the variable `org-startup-folded', and by any VISIBILITY
3829 properties in the buffer.
3831 - When point is at the beginning of a headline, rotate the subtree started
3832 by this line through 3 different states (local cycling)
3833 1. FOLDED: Only the main headline is shown.
3834 2. CHILDREN: The main headline and the direct children are shown.
3835 From this state, you can move to one of the children
3836 and zoom in further.
3837 3. SUBTREE: Show the entire subtree, including body text.
3839 - When there is a numeric prefix, go up to a heading with level ARG, do
3840 a `show-subtree' and return to the previous cursor position. If ARG
3841 is negative, go up that many levels.
3843 - When point is not at the beginning of a headline, execute the global
3844 binding for TAB, which is re-indenting the line. See the option
3845 `org-cycle-emulate-tab' for details.
3847 - Special case: if point is at the beginning of the buffer and there is
3848 no headline in line 1, this function will act as if called with prefix arg.
3849 But only if also the variable `org-cycle-global-at-bob' is t."
3850 (interactive "P")
3851 (org-load-modules-maybe)
3852 (let* ((outline-regexp
3853 (if (and (org-mode-p) org-cycle-include-plain-lists)
3854 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3855 outline-regexp))
3856 (bob-special (and org-cycle-global-at-bob (bobp)
3857 (not (looking-at outline-regexp))))
3858 (org-cycle-hook
3859 (if bob-special
3860 (delq 'org-optimize-window-after-visibility-change
3861 (copy-sequence org-cycle-hook))
3862 org-cycle-hook))
3863 (pos (point)))
3865 (if (or bob-special (equal arg '(4)))
3866 ;; special case: use global cycling
3867 (setq arg t))
3869 (cond
3871 ((equal arg '(16))
3872 (org-set-startup-visibility)
3873 (message "Startup visibility, plus VISIBILITY properties."))
3875 ((org-at-table-p 'any)
3876 ;; Enter the table or move to the next field in the table
3877 (or (org-table-recognize-table.el)
3878 (progn
3879 (if arg (org-table-edit-field t)
3880 (org-table-justify-field-maybe)
3881 (call-interactively 'org-table-next-field)))))
3883 ((eq arg t) ;; Global cycling
3885 (cond
3886 ((and (eq last-command this-command)
3887 (eq org-cycle-global-status 'overview))
3888 ;; We just created the overview - now do table of contents
3889 ;; This can be slow in very large buffers, so indicate action
3890 (message "CONTENTS...")
3891 (org-content)
3892 (message "CONTENTS...done")
3893 (setq org-cycle-global-status 'contents)
3894 (run-hook-with-args 'org-cycle-hook 'contents))
3896 ((and (eq last-command this-command)
3897 (eq org-cycle-global-status 'contents))
3898 ;; We just showed the table of contents - now show everything
3899 (show-all)
3900 (message "SHOW ALL")
3901 (setq org-cycle-global-status 'all)
3902 (run-hook-with-args 'org-cycle-hook 'all))
3905 ;; Default action: go to overview
3906 (org-overview)
3907 (message "OVERVIEW")
3908 (setq org-cycle-global-status 'overview)
3909 (run-hook-with-args 'org-cycle-hook 'overview))))
3911 ((and org-drawers org-drawer-regexp
3912 (save-excursion
3913 (beginning-of-line 1)
3914 (looking-at org-drawer-regexp)))
3915 ;; Toggle block visibility
3916 (org-flag-drawer
3917 (not (get-char-property (match-end 0) 'invisible))))
3919 ((integerp arg)
3920 ;; Show-subtree, ARG levels up from here.
3921 (save-excursion
3922 (org-back-to-heading)
3923 (outline-up-heading (if (< arg 0) (- arg)
3924 (- (funcall outline-level) arg)))
3925 (org-show-subtree)))
3927 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3928 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3929 ;; At a heading: rotate between three different views
3930 (org-back-to-heading)
3931 (let ((goal-column 0) eoh eol eos)
3932 ;; First, some boundaries
3933 (save-excursion
3934 (org-back-to-heading)
3935 (save-excursion
3936 (beginning-of-line 2)
3937 (while (and (not (eobp)) ;; this is like `next-line'
3938 (get-char-property (1- (point)) 'invisible))
3939 (beginning-of-line 2)) (setq eol (point)))
3940 (outline-end-of-heading) (setq eoh (point))
3941 (org-end-of-subtree t)
3942 (unless (eobp)
3943 (skip-chars-forward " \t\n")
3944 (beginning-of-line 1) ; in case this is an item
3946 (setq eos (1- (point))))
3947 ;; Find out what to do next and set `this-command'
3948 (cond
3949 ((= eos eoh)
3950 ;; Nothing is hidden behind this heading
3951 (message "EMPTY ENTRY")
3952 (setq org-cycle-subtree-status nil)
3953 (save-excursion
3954 (goto-char eos)
3955 (outline-next-heading)
3956 (if (org-invisible-p) (org-flag-heading nil))))
3957 ((or (>= eol eos)
3958 (not (string-match "\\S-" (buffer-substring eol eos))))
3959 ;; Entire subtree is hidden in one line: open it
3960 (org-show-entry)
3961 (show-children)
3962 (message "CHILDREN")
3963 (save-excursion
3964 (goto-char eos)
3965 (outline-next-heading)
3966 (if (org-invisible-p) (org-flag-heading nil)))
3967 (setq org-cycle-subtree-status 'children)
3968 (run-hook-with-args 'org-cycle-hook 'children))
3969 ((and (eq last-command this-command)
3970 (eq org-cycle-subtree-status 'children))
3971 ;; We just showed the children, now show everything.
3972 (org-show-subtree)
3973 (message "SUBTREE")
3974 (setq org-cycle-subtree-status 'subtree)
3975 (run-hook-with-args 'org-cycle-hook 'subtree))
3977 ;; Default action: hide the subtree.
3978 (hide-subtree)
3979 (message "FOLDED")
3980 (setq org-cycle-subtree-status 'folded)
3981 (run-hook-with-args 'org-cycle-hook 'folded)))))
3983 ;; TAB emulation and template completion
3984 (buffer-read-only (org-back-to-heading))
3986 ((org-try-structure-completion))
3988 ((org-try-cdlatex-tab))
3990 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3991 (or (not (bolp))
3992 (not (looking-at outline-regexp))))
3993 (call-interactively (global-key-binding "\t")))
3995 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3996 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3997 (or (and (eq org-cycle-emulate-tab 'white)
3998 (= (match-end 0) (point-at-eol)))
3999 (and (eq org-cycle-emulate-tab 'whitestart)
4000 (>= (match-end 0) pos))))
4002 (eq org-cycle-emulate-tab t))
4003 (call-interactively (global-key-binding "\t")))
4005 (t (save-excursion
4006 (org-back-to-heading)
4007 (org-cycle))))))
4009 ;;;###autoload
4010 (defun org-global-cycle (&optional arg)
4011 "Cycle the global visibility. For details see `org-cycle'.
4012 With C-u prefix arg, switch to startup visibility.
4013 With a numeric prefix, show all headlines up to that level."
4014 (interactive "P")
4015 (let ((org-cycle-include-plain-lists
4016 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4017 (cond
4018 ((integerp arg)
4019 (show-all)
4020 (hide-sublevels arg)
4021 (setq org-cycle-global-status 'contents))
4022 ((equal arg '(4))
4023 (org-set-startup-visibility)
4024 (message "Startup visibility, plus VISIBILITY properties."))
4026 (org-cycle '(4))))))
4028 (defun org-set-startup-visibility ()
4029 "Set the visibility required by startup options and properties."
4030 (cond
4031 ((eq org-startup-folded t)
4032 (org-cycle '(4)))
4033 ((eq org-startup-folded 'content)
4034 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4035 (org-cycle '(4)) (org-cycle '(4)))))
4036 (org-set-visibility-according-to-property 'no-cleanup)
4037 (org-cycle-hide-archived-subtrees 'all)
4038 (org-cycle-hide-drawers 'all)
4039 (org-cycle-show-empty-lines 'all))
4041 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4042 "Switch subtree visibilities according to :VISIBILITY: property."
4043 (interactive)
4044 (let (state)
4045 (save-excursion
4046 (goto-char (point-min))
4047 (while (re-search-forward
4048 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4049 nil t)
4050 (setq state (match-string 1))
4051 (save-excursion
4052 (org-back-to-heading t)
4053 (hide-subtree)
4054 (org-reveal)
4055 (cond
4056 ((equal state '("fold" "folded"))
4057 (hide-subtree))
4058 ((equal state "children")
4059 (org-show-hidden-entry)
4060 (show-children))
4061 ((equal state "content")
4062 (save-excursion
4063 (save-restriction
4064 (org-narrow-to-subtree)
4065 (org-content))))
4066 ((member state '("all" "showall"))
4067 (show-subtree)))))
4068 (unless no-cleanup
4069 (org-cycle-hide-archived-subtrees 'all)
4070 (org-cycle-hide-drawers 'all)
4071 (org-cycle-show-empty-lines 'all)))))
4073 (defun org-overview ()
4074 "Switch to overview mode, shoing only top-level headlines.
4075 Really, this shows all headlines with level equal or greater than the level
4076 of the first headline in the buffer. This is important, because if the
4077 first headline is not level one, then (hide-sublevels 1) gives confusing
4078 results."
4079 (interactive)
4080 (let ((level (save-excursion
4081 (goto-char (point-min))
4082 (if (re-search-forward (concat "^" outline-regexp) nil t)
4083 (progn
4084 (goto-char (match-beginning 0))
4085 (funcall outline-level))))))
4086 (and level (hide-sublevels level))))
4088 (defun org-content (&optional arg)
4089 "Show all headlines in the buffer, like a table of contents.
4090 With numerical argument N, show content up to level N."
4091 (interactive "P")
4092 (save-excursion
4093 ;; Visit all headings and show their offspring
4094 (and (integerp arg) (org-overview))
4095 (goto-char (point-max))
4096 (catch 'exit
4097 (while (and (progn (condition-case nil
4098 (outline-previous-visible-heading 1)
4099 (error (goto-char (point-min))))
4101 (looking-at outline-regexp))
4102 (if (integerp arg)
4103 (show-children (1- arg))
4104 (show-branches))
4105 (if (bobp) (throw 'exit nil))))))
4108 (defun org-optimize-window-after-visibility-change (state)
4109 "Adjust the window after a change in outline visibility.
4110 This function is the default value of the hook `org-cycle-hook'."
4111 (when (get-buffer-window (current-buffer))
4112 (cond
4113 ; ((eq state 'overview) (org-first-headline-recenter 1))
4114 ; ((eq state 'overview) (org-beginning-of-line))
4115 ((eq state 'content) nil)
4116 ((eq state 'all) nil)
4117 ((eq state 'folded) nil)
4118 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4119 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4121 (defun org-compact-display-after-subtree-move ()
4122 (let (beg end)
4123 (save-excursion
4124 (if (org-up-heading-safe)
4125 (progn
4126 (hide-subtree)
4127 (show-entry)
4128 (show-children)
4129 (org-cycle-show-empty-lines 'children)
4130 (org-cycle-hide-drawers 'children))
4131 (org-overview)))))
4133 (defun org-cycle-show-empty-lines (state)
4134 "Show empty lines above all visible headlines.
4135 The region to be covered depends on STATE when called through
4136 `org-cycle-hook'. Lisp program can use t for STATE to get the
4137 entire buffer covered. Note that an empty line is only shown if there
4138 are at least `org-cycle-separator-lines' empty lines before the headeline."
4139 (when (> org-cycle-separator-lines 0)
4140 (save-excursion
4141 (let* ((n org-cycle-separator-lines)
4142 (re (cond
4143 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4144 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4145 (t (let ((ns (number-to-string (- n 2))))
4146 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4147 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4148 beg end)
4149 (cond
4150 ((memq state '(overview contents t))
4151 (setq beg (point-min) end (point-max)))
4152 ((memq state '(children folded))
4153 (setq beg (point) end (progn (org-end-of-subtree t t)
4154 (beginning-of-line 2)
4155 (point)))))
4156 (when beg
4157 (goto-char beg)
4158 (while (re-search-forward re end t)
4159 (if (not (get-char-property (match-end 1) 'invisible))
4160 (outline-flag-region
4161 (match-beginning 1) (match-end 1) nil)))))))
4162 ;; Never hide empty lines at the end of the file.
4163 (save-excursion
4164 (goto-char (point-max))
4165 (outline-previous-heading)
4166 (outline-end-of-heading)
4167 (if (and (looking-at "[ \t\n]+")
4168 (= (match-end 0) (point-max)))
4169 (outline-flag-region (point) (match-end 0) nil))))
4171 (defun org-cycle-hide-drawers (state)
4172 "Re-hide all drawers after a visibility state change."
4173 (when (and (org-mode-p)
4174 (not (memq state '(overview folded))))
4175 (save-excursion
4176 (let* ((globalp (memq state '(contents all)))
4177 (beg (if globalp (point-min) (point)))
4178 (end (if globalp (point-max) (org-end-of-subtree t))))
4179 (goto-char beg)
4180 (while (re-search-forward org-drawer-regexp end t)
4181 (org-flag-drawer t))))))
4183 (defun org-flag-drawer (flag)
4184 (save-excursion
4185 (beginning-of-line 1)
4186 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4187 (let ((b (match-end 0))
4188 (outline-regexp org-outline-regexp))
4189 (if (re-search-forward
4190 "^[ \t]*:END:"
4191 (save-excursion (outline-next-heading) (point)) t)
4192 (outline-flag-region b (point-at-eol) flag)
4193 (error ":END: line missing"))))))
4195 (defun org-subtree-end-visible-p ()
4196 "Is the end of the current subtree visible?"
4197 (pos-visible-in-window-p
4198 (save-excursion (org-end-of-subtree t) (point))))
4200 (defun org-first-headline-recenter (&optional N)
4201 "Move cursor to the first headline and recenter the headline.
4202 Optional argument N means, put the headline into the Nth line of the window."
4203 (goto-char (point-min))
4204 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4205 (beginning-of-line)
4206 (recenter (prefix-numeric-value N))))
4208 ;;; Org-goto
4210 (defvar org-goto-window-configuration nil)
4211 (defvar org-goto-marker nil)
4212 (defvar org-goto-map
4213 (let ((map (make-sparse-keymap)))
4214 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4215 (while (setq cmd (pop cmds))
4216 (substitute-key-definition cmd cmd map global-map)))
4217 (suppress-keymap map)
4218 (org-defkey map "\C-m" 'org-goto-ret)
4219 (org-defkey map [(return)] 'org-goto-ret)
4220 (org-defkey map [(left)] 'org-goto-left)
4221 (org-defkey map [(right)] 'org-goto-right)
4222 (org-defkey map [(control ?g)] 'org-goto-quit)
4223 (org-defkey map "\C-i" 'org-cycle)
4224 (org-defkey map [(tab)] 'org-cycle)
4225 (org-defkey map [(down)] 'outline-next-visible-heading)
4226 (org-defkey map [(up)] 'outline-previous-visible-heading)
4227 (if org-goto-auto-isearch
4228 (if (fboundp 'define-key-after)
4229 (define-key-after map [t] 'org-goto-local-auto-isearch)
4230 nil)
4231 (org-defkey map "q" 'org-goto-quit)
4232 (org-defkey map "n" 'outline-next-visible-heading)
4233 (org-defkey map "p" 'outline-previous-visible-heading)
4234 (org-defkey map "f" 'outline-forward-same-level)
4235 (org-defkey map "b" 'outline-backward-same-level)
4236 (org-defkey map "u" 'outline-up-heading))
4237 (org-defkey map "/" 'org-occur)
4238 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4239 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4240 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4241 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4242 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4243 map))
4245 (defconst org-goto-help
4246 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4247 RET=jump to location [Q]uit and return to previous location
4248 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4250 (defvar org-goto-start-pos) ; dynamically scoped parameter
4252 ;; FIXME: Docstring doe not mention both interfaces
4253 (defun org-goto (&optional alternative-interface)
4254 "Look up a different location in the current file, keeping current visibility.
4256 When you want look-up or go to a different location in a document, the
4257 fastest way is often to fold the entire buffer and then dive into the tree.
4258 This method has the disadvantage, that the previous location will be folded,
4259 which may not be what you want.
4261 This command works around this by showing a copy of the current buffer
4262 in an indirect buffer, in overview mode. You can dive into the tree in
4263 that copy, use org-occur and incremental search to find a location.
4264 When pressing RET or `Q', the command returns to the original buffer in
4265 which the visibility is still unchanged. After RET is will also jump to
4266 the location selected in the indirect buffer and expose the
4267 the headline hierarchy above."
4268 (interactive "P")
4269 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4270 (org-refile-use-outline-path t)
4271 (interface
4272 (if (not alternative-interface)
4273 org-goto-interface
4274 (if (eq org-goto-interface 'outline)
4275 'outline-path-completion
4276 'outline)))
4277 (org-goto-start-pos (point))
4278 (selected-point
4279 (if (eq interface 'outline)
4280 (car (org-get-location (current-buffer) org-goto-help))
4281 (nth 3 (org-refile-get-location "Goto: ")))))
4282 (if selected-point
4283 (progn
4284 (org-mark-ring-push org-goto-start-pos)
4285 (goto-char selected-point)
4286 (if (or (org-invisible-p) (org-invisible-p2))
4287 (org-show-context 'org-goto)))
4288 (message "Quit"))))
4290 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4291 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4292 (defvar org-goto-local-auto-isearch-map) ; defined below
4294 (defun org-get-location (buf help)
4295 "Let the user select a location in the Org-mode buffer BUF.
4296 This function uses a recursive edit. It returns the selected position
4297 or nil."
4298 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4299 (isearch-hide-immediately nil)
4300 (isearch-search-fun-function
4301 (lambda () 'org-goto-local-search-forward-headings))
4302 (org-goto-selected-point org-goto-exit-command))
4303 (save-excursion
4304 (save-window-excursion
4305 (delete-other-windows)
4306 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4307 (switch-to-buffer
4308 (condition-case nil
4309 (make-indirect-buffer (current-buffer) "*org-goto*")
4310 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4311 (with-output-to-temp-buffer "*Help*"
4312 (princ help))
4313 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4314 (setq buffer-read-only nil)
4315 (let ((org-startup-truncated t)
4316 (org-startup-folded nil)
4317 (org-startup-align-all-tables nil))
4318 (org-mode)
4319 (org-overview))
4320 (setq buffer-read-only t)
4321 (if (and (boundp 'org-goto-start-pos)
4322 (integer-or-marker-p org-goto-start-pos))
4323 (let ((org-show-hierarchy-above t)
4324 (org-show-siblings t)
4325 (org-show-following-heading t))
4326 (goto-char org-goto-start-pos)
4327 (and (org-invisible-p) (org-show-context)))
4328 (goto-char (point-min)))
4329 (org-beginning-of-line)
4330 (message "Select location and press RET")
4331 (use-local-map org-goto-map)
4332 (recursive-edit)
4334 (kill-buffer "*org-goto*")
4335 (cons org-goto-selected-point org-goto-exit-command)))
4337 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4338 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4339 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4340 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4342 (defun org-goto-local-search-forward-headings (string bound noerror)
4343 "Search and make sure that anu matches are in headlines."
4344 (catch 'return
4345 (while (search-forward string bound noerror)
4346 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4347 (and (member :headline context)
4348 (not (member :tags context))))
4349 (throw 'return (point))))))
4351 (defun org-goto-local-auto-isearch ()
4352 "Start isearch."
4353 (interactive)
4354 (goto-char (point-min))
4355 (let ((keys (this-command-keys)))
4356 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4357 (isearch-mode t)
4358 (isearch-process-search-char (string-to-char keys)))))
4360 (defun org-goto-ret (&optional arg)
4361 "Finish `org-goto' by going to the new location."
4362 (interactive "P")
4363 (setq org-goto-selected-point (point)
4364 org-goto-exit-command 'return)
4365 (throw 'exit nil))
4367 (defun org-goto-left ()
4368 "Finish `org-goto' by going to the new location."
4369 (interactive)
4370 (if (org-on-heading-p)
4371 (progn
4372 (beginning-of-line 1)
4373 (setq org-goto-selected-point (point)
4374 org-goto-exit-command 'left)
4375 (throw 'exit nil))
4376 (error "Not on a heading")))
4378 (defun org-goto-right ()
4379 "Finish `org-goto' by going to the new location."
4380 (interactive)
4381 (if (org-on-heading-p)
4382 (progn
4383 (setq org-goto-selected-point (point)
4384 org-goto-exit-command 'right)
4385 (throw 'exit nil))
4386 (error "Not on a heading")))
4388 (defun org-goto-quit ()
4389 "Finish `org-goto' without cursor motion."
4390 (interactive)
4391 (setq org-goto-selected-point nil)
4392 (setq org-goto-exit-command 'quit)
4393 (throw 'exit nil))
4395 ;;; Indirect buffer display of subtrees
4397 (defvar org-indirect-dedicated-frame nil
4398 "This is the frame being used for indirect tree display.")
4399 (defvar org-last-indirect-buffer nil)
4401 (defun org-tree-to-indirect-buffer (&optional arg)
4402 "Create indirect buffer and narrow it to current subtree.
4403 With numerical prefix ARG, go up to this level and then take that tree.
4404 If ARG is negative, go up that many levels.
4405 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4406 indirect buffer previously made with this command, to avoid proliferation of
4407 indirect buffers. However, when you call the command with a `C-u' prefix, or
4408 when `org-indirect-buffer-display' is `new-frame', the last buffer
4409 is kept so that you can work with several indirect buffers at the same time.
4410 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4411 requests that a new frame be made for the new buffer, so that the dedicated
4412 frame is not changed."
4413 (interactive "P")
4414 (let ((cbuf (current-buffer))
4415 (cwin (selected-window))
4416 (pos (point))
4417 beg end level heading ibuf)
4418 (save-excursion
4419 (org-back-to-heading t)
4420 (when (numberp arg)
4421 (setq level (org-outline-level))
4422 (if (< arg 0) (setq arg (+ level arg)))
4423 (while (> (setq level (org-outline-level)) arg)
4424 (outline-up-heading 1 t)))
4425 (setq beg (point)
4426 heading (org-get-heading))
4427 (org-end-of-subtree t) (setq end (point)))
4428 (if (and (buffer-live-p org-last-indirect-buffer)
4429 (not (eq org-indirect-buffer-display 'new-frame))
4430 (not arg))
4431 (kill-buffer org-last-indirect-buffer))
4432 (setq ibuf (org-get-indirect-buffer cbuf)
4433 org-last-indirect-buffer ibuf)
4434 (cond
4435 ((or (eq org-indirect-buffer-display 'new-frame)
4436 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4437 (select-frame (make-frame))
4438 (delete-other-windows)
4439 (switch-to-buffer ibuf)
4440 (org-set-frame-title heading))
4441 ((eq org-indirect-buffer-display 'dedicated-frame)
4442 (raise-frame
4443 (select-frame (or (and org-indirect-dedicated-frame
4444 (frame-live-p org-indirect-dedicated-frame)
4445 org-indirect-dedicated-frame)
4446 (setq org-indirect-dedicated-frame (make-frame)))))
4447 (delete-other-windows)
4448 (switch-to-buffer ibuf)
4449 (org-set-frame-title (concat "Indirect: " heading)))
4450 ((eq org-indirect-buffer-display 'current-window)
4451 (switch-to-buffer ibuf))
4452 ((eq org-indirect-buffer-display 'other-window)
4453 (pop-to-buffer ibuf))
4454 (t (error "Invalid value.")))
4455 (if (featurep 'xemacs)
4456 (save-excursion (org-mode) (turn-on-font-lock)))
4457 (narrow-to-region beg end)
4458 (show-all)
4459 (goto-char pos)
4460 (and (window-live-p cwin) (select-window cwin))))
4462 (defun org-get-indirect-buffer (&optional buffer)
4463 (setq buffer (or buffer (current-buffer)))
4464 (let ((n 1) (base (buffer-name buffer)) bname)
4465 (while (buffer-live-p
4466 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4467 (setq n (1+ n)))
4468 (condition-case nil
4469 (make-indirect-buffer buffer bname 'clone)
4470 (error (make-indirect-buffer buffer bname)))))
4472 (defun org-set-frame-title (title)
4473 "Set the title of the current frame to the string TITLE."
4474 ;; FIXME: how to name a single frame in XEmacs???
4475 (unless (featurep 'xemacs)
4476 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4478 ;;;; Structure editing
4480 ;;; Inserting headlines
4482 (defun org-insert-heading (&optional force-heading)
4483 "Insert a new heading or item with same depth at point.
4484 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4485 If point is at the beginning of a headline, insert a sibling before the
4486 current headline. If point is not at the beginning, do not split the line,
4487 but create the new hedline after the current line."
4488 (interactive "P")
4489 (if (= (buffer-size) 0)
4490 (insert "\n* ")
4491 (when (or force-heading (not (org-insert-item)))
4492 (let* ((head (save-excursion
4493 (condition-case nil
4494 (progn
4495 (org-back-to-heading)
4496 (match-string 0))
4497 (error "*"))))
4498 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4499 pos)
4500 (cond
4501 ((and (org-on-heading-p) (bolp)
4502 (or (bobp)
4503 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4504 ;; insert before the current line
4505 (open-line (if blank 2 1)))
4506 ((and (bolp)
4507 (or (bobp)
4508 (save-excursion
4509 (backward-char 1) (not (org-invisible-p)))))
4510 ;; insert right here
4511 nil)
4513 ;; in the middle of the line
4514 (org-show-entry)
4515 (let ((split
4516 (org-get-alist-option org-M-RET-may-split-line 'headline))
4517 tags pos)
4518 (if (org-on-heading-p)
4519 (progn
4520 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4521 (setq tags (and (match-end 2) (match-string 2)))
4522 (and (match-end 1)
4523 (delete-region (match-beginning 1) (match-end 1)))
4524 (setq pos (point-at-bol))
4525 (or split (end-of-line 1))
4526 (delete-horizontal-space)
4527 (newline (if blank 2 1))
4528 (when tags
4529 (save-excursion
4530 (goto-char pos)
4531 (end-of-line 1)
4532 (insert " " tags)
4533 (org-set-tags nil 'align))))
4534 (or split (end-of-line 1))
4535 (newline (if blank 2 1))))))
4536 (insert head) (just-one-space)
4537 (setq pos (point))
4538 (end-of-line 1)
4539 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4540 (run-hooks 'org-insert-heading-hook)))))
4542 (defun org-get-heading (&optional no-tags)
4543 "Return the heading of the current entry, without the stars."
4544 (save-excursion
4545 (org-back-to-heading t)
4546 (if (looking-at
4547 (if no-tags
4548 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4549 "\\*+[ \t]+\\([^\r\n]*\\)"))
4550 (match-string 1) "")))
4552 (defun org-insert-heading-after-current ()
4553 "Insert a new heading with same level as current, after current subtree."
4554 (interactive)
4555 (org-back-to-heading)
4556 (org-insert-heading)
4557 (org-move-subtree-down)
4558 (end-of-line 1))
4560 (defun org-insert-todo-heading (arg)
4561 "Insert a new heading with the same level and TODO state as current heading.
4562 If the heading has no TODO state, or if the state is DONE, use the first
4563 state (TODO by default). Also with prefix arg, force first state."
4564 (interactive "P")
4565 (when (not (org-insert-item 'checkbox))
4566 (org-insert-heading)
4567 (save-excursion
4568 (org-back-to-heading)
4569 (outline-previous-heading)
4570 (looking-at org-todo-line-regexp))
4571 (if (or arg
4572 (not (match-beginning 2))
4573 (member (match-string 2) org-done-keywords))
4574 (insert (car org-todo-keywords-1) " ")
4575 (insert (match-string 2) " "))
4576 (when org-provide-todo-statistics
4577 (org-update-parent-todo-statistics))))
4579 (defun org-insert-subheading (arg)
4580 "Insert a new subheading and demote it.
4581 Works for outline headings and for plain lists alike."
4582 (interactive "P")
4583 (org-insert-heading arg)
4584 (cond
4585 ((org-on-heading-p) (org-do-demote))
4586 ((org-at-item-p) (org-indent-item 1))))
4588 (defun org-insert-todo-subheading (arg)
4589 "Insert a new subheading with TODO keyword or checkbox and demote it.
4590 Works for outline headings and for plain lists alike."
4591 (interactive "P")
4592 (org-insert-todo-heading arg)
4593 (cond
4594 ((org-on-heading-p) (org-do-demote))
4595 ((org-at-item-p) (org-indent-item 1))))
4597 ;;; Promotion and Demotion
4599 (defun org-promote-subtree ()
4600 "Promote the entire subtree.
4601 See also `org-promote'."
4602 (interactive)
4603 (save-excursion
4604 (org-map-tree 'org-promote))
4605 (org-fix-position-after-promote))
4607 (defun org-demote-subtree ()
4608 "Demote the entire subtree. See `org-demote'.
4609 See also `org-promote'."
4610 (interactive)
4611 (save-excursion
4612 (org-map-tree 'org-demote))
4613 (org-fix-position-after-promote))
4616 (defun org-do-promote ()
4617 "Promote the current heading higher up the tree.
4618 If the region is active in `transient-mark-mode', promote all headings
4619 in the region."
4620 (interactive)
4621 (save-excursion
4622 (if (org-region-active-p)
4623 (org-map-region 'org-promote (region-beginning) (region-end))
4624 (org-promote)))
4625 (org-fix-position-after-promote))
4627 (defun org-do-demote ()
4628 "Demote the current heading lower down the tree.
4629 If the region is active in `transient-mark-mode', demote all headings
4630 in the region."
4631 (interactive)
4632 (save-excursion
4633 (if (org-region-active-p)
4634 (org-map-region 'org-demote (region-beginning) (region-end))
4635 (org-demote)))
4636 (org-fix-position-after-promote))
4638 (defun org-fix-position-after-promote ()
4639 "Make sure that after pro/demotion cursor position is right."
4640 (let ((pos (point)))
4641 (when (save-excursion
4642 (beginning-of-line 1)
4643 (looking-at org-todo-line-regexp)
4644 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4645 (cond ((eobp) (insert " "))
4646 ((eolp) (insert " "))
4647 ((equal (char-after) ?\ ) (forward-char 1))))))
4649 (defun org-reduced-level (l)
4650 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4652 (defun org-get-valid-level (level &optional change)
4653 "Rectify a level change under the influence of `org-odd-levels-only'
4654 LEVEL is a current level, CHANGE is by how much the level should be
4655 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4656 even level numbers will become the next higher odd number."
4657 (if org-odd-levels-only
4658 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4659 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4660 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4661 (max 1 (+ level change))))
4663 (if (boundp 'define-obsolete-function-alias)
4664 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4665 (define-obsolete-function-alias 'org-get-legal-level
4666 'org-get-valid-level)
4667 (define-obsolete-function-alias 'org-get-legal-level
4668 'org-get-valid-level "23.1")))
4670 (defun org-promote ()
4671 "Promote the current heading higher up the tree.
4672 If the region is active in `transient-mark-mode', promote all headings
4673 in the region."
4674 (org-back-to-heading t)
4675 (let* ((level (save-match-data (funcall outline-level)))
4676 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4677 (diff (abs (- level (length up-head) -1))))
4678 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4679 (replace-match up-head nil t)
4680 ;; Fixup tag positioning
4681 (and org-auto-align-tags (org-set-tags nil t))
4682 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4684 (defun org-demote ()
4685 "Demote the current heading lower down the tree.
4686 If the region is active in `transient-mark-mode', demote all headings
4687 in the region."
4688 (org-back-to-heading t)
4689 (let* ((level (save-match-data (funcall outline-level)))
4690 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4691 (diff (abs (- level (length down-head) -1))))
4692 (replace-match down-head nil t)
4693 ;; Fixup tag positioning
4694 (and org-auto-align-tags (org-set-tags nil t))
4695 (if org-adapt-indentation (org-fixup-indentation diff))))
4697 (defun org-map-tree (fun)
4698 "Call FUN for every heading underneath the current one."
4699 (org-back-to-heading)
4700 (let ((level (funcall outline-level)))
4701 (save-excursion
4702 (funcall fun)
4703 (while (and (progn
4704 (outline-next-heading)
4705 (> (funcall outline-level) level))
4706 (not (eobp)))
4707 (funcall fun)))))
4709 (defun org-map-region (fun beg end)
4710 "Call FUN for every heading between BEG and END."
4711 (let ((org-ignore-region t))
4712 (save-excursion
4713 (setq end (copy-marker end))
4714 (goto-char beg)
4715 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4716 (< (point) end))
4717 (funcall fun))
4718 (while (and (progn
4719 (outline-next-heading)
4720 (< (point) end))
4721 (not (eobp)))
4722 (funcall fun)))))
4724 (defun org-fixup-indentation (diff)
4725 "Change the indentation in the current entry by DIFF
4726 However, if any line in the current entry has no indentation, or if it
4727 would end up with no indentation after the change, nothing at all is done."
4728 (save-excursion
4729 (let ((end (save-excursion (outline-next-heading)
4730 (point-marker)))
4731 (prohibit (if (> diff 0)
4732 "^\\S-"
4733 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4734 col)
4735 (unless (save-excursion (end-of-line 1)
4736 (re-search-forward prohibit end t))
4737 (while (and (< (point) end)
4738 (re-search-forward "^[ \t]+" end t))
4739 (goto-char (match-end 0))
4740 (setq col (current-column))
4741 (if (< diff 0) (replace-match ""))
4742 (indent-to (+ diff col))))
4743 (move-marker end nil))))
4745 (defun org-convert-to-odd-levels ()
4746 "Convert an org-mode file with all levels allowed to one with odd levels.
4747 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4748 level 5 etc."
4749 (interactive)
4750 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4751 (let ((org-odd-levels-only nil) n)
4752 (save-excursion
4753 (goto-char (point-min))
4754 (while (re-search-forward "^\\*\\*+ " nil t)
4755 (setq n (- (length (match-string 0)) 2))
4756 (while (>= (setq n (1- n)) 0)
4757 (org-demote))
4758 (end-of-line 1))))))
4761 (defun org-convert-to-oddeven-levels ()
4762 "Convert an org-mode file with only odd levels to one with odd and even levels.
4763 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4764 section with an even level, conversion would destroy the structure of the file. An error
4765 is signaled in this case."
4766 (interactive)
4767 (goto-char (point-min))
4768 ;; First check if there are no even levels
4769 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4770 (org-show-context t)
4771 (error "Not all levels are odd in this file. Conversion not possible."))
4772 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4773 (let ((org-odd-levels-only nil) n)
4774 (save-excursion
4775 (goto-char (point-min))
4776 (while (re-search-forward "^\\*\\*+ " nil t)
4777 (setq n (/ (1- (length (match-string 0))) 2))
4778 (while (>= (setq n (1- n)) 0)
4779 (org-promote))
4780 (end-of-line 1))))))
4782 (defun org-tr-level (n)
4783 "Make N odd if required."
4784 (if org-odd-levels-only (1+ (/ n 2)) n))
4786 ;;; Vertical tree motion, cutting and pasting of subtrees
4788 (defun org-move-subtree-up (&optional arg)
4789 "Move the current subtree up past ARG headlines of the same level."
4790 (interactive "p")
4791 (org-move-subtree-down (- (prefix-numeric-value arg))))
4793 (defun org-move-subtree-down (&optional arg)
4794 "Move the current subtree down past ARG headlines of the same level."
4795 (interactive "p")
4796 (setq arg (prefix-numeric-value arg))
4797 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4798 'outline-get-last-sibling))
4799 (ins-point (make-marker))
4800 (cnt (abs arg))
4801 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4802 ;; Select the tree
4803 (org-back-to-heading)
4804 (setq beg0 (point))
4805 (save-excursion
4806 (setq ne-beg (org-back-over-empty-lines))
4807 (setq beg (point)))
4808 (save-match-data
4809 (save-excursion (outline-end-of-heading)
4810 (setq folded (org-invisible-p)))
4811 (outline-end-of-subtree))
4812 (outline-next-heading)
4813 (setq ne-end (org-back-over-empty-lines))
4814 (setq end (point))
4815 (goto-char beg0)
4816 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4817 ;; include less whitespace
4818 (save-excursion
4819 (goto-char beg)
4820 (forward-line (- ne-beg ne-end))
4821 (setq beg (point))))
4822 ;; Find insertion point, with error handling
4823 (while (> cnt 0)
4824 (or (and (funcall movfunc) (looking-at outline-regexp))
4825 (progn (goto-char beg0)
4826 (error "Cannot move past superior level or buffer limit")))
4827 (setq cnt (1- cnt)))
4828 (if (> arg 0)
4829 ;; Moving forward - still need to move over subtree
4830 (progn (org-end-of-subtree t t)
4831 (save-excursion
4832 (org-back-over-empty-lines)
4833 (or (bolp) (newline)))))
4834 (setq ne-ins (org-back-over-empty-lines))
4835 (move-marker ins-point (point))
4836 (setq txt (buffer-substring beg end))
4837 (org-save-markers-in-region beg end)
4838 (delete-region beg end)
4839 (outline-flag-region (1- beg) beg nil)
4840 (outline-flag-region (1- (point)) (point) nil)
4841 (let ((bbb (point)))
4842 (insert-before-markers txt)
4843 (org-reinstall-markers-in-region bbb)
4844 (move-marker ins-point bbb))
4845 (or (bolp) (insert "\n"))
4846 (setq ins-end (point))
4847 (goto-char ins-point)
4848 (org-skip-whitespace)
4849 (when (and (< arg 0)
4850 (org-first-sibling-p)
4851 (> ne-ins ne-beg))
4852 ;; Move whitespace back to beginning
4853 (save-excursion
4854 (goto-char ins-end)
4855 (let ((kill-whole-line t))
4856 (kill-line (- ne-ins ne-beg)) (point)))
4857 (insert (make-string (- ne-ins ne-beg) ?\n)))
4858 (move-marker ins-point nil)
4859 (org-compact-display-after-subtree-move)
4860 (unless folded
4861 (org-show-entry)
4862 (show-children)
4863 (org-cycle-hide-drawers 'children))))
4865 (defvar org-subtree-clip ""
4866 "Clipboard for cut and paste of subtrees.
4867 This is actually only a copy of the kill, because we use the normal kill
4868 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4870 (defvar org-subtree-clip-folded nil
4871 "Was the last copied subtree folded?
4872 This is used to fold the tree back after pasting.")
4874 (defun org-cut-subtree (&optional n)
4875 "Cut the current subtree into the clipboard.
4876 With prefix arg N, cut this many sequential subtrees.
4877 This is a short-hand for marking the subtree and then cutting it."
4878 (interactive "p")
4879 (org-copy-subtree n 'cut))
4881 (defun org-copy-subtree (&optional n cut force-store-markers)
4882 "Cut the current subtree into the clipboard.
4883 With prefix arg N, cut this many sequential subtrees.
4884 This is a short-hand for marking the subtree and then copying it.
4885 If CUT is non-nil, actually cut the subtree.
4886 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4887 of some markers in the region, even if CUT is non-nil. This is
4888 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4889 (interactive "p")
4890 (let (beg end folded (beg0 (point)))
4891 (if (interactive-p)
4892 (org-back-to-heading nil) ; take what looks like a subtree
4893 (org-back-to-heading t)) ; take what is really there
4894 (org-back-over-empty-lines)
4895 (setq beg (point))
4896 (skip-chars-forward " \t\r\n")
4897 (save-match-data
4898 (save-excursion (outline-end-of-heading)
4899 (setq folded (org-invisible-p)))
4900 (condition-case nil
4901 (outline-forward-same-level (1- n))
4902 (error nil))
4903 (org-end-of-subtree t t))
4904 (org-back-over-empty-lines)
4905 (setq end (point))
4906 (goto-char beg0)
4907 (when (> end beg)
4908 (setq org-subtree-clip-folded folded)
4909 (when (or cut force-store-markers)
4910 (org-save-markers-in-region beg end))
4911 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4912 (setq org-subtree-clip (current-kill 0))
4913 (message "%s: Subtree(s) with %d characters"
4914 (if cut "Cut" "Copied")
4915 (length org-subtree-clip)))))
4917 (defun org-paste-subtree (&optional level tree)
4918 "Paste the clipboard as a subtree, with modification of headline level.
4919 The entire subtree is promoted or demoted in order to match a new headline
4920 level. By default, the new level is derived from the visible headings
4921 before and after the insertion point, and taken to be the inferior headline
4922 level of the two. So if the previous visible heading is level 3 and the
4923 next is level 4 (or vice versa), level 4 will be used for insertion.
4924 This makes sure that the subtree remains an independent subtree and does
4925 not swallow low level entries.
4927 You can also force a different level, either by using a numeric prefix
4928 argument, or by inserting the heading marker by hand. For example, if the
4929 cursor is after \"*****\", then the tree will be shifted to level 5.
4931 If you want to insert the tree as is, just use \\[yank].
4933 If optional TREE is given, use this text instead of the kill ring."
4934 (interactive "P")
4935 (unless (org-kill-is-subtree-p tree)
4936 (error "%s"
4937 (substitute-command-keys
4938 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4939 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4940 (^re (concat "^\\(" outline-regexp "\\)"))
4941 (re (concat "\\(" outline-regexp "\\)"))
4942 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4944 (old-level (if (string-match ^re txt)
4945 (- (match-end 0) (match-beginning 0) 1)
4946 -1))
4947 (force-level (cond (level (prefix-numeric-value level))
4948 ((string-match
4949 ^re_ (buffer-substring (point-at-bol) (point)))
4950 (- (match-end 1) (match-beginning 1)))
4951 (t nil)))
4952 (previous-level (save-excursion
4953 (condition-case nil
4954 (progn
4955 (outline-previous-visible-heading 1)
4956 (if (looking-at re)
4957 (- (match-end 0) (match-beginning 0) 1)
4959 (error 1))))
4960 (next-level (save-excursion
4961 (condition-case nil
4962 (progn
4963 (or (looking-at outline-regexp)
4964 (outline-next-visible-heading 1))
4965 (if (looking-at re)
4966 (- (match-end 0) (match-beginning 0) 1)
4968 (error 1))))
4969 (new-level (or force-level (max previous-level next-level)))
4970 (shift (if (or (= old-level -1)
4971 (= new-level -1)
4972 (= old-level new-level))
4974 (- new-level old-level)))
4975 (delta (if (> shift 0) -1 1))
4976 (func (if (> shift 0) 'org-demote 'org-promote))
4977 (org-odd-levels-only nil)
4978 beg end)
4979 ;; Remove the forced level indicator
4980 (if force-level
4981 (delete-region (point-at-bol) (point)))
4982 ;; Paste
4983 (beginning-of-line 1)
4984 (org-back-over-empty-lines)
4985 (setq beg (point))
4986 (insert-before-markers txt)
4987 (unless (string-match "\n\\'" txt) (insert "\n"))
4988 (org-reinstall-markers-in-region beg)
4989 (setq end (point))
4990 (goto-char beg)
4991 (skip-chars-forward " \t\n\r")
4992 (setq beg (point))
4993 ;; Shift if necessary
4994 (unless (= shift 0)
4995 (save-restriction
4996 (narrow-to-region beg end)
4997 (while (not (= shift 0))
4998 (org-map-region func (point-min) (point-max))
4999 (setq shift (+ delta shift)))
5000 (goto-char (point-min))))
5001 (when (interactive-p)
5002 (message "Clipboard pasted as level %d subtree" new-level))
5003 (if (and kill-ring
5004 (eq org-subtree-clip (current-kill 0))
5005 org-subtree-clip-folded)
5006 ;; The tree was folded before it was killed/copied
5007 (hide-subtree))))
5009 (defun org-kill-is-subtree-p (&optional txt)
5010 "Check if the current kill is an outline subtree, or a set of trees.
5011 Returns nil if kill does not start with a headline, or if the first
5012 headline level is not the largest headline level in the tree.
5013 So this will actually accept several entries of equal levels as well,
5014 which is OK for `org-paste-subtree'.
5015 If optional TXT is given, check this string instead of the current kill."
5016 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5017 (start-level (and kill
5018 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5019 org-outline-regexp "\\)")
5020 kill)
5021 (- (match-end 2) (match-beginning 2) 1)))
5022 (re (concat "^" org-outline-regexp))
5023 (start (1+ (match-beginning 2))))
5024 (if (not start-level)
5025 (progn
5026 nil) ;; does not even start with a heading
5027 (catch 'exit
5028 (while (setq start (string-match re kill (1+ start)))
5029 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5030 (throw 'exit nil)))
5031 t))))
5033 (defvar org-markers-to-move nil
5034 "Markers that should be moved with a cut-and-paste operation.
5035 Those markers are stored together with their positions relative to
5036 the start of the region.")
5038 (defun org-save-markers-in-region (beg end)
5039 "Check markers in region.
5040 If these markers are between BEG and END, record their position relative
5041 to BEG, so that after moving the block of text, we can put the markers back
5042 into place.
5043 This function gets called just before an entry or tree gets cut from the
5044 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5045 called immediately, to move the markers with the entries."
5046 (setq org-markers-to-move nil)
5047 (when (featurep 'org-clock)
5048 (org-clock-save-markers-for-cut-and-paste beg end))
5049 (when (featurep 'org-agenda)
5050 (org-agenda-save-markers-for-cut-and-paste beg end)))
5052 (defun org-check-and-save-marker (marker beg end)
5053 "Check if MARKER is between BEG and END.
5054 If yes, remember the marker and the distance to BEG."
5055 (when (and (marker-buffer marker)
5056 (equal (marker-buffer marker) (current-buffer)))
5057 (if (and (>= marker beg) (< marker end))
5058 (push (cons marker (- marker beg)) org-markers-to-move))))
5060 (defun org-reinstall-markers-in-region (beg)
5061 "Move all remembered markers to their position relative to BEG."
5062 (mapc (lambda (x)
5063 (move-marker (car x) (+ beg (cdr x))))
5064 org-markers-to-move)
5065 (setq org-markers-to-move nil))
5067 (defun org-narrow-to-subtree ()
5068 "Narrow buffer to the current subtree."
5069 (interactive)
5070 (save-excursion
5071 (save-match-data
5072 (narrow-to-region
5073 (progn (org-back-to-heading) (point))
5074 (progn (org-end-of-subtree t t) (point))))))
5077 ;;; Outline Sorting
5079 (defun org-sort (with-case)
5080 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5081 Optional argument WITH-CASE means sort case-sensitively."
5082 (interactive "P")
5083 (if (org-at-table-p)
5084 (org-call-with-arg 'org-table-sort-lines with-case)
5085 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5087 (defun org-sort-remove-invisible (s)
5088 (remove-text-properties 0 (length s) org-rm-props s)
5089 (while (string-match org-bracket-link-regexp s)
5090 (setq s (replace-match (if (match-end 2)
5091 (match-string 3 s)
5092 (match-string 1 s)) t t s)))
5095 (defvar org-priority-regexp) ; defined later in the file
5097 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5098 "Sort entries on a certain level of an outline tree.
5099 If there is an active region, the entries in the region are sorted.
5100 Else, if the cursor is before the first entry, sort the top-level items.
5101 Else, the children of the entry at point are sorted.
5103 Sorting can be alphabetically, numerically, and by date/time as given by
5104 the first time stamp in the entry. The command prompts for the sorting
5105 type unless it has been given to the function through the SORTING-TYPE
5106 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5107 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5108 called with point at the beginning of the record. It must return either
5109 a string or a number that should serve as the sorting key for that record.
5111 Comparing entries ignores case by default. However, with an optional argument
5112 WITH-CASE, the sorting considers case as well."
5113 (interactive "P")
5114 (let ((case-func (if with-case 'identity 'downcase))
5115 start beg end stars re re2
5116 txt what tmp plain-list-p)
5117 ;; Find beginning and end of region to sort
5118 (cond
5119 ((org-region-active-p)
5120 ;; we will sort the region
5121 (setq end (region-end)
5122 what "region")
5123 (goto-char (region-beginning))
5124 (if (not (org-on-heading-p)) (outline-next-heading))
5125 (setq start (point)))
5126 ((org-at-item-p)
5127 ;; we will sort this plain list
5128 (org-beginning-of-item-list) (setq start (point))
5129 (org-end-of-item-list) (setq end (point))
5130 (goto-char start)
5131 (setq plain-list-p t
5132 what "plain list"))
5133 ((or (org-on-heading-p)
5134 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5135 ;; we will sort the children of the current headline
5136 (org-back-to-heading)
5137 (setq start (point)
5138 end (progn (org-end-of-subtree t t)
5139 (org-back-over-empty-lines)
5140 (point))
5141 what "children")
5142 (goto-char start)
5143 (show-subtree)
5144 (outline-next-heading))
5146 ;; we will sort the top-level entries in this file
5147 (goto-char (point-min))
5148 (or (org-on-heading-p) (outline-next-heading))
5149 (setq start (point) end (point-max) what "top-level")
5150 (goto-char start)
5151 (show-all)))
5153 (setq beg (point))
5154 (if (>= beg end) (error "Nothing to sort"))
5156 (unless plain-list-p
5157 (looking-at "\\(\\*+\\)")
5158 (setq stars (match-string 1)
5159 re (concat "^" (regexp-quote stars) " +")
5160 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5161 txt (buffer-substring beg end))
5162 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5163 (if (and (not (equal stars "*")) (string-match re2 txt))
5164 (error "Region to sort contains a level above the first entry")))
5166 (unless sorting-type
5167 (message
5168 (if plain-list-p
5169 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5170 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5171 what)
5172 (setq sorting-type (read-char-exclusive))
5174 (and (= (downcase sorting-type) ?f)
5175 (setq getkey-func
5176 (completing-read "Sort using function: "
5177 obarray 'fboundp t nil nil))
5178 (setq getkey-func (intern getkey-func)))
5180 (and (= (downcase sorting-type) ?r)
5181 (setq property
5182 (completing-read "Property: "
5183 (mapcar 'list (org-buffer-property-keys t))
5184 nil t))))
5186 (message "Sorting entries...")
5188 (save-restriction
5189 (narrow-to-region start end)
5191 (let ((dcst (downcase sorting-type))
5192 (now (current-time)))
5193 (sort-subr
5194 (/= dcst sorting-type)
5195 ;; This function moves to the beginning character of the "record" to
5196 ;; be sorted.
5197 (if plain-list-p
5198 (lambda nil
5199 (if (org-at-item-p) t (goto-char (point-max))))
5200 (lambda nil
5201 (if (re-search-forward re nil t)
5202 (goto-char (match-beginning 0))
5203 (goto-char (point-max)))))
5204 ;; This function moves to the last character of the "record" being
5205 ;; sorted.
5206 (if plain-list-p
5207 'org-end-of-item
5208 (lambda nil
5209 (save-match-data
5210 (condition-case nil
5211 (outline-forward-same-level 1)
5212 (error
5213 (goto-char (point-max)))))))
5215 ;; This function returns the value that gets sorted against.
5216 (if plain-list-p
5217 (lambda nil
5218 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5219 (cond
5220 ((= dcst ?n)
5221 (string-to-number (buffer-substring (match-end 0)
5222 (point-at-eol))))
5223 ((= dcst ?a)
5224 (buffer-substring (match-end 0) (point-at-eol)))
5225 ((= dcst ?t)
5226 (if (re-search-forward org-ts-regexp
5227 (point-at-eol) t)
5228 (org-time-string-to-time (match-string 0))
5229 now))
5230 ((= dcst ?f)
5231 (if getkey-func
5232 (progn
5233 (setq tmp (funcall getkey-func))
5234 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5235 tmp)
5236 (error "Invalid key function `%s'" getkey-func)))
5237 (t (error "Invalid sorting type `%c'" sorting-type)))))
5238 (lambda nil
5239 (cond
5240 ((= dcst ?n)
5241 (if (looking-at outline-regexp)
5242 (string-to-number (buffer-substring (match-end 0)
5243 (point-at-eol)))
5244 nil))
5245 ((= dcst ?a)
5246 (funcall case-func (buffer-substring (point-at-bol)
5247 (point-at-eol))))
5248 ((= dcst ?t)
5249 (if (re-search-forward org-ts-regexp
5250 (save-excursion
5251 (forward-line 2)
5252 (point)) t)
5253 (org-time-string-to-time (match-string 0))
5254 now))
5255 ((= dcst ?p)
5256 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5257 (string-to-char (match-string 2))
5258 org-default-priority))
5259 ((= dcst ?r)
5260 (or (org-entry-get nil property) ""))
5261 ((= dcst ?o)
5262 (if (looking-at org-complex-heading-regexp)
5263 (- 9999 (length (member (match-string 2)
5264 org-todo-keywords-1)))))
5265 ((= dcst ?f)
5266 (if getkey-func
5267 (progn
5268 (setq tmp (funcall getkey-func))
5269 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5270 tmp)
5271 (error "Invalid key function `%s'" getkey-func)))
5272 (t (error "Invalid sorting type `%c'" sorting-type)))))
5274 (cond
5275 ((= dcst ?a) 'string<)
5276 ((= dcst ?t) 'time-less-p)
5277 (t nil)))))
5278 (message "Sorting entries...done")))
5280 (defun org-do-sort (table what &optional with-case sorting-type)
5281 "Sort TABLE of WHAT according to SORTING-TYPE.
5282 The user will be prompted for the SORTING-TYPE if the call to this
5283 function does not specify it. WHAT is only for the prompt, to indicate
5284 what is being sorted. The sorting key will be extracted from
5285 the car of the elements of the table.
5286 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5287 (unless sorting-type
5288 (message
5289 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5290 what)
5291 (setq sorting-type (read-char-exclusive)))
5292 (let ((dcst (downcase sorting-type))
5293 extractfun comparefun)
5294 ;; Define the appropriate functions
5295 (cond
5296 ((= dcst ?n)
5297 (setq extractfun 'string-to-number
5298 comparefun (if (= dcst sorting-type) '< '>)))
5299 ((= dcst ?a)
5300 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5301 (lambda(x) (downcase (org-sort-remove-invisible x))))
5302 comparefun (if (= dcst sorting-type)
5303 'string<
5304 (lambda (a b) (and (not (string< a b))
5305 (not (string= a b)))))))
5306 ((= dcst ?t)
5307 (setq extractfun
5308 (lambda (x)
5309 (if (string-match org-ts-regexp x)
5310 (time-to-seconds
5311 (org-time-string-to-time (match-string 0 x)))
5313 comparefun (if (= dcst sorting-type) '< '>)))
5314 (t (error "Invalid sorting type `%c'" sorting-type)))
5316 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5317 table)
5318 (lambda (a b) (funcall comparefun (car a) (car b))))))
5320 ;;;; Plain list items, including checkboxes
5322 ;;; Plain list items
5324 (defun org-at-item-p ()
5325 "Is point in a line starting a hand-formatted item?"
5326 (let ((llt org-plain-list-ordered-item-terminator))
5327 (save-excursion
5328 (goto-char (point-at-bol))
5329 (looking-at
5330 (cond
5331 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5332 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5333 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5334 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5336 (defun org-in-item-p ()
5337 "It the cursor inside a plain list item.
5338 Does not have to be the first line."
5339 (save-excursion
5340 (condition-case nil
5341 (progn
5342 (org-beginning-of-item)
5343 (org-at-item-p)
5345 (error nil))))
5347 (defun org-insert-item (&optional checkbox)
5348 "Insert a new item at the current level.
5349 Return t when things worked, nil when we are not in an item."
5350 (when (save-excursion
5351 (condition-case nil
5352 (progn
5353 (org-beginning-of-item)
5354 (org-at-item-p)
5355 (if (org-invisible-p) (error "Invisible item"))
5357 (error nil)))
5358 (let* ((bul (match-string 0))
5359 (descp (save-excursion (goto-char (match-beginning 0))
5360 (beginning-of-line 1)
5361 (save-match-data
5362 (looking-at "[ \t]*.*? ::"))))
5363 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5364 (match-end 0)))
5365 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5366 pos)
5367 (if descp (setq checkbox nil))
5368 (cond
5369 ((and (org-at-item-p) (<= (point) eow))
5370 ;; before the bullet
5371 (beginning-of-line 1)
5372 (open-line (if blank 2 1)))
5373 ((<= (point) eow)
5374 (beginning-of-line 1))
5376 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5377 (end-of-line 1)
5378 (delete-horizontal-space))
5379 (newline (if blank 2 1))))
5380 (insert bul
5381 (if checkbox "[ ]" "")
5382 (if descp (concat (if checkbox " " "")
5383 (read-string "Term: ") " :: ") ""))
5384 (just-one-space)
5385 (setq pos (point))
5386 (end-of-line 1)
5387 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5388 (org-maybe-renumber-ordered-list)
5389 (and checkbox (org-update-checkbox-count-maybe))
5392 ;;; Checkboxes
5394 (defun org-at-item-checkbox-p ()
5395 "Is point at a line starting a plain-list item with a checklet?"
5396 (and (org-at-item-p)
5397 (save-excursion
5398 (goto-char (match-end 0))
5399 (skip-chars-forward " \t")
5400 (looking-at "\\[[- X]\\]"))))
5402 (defun org-toggle-checkbox (&optional arg)
5403 "Toggle the checkbox in the current line."
5404 (interactive "P")
5405 (catch 'exit
5406 (let (beg end status (firstnew 'unknown))
5407 (cond
5408 ((org-region-active-p)
5409 (setq beg (region-beginning) end (region-end)))
5410 ((org-on-heading-p)
5411 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5412 ((org-at-item-checkbox-p)
5413 (let ((pos (point)))
5414 (replace-match
5415 (cond (arg "[-]")
5416 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5417 (t "[ ]"))
5418 t t)
5419 (goto-char pos))
5420 (throw 'exit t))
5421 (t (error "Not at a checkbox or heading, and no active region")))
5422 (save-excursion
5423 (goto-char beg)
5424 (while (< (point) end)
5425 (when (org-at-item-checkbox-p)
5426 (setq status (equal (match-string 0) "[X]"))
5427 (when (eq firstnew 'unknown)
5428 (setq firstnew (not status)))
5429 (replace-match
5430 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5431 (beginning-of-line 2)))))
5432 (org-update-checkbox-count-maybe))
5434 (defun org-update-checkbox-count-maybe ()
5435 "Update checkbox statistics unless turned off by user."
5436 (when org-provide-checkbox-statistics
5437 (org-update-checkbox-count)))
5439 (defun org-update-checkbox-count (&optional all)
5440 "Update the checkbox statistics in the current section.
5441 This will find all statistic cookies like [57%] and [6/12] and update them
5442 with the current numbers. With optional prefix argument ALL, do this for
5443 the whole buffer."
5444 (interactive "P")
5445 (save-excursion
5446 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5447 (beg (condition-case nil
5448 (progn (outline-back-to-heading) (point))
5449 (error (point-min))))
5450 (end (move-marker (make-marker)
5451 (progn (outline-next-heading) (point))))
5452 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5453 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5454 (re-find (concat re "\\|" re-box))
5455 beg-cookie end-cookie is-percent c-on c-off lim
5456 eline curr-ind next-ind continue-from startsearch
5457 (cstat 0)
5459 (when all
5460 (goto-char (point-min))
5461 (outline-next-heading)
5462 (setq beg (point) end (point-max)))
5463 (goto-char end)
5464 ;; find each statistic cookie
5465 (while (re-search-backward re-find beg t)
5466 (setq beg-cookie (match-beginning 1)
5467 end-cookie (match-end 1)
5468 cstat (+ cstat (if end-cookie 1 0))
5469 startsearch (point-at-eol)
5470 continue-from (point-at-bol)
5471 is-percent (match-beginning 2)
5472 lim (cond
5473 ((org-on-heading-p) (outline-next-heading) (point))
5474 ((org-at-item-p) (org-end-of-item) (point))
5475 (t nil))
5476 c-on 0
5477 c-off 0)
5478 (when lim
5479 ;; find first checkbox for this cookie and gather
5480 ;; statistics from all that are at this indentation level
5481 (goto-char startsearch)
5482 (if (re-search-forward re-box lim t)
5483 (progn
5484 (org-beginning-of-item)
5485 (setq curr-ind (org-get-indentation))
5486 (setq next-ind curr-ind)
5487 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5488 (save-excursion (end-of-line) (setq eline (point)))
5489 (if (re-search-forward re-box eline t)
5490 (if (member (match-string 2) '("[ ]" "[-]"))
5491 (setq c-off (1+ c-off))
5492 (setq c-on (1+ c-on))
5495 (org-end-of-item)
5496 (setq next-ind (org-get-indentation))
5498 (goto-char continue-from)
5499 ;; update cookie
5500 (when end-cookie
5501 (delete-region beg-cookie end-cookie)
5502 (goto-char beg-cookie)
5503 (insert
5504 (if is-percent
5505 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5506 (format "[%d/%d]" c-on (+ c-on c-off)))))
5507 ;; update items checkbox if it has one
5508 (when (org-at-item-p)
5509 (org-beginning-of-item)
5510 (when (and (> (+ c-on c-off) 0)
5511 (re-search-forward re-box (point-at-eol) t))
5512 (setq beg-cookie (match-beginning 2)
5513 end-cookie (match-end 2))
5514 (delete-region beg-cookie end-cookie)
5515 (goto-char beg-cookie)
5516 (cond ((= c-off 0) (insert "[X]"))
5517 ((= c-on 0) (insert "[ ]"))
5518 (t (insert "[-]")))
5520 (goto-char continue-from))
5521 (when (interactive-p)
5522 (message "Checkbox satistics updated %s (%d places)"
5523 (if all "in entire file" "in current outline entry") cstat)))))
5525 (defun org-get-checkbox-statistics-face ()
5526 "Select the face for checkbox statistics.
5527 The face will be `org-done' when all relevant boxes are checked. Otherwise
5528 it will be `org-todo'."
5529 (if (match-end 1)
5530 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5531 (if (and (> (match-end 2) (match-beginning 2))
5532 (equal (match-string 2) (match-string 3)))
5533 'org-done
5534 'org-todo)))
5536 (defun org-get-indentation (&optional line)
5537 "Get the indentation of the current line, interpreting tabs.
5538 When LINE is given, assume it represents a line and compute its indentation."
5539 (if line
5540 (if (string-match "^ *" (org-remove-tabs line))
5541 (match-end 0))
5542 (save-excursion
5543 (beginning-of-line 1)
5544 (skip-chars-forward " \t")
5545 (current-column))))
5547 (defun org-remove-tabs (s &optional width)
5548 "Replace tabulators in S with spaces.
5549 Assumes that s is a single line, starting in column 0."
5550 (setq width (or width tab-width))
5551 (while (string-match "\t" s)
5552 (setq s (replace-match
5553 (make-string
5554 (- (* width (/ (+ (match-beginning 0) width) width))
5555 (match-beginning 0)) ?\ )
5556 t t s)))
5559 (defun org-fix-indentation (line ind)
5560 "Fix indentation in LINE.
5561 IND is a cons cell with target and minimum indentation.
5562 If the current indenation in LINE is smaller than the minimum,
5563 leave it alone. If it is larger than ind, set it to the target."
5564 (let* ((l (org-remove-tabs line))
5565 (i (org-get-indentation l))
5566 (i1 (car ind)) (i2 (cdr ind)))
5567 (if (>= i i2) (setq l (substring line i2)))
5568 (if (> i1 0)
5569 (concat (make-string i1 ?\ ) l)
5570 l)))
5572 (defun org-beginning-of-item ()
5573 "Go to the beginning of the current hand-formatted item.
5574 If the cursor is not in an item, throw an error."
5575 (interactive)
5576 (let ((pos (point))
5577 (limit (save-excursion
5578 (condition-case nil
5579 (progn
5580 (org-back-to-heading)
5581 (beginning-of-line 2) (point))
5582 (error (point-min)))))
5583 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5584 ind ind1)
5585 (if (org-at-item-p)
5586 (beginning-of-line 1)
5587 (beginning-of-line 1)
5588 (skip-chars-forward " \t")
5589 (setq ind (current-column))
5590 (if (catch 'exit
5591 (while t
5592 (beginning-of-line 0)
5593 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5595 (if (looking-at "[ \t]*$")
5596 (setq ind1 ind-empty)
5597 (skip-chars-forward " \t")
5598 (setq ind1 (current-column)))
5599 (if (< ind1 ind)
5600 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5602 (goto-char pos)
5603 (error "Not in an item")))))
5605 (defun org-end-of-item ()
5606 "Go to the end of the current hand-formatted item.
5607 If the cursor is not in an item, throw an error."
5608 (interactive)
5609 (let* ((pos (point))
5610 ind1
5611 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5612 (limit (save-excursion (outline-next-heading) (point)))
5613 (ind (save-excursion
5614 (org-beginning-of-item)
5615 (skip-chars-forward " \t")
5616 (current-column)))
5617 (end (catch 'exit
5618 (while t
5619 (beginning-of-line 2)
5620 (if (eobp) (throw 'exit (point)))
5621 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5622 (if (looking-at "[ \t]*$")
5623 (setq ind1 ind-empty)
5624 (skip-chars-forward " \t")
5625 (setq ind1 (current-column)))
5626 (if (<= ind1 ind)
5627 (throw 'exit (point-at-bol)))))))
5628 (if end
5629 (goto-char end)
5630 (goto-char pos)
5631 (error "Not in an item"))))
5633 (defun org-next-item ()
5634 "Move to the beginning of the next item in the current plain list.
5635 Error if not at a plain list, or if this is the last item in the list."
5636 (interactive)
5637 (let (ind ind1 (pos (point)))
5638 (org-beginning-of-item)
5639 (setq ind (org-get-indentation))
5640 (org-end-of-item)
5641 (setq ind1 (org-get-indentation))
5642 (unless (and (org-at-item-p) (= ind ind1))
5643 (goto-char pos)
5644 (error "On last item"))))
5646 (defun org-previous-item ()
5647 "Move to the beginning of the previous item in the current plain list.
5648 Error if not at a plain list, or if this is the first item in the list."
5649 (interactive)
5650 (let (beg ind ind1 (pos (point)))
5651 (org-beginning-of-item)
5652 (setq beg (point))
5653 (setq ind (org-get-indentation))
5654 (goto-char beg)
5655 (catch 'exit
5656 (while t
5657 (beginning-of-line 0)
5658 (if (looking-at "[ \t]*$")
5660 (if (<= (setq ind1 (org-get-indentation)) ind)
5661 (throw 'exit t)))))
5662 (condition-case nil
5663 (if (or (not (org-at-item-p))
5664 (< ind1 (1- ind)))
5665 (error "")
5666 (org-beginning-of-item))
5667 (error (goto-char pos)
5668 (error "On first item")))))
5670 (defun org-first-list-item-p ()
5671 "Is this heading the item in a plain list?"
5672 (unless (org-at-item-p)
5673 (error "Not at a plain list item"))
5674 (org-beginning-of-item)
5675 (= (point) (save-excursion (org-beginning-of-item-list))))
5677 (defun org-move-item-down ()
5678 "Move the plain list item at point down, i.e. swap with following item.
5679 Subitems (items with larger indentation) are considered part of the item,
5680 so this really moves item trees."
5681 (interactive)
5682 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5683 (org-beginning-of-item)
5684 (setq beg0 (point))
5685 (save-excursion
5686 (setq ne-beg (org-back-over-empty-lines))
5687 (setq beg (point)))
5688 (goto-char beg0)
5689 (setq ind (org-get-indentation))
5690 (org-end-of-item)
5691 (setq end0 (point))
5692 (setq ind1 (org-get-indentation))
5693 (setq ne-end (org-back-over-empty-lines))
5694 (setq end (point))
5695 (goto-char beg0)
5696 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5697 ;; include less whitespace
5698 (save-excursion
5699 (goto-char beg)
5700 (forward-line (- ne-beg ne-end))
5701 (setq beg (point))))
5702 (goto-char end0)
5703 (if (and (org-at-item-p) (= ind ind1))
5704 (progn
5705 (org-end-of-item)
5706 (org-back-over-empty-lines)
5707 (setq txt (buffer-substring beg end))
5708 (save-excursion
5709 (delete-region beg end))
5710 (setq pos (point))
5711 (insert txt)
5712 (goto-char pos) (org-skip-whitespace)
5713 (org-maybe-renumber-ordered-list))
5714 (goto-char pos)
5715 (error "Cannot move this item further down"))))
5717 (defun org-move-item-up (arg)
5718 "Move the plain list item at point up, i.e. swap with previous item.
5719 Subitems (items with larger indentation) are considered part of the item,
5720 so this really moves item trees."
5721 (interactive "p")
5722 (let (beg beg0 end ind ind1 (pos (point)) txt
5723 ne-beg ne-ins ins-end)
5724 (org-beginning-of-item)
5725 (setq beg0 (point))
5726 (setq ind (org-get-indentation))
5727 (save-excursion
5728 (setq ne-beg (org-back-over-empty-lines))
5729 (setq beg (point)))
5730 (goto-char beg0)
5731 (org-end-of-item)
5732 (setq end (point))
5733 (goto-char beg0)
5734 (catch 'exit
5735 (while t
5736 (beginning-of-line 0)
5737 (if (looking-at "[ \t]*$")
5738 (if org-empty-line-terminates-plain-lists
5739 (progn
5740 (goto-char pos)
5741 (error "Cannot move this item further up"))
5742 nil)
5743 (if (<= (setq ind1 (org-get-indentation)) ind)
5744 (throw 'exit t)))))
5745 (condition-case nil
5746 (org-beginning-of-item)
5747 (error (goto-char beg)
5748 (error "Cannot move this item further up")))
5749 (setq ind1 (org-get-indentation))
5750 (if (and (org-at-item-p) (= ind ind1))
5751 (progn
5752 (setq ne-ins (org-back-over-empty-lines))
5753 (setq txt (buffer-substring beg end))
5754 (save-excursion
5755 (delete-region beg end))
5756 (setq pos (point))
5757 (insert txt)
5758 (setq ins-end (point))
5759 (goto-char pos) (org-skip-whitespace)
5761 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5762 ;; Move whitespace back to beginning
5763 (save-excursion
5764 (goto-char ins-end)
5765 (let ((kill-whole-line t))
5766 (kill-line (- ne-ins ne-beg)) (point)))
5767 (insert (make-string (- ne-ins ne-beg) ?\n)))
5769 (org-maybe-renumber-ordered-list))
5770 (goto-char pos)
5771 (error "Cannot move this item further up"))))
5773 (defun org-maybe-renumber-ordered-list ()
5774 "Renumber the ordered list at point if setup allows it.
5775 This tests the user option `org-auto-renumber-ordered-lists' before
5776 doing the renumbering."
5777 (interactive)
5778 (when (and org-auto-renumber-ordered-lists
5779 (org-at-item-p))
5780 (if (match-beginning 3)
5781 (org-renumber-ordered-list 1)
5782 (org-fix-bullet-type))))
5784 (defun org-maybe-renumber-ordered-list-safe ()
5785 (condition-case nil
5786 (save-excursion
5787 (org-maybe-renumber-ordered-list))
5788 (error nil)))
5790 (defun org-cycle-list-bullet (&optional which)
5791 "Cycle through the different itemize/enumerate bullets.
5792 This cycle the entire list level through the sequence:
5794 `-' -> `+' -> `*' -> `1.' -> `1)'
5796 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5797 0 meand `-', 1 means `+' etc."
5798 (interactive "P")
5799 (org-preserve-lc
5800 (org-beginning-of-item-list)
5801 (org-at-item-p)
5802 (beginning-of-line 1)
5803 (let ((current (match-string 0))
5804 (prevp (eq which 'previous))
5805 new)
5806 (setq new (cond
5807 ((and (numberp which)
5808 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5809 ((string-match "-" current) (if prevp "1)" "+"))
5810 ((string-match "\\+" current)
5811 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5812 ((string-match "\\*" current) (if prevp "+" "1."))
5813 ((string-match "\\." current) (if prevp "*" "1)"))
5814 ((string-match ")" current) (if prevp "1." "-"))
5815 (t (error "This should not happen"))))
5816 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5817 (org-fix-bullet-type)
5818 (org-maybe-renumber-ordered-list))))
5820 (defun org-get-string-indentation (s)
5821 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5822 (let ((n -1) (i 0) (w tab-width) c)
5823 (catch 'exit
5824 (while (< (setq n (1+ n)) (length s))
5825 (setq c (aref s n))
5826 (cond ((= c ?\ ) (setq i (1+ i)))
5827 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5828 (t (throw 'exit t)))))
5831 (defun org-renumber-ordered-list (arg)
5832 "Renumber an ordered plain list.
5833 Cursor needs to be in the first line of an item, the line that starts
5834 with something like \"1.\" or \"2)\"."
5835 (interactive "p")
5836 (unless (and (org-at-item-p)
5837 (match-beginning 3))
5838 (error "This is not an ordered list"))
5839 (let ((line (org-current-line))
5840 (col (current-column))
5841 (ind (org-get-string-indentation
5842 (buffer-substring (point-at-bol) (match-beginning 3))))
5843 ;; (term (substring (match-string 3) -1))
5844 ind1 (n (1- arg))
5845 fmt)
5846 ;; find where this list begins
5847 (org-beginning-of-item-list)
5848 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5849 (setq fmt (concat "%d" (match-string 1)))
5850 (beginning-of-line 0)
5851 ;; walk forward and replace these numbers
5852 (catch 'exit
5853 (while t
5854 (catch 'next
5855 (beginning-of-line 2)
5856 (if (eobp) (throw 'exit nil))
5857 (if (looking-at "[ \t]*$") (throw 'next nil))
5858 (skip-chars-forward " \t") (setq ind1 (current-column))
5859 (if (> ind1 ind) (throw 'next t))
5860 (if (< ind1 ind) (throw 'exit t))
5861 (if (not (org-at-item-p)) (throw 'exit nil))
5862 (delete-region (match-beginning 2) (match-end 2))
5863 (goto-char (match-beginning 2))
5864 (insert (format fmt (setq n (1+ n)))))))
5865 (goto-line line)
5866 (org-move-to-column col)))
5868 (defun org-fix-bullet-type ()
5869 "Make sure all items in this list have the same bullet as the firsst item."
5870 (interactive)
5871 (unless (org-at-item-p) (error "This is not a list"))
5872 (let ((line (org-current-line))
5873 (col (current-column))
5874 (ind (current-indentation))
5875 ind1 bullet)
5876 ;; find where this list begins
5877 (org-beginning-of-item-list)
5878 (beginning-of-line 1)
5879 ;; find out what the bullet type is
5880 (looking-at "[ \t]*\\(\\S-+\\)")
5881 (setq bullet (match-string 1))
5882 ;; walk forward and replace these numbers
5883 (beginning-of-line 0)
5884 (catch 'exit
5885 (while t
5886 (catch 'next
5887 (beginning-of-line 2)
5888 (if (eobp) (throw 'exit nil))
5889 (if (looking-at "[ \t]*$") (throw 'next nil))
5890 (skip-chars-forward " \t") (setq ind1 (current-column))
5891 (if (> ind1 ind) (throw 'next t))
5892 (if (< ind1 ind) (throw 'exit t))
5893 (if (not (org-at-item-p)) (throw 'exit nil))
5894 (skip-chars-forward " \t")
5895 (looking-at "\\S-+")
5896 (replace-match bullet))))
5897 (goto-line line)
5898 (org-move-to-column col)
5899 (if (string-match "[0-9]" bullet)
5900 (org-renumber-ordered-list 1))))
5902 (defun org-beginning-of-item-list ()
5903 "Go to the beginning of the current item list.
5904 I.e. to the first item in this list."
5905 (interactive)
5906 (org-beginning-of-item)
5907 (let ((pos (point-at-bol))
5908 (ind (org-get-indentation))
5909 ind1)
5910 ;; find where this list begins
5911 (catch 'exit
5912 (while t
5913 (catch 'next
5914 (beginning-of-line 0)
5915 (if (looking-at "[ \t]*$")
5916 (throw (if (bobp) 'exit 'next) t))
5917 (skip-chars-forward " \t") (setq ind1 (current-column))
5918 (if (or (< ind1 ind)
5919 (and (= ind1 ind)
5920 (not (org-at-item-p)))
5921 (bobp))
5922 (throw 'exit t)
5923 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5924 (goto-char pos)))
5927 (defun org-end-of-item-list ()
5928 "Go to the end of the current item list.
5929 I.e. to the text after the last item."
5930 (interactive)
5931 (org-beginning-of-item)
5932 (let ((pos (point-at-bol))
5933 (ind (org-get-indentation))
5934 ind1)
5935 ;; find where this list begins
5936 (catch 'exit
5937 (while t
5938 (catch 'next
5939 (beginning-of-line 2)
5940 (if (looking-at "[ \t]*$")
5941 (throw (if (eobp) 'exit 'next) t))
5942 (skip-chars-forward " \t") (setq ind1 (current-column))
5943 (if (or (< ind1 ind)
5944 (and (= ind1 ind)
5945 (not (org-at-item-p)))
5946 (eobp))
5947 (progn
5948 (setq pos (point-at-bol))
5949 (throw 'exit t))))))
5950 (goto-char pos)))
5953 (defvar org-last-indent-begin-marker (make-marker))
5954 (defvar org-last-indent-end-marker (make-marker))
5956 (defun org-outdent-item (arg)
5957 "Outdent a local list item."
5958 (interactive "p")
5959 (org-indent-item (- arg)))
5961 (defun org-indent-item (arg)
5962 "Indent a local list item."
5963 (interactive "p")
5964 (unless (org-at-item-p)
5965 (error "Not on an item"))
5966 (save-excursion
5967 (let (beg end ind ind1 tmp delta ind-down ind-up)
5968 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5969 (setq beg org-last-indent-begin-marker
5970 end org-last-indent-end-marker)
5971 (org-beginning-of-item)
5972 (setq beg (move-marker org-last-indent-begin-marker (point)))
5973 (org-end-of-item)
5974 (setq end (move-marker org-last-indent-end-marker (point))))
5975 (goto-char beg)
5976 (setq tmp (org-item-indent-positions)
5977 ind (car tmp)
5978 ind-down (nth 2 tmp)
5979 ind-up (nth 1 tmp)
5980 delta (if (> arg 0)
5981 (if ind-down (- ind-down ind) 2)
5982 (if ind-up (- ind-up ind) -2)))
5983 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5984 (while (< (point) end)
5985 (beginning-of-line 1)
5986 (skip-chars-forward " \t") (setq ind1 (current-column))
5987 (delete-region (point-at-bol) (point))
5988 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5989 (beginning-of-line 2))))
5990 (org-fix-bullet-type)
5991 (org-maybe-renumber-ordered-list-safe)
5992 (save-excursion
5993 (beginning-of-line 0)
5994 (condition-case nil (org-beginning-of-item) (error nil))
5995 (org-maybe-renumber-ordered-list-safe)))
5997 (defun org-item-indent-positions ()
5998 "Return indentation for plain list items.
5999 This returns a list with three values: The current indentation, the
6000 parent indentation and the indentation a child should habe.
6001 Assumes cursor in item line."
6002 (let* ((bolpos (point-at-bol))
6003 (ind (org-get-indentation))
6004 ind-down ind-up pos)
6005 (save-excursion
6006 (org-beginning-of-item-list)
6007 (skip-chars-backward "\n\r \t")
6008 (when (org-in-item-p)
6009 (org-beginning-of-item)
6010 (setq ind-up (org-get-indentation))))
6011 (setq pos (point))
6012 (save-excursion
6013 (cond
6014 ((and (condition-case nil (progn (org-previous-item) t)
6015 (error nil))
6016 (or (forward-char 1) t)
6017 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6018 (setq ind-down (org-get-indentation)))
6019 ((and (goto-char pos)
6020 (org-at-item-p))
6021 (goto-char (match-end 0))
6022 (skip-chars-forward " \t")
6023 (setq ind-down (current-column)))))
6024 (list ind ind-up ind-down)))
6026 ;;; The orgstruct minor mode
6028 ;; Define a minor mode which can be used in other modes in order to
6029 ;; integrate the org-mode structure editing commands.
6031 ;; This is really a hack, because the org-mode structure commands use
6032 ;; keys which normally belong to the major mode. Here is how it
6033 ;; works: The minor mode defines all the keys necessary to operate the
6034 ;; structure commands, but wraps the commands into a function which
6035 ;; tests if the cursor is currently at a headline or a plain list
6036 ;; item. If that is the case, the structure command is used,
6037 ;; temporarily setting many Org-mode variables like regular
6038 ;; expressions for filling etc. However, when any of those keys is
6039 ;; used at a different location, function uses `key-binding' to look
6040 ;; up if the key has an associated command in another currently active
6041 ;; keymap (minor modes, major mode, global), and executes that
6042 ;; command. There might be problems if any of the keys is otherwise
6043 ;; used as a prefix key.
6045 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6046 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6047 ;; addresses this by checking explicitly for both bindings.
6049 (defvar orgstruct-mode-map (make-sparse-keymap)
6050 "Keymap for the minor `orgstruct-mode'.")
6052 (defvar org-local-vars nil
6053 "List of local variables, for use by `orgstruct-mode'")
6055 ;;;###autoload
6056 (define-minor-mode orgstruct-mode
6057 "Toggle the minor more `orgstruct-mode'.
6058 This mode is for using Org-mode structure commands in other modes.
6059 The following key behave as if Org-mode was active, if the cursor
6060 is on a headline, or on a plain list item (both in the definition
6061 of Org-mode).
6063 M-up Move entry/item up
6064 M-down Move entry/item down
6065 M-left Promote
6066 M-right Demote
6067 M-S-up Move entry/item up
6068 M-S-down Move entry/item down
6069 M-S-left Promote subtree
6070 M-S-right Demote subtree
6071 M-q Fill paragraph and items like in Org-mode
6072 C-c ^ Sort entries
6073 C-c - Cycle list bullet
6074 TAB Cycle item visibility
6075 M-RET Insert new heading/item
6076 S-M-RET Insert new TODO heading / Chekbox item
6077 C-c C-c Set tags / toggle checkbox"
6078 nil " OrgStruct" nil
6079 (org-load-modules-maybe)
6080 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6082 ;;;###autoload
6083 (defun turn-on-orgstruct ()
6084 "Unconditionally turn on `orgstruct-mode'."
6085 (orgstruct-mode 1))
6087 ;;;###autoload
6088 (defun turn-on-orgstruct++ ()
6089 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6090 In addition to setting orgstruct-mode, this also exports all indentation and
6091 autofilling variables from org-mode into the buffer. Note that turning
6092 off orgstruct-mode will *not* remove these additional settings."
6093 (orgstruct-mode 1)
6094 (let (var val)
6095 (mapc
6096 (lambda (x)
6097 (when (string-match
6098 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6099 (symbol-name (car x)))
6100 (setq var (car x) val (nth 1 x))
6101 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6102 org-local-vars)))
6104 (defun orgstruct-error ()
6105 "Error when there is no default binding for a structure key."
6106 (interactive)
6107 (error "This key has no function outside structure elements"))
6109 (defun orgstruct-setup ()
6110 "Setup orgstruct keymaps."
6111 (let ((nfunc 0)
6112 (bindings
6113 (list
6114 '([(meta up)] org-metaup)
6115 '([(meta down)] org-metadown)
6116 '([(meta left)] org-metaleft)
6117 '([(meta right)] org-metaright)
6118 '([(meta shift up)] org-shiftmetaup)
6119 '([(meta shift down)] org-shiftmetadown)
6120 '([(meta shift left)] org-shiftmetaleft)
6121 '([(meta shift right)] org-shiftmetaright)
6122 '([(shift up)] org-shiftup)
6123 '([(shift down)] org-shiftdown)
6124 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6125 '("\M-q" fill-paragraph)
6126 '("\C-c^" org-sort)
6127 '("\C-c-" org-cycle-list-bullet)))
6128 elt key fun cmd)
6129 (while (setq elt (pop bindings))
6130 (setq nfunc (1+ nfunc))
6131 (setq key (org-key (car elt))
6132 fun (nth 1 elt)
6133 cmd (orgstruct-make-binding fun nfunc key))
6134 (org-defkey orgstruct-mode-map key cmd))
6136 ;; Special treatment needed for TAB and RET
6137 (org-defkey orgstruct-mode-map [(tab)]
6138 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6139 (org-defkey orgstruct-mode-map "\C-i"
6140 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6142 (org-defkey orgstruct-mode-map "\M-\C-m"
6143 (orgstruct-make-binding 'org-insert-heading 105
6144 "\M-\C-m" [(meta return)]))
6145 (org-defkey orgstruct-mode-map [(meta return)]
6146 (orgstruct-make-binding 'org-insert-heading 106
6147 [(meta return)] "\M-\C-m"))
6149 (org-defkey orgstruct-mode-map [(shift meta return)]
6150 (orgstruct-make-binding 'org-insert-todo-heading 107
6151 [(meta return)] "\M-\C-m"))
6153 (unless org-local-vars
6154 (setq org-local-vars (org-get-local-variables)))
6158 (defun orgstruct-make-binding (fun n &rest keys)
6159 "Create a function for binding in the structure minor mode.
6160 FUN is the command to call inside a table. N is used to create a unique
6161 command name. KEYS are keys that should be checked in for a command
6162 to execute outside of tables."
6163 (eval
6164 (list 'defun
6165 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6166 '(arg)
6167 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6168 "Outside of structure, run the binding of `"
6169 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6170 "'.")
6171 '(interactive "p")
6172 (list 'if
6173 '(org-context-p 'headline 'item)
6174 (list 'org-run-like-in-org-mode (list 'quote fun))
6175 (list 'let '(orgstruct-mode)
6176 (list 'call-interactively
6177 (append '(or)
6178 (mapcar (lambda (k)
6179 (list 'key-binding k))
6180 keys)
6181 '('orgstruct-error))))))))
6183 (defun org-context-p (&rest contexts)
6184 "Check if local context is and of CONTEXTS.
6185 Possible values in the list of contexts are `table', `headline', and `item'."
6186 (let ((pos (point)))
6187 (goto-char (point-at-bol))
6188 (prog1 (or (and (memq 'table contexts)
6189 (looking-at "[ \t]*|"))
6190 (and (memq 'headline contexts)
6191 (looking-at "\\*+"))
6192 (and (memq 'item contexts)
6193 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6194 (goto-char pos))))
6196 (defun org-get-local-variables ()
6197 "Return a list of all local variables in an org-mode buffer."
6198 (let (varlist)
6199 (with-current-buffer (get-buffer-create "*Org tmp*")
6200 (erase-buffer)
6201 (org-mode)
6202 (setq varlist (buffer-local-variables)))
6203 (kill-buffer "*Org tmp*")
6204 (delq nil
6205 (mapcar
6206 (lambda (x)
6207 (setq x
6208 (if (symbolp x)
6209 (list x)
6210 (list (car x) (list 'quote (cdr x)))))
6211 (if (string-match
6212 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6213 (symbol-name (car x)))
6214 x nil))
6215 varlist))))
6217 ;;;###autoload
6218 (defun org-run-like-in-org-mode (cmd)
6219 (org-load-modules-maybe)
6220 (unless org-local-vars
6221 (setq org-local-vars (org-get-local-variables)))
6222 (eval (list 'let org-local-vars
6223 (list 'call-interactively (list 'quote cmd)))))
6225 ;;;; Archiving
6227 (defun org-get-category (&optional pos)
6228 "Get the category applying to position POS."
6229 (get-text-property (or pos (point)) 'org-category))
6231 (defun org-refresh-category-properties ()
6232 "Refresh category text properties in the buffer."
6233 (let ((def-cat (cond
6234 ((null org-category)
6235 (if buffer-file-name
6236 (file-name-sans-extension
6237 (file-name-nondirectory buffer-file-name))
6238 "???"))
6239 ((symbolp org-category) (symbol-name org-category))
6240 (t org-category)))
6241 beg end cat pos optionp)
6242 (org-unmodified
6243 (save-excursion
6244 (save-restriction
6245 (widen)
6246 (goto-char (point-min))
6247 (put-text-property (point) (point-max) 'org-category def-cat)
6248 (while (re-search-forward
6249 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6250 (setq pos (match-end 0)
6251 optionp (equal (char-after (match-beginning 0)) ?#)
6252 cat (org-trim (match-string 2)))
6253 (if optionp
6254 (setq beg (point-at-bol) end (point-max))
6255 (org-back-to-heading t)
6256 (setq beg (point) end (org-end-of-subtree t t)))
6257 (put-text-property beg end 'org-category cat)
6258 (goto-char pos)))))))
6261 ;;;; Link Stuff
6263 ;;; Link abbreviations
6265 (defun org-link-expand-abbrev (link)
6266 "Apply replacements as defined in `org-link-abbrev-alist."
6267 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6268 (let* ((key (match-string 1 link))
6269 (as (or (assoc key org-link-abbrev-alist-local)
6270 (assoc key org-link-abbrev-alist)))
6271 (tag (and (match-end 2) (match-string 3 link)))
6272 rpl)
6273 (if (not as)
6274 link
6275 (setq rpl (cdr as))
6276 (cond
6277 ((symbolp rpl) (funcall rpl tag))
6278 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6279 (t (concat rpl tag)))))
6280 link))
6282 ;;; Storing and inserting links
6284 (defvar org-insert-link-history nil
6285 "Minibuffer history for links inserted with `org-insert-link'.")
6287 (defvar org-stored-links nil
6288 "Contains the links stored with `org-store-link'.")
6290 (defvar org-store-link-plist nil
6291 "Plist with info about the most recently link created with `org-store-link'.")
6293 (defvar org-link-protocols nil
6294 "Link protocols added to Org-mode using `org-add-link-type'.")
6296 (defvar org-store-link-functions nil
6297 "List of functions that are called to create and store a link.
6298 Each function will be called in turn until one returns a non-nil
6299 value. Each function should check if it is responsible for creating
6300 this link (for example by looking at the major mode).
6301 If not, it must exit and return nil.
6302 If yes, it should return a non-nil value after a calling
6303 `org-store-link-props' with a list of properties and values.
6304 Special properties are:
6306 :type The link prefix. like \"http\". This must be given.
6307 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6308 This is obligatory as well.
6309 :description Optional default description for the second pair
6310 of brackets in an Org-mode link. The user can still change
6311 this when inserting this link into an Org-mode buffer.
6313 In addition to these, any additional properties can be specified
6314 and then used in remember templates.")
6316 (defun org-add-link-type (type &optional follow export)
6317 "Add TYPE to the list of `org-link-types'.
6318 Re-compute all regular expressions depending on `org-link-types'
6320 FOLLOW and EXPORT are two functions.
6322 FOLLOW should take the link path as the single argument and do whatever
6323 is necessary to follow the link, for example find a file or display
6324 a mail message.
6326 EXPORT should format the link path for export to one of the export formats.
6327 It should be a function accepting three arguments:
6329 path the path of the link, the text after the prefix (like \"http:\")
6330 desc the description of the link, if any, nil if there was no descripton
6331 format the export format, a symbol like `html' or `latex'.
6333 The function may use the FORMAT information to return different values
6334 depending on the format. The return value will be put literally into
6335 the exported file.
6336 Org-mode has a built-in default for exporting links. If you are happy with
6337 this default, there is no need to define an export function for the link
6338 type. For a simple example of an export function, see `org-bbdb.el'."
6339 (add-to-list 'org-link-types type t)
6340 (org-make-link-regexps)
6341 (if (assoc type org-link-protocols)
6342 (setcdr (assoc type org-link-protocols) (list follow export))
6343 (push (list type follow export) org-link-protocols)))
6346 ;;;###autoload
6347 (defun org-store-link (arg)
6348 "\\<org-mode-map>Store an org-link to the current location.
6349 This link is added to `org-stored-links' and can later be inserted
6350 into an org-buffer with \\[org-insert-link].
6352 For some link types, a prefix arg is interpreted:
6353 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6354 For file links, arg negates `org-context-in-file-links'."
6355 (interactive "P")
6356 (org-load-modules-maybe)
6357 (setq org-store-link-plist nil) ; reset
6358 (let (link cpltxt desc description search txt)
6359 (cond
6361 ((run-hook-with-args-until-success 'org-store-link-functions)
6362 (setq link (plist-get org-store-link-plist :link)
6363 desc (or (plist-get org-store-link-plist :description) link)))
6365 ((eq major-mode 'calendar-mode)
6366 (let ((cd (calendar-cursor-to-date)))
6367 (setq link
6368 (format-time-string
6369 (car org-time-stamp-formats)
6370 (apply 'encode-time
6371 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6372 nil nil nil))))
6373 (org-store-link-props :type "calendar" :date cd)))
6375 ((eq major-mode 'w3-mode)
6376 (setq cpltxt (url-view-url t)
6377 link (org-make-link cpltxt))
6378 (org-store-link-props :type "w3" :url (url-view-url t)))
6380 ((eq major-mode 'w3m-mode)
6381 (setq cpltxt (or w3m-current-title w3m-current-url)
6382 link (org-make-link w3m-current-url))
6383 (org-store-link-props :type "w3m" :url (url-view-url t)))
6385 ((setq search (run-hook-with-args-until-success
6386 'org-create-file-search-functions))
6387 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6388 "::" search))
6389 (setq cpltxt (or description link)))
6391 ((eq major-mode 'image-mode)
6392 (setq cpltxt (concat "file:"
6393 (abbreviate-file-name buffer-file-name))
6394 link (org-make-link cpltxt))
6395 (org-store-link-props :type "image" :file buffer-file-name))
6397 ((eq major-mode 'dired-mode)
6398 ;; link to the file in the current line
6399 (setq cpltxt (concat "file:"
6400 (abbreviate-file-name
6401 (expand-file-name
6402 (dired-get-filename nil t))))
6403 link (org-make-link cpltxt)))
6405 ((and buffer-file-name (org-mode-p))
6406 ;; Just link to current headline
6407 (setq cpltxt (concat "file:"
6408 (abbreviate-file-name buffer-file-name)))
6409 ;; Add a context search string
6410 (when (org-xor org-context-in-file-links arg)
6411 ;; Check if we are on a target
6412 (if (org-in-regexp "<<\\(.*?\\)>>")
6413 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6414 (setq txt (cond
6415 ((org-on-heading-p) nil)
6416 ((org-region-active-p)
6417 (buffer-substring (region-beginning) (region-end)))
6418 (t nil)))
6419 (when (or (null txt) (string-match "\\S-" txt))
6420 (setq cpltxt
6421 (concat cpltxt "::"
6422 (condition-case nil
6423 (org-make-org-heading-search-string txt)
6424 (error "")))
6425 desc "NONE"))))
6426 (if (string-match "::\\'" cpltxt)
6427 (setq cpltxt (substring cpltxt 0 -2)))
6428 (setq link (org-make-link cpltxt)))
6430 ((buffer-file-name (buffer-base-buffer))
6431 ;; Just link to this file here.
6432 (setq cpltxt (concat "file:"
6433 (abbreviate-file-name
6434 (buffer-file-name (buffer-base-buffer)))))
6435 ;; Add a context string
6436 (when (org-xor org-context-in-file-links arg)
6437 (setq txt (if (org-region-active-p)
6438 (buffer-substring (region-beginning) (region-end))
6439 (buffer-substring (point-at-bol) (point-at-eol))))
6440 ;; Only use search option if there is some text.
6441 (when (string-match "\\S-" txt)
6442 (setq cpltxt
6443 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6444 desc "NONE")))
6445 (setq link (org-make-link cpltxt)))
6447 ((interactive-p)
6448 (error "Cannot link to a buffer which is not visiting a file"))
6450 (t (setq link nil)))
6452 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6453 (setq link (or link cpltxt)
6454 desc (or desc cpltxt))
6455 (if (equal desc "NONE") (setq desc nil))
6457 (if (and (interactive-p) link)
6458 (progn
6459 (setq org-stored-links
6460 (cons (list link desc) org-stored-links))
6461 (message "Stored: %s" (or desc link)))
6462 (and link (org-make-link-string link desc)))))
6464 (defun org-store-link-props (&rest plist)
6465 "Store link properties, extract names and addresses."
6466 (let (x adr)
6467 (when (setq x (plist-get plist :from))
6468 (setq adr (mail-extract-address-components x))
6469 (plist-put plist :fromname (car adr))
6470 (plist-put plist :fromaddress (nth 1 adr)))
6471 (when (setq x (plist-get plist :to))
6472 (setq adr (mail-extract-address-components x))
6473 (plist-put plist :toname (car adr))
6474 (plist-put plist :toaddress (nth 1 adr))))
6475 (let ((from (plist-get plist :from))
6476 (to (plist-get plist :to)))
6477 (when (and from to org-from-is-user-regexp)
6478 (plist-put plist :fromto
6479 (if (string-match org-from-is-user-regexp from)
6480 (concat "to %t")
6481 (concat "from %f")))))
6482 (setq org-store-link-plist plist))
6484 (defun org-add-link-props (&rest plist)
6485 "Add these properties to the link property list."
6486 (let (key value)
6487 (while plist
6488 (setq key (pop plist) value (pop plist))
6489 (setq org-store-link-plist
6490 (plist-put org-store-link-plist key value)))))
6492 (defun org-email-link-description (&optional fmt)
6493 "Return the description part of an email link.
6494 This takes information from `org-store-link-plist' and formats it
6495 according to FMT (default from `org-email-link-description-format')."
6496 (setq fmt (or fmt org-email-link-description-format))
6497 (let* ((p org-store-link-plist)
6498 (to (plist-get p :toaddress))
6499 (from (plist-get p :fromaddress))
6500 (table
6501 (list
6502 (cons "%c" (plist-get p :fromto))
6503 (cons "%F" (plist-get p :from))
6504 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6505 (cons "%T" (plist-get p :to))
6506 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6507 (cons "%s" (plist-get p :subject))
6508 (cons "%m" (plist-get p :message-id)))))
6509 (when (string-match "%c" fmt)
6510 ;; Check if the user wrote this message
6511 (if (and org-from-is-user-regexp from to
6512 (save-match-data (string-match org-from-is-user-regexp from)))
6513 (setq fmt (replace-match "to %t" t t fmt))
6514 (setq fmt (replace-match "from %f" t t fmt))))
6515 (org-replace-escapes fmt table)))
6517 (defun org-make-org-heading-search-string (&optional string heading)
6518 "Make search string for STRING or current headline."
6519 (interactive)
6520 (let ((s (or string (org-get-heading))))
6521 (unless (and string (not heading))
6522 ;; We are using a headline, clean up garbage in there.
6523 (if (string-match org-todo-regexp s)
6524 (setq s (replace-match "" t t s)))
6525 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6526 (setq s (replace-match "" t t s)))
6527 (setq s (org-trim s))
6528 (if (string-match (concat "^\\(" org-quote-string "\\|"
6529 org-comment-string "\\)") s)
6530 (setq s (replace-match "" t t s)))
6531 (while (string-match org-ts-regexp s)
6532 (setq s (replace-match "" t t s))))
6533 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6534 (setq s (replace-match " " t t s)))
6535 (or string (setq s (concat "*" s))) ; Add * for headlines
6536 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6538 (defun org-make-link (&rest strings)
6539 "Concatenate STRINGS."
6540 (apply 'concat strings))
6542 (defun org-make-link-string (link &optional description)
6543 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6544 (unless (string-match "\\S-" link)
6545 (error "Empty link"))
6546 (when (stringp description)
6547 ;; Remove brackets from the description, they are fatal.
6548 (while (string-match "\\[" description)
6549 (setq description (replace-match "{" t t description)))
6550 (while (string-match "\\]" description)
6551 (setq description (replace-match "}" t t description))))
6552 (when (equal (org-link-escape link) description)
6553 ;; No description needed, it is identical
6554 (setq description nil))
6555 (when (and (not description)
6556 (not (equal link (org-link-escape link))))
6557 (setq description link))
6558 (concat "[[" (org-link-escape link) "]"
6559 (if description (concat "[" description "]") "")
6560 "]"))
6562 (defconst org-link-escape-chars
6563 '((?\ . "%20")
6564 (?\[ . "%5B")
6565 (?\] . "%5D")
6566 (?\340 . "%E0") ; `a
6567 (?\342 . "%E2") ; ^a
6568 (?\347 . "%E7") ; ,c
6569 (?\350 . "%E8") ; `e
6570 (?\351 . "%E9") ; 'e
6571 (?\352 . "%EA") ; ^e
6572 (?\356 . "%EE") ; ^i
6573 (?\364 . "%F4") ; ^o
6574 (?\371 . "%F9") ; `u
6575 (?\373 . "%FB") ; ^u
6576 (?\; . "%3B")
6577 (?? . "%3F")
6578 (?= . "%3D")
6579 (?+ . "%2B")
6581 "Association list of escapes for some characters problematic in links.
6582 This is the list that is used for internal purposes.")
6584 (defconst org-link-escape-chars-browser
6585 '((?\ . "%20")) ; 32 for the SPC char
6586 "Association list of escapes for some characters problematic in links.
6587 This is the list that is used before handing over to the browser.")
6589 (defun org-link-escape (text &optional table)
6590 "Escape charaters in TEXT that are problematic for links."
6591 (setq table (or table org-link-escape-chars))
6592 (when text
6593 (let ((re (mapconcat (lambda (x) (regexp-quote
6594 (char-to-string (car x))))
6595 table "\\|")))
6596 (while (string-match re text)
6597 (setq text
6598 (replace-match
6599 (cdr (assoc (string-to-char (match-string 0 text))
6600 table))
6601 t t text)))
6602 text)))
6604 (defun org-link-unescape (text &optional table)
6605 "Reverse the action of `org-link-escape'."
6606 (setq table (or table org-link-escape-chars))
6607 (when text
6608 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6609 table "\\|")))
6610 (while (string-match re text)
6611 (setq text
6612 (replace-match
6613 (char-to-string (car (rassoc (match-string 0 text) table)))
6614 t t text)))
6615 text)))
6617 (defun org-xor (a b)
6618 "Exclusive or."
6619 (if a (not b) b))
6621 (defun org-get-header (header)
6622 "Find a header field in the current buffer."
6623 (save-excursion
6624 (goto-char (point-min))
6625 (let ((case-fold-search t) s)
6626 (cond
6627 ((eq header 'from)
6628 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6629 (setq s (match-string 1)))
6630 (while (string-match "\"" s)
6631 (setq s (replace-match "" t t s)))
6632 (if (string-match "[<(].*" s)
6633 (setq s (replace-match "" t t s))))
6634 ((eq header 'message-id)
6635 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6636 (setq s (match-string 1))))
6637 ((eq header 'subject)
6638 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6639 (setq s (match-string 1)))))
6640 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6641 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6642 s)))
6645 (defun org-fixup-message-id-for-http (s)
6646 "Replace special characters in a message id, so it can be used in an http query."
6647 (while (string-match "<" s)
6648 (setq s (replace-match "%3C" t t s)))
6649 (while (string-match ">" s)
6650 (setq s (replace-match "%3E" t t s)))
6651 (while (string-match "@" s)
6652 (setq s (replace-match "%40" t t s)))
6655 ;;;###autoload
6656 (defun org-insert-link-global ()
6657 "Insert a link like Org-mode does.
6658 This command can be called in any mode to insert a link in Org-mode syntax."
6659 (interactive)
6660 (org-load-modules-maybe)
6661 (org-run-like-in-org-mode 'org-insert-link))
6663 (defun org-insert-link (&optional complete-file link-location)
6664 "Insert a link. At the prompt, enter the link.
6666 Completion can be used to select a link previously stored with
6667 `org-store-link'. When the empty string is entered (i.e. if you just
6668 press RET at the prompt), the link defaults to the most recently
6669 stored link. As SPC triggers completion in the minibuffer, you need to
6670 use M-SPC or C-q SPC to force the insertion of a space character.
6672 You will also be prompted for a description, and if one is given, it will
6673 be displayed in the buffer instead of the link.
6675 If there is already a link at point, this command will allow you to edit link
6676 and description parts.
6678 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6679 be selected using completion. The path to the file will be relative to the
6680 current directory if the file is in the current directory or a subdirectory.
6681 Otherwise, the link will be the absolute path as completed in the minibuffer
6682 \(i.e. normally ~/path/to/file).
6684 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6685 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6686 of `org-keep-stored-link-after-insertion'.
6688 If `org-make-link-description-function' is non-nil, this function will be
6689 called with the link target, and the result will be the default
6690 link description.
6692 If the LINK-LOCATION parameter is non-nil, this value will be
6693 used as the link location instead of reading one interactively."
6694 (interactive "P")
6695 (let* ((wcf (current-window-configuration))
6696 (region (if (org-region-active-p)
6697 (buffer-substring (region-beginning) (region-end))))
6698 (remove (and region (list (region-beginning) (region-end))))
6699 (desc region)
6700 tmphist ; byte-compile incorrectly complains about this
6701 (link link-location)
6702 entry file)
6703 (cond
6704 (link-location) ; specified by arg, just use it.
6705 ((org-in-regexp org-bracket-link-regexp 1)
6706 ;; We do have a link at point, and we are going to edit it.
6707 (setq remove (list (match-beginning 0) (match-end 0)))
6708 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6709 (setq link (read-string "Link: "
6710 (org-link-unescape
6711 (org-match-string-no-properties 1)))))
6712 ((or (org-in-regexp org-angle-link-re)
6713 (org-in-regexp org-plain-link-re))
6714 ;; Convert to bracket link
6715 (setq remove (list (match-beginning 0) (match-end 0))
6716 link (read-string "Link: "
6717 (org-remove-angle-brackets (match-string 0)))))
6718 ((equal complete-file '(4))
6719 ;; Completing read for file names.
6720 (setq file (read-file-name "File: "))
6721 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6722 (pwd1 (file-name-as-directory (abbreviate-file-name
6723 (expand-file-name ".")))))
6724 (cond
6725 ((equal complete-file '(16))
6726 (setq link (org-make-link
6727 "file:"
6728 (abbreviate-file-name (expand-file-name file)))))
6729 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6730 (setq link (org-make-link "file:" (match-string 1 file))))
6731 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6732 (expand-file-name file))
6733 (setq link (org-make-link
6734 "file:" (match-string 1 (expand-file-name file)))))
6735 (t (setq link (org-make-link "file:" file))))))
6737 ;; Read link, with completion for stored links.
6738 (with-output-to-temp-buffer "*Org Links*"
6739 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6740 (when org-stored-links
6741 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6742 (princ (mapconcat
6743 (lambda (x)
6744 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6745 (reverse org-stored-links) "\n"))))
6746 (let ((cw (selected-window)))
6747 (select-window (get-buffer-window "*Org Links*"))
6748 (shrink-window-if-larger-than-buffer)
6749 (setq truncate-lines t)
6750 (select-window cw))
6751 ;; Fake a link history, containing the stored links.
6752 (setq tmphist (append (mapcar 'car org-stored-links)
6753 org-insert-link-history))
6754 (unwind-protect
6755 (setq link (org-completing-read
6756 "Link: "
6757 (append
6758 (mapcar (lambda (x) (list (concat (car x) ":")))
6759 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6760 (mapcar (lambda (x) (list (concat x ":")))
6761 org-link-types))
6762 nil nil nil
6763 'tmphist
6764 (or (car (car org-stored-links)))))
6765 (set-window-configuration wcf)
6766 (kill-buffer "*Org Links*"))
6767 (setq entry (assoc link org-stored-links))
6768 (or entry (push link org-insert-link-history))
6769 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6770 (not org-keep-stored-link-after-insertion))
6771 (setq org-stored-links (delq (assoc link org-stored-links)
6772 org-stored-links)))
6773 (setq desc (or desc (nth 1 entry)))))
6775 (if (string-match org-plain-link-re link)
6776 ;; URL-like link, normalize the use of angular brackets.
6777 (setq link (org-make-link (org-remove-angle-brackets link))))
6779 ;; Check if we are linking to the current file with a search option
6780 ;; If yes, simplify the link by using only the search option.
6781 (when (and buffer-file-name
6782 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6783 (let* ((path (match-string 1 link))
6784 (case-fold-search nil)
6785 (search (match-string 2 link)))
6786 (save-match-data
6787 (if (equal (file-truename buffer-file-name) (file-truename path))
6788 ;; We are linking to this same file, with a search option
6789 (setq link search)))))
6791 ;; Check if we can/should use a relative path. If yes, simplify the link
6792 (when (string-match "\\<file:\\(.*\\)" link)
6793 (let* ((path (match-string 1 link))
6794 (origpath path)
6795 (case-fold-search nil))
6796 (cond
6797 ((eq org-link-file-path-type 'absolute)
6798 (setq path (abbreviate-file-name (expand-file-name path))))
6799 ((eq org-link-file-path-type 'noabbrev)
6800 (setq path (expand-file-name path)))
6801 ((eq org-link-file-path-type 'relative)
6802 (setq path (file-relative-name path)))
6804 (save-match-data
6805 (if (string-match (concat "^" (regexp-quote
6806 (file-name-as-directory
6807 (expand-file-name "."))))
6808 (expand-file-name path))
6809 ;; We are linking a file with relative path name.
6810 (setq path (substring (expand-file-name path)
6811 (match-end 0)))))))
6812 (setq link (concat "file:" path))
6813 (if (equal desc origpath)
6814 (setq desc path))))
6816 (if org-make-link-description-function
6817 (setq desc (funcall org-make-link-description-function link desc)))
6819 (setq desc (read-string "Description: " desc))
6820 (unless (string-match "\\S-" desc) (setq desc nil))
6821 (if remove (apply 'delete-region remove))
6822 (insert (org-make-link-string link desc))))
6824 (defun org-completing-read (&rest args)
6825 (let ((minibuffer-local-completion-map
6826 (copy-keymap minibuffer-local-completion-map)))
6827 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6828 (apply 'completing-read args)))
6830 ;;; Opening/following a link
6832 (defvar org-link-search-failed nil)
6834 (defun org-next-link ()
6835 "Move forward to the next link.
6836 If the link is in hidden text, expose it."
6837 (interactive)
6838 (when (and org-link-search-failed (eq this-command last-command))
6839 (goto-char (point-min))
6840 (message "Link search wrapped back to beginning of buffer"))
6841 (setq org-link-search-failed nil)
6842 (let* ((pos (point))
6843 (ct (org-context))
6844 (a (assoc :link ct)))
6845 (if a (goto-char (nth 2 a)))
6846 (if (re-search-forward org-any-link-re nil t)
6847 (progn
6848 (goto-char (match-beginning 0))
6849 (if (org-invisible-p) (org-show-context)))
6850 (goto-char pos)
6851 (setq org-link-search-failed t)
6852 (error "No further link found"))))
6854 (defun org-previous-link ()
6855 "Move backward to the previous link.
6856 If the link is in hidden text, expose it."
6857 (interactive)
6858 (when (and org-link-search-failed (eq this-command last-command))
6859 (goto-char (point-max))
6860 (message "Link search wrapped back to end of buffer"))
6861 (setq org-link-search-failed nil)
6862 (let* ((pos (point))
6863 (ct (org-context))
6864 (a (assoc :link ct)))
6865 (if a (goto-char (nth 1 a)))
6866 (if (re-search-backward org-any-link-re nil t)
6867 (progn
6868 (goto-char (match-beginning 0))
6869 (if (org-invisible-p) (org-show-context)))
6870 (goto-char pos)
6871 (setq org-link-search-failed t)
6872 (error "No further link found"))))
6874 (defun org-find-file-at-mouse (ev)
6875 "Open file link or URL at mouse."
6876 (interactive "e")
6877 (mouse-set-point ev)
6878 (org-open-at-point 'in-emacs))
6880 (defun org-open-at-mouse (ev)
6881 "Open file link or URL at mouse."
6882 (interactive "e")
6883 (mouse-set-point ev)
6884 (org-open-at-point))
6886 (defvar org-window-config-before-follow-link nil
6887 "The window configuration before following a link.
6888 This is saved in case the need arises to restore it.")
6890 (defvar org-open-link-marker (make-marker)
6891 "Marker pointing to the location where `org-open-at-point; was called.")
6893 ;;;###autoload
6894 (defun org-open-at-point-global ()
6895 "Follow a link like Org-mode does.
6896 This command can be called in any mode to follow a link that has
6897 Org-mode syntax."
6898 (interactive)
6899 (org-run-like-in-org-mode 'org-open-at-point))
6901 ;;;###autoload
6902 (defun org-open-link-from-string (s &optional arg)
6903 "Open a link in the string S, as if it was in Org-mode."
6904 (interactive "sLink: \nP")
6905 (with-temp-buffer
6906 (let ((org-inhibit-startup t))
6907 (org-mode)
6908 (insert s)
6909 (goto-char (point-min))
6910 (org-open-at-point arg))))
6912 (defun org-open-at-point (&optional in-emacs)
6913 "Open link at or after point.
6914 If there is no link at point, this function will search forward up to
6915 the end of the current subtree.
6916 Normally, files will be opened by an appropriate application. If the
6917 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6918 (interactive "P")
6919 (org-load-modules-maybe)
6920 (move-marker org-open-link-marker (point))
6921 (setq org-window-config-before-follow-link (current-window-configuration))
6922 (org-remove-occur-highlights nil nil t)
6923 (if (org-at-timestamp-p t)
6924 (org-follow-timestamp-link)
6925 (let (type path link line search (pos (point)))
6926 (catch 'match
6927 (save-excursion
6928 (skip-chars-forward "^]\n\r")
6929 (when (org-in-regexp org-bracket-link-regexp)
6930 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6931 (while (string-match " *\n *" link)
6932 (setq link (replace-match " " t t link)))
6933 (setq link (org-link-expand-abbrev link))
6934 (if (string-match org-link-re-with-space2 link)
6935 (setq type (match-string 1 link) path (match-string 2 link))
6936 (setq type "thisfile" path link))
6937 (throw 'match t)))
6939 (when (get-text-property (point) 'org-linked-text)
6940 (setq type "thisfile"
6941 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6942 (1+ (point)) (point))
6943 path (buffer-substring
6944 (previous-single-property-change pos 'org-linked-text)
6945 (next-single-property-change pos 'org-linked-text)))
6946 (throw 'match t))
6948 (save-excursion
6949 (when (or (org-in-regexp org-angle-link-re)
6950 (org-in-regexp org-plain-link-re))
6951 (setq type (match-string 1) path (match-string 2))
6952 (throw 'match t)))
6953 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6954 (setq type "tree-match"
6955 path (match-string 1))
6956 (throw 'match t))
6957 (save-excursion
6958 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6959 (setq type "tags"
6960 path (match-string 1))
6961 (while (string-match ":" path)
6962 (setq path (replace-match "+" t t path)))
6963 (throw 'match t))))
6964 (unless path
6965 (error "No link found"))
6966 ;; Remove any trailing spaces in path
6967 (if (string-match " +\\'" path)
6968 (setq path (replace-match "" t t path)))
6970 (cond
6972 ((assoc type org-link-protocols)
6973 (funcall (nth 1 (assoc type org-link-protocols)) path))
6975 ((equal type "mailto")
6976 (let ((cmd (car org-link-mailto-program))
6977 (args (cdr org-link-mailto-program)) args1
6978 (address path) (subject "") a)
6979 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6980 (setq address (match-string 1 path)
6981 subject (org-link-escape (match-string 2 path))))
6982 (while args
6983 (cond
6984 ((not (stringp (car args))) (push (pop args) args1))
6985 (t (setq a (pop args))
6986 (if (string-match "%a" a)
6987 (setq a (replace-match address t t a)))
6988 (if (string-match "%s" a)
6989 (setq a (replace-match subject t t a)))
6990 (push a args1))))
6991 (apply cmd (nreverse args1))))
6993 ((member type '("http" "https" "ftp" "news"))
6994 (browse-url (concat type ":" (org-link-escape
6995 path org-link-escape-chars-browser))))
6997 ((member type '("message"))
6998 (browse-url (concat type ":" path)))
7000 ((string= type "tags")
7001 (org-tags-view in-emacs path))
7002 ((string= type "thisfile")
7003 (if in-emacs
7004 (switch-to-buffer-other-window
7005 (org-get-buffer-for-internal-link (current-buffer)))
7006 (org-mark-ring-push))
7007 (let ((cmd `(org-link-search
7008 ,path
7009 ,(cond ((equal in-emacs '(4)) 'occur)
7010 ((equal in-emacs '(16)) 'org-occur)
7011 (t nil))
7012 ,pos)))
7013 (condition-case nil (eval cmd)
7014 (error (progn (widen) (eval cmd))))))
7016 ((string= type "tree-match")
7017 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7019 ((string= type "file")
7020 (if (string-match "::\\([0-9]+\\)\\'" path)
7021 (setq line (string-to-number (match-string 1 path))
7022 path (substring path 0 (match-beginning 0)))
7023 (if (string-match "::\\(.+\\)\\'" path)
7024 (setq search (match-string 1 path)
7025 path (substring path 0 (match-beginning 0)))))
7026 (if (string-match "[*?{]" (file-name-nondirectory path))
7027 (dired path)
7028 (org-open-file path in-emacs line search)))
7030 ((string= type "news")
7031 (require 'org-gnus)
7032 (org-gnus-follow-link path))
7034 ((string= type "shell")
7035 (let ((cmd path))
7036 (if (or (not org-confirm-shell-link-function)
7037 (funcall org-confirm-shell-link-function
7038 (format "Execute \"%s\" in shell? "
7039 (org-add-props cmd nil
7040 'face 'org-warning))))
7041 (progn
7042 (message "Executing %s" cmd)
7043 (shell-command cmd))
7044 (error "Abort"))))
7046 ((string= type "elisp")
7047 (let ((cmd path))
7048 (if (or (not org-confirm-elisp-link-function)
7049 (funcall org-confirm-elisp-link-function
7050 (format "Execute \"%s\" as elisp? "
7051 (org-add-props cmd nil
7052 'face 'org-warning))))
7053 (message "%s => %s" cmd (eval (read cmd)))
7054 (error "Abort"))))
7057 (browse-url-at-point)))))
7058 (move-marker org-open-link-marker nil)
7059 (run-hook-with-args 'org-follow-link-hook))
7061 ;;;; Time estimates
7063 (defun org-get-effort (&optional pom)
7064 "Get the effort estimate for the current entry."
7065 (org-entry-get pom org-effort-property))
7067 ;;; File search
7069 (defvar org-create-file-search-functions nil
7070 "List of functions to construct the right search string for a file link.
7071 These functions are called in turn with point at the location to
7072 which the link should point.
7074 A function in the hook should first test if it would like to
7075 handle this file type, for example by checking the major-mode or
7076 the file extension. If it decides not to handle this file, it
7077 should just return nil to give other functions a chance. If it
7078 does handle the file, it must return the search string to be used
7079 when following the link. The search string will be part of the
7080 file link, given after a double colon, and `org-open-at-point'
7081 will automatically search for it. If special measures must be
7082 taken to make the search successful, another function should be
7083 added to the companion hook `org-execute-file-search-functions',
7084 which see.
7086 A function in this hook may also use `setq' to set the variable
7087 `description' to provide a suggestion for the descriptive text to
7088 be used for this link when it gets inserted into an Org-mode
7089 buffer with \\[org-insert-link].")
7091 (defvar org-execute-file-search-functions nil
7092 "List of functions to execute a file search triggered by a link.
7094 Functions added to this hook must accept a single argument, the
7095 search string that was part of the file link, the part after the
7096 double colon. The function must first check if it would like to
7097 handle this search, for example by checking the major-mode or the
7098 file extension. If it decides not to handle this search, it
7099 should just return nil to give other functions a chance. If it
7100 does handle the search, it must return a non-nil value to keep
7101 other functions from trying.
7103 Each function can access the current prefix argument through the
7104 variable `current-prefix-argument'. Note that a single prefix is
7105 used to force opening a link in Emacs, so it may be good to only
7106 use a numeric or double prefix to guide the search function.
7108 In case this is needed, a function in this hook can also restore
7109 the window configuration before `org-open-at-point' was called using:
7111 (set-window-configuration org-window-config-before-follow-link)")
7113 (defun org-link-search (s &optional type avoid-pos)
7114 "Search for a link search option.
7115 If S is surrounded by forward slashes, it is interpreted as a
7116 regular expression. In org-mode files, this will create an `org-occur'
7117 sparse tree. In ordinary files, `occur' will be used to list matches.
7118 If the current buffer is in `dired-mode', grep will be used to search
7119 in all files. If AVOID-POS is given, ignore matches near that position."
7120 (let ((case-fold-search t)
7121 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7122 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7123 (append '(("") (" ") ("\t") ("\n"))
7124 org-emphasis-alist)
7125 "\\|") "\\)"))
7126 (pos (point))
7127 (pre nil) (post nil)
7128 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7129 (cond
7130 ;; First check if there are any special
7131 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7132 ;; Now try the builtin stuff
7133 ((save-excursion
7134 (goto-char (point-min))
7135 (and
7136 (re-search-forward
7137 (concat "<<" (regexp-quote s0) ">>") nil t)
7138 (setq type 'dedicated
7139 pos (match-beginning 0))))
7140 ;; There is an exact target for this
7141 (goto-char pos))
7142 ((string-match "^/\\(.*\\)/$" s)
7143 ;; A regular expression
7144 (cond
7145 ((org-mode-p)
7146 (org-occur (match-string 1 s)))
7147 ;;((eq major-mode 'dired-mode)
7148 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7149 (t (org-do-occur (match-string 1 s)))))
7151 ;; A normal search strings
7152 (when (equal (string-to-char s) ?*)
7153 ;; Anchor on headlines, post may include tags.
7154 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7155 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7156 s (substring s 1)))
7157 (remove-text-properties
7158 0 (length s)
7159 '(face nil mouse-face nil keymap nil fontified nil) s)
7160 ;; Make a series of regular expressions to find a match
7161 (setq words (org-split-string s "[ \n\r\t]+")
7163 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7164 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7165 "\\)" markers)
7166 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7167 re2a (concat "[ \t\r\n]" re2a_)
7168 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7169 re4 (concat "[^a-zA-Z_]" re4_)
7171 re1 (concat pre re2 post)
7172 re3 (concat pre (if pre re4_ re4) post)
7173 re5 (concat pre ".*" re4)
7174 re2 (concat pre re2)
7175 re2a (concat pre (if pre re2a_ re2a))
7176 re4 (concat pre (if pre re4_ re4))
7177 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7178 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7179 re5 "\\)"
7181 (cond
7182 ((eq type 'org-occur) (org-occur reall))
7183 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7184 (t (goto-char (point-min))
7185 (setq type 'fuzzy)
7186 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7187 (org-search-not-self 1 re1 nil t)
7188 (org-search-not-self 1 re2 nil t)
7189 (org-search-not-self 1 re2a nil t)
7190 (org-search-not-self 1 re3 nil t)
7191 (org-search-not-self 1 re4 nil t)
7192 (org-search-not-self 1 re5 nil t)
7194 (goto-char (match-beginning 1))
7195 (goto-char pos)
7196 (error "No match")))))
7198 ;; Normal string-search
7199 (goto-char (point-min))
7200 (if (search-forward s nil t)
7201 (goto-char (match-beginning 0))
7202 (error "No match"))))
7203 (and (org-mode-p) (org-show-context 'link-search))
7204 type))
7206 (defun org-search-not-self (group &rest args)
7207 "Execute `re-search-forward', but only accept matches that do not
7208 enclose the position of `org-open-link-marker'."
7209 (let ((m org-open-link-marker))
7210 (catch 'exit
7211 (while (apply 're-search-forward args)
7212 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7213 (goto-char (match-end group))
7214 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7215 (> (match-beginning 0) (marker-position m))
7216 (< (match-end 0) (marker-position m)))
7217 (save-match-data
7218 (or (not (org-in-regexp
7219 org-bracket-link-analytic-regexp 1))
7220 (not (match-end 4)) ; no description
7221 (and (<= (match-beginning 4) (point))
7222 (>= (match-end 4) (point))))))
7223 (throw 'exit (point))))))))
7225 (defun org-get-buffer-for-internal-link (buffer)
7226 "Return a buffer to be used for displaying the link target of internal links."
7227 (cond
7228 ((not org-display-internal-link-with-indirect-buffer)
7229 buffer)
7230 ((string-match "(Clone)$" (buffer-name buffer))
7231 (message "Buffer is already a clone, not making another one")
7232 ;; we also do not modify visibility in this case
7233 buffer)
7234 (t ; make a new indirect buffer for displaying the link
7235 (let* ((bn (buffer-name buffer))
7236 (ibn (concat bn "(Clone)"))
7237 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7238 (with-current-buffer ib (org-overview))
7239 ib))))
7241 (defun org-do-occur (regexp &optional cleanup)
7242 "Call the Emacs command `occur'.
7243 If CLEANUP is non-nil, remove the printout of the regular expression
7244 in the *Occur* buffer. This is useful if the regex is long and not useful
7245 to read."
7246 (occur regexp)
7247 (when cleanup
7248 (let ((cwin (selected-window)) win beg end)
7249 (when (setq win (get-buffer-window "*Occur*"))
7250 (select-window win))
7251 (goto-char (point-min))
7252 (when (re-search-forward "match[a-z]+" nil t)
7253 (setq beg (match-end 0))
7254 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7255 (setq end (1- (match-beginning 0)))))
7256 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7257 (goto-char (point-min))
7258 (select-window cwin))))
7260 ;;; The mark ring for links jumps
7262 (defvar org-mark-ring nil
7263 "Mark ring for positions before jumps in Org-mode.")
7264 (defvar org-mark-ring-last-goto nil
7265 "Last position in the mark ring used to go back.")
7266 ;; Fill and close the ring
7267 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7268 (loop for i from 1 to org-mark-ring-length do
7269 (push (make-marker) org-mark-ring))
7270 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7271 org-mark-ring)
7273 (defun org-mark-ring-push (&optional pos buffer)
7274 "Put the current position or POS into the mark ring and rotate it."
7275 (interactive)
7276 (setq pos (or pos (point)))
7277 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7278 (move-marker (car org-mark-ring)
7279 (or pos (point))
7280 (or buffer (current-buffer)))
7281 (message "%s"
7282 (substitute-command-keys
7283 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7285 (defun org-mark-ring-goto (&optional n)
7286 "Jump to the previous position in the mark ring.
7287 With prefix arg N, jump back that many stored positions. When
7288 called several times in succession, walk through the entire ring.
7289 Org-mode commands jumping to a different position in the current file,
7290 or to another Org-mode file, automatically push the old position
7291 onto the ring."
7292 (interactive "p")
7293 (let (p m)
7294 (if (eq last-command this-command)
7295 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7296 (setq p org-mark-ring))
7297 (setq org-mark-ring-last-goto p)
7298 (setq m (car p))
7299 (switch-to-buffer (marker-buffer m))
7300 (goto-char m)
7301 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7303 (defun org-remove-angle-brackets (s)
7304 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7305 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7307 (defun org-add-angle-brackets (s)
7308 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7309 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7311 (defun org-remove-double-quotes (s)
7312 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7313 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7316 ;;; Following specific links
7318 (defun org-follow-timestamp-link ()
7319 (cond
7320 ((org-at-date-range-p t)
7321 (let ((org-agenda-start-on-weekday)
7322 (t1 (match-string 1))
7323 (t2 (match-string 2)))
7324 (setq t1 (time-to-days (org-time-string-to-time t1))
7325 t2 (time-to-days (org-time-string-to-time t2)))
7326 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7327 ((org-at-timestamp-p t)
7328 (org-agenda-list nil (time-to-days (org-time-string-to-time
7329 (substring (match-string 1) 0 10)))
7331 (t (error "This should not happen"))))
7334 ;;; Following file links
7335 (defvar org-wait nil)
7336 (defun org-open-file (path &optional in-emacs line search)
7337 "Open the file at PATH.
7338 First, this expands any special file name abbreviations. Then the
7339 configuration variable `org-file-apps' is checked if it contains an
7340 entry for this file type, and if yes, the corresponding command is launched.
7341 If no application is found, Emacs simply visits the file.
7342 With optional argument IN-EMACS, Emacs will visit the file.
7343 Optional LINE specifies a line to go to, optional SEARCH a string to
7344 search for. If LINE or SEARCH is given, the file will always be
7345 opened in Emacs.
7346 If the file does not exist, an error is thrown."
7347 (setq in-emacs (or in-emacs line search))
7348 (let* ((file (if (equal path "")
7349 buffer-file-name
7350 (substitute-in-file-name (expand-file-name path))))
7351 (apps (append org-file-apps (org-default-apps)))
7352 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7353 (dirp (if remp nil (file-directory-p file)))
7354 (dfile (downcase file))
7355 (old-buffer (current-buffer))
7356 (old-pos (point))
7357 (old-mode major-mode)
7358 ext cmd)
7359 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7360 (setq ext (match-string 1 dfile))
7361 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7362 (setq ext (match-string 1 dfile))))
7363 (if in-emacs
7364 (setq cmd 'emacs)
7365 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7366 (and dirp (cdr (assoc 'directory apps)))
7367 (cdr (assoc ext apps))
7368 (cdr (assoc t apps)))))
7369 (when (eq cmd 'mailcap)
7370 (require 'mailcap)
7371 (mailcap-parse-mailcaps)
7372 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7373 (command (mailcap-mime-info mime-type)))
7374 (if (stringp command)
7375 (setq cmd command)
7376 (setq cmd 'emacs))))
7377 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7378 (not (file-exists-p file))
7379 (not org-open-non-existing-files))
7380 (error "No such file: %s" file))
7381 (cond
7382 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7383 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7384 (while (string-match "['\"]%s['\"]" cmd)
7385 (setq cmd (replace-match "%s" t t cmd)))
7386 (while (string-match "%s" cmd)
7387 (setq cmd (replace-match
7388 (save-match-data (shell-quote-argument file))
7389 t t cmd)))
7390 (save-window-excursion
7391 (start-process-shell-command cmd nil cmd)
7392 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7394 ((or (stringp cmd)
7395 (eq cmd 'emacs))
7396 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7397 (widen)
7398 (if line (goto-line line)
7399 (if search (org-link-search search))))
7400 ((consp cmd)
7401 (eval cmd))
7402 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7403 (and (org-mode-p) (eq old-mode 'org-mode)
7404 (or (not (equal old-buffer (current-buffer)))
7405 (not (equal old-pos (point))))
7406 (org-mark-ring-push old-pos old-buffer))))
7408 (defun org-default-apps ()
7409 "Return the default applications for this operating system."
7410 (cond
7411 ((eq system-type 'darwin)
7412 org-file-apps-defaults-macosx)
7413 ((eq system-type 'windows-nt)
7414 org-file-apps-defaults-windowsnt)
7415 (t org-file-apps-defaults-gnu)))
7417 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7418 (defun org-file-remote-p (file)
7419 "Test whether FILE specifies a location on a remote system.
7420 Return non-nil if the location is indeed remote.
7422 For example, the filename \"/user@host:/foo\" specifies a location
7423 on the system \"/user@host:\"."
7424 (cond ((fboundp 'file-remote-p)
7425 (file-remote-p file))
7426 ((fboundp 'tramp-handle-file-remote-p)
7427 (tramp-handle-file-remote-p file))
7428 ((and (boundp 'ange-ftp-name-format)
7429 (string-match (car ange-ftp-name-format) file))
7431 (t nil)))
7434 ;;;; Refiling
7436 (defun org-get-org-file ()
7437 "Read a filename, with default directory `org-directory'."
7438 (let ((default (or org-default-notes-file remember-data-file)))
7439 (read-file-name (format "File name [%s]: " default)
7440 (file-name-as-directory org-directory)
7441 default)))
7443 (defun org-notes-order-reversed-p ()
7444 "Check if the current file should receive notes in reversed order."
7445 (cond
7446 ((not org-reverse-note-order) nil)
7447 ((eq t org-reverse-note-order) t)
7448 ((not (listp org-reverse-note-order)) nil)
7449 (t (catch 'exit
7450 (let ((all org-reverse-note-order)
7451 entry)
7452 (while (setq entry (pop all))
7453 (if (string-match (car entry) buffer-file-name)
7454 (throw 'exit (cdr entry))))
7455 nil)))))
7457 (defvar org-refile-target-table nil
7458 "The list of refile targets, created by `org-refile'.")
7460 (defvar org-agenda-new-buffers nil
7461 "Buffers created to visit agenda files.")
7463 (defun org-get-refile-targets (&optional default-buffer)
7464 "Produce a table with refile targets."
7465 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7466 targets txt re files f desc descre)
7467 (with-current-buffer (or default-buffer (current-buffer))
7468 (while (setq entry (pop entries))
7469 (setq files (car entry) desc (cdr entry))
7470 (cond
7471 ((null files) (setq files (list (current-buffer))))
7472 ((eq files 'org-agenda-files)
7473 (setq files (org-agenda-files 'unrestricted)))
7474 ((and (symbolp files) (fboundp files))
7475 (setq files (funcall files)))
7476 ((and (symbolp files) (boundp files))
7477 (setq files (symbol-value files))))
7478 (if (stringp files) (setq files (list files)))
7479 (cond
7480 ((eq (car desc) :tag)
7481 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7482 ((eq (car desc) :todo)
7483 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7484 ((eq (car desc) :regexp)
7485 (setq descre (cdr desc)))
7486 ((eq (car desc) :level)
7487 (setq descre (concat "^\\*\\{" (number-to-string
7488 (if org-odd-levels-only
7489 (1- (* 2 (cdr desc)))
7490 (cdr desc)))
7491 "\\}[ \t]")))
7492 ((eq (car desc) :maxlevel)
7493 (setq descre (concat "^\\*\\{1," (number-to-string
7494 (if org-odd-levels-only
7495 (1- (* 2 (cdr desc)))
7496 (cdr desc)))
7497 "\\}[ \t]")))
7498 (t (error "Bad refiling target description %s" desc)))
7499 (while (setq f (pop files))
7500 (save-excursion
7501 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7502 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7503 (save-excursion
7504 (save-restriction
7505 (widen)
7506 (goto-char (point-min))
7507 (while (re-search-forward descre nil t)
7508 (goto-char (point-at-bol))
7509 (when (looking-at org-complex-heading-regexp)
7510 (setq txt (match-string 4)
7511 re (concat "^" (regexp-quote
7512 (buffer-substring (match-beginning 1)
7513 (match-end 4)))))
7514 (if (match-end 5) (setq re (concat re "[ \t]+"
7515 (regexp-quote
7516 (match-string 5)))))
7517 (setq re (concat re "[ \t]*$"))
7518 (when org-refile-use-outline-path
7519 (setq txt (mapconcat 'identity
7520 (append
7521 (if (eq org-refile-use-outline-path 'file)
7522 (list (file-name-nondirectory
7523 (buffer-file-name (buffer-base-buffer))))
7524 (if (eq org-refile-use-outline-path 'full-file-path)
7525 (list (buffer-file-name (buffer-base-buffer)))))
7526 (org-get-outline-path)
7527 (list txt))
7528 "/")))
7529 (push (list txt f re (point)) targets))
7530 (goto-char (point-at-eol))))))))
7531 (nreverse targets))))
7533 (defun org-get-outline-path ()
7534 "Return the outline path to the current entry, as a list."
7535 (let (rtn)
7536 (save-excursion
7537 (while (org-up-heading-safe)
7538 (when (looking-at org-complex-heading-regexp)
7539 (push (org-match-string-no-properties 4) rtn)))
7540 rtn)))
7542 (defvar org-refile-history nil
7543 "History for refiling operations.")
7545 (defun org-refile (&optional goto default-buffer)
7546 "Move the entry at point to another heading.
7547 The list of target headings is compiled using the information in
7548 `org-refile-targets', which see. This list is created before each use
7549 and will therefore always be up-to-date.
7551 At the target location, the entry is filed as a subitem of the target heading.
7552 Depending on `org-reverse-note-order', the new subitem will either be the
7553 first of the last subitem.
7555 With prefix arg GOTO, the command will only visit the target location,
7556 not actually move anything.
7557 With a double prefix `C-c C-c', go to the location where the last refiling
7558 operation has put the subtree."
7559 (interactive "P")
7560 (let* ((cbuf (current-buffer))
7561 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7562 pos it nbuf file re level reversed)
7563 (if (equal goto '(16))
7564 (org-refile-goto-last-stored)
7565 (when (setq it (org-refile-get-location
7566 (if goto "Goto: " "Refile to: ") default-buffer))
7567 (setq file (nth 1 it)
7568 re (nth 2 it)
7569 pos (nth 3 it))
7570 (setq nbuf (or (find-buffer-visiting file)
7571 (find-file-noselect file)))
7572 (if goto
7573 (progn
7574 (switch-to-buffer nbuf)
7575 (goto-char pos)
7576 (org-show-context 'org-goto))
7577 (org-copy-subtree 1 nil t)
7578 (save-excursion
7579 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7580 (find-file-noselect file))))
7581 (setq reversed (org-notes-order-reversed-p))
7582 (save-excursion
7583 (save-restriction
7584 (widen)
7585 (goto-char pos)
7586 (looking-at outline-regexp)
7587 (setq level (org-get-valid-level (funcall outline-level) 1))
7588 (goto-char
7589 (if reversed
7590 (outline-next-heading)
7591 (or (save-excursion (outline-get-next-sibling))
7592 (org-end-of-subtree t t)
7593 (point-max))))
7594 (bookmark-set "org-refile-last-stored")
7595 (org-paste-subtree level))))
7596 (org-cut-subtree)
7597 (setq org-markers-to-move nil)
7598 (message "Entry refiled to \"%s\"" (car it)))))))
7600 (defun org-refile-goto-last-stored ()
7601 "Go to the location where the last refile was stored."
7602 (interactive)
7603 (bookmark-jump "org-refile-last-stored")
7604 (message "This is the location of the last refile"))
7606 (defun org-refile-get-location (&optional prompt default-buffer)
7607 "Prompt the user for a refile location, using PROMPT."
7608 (let ((org-refile-targets org-refile-targets)
7609 (org-refile-use-outline-path org-refile-use-outline-path))
7610 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7611 (unless org-refile-target-table
7612 (error "No refile targets"))
7613 (let* ((cbuf (current-buffer))
7614 (cfunc (if org-refile-use-outline-path
7615 'org-olpath-completing-read
7616 'completing-read))
7617 (extra (if org-refile-use-outline-path "/" ""))
7618 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7619 (fname (and filename (file-truename filename)))
7620 (tbl (mapcar
7621 (lambda (x)
7622 (if (not (equal fname (file-truename (nth 1 x))))
7623 (cons (concat (car x) extra " ("
7624 (file-name-nondirectory (nth 1 x)) ")")
7625 (cdr x))
7626 (cons (concat (car x) extra) (cdr x))))
7627 org-refile-target-table))
7628 (completion-ignore-case t))
7629 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7630 tbl)))
7632 (defun org-olpath-completing-read (prompt collection &rest args)
7633 "Read an outline path like a file name."
7634 (let ((thetable collection))
7635 (apply
7636 'completing-read prompt
7637 (lambda (string predicate &optional flag)
7638 (let (rtn r s f (l (length string)))
7639 (cond
7640 ((eq flag nil)
7641 ;; try completion
7642 (try-completion string thetable))
7643 ((eq flag t)
7644 ;; all-completions
7645 (setq rtn (all-completions string thetable predicate))
7646 (mapcar
7647 (lambda (x)
7648 (setq r (substring x l))
7649 (if (string-match " ([^)]*)$" x)
7650 (setq f (match-string 0 x))
7651 (setq f ""))
7652 (if (string-match "/" r)
7653 (concat string (substring r 0 (match-end 0)) f)
7655 rtn))
7656 ((eq flag 'lambda)
7657 ;; exact match?
7658 (assoc string thetable)))
7660 args)))
7662 ;;;; Dynamic blocks
7664 (defun org-find-dblock (name)
7665 "Find the first dynamic block with name NAME in the buffer.
7666 If not found, stay at current position and return nil."
7667 (let (pos)
7668 (save-excursion
7669 (goto-char (point-min))
7670 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7671 nil t)
7672 (match-beginning 0))))
7673 (if pos (goto-char pos))
7674 pos))
7676 (defconst org-dblock-start-re
7677 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7678 "Matches the startline of a dynamic block, with parameters.")
7680 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7681 "Matches the end of a dyhamic block.")
7683 (defun org-create-dblock (plist)
7684 "Create a dynamic block section, with parameters taken from PLIST.
7685 PLIST must containe a :name entry which is used as name of the block."
7686 (unless (bolp) (newline))
7687 (let ((name (plist-get plist :name)))
7688 (insert "#+BEGIN: " name)
7689 (while plist
7690 (if (eq (car plist) :name)
7691 (setq plist (cddr plist))
7692 (insert " " (prin1-to-string (pop plist)))))
7693 (insert "\n\n#+END:\n")
7694 (beginning-of-line -2)))
7696 (defun org-prepare-dblock ()
7697 "Prepare dynamic block for refresh.
7698 This empties the block, puts the cursor at the insert position and returns
7699 the property list including an extra property :name with the block name."
7700 (unless (looking-at org-dblock-start-re)
7701 (error "Not at a dynamic block"))
7702 (let* ((begdel (1+ (match-end 0)))
7703 (name (org-no-properties (match-string 1)))
7704 (params (append (list :name name)
7705 (read (concat "(" (match-string 3) ")")))))
7706 (unless (re-search-forward org-dblock-end-re nil t)
7707 (error "Dynamic block not terminated"))
7708 (setq params
7709 (append params
7710 (list :content (buffer-substring
7711 begdel (match-beginning 0)))))
7712 (delete-region begdel (match-beginning 0))
7713 (goto-char begdel)
7714 (open-line 1)
7715 params))
7717 (defun org-map-dblocks (&optional command)
7718 "Apply COMMAND to all dynamic blocks in the current buffer.
7719 If COMMAND is not given, use `org-update-dblock'."
7720 (let ((cmd (or command 'org-update-dblock))
7721 pos)
7722 (save-excursion
7723 (goto-char (point-min))
7724 (while (re-search-forward org-dblock-start-re nil t)
7725 (goto-char (setq pos (match-beginning 0)))
7726 (condition-case nil
7727 (funcall cmd)
7728 (error (message "Error during update of dynamic block")))
7729 (goto-char pos)
7730 (unless (re-search-forward org-dblock-end-re nil t)
7731 (error "Dynamic block not terminated"))))))
7733 (defun org-dblock-update (&optional arg)
7734 "User command for updating dynamic blocks.
7735 Update the dynamic block at point. With prefix ARG, update all dynamic
7736 blocks in the buffer."
7737 (interactive "P")
7738 (if arg
7739 (org-update-all-dblocks)
7740 (or (looking-at org-dblock-start-re)
7741 (org-beginning-of-dblock))
7742 (org-update-dblock)))
7744 (defun org-update-dblock ()
7745 "Update the dynamic block at point
7746 This means to empty the block, parse for parameters and then call
7747 the correct writing function."
7748 (save-window-excursion
7749 (let* ((pos (point))
7750 (line (org-current-line))
7751 (params (org-prepare-dblock))
7752 (name (plist-get params :name))
7753 (cmd (intern (concat "org-dblock-write:" name))))
7754 (message "Updating dynamic block `%s' at line %d..." name line)
7755 (funcall cmd params)
7756 (message "Updating dynamic block `%s' at line %d...done" name line)
7757 (goto-char pos))))
7759 (defun org-beginning-of-dblock ()
7760 "Find the beginning of the dynamic block at point.
7761 Error if there is no scuh block at point."
7762 (let ((pos (point))
7763 beg)
7764 (end-of-line 1)
7765 (if (and (re-search-backward org-dblock-start-re nil t)
7766 (setq beg (match-beginning 0))
7767 (re-search-forward org-dblock-end-re nil t)
7768 (> (match-end 0) pos))
7769 (goto-char beg)
7770 (goto-char pos)
7771 (error "Not in a dynamic block"))))
7773 (defun org-update-all-dblocks ()
7774 "Update all dynamic blocks in the buffer.
7775 This function can be used in a hook."
7776 (when (org-mode-p)
7777 (org-map-dblocks 'org-update-dblock)))
7780 ;;;; Completion
7782 (defconst org-additional-option-like-keywords
7783 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7784 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7785 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7787 (defcustom org-structure-template-alist
7789 ("s" "#+begin_src ?\n\n#+end_src"
7790 "<src lang=\"?\">\n\n</src>")
7791 ("e" "#+begin_example\n?\n#+end_example"
7792 "<example>\n?\n</example>")
7793 ("q" "#+begin_quote\n?\n#+end_quote"
7794 "<quote>\n?\n</quote>")
7795 ("v" "#+begin_verse\n?\n#+end_verse"
7796 "<verse>\n?\n/verse>")
7797 ("l" "#+begin_latex\n?\n#+end_latex"
7798 "<literal style=\"latex\">\n?\n</literal>")
7799 ("L" "#+latex: "
7800 "<literal style=\"latex\">?</literal>")
7801 ("h" "#+begin_html\n?\n#+end_html"
7802 "<literal style=\"html\">\n?\n</literal>")
7803 ("H" "#+html: "
7804 "<literal style=\"html\">?</literal>")
7805 ("a" "#+begin_ascii\n?\n#+end_ascii")
7806 ("A" "#+ascii: ")
7807 ("i" "#+include %file ?"
7808 "<include file=%file markup=\"?\">")
7810 "Structure completion elements.
7811 This is a list of abbreviation keys and values. The value gets inserted
7812 it you type @samp{.} followed by the key and then the completion key,
7813 usually `M-TAB'. %file will be replaced by a file name after prompting
7814 for the file uning completion.
7815 There are two templates for each key, the first uses the original Org syntax,
7816 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7817 the default when the /org-mtags.el/ module has been loaded. See also the
7818 variable `org-mtags-prefere-muse-templates'.
7819 This is an experimental feature, it is undecided if it is going to stay in."
7820 :group 'org-completion
7821 :type '(repeat
7822 (string :tag "Key")
7823 (string :tag "Template")
7824 (string :tag "Muse Template")))
7826 (defun org-try-structure-completion ()
7827 "Try to complete a structure template before point.
7828 This looks for strings like \"<e\" on an otherwise empty line and
7829 expands them."
7830 (let ((l (buffer-substring (point-at-bol) (point)))
7832 (when (and (looking-at "[ \t]*$")
7833 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7834 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7835 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7836 (match-beginning 1)) a)
7837 t)))
7839 (defun org-complete-expand-structure-template (start cell)
7840 "Expand a structure template."
7841 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7842 (rpl (nth (if musep 2 1) cell)))
7843 (delete-region start (point))
7844 (when (string-match "\\`#\\+" rpl)
7845 (cond
7846 ((bolp))
7847 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7848 (delete-region (point-at-bol) (point)))
7849 (t (newline))))
7850 (setq start (point))
7851 (if (string-match "%file" rpl)
7852 (setq rpl (replace-match
7853 (concat
7854 "\""
7855 (save-match-data
7856 (abbreviate-file-name (read-file-name "Include file: ")))
7857 "\"")
7858 t t rpl)))
7859 (insert rpl)
7860 (if (re-search-backward "\\?" start t) (delete-char 1))))
7863 (defun org-complete (&optional arg)
7864 "Perform completion on word at point.
7865 At the beginning of a headline, this completes TODO keywords as given in
7866 `org-todo-keywords'.
7867 If the current word is preceded by a backslash, completes the TeX symbols
7868 that are supported for HTML support.
7869 If the current word is preceded by \"#+\", completes special words for
7870 setting file options.
7871 In the line after \"#+STARTUP:, complete valid keywords.\"
7872 At all other locations, this simply calls the value of
7873 `org-completion-fallback-command'."
7874 (interactive "P")
7875 (org-without-partial-completion
7876 (catch 'exit
7877 (let* ((a nil)
7878 (end (point))
7879 (beg1 (save-excursion
7880 (skip-chars-backward (org-re "[:alnum:]_@"))
7881 (point)))
7882 (beg (save-excursion
7883 (skip-chars-backward "a-zA-Z0-9_:$")
7884 (point)))
7885 (confirm (lambda (x) (stringp (car x))))
7886 (searchhead (equal (char-before beg) ?*))
7887 (struct
7888 (when (and (member (char-before beg1) '(?. ?<))
7889 (setq a (assoc (buffer-substring beg1 (point))
7890 org-structure-template-alist)))
7891 (org-complete-expand-structure-template (1- beg1) a)
7892 (throw 'exit t)))
7893 (tag (and (equal (char-before beg1) ?:)
7894 (equal (char-after (point-at-bol)) ?*)))
7895 (prop (and (equal (char-before beg1) ?:)
7896 (not (equal (char-after (point-at-bol)) ?*))))
7897 (texp (equal (char-before beg) ?\\))
7898 (link (equal (char-before beg) ?\[))
7899 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7900 beg)
7901 "#+"))
7902 (startup (string-match "^#\\+STARTUP:.*"
7903 (buffer-substring (point-at-bol) (point))))
7904 (completion-ignore-case opt)
7905 (type nil)
7906 (tbl nil)
7907 (table (cond
7908 (opt
7909 (setq type :opt)
7910 (require 'org-exp)
7911 (append
7912 (mapcar
7913 (lambda (x)
7914 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7915 (cons (match-string 2 x) (match-string 1 x)))
7916 (org-split-string (org-get-current-options) "\n"))
7917 (mapcar 'list org-additional-option-like-keywords)))
7918 (startup
7919 (setq type :startup)
7920 org-startup-options)
7921 (link (append org-link-abbrev-alist-local
7922 org-link-abbrev-alist))
7923 (texp
7924 (setq type :tex)
7925 org-html-entities)
7926 ((string-match "\\`\\*+[ \t]+\\'"
7927 (buffer-substring (point-at-bol) beg))
7928 (setq type :todo)
7929 (mapcar 'list org-todo-keywords-1))
7930 (searchhead
7931 (setq type :searchhead)
7932 (save-excursion
7933 (goto-char (point-min))
7934 (while (re-search-forward org-todo-line-regexp nil t)
7935 (push (list
7936 (org-make-org-heading-search-string
7937 (match-string 3) t))
7938 tbl)))
7939 tbl)
7940 (tag (setq type :tag beg beg1)
7941 (or org-tag-alist (org-get-buffer-tags)))
7942 (prop (setq type :prop beg beg1)
7943 (mapcar 'list (org-buffer-property-keys nil t t)))
7944 (t (progn
7945 (call-interactively org-completion-fallback-command)
7946 (throw 'exit nil)))))
7947 (pattern (buffer-substring-no-properties beg end))
7948 (completion (try-completion pattern table confirm)))
7949 (cond ((eq completion t)
7950 (if (not (assoc (upcase pattern) table))
7951 (message "Already complete")
7952 (if (and (equal type :opt)
7953 (not (member (car (assoc (upcase pattern) table))
7954 org-additional-option-like-keywords)))
7955 (insert (substring (cdr (assoc (upcase pattern) table))
7956 (length pattern)))
7957 (if (memq type '(:tag :prop)) (insert ":")))))
7958 ((null completion)
7959 (message "Can't find completion for \"%s\"" pattern)
7960 (ding))
7961 ((not (string= pattern completion))
7962 (delete-region beg end)
7963 (if (string-match " +$" completion)
7964 (setq completion (replace-match "" t t completion)))
7965 (insert completion)
7966 (if (get-buffer-window "*Completions*")
7967 (delete-window (get-buffer-window "*Completions*")))
7968 (if (assoc completion table)
7969 (if (eq type :todo) (insert " ")
7970 (if (memq type '(:tag :prop)) (insert ":"))))
7971 (if (and (equal type :opt) (assoc completion table))
7972 (message "%s" (substitute-command-keys
7973 "Press \\[org-complete] again to insert example settings"))))
7975 (message "Making completion list...")
7976 (let ((list (sort (all-completions pattern table confirm)
7977 'string<)))
7978 (with-output-to-temp-buffer "*Completions*"
7979 (condition-case nil
7980 ;; Protection needed for XEmacs and emacs 21
7981 (display-completion-list list pattern)
7982 (error (display-completion-list list)))))
7983 (message "Making completion list...%s" "done")))))))
7985 ;;;; TODO, DEADLINE, Comments
7987 (defun org-toggle-comment ()
7988 "Change the COMMENT state of an entry."
7989 (interactive)
7990 (save-excursion
7991 (org-back-to-heading)
7992 (let (case-fold-search)
7993 (if (looking-at (concat outline-regexp
7994 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7995 (replace-match "" t t nil 1)
7996 (if (looking-at outline-regexp)
7997 (progn
7998 (goto-char (match-end 0))
7999 (insert org-comment-string " ")))))))
8001 (defvar org-last-todo-state-is-todo nil
8002 "This is non-nil when the last TODO state change led to a TODO state.
8003 If the last change removed the TODO tag or switched to DONE, then
8004 this is nil.")
8006 (defvar org-setting-tags nil) ; dynamically skiped
8008 (defun org-parse-local-options (string var)
8009 "Parse STRING for startup setting relevant for variable VAR."
8010 (let ((rtn (symbol-value var))
8011 e opts)
8012 (save-match-data
8013 (if (or (not string) (not (string-match "\\S-" string)))
8015 (setq opts (delq nil (mapcar (lambda (x)
8016 (setq e (assoc x org-startup-options))
8017 (if (eq (nth 1 e) var) e nil))
8018 (org-split-string string "[ \t]+"))))
8019 (if (not opts)
8021 (setq rtn nil)
8022 (while (setq e (pop opts))
8023 (if (not (nth 3 e))
8024 (setq rtn (nth 2 e))
8025 (if (not (listp rtn)) (setq rtn nil))
8026 (push (nth 2 e) rtn)))
8027 rtn)))))
8029 (defvar org-blocker-hook nil
8030 "Hook for functions that are allowed to block a state change.
8032 Each function gets as its single argument a property list, see
8033 `org-trigger-hook' for more information about this list.
8035 If any of the functions in this hook returns nil, the state change
8036 is blocked.")
8038 (defvar org-trigger-hook nil
8039 "Hook for functions that are triggered by a state change.
8041 Each function gets as its single argument a property list with at least
8042 the following elements:
8044 (:type type-of-change :position pos-at-entry-start
8045 :from old-state :to new-state)
8047 Depending on the type, more properties may be present.
8049 This mechanism is currently implemented for:
8051 TODO state changes
8052 ------------------
8053 :type todo-state-change
8054 :from previous state (keyword as a string), or nil
8055 :to new state (keyword as a string), or nil")
8058 (defun org-todo (&optional arg)
8059 "Change the TODO state of an item.
8060 The state of an item is given by a keyword at the start of the heading,
8061 like
8062 *** TODO Write paper
8063 *** DONE Call mom
8065 The different keywords are specified in the variable `org-todo-keywords'.
8066 By default the available states are \"TODO\" and \"DONE\".
8067 So for this example: when the item starts with TODO, it is changed to DONE.
8068 When it starts with DONE, the DONE is removed. And when neither TODO nor
8069 DONE are present, add TODO at the beginning of the heading.
8071 With C-u prefix arg, use completion to determine the new state.
8072 With numeric prefix arg, switch to that state.
8074 For calling through lisp, arg is also interpreted in the following way:
8075 'none -> empty state
8076 \"\"(empty string) -> switch to empty state
8077 'done -> switch to DONE
8078 'nextset -> switch to the next set of keywords
8079 'previousset -> switch to the previous set of keywords
8080 \"WAITING\" -> switch to the specified keyword, but only if it
8081 really is a member of `org-todo-keywords'."
8082 (interactive "P")
8083 (save-excursion
8084 (catch 'exit
8085 (org-back-to-heading)
8086 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8087 (or (looking-at (concat " +" org-todo-regexp " *"))
8088 (looking-at " *"))
8089 (let* ((match-data (match-data))
8090 (startpos (point-at-bol))
8091 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8092 (org-log-done org-log-done)
8093 (org-log-repeat org-log-repeat)
8094 (org-todo-log-states org-todo-log-states)
8095 (this (match-string 1))
8096 (hl-pos (match-beginning 0))
8097 (head (org-get-todo-sequence-head this))
8098 (ass (assoc head org-todo-kwd-alist))
8099 (interpret (nth 1 ass))
8100 (done-word (nth 3 ass))
8101 (final-done-word (nth 4 ass))
8102 (last-state (or this ""))
8103 (completion-ignore-case t)
8104 (member (member this org-todo-keywords-1))
8105 (tail (cdr member))
8106 (state (cond
8107 ((and org-todo-key-trigger
8108 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8109 (and (not arg) org-use-fast-todo-selection
8110 (not (eq org-use-fast-todo-selection 'prefix)))))
8111 ;; Use fast selection
8112 (org-fast-todo-selection))
8113 ((and (equal arg '(4))
8114 (or (not org-use-fast-todo-selection)
8115 (not org-todo-key-trigger)))
8116 ;; Read a state with completion
8117 (completing-read "State: " (mapcar (lambda(x) (list x))
8118 org-todo-keywords-1)
8119 nil t))
8120 ((eq arg 'right)
8121 (if this
8122 (if tail (car tail) nil)
8123 (car org-todo-keywords-1)))
8124 ((eq arg 'left)
8125 (if (equal member org-todo-keywords-1)
8127 (if this
8128 (nth (- (length org-todo-keywords-1) (length tail) 2)
8129 org-todo-keywords-1)
8130 (org-last org-todo-keywords-1))))
8131 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8132 (setq arg nil))) ; hack to fall back to cycling
8133 (arg
8134 ;; user or caller requests a specific state
8135 (cond
8136 ((equal arg "") nil)
8137 ((eq arg 'none) nil)
8138 ((eq arg 'done) (or done-word (car org-done-keywords)))
8139 ((eq arg 'nextset)
8140 (or (car (cdr (member head org-todo-heads)))
8141 (car org-todo-heads)))
8142 ((eq arg 'previousset)
8143 (let ((org-todo-heads (reverse org-todo-heads)))
8144 (or (car (cdr (member head org-todo-heads)))
8145 (car org-todo-heads))))
8146 ((car (member arg org-todo-keywords-1)))
8147 ((nth (1- (prefix-numeric-value arg))
8148 org-todo-keywords-1))))
8149 ((null member) (or head (car org-todo-keywords-1)))
8150 ((equal this final-done-word) nil) ;; -> make empty
8151 ((null tail) nil) ;; -> first entry
8152 ((eq interpret 'sequence)
8153 (car tail))
8154 ((memq interpret '(type priority))
8155 (if (eq this-command last-command)
8156 (car tail)
8157 (if (> (length tail) 0)
8158 (or done-word (car org-done-keywords))
8159 nil)))
8160 (t nil)))
8161 (next (if state (concat " " state " ") " "))
8162 (change-plist (list :type 'todo-state-change :from this :to state
8163 :position startpos))
8164 dolog now-done-p)
8165 (when org-blocker-hook
8166 (unless (save-excursion
8167 (save-match-data
8168 (run-hook-with-args-until-failure
8169 'org-blocker-hook change-plist)))
8170 (if (interactive-p)
8171 (error "TODO state change from %s to %s blocked" this state)
8172 ;; fail silently
8173 (message "TODO state change from %s to %s blocked" this state)
8174 (throw 'exit nil))))
8175 (store-match-data match-data)
8176 (replace-match next t t)
8177 (unless (pos-visible-in-window-p hl-pos)
8178 (message "TODO state changed to %s" (org-trim next)))
8179 (unless head
8180 (setq head (org-get-todo-sequence-head state)
8181 ass (assoc head org-todo-kwd-alist)
8182 interpret (nth 1 ass)
8183 done-word (nth 3 ass)
8184 final-done-word (nth 4 ass)))
8185 (when (memq arg '(nextset previousset))
8186 (message "Keyword-Set %d/%d: %s"
8187 (- (length org-todo-sets) -1
8188 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8189 (length org-todo-sets)
8190 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8191 (setq org-last-todo-state-is-todo
8192 (not (member state org-done-keywords)))
8193 (setq now-done-p (and (member state org-done-keywords)
8194 (not (member this org-done-keywords))))
8195 (and logging (org-local-logging logging))
8196 (when (and (or org-todo-log-states org-log-done)
8197 (not (memq arg '(nextset previousset))))
8198 ;; we need to look at recording a time and note
8199 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8200 (nth 2 (assoc this org-todo-log-states))))
8201 (when (and state
8202 (member state org-not-done-keywords)
8203 (not (member this org-not-done-keywords)))
8204 ;; This is now a todo state and was not one before
8205 ;; If there was a CLOSED time stamp, get rid of it.
8206 (org-add-planning-info nil nil 'closed))
8207 (when (and now-done-p org-log-done)
8208 ;; It is now done, and it was not done before
8209 (org-add-planning-info 'closed (org-current-time))
8210 (if (and (not dolog) (eq 'note org-log-done))
8211 (org-add-log-setup 'done state 'findpos 'note)))
8212 (when (and state dolog)
8213 ;; This is a non-nil state, and we need to log it
8214 (org-add-log-setup 'state state 'findpos dolog)))
8215 ;; Fixup tag positioning
8216 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8217 (when org-provide-todo-statistics
8218 (org-update-parent-todo-statistics))
8219 (run-hooks 'org-after-todo-state-change-hook)
8220 (if (and arg (not (member state org-done-keywords)))
8221 (setq head (org-get-todo-sequence-head state)))
8222 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8223 ;; Do we need to trigger a repeat?
8224 (when now-done-p (org-auto-repeat-maybe state))
8225 ;; Fixup cursor location if close to the keyword
8226 (if (and (outline-on-heading-p)
8227 (not (bolp))
8228 (save-excursion (beginning-of-line 1)
8229 (looking-at org-todo-line-regexp))
8230 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8231 (progn
8232 (goto-char (or (match-end 2) (match-end 1)))
8233 (just-one-space)))
8234 (when org-trigger-hook
8235 (save-excursion
8236 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8238 (defun org-update-parent-todo-statistics ()
8239 "Update any statistics cookie in the parent of the current headline."
8240 (interactive)
8241 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8242 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8243 (catch 'exit
8244 (save-excursion
8245 (setq level (org-up-heading-safe))
8246 (unless (and level
8247 (re-search-forward box-re (point-at-eol) t))
8248 (throw 'exit nil))
8249 (setq is-percent (match-end 2))
8250 (save-match-data
8251 (unless (outline-next-heading) (throw 'exit nil))
8252 (while (looking-at org-todo-line-regexp)
8253 (setq kwd (match-string 2))
8254 (and kwd (setq cnt-all (1+ cnt-all)))
8255 (and (member kwd org-done-keywords)
8256 (setq cnt-done (1+ cnt-done)))
8257 (condition-case nil
8258 (outline-forward-same-level 1)
8259 (error (end-of-line 1)))))
8260 (replace-match
8261 (if is-percent
8262 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8263 (format "[%d/%d]" cnt-done cnt-all)))
8264 (run-hook-with-args 'org-after-todo-statistics-hook
8265 cnt-done (- cnt-all cnt-done))))))
8267 (defvar org-after-todo-statistics-hook nil
8268 "Hook that is called after a TODO statistics cookie has been updated.
8269 Each function is called with two arguments: the number of not-done entries
8270 and the number of done entries.
8272 For example, the following function, when added to this hook, will switch
8273 an entry to DONE when all children are done, and back to TODO when new
8274 entries are set to a TODO status. Note that this hook is only called
8275 when there is a statistics cookie in the headline!
8277 (defun org-summary-todo (n-done n-not-done)
8278 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8279 (let (org-log-done org-log-states) ; turn off logging
8280 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8283 (defun org-local-logging (value)
8284 "Get logging settings from a property VALUE."
8285 (let* (words w a)
8286 ;; directly set the variables, they are already local.
8287 (setq org-log-done nil
8288 org-log-repeat nil
8289 org-todo-log-states nil)
8290 (setq words (org-split-string value))
8291 (while (setq w (pop words))
8292 (cond
8293 ((setq a (assoc w org-startup-options))
8294 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8295 (set (nth 1 a) (nth 2 a))))
8296 ((setq a (org-extract-log-state-settings w))
8297 (and (member (car a) org-todo-keywords-1)
8298 (push a org-todo-log-states)))))))
8300 (defun org-get-todo-sequence-head (kwd)
8301 "Return the head of the TODO sequence to which KWD belongs.
8302 If KWD is not set, check if there is a text property remembering the
8303 right sequence."
8304 (let (p)
8305 (cond
8306 ((not kwd)
8307 (or (get-text-property (point-at-bol) 'org-todo-head)
8308 (progn
8309 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8310 nil (point-at-eol)))
8311 (get-text-property p 'org-todo-head))))
8312 ((not (member kwd org-todo-keywords-1))
8313 (car org-todo-keywords-1))
8314 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8316 (defun org-fast-todo-selection ()
8317 "Fast TODO keyword selection with single keys.
8318 Returns the new TODO keyword, or nil if no state change should occur."
8319 (let* ((fulltable org-todo-key-alist)
8320 (done-keywords org-done-keywords) ;; needed for the faces.
8321 (maxlen (apply 'max (mapcar
8322 (lambda (x)
8323 (if (stringp (car x)) (string-width (car x)) 0))
8324 fulltable)))
8325 (expert nil)
8326 (fwidth (+ maxlen 3 1 3))
8327 (ncol (/ (- (window-width) 4) fwidth))
8328 tg cnt e c tbl
8329 groups ingroup)
8330 (save-window-excursion
8331 (if expert
8332 (set-buffer (get-buffer-create " *Org todo*"))
8333 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8334 (erase-buffer)
8335 (org-set-local 'org-done-keywords done-keywords)
8336 (setq tbl fulltable cnt 0)
8337 (while (setq e (pop tbl))
8338 (cond
8339 ((equal e '(:startgroup))
8340 (push '() groups) (setq ingroup t)
8341 (when (not (= cnt 0))
8342 (setq cnt 0)
8343 (insert "\n"))
8344 (insert "{ "))
8345 ((equal e '(:endgroup))
8346 (setq ingroup nil cnt 0)
8347 (insert "}\n"))
8349 (setq tg (car e) c (cdr e))
8350 (if ingroup (push tg (car groups)))
8351 (setq tg (org-add-props tg nil 'face
8352 (org-get-todo-face tg)))
8353 (if (and (= cnt 0) (not ingroup)) (insert " "))
8354 (insert "[" c "] " tg (make-string
8355 (- fwidth 4 (length tg)) ?\ ))
8356 (when (= (setq cnt (1+ cnt)) ncol)
8357 (insert "\n")
8358 (if ingroup (insert " "))
8359 (setq cnt 0)))))
8360 (insert "\n")
8361 (goto-char (point-min))
8362 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8363 (fit-window-to-buffer))
8364 (message "[a-z..]:Set [SPC]:clear")
8365 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8366 (cond
8367 ((or (= c ?\C-g)
8368 (and (= c ?q) (not (rassoc c fulltable))))
8369 (setq quit-flag t))
8370 ((= c ?\ ) nil)
8371 ((setq e (rassoc c fulltable) tg (car e))
8373 (t (setq quit-flag t))))))
8375 (defun org-entry-is-todo-p ()
8376 (member (org-get-todo-state) org-not-done-keywords))
8378 (defun org-entry-is-done-p ()
8379 (member (org-get-todo-state) org-done-keywords))
8381 (defun org-get-todo-state ()
8382 (save-excursion
8383 (org-back-to-heading t)
8384 (and (looking-at org-todo-line-regexp)
8385 (match-end 2)
8386 (match-string 2))))
8388 (defun org-at-date-range-p (&optional inactive-ok)
8389 "Is the cursor inside a date range?"
8390 (interactive)
8391 (save-excursion
8392 (catch 'exit
8393 (let ((pos (point)))
8394 (skip-chars-backward "^[<\r\n")
8395 (skip-chars-backward "<[")
8396 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8397 (>= (match-end 0) pos)
8398 (throw 'exit t))
8399 (skip-chars-backward "^<[\r\n")
8400 (skip-chars-backward "<[")
8401 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8402 (>= (match-end 0) pos)
8403 (throw 'exit t)))
8404 nil)))
8406 (defun org-get-repeat ()
8407 "Check if tere is a deadline/schedule with repeater in this entry."
8408 (save-match-data
8409 (save-excursion
8410 (org-back-to-heading t)
8411 (if (re-search-forward
8412 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8413 (match-string 1)))))
8415 (defvar org-last-changed-timestamp)
8416 (defvar org-log-post-message)
8417 (defvar org-log-note-purpose)
8418 (defvar org-log-note-how)
8419 (defun org-auto-repeat-maybe (done-word)
8420 "Check if the current headline contains a repeated deadline/schedule.
8421 If yes, set TODO state back to what it was and change the base date
8422 of repeating deadline/scheduled time stamps to new date.
8423 This function is run automatically after each state change to a DONE state."
8424 ;; last-state is dynamically scoped into this function
8425 (let* ((repeat (org-get-repeat))
8426 (aa (assoc last-state org-todo-kwd-alist))
8427 (interpret (nth 1 aa))
8428 (head (nth 2 aa))
8429 (whata '(("d" . day) ("m" . month) ("y" . year)))
8430 (msg "Entry repeats: ")
8431 (org-log-done nil)
8432 (org-todo-log-states nil)
8433 (nshiftmax 10) (nshift 0)
8434 re type n what ts mb0 time)
8435 (when repeat
8436 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8437 (org-todo (if (eq interpret 'type) last-state head))
8438 (when org-log-repeat
8439 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8440 (memq 'org-add-log-note post-command-hook))
8441 ;; OK, we are already setup for some record
8442 (if (eq org-log-repeat 'note)
8443 ;; make sure we take a note, not only a time stamp
8444 (setq org-log-note-how 'note))
8445 ;; Set up for taking a record
8446 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8447 'findpos org-log-repeat)))
8448 (org-back-to-heading t)
8449 (org-add-planning-info nil nil 'closed)
8450 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8451 org-deadline-time-regexp "\\)\\|\\("
8452 org-ts-regexp "\\)"))
8453 (while (re-search-forward
8454 re (save-excursion (outline-next-heading) (point)) t)
8455 (setq type (if (match-end 1) org-scheduled-string
8456 (if (match-end 3) org-deadline-string "Plain:"))
8457 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8458 mb0 (match-beginning 0))
8459 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8460 (setq n (string-to-number (match-string 2 ts))
8461 what (match-string 3 ts))
8462 (if (equal what "w") (setq n (* n 7) what "d"))
8463 ;; Preparation, see if we need to modify the start date for the change
8464 (when (match-end 1)
8465 (setq time (save-match-data (org-time-string-to-time ts)))
8466 (cond
8467 ((equal (match-string 1 ts) ".")
8468 ;; Shift starting date to today
8469 (org-timestamp-change
8470 (- (time-to-days (current-time)) (time-to-days time))
8471 'day))
8472 ((equal (match-string 1 ts) "+")
8473 (while (or (= nshift 0)
8474 (<= (time-to-days time) (time-to-days (current-time))))
8475 (when (= (incf nshift) nshiftmax)
8476 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8477 (error "Abort")))
8478 (org-timestamp-change n (cdr (assoc what whata)))
8479 (org-at-timestamp-p t)
8480 (setq ts (match-string 1))
8481 (setq time (save-match-data (org-time-string-to-time ts))))
8482 (org-timestamp-change (- n) (cdr (assoc what whata)))
8483 ;; rematch, so that we have everything in place for the real shift
8484 (org-at-timestamp-p t)
8485 (setq ts (match-string 1))
8486 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8487 (org-timestamp-change n (cdr (assoc what whata)))
8488 (setq msg (concat msg type org-last-changed-timestamp " "))))
8489 (setq org-log-post-message msg)
8490 (message "%s" msg))))
8492 (defun org-show-todo-tree (arg)
8493 "Make a compact tree which shows all headlines marked with TODO.
8494 The tree will show the lines where the regexp matches, and all higher
8495 headlines above the match.
8496 With a \\[universal-argument] prefix, also show the DONE entries.
8497 With a numeric prefix N, construct a sparse tree for the Nth element
8498 of `org-todo-keywords-1'."
8499 (interactive "P")
8500 (let ((case-fold-search nil)
8501 (kwd-re
8502 (cond ((null arg) org-not-done-regexp)
8503 ((equal arg '(4))
8504 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8505 (mapcar 'list org-todo-keywords-1))))
8506 (concat "\\("
8507 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8508 "\\)\\>")))
8509 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8510 (regexp-quote (nth (1- (prefix-numeric-value arg))
8511 org-todo-keywords-1)))
8512 (t (error "Invalid prefix argument: %s" arg)))))
8513 (message "%d TODO entries found"
8514 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8516 (defun org-deadline (&optional remove)
8517 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8518 With argument REMOVE, remove any deadline from the item."
8519 (interactive "P")
8520 (if remove
8521 (progn
8522 (org-remove-timestamp-with-keyword org-deadline-string)
8523 (message "Item no longer has a deadline."))
8524 (org-add-planning-info 'deadline nil 'closed)))
8526 (defun org-schedule (&optional remove)
8527 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8528 With argument REMOVE, remove any scheduling date from the item."
8529 (interactive "P")
8530 (if remove
8531 (progn
8532 (org-remove-timestamp-with-keyword org-scheduled-string)
8533 (message "Item is no longer scheduled."))
8534 (org-add-planning-info 'scheduled nil 'closed)))
8536 (defun org-remove-timestamp-with-keyword (keyword)
8537 "Remove all time stamps with KEYWORD in the current entry."
8538 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8539 beg)
8540 (save-excursion
8541 (org-back-to-heading t)
8542 (setq beg (point))
8543 (org-end-of-subtree t t)
8544 (while (re-search-backward re beg t)
8545 (replace-match "")
8546 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8547 (equal (char-before) ?\ ))
8548 (backward-delete-char 1)
8549 (if (string-match "^[ \t]*$" (buffer-substring
8550 (point-at-bol) (point-at-eol)))
8551 (delete-region (point-at-bol)
8552 (min (point-max) (1+ (point-at-eol))))))))))
8554 (defun org-add-planning-info (what &optional time &rest remove)
8555 "Insert new timestamp with keyword in the line directly after the headline.
8556 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8557 If non is given, the user is prompted for a date.
8558 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8559 be removed."
8560 (interactive)
8561 (let (org-time-was-given org-end-time-was-given ts
8562 end default-time default-input)
8564 (when (and (not time) (memq what '(scheduled deadline)))
8565 ;; Try to get a default date/time from existing timestamp
8566 (save-excursion
8567 (org-back-to-heading t)
8568 (setq end (save-excursion (outline-next-heading) (point)))
8569 (when (re-search-forward (if (eq what 'scheduled)
8570 org-scheduled-time-regexp
8571 org-deadline-time-regexp)
8572 end t)
8573 (setq ts (match-string 1)
8574 default-time
8575 (apply 'encode-time (org-parse-time-string ts))
8576 default-input (and ts (org-get-compact-tod ts))))))
8577 (when what
8578 ;; If necessary, get the time from the user
8579 (setq time (or time (org-read-date nil 'to-time nil nil
8580 default-time default-input))))
8582 (when (and org-insert-labeled-timestamps-at-point
8583 (member what '(scheduled deadline)))
8584 (insert
8585 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8586 (org-insert-time-stamp time org-time-was-given
8587 nil nil nil (list org-end-time-was-given))
8588 (setq what nil))
8589 (save-excursion
8590 (save-restriction
8591 (let (col list elt ts buffer-invisibility-spec)
8592 (org-back-to-heading t)
8593 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8594 (goto-char (match-end 1))
8595 (setq col (current-column))
8596 (goto-char (match-end 0))
8597 (if (eobp) (insert "\n") (forward-char 1))
8598 (if (and (not (looking-at outline-regexp))
8599 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8600 "[^\r\n]*"))
8601 (not (equal (match-string 1) org-clock-string)))
8602 (narrow-to-region (match-beginning 0) (match-end 0))
8603 (insert-before-markers "\n")
8604 (backward-char 1)
8605 (narrow-to-region (point) (point))
8606 (org-indent-to-column col))
8607 ;; Check if we have to remove something.
8608 (setq list (cons what remove))
8609 (while list
8610 (setq elt (pop list))
8611 (goto-char (point-min))
8612 (when (or (and (eq elt 'scheduled)
8613 (re-search-forward org-scheduled-time-regexp nil t))
8614 (and (eq elt 'deadline)
8615 (re-search-forward org-deadline-time-regexp nil t))
8616 (and (eq elt 'closed)
8617 (re-search-forward org-closed-time-regexp nil t)))
8618 (replace-match "")
8619 (if (looking-at "--+<[^>]+>") (replace-match ""))
8620 (if (looking-at " +") (replace-match ""))))
8621 (goto-char (point-max))
8622 (when what
8623 (insert
8624 (if (not (equal (char-before) ?\ )) " " "")
8625 (cond ((eq what 'scheduled) org-scheduled-string)
8626 ((eq what 'deadline) org-deadline-string)
8627 ((eq what 'closed) org-closed-string))
8628 " ")
8629 (setq ts (org-insert-time-stamp
8630 time
8631 (or org-time-was-given
8632 (and (eq what 'closed) org-log-done-with-time))
8633 (eq what 'closed)
8634 nil nil (list org-end-time-was-given)))
8635 (end-of-line 1))
8636 (goto-char (point-min))
8637 (widen)
8638 (if (and (looking-at "[ \t]+\n")
8639 (equal (char-before) ?\n))
8640 (delete-region (1- (point)) (point-at-eol)))
8641 ts)))))
8643 (defvar org-log-note-marker (make-marker))
8644 (defvar org-log-note-purpose nil)
8645 (defvar org-log-note-state nil)
8646 (defvar org-log-note-how nil)
8647 (defvar org-log-note-window-configuration nil)
8648 (defvar org-log-note-return-to (make-marker))
8649 (defvar org-log-post-message nil
8650 "Message to be displayed after a log note has been stored.
8651 The auto-repeater uses this.")
8653 (defun org-add-note ()
8654 "Add a note to the current entry.
8655 This is done in the same way as adding a state change note."
8656 (interactive)
8657 (org-add-log-setup 'note nil t nil))
8659 (defun org-add-log-setup (&optional purpose state findpos how)
8660 "Set up the post command hook to take a note.
8661 If this is about to TODO state change, the new state is expected in STATE.
8662 When FINDPOS is non-nil, find the correct position for the note in
8663 the current entry. If not, assume that it can be inserted at point."
8664 (save-excursion
8665 (when findpos
8666 (org-back-to-heading t)
8667 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8668 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8669 "[^\r\n]*\\)?"))
8670 (goto-char (match-end 0))
8671 (unless org-log-states-order-reversed
8672 (and (= (char-after) ?\n) (forward-char 1))
8673 (org-skip-over-state-notes)
8674 (skip-chars-backward " \t\n\r")))
8675 (move-marker org-log-note-marker (point))
8676 (setq org-log-note-purpose purpose
8677 org-log-note-state state
8678 org-log-note-how how)
8679 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8681 (defun org-skip-over-state-notes ()
8682 "Skip past the list of State notes in an entry."
8683 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8684 (while (looking-at "[ \t]*- State")
8685 (condition-case nil
8686 (org-next-item)
8687 (error (org-end-of-item)))))
8689 (defun org-add-log-note (&optional purpose)
8690 "Pop up a window for taking a note, and add this note later at point."
8691 (remove-hook 'post-command-hook 'org-add-log-note)
8692 (setq org-log-note-window-configuration (current-window-configuration))
8693 (delete-other-windows)
8694 (move-marker org-log-note-return-to (point))
8695 (switch-to-buffer (marker-buffer org-log-note-marker))
8696 (goto-char org-log-note-marker)
8697 (org-switch-to-buffer-other-window "*Org Note*")
8698 (erase-buffer)
8699 (if (memq org-log-note-how '(time state))
8700 (org-store-log-note)
8701 (let ((org-inhibit-startup t)) (org-mode))
8702 (insert (format "# Insert note for %s.
8703 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8704 (cond
8705 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8706 ((eq org-log-note-purpose 'done) "closed todo item")
8707 ((eq org-log-note-purpose 'state)
8708 (format "state change to \"%s\"" org-log-note-state))
8709 ((eq org-log-note-purpose 'note)
8710 "this entry")
8711 (t (error "This should not happen")))))
8712 (org-set-local 'org-finish-function 'org-store-log-note)))
8714 (defvar org-note-abort nil) ; dynamically scoped
8715 (defun org-store-log-note ()
8716 "Finish taking a log note, and insert it to where it belongs."
8717 (let ((txt (buffer-string))
8718 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8719 lines ind)
8720 (kill-buffer (current-buffer))
8721 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8722 (setq txt (replace-match "" t t txt)))
8723 (if (string-match "\\s-+\\'" txt)
8724 (setq txt (replace-match "" t t txt)))
8725 (setq lines (org-split-string txt "\n"))
8726 (when (and note (string-match "\\S-" note))
8727 (setq note
8728 (org-replace-escapes
8729 note
8730 (list (cons "%u" (user-login-name))
8731 (cons "%U" user-full-name)
8732 (cons "%t" (format-time-string
8733 (org-time-stamp-format 'long 'inactive)
8734 (current-time)))
8735 (cons "%s" (if org-log-note-state
8736 (concat "\"" org-log-note-state "\"")
8737 "")))))
8738 (if lines (setq note (concat note " \\\\")))
8739 (push note lines))
8740 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8741 (when lines
8742 (save-excursion
8743 (set-buffer (marker-buffer org-log-note-marker))
8744 (save-excursion
8745 (goto-char org-log-note-marker)
8746 (move-marker org-log-note-marker nil)
8747 (end-of-line 1)
8748 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8749 (indent-relative nil)
8750 (insert "- " (pop lines))
8751 (org-indent-line-function)
8752 (beginning-of-line 1)
8753 (looking-at "[ \t]*")
8754 (setq ind (concat (match-string 0) " "))
8755 (end-of-line 1)
8756 (while lines (insert "\n" ind (pop lines)))))))
8757 (set-window-configuration org-log-note-window-configuration)
8758 (with-current-buffer (marker-buffer org-log-note-return-to)
8759 (goto-char org-log-note-return-to))
8760 (move-marker org-log-note-return-to nil)
8761 (and org-log-post-message (message "%s" org-log-post-message)))
8763 (defun org-sparse-tree (&optional arg)
8764 "Create a sparse tree, prompt for the details.
8765 This command can create sparse trees. You first need to select the type
8766 of match used to create the tree:
8768 t Show entries with a specific TODO keyword.
8769 T Show entries selected by a tags match.
8770 p Enter a property name and its value (both with completion on existing
8771 names/values) and show entries with that property.
8772 r Show entries matching a regular expression
8773 d Show deadlines due within `org-deadline-warning-days'."
8774 (interactive "P")
8775 (let (ans kwd value)
8776 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8777 (setq ans (read-char-exclusive))
8778 (cond
8779 ((equal ans ?d)
8780 (call-interactively 'org-check-deadlines))
8781 ((equal ans ?b)
8782 (call-interactively 'org-check-before-date))
8783 ((equal ans ?t)
8784 (org-show-todo-tree '(4)))
8785 ((equal ans ?T)
8786 (call-interactively 'org-tags-sparse-tree))
8787 ((member ans '(?p ?P))
8788 (setq kwd (completing-read "Property: "
8789 (mapcar 'list (org-buffer-property-keys))))
8790 (setq value (completing-read "Value: "
8791 (mapcar 'list (org-property-values kwd))))
8792 (unless (string-match "\\`{.*}\\'" value)
8793 (setq value (concat "\"" value "\"")))
8794 (org-tags-sparse-tree arg (concat kwd "=" value)))
8795 ((member ans '(?r ?R ?/))
8796 (call-interactively 'org-occur))
8797 (t (error "No such sparse tree command \"%c\"" ans)))))
8799 (defvar org-occur-highlights nil
8800 "List of overlays used for occur matches.")
8801 (make-variable-buffer-local 'org-occur-highlights)
8802 (defvar org-occur-parameters nil
8803 "Parameters of the active org-occur calls.
8804 This is a list, each call to org-occur pushes as cons cell,
8805 containing the regular expression and the callback, onto the list.
8806 The list can contain several entries if `org-occur' has been called
8807 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8808 will only contain one set of parameters. When the highlights are
8809 removed (for example with `C-c C-c', or with the next edit (depending
8810 on `org-remove-highlights-with-change'), this variable is emptied
8811 as well.")
8812 (make-variable-buffer-local 'org-occur-parameters)
8814 (defun org-occur (regexp &optional keep-previous callback)
8815 "Make a compact tree which shows all matches of REGEXP.
8816 The tree will show the lines where the regexp matches, and all higher
8817 headlines above the match. It will also show the heading after the match,
8818 to make sure editing the matching entry is easy.
8819 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8820 call to `org-occur' will be kept, to allow stacking of calls to this
8821 command.
8822 If CALLBACK is non-nil, it is a function which is called to confirm
8823 that the match should indeed be shown."
8824 (interactive "sRegexp: \nP")
8825 (unless keep-previous
8826 (org-remove-occur-highlights nil nil t))
8827 (push (cons regexp callback) org-occur-parameters)
8828 (let ((cnt 0))
8829 (save-excursion
8830 (goto-char (point-min))
8831 (if (or (not keep-previous) ; do not want to keep
8832 (not org-occur-highlights)) ; no previous matches
8833 ;; hide everything
8834 (org-overview))
8835 (while (re-search-forward regexp nil t)
8836 (when (or (not callback)
8837 (save-match-data (funcall callback)))
8838 (setq cnt (1+ cnt))
8839 (when org-highlight-sparse-tree-matches
8840 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8841 (org-show-context 'occur-tree))))
8842 (when org-remove-highlights-with-change
8843 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8844 nil 'local))
8845 (unless org-sparse-tree-open-archived-trees
8846 (org-hide-archived-subtrees (point-min) (point-max)))
8847 (run-hooks 'org-occur-hook)
8848 (if (interactive-p)
8849 (message "%d match(es) for regexp %s" cnt regexp))
8850 cnt))
8852 (defun org-show-context (&optional key)
8853 "Make sure point and context and visible.
8854 How much context is shown depends upon the variables
8855 `org-show-hierarchy-above', `org-show-following-heading'. and
8856 `org-show-siblings'."
8857 (let ((heading-p (org-on-heading-p t))
8858 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8859 (following-p (org-get-alist-option org-show-following-heading key))
8860 (entry-p (org-get-alist-option org-show-entry-below key))
8861 (siblings-p (org-get-alist-option org-show-siblings key)))
8862 (catch 'exit
8863 ;; Show heading or entry text
8864 (if (and heading-p (not entry-p))
8865 (org-flag-heading nil) ; only show the heading
8866 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8867 (org-show-hidden-entry))) ; show entire entry
8868 (when following-p
8869 ;; Show next sibling, or heading below text
8870 (save-excursion
8871 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8872 (org-flag-heading nil))))
8873 (when siblings-p (org-show-siblings))
8874 (when hierarchy-p
8875 ;; show all higher headings, possibly with siblings
8876 (save-excursion
8877 (while (and (condition-case nil
8878 (progn (org-up-heading-all 1) t)
8879 (error nil))
8880 (not (bobp)))
8881 (org-flag-heading nil)
8882 (when siblings-p (org-show-siblings))))))))
8884 (defun org-reveal (&optional siblings)
8885 "Show current entry, hierarchy above it, and the following headline.
8886 This can be used to show a consistent set of context around locations
8887 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8888 not t for the search context.
8890 With optional argument SIBLINGS, on each level of the hierarchy all
8891 siblings are shown. This repairs the tree structure to what it would
8892 look like when opened with hierarchical calls to `org-cycle'."
8893 (interactive "P")
8894 (let ((org-show-hierarchy-above t)
8895 (org-show-following-heading t)
8896 (org-show-siblings (if siblings t org-show-siblings)))
8897 (org-show-context nil)))
8899 (defun org-highlight-new-match (beg end)
8900 "Highlight from BEG to END and mark the highlight is an occur headline."
8901 (let ((ov (org-make-overlay beg end)))
8902 (org-overlay-put ov 'face 'secondary-selection)
8903 (push ov org-occur-highlights)))
8905 (defun org-remove-occur-highlights (&optional beg end noremove)
8906 "Remove the occur highlights from the buffer.
8907 BEG and END are ignored. If NOREMOVE is nil, remove this function
8908 from the `before-change-functions' in the current buffer."
8909 (interactive)
8910 (unless org-inhibit-highlight-removal
8911 (mapc 'org-delete-overlay org-occur-highlights)
8912 (setq org-occur-highlights nil)
8913 (setq org-occur-parameters nil)
8914 (unless noremove
8915 (remove-hook 'before-change-functions
8916 'org-remove-occur-highlights 'local))))
8918 ;;;; Priorities
8920 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8921 "Regular expression matching the priority indicator.")
8923 (defvar org-remove-priority-next-time nil)
8925 (defun org-priority-up ()
8926 "Increase the priority of the current item."
8927 (interactive)
8928 (org-priority 'up))
8930 (defun org-priority-down ()
8931 "Decrease the priority of the current item."
8932 (interactive)
8933 (org-priority 'down))
8935 (defun org-priority (&optional action)
8936 "Change the priority of an item by ARG.
8937 ACTION can be `set', `up', `down', or a character."
8938 (interactive)
8939 (setq action (or action 'set))
8940 (let (current new news have remove)
8941 (save-excursion
8942 (org-back-to-heading)
8943 (if (looking-at org-priority-regexp)
8944 (setq current (string-to-char (match-string 2))
8945 have t)
8946 (setq current org-default-priority))
8947 (cond
8948 ((or (eq action 'set)
8949 (if (featurep 'xemacs) (characterp action) (integerp action)))
8950 (if (not (eq action 'set))
8951 (setq new action)
8952 (message "Priority %c-%c, SPC to remove: "
8953 org-highest-priority org-lowest-priority)
8954 (setq new (read-char-exclusive)))
8955 (if (and (= (upcase org-highest-priority) org-highest-priority)
8956 (= (upcase org-lowest-priority) org-lowest-priority))
8957 (setq new (upcase new)))
8958 (cond ((equal new ?\ ) (setq remove t))
8959 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8960 (error "Priority must be between `%c' and `%c'"
8961 org-highest-priority org-lowest-priority))))
8962 ((eq action 'up)
8963 (if (and (not have) (eq last-command this-command))
8964 (setq new org-lowest-priority)
8965 (setq new (if (and org-priority-start-cycle-with-default (not have))
8966 org-default-priority (1- current)))))
8967 ((eq action 'down)
8968 (if (and (not have) (eq last-command this-command))
8969 (setq new org-highest-priority)
8970 (setq new (if (and org-priority-start-cycle-with-default (not have))
8971 org-default-priority (1+ current)))))
8972 (t (error "Invalid action")))
8973 (if (or (< (upcase new) org-highest-priority)
8974 (> (upcase new) org-lowest-priority))
8975 (setq remove t))
8976 (setq news (format "%c" new))
8977 (if have
8978 (if remove
8979 (replace-match "" t t nil 1)
8980 (replace-match news t t nil 2))
8981 (if remove
8982 (error "No priority cookie found in line")
8983 (looking-at org-todo-line-regexp)
8984 (if (match-end 2)
8985 (progn
8986 (goto-char (match-end 2))
8987 (insert " [#" news "]"))
8988 (goto-char (match-beginning 3))
8989 (insert "[#" news "] ")))))
8990 (org-preserve-lc (org-set-tags nil 'align))
8991 (if remove
8992 (message "Priority removed")
8993 (message "Priority of current item set to %s" news))))
8996 (defun org-get-priority (s)
8997 "Find priority cookie and return priority."
8998 (save-match-data
8999 (if (not (string-match org-priority-regexp s))
9000 (* 1000 (- org-lowest-priority org-default-priority))
9001 (* 1000 (- org-lowest-priority
9002 (string-to-char (match-string 2 s)))))))
9004 ;;;; Tags
9006 (defun org-scan-tags (action matcher &optional todo-only)
9007 "Scan headline tags with inheritance and produce output ACTION.
9008 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9009 evaluated, testing if a given set of tags qualifies a headline for
9010 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9011 are included in the output."
9012 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9013 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9014 (org-re
9015 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9016 (props (list 'face nil
9017 'done-face 'org-done
9018 'undone-face nil
9019 'mouse-face 'highlight
9020 'org-not-done-regexp org-not-done-regexp
9021 'org-todo-regexp org-todo-regexp
9022 'keymap org-agenda-keymap
9023 'help-echo
9024 (format "mouse-2 or RET jump to org file %s"
9025 (abbreviate-file-name
9026 (or (buffer-file-name (buffer-base-buffer))
9027 (buffer-name (buffer-base-buffer)))))))
9028 (case-fold-search nil)
9029 lspos tags tags-list
9030 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9031 (llast 0) rtn level category i txt
9032 todo marker entry priority)
9033 (save-excursion
9034 (goto-char (point-min))
9035 (when (eq action 'sparse-tree)
9036 (org-overview)
9037 (org-remove-occur-highlights))
9038 (while (re-search-forward re nil t)
9039 (catch :skip
9040 (setq todo (if (match-end 1) (match-string 2))
9041 tags (if (match-end 4) (match-string 4)))
9042 (goto-char (setq lspos (1+ (match-beginning 0))))
9043 (setq level (org-reduced-level (funcall outline-level))
9044 category (org-get-category))
9045 (setq i llast llast level)
9046 ;; remove tag lists from same and sublevels
9047 (while (>= i level)
9048 (when (setq entry (assoc i tags-alist))
9049 (setq tags-alist (delete entry tags-alist)))
9050 (setq i (1- i)))
9051 ;; add the next tags
9052 (when tags
9053 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9054 tags-alist
9055 (cons (cons level tags) tags-alist)))
9056 ;; compile tags for current headline
9057 (setq tags-list
9058 (if org-use-tag-inheritance
9059 (apply 'append (mapcar 'cdr tags-alist))
9060 tags))
9061 (when (and tags org-use-tag-inheritance
9062 (not (eq t org-use-tag-inheritance)))
9063 ;; selective inheritance, remove uninherited ones
9064 (setcdr (car tags-alist)
9065 (org-remove-uniherited-tags (cdar tags-alist))))
9066 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9067 (eval matcher)
9068 (or (not org-agenda-skip-archived-trees)
9069 (not (member org-archive-tag tags-list))))
9070 (and (eq action 'agenda) (org-agenda-skip))
9071 ;; list this headline
9073 (if (eq action 'sparse-tree)
9074 (progn
9075 (and org-highlight-sparse-tree-matches
9076 (org-get-heading) (match-end 0)
9077 (org-highlight-new-match
9078 (match-beginning 0) (match-beginning 1)))
9079 (org-show-context 'tags-tree))
9080 (setq txt (org-format-agenda-item
9082 (concat
9083 (if org-tags-match-list-sublevels
9084 (make-string (1- level) ?.) "")
9085 (org-get-heading))
9086 category tags-list)
9087 priority (org-get-priority txt))
9088 (goto-char lspos)
9089 (setq marker (org-agenda-new-marker))
9090 (org-add-props txt props
9091 'org-marker marker 'org-hd-marker marker 'org-category category
9092 'priority priority 'type "tagsmatch")
9093 (push txt rtn))
9094 ;; if we are to skip sublevels, jump to end of subtree
9095 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9096 (when (and (eq action 'sparse-tree)
9097 (not org-sparse-tree-open-archived-trees))
9098 (org-hide-archived-subtrees (point-min) (point-max)))
9099 (nreverse rtn)))
9101 (defun org-remove-uniherited-tags (tags)
9102 "Remove all tags that are not inherited from the list TAGS."
9103 (cond
9104 ((eq org-use-tag-inheritance t) tags)
9105 ((not org-use-tag-inheritance) nil)
9106 ((stringp org-use-tag-inheritance)
9107 (delq nil (mapcar
9108 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9109 tags)))
9110 ((listp org-use-tag-inheritance)
9111 (org-delete-all org-use-tag-inheritance tags))))
9113 (defvar todo-only) ;; dynamically scoped
9115 (defun org-tags-sparse-tree (&optional todo-only match)
9116 "Create a sparse tree according to tags string MATCH.
9117 MATCH can contain positive and negative selection of tags, like
9118 \"+WORK+URGENT-WITHBOSS\".
9119 If optional argument TODO_ONLY is non-nil, only select lines that are
9120 also TODO lines."
9121 (interactive "P")
9122 (org-prepare-agenda-buffers (list (current-buffer)))
9123 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9125 (defvar org-cached-props nil)
9126 (defun org-cached-entry-get (pom property)
9127 (if (or (eq t org-use-property-inheritance)
9128 (and (stringp org-use-property-inheritance)
9129 (string-match org-use-property-inheritance property))
9130 (and (listp org-use-property-inheritance)
9131 (member property org-use-property-inheritance)))
9132 ;; Caching is not possible, check it directly
9133 (org-entry-get pom property 'inherit)
9134 ;; Get all properties, so that we can do complicated checks easily
9135 (cdr (assoc property (or org-cached-props
9136 (setq org-cached-props
9137 (org-entry-properties pom)))))))
9139 (defun org-global-tags-completion-table (&optional files)
9140 "Return the list of all tags in all agenda buffer/files."
9141 (save-excursion
9142 (org-uniquify
9143 (delq nil
9144 (apply 'append
9145 (mapcar
9146 (lambda (file)
9147 (set-buffer (find-file-noselect file))
9148 (append (org-get-buffer-tags)
9149 (mapcar (lambda (x) (if (stringp (car-safe x))
9150 (list (car-safe x)) nil))
9151 org-tag-alist)))
9152 (if (and files (car files))
9153 files
9154 (org-agenda-files))))))))
9156 (defun org-make-tags-matcher (match)
9157 "Create the TAGS//TODO matcher form for the selection string MATCH."
9158 ;; todo-only is scoped dynamically into this function, and the function
9159 ;; may change it it the matcher asksk for it.
9160 (unless match
9161 ;; Get a new match request, with completion
9162 (let ((org-last-tags-completion-table
9163 (org-global-tags-completion-table)))
9164 (setq match (completing-read
9165 "Match: " 'org-tags-completion-function nil nil nil
9166 'org-tags-history))))
9168 ;; Parse the string and create a lisp form
9169 (let ((match0 match)
9170 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9171 minus tag mm
9172 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9173 orterms term orlist re-p str-p level-p level-op
9174 prop-p pn pv po cat-p gv)
9175 (if (string-match "/+" match)
9176 ;; match contains also a todo-matching request
9177 (progn
9178 (setq tagsmatch (substring match 0 (match-beginning 0))
9179 todomatch (substring match (match-end 0)))
9180 (if (string-match "^!" todomatch)
9181 (setq todo-only t todomatch (substring todomatch 1)))
9182 (if (string-match "^\\s-*$" todomatch)
9183 (setq todomatch nil)))
9184 ;; only matching tags
9185 (setq tagsmatch match todomatch nil))
9187 ;; Make the tags matcher
9188 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9189 (setq tagsmatcher t)
9190 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9191 (while (setq term (pop orterms))
9192 (while (and (equal (substring term -1) "\\") orterms)
9193 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9194 (while (string-match re term)
9195 (setq minus (and (match-end 1)
9196 (equal (match-string 1 term) "-"))
9197 tag (match-string 2 term)
9198 re-p (equal (string-to-char tag) ?{)
9199 level-p (match-end 4)
9200 prop-p (match-end 5)
9201 mm (cond
9202 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9203 (level-p
9204 (setq level-op (org-op-to-function (match-string 3 term)))
9205 `(,level-op level ,(string-to-number
9206 (match-string 4 term))))
9207 (prop-p
9208 (setq pn (match-string 5 term)
9209 po (match-string 6 term)
9210 pv (match-string 7 term)
9211 cat-p (equal pn "CATEGORY")
9212 re-p (equal (string-to-char pv) ?{)
9213 str-p (equal (string-to-char pv) ?\")
9214 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9215 (setq po (org-op-to-function po str-p))
9216 (if (equal pn "CATEGORY")
9217 (setq gv '(get-text-property (point) 'org-category))
9218 (setq gv `(org-cached-entry-get nil ,pn)))
9219 (if re-p
9220 (if (eq po 'org<>)
9221 `(not (string-match ,pv (or ,gv "")))
9222 `(string-match ,pv (or ,gv "")))
9223 (if str-p
9224 `(,po (or ,gv "") ,pv)
9225 `(,po (string-to-number (or ,gv ""))
9226 ,(string-to-number pv) ))))
9227 (t `(member ,(downcase tag) tags-list)))
9228 mm (if minus (list 'not mm) mm)
9229 term (substring term (match-end 0)))
9230 (push mm tagsmatcher))
9231 (push (if (> (length tagsmatcher) 1)
9232 (cons 'and tagsmatcher)
9233 (car tagsmatcher))
9234 orlist)
9235 (setq tagsmatcher nil))
9236 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9237 (setq tagsmatcher
9238 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9239 ;; Make the todo matcher
9240 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9241 (setq todomatcher t)
9242 (setq orterms (org-split-string todomatch "|") orlist nil)
9243 (while (setq term (pop orterms))
9244 (while (string-match re term)
9245 (setq minus (and (match-end 1)
9246 (equal (match-string 1 term) "-"))
9247 kwd (match-string 2 term)
9248 re-p (equal (string-to-char kwd) ?{)
9249 term (substring term (match-end 0))
9250 mm (if re-p
9251 `(string-match ,(substring kwd 1 -1) todo)
9252 (list 'equal 'todo kwd))
9253 mm (if minus (list 'not mm) mm))
9254 (push mm todomatcher))
9255 (push (if (> (length todomatcher) 1)
9256 (cons 'and todomatcher)
9257 (car todomatcher))
9258 orlist)
9259 (setq todomatcher nil))
9260 (setq todomatcher (if (> (length orlist) 1)
9261 (cons 'or orlist) (car orlist))))
9263 ;; Return the string and lisp forms of the matcher
9264 (setq matcher (if todomatcher
9265 (list 'and tagsmatcher todomatcher)
9266 tagsmatcher))
9267 (cons match0 matcher)))
9269 (defun org-op-to-function (op &optional stringp)
9270 (setq op
9271 (cond
9272 ((equal op "<" ) '(< string< ))
9273 ((equal op ">" ) '(> org-string> ))
9274 ((member op '("<=" "=<")) '(<= org-string<= ))
9275 ((member op '(">=" "=>")) '(>= org-string>= ))
9276 ((member op '("=" "==")) '(= string= ))
9277 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9278 (nth (if stringp 1 0) op))
9280 (defun org<> (a b) (not (= a b)))
9281 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9282 (defun org-string>= (a b) (not (string< a b)))
9283 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9284 (defun org-string<> (a b) (not (string= a b)))
9286 (defun org-match-any-p (re list)
9287 "Does re match any element of list?"
9288 (setq list (mapcar (lambda (x) (string-match re x)) list))
9289 (delq nil list))
9291 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9292 (defvar org-tags-overlay (org-make-overlay 1 1))
9293 (org-detach-overlay org-tags-overlay)
9295 (defun org-get-tags-at (&optional pos)
9296 "Get a list of all headline tags applicable at POS.
9297 POS defaults to point. If tags are inherited, the list contains
9298 the targets in the same sequence as the headlines appear, i.e.
9299 sthe tags of the current headline come last."
9300 (interactive)
9301 (let (tags ltags lastpos parent)
9302 (save-excursion
9303 (save-restriction
9304 (widen)
9305 (goto-char (or pos (point)))
9306 (save-match-data
9307 (condition-case nil
9308 (progn
9309 (org-back-to-heading t)
9310 (while (not (equal lastpos (point)))
9311 (setq lastpos (point))
9312 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9313 (setq ltags (org-split-string
9314 (org-match-string-no-properties 1) ":"))
9315 (setq tags (append (org-remove-uniherited-tags ltags)
9316 tags)))
9317 (or org-use-tag-inheritance (error ""))
9318 (org-up-heading-all 1)
9319 (setq parent t)))
9320 (error nil))))
9321 tags)))
9323 (defun org-toggle-tag (tag &optional onoff)
9324 "Toggle the tag TAG for the current line.
9325 If ONOFF is `on' or `off', don't toggle but set to this state."
9326 (unless (org-on-heading-p t) (error "Not on headling"))
9327 (let (res current)
9328 (save-excursion
9329 (beginning-of-line)
9330 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9331 (point-at-eol) t)
9332 (progn
9333 (setq current (match-string 1))
9334 (replace-match ""))
9335 (setq current ""))
9336 (setq current (nreverse (org-split-string current ":")))
9337 (cond
9338 ((eq onoff 'on)
9339 (setq res t)
9340 (or (member tag current) (push tag current)))
9341 ((eq onoff 'off)
9342 (or (not (member tag current)) (setq current (delete tag current))))
9343 (t (if (member tag current)
9344 (setq current (delete tag current))
9345 (setq res t)
9346 (push tag current))))
9347 (end-of-line 1)
9348 (if current
9349 (progn
9350 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9351 (org-set-tags nil t))
9352 (delete-horizontal-space))
9353 (run-hooks 'org-after-tags-change-hook))
9354 res))
9356 (defun org-align-tags-here (to-col)
9357 ;; Assumes that this is a headline
9358 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9359 (beginning-of-line 1)
9360 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9361 (< pos (match-beginning 2)))
9362 (progn
9363 (setq tags-l (- (match-end 2) (match-beginning 2)))
9364 (goto-char (match-beginning 1))
9365 (insert " ")
9366 (delete-region (point) (1+ (match-beginning 2)))
9367 (setq ncol (max (1+ (current-column))
9368 (1+ col)
9369 (if (> to-col 0)
9370 to-col
9371 (- (abs to-col) tags-l))))
9372 (setq p (point))
9373 (insert (make-string (- ncol (current-column)) ?\ ))
9374 (setq ncol (current-column))
9375 (tabify p (point-at-eol))
9376 (org-move-to-column (min ncol col) t))
9377 (goto-char pos))))
9379 (defun org-set-tags (&optional arg just-align)
9380 "Set the tags for the current headline.
9381 With prefix ARG, realign all tags in headings in the current buffer."
9382 (interactive "P")
9383 (let* ((re (concat "^" outline-regexp))
9384 (current (org-get-tags-string))
9385 (col (current-column))
9386 (org-setting-tags t)
9387 table current-tags inherited-tags ; computed below when needed
9388 tags p0 c0 c1 rpl)
9389 (if arg
9390 (save-excursion
9391 (goto-char (point-min))
9392 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9393 (while (re-search-forward re nil t)
9394 (org-set-tags nil t)
9395 (end-of-line 1)))
9396 (message "All tags realigned to column %d" org-tags-column))
9397 (if just-align
9398 (setq tags current)
9399 ;; Get a new set of tags from the user
9400 (save-excursion
9401 (setq table (or org-tag-alist (org-get-buffer-tags))
9402 org-last-tags-completion-table table
9403 current-tags (org-split-string current ":")
9404 inherited-tags (nreverse
9405 (nthcdr (length current-tags)
9406 (nreverse (org-get-tags-at))))
9407 tags
9408 (if (or (eq t org-use-fast-tag-selection)
9409 (and org-use-fast-tag-selection
9410 (delq nil (mapcar 'cdr table))))
9411 (org-fast-tag-selection
9412 current-tags inherited-tags table
9413 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9414 (let ((org-add-colon-after-tag-completion t))
9415 (org-trim
9416 (org-without-partial-completion
9417 (completing-read "Tags: " 'org-tags-completion-function
9418 nil nil current 'org-tags-history)))))))
9419 (while (string-match "[-+&]+" tags)
9420 ;; No boolean logic, just a list
9421 (setq tags (replace-match ":" t t tags))))
9423 (if (string-match "\\`[\t ]*\\'" tags)
9424 (setq tags "")
9425 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9426 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9428 ;; Insert new tags at the correct column
9429 (beginning-of-line 1)
9430 (cond
9431 ((and (equal current "") (equal tags "")))
9432 ((re-search-forward
9433 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9434 (point-at-eol) t)
9435 (if (equal tags "")
9436 (setq rpl "")
9437 (goto-char (match-beginning 0))
9438 (setq c0 (current-column) p0 (point)
9439 c1 (max (1+ c0) (if (> org-tags-column 0)
9440 org-tags-column
9441 (- (- org-tags-column) (length tags))))
9442 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9443 (replace-match rpl t t)
9444 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9445 tags)
9446 (t (error "Tags alignment failed")))
9447 (org-move-to-column col)
9448 (unless just-align
9449 (run-hooks 'org-after-tags-change-hook)))))
9451 (defun org-change-tag-in-region (beg end tag off)
9452 "Add or remove TAG for each entry in the region.
9453 This works in the agenda, and also in an org-mode buffer."
9454 (interactive
9455 (list (region-beginning) (region-end)
9456 (let ((org-last-tags-completion-table
9457 (if (org-mode-p)
9458 (org-get-buffer-tags)
9459 (org-global-tags-completion-table))))
9460 (completing-read
9461 "Tag: " 'org-tags-completion-function nil nil nil
9462 'org-tags-history))
9463 (progn
9464 (message "[s]et or [r]emove? ")
9465 (equal (read-char-exclusive) ?r))))
9466 (if (fboundp 'deactivate-mark) (deactivate-mark))
9467 (let ((agendap (equal major-mode 'org-agenda-mode))
9468 l1 l2 m buf pos newhead (cnt 0))
9469 (goto-char end)
9470 (setq l2 (1- (org-current-line)))
9471 (goto-char beg)
9472 (setq l1 (org-current-line))
9473 (loop for l from l1 to l2 do
9474 (goto-line l)
9475 (setq m (get-text-property (point) 'org-hd-marker))
9476 (when (or (and (org-mode-p) (org-on-heading-p))
9477 (and agendap m))
9478 (setq buf (if agendap (marker-buffer m) (current-buffer))
9479 pos (if agendap m (point)))
9480 (with-current-buffer buf
9481 (save-excursion
9482 (save-restriction
9483 (goto-char pos)
9484 (setq cnt (1+ cnt))
9485 (org-toggle-tag tag (if off 'off 'on))
9486 (setq newhead (org-get-heading)))))
9487 (and agendap (org-agenda-change-all-lines newhead m))))
9488 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9490 (defun org-tags-completion-function (string predicate &optional flag)
9491 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9492 (confirm (lambda (x) (stringp (car x)))))
9493 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9494 (setq s1 (match-string 1 string)
9495 s2 (match-string 2 string))
9496 (setq s1 "" s2 string))
9497 (cond
9498 ((eq flag nil)
9499 ;; try completion
9500 (setq rtn (try-completion s2 ctable confirm))
9501 (if (stringp rtn)
9502 (setq rtn
9503 (concat s1 s2 (substring rtn (length s2))
9504 (if (and org-add-colon-after-tag-completion
9505 (assoc rtn ctable))
9506 ":" ""))))
9507 rtn)
9508 ((eq flag t)
9509 ;; all-completions
9510 (all-completions s2 ctable confirm)
9512 ((eq flag 'lambda)
9513 ;; exact match?
9514 (assoc s2 ctable)))
9517 (defun org-fast-tag-insert (kwd tags face &optional end)
9518 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9519 (insert (format "%-12s" (concat kwd ":"))
9520 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9521 (or end "")))
9523 (defun org-fast-tag-show-exit (flag)
9524 (save-excursion
9525 (goto-line 3)
9526 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9527 (replace-match ""))
9528 (when flag
9529 (end-of-line 1)
9530 (org-move-to-column (- (window-width) 19) t)
9531 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9533 (defun org-set-current-tags-overlay (current prefix)
9534 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9535 (if (featurep 'xemacs)
9536 (org-overlay-display org-tags-overlay (concat prefix s)
9537 'secondary-selection)
9538 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9539 (org-overlay-display org-tags-overlay (concat prefix s)))))
9541 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9542 "Fast tag selection with single keys.
9543 CURRENT is the current list of tags in the headline, INHERITED is the
9544 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9545 possibly with grouping information. TODO-TABLE is a similar table with
9546 TODO keywords, should these have keys assigned to them.
9547 If the keys are nil, a-z are automatically assigned.
9548 Returns the new tags string, or nil to not change the current settings."
9549 (let* ((fulltable (append table todo-table))
9550 (maxlen (apply 'max (mapcar
9551 (lambda (x)
9552 (if (stringp (car x)) (string-width (car x)) 0))
9553 fulltable)))
9554 (buf (current-buffer))
9555 (expert (eq org-fast-tag-selection-single-key 'expert))
9556 (buffer-tags nil)
9557 (fwidth (+ maxlen 3 1 3))
9558 (ncol (/ (- (window-width) 4) fwidth))
9559 (i-face 'org-done)
9560 (c-face 'org-todo)
9561 tg cnt e c char c1 c2 ntable tbl rtn
9562 ov-start ov-end ov-prefix
9563 (exit-after-next org-fast-tag-selection-single-key)
9564 (done-keywords org-done-keywords)
9565 groups ingroup)
9566 (save-excursion
9567 (beginning-of-line 1)
9568 (if (looking-at
9569 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9570 (setq ov-start (match-beginning 1)
9571 ov-end (match-end 1)
9572 ov-prefix "")
9573 (setq ov-start (1- (point-at-eol))
9574 ov-end (1+ ov-start))
9575 (skip-chars-forward "^\n\r")
9576 (setq ov-prefix
9577 (concat
9578 (buffer-substring (1- (point)) (point))
9579 (if (> (current-column) org-tags-column)
9581 (make-string (- org-tags-column (current-column)) ?\ ))))))
9582 (org-move-overlay org-tags-overlay ov-start ov-end)
9583 (save-window-excursion
9584 (if expert
9585 (set-buffer (get-buffer-create " *Org tags*"))
9586 (delete-other-windows)
9587 (split-window-vertically)
9588 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9589 (erase-buffer)
9590 (org-set-local 'org-done-keywords done-keywords)
9591 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9592 (org-fast-tag-insert "Current" current c-face "\n\n")
9593 (org-fast-tag-show-exit exit-after-next)
9594 (org-set-current-tags-overlay current ov-prefix)
9595 (setq tbl fulltable char ?a cnt 0)
9596 (while (setq e (pop tbl))
9597 (cond
9598 ((equal e '(:startgroup))
9599 (push '() groups) (setq ingroup t)
9600 (when (not (= cnt 0))
9601 (setq cnt 0)
9602 (insert "\n"))
9603 (insert "{ "))
9604 ((equal e '(:endgroup))
9605 (setq ingroup nil cnt 0)
9606 (insert "}\n"))
9608 (setq tg (car e) c2 nil)
9609 (if (cdr e)
9610 (setq c (cdr e))
9611 ;; automatically assign a character.
9612 (setq c1 (string-to-char
9613 (downcase (substring
9614 tg (if (= (string-to-char tg) ?@) 1 0)))))
9615 (if (or (rassoc c1 ntable) (rassoc c1 table))
9616 (while (or (rassoc char ntable) (rassoc char table))
9617 (setq char (1+ char)))
9618 (setq c2 c1))
9619 (setq c (or c2 char)))
9620 (if ingroup (push tg (car groups)))
9621 (setq tg (org-add-props tg nil 'face
9622 (cond
9623 ((not (assoc tg table))
9624 (org-get-todo-face tg))
9625 ((member tg current) c-face)
9626 ((member tg inherited) i-face)
9627 (t nil))))
9628 (if (and (= cnt 0) (not ingroup)) (insert " "))
9629 (insert "[" c "] " tg (make-string
9630 (- fwidth 4 (length tg)) ?\ ))
9631 (push (cons tg c) ntable)
9632 (when (= (setq cnt (1+ cnt)) ncol)
9633 (insert "\n")
9634 (if ingroup (insert " "))
9635 (setq cnt 0)))))
9636 (setq ntable (nreverse ntable))
9637 (insert "\n")
9638 (goto-char (point-min))
9639 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9640 (fit-window-to-buffer))
9641 (setq rtn
9642 (catch 'exit
9643 (while t
9644 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9645 (if groups " [!] no groups" " [!]groups")
9646 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9647 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9648 (cond
9649 ((= c ?\r) (throw 'exit t))
9650 ((= c ?!)
9651 (setq groups (not groups))
9652 (goto-char (point-min))
9653 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9654 ((= c ?\C-c)
9655 (if (not expert)
9656 (org-fast-tag-show-exit
9657 (setq exit-after-next (not exit-after-next)))
9658 (setq expert nil)
9659 (delete-other-windows)
9660 (split-window-vertically)
9661 (org-switch-to-buffer-other-window " *Org tags*")
9662 (and (fboundp 'fit-window-to-buffer)
9663 (fit-window-to-buffer))))
9664 ((or (= c ?\C-g)
9665 (and (= c ?q) (not (rassoc c ntable))))
9666 (org-detach-overlay org-tags-overlay)
9667 (setq quit-flag t))
9668 ((= c ?\ )
9669 (setq current nil)
9670 (if exit-after-next (setq exit-after-next 'now)))
9671 ((= c ?\t)
9672 (condition-case nil
9673 (setq tg (completing-read
9674 "Tag: "
9675 (or buffer-tags
9676 (with-current-buffer buf
9677 (org-get-buffer-tags)))))
9678 (quit (setq tg "")))
9679 (when (string-match "\\S-" tg)
9680 (add-to-list 'buffer-tags (list tg))
9681 (if (member tg current)
9682 (setq current (delete tg current))
9683 (push tg current)))
9684 (if exit-after-next (setq exit-after-next 'now)))
9685 ((setq e (rassoc c todo-table) tg (car e))
9686 (with-current-buffer buf
9687 (save-excursion (org-todo tg)))
9688 (if exit-after-next (setq exit-after-next 'now)))
9689 ((setq e (rassoc c ntable) tg (car e))
9690 (if (member tg current)
9691 (setq current (delete tg current))
9692 (loop for g in groups do
9693 (if (member tg g)
9694 (mapc (lambda (x)
9695 (setq current (delete x current)))
9696 g)))
9697 (push tg current))
9698 (if exit-after-next (setq exit-after-next 'now))))
9700 ;; Create a sorted list
9701 (setq current
9702 (sort current
9703 (lambda (a b)
9704 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9705 (if (eq exit-after-next 'now) (throw 'exit t))
9706 (goto-char (point-min))
9707 (beginning-of-line 2)
9708 (delete-region (point) (point-at-eol))
9709 (org-fast-tag-insert "Current" current c-face)
9710 (org-set-current-tags-overlay current ov-prefix)
9711 (while (re-search-forward
9712 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9713 (setq tg (match-string 1))
9714 (add-text-properties
9715 (match-beginning 1) (match-end 1)
9716 (list 'face
9717 (cond
9718 ((member tg current) c-face)
9719 ((member tg inherited) i-face)
9720 (t (get-text-property (match-beginning 1) 'face))))))
9721 (goto-char (point-min)))))
9722 (org-detach-overlay org-tags-overlay)
9723 (if rtn
9724 (mapconcat 'identity current ":")
9725 nil))))
9727 (defun org-get-tags-string ()
9728 "Get the TAGS string in the current headline."
9729 (unless (org-on-heading-p t)
9730 (error "Not on a heading"))
9731 (save-excursion
9732 (beginning-of-line 1)
9733 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9734 (org-match-string-no-properties 1)
9735 "")))
9737 (defun org-get-tags ()
9738 "Get the list of tags specified in the current headline."
9739 (org-split-string (org-get-tags-string) ":"))
9741 (defun org-get-buffer-tags ()
9742 "Get a table of all tags used in the buffer, for completion."
9743 (let (tags)
9744 (save-excursion
9745 (goto-char (point-min))
9746 (while (re-search-forward
9747 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9748 (when (equal (char-after (point-at-bol 0)) ?*)
9749 (mapc (lambda (x) (add-to-list 'tags x))
9750 (org-split-string (org-match-string-no-properties 1) ":")))))
9751 (mapcar 'list tags)))
9754 ;;;; Properties
9756 ;;; Setting and retrieving properties
9758 (defconst org-special-properties
9759 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9760 "TIMESTAMP" "TIMESTAMP_IA")
9761 "The special properties valid in Org-mode.
9763 These are properties that are not defined in the property drawer,
9764 but in some other way.")
9766 (defconst org-default-properties
9767 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9768 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9769 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9770 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9771 "Some properties that are used by Org-mode for various purposes.
9772 Being in this list makes sure that they are offered for completion.")
9774 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9775 "Regular expression matching the first line of a property drawer.")
9777 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9778 "Regular expression matching the first line of a property drawer.")
9780 (defun org-property-action ()
9781 "Do an action on properties."
9782 (interactive)
9783 (let (c)
9784 (org-at-property-p)
9785 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9786 (setq c (read-char-exclusive))
9787 (cond
9788 ((equal c ?s)
9789 (call-interactively 'org-set-property))
9790 ((equal c ?d)
9791 (call-interactively 'org-delete-property))
9792 ((equal c ?D)
9793 (call-interactively 'org-delete-property-globally))
9794 ((equal c ?c)
9795 (call-interactively 'org-compute-property-at-point))
9796 (t (error "No such property action %c" c)))))
9798 (defun org-at-property-p ()
9799 "Is the cursor in a property line?"
9800 ;; FIXME: Does not check if we are actually in the drawer.
9801 ;; FIXME: also returns true on any drawers.....
9802 ;; This is used by C-c C-c for property action.
9803 (save-excursion
9804 (beginning-of-line 1)
9805 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9807 (defun org-get-property-block (&optional beg end force)
9808 "Return the (beg . end) range of the body of the property drawer.
9809 BEG and END can be beginning and end of subtree, if not given
9810 they will be found.
9811 If the drawer does not exist and FORCE is non-nil, create the drawer."
9812 (catch 'exit
9813 (save-excursion
9814 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9815 (end (or end (progn (outline-next-heading) (point)))))
9816 (goto-char beg)
9817 (if (re-search-forward org-property-start-re end t)
9818 (setq beg (1+ (match-end 0)))
9819 (if force
9820 (save-excursion
9821 (org-insert-property-drawer)
9822 (setq end (progn (outline-next-heading) (point))))
9823 (throw 'exit nil))
9824 (goto-char beg)
9825 (if (re-search-forward org-property-start-re end t)
9826 (setq beg (1+ (match-end 0)))))
9827 (if (re-search-forward org-property-end-re end t)
9828 (setq end (match-beginning 0))
9829 (or force (throw 'exit nil))
9830 (goto-char beg)
9831 (setq end beg)
9832 (org-indent-line-function)
9833 (insert ":END:\n"))
9834 (cons beg end)))))
9836 (defun org-entry-properties (&optional pom which)
9837 "Get all properties of the entry at point-or-marker POM.
9838 This includes the TODO keyword, the tags, time strings for deadline,
9839 scheduled, and clocking, and any additional properties defined in the
9840 entry. The return value is an alist, keys may occur multiple times
9841 if the property key was used several times.
9842 POM may also be nil, in which case the current entry is used.
9843 If WHICH is nil or `all', get all properties. If WHICH is
9844 `special' or `standard', only get that subclass."
9845 (setq which (or which 'all))
9846 (org-with-point-at pom
9847 (let ((clockstr (substring org-clock-string 0 -1))
9848 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9849 beg end range props sum-props key value string clocksum)
9850 (save-excursion
9851 (when (condition-case nil (org-back-to-heading t) (error nil))
9852 (setq beg (point))
9853 (setq sum-props (get-text-property (point) 'org-summaries))
9854 (setq clocksum (get-text-property (point) :org-clock-minutes))
9855 (outline-next-heading)
9856 (setq end (point))
9857 (when (memq which '(all special))
9858 ;; Get the special properties, like TODO and tags
9859 (goto-char beg)
9860 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9861 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9862 (when (looking-at org-priority-regexp)
9863 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9864 (when (and (setq value (org-get-tags-string))
9865 (string-match "\\S-" value))
9866 (push (cons "TAGS" value) props))
9867 (when (setq value (org-get-tags-at))
9868 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9869 props))
9870 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9871 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9872 string (if (equal key clockstr)
9873 (org-no-properties
9874 (org-trim
9875 (buffer-substring
9876 (match-beginning 3) (goto-char (point-at-eol)))))
9877 (substring (org-match-string-no-properties 3) 1 -1)))
9878 (unless key
9879 (if (= (char-after (match-beginning 3)) ?\[)
9880 (setq key "TIMESTAMP_IA")
9881 (setq key "TIMESTAMP")))
9882 (when (or (equal key clockstr) (not (assoc key props)))
9883 (push (cons key string) props)))
9887 (when (memq which '(all standard))
9888 ;; Get the standard properties, like :PORP: ...
9889 (setq range (org-get-property-block beg end))
9890 (when range
9891 (goto-char (car range))
9892 (while (re-search-forward
9893 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9894 (cdr range) t)
9895 (setq key (org-match-string-no-properties 1)
9896 value (org-trim (or (org-match-string-no-properties 2) "")))
9897 (unless (member key excluded)
9898 (push (cons key (or value "")) props)))))
9899 (if clocksum
9900 (push (cons "CLOCKSUM"
9901 (org-columns-number-to-string (/ (float clocksum) 60.)
9902 'add_times))
9903 props))
9904 (append sum-props (nreverse props)))))))
9906 (defun org-entry-get (pom property &optional inherit)
9907 "Get value of PROPERTY for entry at point-or-marker POM.
9908 If INHERIT is non-nil and the entry does not have the property,
9909 then also check higher levels of the hierarchy.
9910 If INHERIT is the symbol `selective', use inheritance only if the setting
9911 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9912 If the property is present but empty, the return value is the empty string.
9913 If the property is not present at all, nil is returned."
9914 (org-with-point-at pom
9915 (if (and inherit (if (eq inherit 'selective)
9916 (org-property-inherit-p property)
9918 (org-entry-get-with-inheritance property)
9919 (if (member property org-special-properties)
9920 ;; We need a special property. Use brute force, get all properties.
9921 (cdr (assoc property (org-entry-properties nil 'special)))
9922 (let ((range (org-get-property-block)))
9923 (if (and range
9924 (goto-char (car range))
9925 (re-search-forward
9926 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9927 (cdr range) t))
9928 ;; Found the property, return it.
9929 (if (match-end 1)
9930 (org-match-string-no-properties 1)
9931 "")))))))
9933 (defun org-property-or-variable-value (var &optional inherit)
9934 "Check if there is a property fixing the value of VAR.
9935 If yes, return this value. If not, return the current value of the variable."
9936 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9937 (if (and prop (stringp prop) (string-match "\\S-" prop))
9938 (read prop)
9939 (symbol-value var))))
9941 (defun org-entry-delete (pom property)
9942 "Delete the property PROPERTY from entry at point-or-marker POM."
9943 (org-with-point-at pom
9944 (if (member property org-special-properties)
9945 nil ; cannot delete these properties.
9946 (let ((range (org-get-property-block)))
9947 (if (and range
9948 (goto-char (car range))
9949 (re-search-forward
9950 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9951 (cdr range) t))
9952 (progn
9953 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9955 nil)))))
9957 ;; Multi-values properties are properties that contain multiple values
9958 ;; These values are assumed to be single words, separated by whitespace.
9959 (defun org-entry-add-to-multivalued-property (pom property value)
9960 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9961 (let* ((old (org-entry-get pom property))
9962 (values (and old (org-split-string old "[ \t]"))))
9963 (unless (member value values)
9964 (setq values (cons value values))
9965 (org-entry-put pom property
9966 (mapconcat 'identity values " ")))))
9968 (defun org-entry-remove-from-multivalued-property (pom property value)
9969 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9970 (let* ((old (org-entry-get pom property))
9971 (values (and old (org-split-string old "[ \t]"))))
9972 (when (member value values)
9973 (setq values (delete value values))
9974 (org-entry-put pom property
9975 (mapconcat 'identity values " ")))))
9977 (defun org-entry-member-in-multivalued-property (pom property value)
9978 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9979 (let* ((old (org-entry-get pom property))
9980 (values (and old (org-split-string old "[ \t]"))))
9981 (member value values)))
9983 (defvar org-entry-property-inherited-from (make-marker))
9985 (defun org-entry-get-with-inheritance (property)
9986 "Get entry property, and search higher levels if not present."
9987 (let (tmp)
9988 (save-excursion
9989 (save-restriction
9990 (widen)
9991 (catch 'ex
9992 (while t
9993 (when (setq tmp (org-entry-get nil property))
9994 (org-back-to-heading t)
9995 (move-marker org-entry-property-inherited-from (point))
9996 (throw 'ex tmp))
9997 (or (org-up-heading-safe) (throw 'ex nil)))))
9998 (or tmp
9999 (cdr (assoc property org-file-properties))
10000 (cdr (assoc property org-global-properties))
10001 (cdr (assoc property org-global-properties-fixed))))))
10003 (defun org-entry-put (pom property value)
10004 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10005 (org-with-point-at pom
10006 (org-back-to-heading t)
10007 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10008 range)
10009 (cond
10010 ((equal property "TODO")
10011 (when (and (stringp value) (string-match "\\S-" value)
10012 (not (member value org-todo-keywords-1)))
10013 (error "\"%s\" is not a valid TODO state" value))
10014 (if (or (not value)
10015 (not (string-match "\\S-" value)))
10016 (setq value 'none))
10017 (org-todo value)
10018 (org-set-tags nil 'align))
10019 ((equal property "PRIORITY")
10020 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10021 (string-to-char value) ?\ ))
10022 (org-set-tags nil 'align))
10023 ((equal property "SCHEDULED")
10024 (if (re-search-forward org-scheduled-time-regexp end t)
10025 (cond
10026 ((eq value 'earlier) (org-timestamp-change -1 'day))
10027 ((eq value 'later) (org-timestamp-change 1 'day))
10028 (t (call-interactively 'org-schedule)))
10029 (call-interactively 'org-schedule)))
10030 ((equal property "DEADLINE")
10031 (if (re-search-forward org-deadline-time-regexp end t)
10032 (cond
10033 ((eq value 'earlier) (org-timestamp-change -1 'day))
10034 ((eq value 'later) (org-timestamp-change 1 'day))
10035 (t (call-interactively 'org-deadline)))
10036 (call-interactively 'org-deadline)))
10037 ((member property org-special-properties)
10038 (error "The %s property can not yet be set with `org-entry-put'"
10039 property))
10040 (t ; a non-special property
10041 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10042 (setq range (org-get-property-block beg end 'force))
10043 (goto-char (car range))
10044 (if (re-search-forward
10045 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10046 (progn
10047 (delete-region (match-beginning 1) (match-end 1))
10048 (goto-char (match-beginning 1)))
10049 (goto-char (cdr range))
10050 (insert "\n")
10051 (backward-char 1)
10052 (org-indent-line-function)
10053 (insert ":" property ":"))
10054 (and value (insert " " value))
10055 (org-indent-line-function)))))))
10057 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10058 "Get all property keys in the current buffer.
10059 With INCLUDE-SPECIALS, also list the special properties that relect things
10060 like tags and TODO state.
10061 With INCLUDE-DEFAULTS, also include properties that has special meaning
10062 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10063 With INCLUDE-COLUMNS, also include property names given in COLUMN
10064 formats in the current buffer."
10065 (let (rtn range cfmt cols s p)
10066 (save-excursion
10067 (save-restriction
10068 (widen)
10069 (goto-char (point-min))
10070 (while (re-search-forward org-property-start-re nil t)
10071 (setq range (org-get-property-block))
10072 (goto-char (car range))
10073 (while (re-search-forward
10074 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10075 (cdr range) t)
10076 (add-to-list 'rtn (org-match-string-no-properties 1)))
10077 (outline-next-heading))))
10079 (when include-specials
10080 (setq rtn (append org-special-properties rtn)))
10082 (when include-defaults
10083 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10085 (when include-columns
10086 (save-excursion
10087 (save-restriction
10088 (widen)
10089 (goto-char (point-min))
10090 (while (re-search-forward
10091 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10092 nil t)
10093 (setq cfmt (match-string 2) s 0)
10094 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10095 cfmt s)
10096 (setq s (match-end 0)
10097 p (match-string 1 cfmt))
10098 (unless (or (equal p "ITEM")
10099 (member p org-special-properties))
10100 (add-to-list 'rtn (match-string 1 cfmt))))))))
10102 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10104 (defun org-property-values (key)
10105 "Return a list of all values of property KEY."
10106 (save-excursion
10107 (save-restriction
10108 (widen)
10109 (goto-char (point-min))
10110 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10111 values)
10112 (while (re-search-forward re nil t)
10113 (add-to-list 'values (org-trim (match-string 1))))
10114 (delete "" values)))))
10116 (defun org-insert-property-drawer ()
10117 "Insert a property drawer into the current entry."
10118 (interactive)
10119 (org-back-to-heading t)
10120 (looking-at outline-regexp)
10121 (let ((indent (- (match-end 0)(match-beginning 0)))
10122 (beg (point))
10123 (re (concat "^[ \t]*" org-keyword-time-regexp))
10124 end hiddenp)
10125 (outline-next-heading)
10126 (setq end (point))
10127 (goto-char beg)
10128 (while (re-search-forward re end t))
10129 (setq hiddenp (org-invisible-p))
10130 (end-of-line 1)
10131 (and (equal (char-after) ?\n) (forward-char 1))
10132 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10133 (beginning-of-line 2))
10134 (org-skip-over-state-notes)
10135 (skip-chars-backward " \t\n\r")
10136 (if (eq (char-before) ?*) (forward-char 1))
10137 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10138 (beginning-of-line 0)
10139 (org-indent-to-column indent)
10140 (beginning-of-line 2)
10141 (org-indent-to-column indent)
10142 (beginning-of-line 0)
10143 (if hiddenp
10144 (save-excursion
10145 (org-back-to-heading t)
10146 (hide-entry))
10147 (org-flag-drawer t))))
10149 (defun org-set-property (property value)
10150 "In the current entry, set PROPERTY to VALUE.
10151 When called interactively, this will prompt for a property name, offering
10152 completion on existing and default properties. And then it will prompt
10153 for a value, offering competion either on allowed values (via an inherited
10154 xxx_ALL property) or on existing values in other instances of this property
10155 in the current file."
10156 (interactive
10157 (let* ((completion-ignore-case t)
10158 (keys (org-buffer-property-keys nil t t))
10159 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10160 (prop (if (member prop0 keys)
10161 prop0
10162 (or (cdr (assoc (downcase prop0)
10163 (mapcar (lambda (x) (cons (downcase x) x))
10164 keys)))
10165 prop0)))
10166 (cur (org-entry-get nil prop))
10167 (allowed (org-property-get-allowed-values nil prop 'table))
10168 (existing (mapcar 'list (org-property-values prop)))
10169 (val (if allowed
10170 (org-completing-read "Value: " allowed nil 'req-match)
10171 (org-completing-read
10172 (concat "Value" (if (and cur (string-match "\\S-" cur))
10173 (concat "[" cur "]") "")
10174 ": ")
10175 existing nil nil "" nil cur))))
10176 (list prop (if (equal val "") cur val))))
10177 (unless (equal (org-entry-get nil property) value)
10178 (org-entry-put nil property value)))
10180 (defun org-delete-property (property)
10181 "In the current entry, delete PROPERTY."
10182 (interactive
10183 (let* ((completion-ignore-case t)
10184 (prop (completing-read
10185 "Property: " (org-entry-properties nil 'standard))))
10186 (list prop)))
10187 (message "Property %s %s" property
10188 (if (org-entry-delete nil property)
10189 "deleted"
10190 "was not present in the entry")))
10192 (defun org-delete-property-globally (property)
10193 "Remove PROPERTY globally, from all entries."
10194 (interactive
10195 (let* ((completion-ignore-case t)
10196 (prop (completing-read
10197 "Globally remove property: "
10198 (mapcar 'list (org-buffer-property-keys)))))
10199 (list prop)))
10200 (save-excursion
10201 (save-restriction
10202 (widen)
10203 (goto-char (point-min))
10204 (let ((cnt 0))
10205 (while (re-search-forward
10206 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10207 nil t)
10208 (setq cnt (1+ cnt))
10209 (replace-match ""))
10210 (message "Property \"%s\" removed from %d entries" property cnt)))))
10212 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10214 (defun org-compute-property-at-point ()
10215 "Compute the property at point.
10216 This looks for an enclosing column format, extracts the operator and
10217 then applies it to the proerty in the column format's scope."
10218 (interactive)
10219 (unless (org-at-property-p)
10220 (error "Not at a property"))
10221 (let ((prop (org-match-string-no-properties 2)))
10222 (org-columns-get-format-and-top-level)
10223 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10224 (error "No operator defined for property %s" prop))
10225 (org-columns-compute prop)))
10227 (defun org-property-get-allowed-values (pom property &optional table)
10228 "Get allowed values for the property PROPERTY.
10229 When TABLE is non-nil, return an alist that can directly be used for
10230 completion."
10231 (let (vals)
10232 (cond
10233 ((equal property "TODO")
10234 (setq vals (org-with-point-at pom
10235 (append org-todo-keywords-1 '("")))))
10236 ((equal property "PRIORITY")
10237 (let ((n org-lowest-priority))
10238 (while (>= n org-highest-priority)
10239 (push (char-to-string n) vals)
10240 (setq n (1- n)))))
10241 ((member property org-special-properties))
10243 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10245 (when (and vals (string-match "\\S-" vals))
10246 (setq vals (car (read-from-string (concat "(" vals ")"))))
10247 (setq vals (mapcar (lambda (x)
10248 (cond ((stringp x) x)
10249 ((numberp x) (number-to-string x))
10250 ((symbolp x) (symbol-name x))
10251 (t "???")))
10252 vals)))))
10253 (if table (mapcar 'list vals) vals)))
10255 (defun org-property-previous-allowed-value (&optional previous)
10256 "Switch to the next allowed value for this property."
10257 (interactive)
10258 (org-property-next-allowed-value t))
10260 (defun org-property-next-allowed-value (&optional previous)
10261 "Switch to the next allowed value for this property."
10262 (interactive)
10263 (unless (org-at-property-p)
10264 (error "Not at a property"))
10265 (let* ((key (match-string 2))
10266 (value (match-string 3))
10267 (allowed (or (org-property-get-allowed-values (point) key)
10268 (and (member value '("[ ]" "[-]" "[X]"))
10269 '("[ ]" "[X]"))))
10270 nval)
10271 (unless allowed
10272 (error "Allowed values for this property have not been defined"))
10273 (if previous (setq allowed (reverse allowed)))
10274 (if (member value allowed)
10275 (setq nval (car (cdr (member value allowed)))))
10276 (setq nval (or nval (car allowed)))
10277 (if (equal nval value)
10278 (error "Only one allowed value for this property"))
10279 (org-at-property-p)
10280 (replace-match (concat " :" key ": " nval) t t)
10281 (org-indent-line-function)
10282 (beginning-of-line 1)
10283 (skip-chars-forward " \t")))
10285 (defun org-find-entry-with-id (ident)
10286 "Locate the entry that contains the ID property with exact value IDENT.
10287 IDENT can be a string, a symbol or a number, this function will search for
10288 the string representation of it.
10289 Return the position where this entry starts, or nil if there is no such entry."
10290 (let ((id (cond
10291 ((stringp ident) ident)
10292 ((symbol-name ident) (symbol-name ident))
10293 ((numberp ident) (number-to-string ident))
10294 (t (error "IDENT %s must be a string, symbol or number" ident))))
10295 (case-fold-search nil))
10296 (save-excursion
10297 (save-restriction
10298 (widen)
10299 (goto-char (point-min))
10300 (when (re-search-forward
10301 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10302 nil t)
10303 (org-back-to-heading)
10304 (point))))))
10306 ;;;; Timestamps
10308 (defvar org-last-changed-timestamp nil)
10309 (defvar org-time-was-given) ; dynamically scoped parameter
10310 (defvar org-end-time-was-given) ; dynamically scoped parameter
10311 (defvar org-ts-what) ; dynamically scoped parameter
10313 (defun org-time-stamp (arg)
10314 "Prompt for a date/time and insert a time stamp.
10315 If the user specifies a time like HH:MM, or if this command is called
10316 with a prefix argument, the time stamp will contain date and time.
10317 Otherwise, only the date will be included. All parts of a date not
10318 specified by the user will be filled in from the current date/time.
10319 So if you press just return without typing anything, the time stamp
10320 will represent the current date/time. If there is already a timestamp
10321 at the cursor, it will be modified."
10322 (interactive "P")
10323 (let* ((ts nil)
10324 (default-time
10325 ;; Default time is either today, or, when entering a range,
10326 ;; the range start.
10327 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10328 (save-excursion
10329 (re-search-backward
10330 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10331 (- (point) 20) t)))
10332 (apply 'encode-time (org-parse-time-string (match-string 1)))
10333 (current-time)))
10334 (default-input (and ts (org-get-compact-tod ts)))
10335 org-time-was-given org-end-time-was-given time)
10336 (cond
10337 ((and (org-at-timestamp-p)
10338 (eq last-command 'org-time-stamp)
10339 (eq this-command 'org-time-stamp))
10340 (insert "--")
10341 (setq time (let ((this-command this-command))
10342 (org-read-date arg 'totime nil nil default-time default-input)))
10343 (org-insert-time-stamp time (or org-time-was-given arg)))
10344 ((org-at-timestamp-p)
10345 (setq time (let ((this-command this-command))
10346 (org-read-date arg 'totime nil nil default-time default-input)))
10347 (when (org-at-timestamp-p) ; just to get the match data
10348 (replace-match "")
10349 (setq org-last-changed-timestamp
10350 (org-insert-time-stamp
10351 time (or org-time-was-given arg)
10352 nil nil nil (list org-end-time-was-given))))
10353 (message "Timestamp updated"))
10355 (setq time (let ((this-command this-command))
10356 (org-read-date arg 'totime nil nil default-time default-input)))
10357 (org-insert-time-stamp time (or org-time-was-given arg)
10358 nil nil nil (list org-end-time-was-given))))))
10360 ;; FIXME: can we use this for something else, like computing time differences?
10361 (defun org-get-compact-tod (s)
10362 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10363 (let* ((t1 (match-string 1 s))
10364 (h1 (string-to-number (match-string 2 s)))
10365 (m1 (string-to-number (match-string 3 s)))
10366 (t2 (and (match-end 4) (match-string 5 s)))
10367 (h2 (and t2 (string-to-number (match-string 6 s))))
10368 (m2 (and t2 (string-to-number (match-string 7 s))))
10369 dh dm)
10370 (if (not t2)
10372 (setq dh (- h2 h1) dm (- m2 m1))
10373 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10374 (concat t1 "+" (number-to-string dh)
10375 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10377 (defun org-time-stamp-inactive (&optional arg)
10378 "Insert an inactive time stamp.
10379 An inactive time stamp is enclosed in square brackets instead of angle
10380 brackets. It is inactive in the sense that it does not trigger agenda entries,
10381 does not link to the calendar and cannot be changed with the S-cursor keys.
10382 So these are more for recording a certain time/date."
10383 (interactive "P")
10384 (let (org-time-was-given org-end-time-was-given time)
10385 (setq time (org-read-date arg 'totime))
10386 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10387 nil nil (list org-end-time-was-given))))
10389 (defvar org-date-ovl (org-make-overlay 1 1))
10390 (org-overlay-put org-date-ovl 'face 'org-warning)
10391 (org-detach-overlay org-date-ovl)
10393 (defvar org-ans1) ; dynamically scoped parameter
10394 (defvar org-ans2) ; dynamically scoped parameter
10396 (defvar org-plain-time-of-day-regexp) ; defined below
10398 (defvar org-read-date-overlay nil)
10399 (defvar org-dcst nil) ; dynamically scoped
10401 (defun org-read-date (&optional with-time to-time from-string prompt
10402 default-time default-input)
10403 "Read a date, possibly a time, and make things smooth for the user.
10404 The prompt will suggest to enter an ISO date, but you can also enter anything
10405 which will at least partially be understood by `parse-time-string'.
10406 Unrecognized parts of the date will default to the current day, month, year,
10407 hour and minute. If this command is called to replace a timestamp at point,
10408 of to enter the second timestamp of a range, the default time is taken from the
10409 existing stamp. For example,
10410 3-2-5 --> 2003-02-05
10411 feb 15 --> currentyear-02-15
10412 sep 12 9 --> 2009-09-12
10413 12:45 --> today 12:45
10414 22 sept 0:34 --> currentyear-09-22 0:34
10415 12 --> currentyear-currentmonth-12
10416 Fri --> nearest Friday (today or later)
10417 etc.
10419 Furthermore you can specify a relative date by giving, as the *first* thing
10420 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10421 change in days weeks, months, years.
10422 With a single plus or minus, the date is relative to today. With a double
10423 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10424 +4d --> four days from today
10425 +4 --> same as above
10426 +2w --> two weeks from today
10427 ++5 --> five days from default date
10429 The function understands only English month and weekday abbreviations,
10430 but this can be configured with the variables `parse-time-months' and
10431 `parse-time-weekdays'.
10433 While prompting, a calendar is popped up - you can also select the
10434 date with the mouse (button 1). The calendar shows a period of three
10435 months. To scroll it to other months, use the keys `>' and `<'.
10436 If you don't like the calendar, turn it off with
10437 \(setq org-read-date-popup-calendar nil)
10439 With optional argument TO-TIME, the date will immediately be converted
10440 to an internal time.
10441 With an optional argument WITH-TIME, the prompt will suggest to also
10442 insert a time. Note that when WITH-TIME is not set, you can still
10443 enter a time, and this function will inform the calling routine about
10444 this change. The calling routine may then choose to change the format
10445 used to insert the time stamp into the buffer to include the time.
10446 With optional argument FROM-STRING, read from this string instead from
10447 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10448 the time/date that is used for everything that is not specified by the
10449 user."
10450 (require 'parse-time)
10451 (let* ((org-time-stamp-rounding-minutes
10452 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10453 (org-dcst org-display-custom-times)
10454 (ct (org-current-time))
10455 (def (or default-time ct))
10456 (defdecode (decode-time def))
10457 (dummy (progn
10458 (when (< (nth 2 defdecode) org-extend-today-until)
10459 (setcar (nthcdr 2 defdecode) -1)
10460 (setcar (nthcdr 1 defdecode) 59)
10461 (setq def (apply 'encode-time defdecode)
10462 defdecode (decode-time def)))))
10463 (calendar-move-hook nil)
10464 (calendar-view-diary-initially-flag nil)
10465 (view-diary-entries-initially nil)
10466 (calendar-view-holidays-initially-flag nil)
10467 (view-calendar-holidays-initially nil)
10468 (timestr (format-time-string
10469 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10470 (prompt (concat (if prompt (concat prompt " ") "")
10471 (format "Date+time [%s]: " timestr)))
10472 ans (org-ans0 "") org-ans1 org-ans2 final)
10474 (cond
10475 (from-string (setq ans from-string))
10476 (org-read-date-popup-calendar
10477 (save-excursion
10478 (save-window-excursion
10479 (calendar)
10480 (calendar-forward-day (- (time-to-days def)
10481 (calendar-absolute-from-gregorian
10482 (calendar-current-date))))
10483 (org-eval-in-calendar nil t)
10484 (let* ((old-map (current-local-map))
10485 (map (copy-keymap calendar-mode-map))
10486 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10487 (org-defkey map (kbd "RET") 'org-calendar-select)
10488 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10489 'org-calendar-select-mouse)
10490 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10491 'org-calendar-select-mouse)
10492 (org-defkey minibuffer-local-map [(meta shift left)]
10493 (lambda () (interactive)
10494 (org-eval-in-calendar '(calendar-backward-month 1))))
10495 (org-defkey minibuffer-local-map [(meta shift right)]
10496 (lambda () (interactive)
10497 (org-eval-in-calendar '(calendar-forward-month 1))))
10498 (org-defkey minibuffer-local-map [(meta shift up)]
10499 (lambda () (interactive)
10500 (org-eval-in-calendar '(calendar-backward-year 1))))
10501 (org-defkey minibuffer-local-map [(meta shift down)]
10502 (lambda () (interactive)
10503 (org-eval-in-calendar '(calendar-forward-year 1))))
10504 (org-defkey minibuffer-local-map [(shift up)]
10505 (lambda () (interactive)
10506 (org-eval-in-calendar '(calendar-backward-week 1))))
10507 (org-defkey minibuffer-local-map [(shift down)]
10508 (lambda () (interactive)
10509 (org-eval-in-calendar '(calendar-forward-week 1))))
10510 (org-defkey minibuffer-local-map [(shift left)]
10511 (lambda () (interactive)
10512 (org-eval-in-calendar '(calendar-backward-day 1))))
10513 (org-defkey minibuffer-local-map [(shift right)]
10514 (lambda () (interactive)
10515 (org-eval-in-calendar '(calendar-forward-day 1))))
10516 (org-defkey minibuffer-local-map ">"
10517 (lambda () (interactive)
10518 (org-eval-in-calendar '(scroll-calendar-left 1))))
10519 (org-defkey minibuffer-local-map "<"
10520 (lambda () (interactive)
10521 (org-eval-in-calendar '(scroll-calendar-right 1))))
10522 (unwind-protect
10523 (progn
10524 (use-local-map map)
10525 (add-hook 'post-command-hook 'org-read-date-display)
10526 (setq org-ans0 (read-string prompt default-input nil nil))
10527 ;; org-ans0: from prompt
10528 ;; org-ans1: from mouse click
10529 ;; org-ans2: from calendar motion
10530 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10531 (remove-hook 'post-command-hook 'org-read-date-display)
10532 (use-local-map old-map)
10533 (when org-read-date-overlay
10534 (org-delete-overlay org-read-date-overlay)
10535 (setq org-read-date-overlay nil)))))))
10537 (t ; Naked prompt only
10538 (unwind-protect
10539 (setq ans (read-string prompt default-input nil timestr))
10540 (when org-read-date-overlay
10541 (org-delete-overlay org-read-date-overlay)
10542 (setq org-read-date-overlay nil)))))
10544 (setq final (org-read-date-analyze ans def defdecode))
10546 (if to-time
10547 (apply 'encode-time final)
10548 (if (and (boundp 'org-time-was-given) org-time-was-given)
10549 (format "%04d-%02d-%02d %02d:%02d"
10550 (nth 5 final) (nth 4 final) (nth 3 final)
10551 (nth 2 final) (nth 1 final))
10552 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10553 (defvar def)
10554 (defvar defdecode)
10555 (defvar with-time)
10556 (defun org-read-date-display ()
10557 "Display the currrent date prompt interpretation in the minibuffer."
10558 (when org-read-date-display-live
10559 (when org-read-date-overlay
10560 (org-delete-overlay org-read-date-overlay))
10561 (let ((p (point)))
10562 (end-of-line 1)
10563 (while (not (equal (buffer-substring
10564 (max (point-min) (- (point) 4)) (point))
10565 " "))
10566 (insert " "))
10567 (goto-char p))
10568 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10569 " " (or org-ans1 org-ans2)))
10570 (org-end-time-was-given nil)
10571 (f (org-read-date-analyze ans def defdecode))
10572 (fmts (if org-dcst
10573 org-time-stamp-custom-formats
10574 org-time-stamp-formats))
10575 (fmt (if (or with-time
10576 (and (boundp 'org-time-was-given) org-time-was-given))
10577 (cdr fmts)
10578 (car fmts)))
10579 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10580 (when (and org-end-time-was-given
10581 (string-match org-plain-time-of-day-regexp txt))
10582 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10583 org-end-time-was-given
10584 (substring txt (match-end 0)))))
10585 (setq org-read-date-overlay
10586 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10587 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10589 (defun org-read-date-analyze (ans def defdecode)
10590 "Analyze the combined answer of the date prompt."
10591 ;; FIXME: cleanup and comment
10592 (let (delta deltan deltaw deltadef year month day
10593 hour minute second wday pm h2 m2 tl wday1
10594 iso-year iso-weekday iso-week iso-year iso-date)
10596 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10597 (setq ans "+0"))
10599 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10600 (setq ans (replace-match "" t t ans)
10601 deltan (car delta)
10602 deltaw (nth 1 delta)
10603 deltadef (nth 2 delta)))
10605 ;; Check if there is an iso week date in there
10606 ;; If yes, sore the info and ostpone interpreting it until the rest
10607 ;; of the parsing is done
10608 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10609 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10610 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10611 iso-week (string-to-number (match-string 2 ans)))
10612 (setq ans (replace-match "" t t ans)))
10614 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10615 (when (string-match
10616 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10617 (setq year (if (match-end 2)
10618 (string-to-number (match-string 2 ans))
10619 (string-to-number (format-time-string "%Y")))
10620 month (string-to-number (match-string 3 ans))
10621 day (string-to-number (match-string 4 ans)))
10622 (if (< year 100) (setq year (+ 2000 year)))
10623 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10624 t nil ans)))
10625 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10626 ;; If there is a time with am/pm, and *no* time without it, we convert
10627 ;; so that matching will be successful.
10628 (loop for i from 1 to 2 do ; twice, for end time as well
10629 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10630 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10631 (setq hour (string-to-number (match-string 1 ans))
10632 minute (if (match-end 3)
10633 (string-to-number (match-string 3 ans))
10635 pm (equal ?p
10636 (string-to-char (downcase (match-string 4 ans)))))
10637 (if (and (= hour 12) (not pm))
10638 (setq hour 0)
10639 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10640 (setq ans (replace-match (format "%02d:%02d" hour minute)
10641 t t ans))))
10643 ;; Check if a time range is given as a duration
10644 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10645 (setq hour (string-to-number (match-string 1 ans))
10646 h2 (+ hour (string-to-number (match-string 3 ans)))
10647 minute (string-to-number (match-string 2 ans))
10648 m2 (+ minute (if (match-end 5) (string-to-number
10649 (match-string 5 ans))0)))
10650 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10651 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10652 t t ans)))
10654 ;; Check if there is a time range
10655 (when (boundp 'org-end-time-was-given)
10656 (setq org-time-was-given nil)
10657 (when (and (string-match org-plain-time-of-day-regexp ans)
10658 (match-end 8))
10659 (setq org-end-time-was-given (match-string 8 ans))
10660 (setq ans (concat (substring ans 0 (match-beginning 7))
10661 (substring ans (match-end 7))))))
10663 (setq tl (parse-time-string ans)
10664 day (or (nth 3 tl) (nth 3 defdecode))
10665 month (or (nth 4 tl)
10666 (if (and org-read-date-prefer-future
10667 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10668 (1+ (nth 4 defdecode))
10669 (nth 4 defdecode)))
10670 year (or (nth 5 tl)
10671 (if (and org-read-date-prefer-future
10672 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10673 (1+ (nth 5 defdecode))
10674 (nth 5 defdecode)))
10675 hour (or (nth 2 tl) (nth 2 defdecode))
10676 minute (or (nth 1 tl) (nth 1 defdecode))
10677 second (or (nth 0 tl) 0)
10678 wday (nth 6 tl))
10680 ;; Special date definitions below
10681 (cond
10682 (iso-week
10683 ;; There was an iso week
10684 (setq year (or iso-year year)
10685 day (or iso-weekday wday 1)
10686 wday nil ; to make sure that the trigger below does not match
10687 iso-date (calendar-gregorian-from-absolute
10688 (calendar-absolute-from-iso
10689 (list iso-week day year))))
10690 ; FIXME: Should we also push ISO weeks into the future?
10691 ; (when (and org-read-date-prefer-future
10692 ; (not iso-year)
10693 ; (< (calendar-absolute-from-gregorian iso-date)
10694 ; (time-to-days (current-time))))
10695 ; (setq year (1+ year)
10696 ; iso-date (calendar-gregorian-from-absolute
10697 ; (calendar-absolute-from-iso
10698 ; (list iso-week day year)))))
10699 (setq month (car iso-date)
10700 year (nth 2 iso-date)
10701 day (nth 1 iso-date)))
10702 (deltan
10703 (unless deltadef
10704 (let ((now (decode-time (current-time))))
10705 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10706 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10707 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10708 ((equal deltaw "m") (setq month (+ month deltan)))
10709 ((equal deltaw "y") (setq year (+ year deltan)))))
10710 ((and wday (not (nth 3 tl)))
10711 ;; Weekday was given, but no day, so pick that day in the week
10712 ;; on or after the derived date.
10713 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10714 (unless (equal wday wday1)
10715 (setq day (+ day (% (- wday wday1 -7) 7))))))
10716 (if (and (boundp 'org-time-was-given)
10717 (nth 2 tl))
10718 (setq org-time-was-given t))
10719 (if (< year 100) (setq year (+ 2000 year)))
10720 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10721 (list second minute hour day month year)))
10723 (defvar parse-time-weekdays)
10725 (defun org-read-date-get-relative (s today default)
10726 "Check string S for special relative date string.
10727 TODAY and DEFAULT are internal times, for today and for a default.
10728 Return shift list (N what def-flag)
10729 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10730 N is the number of WHATs to shift.
10731 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10732 the DEFAULT date rather than TODAY."
10733 (when (and
10734 (string-match
10735 (concat
10736 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10737 "\\([0-9]+\\)?"
10738 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10739 "\\([ \t]\\|$\\)") s)
10740 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10741 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10742 (string-to-char (substring (match-string 1 s) -1))
10743 ?+))
10744 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10745 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10746 (what (if (match-end 3) (match-string 3 s) "d"))
10747 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10748 (date (if rel default today))
10749 (wday (nth 6 (decode-time date)))
10750 delta)
10751 (if wday1
10752 (progn
10753 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10754 (if (= dir ?-) (setq delta (- delta 7)))
10755 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10756 (list delta "d" rel))
10757 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10759 (defun org-eval-in-calendar (form &optional keepdate)
10760 "Eval FORM in the calendar window and return to current window.
10761 Also, store the cursor date in variable org-ans2."
10762 (let ((sw (selected-window)))
10763 (select-window (get-buffer-window "*Calendar*"))
10764 (eval form)
10765 (when (and (not keepdate) (calendar-cursor-to-date))
10766 (let* ((date (calendar-cursor-to-date))
10767 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10768 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10769 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10770 (select-window sw)))
10772 ; ;; Update the prompt to show new default date
10773 ; (save-excursion
10774 ; (goto-char (point-min))
10775 ; (when (and org-ans2
10776 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10777 ; (get-text-property (match-end 0) 'field))
10778 ; (let ((inhibit-read-only t))
10779 ; (replace-match (concat "[" org-ans2 "]") t t)
10780 ; (add-text-properties (point-min) (1+ (match-end 0))
10781 ; (text-properties-at (1+ (point-min)))))))))
10783 (defun org-calendar-select ()
10784 "Return to `org-read-date' with the date currently selected.
10785 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10786 (interactive)
10787 (when (calendar-cursor-to-date)
10788 (let* ((date (calendar-cursor-to-date))
10789 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10790 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10791 (if (active-minibuffer-window) (exit-minibuffer))))
10793 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10794 "Insert a date stamp for the date given by the internal TIME.
10795 WITH-HM means, use the stamp format that includes the time of the day.
10796 INACTIVE means use square brackets instead of angular ones, so that the
10797 stamp will not contribute to the agenda.
10798 PRE and POST are optional strings to be inserted before and after the
10799 stamp.
10800 The command returns the inserted time stamp."
10801 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10802 stamp)
10803 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10804 (insert-before-markers (or pre ""))
10805 (insert-before-markers (setq stamp (format-time-string fmt time)))
10806 (when (listp extra)
10807 (setq extra (car extra))
10808 (if (and (stringp extra)
10809 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10810 (setq extra (format "-%02d:%02d"
10811 (string-to-number (match-string 1 extra))
10812 (string-to-number (match-string 2 extra))))
10813 (setq extra nil)))
10814 (when extra
10815 (backward-char 1)
10816 (insert-before-markers extra)
10817 (forward-char 1))
10818 (insert-before-markers (or post ""))
10819 stamp))
10821 (defun org-toggle-time-stamp-overlays ()
10822 "Toggle the use of custom time stamp formats."
10823 (interactive)
10824 (setq org-display-custom-times (not org-display-custom-times))
10825 (unless org-display-custom-times
10826 (let ((p (point-min)) (bmp (buffer-modified-p)))
10827 (while (setq p (next-single-property-change p 'display))
10828 (if (and (get-text-property p 'display)
10829 (eq (get-text-property p 'face) 'org-date))
10830 (remove-text-properties
10831 p (setq p (next-single-property-change p 'display))
10832 '(display t))))
10833 (set-buffer-modified-p bmp)))
10834 (if (featurep 'xemacs)
10835 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10836 (org-restart-font-lock)
10837 (setq org-table-may-need-update t)
10838 (if org-display-custom-times
10839 (message "Time stamps are overlayed with custom format")
10840 (message "Time stamp overlays removed")))
10842 (defun org-display-custom-time (beg end)
10843 "Overlay modified time stamp format over timestamp between BEG and END."
10844 (let* ((ts (buffer-substring beg end))
10845 t1 w1 with-hm tf time str w2 (off 0))
10846 (save-match-data
10847 (setq t1 (org-parse-time-string ts t))
10848 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10849 (setq off (- (match-end 0) (match-beginning 0)))))
10850 (setq end (- end off))
10851 (setq w1 (- end beg)
10852 with-hm (and (nth 1 t1) (nth 2 t1))
10853 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10854 time (org-fix-decoded-time t1)
10855 str (org-add-props
10856 (format-time-string
10857 (substring tf 1 -1) (apply 'encode-time time))
10858 nil 'mouse-face 'highlight)
10859 w2 (length str))
10860 (if (not (= w2 w1))
10861 (add-text-properties (1+ beg) (+ 2 beg)
10862 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10863 (if (featurep 'xemacs)
10864 (progn
10865 (put-text-property beg end 'invisible t)
10866 (put-text-property beg end 'end-glyph (make-glyph str)))
10867 (put-text-property beg end 'display str))))
10869 (defun org-translate-time (string)
10870 "Translate all timestamps in STRING to custom format.
10871 But do this only if the variable `org-display-custom-times' is set."
10872 (when org-display-custom-times
10873 (save-match-data
10874 (let* ((start 0)
10875 (re org-ts-regexp-both)
10876 t1 with-hm inactive tf time str beg end)
10877 (while (setq start (string-match re string start))
10878 (setq beg (match-beginning 0)
10879 end (match-end 0)
10880 t1 (save-match-data
10881 (org-parse-time-string (substring string beg end) t))
10882 with-hm (and (nth 1 t1) (nth 2 t1))
10883 inactive (equal (substring string beg (1+ beg)) "[")
10884 tf (funcall (if with-hm 'cdr 'car)
10885 org-time-stamp-custom-formats)
10886 time (org-fix-decoded-time t1)
10887 str (format-time-string
10888 (concat
10889 (if inactive "[" "<") (substring tf 1 -1)
10890 (if inactive "]" ">"))
10891 (apply 'encode-time time))
10892 string (replace-match str t t string)
10893 start (+ start (length str)))))))
10894 string)
10896 (defun org-fix-decoded-time (time)
10897 "Set 0 instead of nil for the first 6 elements of time.
10898 Don't touch the rest."
10899 (let ((n 0))
10900 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10902 (defun org-days-to-time (timestamp-string)
10903 "Difference between TIMESTAMP-STRING and now in days."
10904 (- (time-to-days (org-time-string-to-time timestamp-string))
10905 (time-to-days (current-time))))
10907 (defun org-deadline-close (timestamp-string &optional ndays)
10908 "Is the time in TIMESTAMP-STRING close to the current date?"
10909 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10910 (and (< (org-days-to-time timestamp-string) ndays)
10911 (not (org-entry-is-done-p))))
10913 (defun org-get-wdays (ts)
10914 "Get the deadline lead time appropriate for timestring TS."
10915 (cond
10916 ((<= org-deadline-warning-days 0)
10917 ;; 0 or negative, enforce this value no matter what
10918 (- org-deadline-warning-days))
10919 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10920 ;; lead time is specified.
10921 (floor (* (string-to-number (match-string 1 ts))
10922 (cdr (assoc (match-string 2 ts)
10923 '(("d" . 1) ("w" . 7)
10924 ("m" . 30.4) ("y" . 365.25)))))))
10925 ;; go for the default.
10926 (t org-deadline-warning-days)))
10928 (defun org-calendar-select-mouse (ev)
10929 "Return to `org-read-date' with the date currently selected.
10930 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10931 (interactive "e")
10932 (mouse-set-point ev)
10933 (when (calendar-cursor-to-date)
10934 (let* ((date (calendar-cursor-to-date))
10935 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10936 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10937 (if (active-minibuffer-window) (exit-minibuffer))))
10939 (defun org-check-deadlines (ndays)
10940 "Check if there are any deadlines due or past due.
10941 A deadline is considered due if it happens within `org-deadline-warning-days'
10942 days from today's date. If the deadline appears in an entry marked DONE,
10943 it is not shown. The prefix arg NDAYS can be used to test that many
10944 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10945 (interactive "P")
10946 (let* ((org-warn-days
10947 (cond
10948 ((equal ndays '(4)) 100000)
10949 (ndays (prefix-numeric-value ndays))
10950 (t (abs org-deadline-warning-days))))
10951 (case-fold-search nil)
10952 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10953 (callback
10954 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10956 (message "%d deadlines past-due or due within %d days"
10957 (org-occur regexp nil callback)
10958 org-warn-days)))
10960 (defun org-check-before-date (date)
10961 "Check if there are deadlines or scheduled entries before DATE."
10962 (interactive (list (org-read-date)))
10963 (let ((case-fold-search nil)
10964 (regexp (concat "\\<\\(" org-deadline-string
10965 "\\|" org-scheduled-string
10966 "\\) *<\\([^>]+\\)>"))
10967 (callback
10968 (lambda () (time-less-p
10969 (org-time-string-to-time (match-string 2))
10970 (org-time-string-to-time date)))))
10971 (message "%d entries before %s"
10972 (org-occur regexp nil callback) date)))
10974 (defun org-evaluate-time-range (&optional to-buffer)
10975 "Evaluate a time range by computing the difference between start and end.
10976 Normally the result is just printed in the echo area, but with prefix arg
10977 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10978 If the time range is actually in a table, the result is inserted into the
10979 next column.
10980 For time difference computation, a year is assumed to be exactly 365
10981 days in order to avoid rounding problems."
10982 (interactive "P")
10984 (org-clock-update-time-maybe)
10985 (save-excursion
10986 (unless (org-at-date-range-p t)
10987 (goto-char (point-at-bol))
10988 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10989 (if (not (org-at-date-range-p t))
10990 (error "Not at a time-stamp range, and none found in current line")))
10991 (let* ((ts1 (match-string 1))
10992 (ts2 (match-string 2))
10993 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10994 (match-end (match-end 0))
10995 (time1 (org-time-string-to-time ts1))
10996 (time2 (org-time-string-to-time ts2))
10997 (t1 (time-to-seconds time1))
10998 (t2 (time-to-seconds time2))
10999 (diff (abs (- t2 t1)))
11000 (negative (< (- t2 t1) 0))
11001 ;; (ys (floor (* 365 24 60 60)))
11002 (ds (* 24 60 60))
11003 (hs (* 60 60))
11004 (fy "%dy %dd %02d:%02d")
11005 (fy1 "%dy %dd")
11006 (fd "%dd %02d:%02d")
11007 (fd1 "%dd")
11008 (fh "%02d:%02d")
11009 y d h m align)
11010 (if havetime
11011 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11013 d (floor (/ diff ds)) diff (mod diff ds)
11014 h (floor (/ diff hs)) diff (mod diff hs)
11015 m (floor (/ diff 60)))
11016 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11018 d (floor (+ (/ diff ds) 0.5))
11019 h 0 m 0))
11020 (if (not to-buffer)
11021 (message "%s" (org-make-tdiff-string y d h m))
11022 (if (org-at-table-p)
11023 (progn
11024 (goto-char match-end)
11025 (setq align t)
11026 (and (looking-at " *|") (goto-char (match-end 0))))
11027 (goto-char match-end))
11028 (if (looking-at
11029 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11030 (replace-match ""))
11031 (if negative (insert " -"))
11032 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11033 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11034 (insert " " (format fh h m))))
11035 (if align (org-table-align))
11036 (message "Time difference inserted")))))
11038 (defun org-make-tdiff-string (y d h m)
11039 (let ((fmt "")
11040 (l nil))
11041 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11042 l (push y l)))
11043 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11044 l (push d l)))
11045 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11046 l (push h l)))
11047 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11048 l (push m l)))
11049 (apply 'format fmt (nreverse l))))
11051 (defun org-time-string-to-time (s)
11052 (apply 'encode-time (org-parse-time-string s)))
11054 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11055 "Convert a time stamp to an absolute day number.
11056 If there is a specifyer for a cyclic time stamp, get the closest date to
11057 DAYNR.
11058 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11059 (cond
11060 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11061 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11062 daynr
11063 (+ daynr 1000)))
11064 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11065 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11066 (time-to-days (current-time))) (match-string 0 s)
11067 prefer show-all))
11068 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11070 (defun org-days-to-iso-week (days)
11071 "Return the iso week number."
11072 (require 'cal-iso)
11073 (car (calendar-iso-from-absolute days)))
11075 (defun org-small-year-to-year (year)
11076 "Convert 2-digit years into 4-digit years.
11077 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11078 The year 2000 cannot be abbreviated. Any year lager than 99
11079 is retrned unchanged."
11080 (if (< year 38)
11081 (setq year (+ 2000 year))
11082 (if (< year 100)
11083 (setq year (+ 1900 year))))
11084 year)
11086 (defun org-time-from-absolute (d)
11087 "Return the time corresponding to date D.
11088 D may be an absolute day number, or a calendar-type list (month day year)."
11089 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11090 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11092 (defun org-calendar-holiday ()
11093 "List of holidays, for Diary display in Org-mode."
11094 (require 'holidays)
11095 (let ((hl (funcall
11096 (if (fboundp 'calendar-check-holidays)
11097 'calendar-check-holidays 'check-calendar-holidays) date)))
11098 (if hl (mapconcat 'identity hl "; "))))
11100 (defun org-diary-sexp-entry (sexp entry date)
11101 "Process a SEXP diary ENTRY for DATE."
11102 (require 'diary-lib)
11103 (let ((result (if calendar-debug-sexp
11104 (let ((stack-trace-on-error t))
11105 (eval (car (read-from-string sexp))))
11106 (condition-case nil
11107 (eval (car (read-from-string sexp)))
11108 (error
11109 (beep)
11110 (message "Bad sexp at line %d in %s: %s"
11111 (org-current-line)
11112 (buffer-file-name) sexp)
11113 (sleep-for 2))))))
11114 (cond ((stringp result) result)
11115 ((and (consp result)
11116 (stringp (cdr result))) (cdr result))
11117 (result entry)
11118 (t nil))))
11120 (defun org-diary-to-ical-string (frombuf)
11121 "Get iCalendar entries from diary entries in buffer FROMBUF.
11122 This uses the icalendar.el library."
11123 (let* ((tmpdir (if (featurep 'xemacs)
11124 (temp-directory)
11125 temporary-file-directory))
11126 (tmpfile (make-temp-name
11127 (expand-file-name "orgics" tmpdir)))
11128 buf rtn b e)
11129 (save-excursion
11130 (set-buffer frombuf)
11131 (icalendar-export-region (point-min) (point-max) tmpfile)
11132 (setq buf (find-buffer-visiting tmpfile))
11133 (set-buffer buf)
11134 (goto-char (point-min))
11135 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11136 (setq b (match-beginning 0)))
11137 (goto-char (point-max))
11138 (if (re-search-backward "^END:VEVENT" nil t)
11139 (setq e (match-end 0)))
11140 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11141 (kill-buffer buf)
11142 (kill-buffer frombuf)
11143 (delete-file tmpfile)
11144 rtn))
11146 (defun org-closest-date (start current change prefer show-all)
11147 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11148 When PREFER is `past' return a date that is either CURRENT or past.
11149 When PREFER is `future', return a date that is either CURRENT or future.
11150 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11151 ;; Make the proper lists from the dates
11152 (catch 'exit
11153 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11154 dn dw sday cday n1 n2
11155 d m y y1 y2 date1 date2 nmonths nm ny m2)
11157 (setq start (org-date-to-gregorian start)
11158 current (org-date-to-gregorian
11159 (if show-all
11160 current
11161 (time-to-days (current-time))))
11162 sday (calendar-absolute-from-gregorian start)
11163 cday (calendar-absolute-from-gregorian current))
11165 (if (<= cday sday) (throw 'exit sday))
11167 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11168 (setq dn (string-to-number (match-string 1 change))
11169 dw (cdr (assoc (match-string 2 change) a1)))
11170 (error "Invalid change specifyer: %s" change))
11171 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11172 (cond
11173 ((eq dw 'day)
11174 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11175 n2 (+ n1 dn)))
11176 ((eq dw 'year)
11177 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11178 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11179 (setq date1 (list m d y1)
11180 n1 (calendar-absolute-from-gregorian date1)
11181 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11182 n2 (calendar-absolute-from-gregorian date2)))
11183 ((eq dw 'month)
11184 ;; approx number of month between the tow dates
11185 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11186 ;; How often does dn fit in there?
11187 (setq d (nth 1 start) m (car start) y (nth 2 start)
11188 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11189 m (+ m nm)
11190 ny (floor (/ m 12))
11191 y (+ y ny)
11192 m (- m (* ny 12)))
11193 (while (> m 12) (setq m (- m 12) y (1+ y)))
11194 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11195 (setq m2 (+ m dn) y2 y)
11196 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11197 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11198 (while (< n2 cday)
11199 (setq n1 n2 m m2 y y2)
11200 (setq m2 (+ m dn) y2 y)
11201 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11202 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11204 (if show-all
11205 (cond
11206 ((eq prefer 'past) n1)
11207 ((eq prefer 'future) (if (= cday n1) n1 n2))
11208 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11209 (cond
11210 ((eq prefer 'past) n1)
11211 ((eq prefer 'future) (if (= cday n1) n1 n2))
11212 (t (if (= cday n1) n1 n2)))))))
11214 (defun org-date-to-gregorian (date)
11215 "Turn any specification of DATE into a gregorian date for the calendar."
11216 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11217 ((and (listp date) (= (length date) 3)) date)
11218 ((stringp date)
11219 (setq date (org-parse-time-string date))
11220 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11221 ((listp date)
11222 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11224 (defun org-parse-time-string (s &optional nodefault)
11225 "Parse the standard Org-mode time string.
11226 This should be a lot faster than the normal `parse-time-string'.
11227 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11228 hour and minute fields will be nil if not given."
11229 (if (string-match org-ts-regexp0 s)
11230 (list 0
11231 (if (or (match-beginning 8) (not nodefault))
11232 (string-to-number (or (match-string 8 s) "0")))
11233 (if (or (match-beginning 7) (not nodefault))
11234 (string-to-number (or (match-string 7 s) "0")))
11235 (string-to-number (match-string 4 s))
11236 (string-to-number (match-string 3 s))
11237 (string-to-number (match-string 2 s))
11238 nil nil nil)
11239 (make-list 9 0)))
11241 (defun org-timestamp-up (&optional arg)
11242 "Increase the date item at the cursor by one.
11243 If the cursor is on the year, change the year. If it is on the month or
11244 the day, change that.
11245 With prefix ARG, change by that many units."
11246 (interactive "p")
11247 (org-timestamp-change (prefix-numeric-value arg)))
11249 (defun org-timestamp-down (&optional arg)
11250 "Decrease the date item at the cursor by one.
11251 If the cursor is on the year, change the year. If it is on the month or
11252 the day, change that.
11253 With prefix ARG, change by that many units."
11254 (interactive "p")
11255 (org-timestamp-change (- (prefix-numeric-value arg))))
11257 (defun org-timestamp-up-day (&optional arg)
11258 "Increase the date in the time stamp by one day.
11259 With prefix ARG, change that many days."
11260 (interactive "p")
11261 (if (and (not (org-at-timestamp-p t))
11262 (org-on-heading-p))
11263 (org-todo 'up)
11264 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11266 (defun org-timestamp-down-day (&optional arg)
11267 "Decrease the date in the time stamp by one day.
11268 With prefix ARG, change that many days."
11269 (interactive "p")
11270 (if (and (not (org-at-timestamp-p t))
11271 (org-on-heading-p))
11272 (org-todo 'down)
11273 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11275 (defun org-at-timestamp-p (&optional inactive-ok)
11276 "Determine if the cursor is in or at a timestamp."
11277 (interactive)
11278 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11279 (pos (point))
11280 (ans (or (looking-at tsr)
11281 (save-excursion
11282 (skip-chars-backward "^[<\n\r\t")
11283 (if (> (point) (point-min)) (backward-char 1))
11284 (and (looking-at tsr)
11285 (> (- (match-end 0) pos) -1))))))
11286 (and ans
11287 (boundp 'org-ts-what)
11288 (setq org-ts-what
11289 (cond
11290 ((= pos (match-beginning 0)) 'bracket)
11291 ((= pos (1- (match-end 0))) 'bracket)
11292 ((org-pos-in-match-range pos 2) 'year)
11293 ((org-pos-in-match-range pos 3) 'month)
11294 ((org-pos-in-match-range pos 7) 'hour)
11295 ((org-pos-in-match-range pos 8) 'minute)
11296 ((or (org-pos-in-match-range pos 4)
11297 (org-pos-in-match-range pos 5)) 'day)
11298 ((and (> pos (or (match-end 8) (match-end 5)))
11299 (< pos (match-end 0)))
11300 (- pos (or (match-end 8) (match-end 5))))
11301 (t 'day))))
11302 ans))
11304 (defun org-toggle-timestamp-type ()
11305 "Toggle the type (<active> or [inactive]) of a time stamp."
11306 (interactive)
11307 (when (org-at-timestamp-p t)
11308 (save-excursion
11309 (goto-char (match-beginning 0))
11310 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11311 (goto-char (1- (match-end 0)))
11312 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11313 (message "Timestamp is now %sactive"
11314 (if (equal (char-before) ?>) "in" ""))))
11316 (defun org-timestamp-change (n &optional what)
11317 "Change the date in the time stamp at point.
11318 The date will be changed by N times WHAT. WHAT can be `day', `month',
11319 `year', `minute', `second'. If WHAT is not given, the cursor position
11320 in the timestamp determines what will be changed."
11321 (let ((pos (point))
11322 with-hm inactive
11323 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11324 org-ts-what
11325 extra rem
11326 ts time time0)
11327 (if (not (org-at-timestamp-p t))
11328 (error "Not at a timestamp"))
11329 (if (and (not what) (eq org-ts-what 'bracket))
11330 (org-toggle-timestamp-type)
11331 (if (and (not what) (not (eq org-ts-what 'day))
11332 org-display-custom-times
11333 (get-text-property (point) 'display)
11334 (not (get-text-property (1- (point)) 'display)))
11335 (setq org-ts-what 'day))
11336 (setq org-ts-what (or what org-ts-what)
11337 inactive (= (char-after (match-beginning 0)) ?\[)
11338 ts (match-string 0))
11339 (replace-match "")
11340 (if (string-match
11341 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11343 (setq extra (match-string 1 ts)))
11344 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11345 (setq with-hm t))
11346 (setq time0 (org-parse-time-string ts))
11347 (when (and (eq org-ts-what 'minute)
11348 (eq current-prefix-arg nil))
11349 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11350 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11351 (setcar (cdr time0) (+ (nth 1 time0)
11352 (if (> n 0) (- rem) (- dm rem))))))
11353 (setq time
11354 (encode-time (or (car time0) 0)
11355 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11356 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11357 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11358 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11359 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11360 (nthcdr 6 time0)))
11361 (when (integerp org-ts-what)
11362 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11363 (if (eq what 'calendar)
11364 (let ((cal-date (org-get-date-from-calendar)))
11365 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11366 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11367 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11368 (setcar time0 (or (car time0) 0))
11369 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11370 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11371 (setq time (apply 'encode-time time0))))
11372 (setq org-last-changed-timestamp
11373 (org-insert-time-stamp time with-hm inactive nil nil extra))
11374 (org-clock-update-time-maybe)
11375 (goto-char pos)
11376 ;; Try to recenter the calendar window, if any
11377 (if (and org-calendar-follow-timestamp-change
11378 (get-buffer-window "*Calendar*" t)
11379 (memq org-ts-what '(day month year)))
11380 (org-recenter-calendar (time-to-days time))))))
11382 (defun org-modify-ts-extra (s pos n dm)
11383 "Change the different parts of the lead-time and repeat fields in timestamp."
11384 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11385 ng h m new rem)
11386 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11387 (cond
11388 ((or (org-pos-in-match-range pos 2)
11389 (org-pos-in-match-range pos 3))
11390 (setq m (string-to-number (match-string 3 s))
11391 h (string-to-number (match-string 2 s)))
11392 (if (org-pos-in-match-range pos 2)
11393 (setq h (+ h n))
11394 (setq n (* dm (org-no-warnings (signum n))))
11395 (when (not (= 0 (setq rem (% m dm))))
11396 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11397 (setq m (+ m n)))
11398 (if (< m 0) (setq m (+ m 60) h (1- h)))
11399 (if (> m 59) (setq m (- m 60) h (1+ h)))
11400 (setq h (min 24 (max 0 h)))
11401 (setq ng 1 new (format "-%02d:%02d" h m)))
11402 ((org-pos-in-match-range pos 6)
11403 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11404 ((org-pos-in-match-range pos 5)
11405 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11407 ((org-pos-in-match-range pos 9)
11408 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11409 ((org-pos-in-match-range pos 8)
11410 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11412 (when ng
11413 (setq s (concat
11414 (substring s 0 (match-beginning ng))
11416 (substring s (match-end ng))))))
11419 (defun org-recenter-calendar (date)
11420 "If the calendar is visible, recenter it to DATE."
11421 (let* ((win (selected-window))
11422 (cwin (get-buffer-window "*Calendar*" t))
11423 (calendar-move-hook nil))
11424 (when cwin
11425 (select-window cwin)
11426 (calendar-goto-date (if (listp date) date
11427 (calendar-gregorian-from-absolute date)))
11428 (select-window win))))
11430 (defun org-goto-calendar (&optional arg)
11431 "Go to the Emacs calendar at the current date.
11432 If there is a time stamp in the current line, go to that date.
11433 A prefix ARG can be used to force the current date."
11434 (interactive "P")
11435 (let ((tsr org-ts-regexp) diff
11436 (calendar-move-hook nil)
11437 (calendar-view-holidays-initially-flag nil)
11438 (view-calendar-holidays-initially nil)
11439 (calendar-view-diary-initially-flag nil)
11440 (view-diary-entries-initially nil))
11441 (if (or (org-at-timestamp-p)
11442 (save-excursion
11443 (beginning-of-line 1)
11444 (looking-at (concat ".*" tsr))))
11445 (let ((d1 (time-to-days (current-time)))
11446 (d2 (time-to-days
11447 (org-time-string-to-time (match-string 1)))))
11448 (setq diff (- d2 d1))))
11449 (calendar)
11450 (calendar-goto-today)
11451 (if (and diff (not arg)) (calendar-forward-day diff))))
11453 (defun org-get-date-from-calendar ()
11454 "Return a list (month day year) of date at point in calendar."
11455 (with-current-buffer "*Calendar*"
11456 (save-match-data
11457 (calendar-cursor-to-date))))
11459 (defun org-date-from-calendar ()
11460 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11461 If there is already a time stamp at the cursor position, update it."
11462 (interactive)
11463 (if (org-at-timestamp-p t)
11464 (org-timestamp-change 0 'calendar)
11465 (let ((cal-date (org-get-date-from-calendar)))
11466 (org-insert-time-stamp
11467 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11469 (defun org-minutes-to-hh:mm-string (m)
11470 "Compute H:MM from a number of minutes."
11471 (let ((h (/ m 60)))
11472 (setq m (- m (* 60 h)))
11473 (format org-time-clocksum-format h m)))
11475 (defun org-hh:mm-string-to-minutes (s)
11476 "Convert a string H:MM to a number of minutes."
11477 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11478 (+ (* (string-to-number (match-string 1 s)) 60)
11479 (string-to-number (match-string 2 s)))
11482 ;;;; Agenda files
11484 ;;;###autoload
11485 (defun org-iswitchb (&optional arg)
11486 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11487 With a prefix argument, restrict available to files.
11488 With two prefix arguments, restrict available buffers to agenda files.
11490 Due to some yet unresolved reason, global function
11491 `iswitchb-mode' needs to be active for this function to work."
11492 (interactive "P")
11493 (require 'iswitchb)
11494 (let ((enabled iswitchb-mode) blist)
11495 (or enabled (iswitchb-mode 1))
11496 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11497 ((equal arg '(16)) (org-buffer-list 'agenda))
11498 (t (org-buffer-list))))
11499 (unwind-protect
11500 (let ((iswitchb-make-buflist-hook
11501 (lambda ()
11502 (setq iswitchb-temp-buflist
11503 (mapcar 'buffer-name blist)))))
11504 (switch-to-buffer
11505 (iswitchb-read-buffer
11506 "Switch-to: " nil t))
11507 (or enabled (iswitchb-mode -1))))))
11509 (defun org-buffer-list (&optional predicate tmp)
11510 "Return a list of Org buffers.
11511 PREDICATE can be either 'export, 'files or 'agenda.
11513 'export restrict the list to Export buffers.
11514 'files restrict the list to buffers visiting Org files.
11515 'agenda restrict the list to buffers visiting agenda files.
11517 If TMP is non-nil, don't include temporary buffers."
11518 (let (filter blist)
11519 (setq filter
11520 (cond ((eq predicate 'files) "\.org$")
11521 ((eq predicate 'export) "\*Org .*Export")
11522 (t "\*Org \\|\.org$")))
11523 (setq blist
11524 (mapcar
11525 (lambda(b)
11526 (let ((bname (buffer-name b))
11527 (bfile (buffer-file-name b)))
11528 (if (and (string-match filter bname)
11529 (if (eq predicate 'agenda)
11530 (member bfile
11531 (mapcar (lambda(f) (file-truename f))
11532 org-agenda-files)) t)
11533 (if tmp (not (string-match "tmp" bname)) t)) b)))
11534 (buffer-list)))
11535 (delete nil blist)))
11537 (defun org-agenda-files (&optional unrestricted ext)
11538 "Get the list of agenda files.
11539 Optional UNRESTRICTED means return the full list even if a restriction
11540 is currently in place.
11541 When EXT is non-nil, try to add all files that are created by adding EXT
11542 to the file nemes. Basically, this is a way to add the archive files
11543 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11544 a string, \"_archive\" will be used."
11545 (let ((files
11546 (cond
11547 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11548 ((stringp org-agenda-files) (org-read-agenda-file-list))
11549 ((listp org-agenda-files) org-agenda-files)
11550 (t (error "Invalid value of `org-agenda-files'")))))
11551 (setq files (apply 'append
11552 (mapcar (lambda (f)
11553 (if (file-directory-p f)
11554 (directory-files
11555 f t org-agenda-file-regexp)
11556 (list f)))
11557 files)))
11558 (when org-agenda-skip-unavailable-files
11559 (setq files (delq nil
11560 (mapcar (function
11561 (lambda (file)
11562 (and (file-readable-p file) file)))
11563 files))))
11564 (when ext
11565 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11566 ext "_archive"))
11567 (setq files (apply 'append
11568 (mapcar
11569 (lambda (f)
11570 (if (file-exists-p (concat f ext))
11571 (list f (concat f ext))
11572 (list f)))
11573 files))))
11574 files))
11576 (defun org-edit-agenda-file-list ()
11577 "Edit the list of agenda files.
11578 Depending on setup, this either uses customize to edit the variable
11579 `org-agenda-files', or it visits the file that is holding the list. In the
11580 latter case, the buffer is set up in a way that saving it automatically kills
11581 the buffer and restores the previous window configuration."
11582 (interactive)
11583 (if (stringp org-agenda-files)
11584 (let ((cw (current-window-configuration)))
11585 (find-file org-agenda-files)
11586 (org-set-local 'org-window-configuration cw)
11587 (org-add-hook 'after-save-hook
11588 (lambda ()
11589 (set-window-configuration
11590 (prog1 org-window-configuration
11591 (kill-buffer (current-buffer))))
11592 (org-install-agenda-files-menu)
11593 (message "New agenda file list installed"))
11594 nil 'local)
11595 (message "%s" (substitute-command-keys
11596 "Edit list and finish with \\[save-buffer]")))
11597 (customize-variable 'org-agenda-files)))
11599 (defun org-store-new-agenda-file-list (list)
11600 "Set new value for the agenda file list and save it correcly."
11601 (if (stringp org-agenda-files)
11602 (let ((f org-agenda-files) b)
11603 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11604 (with-temp-file f
11605 (insert (mapconcat 'identity list "\n") "\n")))
11606 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11607 (setq org-agenda-files list)
11608 (customize-save-variable 'org-agenda-files org-agenda-files))))
11610 (defun org-read-agenda-file-list ()
11611 "Read the list of agenda files from a file."
11612 (when (file-directory-p org-agenda-files)
11613 (error "`org-agenda-files' cannot be a single directory"))
11614 (when (stringp org-agenda-files)
11615 (with-temp-buffer
11616 (insert-file-contents org-agenda-files)
11617 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11620 ;;;###autoload
11621 (defun org-cycle-agenda-files ()
11622 "Cycle through the files in `org-agenda-files'.
11623 If the current buffer visits an agenda file, find the next one in the list.
11624 If the current buffer does not, find the first agenda file."
11625 (interactive)
11626 (let* ((fs (org-agenda-files t))
11627 (files (append fs (list (car fs))))
11628 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11629 file)
11630 (unless files (error "No agenda files"))
11631 (catch 'exit
11632 (while (setq file (pop files))
11633 (if (equal (file-truename file) tcf)
11634 (when (car files)
11635 (find-file (car files))
11636 (throw 'exit t))))
11637 (find-file (car fs)))
11638 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11640 (defun org-agenda-file-to-front (&optional to-end)
11641 "Move/add the current file to the top of the agenda file list.
11642 If the file is not present in the list, it is added to the front. If it is
11643 present, it is moved there. With optional argument TO-END, add/move to the
11644 end of the list."
11645 (interactive "P")
11646 (let ((org-agenda-skip-unavailable-files nil)
11647 (file-alist (mapcar (lambda (x)
11648 (cons (file-truename x) x))
11649 (org-agenda-files t)))
11650 (ctf (file-truename buffer-file-name))
11651 x had)
11652 (setq x (assoc ctf file-alist) had x)
11654 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11655 (if to-end
11656 (setq file-alist (append (delq x file-alist) (list x)))
11657 (setq file-alist (cons x (delq x file-alist))))
11658 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11659 (org-install-agenda-files-menu)
11660 (message "File %s to %s of agenda file list"
11661 (if had "moved" "added") (if to-end "end" "front"))))
11663 (defun org-remove-file (&optional file)
11664 "Remove current file from the list of files in variable `org-agenda-files'.
11665 These are the files which are being checked for agenda entries.
11666 Optional argument FILE means, use this file instead of the current."
11667 (interactive)
11668 (let* ((org-agenda-skip-unavailable-files nil)
11669 (file (or file buffer-file-name))
11670 (true-file (file-truename file))
11671 (afile (abbreviate-file-name file))
11672 (files (delq nil (mapcar
11673 (lambda (x)
11674 (if (equal true-file
11675 (file-truename x))
11676 nil x))
11677 (org-agenda-files t)))))
11678 (if (not (= (length files) (length (org-agenda-files t))))
11679 (progn
11680 (org-store-new-agenda-file-list files)
11681 (org-install-agenda-files-menu)
11682 (message "Removed file: %s" afile))
11683 (message "File was not in list: %s (not removed)" afile))))
11685 (defun org-file-menu-entry (file)
11686 (vector file (list 'find-file file) t))
11688 (defun org-check-agenda-file (file)
11689 "Make sure FILE exists. If not, ask user what to do."
11690 (when (not (file-exists-p file))
11691 (message "non-existent file %s. [R]emove from list or [A]bort?"
11692 (abbreviate-file-name file))
11693 (let ((r (downcase (read-char-exclusive))))
11694 (cond
11695 ((equal r ?r)
11696 (org-remove-file file)
11697 (throw 'nextfile t))
11698 (t (error "Abort"))))))
11700 (defun org-get-agenda-file-buffer (file)
11701 "Get a buffer visiting FILE. If the buffer needs to be created, add
11702 it to the list of buffers which might be released later."
11703 (let ((buf (org-find-base-buffer-visiting file)))
11704 (if buf
11705 buf ; just return it
11706 ;; Make a new buffer and remember it
11707 (setq buf (find-file-noselect file))
11708 (if buf (push buf org-agenda-new-buffers))
11709 buf)))
11711 (defun org-release-buffers (blist)
11712 "Release all buffers in list, asking the user for confirmation when needed.
11713 When a buffer is unmodified, it is just killed. When modified, it is saved
11714 \(if the user agrees) and then killed."
11715 (let (buf file)
11716 (while (setq buf (pop blist))
11717 (setq file (buffer-file-name buf))
11718 (when (and (buffer-modified-p buf)
11719 file
11720 (y-or-n-p (format "Save file %s? " file)))
11721 (with-current-buffer buf (save-buffer)))
11722 (kill-buffer buf))))
11724 (defun org-prepare-agenda-buffers (files)
11725 "Create buffers for all agenda files, protect archived trees and comments."
11726 (interactive)
11727 (let ((pa '(:org-archived t))
11728 (pc '(:org-comment t))
11729 (pall '(:org-archived t :org-comment t))
11730 (inhibit-read-only t)
11731 (rea (concat ":" org-archive-tag ":"))
11732 bmp file re)
11733 (save-excursion
11734 (save-restriction
11735 (while (setq file (pop files))
11736 (if (bufferp file)
11737 (set-buffer file)
11738 (org-check-agenda-file file)
11739 (set-buffer (org-get-agenda-file-buffer file)))
11740 (widen)
11741 (setq bmp (buffer-modified-p))
11742 (org-refresh-category-properties)
11743 (setq org-todo-keywords-for-agenda
11744 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11745 (setq org-done-keywords-for-agenda
11746 (append org-done-keywords-for-agenda org-done-keywords))
11747 (save-excursion
11748 (remove-text-properties (point-min) (point-max) pall)
11749 (when org-agenda-skip-archived-trees
11750 (goto-char (point-min))
11751 (while (re-search-forward rea nil t)
11752 (if (org-on-heading-p t)
11753 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11754 (goto-char (point-min))
11755 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11756 (while (re-search-forward re nil t)
11757 (add-text-properties
11758 (match-beginning 0) (org-end-of-subtree t) pc)))
11759 (set-buffer-modified-p bmp))))))
11761 ;;;; Embedded LaTeX
11763 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11764 "Keymap for the minor `org-cdlatex-mode'.")
11766 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11767 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11768 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11769 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11770 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11772 (defvar org-cdlatex-texmathp-advice-is-done nil
11773 "Flag remembering if we have applied the advice to texmathp already.")
11775 (define-minor-mode org-cdlatex-mode
11776 "Toggle the minor `org-cdlatex-mode'.
11777 This mode supports entering LaTeX environment and math in LaTeX fragments
11778 in Org-mode.
11779 \\{org-cdlatex-mode-map}"
11780 nil " OCDL" nil
11781 (when org-cdlatex-mode (require 'cdlatex))
11782 (unless org-cdlatex-texmathp-advice-is-done
11783 (setq org-cdlatex-texmathp-advice-is-done t)
11784 (defadvice texmathp (around org-math-always-on activate)
11785 "Always return t in org-mode buffers.
11786 This is because we want to insert math symbols without dollars even outside
11787 the LaTeX math segments. If Orgmode thinks that point is actually inside
11788 en embedded LaTeX fragement, let texmathp do its job.
11789 \\[org-cdlatex-mode-map]"
11790 (interactive)
11791 (let (p)
11792 (cond
11793 ((not (org-mode-p)) ad-do-it)
11794 ((eq this-command 'cdlatex-math-symbol)
11795 (setq ad-return-value t
11796 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11798 (let ((p (org-inside-LaTeX-fragment-p)))
11799 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11800 (setq ad-return-value t
11801 texmathp-why '("Org-mode embedded math" . 0))
11802 (if p ad-do-it)))))))))
11804 (defun turn-on-org-cdlatex ()
11805 "Unconditionally turn on `org-cdlatex-mode'."
11806 (org-cdlatex-mode 1))
11808 (defun org-inside-LaTeX-fragment-p ()
11809 "Test if point is inside a LaTeX fragment.
11810 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11811 sequence appearing also before point.
11812 Even though the matchers for math are configurable, this function assumes
11813 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11814 delimiters are skipped when they have been removed by customization.
11815 The return value is nil, or a cons cell with the delimiter and
11816 and the position of this delimiter.
11818 This function does a reasonably good job, but can locally be fooled by
11819 for example currency specifications. For example it will assume being in
11820 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11821 fragments that are properly closed, but during editing, we have to live
11822 with the uncertainty caused by missing closing delimiters. This function
11823 looks only before point, not after."
11824 (catch 'exit
11825 (let ((pos (point))
11826 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11827 (lim (progn
11828 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11829 (point)))
11830 dd-on str (start 0) m re)
11831 (goto-char pos)
11832 (when dodollar
11833 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11834 re (nth 1 (assoc "$" org-latex-regexps)))
11835 (while (string-match re str start)
11836 (cond
11837 ((= (match-end 0) (length str))
11838 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11839 ((= (match-end 0) (- (length str) 5))
11840 (throw 'exit nil))
11841 (t (setq start (match-end 0))))))
11842 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11843 (goto-char pos)
11844 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11845 (and (match-beginning 2) (throw 'exit nil))
11846 ;; count $$
11847 (while (re-search-backward "\\$\\$" lim t)
11848 (setq dd-on (not dd-on)))
11849 (goto-char pos)
11850 (if dd-on (cons "$$" m))))))
11853 (defun org-try-cdlatex-tab ()
11854 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11855 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11856 - inside a LaTeX fragment, or
11857 - after the first word in a line, where an abbreviation expansion could
11858 insert a LaTeX environment."
11859 (when org-cdlatex-mode
11860 (cond
11861 ((save-excursion
11862 (skip-chars-backward "a-zA-Z0-9*")
11863 (skip-chars-backward " \t")
11864 (bolp))
11865 (cdlatex-tab) t)
11866 ((org-inside-LaTeX-fragment-p)
11867 (cdlatex-tab) t)
11868 (t nil))))
11870 (defun org-cdlatex-underscore-caret (&optional arg)
11871 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11872 Revert to the normal definition outside of these fragments."
11873 (interactive "P")
11874 (if (org-inside-LaTeX-fragment-p)
11875 (call-interactively 'cdlatex-sub-superscript)
11876 (let (org-cdlatex-mode)
11877 (call-interactively (key-binding (vector last-input-event))))))
11879 (defun org-cdlatex-math-modify (&optional arg)
11880 "Execute `cdlatex-math-modify' in LaTeX fragments.
11881 Revert to the normal definition outside of these fragments."
11882 (interactive "P")
11883 (if (org-inside-LaTeX-fragment-p)
11884 (call-interactively 'cdlatex-math-modify)
11885 (let (org-cdlatex-mode)
11886 (call-interactively (key-binding (vector last-input-event))))))
11888 (defvar org-latex-fragment-image-overlays nil
11889 "List of overlays carrying the images of latex fragments.")
11890 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11892 (defun org-remove-latex-fragment-image-overlays ()
11893 "Remove all overlays with LaTeX fragment images in current buffer."
11894 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11895 (setq org-latex-fragment-image-overlays nil))
11897 (defun org-preview-latex-fragment (&optional subtree)
11898 "Preview the LaTeX fragment at point, or all locally or globally.
11899 If the cursor is in a LaTeX fragment, create the image and overlay
11900 it over the source code. If there is no fragment at point, display
11901 all fragments in the current text, from one headline to the next. With
11902 prefix SUBTREE, display all fragments in the current subtree. With a
11903 double prefix `C-u C-u', or when the cursor is before the first headline,
11904 display all fragments in the buffer.
11905 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11906 (interactive "P")
11907 (org-remove-latex-fragment-image-overlays)
11908 (save-excursion
11909 (save-restriction
11910 (let (beg end at msg)
11911 (cond
11912 ((or (equal subtree '(16))
11913 (not (save-excursion
11914 (re-search-backward (concat "^" outline-regexp) nil t))))
11915 (setq beg (point-min) end (point-max)
11916 msg "Creating images for buffer...%s"))
11917 ((equal subtree '(4))
11918 (org-back-to-heading)
11919 (setq beg (point) end (org-end-of-subtree t)
11920 msg "Creating images for subtree...%s"))
11922 (if (setq at (org-inside-LaTeX-fragment-p))
11923 (goto-char (max (point-min) (- (cdr at) 2)))
11924 (org-back-to-heading))
11925 (setq beg (point) end (progn (outline-next-heading) (point))
11926 msg (if at "Creating image...%s"
11927 "Creating images for entry...%s"))))
11928 (message msg "")
11929 (narrow-to-region beg end)
11930 (goto-char beg)
11931 (org-format-latex
11932 (concat "ltxpng/" (file-name-sans-extension
11933 (file-name-nondirectory
11934 buffer-file-name)))
11935 default-directory 'overlays msg at 'forbuffer)
11936 (message msg "done. Use `C-c C-c' to remove images.")))))
11938 (defvar org-latex-regexps
11939 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11940 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11941 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11942 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11943 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11944 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11945 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11946 "Regular expressions for matching embedded LaTeX.")
11948 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11949 "Replace LaTeX fragments with links to an image, and produce images."
11950 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11951 (let* ((prefixnodir (file-name-nondirectory prefix))
11952 (absprefix (expand-file-name prefix dir))
11953 (todir (file-name-directory absprefix))
11954 (opt org-format-latex-options)
11955 (matchers (plist-get opt :matchers))
11956 (re-list org-latex-regexps)
11957 (cnt 0) txt link beg end re e checkdir
11958 m n block linkfile movefile ov)
11959 ;; Check if there are old images files with this prefix, and remove them
11960 (when (file-directory-p todir)
11961 (mapc 'delete-file
11962 (directory-files
11963 todir 'full
11964 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11965 ;; Check the different regular expressions
11966 (while (setq e (pop re-list))
11967 (setq m (car e) re (nth 1 e) n (nth 2 e)
11968 block (if (nth 3 e) "\n\n" ""))
11969 (when (member m matchers)
11970 (goto-char (point-min))
11971 (while (re-search-forward re nil t)
11972 (when (or (not at) (equal (cdr at) (match-beginning n)))
11973 (setq txt (match-string n)
11974 beg (match-beginning n) end (match-end n)
11975 cnt (1+ cnt)
11976 linkfile (format "%s_%04d.png" prefix cnt)
11977 movefile (format "%s_%04d.png" absprefix cnt)
11978 link (concat block "[[file:" linkfile "]]" block))
11979 (if msg (message msg cnt))
11980 (goto-char beg)
11981 (unless checkdir ; make sure the directory exists
11982 (setq checkdir t)
11983 (or (file-directory-p todir) (make-directory todir)))
11984 (org-create-formula-image
11985 txt movefile opt forbuffer)
11986 (if overlays
11987 (progn
11988 (setq ov (org-make-overlay beg end))
11989 (if (featurep 'xemacs)
11990 (progn
11991 (org-overlay-put ov 'invisible t)
11992 (org-overlay-put
11993 ov 'end-glyph
11994 (make-glyph (vector 'png :file movefile))))
11995 (org-overlay-put
11996 ov 'display
11997 (list 'image :type 'png :file movefile :ascent 'center)))
11998 (push ov org-latex-fragment-image-overlays)
11999 (goto-char end))
12000 (delete-region beg end)
12001 (insert link))))))))
12003 ;; This function borrows from Ganesh Swami's latex2png.el
12004 (defun org-create-formula-image (string tofile options buffer)
12005 (let* ((tmpdir (if (featurep 'xemacs)
12006 (temp-directory)
12007 temporary-file-directory))
12008 (texfilebase (make-temp-name
12009 (expand-file-name "orgtex" tmpdir)))
12010 (texfile (concat texfilebase ".tex"))
12011 (dvifile (concat texfilebase ".dvi"))
12012 (pngfile (concat texfilebase ".png"))
12013 (fnh (if (featurep 'xemacs)
12014 (font-height (get-face-font 'default))
12015 (face-attribute 'default :height nil)))
12016 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12017 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12018 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12019 "Black"))
12020 (bg (or (plist-get options (if buffer :background :html-background))
12021 "Transparent")))
12022 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12023 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12024 (with-temp-file texfile
12025 (insert org-format-latex-header
12026 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12027 (let ((dir default-directory))
12028 (condition-case nil
12029 (progn
12030 (cd tmpdir)
12031 (call-process "latex" nil nil nil texfile))
12032 (error nil))
12033 (cd dir))
12034 (if (not (file-exists-p dvifile))
12035 (progn (message "Failed to create dvi file from %s" texfile) nil)
12036 (call-process "dvipng" nil nil nil
12037 "-E" "-fg" fg "-bg" bg
12038 "-D" dpi
12039 ;;"-x" scale "-y" scale
12040 "-T" "tight"
12041 "-o" pngfile
12042 dvifile)
12043 (if (not (file-exists-p pngfile))
12044 (progn (message "Failed to create png file from %s" texfile) nil)
12045 ;; Use the requested file name and clean up
12046 (copy-file pngfile tofile 'replace)
12047 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12048 (delete-file (concat texfilebase e)))
12049 pngfile))))
12051 (defun org-dvipng-color (attr)
12052 "Return an rgb color specification for dvipng."
12053 (apply 'format "rgb %s %s %s"
12054 (mapcar 'org-normalize-color
12055 (color-values (face-attribute 'default attr nil)))))
12057 (defun org-normalize-color (value)
12058 "Return string to be used as color value for an RGB component."
12059 (format "%g" (/ value 65535.0)))
12062 ;;;; Key bindings
12064 ;; Make `C-c C-x' a prefix key
12065 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12067 ;; TAB key with modifiers
12068 (org-defkey org-mode-map "\C-i" 'org-cycle)
12069 (org-defkey org-mode-map [(tab)] 'org-cycle)
12070 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12071 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12072 (org-defkey org-mode-map "\M-\t" 'org-complete)
12073 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12074 ;; The following line is necessary under Suse GNU/Linux
12075 (unless (featurep 'xemacs)
12076 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12077 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12078 (define-key org-mode-map [backtab] 'org-shifttab)
12080 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12081 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12082 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12084 ;; Cursor keys with modifiers
12085 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12086 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12087 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12088 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12090 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12091 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12092 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12093 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12095 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12096 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12097 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12098 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12100 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12101 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12103 ;;; Extra keys for tty access.
12104 ;; We only set them when really needed because otherwise the
12105 ;; menus don't show the simple keys
12107 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12108 (not window-system))
12109 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12110 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12111 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12112 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12113 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12114 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12115 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12116 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12117 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12118 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12119 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12120 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12121 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12122 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12123 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12124 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12125 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12126 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12127 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12128 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12129 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12130 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12132 ;; All the other keys
12134 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12135 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12136 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
12137 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12138 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12139 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12140 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12141 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12142 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12143 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12144 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12145 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12146 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12147 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12148 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12149 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12150 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12151 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12152 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12153 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12154 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12155 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12156 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12157 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12158 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12159 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12160 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12161 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12162 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12163 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12164 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12165 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12166 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12167 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12168 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12169 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12170 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12171 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12172 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12173 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12174 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12175 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12176 (org-defkey org-mode-map "\C-c^" 'org-sort)
12177 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12178 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12179 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12180 (org-defkey org-mode-map "\C-m" 'org-return)
12181 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12182 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12183 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12184 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12185 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12186 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
12187 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12188 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12189 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12190 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12191 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12192 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12193 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12194 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12195 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12196 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12198 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12199 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12200 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12201 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12203 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12204 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12205 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12206 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12207 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12208 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12209 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12210 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12211 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12212 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12213 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12214 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12216 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12218 (when (featurep 'xemacs)
12219 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12221 (defvar org-table-auto-blank-field) ; defined in org-table.el
12222 (defun org-self-insert-command (N)
12223 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12224 If the cursor is in a table looking at whitespace, the whitespace is
12225 overwritten, and the table is not marked as requiring realignment."
12226 (interactive "p")
12227 (if (and (org-table-p)
12228 (progn
12229 ;; check if we blank the field, and if that triggers align
12230 (and (featurep 'org-table) org-table-auto-blank-field
12231 (member last-command
12232 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12233 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12234 ;; got extra space, this field does not determine column width
12235 (let (org-table-may-need-update) (org-table-blank-field))
12236 ;; no extra space, this field may determine column width
12237 (org-table-blank-field)))
12239 (eq N 1)
12240 (looking-at "[^|\n]* |"))
12241 (let (org-table-may-need-update)
12242 (goto-char (1- (match-end 0)))
12243 (delete-backward-char 1)
12244 (goto-char (match-beginning 0))
12245 (self-insert-command N))
12246 (setq org-table-may-need-update t)
12247 (self-insert-command N)
12248 (org-fix-tags-on-the-fly)))
12250 (defun org-fix-tags-on-the-fly ()
12251 (when (and (equal (char-after (point-at-bol)) ?*)
12252 (org-on-heading-p))
12253 (org-align-tags-here org-tags-column)))
12255 (defun org-delete-backward-char (N)
12256 "Like `delete-backward-char', insert whitespace at field end in tables.
12257 When deleting backwards, in tables this function will insert whitespace in
12258 front of the next \"|\" separator, to keep the table aligned. The table will
12259 still be marked for re-alignment if the field did fill the entire column,
12260 because, in this case the deletion might narrow the column."
12261 (interactive "p")
12262 (if (and (org-table-p)
12263 (eq N 1)
12264 (string-match "|" (buffer-substring (point-at-bol) (point)))
12265 (looking-at ".*?|"))
12266 (let ((pos (point))
12267 (noalign (looking-at "[^|\n\r]* |"))
12268 (c org-table-may-need-update))
12269 (backward-delete-char N)
12270 (skip-chars-forward "^|")
12271 (insert " ")
12272 (goto-char (1- pos))
12273 ;; noalign: if there were two spaces at the end, this field
12274 ;; does not determine the width of the column.
12275 (if noalign (setq org-table-may-need-update c)))
12276 (backward-delete-char N)
12277 (org-fix-tags-on-the-fly)))
12279 (defun org-delete-char (N)
12280 "Like `delete-char', but insert whitespace at field end in tables.
12281 When deleting characters, in tables this function will insert whitespace in
12282 front of the next \"|\" separator, to keep the table aligned. The table will
12283 still be marked for re-alignment if the field did fill the entire column,
12284 because, in this case the deletion might narrow the column."
12285 (interactive "p")
12286 (if (and (org-table-p)
12287 (not (bolp))
12288 (not (= (char-after) ?|))
12289 (eq N 1))
12290 (if (looking-at ".*?|")
12291 (let ((pos (point))
12292 (noalign (looking-at "[^|\n\r]* |"))
12293 (c org-table-may-need-update))
12294 (replace-match (concat
12295 (substring (match-string 0) 1 -1)
12296 " |"))
12297 (goto-char pos)
12298 ;; noalign: if there were two spaces at the end, this field
12299 ;; does not determine the width of the column.
12300 (if noalign (setq org-table-may-need-update c)))
12301 (delete-char N))
12302 (delete-char N)
12303 (org-fix-tags-on-the-fly)))
12305 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12306 (put 'org-self-insert-command 'delete-selection t)
12307 (put 'orgtbl-self-insert-command 'delete-selection t)
12308 (put 'org-delete-char 'delete-selection 'supersede)
12309 (put 'org-delete-backward-char 'delete-selection 'supersede)
12311 ;; Make `flyspell-mode' delay after some commands
12312 (put 'org-self-insert-command 'flyspell-delayed t)
12313 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12314 (put 'org-delete-char 'flyspell-delayed t)
12315 (put 'org-delete-backward-char 'flyspell-delayed t)
12317 ;; Make pabbrev-mode expand after org-mode commands
12318 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12319 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12321 ;; How to do this: Measure non-white length of current string
12322 ;; If equal to column width, we should realign.
12324 (defun org-remap (map &rest commands)
12325 "In MAP, remap the functions given in COMMANDS.
12326 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12327 (let (new old)
12328 (while commands
12329 (setq old (pop commands) new (pop commands))
12330 (if (fboundp 'command-remapping)
12331 (org-defkey map (vector 'remap old) new)
12332 (substitute-key-definition old new map global-map)))))
12334 (when (eq org-enable-table-editor 'optimized)
12335 ;; If the user wants maximum table support, we need to hijack
12336 ;; some standard editing functions
12337 (org-remap org-mode-map
12338 'self-insert-command 'org-self-insert-command
12339 'delete-char 'org-delete-char
12340 'delete-backward-char 'org-delete-backward-char)
12341 (org-defkey org-mode-map "|" 'org-force-self-insert))
12343 (defun org-shiftcursor-error ()
12344 "Throw an error because Shift-Cursor command was applied in wrong context."
12345 (error "This command is active in special context like tables, headlines or timestamps"))
12347 (defun org-shifttab (&optional arg)
12348 "Global visibility cycling or move to previous table field.
12349 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12350 on context.
12351 See the individual commands for more information."
12352 (interactive "P")
12353 (cond
12354 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12355 ((integerp arg)
12356 (message "Content view to level: %d" arg)
12357 (org-content (prefix-numeric-value arg))
12358 (setq org-cycle-global-status 'overview))
12359 (t (call-interactively 'org-global-cycle))))
12361 (defun org-shiftmetaleft ()
12362 "Promote subtree or delete table column.
12363 Calls `org-promote-subtree', `org-outdent-item',
12364 or `org-table-delete-column', depending on context.
12365 See the individual commands for more information."
12366 (interactive)
12367 (cond
12368 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12369 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12370 ((org-at-item-p) (call-interactively 'org-outdent-item))
12371 (t (org-shiftcursor-error))))
12373 (defun org-shiftmetaright ()
12374 "Demote subtree or insert table column.
12375 Calls `org-demote-subtree', `org-indent-item',
12376 or `org-table-insert-column', depending on context.
12377 See the individual commands for more information."
12378 (interactive)
12379 (cond
12380 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12381 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12382 ((org-at-item-p) (call-interactively 'org-indent-item))
12383 (t (org-shiftcursor-error))))
12385 (defun org-shiftmetaup (&optional arg)
12386 "Move subtree up or kill table row.
12387 Calls `org-move-subtree-up' or `org-table-kill-row' or
12388 `org-move-item-up' depending on context. See the individual commands
12389 for more information."
12390 (interactive "P")
12391 (cond
12392 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12393 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12394 ((org-at-item-p) (call-interactively 'org-move-item-up))
12395 (t (org-shiftcursor-error))))
12396 (defun org-shiftmetadown (&optional arg)
12397 "Move subtree down or insert table row.
12398 Calls `org-move-subtree-down' or `org-table-insert-row' or
12399 `org-move-item-down', depending on context. See the individual
12400 commands for more information."
12401 (interactive "P")
12402 (cond
12403 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12404 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12405 ((org-at-item-p) (call-interactively 'org-move-item-down))
12406 (t (org-shiftcursor-error))))
12408 (defun org-metaleft (&optional arg)
12409 "Promote heading or move table column to left.
12410 Calls `org-do-promote' or `org-table-move-column', depending on context.
12411 With no specific context, calls the Emacs default `backward-word'.
12412 See the individual commands for more information."
12413 (interactive "P")
12414 (cond
12415 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12416 ((or (org-on-heading-p) (org-region-active-p))
12417 (call-interactively 'org-do-promote))
12418 ((org-at-item-p) (call-interactively 'org-outdent-item))
12419 (t (call-interactively 'backward-word))))
12421 (defun org-metaright (&optional arg)
12422 "Demote subtree or move table column to right.
12423 Calls `org-do-demote' or `org-table-move-column', depending on context.
12424 With no specific context, calls the Emacs default `forward-word'.
12425 See the individual commands for more information."
12426 (interactive "P")
12427 (cond
12428 ((org-at-table-p) (call-interactively 'org-table-move-column))
12429 ((or (org-on-heading-p) (org-region-active-p))
12430 (call-interactively 'org-do-demote))
12431 ((org-at-item-p) (call-interactively 'org-indent-item))
12432 (t (call-interactively 'forward-word))))
12434 (defun org-metaup (&optional arg)
12435 "Move subtree up or move table row up.
12436 Calls `org-move-subtree-up' or `org-table-move-row' or
12437 `org-move-item-up', depending on context. See the individual commands
12438 for more information."
12439 (interactive "P")
12440 (cond
12441 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12442 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12443 ((org-at-item-p) (call-interactively 'org-move-item-up))
12444 (t (transpose-lines 1) (beginning-of-line -1))))
12446 (defun org-metadown (&optional arg)
12447 "Move subtree down or move table row down.
12448 Calls `org-move-subtree-down' or `org-table-move-row' or
12449 `org-move-item-down', depending on context. See the individual
12450 commands for more information."
12451 (interactive "P")
12452 (cond
12453 ((org-at-table-p) (call-interactively 'org-table-move-row))
12454 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12455 ((org-at-item-p) (call-interactively 'org-move-item-down))
12456 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12458 (defun org-shiftup (&optional arg)
12459 "Increase item in timestamp or increase priority of current headline.
12460 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12461 depending on context. See the individual commands for more information."
12462 (interactive "P")
12463 (cond
12464 ((org-at-timestamp-p t)
12465 (call-interactively (if org-edit-timestamp-down-means-later
12466 'org-timestamp-down 'org-timestamp-up)))
12467 ((org-on-heading-p) (call-interactively 'org-priority-up))
12468 ((org-at-item-p) (call-interactively 'org-previous-item))
12469 ((org-clocktable-try-shift 'up arg))
12470 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12472 (defun org-shiftdown (&optional arg)
12473 "Decrease item in timestamp or decrease priority of current headline.
12474 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12475 depending on context. See the individual commands for more information."
12476 (interactive "P")
12477 (cond
12478 ((org-at-timestamp-p t)
12479 (call-interactively (if org-edit-timestamp-down-means-later
12480 'org-timestamp-up 'org-timestamp-down)))
12481 ((org-on-heading-p) (call-interactively 'org-priority-down))
12482 ((org-clocktable-try-shift 'down arg))
12483 (t (call-interactively 'org-next-item))))
12485 (defun org-shiftright (&optional arg)
12486 "Next TODO keyword or timestamp one day later, depending on context."
12487 (interactive "P")
12488 (cond
12489 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12490 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12491 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12492 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12493 ((org-clocktable-try-shift 'right arg))
12494 (t (org-shiftcursor-error))))
12496 (defun org-shiftleft (&optional arg)
12497 "Previous TODO keyword or timestamp one day earlier, depending on context."
12498 (interactive "P")
12499 (cond
12500 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12501 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12502 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12503 ((org-at-property-p)
12504 (call-interactively 'org-property-previous-allowed-value))
12505 ((org-clocktable-try-shift 'left arg))
12506 (t (org-shiftcursor-error))))
12508 (defun org-shiftcontrolright ()
12509 "Switch to next TODO set."
12510 (interactive)
12511 (cond
12512 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12513 (t (org-shiftcursor-error))))
12515 (defun org-shiftcontrolleft ()
12516 "Switch to previous TODO set."
12517 (interactive)
12518 (cond
12519 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12520 (t (org-shiftcursor-error))))
12522 (defun org-ctrl-c-ret ()
12523 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12524 (interactive)
12525 (cond
12526 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12527 (t (call-interactively 'org-insert-heading))))
12529 (defun org-copy-special ()
12530 "Copy region in table or copy current subtree.
12531 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12532 See the individual commands for more information."
12533 (interactive)
12534 (call-interactively
12535 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12537 (defun org-cut-special ()
12538 "Cut region in table or cut current subtree.
12539 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12540 See the individual commands for more information."
12541 (interactive)
12542 (call-interactively
12543 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12545 (defun org-paste-special (arg)
12546 "Paste rectangular region into table, or past subtree relative to level.
12547 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12548 See the individual commands for more information."
12549 (interactive "P")
12550 (if (org-at-table-p)
12551 (org-table-paste-rectangle)
12552 (org-paste-subtree arg)))
12554 (defun org-ctrl-c-ctrl-c (&optional arg)
12555 "Set tags in headline, or update according to changed information at point.
12557 This command does many different things, depending on context:
12559 - If the cursor is in a headline, prompt for tags and insert them
12560 into the current line, aligned to `org-tags-column'. When called
12561 with prefix arg, realign all tags in the current buffer.
12563 - If the cursor is in one of the special #+KEYWORD lines, this
12564 triggers scanning the buffer for these lines and updating the
12565 information.
12567 - If the cursor is inside a table, realign the table. This command
12568 works even if the automatic table editor has been turned off.
12570 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12571 the entire table.
12573 - If the cursor is a the beginning of a dynamic block, update it.
12575 - If the cursor is inside a table created by the table.el package,
12576 activate that table.
12578 - If the current buffer is a remember buffer, close note and file it.
12579 with a prefix argument, file it without further interaction to the default
12580 location.
12582 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12583 links in this buffer.
12585 - If the cursor is on a numbered item in a plain list, renumber the
12586 ordered list.
12588 - If the cursor is on a checkbox, toggle it."
12589 (interactive "P")
12590 (let ((org-enable-table-editor t))
12591 (cond
12592 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12593 org-occur-highlights
12594 org-latex-fragment-image-overlays)
12595 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12596 (org-remove-occur-highlights)
12597 (org-remove-latex-fragment-image-overlays)
12598 (message "Temporary highlights/overlays removed from current buffer"))
12599 ((and (local-variable-p 'org-finish-function (current-buffer))
12600 (fboundp org-finish-function))
12601 (funcall org-finish-function))
12602 ((org-at-property-p)
12603 (call-interactively 'org-property-action))
12604 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12605 ((org-on-heading-p) (call-interactively 'org-set-tags))
12606 ((org-at-table.el-p)
12607 (require 'table)
12608 (beginning-of-line 1)
12609 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12610 (call-interactively 'table-recognize-table))
12611 ((org-at-table-p)
12612 (org-table-maybe-eval-formula)
12613 (if arg
12614 (call-interactively 'org-table-recalculate)
12615 (org-table-maybe-recalculate-line))
12616 (call-interactively 'org-table-align))
12617 ((org-at-item-checkbox-p)
12618 (call-interactively 'org-toggle-checkbox))
12619 ((org-at-item-p)
12620 (call-interactively 'org-maybe-renumber-ordered-list))
12621 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12622 ;; Dynamic block
12623 (beginning-of-line 1)
12624 (org-update-dblock))
12625 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12626 (cond
12627 ((equal (match-string 1) "TBLFM")
12628 ;; Recalculate the table before this line
12629 (save-excursion
12630 (beginning-of-line 1)
12631 (skip-chars-backward " \r\n\t")
12632 (if (org-at-table-p)
12633 (org-call-with-arg 'org-table-recalculate t))))
12635 ; (org-set-regexps-and-options)
12636 ; (org-restart-font-lock)
12637 (let ((org-inhibit-startup t)) (org-mode-restart))
12638 (message "Local setup has been refreshed"))))
12639 (t (error "C-c C-c can do nothing useful at this location.")))))
12641 (defun org-mode-restart ()
12642 "Restart Org-mode, to scan again for special lines.
12643 Also updates the keyword regular expressions."
12644 (interactive)
12645 (org-mode)
12646 (message "Org-mode restarted"))
12648 (defun org-kill-note-or-show-branches ()
12649 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12650 (interactive)
12651 (if (not org-finish-function)
12652 (call-interactively 'show-branches)
12653 (let ((org-note-abort t))
12654 (funcall org-finish-function))))
12656 (defun org-return (&optional indent)
12657 "Goto next table row or insert a newline.
12658 Calls `org-table-next-row' or `newline', depending on context.
12659 See the individual commands for more information."
12660 (interactive)
12661 (cond
12662 ((bobp) (if indent (newline-and-indent) (newline)))
12663 ((and (org-at-heading-p)
12664 (looking-at
12665 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12666 (org-show-entry)
12667 (end-of-line 1)
12668 (newline))
12669 ((org-at-table-p)
12670 (org-table-justify-field-maybe)
12671 (call-interactively 'org-table-next-row))
12672 (t (if indent (newline-and-indent) (newline)))))
12674 (defun org-return-indent ()
12675 "Goto next table row or insert a newline and indent.
12676 Calls `org-table-next-row' or `newline-and-indent', depending on
12677 context. See the individual commands for more information."
12678 (interactive)
12679 (org-return t))
12681 (defun org-ctrl-c-star ()
12682 "Compute table, or change heading status of lines.
12683 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12684 depending on context. This will also turn a plain list item or a normal
12685 line into a subheading."
12686 (interactive)
12687 (cond
12688 ((org-at-table-p)
12689 (call-interactively 'org-table-recalculate))
12690 ((org-region-active-p)
12691 ;; Convert all lines in region to list items
12692 (call-interactively 'org-toggle-region-headings))
12693 ((org-on-heading-p)
12694 (org-toggle-region-headings (point-at-bol)
12695 (min (1+ (point-at-eol)) (point-max))))
12696 ((org-at-item-p)
12697 ;; Convert to heading
12698 (let ((level (save-match-data
12699 (save-excursion
12700 (condition-case nil
12701 (progn
12702 (org-back-to-heading t)
12703 (funcall outline-level))
12704 (error 0))))))
12705 (replace-match
12706 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12707 (t (org-toggle-region-headings (point-at-bol)
12708 (min (1+ (point-at-eol)) (point-max))))))
12710 (defun org-ctrl-c-minus ()
12711 "Insert separator line in table or modify bullet status of line.
12712 Also turns a plain line or a region of lines into list items.
12713 Calls `org-table-insert-hline', `org-toggle-region-items', or
12714 `org-cycle-list-bullet', depending on context."
12715 (interactive)
12716 (cond
12717 ((org-at-table-p)
12718 (call-interactively 'org-table-insert-hline))
12719 ((org-on-heading-p)
12720 ;; Convert to item
12721 (save-excursion
12722 (beginning-of-line 1)
12723 (if (looking-at "\\*+ ")
12724 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12725 ((org-region-active-p)
12726 ;; Convert all lines in region to list items
12727 (call-interactively 'org-toggle-region-items))
12728 ((org-in-item-p)
12729 (call-interactively 'org-cycle-list-bullet))
12730 (t (org-toggle-region-items (point-at-bol)
12731 (min (1+ (point-at-eol)) (point-max))))))
12733 (defun org-toggle-region-items (beg end)
12734 "Convert all lines in region to list items.
12735 If the first line is already an item, convert all list items in the region
12736 to normal lines."
12737 (interactive "r")
12738 (let (l2 l)
12739 (save-excursion
12740 (goto-char end)
12741 (setq l2 (org-current-line))
12742 (goto-char beg)
12743 (beginning-of-line 1)
12744 (setq l (1- (org-current-line)))
12745 (if (org-at-item-p)
12746 ;; We already have items, de-itemize
12747 (while (< (setq l (1+ l)) l2)
12748 (when (org-at-item-p)
12749 (goto-char (match-beginning 2))
12750 (delete-region (match-beginning 2) (match-end 2))
12751 (and (looking-at "[ \t]+") (replace-match "")))
12752 (beginning-of-line 2))
12753 (while (< (setq l (1+ l)) l2)
12754 (unless (org-at-item-p)
12755 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12756 (replace-match "\\1- \\2")))
12757 (beginning-of-line 2))))))
12759 (defun org-toggle-region-headings (beg end)
12760 "Convert all lines in region to list items.
12761 If the first line is already an item, convert all list items in the region
12762 to normal lines."
12763 (interactive "r")
12764 (let (l2 l)
12765 (save-excursion
12766 (goto-char end)
12767 (setq l2 (org-current-line))
12768 (goto-char beg)
12769 (beginning-of-line 1)
12770 (setq l (1- (org-current-line)))
12771 (if (org-on-heading-p)
12772 ;; We already have headlines, de-star them
12773 (while (< (setq l (1+ l)) l2)
12774 (when (org-on-heading-p t)
12775 (and (looking-at outline-regexp) (replace-match "")))
12776 (beginning-of-line 2))
12777 (let* ((stars (save-excursion
12778 (re-search-backward org-complex-heading-regexp nil t)
12779 (or (match-string 1) "*")))
12780 (add-stars (if org-odd-levels-only "**" "*"))
12781 (rpl (concat stars add-stars " \\2")))
12782 (while (< (setq l (1+ l)) l2)
12783 (unless (org-on-heading-p)
12784 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12785 (replace-match rpl)))
12786 (beginning-of-line 2)))))))
12788 (defun org-meta-return (&optional arg)
12789 "Insert a new heading or wrap a region in a table.
12790 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12791 See the individual commands for more information."
12792 (interactive "P")
12793 (cond
12794 ((org-at-table-p)
12795 (call-interactively 'org-table-wrap-region))
12796 (t (call-interactively 'org-insert-heading))))
12798 ;;; Menu entries
12800 ;; Define the Org-mode menus
12801 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12802 '("Tbl"
12803 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12804 ["Next Field" org-cycle (org-at-table-p)]
12805 ["Previous Field" org-shifttab (org-at-table-p)]
12806 ["Next Row" org-return (org-at-table-p)]
12807 "--"
12808 ["Blank Field" org-table-blank-field (org-at-table-p)]
12809 ["Edit Field" org-table-edit-field (org-at-table-p)]
12810 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12811 "--"
12812 ("Column"
12813 ["Move Column Left" org-metaleft (org-at-table-p)]
12814 ["Move Column Right" org-metaright (org-at-table-p)]
12815 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12816 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12817 ("Row"
12818 ["Move Row Up" org-metaup (org-at-table-p)]
12819 ["Move Row Down" org-metadown (org-at-table-p)]
12820 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12821 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12822 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12823 "--"
12824 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12825 ("Rectangle"
12826 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12827 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12828 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12829 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12830 "--"
12831 ("Calculate"
12832 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12833 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12834 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12835 "--"
12836 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12837 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12838 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12839 "--"
12840 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12841 "--"
12842 ["Sum Column/Rectangle" org-table-sum
12843 (or (org-at-table-p) (org-region-active-p))]
12844 ["Which Column?" org-table-current-column (org-at-table-p)])
12845 ["Debug Formulas"
12846 org-table-toggle-formula-debugger
12847 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12848 ["Show Col/Row Numbers"
12849 org-table-toggle-coordinate-overlays
12850 :style toggle
12851 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12852 "--"
12853 ["Create" org-table-create (and (not (org-at-table-p))
12854 org-enable-table-editor)]
12855 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12856 ["Import from File" org-table-import (not (org-at-table-p))]
12857 ["Export to File" org-table-export (org-at-table-p)]
12858 "--"
12859 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12861 (easy-menu-define org-org-menu org-mode-map "Org menu"
12862 '("Org"
12863 ("Show/Hide"
12864 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12865 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12866 ["Sparse Tree..." org-sparse-tree t]
12867 ["Reveal Context" org-reveal t]
12868 ["Show All" show-all t]
12869 "--"
12870 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12871 "--"
12872 ["New Heading" org-insert-heading t]
12873 ("Navigate Headings"
12874 ["Up" outline-up-heading t]
12875 ["Next" outline-next-visible-heading t]
12876 ["Previous" outline-previous-visible-heading t]
12877 ["Next Same Level" outline-forward-same-level t]
12878 ["Previous Same Level" outline-backward-same-level t]
12879 "--"
12880 ["Jump" org-goto t])
12881 ("Edit Structure"
12882 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12883 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12884 "--"
12885 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12886 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12887 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12888 "--"
12889 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12890 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12891 ["Demote Heading" org-metaright (not (org-at-table-p))]
12892 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12893 "--"
12894 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12895 "--"
12896 ["Convert to odd levels" org-convert-to-odd-levels t]
12897 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12898 ("Editing"
12899 ["Emphasis..." org-emphasize t])
12900 ("Archive"
12901 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12902 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12903 ; :active t :keys "C-u C-c C-x C-a"]
12904 ["Sparse trees open ARCHIVE trees"
12905 (setq org-sparse-tree-open-archived-trees
12906 (not org-sparse-tree-open-archived-trees))
12907 :style toggle :selected org-sparse-tree-open-archived-trees]
12908 ["Cycling opens ARCHIVE trees"
12909 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12910 :style toggle :selected org-cycle-open-archived-trees]
12911 ["Agenda includes ARCHIVE trees"
12912 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12913 :style toggle :selected (not org-agenda-skip-archived-trees)]
12914 "--"
12915 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12916 ; ["Check and Move Children" (org-archive-subtree '(4))
12917 ; :active t :keys "C-u C-c C-x C-s"]
12919 "--"
12920 ("TODO Lists"
12921 ["TODO/DONE/-" org-todo t]
12922 ("Select keyword"
12923 ["Next keyword" org-shiftright (org-on-heading-p)]
12924 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12925 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12926 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12927 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12928 ["Show TODO Tree" org-show-todo-tree t]
12929 ["Global TODO list" org-todo-list t]
12930 "--"
12931 ["Set Priority" org-priority t]
12932 ["Priority Up" org-shiftup t]
12933 ["Priority Down" org-shiftdown t])
12934 ("TAGS and Properties"
12935 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12936 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12937 "--"
12938 ["Set property" 'org-set-property t]
12939 ["Column view of properties" org-columns t]
12940 ["Insert Column View DBlock" org-insert-columns-dblock t])
12941 ("Dates and Scheduling"
12942 ["Timestamp" org-time-stamp t]
12943 ["Timestamp (inactive)" org-time-stamp-inactive t]
12944 ("Change Date"
12945 ["1 Day Later" org-shiftright t]
12946 ["1 Day Earlier" org-shiftleft t]
12947 ["1 ... Later" org-shiftup t]
12948 ["1 ... Earlier" org-shiftdown t])
12949 ["Compute Time Range" org-evaluate-time-range t]
12950 ["Schedule Item" org-schedule t]
12951 ["Deadline" org-deadline t]
12952 "--"
12953 ["Custom time format" org-toggle-time-stamp-overlays
12954 :style radio :selected org-display-custom-times]
12955 "--"
12956 ["Goto Calendar" org-goto-calendar t]
12957 ["Date from Calendar" org-date-from-calendar t])
12958 ("Logging work"
12959 ["Clock in" org-clock-in t]
12960 ["Clock out" org-clock-out t]
12961 ["Clock cancel" org-clock-cancel t]
12962 ["Goto running clock" org-clock-goto t]
12963 ["Display times" org-clock-display t]
12964 ["Create clock table" org-clock-report t]
12965 "--"
12966 ["Record DONE time"
12967 (progn (setq org-log-done (not org-log-done))
12968 (message "Switching to %s will %s record a timestamp"
12969 (car org-done-keywords)
12970 (if org-log-done "automatically" "not")))
12971 :style toggle :selected org-log-done])
12972 "--"
12973 ["Agenda Command..." org-agenda t]
12974 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12975 ("File List for Agenda")
12976 ("Special views current file"
12977 ["TODO Tree" org-show-todo-tree t]
12978 ["Check Deadlines" org-check-deadlines t]
12979 ["Timeline" org-timeline t]
12980 ["Tags Tree" org-tags-sparse-tree t])
12981 "--"
12982 ("Hyperlinks"
12983 ["Store Link (Global)" org-store-link t]
12984 ["Insert Link" org-insert-link t]
12985 ["Follow Link" org-open-at-point t]
12986 "--"
12987 ["Next link" org-next-link t]
12988 ["Previous link" org-previous-link t]
12989 "--"
12990 ["Descriptive Links"
12991 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12992 :style radio
12993 :selected (member '(org-link) buffer-invisibility-spec)]
12994 ["Literal Links"
12995 (progn
12996 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12997 :style radio
12998 :selected (not (member '(org-link) buffer-invisibility-spec))])
12999 "--"
13000 ["Export/Publish..." org-export t]
13001 ("LaTeX"
13002 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13003 :selected org-cdlatex-mode]
13004 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13005 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13006 ["Modify math symbol" org-cdlatex-math-modify
13007 (org-inside-LaTeX-fragment-p)]
13008 ["Export LaTeX fragments as images"
13009 (if (featurep 'org-exp)
13010 (setq org-export-with-LaTeX-fragments
13011 (not org-export-with-LaTeX-fragments))
13012 (require 'org-exp))
13013 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13014 org-export-with-LaTeX-fragments)])
13015 "--"
13016 ("Documentation"
13017 ["Show Version" org-version t]
13018 ["Info Documentation" org-info t])
13019 ("Customize"
13020 ["Browse Org Group" org-customize t]
13021 "--"
13022 ["Expand This Menu" org-create-customize-menu
13023 (fboundp 'customize-menu-create)])
13024 "--"
13025 ["Refresh setup" org-mode-restart t]
13028 (defun org-info (&optional node)
13029 "Read documentation for Org-mode in the info system.
13030 With optional NODE, go directly to that node."
13031 (interactive)
13032 (info (format "(org)%s" (or node ""))))
13034 (defun org-install-agenda-files-menu ()
13035 (let ((bl (buffer-list)))
13036 (save-excursion
13037 (while bl
13038 (set-buffer (pop bl))
13039 (if (org-mode-p) (setq bl nil)))
13040 (when (org-mode-p)
13041 (easy-menu-change
13042 '("Org") "File List for Agenda"
13043 (append
13044 (list
13045 ["Edit File List" (org-edit-agenda-file-list) t]
13046 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13047 ["Remove Current File from List" org-remove-file t]
13048 ["Cycle through agenda files" org-cycle-agenda-files t]
13049 ["Occur in all agenda files" org-occur-in-agenda-files t]
13050 "--")
13051 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13053 ;;;; Documentation
13055 (defun org-require-autoloaded-modules ()
13056 (interactive)
13057 (mapc 'require
13058 '(org-agenda org-archive org-clock org-colview
13059 org-exp org-export-latex org-publish
13060 org-remember org-table)))
13062 (defun org-customize ()
13063 "Call the customize function with org as argument."
13064 (interactive)
13065 (org-load-modules-maybe)
13066 (org-require-autoloaded-modules)
13067 (customize-browse 'org))
13069 (defun org-create-customize-menu ()
13070 "Create a full customization menu for Org-mode, insert it into the menu."
13071 (interactive)
13072 (org-load-modules-maybe)
13073 (org-require-autoloaded-modules)
13074 (if (fboundp 'customize-menu-create)
13075 (progn
13076 (easy-menu-change
13077 '("Org") "Customize"
13078 `(["Browse Org group" org-customize t]
13079 "--"
13080 ,(customize-menu-create 'org)
13081 ["Set" Custom-set t]
13082 ["Save" Custom-save t]
13083 ["Reset to Current" Custom-reset-current t]
13084 ["Reset to Saved" Custom-reset-saved t]
13085 ["Reset to Standard Settings" Custom-reset-standard t]))
13086 (message "\"Org\"-menu now contains full customization menu"))
13087 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13089 ;;;; Miscellaneous stuff
13091 ;;; Generally useful functions
13093 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13094 "Display the given MESSAGE as a warning."
13095 (if (fboundp 'display-warning)
13096 (display-warning 'org message
13097 (if (featurep 'xemacs)
13098 'warning
13099 :warning))
13100 (let ((buf (get-buffer-create "*Org warnings*")))
13101 (with-current-buffer buf
13102 (goto-char (point-max))
13103 (insert "Warning (Org): " message)
13104 (unless (bolp)
13105 (newline)))
13106 (display-buffer buf)
13107 (sit-for 0))))
13109 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13110 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13111 (if (and marker (marker-buffer marker)
13112 (buffer-live-p (marker-buffer marker)))
13113 (progn
13114 (switch-to-buffer (marker-buffer marker))
13115 (if (or (> marker (point-max)) (< marker (point-min)))
13116 (widen))
13117 (goto-char marker))
13118 (if bookmark
13119 (bookmark-jump bookmark)
13120 (error "Cannot find location"))))
13122 (defun org-quote-csv-field (s)
13123 "Quote field for inclusion in CSV material."
13124 (if (string-match "[\",]" s)
13125 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13128 (defun org-plist-delete (plist property)
13129 "Delete PROPERTY from PLIST.
13130 This is in contrast to merely setting it to 0."
13131 (let (p)
13132 (while plist
13133 (if (not (eq property (car plist)))
13134 (setq p (plist-put p (car plist) (nth 1 plist))))
13135 (setq plist (cddr plist)))
13138 (defun org-force-self-insert (N)
13139 "Needed to enforce self-insert under remapping."
13140 (interactive "p")
13141 (self-insert-command N))
13143 (defun org-string-width (s)
13144 "Compute width of string, ignoring invisible characters.
13145 This ignores character with invisibility property `org-link', and also
13146 characters with property `org-cwidth', because these will become invisible
13147 upon the next fontification round."
13148 (let (b l)
13149 (when (or (eq t buffer-invisibility-spec)
13150 (assq 'org-link buffer-invisibility-spec))
13151 (while (setq b (text-property-any 0 (length s)
13152 'invisible 'org-link s))
13153 (setq s (concat (substring s 0 b)
13154 (substring s (or (next-single-property-change
13155 b 'invisible s) (length s)))))))
13156 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13157 (setq s (concat (substring s 0 b)
13158 (substring s (or (next-single-property-change
13159 b 'org-cwidth s) (length s))))))
13160 (setq l (string-width s) b -1)
13161 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13162 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13165 (defun org-base-buffer (buffer)
13166 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13167 (if (not buffer)
13168 buffer
13169 (or (buffer-base-buffer buffer)
13170 buffer)))
13172 (defun org-trim (s)
13173 "Remove whitespace at beginning and end of string."
13174 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13175 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13178 (defun org-wrap (string &optional width lines)
13179 "Wrap string to either a number of lines, or a width in characters.
13180 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13181 that costs. If there is a word longer than WIDTH, the text is actually
13182 wrapped to the length of that word.
13183 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13184 many lines, whatever width that takes.
13185 The return value is a list of lines, without newlines at the end."
13186 (let* ((words (org-split-string string "[ \t\n]+"))
13187 (maxword (apply 'max (mapcar 'org-string-width words)))
13188 w ll)
13189 (cond (width
13190 (org-do-wrap words (max maxword width)))
13191 (lines
13192 (setq w maxword)
13193 (setq ll (org-do-wrap words maxword))
13194 (if (<= (length ll) lines)
13196 (setq ll words)
13197 (while (> (length ll) lines)
13198 (setq w (1+ w))
13199 (setq ll (org-do-wrap words w)))
13200 ll))
13201 (t (error "Cannot wrap this")))))
13203 (defun org-do-wrap (words width)
13204 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13205 (let (lines line)
13206 (while words
13207 (setq line (pop words))
13208 (while (and words (< (+ (length line) (length (car words))) width))
13209 (setq line (concat line " " (pop words))))
13210 (setq lines (push line lines)))
13211 (nreverse lines)))
13213 (defun org-split-string (string &optional separators)
13214 "Splits STRING into substrings at SEPARATORS.
13215 No empty strings are returned if there are matches at the beginning
13216 and end of string."
13217 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13218 (start 0)
13219 notfirst
13220 (list nil))
13221 (while (and (string-match rexp string
13222 (if (and notfirst
13223 (= start (match-beginning 0))
13224 (< start (length string)))
13225 (1+ start) start))
13226 (< (match-beginning 0) (length string)))
13227 (setq notfirst t)
13228 (or (eq (match-beginning 0) 0)
13229 (and (eq (match-beginning 0) (match-end 0))
13230 (eq (match-beginning 0) start))
13231 (setq list
13232 (cons (substring string start (match-beginning 0))
13233 list)))
13234 (setq start (match-end 0)))
13235 (or (eq start (length string))
13236 (setq list
13237 (cons (substring string start)
13238 list)))
13239 (nreverse list)))
13241 (defun org-context ()
13242 "Return a list of contexts of the current cursor position.
13243 If several contexts apply, all are returned.
13244 Each context entry is a list with a symbol naming the context, and
13245 two positions indicating start and end of the context. Possible
13246 contexts are:
13248 :headline anywhere in a headline
13249 :headline-stars on the leading stars in a headline
13250 :todo-keyword on a TODO keyword (including DONE) in a headline
13251 :tags on the TAGS in a headline
13252 :priority on the priority cookie in a headline
13253 :item on the first line of a plain list item
13254 :item-bullet on the bullet/number of a plain list item
13255 :checkbox on the checkbox in a plain list item
13256 :table in an org-mode table
13257 :table-special on a special filed in a table
13258 :table-table in a table.el table
13259 :link on a hyperlink
13260 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13261 :target on a <<target>>
13262 :radio-target on a <<<radio-target>>>
13263 :latex-fragment on a LaTeX fragment
13264 :latex-preview on a LaTeX fragment with overlayed preview image
13266 This function expects the position to be visible because it uses font-lock
13267 faces as a help to recognize the following contexts: :table-special, :link,
13268 and :keyword."
13269 (let* ((f (get-text-property (point) 'face))
13270 (faces (if (listp f) f (list f)))
13271 (p (point)) clist o)
13272 ;; First the large context
13273 (cond
13274 ((org-on-heading-p t)
13275 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13276 (when (progn
13277 (beginning-of-line 1)
13278 (looking-at org-todo-line-tags-regexp))
13279 (push (org-point-in-group p 1 :headline-stars) clist)
13280 (push (org-point-in-group p 2 :todo-keyword) clist)
13281 (push (org-point-in-group p 4 :tags) clist))
13282 (goto-char p)
13283 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13284 (if (looking-at "\\[#[A-Z0-9]\\]")
13285 (push (org-point-in-group p 0 :priority) clist)))
13287 ((org-at-item-p)
13288 (push (org-point-in-group p 2 :item-bullet) clist)
13289 (push (list :item (point-at-bol)
13290 (save-excursion (org-end-of-item) (point)))
13291 clist)
13292 (and (org-at-item-checkbox-p)
13293 (push (org-point-in-group p 0 :checkbox) clist)))
13295 ((org-at-table-p)
13296 (push (list :table (org-table-begin) (org-table-end)) clist)
13297 (if (memq 'org-formula faces)
13298 (push (list :table-special
13299 (previous-single-property-change p 'face)
13300 (next-single-property-change p 'face)) clist)))
13301 ((org-at-table-p 'any)
13302 (push (list :table-table) clist)))
13303 (goto-char p)
13305 ;; Now the small context
13306 (cond
13307 ((org-at-timestamp-p)
13308 (push (org-point-in-group p 0 :timestamp) clist))
13309 ((memq 'org-link faces)
13310 (push (list :link
13311 (previous-single-property-change p 'face)
13312 (next-single-property-change p 'face)) clist))
13313 ((memq 'org-special-keyword faces)
13314 (push (list :keyword
13315 (previous-single-property-change p 'face)
13316 (next-single-property-change p 'face)) clist))
13317 ((org-on-target-p)
13318 (push (org-point-in-group p 0 :target) clist)
13319 (goto-char (1- (match-beginning 0)))
13320 (if (looking-at org-radio-target-regexp)
13321 (push (org-point-in-group p 0 :radio-target) clist))
13322 (goto-char p))
13323 ((setq o (car (delq nil
13324 (mapcar
13325 (lambda (x)
13326 (if (memq x org-latex-fragment-image-overlays) x))
13327 (org-overlays-at (point))))))
13328 (push (list :latex-fragment
13329 (org-overlay-start o) (org-overlay-end o)) clist)
13330 (push (list :latex-preview
13331 (org-overlay-start o) (org-overlay-end o)) clist))
13332 ((org-inside-LaTeX-fragment-p)
13333 ;; FIXME: positions wrong.
13334 (push (list :latex-fragment (point) (point)) clist)))
13336 (setq clist (nreverse (delq nil clist)))
13337 clist))
13339 ;; FIXME: Compare with at-regexp-p Do we need both?
13340 (defun org-in-regexp (re &optional nlines visually)
13341 "Check if point is inside a match of regexp.
13342 Normally only the current line is checked, but you can include NLINES extra
13343 lines both before and after point into the search.
13344 If VISUALLY is set, require that the cursor is not after the match but
13345 really on, so that the block visually is on the match."
13346 (catch 'exit
13347 (let ((pos (point))
13348 (eol (point-at-eol (+ 1 (or nlines 0))))
13349 (inc (if visually 1 0)))
13350 (save-excursion
13351 (beginning-of-line (- 1 (or nlines 0)))
13352 (while (re-search-forward re eol t)
13353 (if (and (<= (match-beginning 0) pos)
13354 (>= (+ inc (match-end 0)) pos))
13355 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13357 (defun org-at-regexp-p (regexp)
13358 "Is point inside a match of REGEXP in the current line?"
13359 (catch 'exit
13360 (save-excursion
13361 (let ((pos (point)) (end (point-at-eol)))
13362 (beginning-of-line 1)
13363 (while (re-search-forward regexp end t)
13364 (if (and (<= (match-beginning 0) pos)
13365 (>= (match-end 0) pos))
13366 (throw 'exit t)))
13367 nil))))
13369 (defun org-occur-in-agenda-files (regexp &optional nlines)
13370 "Call `multi-occur' with buffers for all agenda files."
13371 (interactive "sOrg-files matching: \np")
13372 (let* ((files (org-agenda-files))
13373 (tnames (mapcar 'file-truename files))
13374 (extra org-agenda-text-search-extra-files)
13376 (when (eq (car extra) 'agenda-archives)
13377 (setq extra (cdr extra))
13378 (setq files (org-add-archive-files files)))
13379 (while (setq f (pop extra))
13380 (unless (member (file-truename f) tnames)
13381 (add-to-list 'files f 'append)
13382 (add-to-list 'tnames (file-truename f) 'append)))
13383 (multi-occur
13384 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13385 regexp)))
13387 (if (boundp 'occur-mode-find-occurrence-hook)
13388 ;; Emacs 23
13389 (add-hook 'occur-mode-find-occurrence-hook
13390 (lambda ()
13391 (when (org-mode-p)
13392 (org-reveal))))
13393 ;; Emacs 22
13394 (defadvice occur-mode-goto-occurrence
13395 (after org-occur-reveal activate)
13396 (and (org-mode-p) (org-reveal)))
13397 (defadvice occur-mode-goto-occurrence-other-window
13398 (after org-occur-reveal activate)
13399 (and (org-mode-p) (org-reveal)))
13400 (defadvice occur-mode-display-occurrence
13401 (after org-occur-reveal activate)
13402 (when (org-mode-p)
13403 (let ((pos (occur-mode-find-occurrence)))
13404 (with-current-buffer (marker-buffer pos)
13405 (save-excursion
13406 (goto-char pos)
13407 (org-reveal)))))))
13409 (defun org-uniquify (list)
13410 "Remove duplicate elements from LIST."
13411 (let (res)
13412 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13413 res))
13415 (defun org-delete-all (elts list)
13416 "Remove all elements in ELTS from LIST."
13417 (while elts
13418 (setq list (delete (pop elts) list)))
13419 list)
13421 (defun org-back-over-empty-lines ()
13422 "Move backwards over witespace, to the beginning of the first empty line.
13423 Returns the number of empty lines passed."
13424 (let ((pos (point)))
13425 (skip-chars-backward " \t\n\r")
13426 (beginning-of-line 2)
13427 (goto-char (min (point) pos))
13428 (count-lines (point) pos)))
13430 (defun org-skip-whitespace ()
13431 (skip-chars-forward " \t\n\r"))
13433 (defun org-point-in-group (point group &optional context)
13434 "Check if POINT is in match-group GROUP.
13435 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13436 match. If the match group does ot exist or point is not inside it,
13437 return nil."
13438 (and (match-beginning group)
13439 (>= point (match-beginning group))
13440 (<= point (match-end group))
13441 (if context
13442 (list context (match-beginning group) (match-end group))
13443 t)))
13445 (defun org-switch-to-buffer-other-window (&rest args)
13446 "Switch to buffer in a second window on the current frame.
13447 In particular, do not allow pop-up frames."
13448 (let (pop-up-frames special-display-buffer-names special-display-regexps
13449 special-display-function)
13450 (apply 'switch-to-buffer-other-window args)))
13452 (defun org-combine-plists (&rest plists)
13453 "Create a single property list from all plists in PLISTS.
13454 The process starts by copying the first list, and then setting properties
13455 from the other lists. Settings in the last list are the most significant
13456 ones and overrule settings in the other lists."
13457 (let ((rtn (copy-sequence (pop plists)))
13458 p v ls)
13459 (while plists
13460 (setq ls (pop plists))
13461 (while ls
13462 (setq p (pop ls) v (pop ls))
13463 (setq rtn (plist-put rtn p v))))
13464 rtn))
13466 (defun org-move-line-down (arg)
13467 "Move the current line down. With prefix argument, move it past ARG lines."
13468 (interactive "p")
13469 (let ((col (current-column))
13470 beg end pos)
13471 (beginning-of-line 1) (setq beg (point))
13472 (beginning-of-line 2) (setq end (point))
13473 (beginning-of-line (+ 1 arg))
13474 (setq pos (move-marker (make-marker) (point)))
13475 (insert (delete-and-extract-region beg end))
13476 (goto-char pos)
13477 (org-move-to-column col)))
13479 (defun org-move-line-up (arg)
13480 "Move the current line up. With prefix argument, move it past ARG lines."
13481 (interactive "p")
13482 (let ((col (current-column))
13483 beg end pos)
13484 (beginning-of-line 1) (setq beg (point))
13485 (beginning-of-line 2) (setq end (point))
13486 (beginning-of-line (- arg))
13487 (setq pos (move-marker (make-marker) (point)))
13488 (insert (delete-and-extract-region beg end))
13489 (goto-char pos)
13490 (org-move-to-column col)))
13492 (defun org-replace-escapes (string table)
13493 "Replace %-escapes in STRING with values in TABLE.
13494 TABLE is an association list with keys like \"%a\" and string values.
13495 The sequences in STRING may contain normal field width and padding information,
13496 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13497 so values can contain further %-escapes if they are define later in TABLE."
13498 (let ((case-fold-search nil)
13499 e re rpl)
13500 (while (setq e (pop table))
13501 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13502 (while (string-match re string)
13503 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13504 (cdr e)))
13505 (setq string (replace-match rpl t t string))))
13506 string))
13509 (defun org-sublist (list start end)
13510 "Return a section of LIST, from START to END.
13511 Counting starts at 1."
13512 (let (rtn (c start))
13513 (setq list (nthcdr (1- start) list))
13514 (while (and list (<= c end))
13515 (push (pop list) rtn)
13516 (setq c (1+ c)))
13517 (nreverse rtn)))
13519 (defun org-find-base-buffer-visiting (file)
13520 "Like `find-buffer-visiting' but alway return the base buffer and
13521 not an indirect buffer."
13522 (let ((buf (find-buffer-visiting file)))
13523 (if buf
13524 (or (buffer-base-buffer buf) buf)
13525 nil)))
13527 (defun org-image-file-name-regexp ()
13528 "Return regexp matching the file names of images."
13529 (if (fboundp 'image-file-name-regexp)
13530 (image-file-name-regexp)
13531 (let ((image-file-name-extensions
13532 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13533 "xbm" "xpm" "pbm" "pgm" "ppm")))
13534 (concat "\\."
13535 (regexp-opt (nconc (mapcar 'upcase
13536 image-file-name-extensions)
13537 image-file-name-extensions)
13539 "\\'"))))
13541 (defun org-file-image-p (file)
13542 "Return non-nil if FILE is an image."
13543 (save-match-data
13544 (string-match (org-image-file-name-regexp) file)))
13546 ;;; Paragraph filling stuff.
13547 ;; We want this to be just right, so use the full arsenal.
13549 (defun org-indent-line-function ()
13550 "Indent line like previous, but further if previous was headline or item."
13551 (interactive)
13552 (let* ((pos (point))
13553 (itemp (org-at-item-p))
13554 column bpos bcol tpos tcol bullet btype bullet-type)
13555 ;; Find the previous relevant line
13556 (beginning-of-line 1)
13557 (cond
13558 ((looking-at "#") (setq column 0))
13559 ((looking-at "\\*+ ") (setq column 0))
13561 (beginning-of-line 0)
13562 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13563 (beginning-of-line 0))
13564 (cond
13565 ((looking-at "\\*+[ \t]+")
13566 (goto-char (match-end 0))
13567 (setq column (current-column)))
13568 ((org-in-item-p)
13569 (org-beginning-of-item)
13570 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13571 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13572 (setq bpos (match-beginning 1) tpos (match-end 0)
13573 bcol (progn (goto-char bpos) (current-column))
13574 tcol (progn (goto-char tpos) (current-column))
13575 bullet (match-string 1)
13576 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13577 (if (> tcol (+ bcol org-description-max-indent))
13578 (setq tcol (+ bcol 5)))
13579 (if (not itemp)
13580 (setq column tcol)
13581 (goto-char pos)
13582 (beginning-of-line 1)
13583 (if (looking-at "\\S-")
13584 (progn
13585 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13586 (setq bullet (match-string 1)
13587 btype (if (string-match "[0-9]" bullet) "n" bullet))
13588 (setq column (if (equal btype bullet-type) bcol tcol)))
13589 (setq column (org-get-indentation)))))
13590 (t (setq column (org-get-indentation))))))
13591 (goto-char pos)
13592 (if (<= (current-column) (current-indentation))
13593 (org-indent-line-to column)
13594 (save-excursion (org-indent-line-to column)))
13595 (setq column (current-column))
13596 (beginning-of-line 1)
13597 (if (looking-at
13598 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13599 (replace-match (concat "\\1" (format org-property-format
13600 (match-string 2) (match-string 3)))
13601 t nil))
13602 (org-move-to-column column)))
13604 (defun org-set-autofill-regexps ()
13605 (interactive)
13606 ;; In the paragraph separator we include headlines, because filling
13607 ;; text in a line directly attached to a headline would otherwise
13608 ;; fill the headline as well.
13609 (org-set-local 'comment-start-skip "^#+[ \t]*")
13610 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13611 ;; The paragraph starter includes hand-formatted lists.
13612 (org-set-local 'paragraph-start
13613 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13614 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13615 ;; But only if the user has not turned off tables or fixed-width regions
13616 (org-set-local
13617 'auto-fill-inhibit-regexp
13618 (concat "\\*+ \\|#\\+"
13619 "\\|[ \t]*" org-keyword-time-regexp
13620 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13621 (concat
13622 "\\|[ \t]*["
13623 (if org-enable-table-editor "|" "")
13624 (if org-enable-fixed-width-editor ":" "")
13625 "]"))))
13626 ;; We use our own fill-paragraph function, to make sure that tables
13627 ;; and fixed-width regions are not wrapped. That function will pass
13628 ;; through to `fill-paragraph' when appropriate.
13629 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13630 ; Adaptive filling: To get full control, first make sure that
13631 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13632 (org-set-local 'adaptive-fill-regexp "\000")
13633 (org-set-local 'adaptive-fill-function
13634 'org-adaptive-fill-function)
13635 (org-set-local
13636 'align-mode-rules-list
13637 '((org-in-buffer-settings
13638 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13639 (modes . '(org-mode))))))
13641 (defun org-fill-paragraph (&optional justify)
13642 "Re-align a table, pass through to fill-paragraph if no table."
13643 (let ((table-p (org-at-table-p))
13644 (table.el-p (org-at-table.el-p)))
13645 (cond ((and (equal (char-after (point-at-bol)) ?*)
13646 (save-excursion (goto-char (point-at-bol))
13647 (looking-at outline-regexp)))
13648 t) ; skip headlines
13649 (table.el-p t) ; skip table.el tables
13650 (table-p (org-table-align) t) ; align org-mode tables
13651 (t nil)))) ; call paragraph-fill
13653 ;; For reference, this is the default value of adaptive-fill-regexp
13654 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13656 (defun org-adaptive-fill-function ()
13657 "Return a fill prefix for org-mode files.
13658 In particular, this makes sure hanging paragraphs for hand-formatted lists
13659 work correctly."
13660 (cond ((looking-at "#[ \t]+")
13661 (match-string 0))
13662 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13663 (save-excursion
13664 (if (> (match-end 1) (+ (match-beginning 1)
13665 org-description-max-indent))
13666 (goto-char (+ (match-beginning 1) 5))
13667 (goto-char (match-end 0)))
13668 (make-string (current-column) ?\ )))
13669 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13670 (save-excursion
13671 (goto-char (match-end 0))
13672 (make-string (current-column) ?\ )))
13673 (t nil)))
13675 ;;; Other stuff.
13677 (defun org-toggle-fixed-width-section (arg)
13678 "Toggle the fixed-width export.
13679 If there is no active region, the QUOTE keyword at the current headline is
13680 inserted or removed. When present, it causes the text between this headline
13681 and the next to be exported as fixed-width text, and unmodified.
13682 If there is an active region, this command adds or removes a colon as the
13683 first character of this line. If the first character of a line is a colon,
13684 this line is also exported in fixed-width font."
13685 (interactive "P")
13686 (let* ((cc 0)
13687 (regionp (org-region-active-p))
13688 (beg (if regionp (region-beginning) (point)))
13689 (end (if regionp (region-end)))
13690 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13691 (case-fold-search nil)
13692 (re "[ \t]*\\(:\\)")
13693 off)
13694 (if regionp
13695 (save-excursion
13696 (goto-char beg)
13697 (setq cc (current-column))
13698 (beginning-of-line 1)
13699 (setq off (looking-at re))
13700 (while (> nlines 0)
13701 (setq nlines (1- nlines))
13702 (beginning-of-line 1)
13703 (cond
13704 (arg
13705 (org-move-to-column cc t)
13706 (insert ":\n")
13707 (forward-line -1))
13708 ((and off (looking-at re))
13709 (replace-match "" t t nil 1))
13710 ((not off) (org-move-to-column cc t) (insert ":")))
13711 (forward-line 1)))
13712 (save-excursion
13713 (org-back-to-heading)
13714 (if (looking-at (concat outline-regexp
13715 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13716 (replace-match "" t t nil 1)
13717 (if (looking-at outline-regexp)
13718 (progn
13719 (goto-char (match-end 0))
13720 (insert org-quote-string " "))))))))
13722 ;;;; Functions extending outline functionality
13724 (defun org-beginning-of-line (&optional arg)
13725 "Go to the beginning of the current line. If that is invisible, continue
13726 to a visible line beginning. This makes the function of C-a more intuitive.
13727 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13728 first attempt, and only move to after the tags when the cursor is already
13729 beyond the end of the headline."
13730 (interactive "P")
13731 (let ((pos (point)))
13732 (beginning-of-line 1)
13733 (if (bobp)
13735 (backward-char 1)
13736 (if (org-invisible-p)
13737 (while (and (not (bobp)) (org-invisible-p))
13738 (backward-char 1)
13739 (beginning-of-line 1))
13740 (forward-char 1)))
13741 (when org-special-ctrl-a/e
13742 (cond
13743 ((and (looking-at org-todo-line-regexp)
13744 (= (char-after (match-end 1)) ?\ ))
13745 (goto-char
13746 (if (eq org-special-ctrl-a/e t)
13747 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13748 ((= pos (point)) (match-beginning 3))
13749 (t (point)))
13750 (cond ((> pos (point)) (point))
13751 ((not (eq last-command this-command)) (point))
13752 (t (match-beginning 3))))))
13753 ((org-at-item-p)
13754 (goto-char
13755 (if (eq org-special-ctrl-a/e t)
13756 (cond ((> pos (match-end 4)) (match-end 4))
13757 ((= pos (point)) (match-end 4))
13758 (t (point)))
13759 (cond ((> pos (point)) (point))
13760 ((not (eq last-command this-command)) (point))
13761 (t (match-end 4))))))))))
13763 (defun org-end-of-line (&optional arg)
13764 "Go to the end of the line.
13765 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13766 first attempt, and only move to after the tags when the cursor is already
13767 beyond the end of the headline."
13768 (interactive "P")
13769 (if (or (not org-special-ctrl-a/e)
13770 (not (org-on-heading-p)))
13771 (end-of-line arg)
13772 (let ((pos (point)))
13773 (beginning-of-line 1)
13774 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13775 (if (eq org-special-ctrl-a/e t)
13776 (if (or (< pos (match-beginning 1))
13777 (= pos (match-end 0)))
13778 (goto-char (match-beginning 1))
13779 (goto-char (match-end 0)))
13780 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13781 (goto-char (match-end 0))
13782 (goto-char (match-beginning 1))))
13783 (end-of-line arg)))))
13785 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13786 (define-key org-mode-map "\C-e" 'org-end-of-line)
13788 (defun org-kill-line (&optional arg)
13789 "Kill line, to tags or end of line."
13790 (interactive "P")
13791 (cond
13792 ((or (not org-special-ctrl-k)
13793 (bolp)
13794 (not (org-on-heading-p)))
13795 (call-interactively 'kill-line))
13796 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13797 (kill-region (point) (match-beginning 1))
13798 (org-set-tags nil t))
13799 (t (kill-region (point) (point-at-eol)))))
13801 (define-key org-mode-map "\C-k" 'org-kill-line)
13803 (defun org-invisible-p ()
13804 "Check if point is at a character currently not visible."
13805 ;; Early versions of noutline don't have `outline-invisible-p'.
13806 (if (fboundp 'outline-invisible-p)
13807 (outline-invisible-p)
13808 (get-char-property (point) 'invisible)))
13810 (defun org-invisible-p2 ()
13811 "Check if point is at a character currently not visible."
13812 (save-excursion
13813 (if (and (eolp) (not (bobp))) (backward-char 1))
13814 ;; Early versions of noutline don't have `outline-invisible-p'.
13815 (if (fboundp 'outline-invisible-p)
13816 (outline-invisible-p)
13817 (get-char-property (point) 'invisible))))
13819 (defalias 'org-back-to-heading 'outline-back-to-heading)
13820 (defalias 'org-on-heading-p 'outline-on-heading-p)
13821 (defalias 'org-at-heading-p 'outline-on-heading-p)
13822 (defun org-at-heading-or-item-p ()
13823 (or (org-on-heading-p) (org-at-item-p)))
13825 (defun org-on-target-p ()
13826 (or (org-in-regexp org-radio-target-regexp)
13827 (org-in-regexp org-target-regexp)))
13829 (defun org-up-heading-all (arg)
13830 "Move to the heading line of which the present line is a subheading.
13831 This function considers both visible and invisible heading lines.
13832 With argument, move up ARG levels."
13833 (if (fboundp 'outline-up-heading-all)
13834 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13835 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13837 (defun org-up-heading-safe ()
13838 "Move to the heading line of which the present line is a subheading.
13839 This version will not throw an error. It will return the level of the
13840 headline found, or nil if no higher level is found."
13841 (let ((pos (point)) start-level level
13842 (re (concat "^" outline-regexp)))
13843 (catch 'exit
13844 (outline-back-to-heading t)
13845 (setq start-level (funcall outline-level))
13846 (if (equal start-level 1) (throw 'exit nil))
13847 (while (re-search-backward re nil t)
13848 (setq level (funcall outline-level))
13849 (if (< level start-level) (throw 'exit level)))
13850 nil)))
13852 (defun org-first-sibling-p ()
13853 "Is this heading the first child of its parents?"
13854 (interactive)
13855 (let ((re (concat "^" outline-regexp))
13856 level l)
13857 (unless (org-at-heading-p t)
13858 (error "Not at a heading"))
13859 (setq level (funcall outline-level))
13860 (save-excursion
13861 (if (not (re-search-backward re nil t))
13863 (setq l (funcall outline-level))
13864 (< l level)))))
13866 (defun org-goto-sibling (&optional previous)
13867 "Goto the next sibling, even if it is invisible.
13868 When PREVIOUS is set, go to the previous sibling instead. Returns t
13869 when a sibling was found. When none is found, return nil and don't
13870 move point."
13871 (let ((fun (if previous 're-search-backward 're-search-forward))
13872 (pos (point))
13873 (re (concat "^" outline-regexp))
13874 level l)
13875 (when (condition-case nil (org-back-to-heading t) (error nil))
13876 (setq level (funcall outline-level))
13877 (catch 'exit
13878 (or previous (forward-char 1))
13879 (while (funcall fun re nil t)
13880 (setq l (funcall outline-level))
13881 (when (< l level) (goto-char pos) (throw 'exit nil))
13882 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13883 (goto-char pos)
13884 nil))))
13886 (defun org-show-siblings ()
13887 "Show all siblings of the current headline."
13888 (save-excursion
13889 (while (org-goto-sibling) (org-flag-heading nil)))
13890 (save-excursion
13891 (while (org-goto-sibling 'previous)
13892 (org-flag-heading nil))))
13894 (defun org-show-hidden-entry ()
13895 "Show an entry where even the heading is hidden."
13896 (save-excursion
13897 (org-show-entry)))
13899 (defun org-flag-heading (flag &optional entry)
13900 "Flag the current heading. FLAG non-nil means make invisible.
13901 When ENTRY is non-nil, show the entire entry."
13902 (save-excursion
13903 (org-back-to-heading t)
13904 ;; Check if we should show the entire entry
13905 (if entry
13906 (progn
13907 (org-show-entry)
13908 (save-excursion
13909 (and (outline-next-heading)
13910 (org-flag-heading nil))))
13911 (outline-flag-region (max (point-min) (1- (point)))
13912 (save-excursion (outline-end-of-heading) (point))
13913 flag))))
13915 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13916 ;; This is an exact copy of the original function, but it uses
13917 ;; `org-back-to-heading', to make it work also in invisible
13918 ;; trees. And is uses an invisible-OK argument.
13919 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13920 (org-back-to-heading invisible-OK)
13921 (let ((first t)
13922 (level (funcall outline-level)))
13923 (while (and (not (eobp))
13924 (or first (> (funcall outline-level) level)))
13925 (setq first nil)
13926 (outline-next-heading))
13927 (unless to-heading
13928 (if (memq (preceding-char) '(?\n ?\^M))
13929 (progn
13930 ;; Go to end of line before heading
13931 (forward-char -1)
13932 (if (memq (preceding-char) '(?\n ?\^M))
13933 ;; leave blank line before heading
13934 (forward-char -1))))))
13935 (point))
13937 (defun org-show-subtree ()
13938 "Show everything after this heading at deeper levels."
13939 (outline-flag-region
13940 (point)
13941 (save-excursion
13942 (outline-end-of-subtree) (outline-next-heading) (point))
13943 nil))
13945 (defun org-show-entry ()
13946 "Show the body directly following this heading.
13947 Show the heading too, if it is currently invisible."
13948 (interactive)
13949 (save-excursion
13950 (condition-case nil
13951 (progn
13952 (org-back-to-heading t)
13953 (outline-flag-region
13954 (max (point-min) (1- (point)))
13955 (save-excursion
13956 (re-search-forward
13957 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13958 (or (match-beginning 1) (point-max)))
13959 nil))
13960 (error nil))))
13962 (defun org-make-options-regexp (kwds)
13963 "Make a regular expression for keyword lines."
13964 (concat
13966 "#?[ \t]*\\+\\("
13967 (mapconcat 'regexp-quote kwds "\\|")
13968 "\\):[ \t]*"
13969 "\\(.+\\)"))
13971 ;; Make isearch reveal the necessary context
13972 (defun org-isearch-end ()
13973 "Reveal context after isearch exits."
13974 (when isearch-success ; only if search was successful
13975 (if (featurep 'xemacs)
13976 ;; Under XEmacs, the hook is run in the correct place,
13977 ;; we directly show the context.
13978 (org-show-context 'isearch)
13979 ;; In Emacs the hook runs *before* restoring the overlays.
13980 ;; So we have to use a one-time post-command-hook to do this.
13981 ;; (Emacs 22 has a special variable, see function `org-mode')
13982 (unless (and (boundp 'isearch-mode-end-hook-quit)
13983 isearch-mode-end-hook-quit)
13984 ;; Only when the isearch was not quitted.
13985 (org-add-hook 'post-command-hook 'org-isearch-post-command
13986 'append 'local)))))
13988 (defun org-isearch-post-command ()
13989 "Remove self from hook, and show context."
13990 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13991 (org-show-context 'isearch))
13994 ;;;; Integration with and fixes for other packages
13996 ;;; Imenu support
13998 (defvar org-imenu-markers nil
13999 "All markers currently used by Imenu.")
14000 (make-variable-buffer-local 'org-imenu-markers)
14002 (defun org-imenu-new-marker (&optional pos)
14003 "Return a new marker for use by Imenu, and remember the marker."
14004 (let ((m (make-marker)))
14005 (move-marker m (or pos (point)))
14006 (push m org-imenu-markers)
14009 (defun org-imenu-get-tree ()
14010 "Produce the index for Imenu."
14011 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14012 (setq org-imenu-markers nil)
14013 (let* ((n org-imenu-depth)
14014 (re (concat "^" outline-regexp))
14015 (subs (make-vector (1+ n) nil))
14016 (last-level 0)
14017 m tree level head)
14018 (save-excursion
14019 (save-restriction
14020 (widen)
14021 (goto-char (point-max))
14022 (while (re-search-backward re nil t)
14023 (setq level (org-reduced-level (funcall outline-level)))
14024 (when (<= level n)
14025 (looking-at org-complex-heading-regexp)
14026 (setq head (org-match-string-no-properties 4)
14027 m (org-imenu-new-marker))
14028 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14029 (if (>= level last-level)
14030 (push (cons head m) (aref subs level))
14031 (push (cons head (aref subs (1+ level))) (aref subs level))
14032 (loop for i from (1+ level) to n do (aset subs i nil)))
14033 (setq last-level level)))))
14034 (aref subs 1)))
14036 (eval-after-load "imenu"
14037 '(progn
14038 (add-hook 'imenu-after-jump-hook
14039 (lambda () (org-show-context 'org-goto)))))
14041 ;; Speedbar support
14043 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14044 "Overlay marking the agenda restriction line in speedbar.")
14045 (org-overlay-put org-speedbar-restriction-lock-overlay
14046 'face 'org-agenda-restriction-lock)
14047 (org-overlay-put org-speedbar-restriction-lock-overlay
14048 'help-echo "Agendas are currently limited to this item.")
14049 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14051 (defun org-speedbar-set-agenda-restriction ()
14052 "Restrict future agenda commands to the location at point in speedbar.
14053 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14054 (interactive)
14055 (require 'org-agenda)
14056 (let (p m tp np dir txt w)
14057 (cond
14058 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14059 'org-imenu t))
14060 (setq m (get-text-property p 'org-imenu-marker))
14061 (save-excursion
14062 (save-restriction
14063 (set-buffer (marker-buffer m))
14064 (goto-char m)
14065 (org-agenda-set-restriction-lock 'subtree))))
14066 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14067 'speedbar-function 'speedbar-find-file))
14068 (setq tp (previous-single-property-change
14069 (1+ p) 'speedbar-function)
14070 np (next-single-property-change
14071 tp 'speedbar-function)
14072 dir (speedbar-line-directory)
14073 txt (buffer-substring-no-properties (or tp (point-min))
14074 (or np (point-max))))
14075 (save-excursion
14076 (save-restriction
14077 (set-buffer (find-file-noselect
14078 (let ((default-directory dir))
14079 (expand-file-name txt))))
14080 (unless (org-mode-p)
14081 (error "Cannot restrict to non-Org-mode file"))
14082 (org-agenda-set-restriction-lock 'file))))
14083 (t (error "Don't know how to restrict Org-mode's agenda")))
14084 (org-move-overlay org-speedbar-restriction-lock-overlay
14085 (point-at-bol) (point-at-eol))
14086 (setq current-prefix-arg nil)
14087 (org-agenda-maybe-redo)))
14089 (eval-after-load "speedbar"
14090 '(progn
14091 (speedbar-add-supported-extension ".org")
14092 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14093 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14094 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14095 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14096 (add-hook 'speedbar-visiting-tag-hook
14097 (lambda () (org-show-context 'org-goto)))))
14100 ;;; Fixes and Hacks for problems with other packages
14102 ;; Make flyspell not check words in links, to not mess up our keymap
14103 (defun org-mode-flyspell-verify ()
14104 "Don't let flyspell put overlays at active buttons."
14105 (not (get-text-property (point) 'keymap)))
14107 ;; Make `bookmark-jump' show the jump location if it was hidden.
14108 (eval-after-load "bookmark"
14109 '(if (boundp 'bookmark-after-jump-hook)
14110 ;; We can use the hook
14111 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14112 ;; Hook not available, use advice
14113 (defadvice bookmark-jump (after org-make-visible activate)
14114 "Make the position visible."
14115 (org-bookmark-jump-unhide))))
14117 (defun org-bookmark-jump-unhide ()
14118 "Unhide the current position, to show the bookmark location."
14119 (and (org-mode-p)
14120 (or (org-invisible-p)
14121 (save-excursion (goto-char (max (point-min) (1- (point))))
14122 (org-invisible-p)))
14123 (org-show-context 'bookmark-jump)))
14125 ;; Make session.el ignore our circular variable
14126 (eval-after-load "session"
14127 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14129 ;;;; Experimental code
14131 (defun org-closed-in-range ()
14132 "Sparse tree of items closed in a certain time range.
14133 Still experimental, may disappear in the future."
14134 (interactive)
14135 ;; Get the time interval from the user.
14136 (let* ((time1 (time-to-seconds
14137 (org-read-date nil 'to-time nil "Starting date: ")))
14138 (time2 (time-to-seconds
14139 (org-read-date nil 'to-time nil "End date:")))
14140 ;; callback function
14141 (callback (lambda ()
14142 (let ((time
14143 (time-to-seconds
14144 (apply 'encode-time
14145 (org-parse-time-string
14146 (match-string 1))))))
14147 ;; check if time in interval
14148 (and (>= time time1) (<= time time2))))))
14149 ;; make tree, check each match with the callback
14150 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14153 ;;;; Finish up
14155 (provide 'org)
14157 (run-hooks 'org-load-hook)
14159 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14161 ;;; org.el ends here