Coderefs: Insert links in export backends
[org-mode/org-tableheadings.git] / lisp / org.el
blobc86ad654396d3cc3f497fc10006ed18c85d52f31
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.16trans
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)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.16trans"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-modules'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global IDs for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
176 (const :tag " mouse: Additional mouse support" org-mouse)
178 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
179 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
180 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
181 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
182 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
183 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
184 (const :tag "C eval: Include command output as text" org-eval)
185 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
186 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
187 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
188 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
189 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
190 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
191 (const :tag "C mtags: Support for muse-like tags" org-mtags)
192 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
193 (const :tag "C registry: A registry for Org links" org-registry)
194 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
195 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
196 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
197 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
198 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
201 (defgroup org-startup nil
202 "Options concerning startup of Org-mode."
203 :tag "Org Startup"
204 :group 'org)
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-startup-align-all-tables nil
228 "Non-nil means, align all tables when visiting a file.
229 This is useful when the column width in tables is forced with <N> cookies
230 in table fields. Such tables will look correct only after the first re-align.
231 This can also be configured on a per-file basis by adding one of
232 the following lines anywhere in the buffer:
233 #+STARTUP: align
234 #+STARTUP: noalign"
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-insert-mode-line-in-empty-file nil
239 "Non-nil means insert the first line setting Org-mode in empty files.
240 When the function `org-mode' is called interactively in an empty file, this
241 normally means that the file name does not automatically trigger Org-mode.
242 To ensure that the file will always be in Org-mode in the future, a
243 line enforcing Org-mode will be inserted into the buffer, if this option
244 has been set."
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-replace-disputed-keys nil
249 "Non-nil means use alternative key bindings for some keys.
250 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
251 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
252 If you want to use Org-mode together with one of these other modes,
253 or more generally if you would like to move some Org-mode commands to
254 other keys, set this variable and configure the keys with the variable
255 `org-disputed-keys'.
257 This option is only relevant at load-time of Org-mode, and must be set
258 *before* org.el is loaded. Changing it requires a restart of Emacs to
259 become effective."
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-use-extra-keys nil
264 "Non-nil means use extra key sequence definitions for certain
265 commands. This happens automatically if you run XEmacs or if
266 window-system is nil. This variable lets you do the same
267 manually. You must set it before loading org.
269 Example: on Carbon Emacs 22 running graphically, with an external
270 keyboard on a Powerbook, the default way of setting M-left might
271 not work for either Alt or ESC. Setting this variable will make
272 it work for ESC."
273 :group 'org-startup
274 :type 'boolean)
276 (if (fboundp 'defvaralias)
277 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
279 (defcustom org-disputed-keys
280 '(([(shift up)] . [(meta p)])
281 ([(shift down)] . [(meta n)])
282 ([(shift left)] . [(meta -)])
283 ([(shift right)] . [(meta +)])
284 ([(control shift right)] . [(meta shift +)])
285 ([(control shift left)] . [(meta shift -)]))
286 "Keys for which Org-mode and other modes compete.
287 This is an alist, cars are the default keys, second element specifies
288 the alternative to use when `org-replace-disputed-keys' is t.
290 Keys can be specified in any syntax supported by `define-key'.
291 The value of this option takes effect only at Org-mode's startup,
292 therefore you'll have to restart Emacs to apply it after changing."
293 :group 'org-startup
294 :type 'alist)
296 (defun org-key (key)
297 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
298 Or return the original if not disputed."
299 (if org-replace-disputed-keys
300 (let* ((nkey (key-description key))
301 (x (org-find-if (lambda (x)
302 (equal (key-description (car x)) nkey))
303 org-disputed-keys)))
304 (if x (cdr x) key))
305 key))
307 (defun org-find-if (predicate seq)
308 (catch 'exit
309 (while seq
310 (if (funcall predicate (car seq))
311 (throw 'exit (car seq))
312 (pop seq)))))
314 (defun org-defkey (keymap key def)
315 "Define a key, possibly translated, as returned by `org-key'."
316 (define-key keymap (org-key key) def))
318 (defcustom org-ellipsis nil
319 "The ellipsis to use in the Org-mode outline.
320 When nil, just use the standard three dots. When a string, use that instead,
321 When a face, use the standard 3 dots, but with the specified face.
322 The change affects only Org-mode (which will then use its own display table).
323 Changing this requires executing `M-x org-mode' in a buffer to become
324 effective."
325 :group 'org-startup
326 :type '(choice (const :tag "Default" nil)
327 (face :tag "Face" :value org-warning)
328 (string :tag "String" :value "...#")))
330 (defvar org-display-table nil
331 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
333 (defgroup org-keywords nil
334 "Keywords in Org-mode."
335 :tag "Org Keywords"
336 :group 'org)
338 (defcustom org-deadline-string "DEADLINE:"
339 "String to mark deadline entries.
340 A deadline is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-deadline].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-scheduled-string "SCHEDULED:"
348 "String to mark scheduled TODO entries.
349 A schedule is this string, followed by a time stamp. Should be a word,
350 terminated by a colon. You can insert a schedule keyword and
351 a timestamp with \\[org-schedule].
352 Changes become only effective after restarting Emacs."
353 :group 'org-keywords
354 :type 'string)
356 (defcustom org-closed-string "CLOSED:"
357 "String used as the prefix for timestamps logging closing a TODO entry."
358 :group 'org-keywords
359 :type 'string)
361 (defcustom org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item."
363 :group 'org-keywords
364 :type 'string)
366 (defcustom org-comment-string "COMMENT"
367 "Entries starting with this keyword will never be exported.
368 An entry can be toggled between COMMENT and normal with
369 \\[org-toggle-comment].
370 Changes become only effective after restarting Emacs."
371 :group 'org-keywords
372 :type 'string)
374 (defcustom org-quote-string "QUOTE"
375 "Entries starting with this keyword will be exported in fixed-width font.
376 Quoting applies only to the text in the entry following the headline, and does
377 not extend beyond the next headline, even if that is lower level.
378 An entry can be toggled between QUOTE and normal with
379 \\[org-toggle-fixed-width-section]."
380 :group 'org-keywords
381 :type 'string)
383 (defconst org-repeat-re
384 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
385 "Regular expression for specifying repeated events.
386 After a match, group 1 contains the repeat expression.")
388 (defgroup org-structure nil
389 "Options concerning the general structure of Org-mode files."
390 :tag "Org Structure"
391 :group 'org)
393 (defgroup org-reveal-location nil
394 "Options about how to make context of a location visible."
395 :tag "Org Reveal Location"
396 :group 'org-structure)
398 (defconst org-context-choice
399 '(choice
400 (const :tag "Always" t)
401 (const :tag "Never" nil)
402 (repeat :greedy t :tag "Individual contexts"
403 (cons
404 (choice :tag "Context"
405 (const agenda)
406 (const org-goto)
407 (const occur-tree)
408 (const tags-tree)
409 (const link-search)
410 (const mark-goto)
411 (const bookmark-jump)
412 (const isearch)
413 (const default))
414 (boolean))))
415 "Contexts for the reveal options.")
417 (defcustom org-show-hierarchy-above '((default . t))
418 "Non-nil means, show full hierarchy when revealing a location.
419 Org-mode often shows locations in an org-mode file which might have
420 been invisible before. When this is set, the hierarchy of headings
421 above the exposed location is shown.
422 Turning this off for example for sparse trees makes them very compact.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. Valid contexts are
425 agenda when exposing an entry from the agenda
426 org-goto when using the command `org-goto' on key C-c C-j
427 occur-tree when using the command `org-occur' on key C-c /
428 tags-tree when constructing a sparse tree based on tags matches
429 link-search when exposing search matches associated with a link
430 mark-goto when exposing the jump goal of a mark
431 bookmark-jump when exposing a bookmark location
432 isearch when exiting from an incremental search
433 default default for all contexts not set explicitly"
434 :group 'org-reveal-location
435 :type org-context-choice)
437 (defcustom org-show-following-heading '((default . nil))
438 "Non-nil means, show following heading when revealing a location.
439 Org-mode often shows locations in an org-mode file which might have
440 been invisible before. When this is set, the heading following the
441 match is shown.
442 Turning this off for example for sparse trees makes them very compact,
443 but makes it harder to edit the location of the match. In such a case,
444 use the command \\[org-reveal] to show more context.
445 Instead of t, this can also be an alist specifying this option for different
446 contexts. See `org-show-hierarchy-above' for valid contexts."
447 :group 'org-reveal-location
448 :type org-context-choice)
450 (defcustom org-show-siblings '((default . nil) (isearch t))
451 "Non-nil means, show all sibling heading when revealing a location.
452 Org-mode often shows locations in an org-mode file which might have
453 been invisible before. When this is set, the sibling of the current entry
454 heading are all made visible. If `org-show-hierarchy-above' is t,
455 the same happens on each level of the hierarchy above the current entry.
457 By default this is on for the isearch context, off for all other contexts.
458 Turning this off for example for sparse trees makes them very compact,
459 but makes it harder to edit the location of the match. In such a case,
460 use the command \\[org-reveal] to show more context.
461 Instead of t, this can also be an alist specifying this option for different
462 contexts. See `org-show-hierarchy-above' for valid contexts."
463 :group 'org-reveal-location
464 :type org-context-choice)
466 (defcustom org-show-entry-below '((default . nil))
467 "Non-nil means, show the entry below a headline when revealing a location.
468 Org-mode often shows locations in an org-mode file which might have
469 been invisible before. When this is set, the text below the headline that is
470 exposed is also shown.
472 By default this is off for all contexts.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
478 (defcustom org-indirect-buffer-display 'other-window
479 "How should indirect tree buffers be displayed?
480 This applies to indirect buffers created with the commands
481 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
482 Valid values are:
483 current-window Display in the current window
484 other-window Just display in another window.
485 dedicated-frame Create one new frame, and re-use it each time.
486 new-frame Make a new frame each time. Note that in this case
487 previously-made indirect buffers are kept, and you need to
488 kill these buffers yourself."
489 :group 'org-structure
490 :group 'org-agenda-windows
491 :type '(choice
492 (const :tag "In current window" current-window)
493 (const :tag "In current frame, other window" other-window)
494 (const :tag "Each time a new frame" new-frame)
495 (const :tag "One dedicated frame" dedicated-frame)))
497 (defgroup org-cycle nil
498 "Options concerning visibility cycling in Org-mode."
499 :tag "Org Cycle"
500 :group 'org-structure)
502 (defcustom org-drawers '("PROPERTIES" "CLOCK")
503 "Names of drawers. Drawers are not opened by cycling on the headline above.
504 Drawers only open with a TAB on the drawer line itself. A drawer looks like
505 this:
506 :DRAWERNAME:
507 .....
508 :END:
509 The drawer \"PROPERTIES\" is special for capturing properties through
510 the property API.
512 Drawers can be defined on the per-file basis with a line like:
514 #+DRAWERS: HIDDEN STATE PROPERTIES"
515 :group 'org-structure
516 :type '(repeat (string :tag "Drawer Name")))
518 (defcustom org-cycle-global-at-bob nil
519 "Cycle globally if cursor is at beginning of buffer and not at a headline.
520 This makes it possible to do global cycling without having to use S-TAB or
521 C-u TAB. For this special case to work, the first line of the buffer
522 must not be a headline - it may be empty ot some other text. When used in
523 this way, `org-cycle-hook' is disables temporarily, to make sure the
524 cursor stays at the beginning of the buffer.
525 When this option is nil, don't do anything special at the beginning
526 of the buffer."
527 :group 'org-cycle
528 :type 'boolean)
530 (defcustom org-cycle-emulate-tab t
531 "Where should `org-cycle' emulate TAB.
532 nil Never
533 white Only in completely white lines
534 whitestart Only at the beginning of lines, before the first non-white char
535 t Everywhere except in headlines
536 exc-hl-bol Everywhere except at the start of a headline
537 If TAB is used in a place where it does not emulate TAB, the current subtree
538 visibility is cycled."
539 :group 'org-cycle
540 :type '(choice (const :tag "Never" nil)
541 (const :tag "Only in completely white lines" white)
542 (const :tag "Before first char in a line" whitestart)
543 (const :tag "Everywhere except in headlines" t)
544 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
547 (defcustom org-cycle-separator-lines 2
548 "Number of empty lines needed to keep an empty line between collapsed trees.
549 If you leave an empty line between the end of a subtree and the following
550 headline, this empty line is hidden when the subtree is folded.
551 Org-mode will leave (exactly) one empty line visible if the number of
552 empty lines is equal or larger to the number given in this variable.
553 So the default 2 means, at least 2 empty lines after the end of a subtree
554 are needed to produce free space between a collapsed subtree and the
555 following headline.
557 Special case: when 0, never leave empty lines in collapsed view."
558 :group 'org-cycle
559 :type 'integer)
560 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
562 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
563 org-cycle-hide-drawers
564 org-cycle-show-empty-lines
565 org-optimize-window-after-visibility-change)
566 "Hook that is run after `org-cycle' has changed the buffer visibility.
567 The function(s) in this hook must accept a single argument which indicates
568 the new state that was set by the most recent `org-cycle' command. The
569 argument is a symbol. After a global state change, it can have the values
570 `overview', `content', or `all'. After a local state change, it can have
571 the values `folded', `children', or `subtree'."
572 :group 'org-cycle
573 :type 'hook)
575 (defgroup org-edit-structure nil
576 "Options concerning structure editing in Org-mode."
577 :tag "Org Edit Structure"
578 :group 'org-structure)
580 (defcustom org-odd-levels-only nil
581 "Non-nil means, skip even levels and only use odd levels for the outline.
582 This has the effect that two stars are being added/taken away in
583 promotion/demotion commands. It also influences how levels are
584 handled by the exporters.
585 Changing it requires restart of `font-lock-mode' to become effective
586 for fontification also in regions already fontified.
587 You may also set this on a per-file basis by adding one of the following
588 lines to the buffer:
590 #+STARTUP: odd
591 #+STARTUP: oddeven"
592 :group 'org-edit-structure
593 :group 'org-font-lock
594 :type 'boolean)
596 (defcustom org-adapt-indentation t
597 "Non-nil means, adapt indentation when promoting and demoting.
598 When this is set and the *entire* text in an entry is indented, the
599 indentation is increased by one space in a demotion command, and
600 decreased by one in a promotion command. If any line in the entry
601 body starts at column 0, indentation is not changed at all."
602 :group 'org-edit-structure
603 :type 'boolean)
605 (defcustom org-special-ctrl-a/e nil
606 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
607 When t, `C-a' will bring back the cursor to the beginning of the
608 headline text, i.e. after the stars and after a possible TODO keyword.
609 In an item, this will be the position after the bullet.
610 When the cursor is already at that position, another `C-a' will bring
611 it to the beginning of the line.
612 `C-e' will jump to the end of the headline, ignoring the presence of tags
613 in the headline. A second `C-e' will then jump to the true end of the
614 line, after any tags.
615 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
616 and only a directly following, identical keypress will bring the cursor
617 to the special positions."
618 :group 'org-edit-structure
619 :type '(choice
620 (const :tag "off" nil)
621 (const :tag "after bullet first" t)
622 (const :tag "border first" reversed)))
624 (if (fboundp 'defvaralias)
625 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
627 (defcustom org-special-ctrl-k nil
628 "Non-nil means `C-k' will behave specially in headlines.
629 When nil, `C-k' will call the default `kill-line' command.
630 When t, the following will happen while the cursor is in the headline:
632 - When the cursor is at the beginning of a headline, kill the entire
633 line and possible the folded subtree below the line.
634 - When in the middle of the headline text, kill the headline up to the tags.
635 - When after the headline text, kill the tags."
636 :group 'org-edit-structure
637 :type 'boolean)
639 (defcustom org-yank-folded-subtrees t
640 "Non-nil means, when yanking subtrees, fold them.
641 If the kill is a single subtree, or a sequence of subtrees, i.e. if
642 it starts with a heading and all other headings in it are either children
643 or siblings, then fold all the subtrees. However, do this only if no
644 text after the yank would be swallowed into a folded tree by this action."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defcustom org-yank-adjusted-subtrees t
649 "Non-nil means, when yanking subtrees, adjust the level.
650 With this setting, `org-paste-subtree' is used to insert the subtree, see
651 this function for details."
652 :group 'org-edit-structure
653 :type 'boolean)
655 (defcustom org-M-RET-may-split-line '((default . t))
656 "Non-nil means, M-RET will split the line at the cursor position.
657 When nil, it will go to the end of the line before making a
658 new line.
659 You may also set this option in a different way for different
660 contexts. Valid contexts are:
662 headline when creating a new headline
663 item when creating a new item
664 table in a table field
665 default the value to be used for all contexts not explicitly
666 customized"
667 :group 'org-structure
668 :group 'org-table
669 :type '(choice
670 (const :tag "Always" t)
671 (const :tag "Never" nil)
672 (repeat :greedy t :tag "Individual contexts"
673 (cons
674 (choice :tag "Context"
675 (const headline)
676 (const item)
677 (const table)
678 (const default))
679 (boolean)))))
682 (defcustom org-insert-heading-respect-content nil
683 "Non-nil means, insert new headings after the current subtree.
684 When nil, the new heading is created directly after the current line.
685 The commands \\[org-insert-heading-respect-content] and
686 \\[org-insert-todo-heading-respect-content] turn this variable on
687 for the duration of the command."
688 :group 'org-structure
689 :type 'boolean)
691 (defcustom org-blank-before-new-entry '((heading . nil)
692 (plain-list-item . nil))
693 "Should `org-insert-heading' leave a blank line before new heading/item?
694 The value is an alist, with `heading' and `plain-list-item' as car,
695 and a boolean flag as cdr."
696 :group 'org-edit-structure
697 :type '(list
698 (cons (const heading) (boolean))
699 (cons (const plain-list-item) (boolean))))
701 (defcustom org-insert-heading-hook nil
702 "Hook being run after inserting a new heading."
703 :group 'org-edit-structure
704 :type 'hook)
706 (defcustom org-enable-fixed-width-editor t
707 "Non-nil means, lines starting with \":\" are treated as fixed-width.
708 This currently only means, they are never auto-wrapped.
709 When nil, such lines will be treated like ordinary lines.
710 See also the QUOTE keyword."
711 :group 'org-edit-structure
712 :type 'boolean)
714 (defcustom org-edit-src-region-extra nil
715 "Additional regexps to identify regions for editing with `org-edit-src-code'.
716 For examples see the function `org-edit-src-find-region-and-lang'.
717 The regular expression identifying the begin marker should end with a newline,
718 and the regexp marking the end line should start with a newline, to make sure
719 there are kept outside the narrowed region."
720 :group 'org-edit-structure
721 :type '(repeat
722 (list
723 (regexp :tag "begin regexp")
724 (regexp :tag "end regexp")
725 (choice :tag "language"
726 (string :tag "specify")
727 (integer :tag "from match group")
728 (const :tag "from `lang' element")
729 (const :tag "from `style' element")))))
731 (defcustom org-edit-fixed-width-region-mode 'artist-mode
732 "The mode that should be used to edit fixed-width regions.
733 These are the regions where each line starts with a colon."
734 :group 'org-edit-structure
735 :type '(choice
736 (const artist-mode)
737 (const picture-mode)
738 (const fundamental-mode)
739 (function :tag "Other (specify)")))
741 (defcustom org-goto-auto-isearch t
742 "Non-nil means, typing characters in org-goto starts incremental search."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defgroup org-sparse-trees nil
747 "Options concerning sparse trees in Org-mode."
748 :tag "Org Sparse Trees"
749 :group 'org-structure)
751 (defcustom org-highlight-sparse-tree-matches t
752 "Non-nil means, highlight all matches that define a sparse tree.
753 The highlights will automatically disappear the next time the buffer is
754 changed by an edit command."
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-remove-highlights-with-change t
759 "Non-nil means, any change to the buffer will remove temporary highlights.
760 Such highlights are created by `org-occur' and `org-clock-display'.
761 When nil, `C-c C-c needs to be used to get rid of the highlights.
762 The highlights created by `org-preview-latex-fragment' always need
763 `C-c C-c' to be removed."
764 :group 'org-sparse-trees
765 :group 'org-time
766 :type 'boolean)
769 (defcustom org-occur-hook '(org-first-headline-recenter)
770 "Hook that is run after `org-occur' has constructed a sparse tree.
771 This can be used to recenter the window to show as much of the structure
772 as possible."
773 :group 'org-sparse-trees
774 :type 'hook)
776 (defgroup org-imenu-and-speedbar nil
777 "Options concerning imenu and speedbar in Org-mode."
778 :tag "Org Imenu and Speedbar"
779 :group 'org-structure)
781 (defcustom org-imenu-depth 2
782 "The maximum level for Imenu access to Org-mode headlines.
783 This also applied for speedbar access."
784 :group 'org-imenu-and-speedbar
785 :type 'number)
787 (defgroup org-table nil
788 "Options concerning tables in Org-mode."
789 :tag "Org Table"
790 :group 'org)
792 (defcustom org-enable-table-editor 'optimized
793 "Non-nil means, lines starting with \"|\" are handled by the table editor.
794 When nil, such lines will be treated like ordinary lines.
796 When equal to the symbol `optimized', the table editor will be optimized to
797 do the following:
798 - Automatic overwrite mode in front of whitespace in table fields.
799 This makes the structure of the table stay in tact as long as the edited
800 field does not exceed the column width.
801 - Minimize the number of realigns. Normally, the table is aligned each time
802 TAB or RET are pressed to move to another field. With optimization this
803 happens only if changes to a field might have changed the column width.
804 Optimization requires replacing the functions `self-insert-command',
805 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
806 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
807 very good at guessing when a re-align will be necessary, but you can always
808 force one with \\[org-ctrl-c-ctrl-c].
810 If you would like to use the optimized version in Org-mode, but the
811 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
813 This variable can be used to turn on and off the table editor during a session,
814 but in order to toggle optimization, a restart is required.
816 See also the variable `org-table-auto-blank-field'."
817 :group 'org-table
818 :type '(choice
819 (const :tag "off" nil)
820 (const :tag "on" t)
821 (const :tag "on, optimized" optimized)))
823 (defcustom org-table-tab-recognizes-table.el t
824 "Non-nil means, TAB will automatically notice a table.el table.
825 When it sees such a table, it moves point into it and - if necessary -
826 calls `table-recognize-table'."
827 :group 'org-table-editing
828 :type 'boolean)
830 (defgroup org-link nil
831 "Options concerning links in Org-mode."
832 :tag "Org Link"
833 :group 'org)
835 (defvar org-link-abbrev-alist-local nil
836 "Buffer-local version of `org-link-abbrev-alist', which see.
837 The value of this is taken from the #+LINK lines.")
838 (make-variable-buffer-local 'org-link-abbrev-alist-local)
840 (defcustom org-link-abbrev-alist nil
841 "Alist of link abbreviations.
842 The car of each element is a string, to be replaced at the start of a link.
843 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
844 links in Org-mode buffers can have an optional tag after a double colon, e.g.
846 [[linkkey:tag][description]]
848 If REPLACE is a string, the tag will simply be appended to create the link.
849 If the string contains \"%s\", the tag will be inserted there. Alternatively,
850 the placeholder \"%h\" will cause a url-encoded version of the tag to
851 be inserted at that point (see the function `url-hexify-string').
853 REPLACE may also be a function that will be called with the tag as the
854 only argument to create the link, which should be returned as a string.
856 See the manual for examples."
857 :group 'org-link
858 :type '(repeat
859 (cons
860 (string :tag "Protocol")
861 (choice
862 (string :tag "Format")
863 (function)))))
865 (defcustom org-descriptive-links t
866 "Non-nil means, hide link part and only show description of bracket links.
867 Bracket links are like [[link][description]]. This variable sets the initial
868 state in new org-mode buffers. The setting can then be toggled on a
869 per-buffer basis from the Org->Hyperlinks menu."
870 :group 'org-link
871 :type 'boolean)
873 (defcustom org-link-file-path-type 'adaptive
874 "How the path name in file links should be stored.
875 Valid values are:
877 relative Relative to the current directory, i.e. the directory of the file
878 into which the link is being inserted.
879 absolute Absolute path, if possible with ~ for home directory.
880 noabbrev Absolute path, no abbreviation of home directory.
881 adaptive Use relative path for files in the current directory and sub-
882 directories of it. For other files, use an absolute path."
883 :group 'org-link
884 :type '(choice
885 (const relative)
886 (const absolute)
887 (const noabbrev)
888 (const adaptive)))
890 (defcustom org-activate-links '(bracket angle plain radio tag date)
891 "Types of links that should be activated in Org-mode files.
892 This is a list of symbols, each leading to the activation of a certain link
893 type. In principle, it does not hurt to turn on most link types - there may
894 be a small gain when turning off unused link types. The types are:
896 bracket The recommended [[link][description]] or [[link]] links with hiding.
897 angular Links in angular brackets that may contain whitespace like
898 <bbdb:Carsten Dominik>.
899 plain Plain links in normal text, no whitespace, like http://google.com.
900 radio Text that is matched by a radio target, see manual for details.
901 tag Tag settings in a headline (link to tag search).
902 date Time stamps (link to calendar).
904 Changing this variable requires a restart of Emacs to become effective."
905 :group 'org-link
906 :type '(set (const :tag "Double bracket links (new style)" bracket)
907 (const :tag "Angular bracket links (old style)" angular)
908 (const :tag "Plain text links" plain)
909 (const :tag "Radio target matches" radio)
910 (const :tag "Tags" tag)
911 (const :tag "Timestamps" date)))
913 (defcustom org-make-link-description-function nil
914 "Function to use to generate link descriptions from links. If
915 nil the link location will be used. This function must take two
916 parameters; the first is the link and the second the description
917 org-insert-link has generated, and should return the description
918 to use."
919 :group 'org-link
920 :type 'function)
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode."
924 :tag "Org Store Link"
925 :group 'org-link)
927 (defcustom org-email-link-description-format "Email %c: %.30s"
928 "Format of the description part of a link to an email or usenet message.
929 The following %-escapes will be replaced by corresponding information:
931 %F full \"From\" field
932 %f name, taken from \"From\" field, address if no name
933 %T full \"To\" field
934 %t first name in \"To\" field, address if no name
935 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
936 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
937 %s subject
938 %m message-id.
940 You may use normal field width specification between the % and the letter.
941 This is for example useful to limit the length of the subject.
943 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944 :group 'org-link-store
945 :type 'string)
947 (defcustom org-from-is-user-regexp
948 (let (r1 r2)
949 (when (and user-mail-address (not (string= user-mail-address "")))
950 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951 (when (and user-full-name (not (string= user-full-name "")))
952 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954 "Regexp matched against the \"From:\" header of an email or usenet message.
955 It should match if the message is from the user him/herself."
956 :group 'org-link-store
957 :type 'regexp)
959 (defcustom org-link-to-org-use-id 'create-if-interactive
960 "Non-nil means, storing a link to an Org file will use entry IDs.
962 Note that before this variable is even considered, org-id must be loaded,
963 to please customize `org-modules' and turn it on.
965 The variable can have the following values:
967 t Create an ID if needed to make a link to the current entry.
969 create-if-interactive
970 If `org-store-link' is called directly (interactively, as a user
971 command), do create an ID to support the link. But when doing the
972 job for remember, only use the ID if it already exists. The
973 purpose of this setting is to avoid proliferation of unwanted
974 IDs, just because you happen to be in an Org file when you
975 call `org-remember' that automatically and preemptively
976 creates a link. If you do want to get an ID link in a remember
977 template to an entry not having an ID, create it first by
978 explicitly creating a link to it, using `C-c C-l' first.
980 use-existing
981 Use existing ID, do not create one.
983 nil Never use an ID to make a link, instead link using a text search for
984 the headline text."
985 :group 'org-link-store
986 :type '(choice
987 (const :tag "Create ID to make link" t)
988 (const :tag "Create if string link interactively"
989 'create-if-interactive)
990 (const :tag "Only use existing" 'use-existing)
991 (const :tag "Do not use ID to create link" nil)))
993 (defcustom org-context-in-file-links t
994 "Non-nil means, file links from `org-store-link' contain context.
995 A search string will be added to the file name with :: as separator and
996 used to find the context when the link is activated by the command
997 `org-open-at-point'.
998 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
999 negates this setting for the duration of the command."
1000 :group 'org-link-store
1001 :type 'boolean)
1003 (defcustom org-keep-stored-link-after-insertion nil
1004 "Non-nil means, keep link in list for entire session.
1006 The command `org-store-link' adds a link pointing to the current
1007 location to an internal list. These links accumulate during a session.
1008 The command `org-insert-link' can be used to insert links into any
1009 Org-mode file (offering completion for all stored links). When this
1010 option is nil, every link which has been inserted once using \\[org-insert-link]
1011 will be removed from the list, to make completing the unused links
1012 more efficient."
1013 :group 'org-link-store
1014 :type 'boolean)
1016 (defgroup org-link-follow nil
1017 "Options concerning following links in Org-mode."
1018 :tag "Org Follow Link"
1019 :group 'org-link)
1021 (defcustom org-link-translation-function nil
1022 "Function to translate links with different syntax to Org syntax.
1023 This can be used to translate links created for example by the Planner
1024 or emacs-wiki packages to Org syntax.
1025 The function must accept two parameters, a TYPE containing the link
1026 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1027 which is everything after the link protocol. It should return a cons
1028 with possibly modified values of type and path.
1029 Org contains a function for this, so if you set this variable to
1030 `org-translate-link-from-planner', you should be able follow many
1031 links created by planner."
1032 :group 'org-link-follow
1033 :type 'function)
1035 (defcustom org-follow-link-hook nil
1036 "Hook that is run after a link has been followed."
1037 :group 'org-link-follow
1038 :type 'hook)
1040 (defcustom org-tab-follows-link nil
1041 "Non-nil means, on links TAB will follow the link.
1042 Needs to be set before org.el is loaded."
1043 :group 'org-link-follow
1044 :type 'boolean)
1046 (defcustom org-return-follows-link nil
1047 "Non-nil means, on links RET will follow the link.
1048 Needs to be set before org.el is loaded."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-mouse-1-follows-link
1053 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1054 "Non-nil means, mouse-1 on a link will follow the link.
1055 A longer mouse click will still set point. Does not work on XEmacs.
1056 Needs to be set before org.el is loaded."
1057 :group 'org-link-follow
1058 :type 'boolean)
1060 (defcustom org-mark-ring-length 4
1061 "Number of different positions to be recorded in the ring
1062 Changing this requires a restart of Emacs to work correctly."
1063 :group 'org-link-follow
1064 :type 'integer)
1066 (defcustom org-link-frame-setup
1067 '((vm . vm-visit-folder-other-frame)
1068 (gnus . gnus-other-frame)
1069 (file . find-file-other-window))
1070 "Setup the frame configuration for following links.
1071 When following a link with Emacs, it may often be useful to display
1072 this link in another window or frame. This variable can be used to
1073 set this up for the different types of links.
1074 For VM, use any of
1075 `vm-visit-folder'
1076 `vm-visit-folder-other-frame'
1077 For Gnus, use any of
1078 `gnus'
1079 `gnus-other-frame'
1080 `org-gnus-no-new-news'
1081 For FILE, use any of
1082 `find-file'
1083 `find-file-other-window'
1084 `find-file-other-frame'
1085 For the calendar, use the variable `calendar-setup'.
1086 For BBDB, it is currently only possible to display the matches in
1087 another window."
1088 :group 'org-link-follow
1089 :type '(list
1090 (cons (const vm)
1091 (choice
1092 (const vm-visit-folder)
1093 (const vm-visit-folder-other-window)
1094 (const vm-visit-folder-other-frame)))
1095 (cons (const gnus)
1096 (choice
1097 (const gnus)
1098 (const gnus-other-frame)
1099 (const org-gnus-no-new-news)))
1100 (cons (const file)
1101 (choice
1102 (const find-file)
1103 (const find-file-other-window)
1104 (const find-file-other-frame)))))
1106 (defcustom org-display-internal-link-with-indirect-buffer nil
1107 "Non-nil means, use indirect buffer to display infile links.
1108 Activating internal links (from one location in a file to another location
1109 in the same file) normally just jumps to the location. When the link is
1110 activated with a C-u prefix (or with mouse-3), the link is displayed in
1111 another window. When this option is set, the other window actually displays
1112 an indirect buffer clone of the current buffer, to avoid any visibility
1113 changes to the current buffer."
1114 :group 'org-link-follow
1115 :type 'boolean)
1117 (defcustom org-open-non-existing-files nil
1118 "Non-nil means, `org-open-file' will open non-existing files.
1119 When nil, an error will be generated."
1120 :group 'org-link-follow
1121 :type 'boolean)
1123 (defcustom org-open-directory-means-index-dot-org nil
1124 "Non-nil means, a link to a directory really means to index.org.
1125 When nil, following a directory link will run dired or open a finder/explorer
1126 window on that directory."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1131 "Function and arguments to call for following mailto links.
1132 This is a list with the first element being a lisp function, and the
1133 remaining elements being arguments to the function. In string arguments,
1134 %a will be replaced by the address, and %s will be replaced by the subject
1135 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1136 :group 'org-link-follow
1137 :type '(choice
1138 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1139 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1140 (const :tag "message-mail" (message-mail "%a" "%s"))
1141 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1143 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1144 "Non-nil means, ask for confirmation before executing shell links.
1145 Shell links can be dangerous: just think about a link
1147 [[shell:rm -rf ~/*][Google Search]]
1149 This link would show up in your Org-mode document as \"Google Search\",
1150 but really it would remove your entire home directory.
1151 Therefore we advise against setting this variable to nil.
1152 Just change it to `y-or-n-p' of you want to confirm with a
1153 single keystroke rather than having to type \"yes\"."
1154 :group 'org-link-follow
1155 :type '(choice
1156 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1157 (const :tag "with y-or-n (faster)" y-or-n-p)
1158 (const :tag "no confirmation (dangerous)" nil)))
1160 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1161 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1162 Elisp links can be dangerous: just think about a link
1164 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1166 This link would show up in your Org-mode document as \"Google Search\",
1167 but really it would remove your entire home directory.
1168 Therefore we advise against setting this variable to nil.
1169 Just change it to `y-or-n-p' of you want to confirm with a
1170 single keystroke rather than having to type \"yes\"."
1171 :group 'org-link-follow
1172 :type '(choice
1173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1174 (const :tag "with y-or-n (faster)" y-or-n-p)
1175 (const :tag "no confirmation (dangerous)" nil)))
1177 (defconst org-file-apps-defaults-gnu
1178 '((remote . emacs)
1179 (system . mailcap)
1180 (t . mailcap))
1181 "Default file applications on a UNIX or GNU/Linux system.
1182 See `org-file-apps'.")
1184 (defconst org-file-apps-defaults-macosx
1185 '((remote . emacs)
1186 (t . "open %s")
1187 (system . "open %s")
1188 ("ps.gz" . "gv %s")
1189 ("eps.gz" . "gv %s")
1190 ("dvi" . "xdvi %s")
1191 ("fig" . "xfig %s"))
1192 "Default file applications on a MacOS X system.
1193 The system \"open\" is known as a default, but we use X11 applications
1194 for some files for which the OS does not have a good default.
1195 See `org-file-apps'.")
1197 (defconst org-file-apps-defaults-windowsnt
1198 (list
1199 '(remote . emacs)
1200 (cons t
1201 (list (if (featurep 'xemacs)
1202 'mswindows-shell-execute
1203 'w32-shell-execute)
1204 "open" 'file))
1205 (cons 'system
1206 (list (if (featurep 'xemacs)
1207 'mswindows-shell-execute
1208 'w32-shell-execute)
1209 "open" 'file)))
1210 "Default file applications on a Windows NT system.
1211 The system \"open\" is used for most files.
1212 See `org-file-apps'.")
1214 (defcustom org-file-apps
1216 (auto-mode . emacs)
1217 ("\\.x?html?\\'" . default)
1218 ("\\.pdf\\'" . default)
1220 "External applications for opening `file:path' items in a document.
1221 Org-mode uses system defaults for different file types, but
1222 you can use this variable to set the application for a given file
1223 extension. The entries in this list are cons cells where the car identifies
1224 files and the cdr the corresponding command. Possible values for the
1225 file identifier are
1226 \"regex\" Regular expression matched against the file name. For backward
1227 compatibility, this can also be a string with only alphanumeric
1228 characters, which is then interpreted as an extension.
1229 `directory' Matches a directory
1230 `remote' Matches a remote file, accessible through tramp or efs.
1231 Remote files most likely should be visited through Emacs
1232 because external applications cannot handle such paths.
1233 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1234 so all files Emacs knows how to handle. Using this with
1235 command `emacs' will open most files in Emacs. Beware that this
1236 will also open html files inside Emacs, unless you add
1237 (\"html\" . default) to the list as well.
1238 t Default for files not matched by any of the other options.
1239 `system' The system command to open files, like `open' on Windows
1240 and Mac OS X, and mailcap under GNU/Linux. This is the command
1241 that will be selected if you call `C-c C-o' with a double
1242 `C-u C-u' prefix.
1244 Possible values for the command are:
1245 `emacs' The file will be visited by the current Emacs process.
1246 `default' Use the default application for this file type, which is the
1247 association for t in the list, most likely in the system-specific
1248 part.
1249 This can be used to overrule an unwanted setting in the
1250 system-specific variable.
1251 `system' Use the system command for opening files, like \"open\".
1252 This command is specified by the entry whose car is `system'.
1253 Most likely, the system-specific version of this variable
1254 does define this command, but you can overrule/replace it
1255 here.
1256 string A command to be executed by a shell; %s will be replaced
1257 by the path to the file.
1258 sexp A Lisp form which will be evaluated. The file path will
1259 be available in the Lisp variable `file'.
1260 For more examples, see the system specific constants
1261 `org-file-apps-defaults-macosx'
1262 `org-file-apps-defaults-windowsnt'
1263 `org-file-apps-defaults-gnu'."
1264 :group 'org-link-follow
1265 :type '(repeat
1266 (cons (choice :value ""
1267 (string :tag "Extension")
1268 (const :tag "System command to open files" system)
1269 (const :tag "Default for unrecognized files" t)
1270 (const :tag "Remote file" remote)
1271 (const :tag "Links to a directory" directory)
1272 (const :tag "Any files that have Emacs modes"
1273 auto-mode))
1274 (choice :value ""
1275 (const :tag "Visit with Emacs" emacs)
1276 (const :tag "Use default" default)
1277 (const :tag "Use the system command" system)
1278 (string :tag "Command")
1279 (sexp :tag "Lisp form")))))
1281 (defgroup org-refile nil
1282 "Options concerning refiling entries in Org-mode."
1283 :tag "Org Refile"
1284 :group 'org)
1286 (defcustom org-directory "~/org"
1287 "Directory with org files.
1288 This directory will be used as default to prompt for org files.
1289 Used by the hooks for remember.el."
1290 :group 'org-refile
1291 :group 'org-remember
1292 :type 'directory)
1294 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1295 "Default target for storing notes.
1296 Used by the hooks for remember.el. This can be a string, or nil to mean
1297 the value of `remember-data-file'.
1298 You can set this on a per-template basis with the variable
1299 `org-remember-templates'."
1300 :group 'org-refile
1301 :group 'org-remember
1302 :type '(choice
1303 (const :tag "Default from remember-data-file" nil)
1304 file))
1306 (defcustom org-goto-interface 'outline
1307 "The default interface to be used for `org-goto'.
1308 Allowed values are:
1309 outline The interface shows an outline of the relevant file
1310 and the correct heading is found by moving through
1311 the outline or by searching with incremental search.
1312 outline-path-completion Headlines in the current buffer are offered via
1313 completion. This is the interface also used by
1314 the refile command."
1315 :group 'org-refile
1316 :type '(choice
1317 (const :tag "Outline" outline)
1318 (const :tag "Outline-path-completion" outline-path-completion)))
1320 (defcustom org-goto-max-level 5
1321 "Maximum level to be considered when running org-goto with refile interface."
1322 :group 'org-refile
1323 :type 'number)
1325 (defcustom org-reverse-note-order nil
1326 "Non-nil means, store new notes at the beginning of a file or entry.
1327 When nil, new notes will be filed to the end of a file or entry.
1328 This can also be a list with cons cells of regular expressions that
1329 are matched against file names, and values."
1330 :group 'org-remember
1331 :group 'org-refile
1332 :type '(choice
1333 (const :tag "Reverse always" t)
1334 (const :tag "Reverse never" nil)
1335 (repeat :tag "By file name regexp"
1336 (cons regexp boolean))))
1338 (defcustom org-refile-targets nil
1339 "Targets for refiling entries with \\[org-refile].
1340 This is list of cons cells. Each cell contains:
1341 - a specification of the files to be considered, either a list of files,
1342 or a symbol whose function or variable value will be used to retrieve
1343 a file name or a list of file names. If you use `org-agenda-files' for
1344 that, all agenda files will be scanned for targets. Nil means, consider
1345 headings in the current buffer.
1346 - A specification of how to select find candidate refile targets. This
1347 may be any of
1348 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1349 This tag has to be present in all target headlines, inheritance will
1350 not be considered.
1351 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1352 todo keyword.
1353 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1354 headlines that are refiling targets.
1355 - a cons cell (:level . N). Any headline of level N is considered a target.
1356 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1358 When this variable is nil, all top-level headlines in the current buffer
1359 are used, equivalent to the value `((nil . (:level . 1))'."
1360 :group 'org-refile
1361 :type '(repeat
1362 (cons
1363 (choice :value org-agenda-files
1364 (const :tag "All agenda files" org-agenda-files)
1365 (const :tag "Current buffer" nil)
1366 (function) (variable) (file))
1367 (choice :tag "Identify target headline by"
1368 (cons :tag "Specific tag" (const :value :tag) (string))
1369 (cons :tag "TODO keyword" (const :value :todo) (string))
1370 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1371 (cons :tag "Level number" (const :value :level) (integer))
1372 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1374 (defcustom org-refile-use-outline-path nil
1375 "Non-nil means, provide refile targets as paths.
1376 So a level 3 headline will be available as level1/level2/level3.
1377 When the value is `file', also include the file name (without directory)
1378 into the path. When `full-file-path', include the full file path."
1379 :group 'org-refile
1380 :type '(choice
1381 (const :tag "Not" nil)
1382 (const :tag "Yes" t)
1383 (const :tag "Start with file name" file)
1384 (const :tag "Start with full file path" full-file-path)))
1386 (defcustom org-outline-path-complete-in-steps t
1387 "Non-nil means, complete the outline path in hierarchical steps.
1388 When Org-mode uses the refile interface to select an outline path
1389 \(see variable `org-refile-use-outline-path'), the completion of
1390 the path can be done is a single go, or if can be done in steps down
1391 the headline hierarchy. Going in steps is probably the best if you
1392 do not use a special completion package like `ido' or `icicles'.
1393 However, when using these packages, going in one step can be very
1394 fast, while still showing the whole path to the entry."
1395 :group 'org-refile
1396 :type 'boolean)
1398 (defgroup org-todo nil
1399 "Options concerning TODO items in Org-mode."
1400 :tag "Org TODO"
1401 :group 'org)
1403 (defgroup org-progress nil
1404 "Options concerning Progress logging in Org-mode."
1405 :tag "Org Progress"
1406 :group 'org-time)
1408 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1409 "List of TODO entry keyword sequences and their interpretation.
1410 \\<org-mode-map>This is a list of sequences.
1412 Each sequence starts with a symbol, either `sequence' or `type',
1413 indicating if the keywords should be interpreted as a sequence of
1414 action steps, or as different types of TODO items. The first
1415 keywords are states requiring action - these states will select a headline
1416 for inclusion into the global TODO list Org-mode produces. If one of
1417 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1418 signify that no further action is necessary. If \"|\" is not found,
1419 the last keyword is treated as the only DONE state of the sequence.
1421 The command \\[org-todo] cycles an entry through these states, and one
1422 additional state where no keyword is present. For details about this
1423 cycling, see the manual.
1425 TODO keywords and interpretation can also be set on a per-file basis with
1426 the special #+SEQ_TODO and #+TYP_TODO lines.
1428 Each keyword can optionally specify a character for fast state selection
1429 \(in combination with the variable `org-use-fast-todo-selection')
1430 and specifiers for state change logging, using the same syntax
1431 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1432 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1433 indicates to record a time stamp each time this state is selected.
1435 Each keyword may also specify if a timestamp or a note should be
1436 recorded when entering or leaving the state, by adding additional
1437 characters in the parenthesis after the keyword. This looks like this:
1438 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1439 record only the time of the state change. With X and Y being either
1440 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1441 Y when leaving the state if and only if the *target* state does not
1442 define X. You may omit any of the fast-selection key or X or /Y,
1443 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1445 For backward compatibility, this variable may also be just a list
1446 of keywords - in this case the interpretation (sequence or type) will be
1447 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1448 :group 'org-todo
1449 :group 'org-keywords
1450 :type '(choice
1451 (repeat :tag "Old syntax, just keywords"
1452 (string :tag "Keyword"))
1453 (repeat :tag "New syntax"
1454 (cons
1455 (choice
1456 :tag "Interpretation"
1457 (const :tag "Sequence (cycling hits every state)" sequence)
1458 (const :tag "Type (cycling directly to DONE)" type))
1459 (repeat
1460 (string :tag "Keyword"))))))
1462 (defvar org-todo-keywords-1 nil
1463 "All TODO and DONE keywords active in a buffer.")
1464 (make-variable-buffer-local 'org-todo-keywords-1)
1465 (defvar org-todo-keywords-for-agenda nil)
1466 (defvar org-done-keywords-for-agenda nil)
1467 (defvar org-todo-keyword-alist-for-agenda nil)
1468 (defvar org-tag-alist-for-agenda nil)
1469 (defvar org-agenda-contributing-files nil)
1470 (defvar org-not-done-keywords nil)
1471 (make-variable-buffer-local 'org-not-done-keywords)
1472 (defvar org-done-keywords nil)
1473 (make-variable-buffer-local 'org-done-keywords)
1474 (defvar org-todo-heads nil)
1475 (make-variable-buffer-local 'org-todo-heads)
1476 (defvar org-todo-sets nil)
1477 (make-variable-buffer-local 'org-todo-sets)
1478 (defvar org-todo-log-states nil)
1479 (make-variable-buffer-local 'org-todo-log-states)
1480 (defvar org-todo-kwd-alist nil)
1481 (make-variable-buffer-local 'org-todo-kwd-alist)
1482 (defvar org-todo-key-alist nil)
1483 (make-variable-buffer-local 'org-todo-key-alist)
1484 (defvar org-todo-key-trigger nil)
1485 (make-variable-buffer-local 'org-todo-key-trigger)
1487 (defcustom org-todo-interpretation 'sequence
1488 "Controls how TODO keywords are interpreted.
1489 This variable is in principle obsolete and is only used for
1490 backward compatibility, if the interpretation of todo keywords is
1491 not given already in `org-todo-keywords'. See that variable for
1492 more information."
1493 :group 'org-todo
1494 :group 'org-keywords
1495 :type '(choice (const sequence)
1496 (const type)))
1498 (defcustom org-use-fast-todo-selection 'prefix
1499 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1500 This variable describes if and under what circumstances the cycling
1501 mechanism for TODO keywords will be replaced by a single-key, direct
1502 selection scheme.
1504 When nil, fast selection is never used.
1506 When the symbol `prefix', it will be used when `org-todo' is called with
1507 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1508 in an agenda buffer.
1510 When t, fast selection is used by default. In this case, the prefix
1511 argument forces cycling instead.
1513 In all cases, the special interface is only used if access keys have actually
1514 been assigned by the user, i.e. if keywords in the configuration are followed
1515 by a letter in parenthesis, like TODO(t)."
1516 :group 'org-todo
1517 :type '(choice
1518 (const :tag "Never" nil)
1519 (const :tag "By default" t)
1520 (const :tag "Only with C-u C-c C-t" prefix)))
1522 (defcustom org-provide-todo-statistics t
1523 "Non-nil means, update todo statistics after insert and toggle.
1524 When this is set, todo statistics is updated in the parent of the current
1525 entry each time a todo state is changed."
1526 :group 'org-todo
1527 :type 'boolean)
1529 (defcustom org-after-todo-state-change-hook nil
1530 "Hook which is run after the state of a TODO item was changed.
1531 The new state (a string with a TODO keyword, or nil) is available in the
1532 Lisp variable `state'."
1533 :group 'org-todo
1534 :type 'hook)
1536 (defcustom org-todo-state-tags-triggers nil
1537 "Tag changes that should be triggered by TODO state changes.
1538 This is a list. Each entry is
1540 (state-change (tag . flag) .......)
1542 State-change can be a string with a state, and empty string to indicate the
1543 state that has no TODO keyword, or it can be one of the symbols `todo'
1544 or `done', meaning any not-done or done state, respectively."
1545 :group 'org-todo
1546 :group 'org-tags
1547 :type '(repeat
1548 (cons (choice :tag "When changing to"
1549 (const :tag "Not-done state" todo)
1550 (const :tag "Done state" done)
1551 (string :tag "State"))
1552 (repeat
1553 (cons :tag "Tag action"
1554 (string :tag "Tag")
1555 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1557 (defcustom org-log-done nil
1558 "Information to record when a task moves to the DONE state.
1560 Possible values are:
1562 nil Don't add anything, just change the keyword
1563 time Add a time stamp to the task
1564 note Prompt a closing note and add it with template `org-log-note-headings'
1566 This option can also be set with on a per-file-basis with
1568 #+STARTUP: nologdone
1569 #+STARTUP: logdone
1570 #+STARTUP: lognotedone
1572 You can have local logging settings for a subtree by setting the LOGGING
1573 property to one or more of these keywords."
1574 :group 'org-todo
1575 :group 'org-progress
1576 :type '(choice
1577 (const :tag "No logging" nil)
1578 (const :tag "Record CLOSED timestamp" time)
1579 (const :tag "Record CLOSED timestamp with closing note." note)))
1581 ;; Normalize old uses of org-log-done.
1582 (cond
1583 ((eq org-log-done t) (setq org-log-done 'time))
1584 ((and (listp org-log-done) (memq 'done org-log-done))
1585 (setq org-log-done 'note)))
1587 (defcustom org-log-note-clock-out nil
1588 "Non-nil means, record a note when clocking out of an item.
1589 This can also be configured on a per-file basis by adding one of
1590 the following lines anywhere in the buffer:
1592 #+STARTUP: lognoteclock-out
1593 #+STARTUP: nolognoteclock-out"
1594 :group 'org-todo
1595 :group 'org-progress
1596 :type 'boolean)
1598 (defcustom org-log-done-with-time t
1599 "Non-nil means, the CLOSED time stamp will contain date and time.
1600 When nil, only the date will be recorded."
1601 :group 'org-progress
1602 :type 'boolean)
1604 (defcustom org-log-note-headings
1605 '((done . "CLOSING NOTE %t")
1606 (state . "State %-12s %t")
1607 (note . "Note taken on %t")
1608 (clock-out . ""))
1609 "Headings for notes added to entries.
1610 The value is an alist, with the car being a symbol indicating the note
1611 context, and the cdr is the heading to be used. The heading may also be the
1612 empty string.
1613 %t in the heading will be replaced by a time stamp.
1614 %s will be replaced by the new TODO state, in double quotes.
1615 %u will be replaced by the user name.
1616 %U will be replaced by the full user name."
1617 :group 'org-todo
1618 :group 'org-progress
1619 :type '(list :greedy t
1620 (cons (const :tag "Heading when closing an item" done) string)
1621 (cons (const :tag
1622 "Heading when changing todo state (todo sequence only)"
1623 state) string)
1624 (cons (const :tag "Heading when just taking a note" note) string)
1625 (cons (const :tag "Heading when clocking out" clock-out) string)))
1627 (unless (assq 'note org-log-note-headings)
1628 (push '(note . "%t") org-log-note-headings))
1630 (defcustom org-log-state-notes-insert-after-drawers nil
1631 "Non-nil means, insert state change notes after any drawers in entry.
1632 Only the drawers that *immediately* follow the headline and the
1633 deadline/scheduled line are skipped.
1634 When nil, insert notes right after the heading and perhaps the line
1635 with deadline/scheduling if present."
1636 :group 'org-todo
1637 :group 'org-progress
1638 :type 'boolean)
1640 (defcustom org-log-states-order-reversed t
1641 "Non-nil means, the latest state change note will be directly after heading.
1642 When nil, the notes will be orderer according to time."
1643 :group 'org-todo
1644 :group 'org-progress
1645 :type 'boolean)
1647 (defcustom org-log-repeat 'time
1648 "Non-nil means, record moving through the DONE state when triggering repeat.
1649 An auto-repeating tasks is immediately switched back to TODO when marked
1650 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1651 the TODO keyword definition, or recording a closing note by setting
1652 `org-log-done', there will be no record of the task moving through DONE.
1653 This variable forces taking a note anyway. Possible values are:
1655 nil Don't force a record
1656 time Record a time stamp
1657 note Record a note
1659 This option can also be set with on a per-file-basis with
1661 #+STARTUP: logrepeat
1662 #+STARTUP: lognoterepeat
1663 #+STARTUP: nologrepeat
1665 You can have local logging settings for a subtree by setting the LOGGING
1666 property to one or more of these keywords."
1667 :group 'org-todo
1668 :group 'org-progress
1669 :type '(choice
1670 (const :tag "Don't force a record" nil)
1671 (const :tag "Force recording the DONE state" time)
1672 (const :tag "Force recording a note with the DONE state" note)))
1675 (defgroup org-priorities nil
1676 "Priorities in Org-mode."
1677 :tag "Org Priorities"
1678 :group 'org-todo)
1680 (defcustom org-highest-priority ?A
1681 "The highest priority of TODO items. A character like ?A, ?B etc.
1682 Must have a smaller ASCII number than `org-lowest-priority'."
1683 :group 'org-priorities
1684 :type 'character)
1686 (defcustom org-lowest-priority ?C
1687 "The lowest priority of TODO items. A character like ?A, ?B etc.
1688 Must have a larger ASCII number than `org-highest-priority'."
1689 :group 'org-priorities
1690 :type 'character)
1692 (defcustom org-default-priority ?B
1693 "The default priority of TODO items.
1694 This is the priority an item get if no explicit priority is given."
1695 :group 'org-priorities
1696 :type 'character)
1698 (defcustom org-priority-start-cycle-with-default t
1699 "Non-nil means, start with default priority when starting to cycle.
1700 When this is nil, the first step in the cycle will be (depending on the
1701 command used) one higher or lower that the default priority."
1702 :group 'org-priorities
1703 :type 'boolean)
1705 (defgroup org-time nil
1706 "Options concerning time stamps and deadlines in Org-mode."
1707 :tag "Org Time"
1708 :group 'org)
1710 (defcustom org-insert-labeled-timestamps-at-point nil
1711 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1712 When nil, these labeled time stamps are forces into the second line of an
1713 entry, just after the headline. When scheduling from the global TODO list,
1714 the time stamp will always be forced into the second line."
1715 :group 'org-time
1716 :type 'boolean)
1718 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1719 "Formats for `format-time-string' which are used for time stamps.
1720 It is not recommended to change this constant.")
1722 (defcustom org-time-stamp-rounding-minutes '(0 5)
1723 "Number of minutes to round time stamps to.
1724 These are two values, the first applies when first creating a time stamp.
1725 The second applies when changing it with the commands `S-up' and `S-down'.
1726 When changing the time stamp, this means that it will change in steps
1727 of N minutes, as given by the second value.
1729 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1730 numbers should be factors of 60, so for example 5, 10, 15.
1732 When this is larger than 1, you can still force an exact time-stamp by using
1733 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1734 and by using a prefix arg to `S-up/down' to specify the exact number
1735 of minutes to shift."
1736 :group 'org-time
1737 :get '(lambda (var) ; Make sure all entries have 5 elements
1738 (if (integerp (default-value var))
1739 (list (default-value var) 5)
1740 (default-value var)))
1741 :type '(list
1742 (integer :tag "when inserting times")
1743 (integer :tag "when modifying times")))
1745 ;; Normalize old customizations of this variable.
1746 (when (integerp org-time-stamp-rounding-minutes)
1747 (setq org-time-stamp-rounding-minutes
1748 (list org-time-stamp-rounding-minutes
1749 org-time-stamp-rounding-minutes)))
1751 (defcustom org-display-custom-times nil
1752 "Non-nil means, overlay custom formats over all time stamps.
1753 The formats are defined through the variable `org-time-stamp-custom-formats'.
1754 To turn this on on a per-file basis, insert anywhere in the file:
1755 #+STARTUP: customtime"
1756 :group 'org-time
1757 :set 'set-default
1758 :type 'sexp)
1759 (make-variable-buffer-local 'org-display-custom-times)
1761 (defcustom org-time-stamp-custom-formats
1762 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1763 "Custom formats for time stamps. See `format-time-string' for the syntax.
1764 These are overlayed over the default ISO format if the variable
1765 `org-display-custom-times' is set. Time like %H:%M should be at the
1766 end of the second format."
1767 :group 'org-time
1768 :type 'sexp)
1770 (defun org-time-stamp-format (&optional long inactive)
1771 "Get the right format for a time string."
1772 (let ((f (if long (cdr org-time-stamp-formats)
1773 (car org-time-stamp-formats))))
1774 (if inactive
1775 (concat "[" (substring f 1 -1) "]")
1776 f)))
1778 (defcustom org-time-clocksum-format "%d:%02d"
1779 "The format string used when creating CLOCKSUM lines, or when
1780 org-mode generates a time duration."
1781 :group 'org-time
1782 :type 'string)
1784 (defcustom org-deadline-warning-days 14
1785 "No. of days before expiration during which a deadline becomes active.
1786 This variable governs the display in sparse trees and in the agenda.
1787 When 0 or negative, it means use this number (the absolute value of it)
1788 even if a deadline has a different individual lead time specified."
1789 :group 'org-time
1790 :group 'org-agenda-daily/weekly
1791 :type 'number)
1793 (defcustom org-read-date-prefer-future t
1794 "Non-nil means, assume future for incomplete date input from user.
1795 This affects the following situations:
1796 1. The user gives a day, but no month.
1797 For example, if today is the 15th, and you enter \"3\", Org-mode will
1798 read this as the third of *next* month. However, if you enter \"17\",
1799 it will be considered as *this* month.
1800 2. The user gives a month but not a year.
1801 For example, if it is april and you enter \"feb 2\", this will be read
1802 as feb 2, *next* year. \"May 5\", however, will be this year.
1804 Currently this does not work for ISO week specifications.
1806 When this option is nil, the current month and year will always be used
1807 as defaults."
1808 :group 'org-time
1809 :type 'boolean)
1811 (defcustom org-read-date-display-live t
1812 "Non-nil means, display current interpretation of date prompt live.
1813 This display will be in an overlay, in the minibuffer."
1814 :group 'org-time
1815 :type 'boolean)
1817 (defcustom org-read-date-popup-calendar t
1818 "Non-nil means, pop up a calendar when prompting for a date.
1819 In the calendar, the date can be selected with mouse-1. However, the
1820 minibuffer will also be active, and you can simply enter the date as well.
1821 When nil, only the minibuffer will be available."
1822 :group 'org-time
1823 :type 'boolean)
1824 (if (fboundp 'defvaralias)
1825 (defvaralias 'org-popup-calendar-for-date-prompt
1826 'org-read-date-popup-calendar))
1828 (defcustom org-extend-today-until 0
1829 "The hour when your day really ends. Must be an integer.
1830 This has influence for the following applications:
1831 - When switching the agenda to \"today\". It it is still earlier than
1832 the time given here, the day recognized as TODAY is actually yesterday.
1833 - When a date is read from the user and it is still before the time given
1834 here, the current date and time will be assumed to be yesterday, 23:59.
1835 Also, timestamps inserted in remember templates follow this rule.
1837 IMPORTANT: This is a feature whose implementation is and likely will
1838 remain incomplete. Really, it is only here because past midnight seems to
1839 be the favorite working time of John Wiegley :-)"
1840 :group 'org-time
1841 :type 'number)
1843 (defcustom org-edit-timestamp-down-means-later nil
1844 "Non-nil means, S-down will increase the time in a time stamp.
1845 When nil, S-up will increase."
1846 :group 'org-time
1847 :type 'boolean)
1849 (defcustom org-calendar-follow-timestamp-change t
1850 "Non-nil means, make the calendar window follow timestamp changes.
1851 When a timestamp is modified and the calendar window is visible, it will be
1852 moved to the new date."
1853 :group 'org-time
1854 :type 'boolean)
1856 (defgroup org-tags nil
1857 "Options concerning tags in Org-mode."
1858 :tag "Org Tags"
1859 :group 'org)
1861 (defcustom org-tag-alist nil
1862 "List of tags allowed in Org-mode files.
1863 When this list is nil, Org-mode will base TAG input on what is already in the
1864 buffer.
1865 The value of this variable is an alist, the car of each entry must be a
1866 keyword as a string, the cdr may be a character that is used to select
1867 that tag through the fast-tag-selection interface.
1868 See the manual for details."
1869 :group 'org-tags
1870 :type '(repeat
1871 (choice
1872 (cons (string :tag "Tag name")
1873 (character :tag "Access char"))
1874 (const :tag "Start radio group" (:startgroup))
1875 (const :tag "End radio group" (:endgroup)))))
1877 (defvar org-file-tags nil
1878 "List of tags that can be inherited by all entries in the file.
1879 The tags will be inherited if the variable `org-use-tag-inheritance'
1880 says they should be.
1881 This variable is populated from #+TAG lines.")
1883 (defcustom org-use-fast-tag-selection 'auto
1884 "Non-nil means, use fast tag selection scheme.
1885 This is a special interface to select and deselect tags with single keys.
1886 When nil, fast selection is never used.
1887 When the symbol `auto', fast selection is used if and only if selection
1888 characters for tags have been configured, either through the variable
1889 `org-tag-alist' or through a #+TAGS line in the buffer.
1890 When t, fast selection is always used and selection keys are assigned
1891 automatically if necessary."
1892 :group 'org-tags
1893 :type '(choice
1894 (const :tag "Always" t)
1895 (const :tag "Never" nil)
1896 (const :tag "When selection characters are configured" 'auto)))
1898 (defcustom org-fast-tag-selection-single-key nil
1899 "Non-nil means, fast tag selection exits after first change.
1900 When nil, you have to press RET to exit it.
1901 During fast tag selection, you can toggle this flag with `C-c'.
1902 This variable can also have the value `expert'. In this case, the window
1903 displaying the tags menu is not even shown, until you press C-c again."
1904 :group 'org-tags
1905 :type '(choice
1906 (const :tag "No" nil)
1907 (const :tag "Yes" t)
1908 (const :tag "Expert" expert)))
1910 (defvar org-fast-tag-selection-include-todo nil
1911 "Non-nil means, fast tags selection interface will also offer TODO states.
1912 This is an undocumented feature, you should not rely on it.")
1914 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1915 "The column to which tags should be indented in a headline.
1916 If this number is positive, it specifies the column. If it is negative,
1917 it means that the tags should be flushright to that column. For example,
1918 -80 works well for a normal 80 character screen."
1919 :group 'org-tags
1920 :type 'integer)
1922 (defcustom org-auto-align-tags t
1923 "Non-nil means, realign tags after pro/demotion of TODO state change.
1924 These operations change the length of a headline and therefore shift
1925 the tags around. With this options turned on, after each such operation
1926 the tags are again aligned to `org-tags-column'."
1927 :group 'org-tags
1928 :type 'boolean)
1930 (defcustom org-use-tag-inheritance t
1931 "Non-nil means, tags in levels apply also for sublevels.
1932 When nil, only the tags directly given in a specific line apply there.
1933 This may also be a list of tags that should be inherited, or a regexp that
1934 matches tags that should be inherited. Additional control is possible
1935 with the variable `org-tags-exclude-from-inheritance' which gives an
1936 explicit list of tags to be excluded from inheritance., even if the value of
1937 `org-use-tag-inheritance' would select it for inheritance.
1939 If this option is t, a match early-on in a tree can lead to a large
1940 number of matches in the subtree when constructing the agenda or creating
1941 a sparse tree. If you only want to see the first match in a tree during
1942 a search, check out the variable `org-tags-match-list-sublevels'."
1943 :group 'org-tags
1944 :type '(choice
1945 (const :tag "Not" nil)
1946 (const :tag "Always" t)
1947 (repeat :tag "Specific tags" (string :tag "Tag"))
1948 (regexp :tag "Tags matched by regexp")))
1950 (defcustom org-tags-exclude-from-inheritance nil
1951 "List of tags that should never be inherited.
1952 This is a way to exclude a few tags from inheritance. For way to do
1953 the opposite, to actively allow inheritance for selected tags,
1954 see the variable `org-use-tag-inheritance'."
1955 :group 'org-tags
1956 :type '(repeat (string :tag "Tag")))
1958 (defun org-tag-inherit-p (tag)
1959 "Check if TAG is one that should be inherited."
1960 (cond
1961 ((member tag org-tags-exclude-from-inheritance) nil)
1962 ((eq org-use-tag-inheritance t) t)
1963 ((not org-use-tag-inheritance) nil)
1964 ((stringp org-use-tag-inheritance)
1965 (string-match org-use-tag-inheritance tag))
1966 ((listp org-use-tag-inheritance)
1967 (member tag org-use-tag-inheritance))
1968 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1970 (defcustom org-tags-match-list-sublevels t
1971 "Non-nil means list also sublevels of headlines matching tag search.
1972 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1973 the sublevels of a headline matching a tag search often also match
1974 the same search. Listing all of them can create very long lists.
1975 Setting this variable to nil causes subtrees of a match to be skipped.
1976 This option is off by default, because inheritance in on. If you turn
1977 inheritance off, you very likely want to turn this option on.
1979 As a special case, if the tag search is restricted to TODO items, the
1980 value of this variable is ignored and sublevels are always checked, to
1981 make sure all corresponding TODO items find their way into the list.
1983 This variable is semi-obsolete and probably should always be true. It
1984 is better to limit inheritance to certain tags using the variables
1985 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
1986 :group 'org-tags
1987 :type 'boolean)
1989 (defvar org-tags-history nil
1990 "History of minibuffer reads for tags.")
1991 (defvar org-last-tags-completion-table nil
1992 "The last used completion table for tags.")
1993 (defvar org-after-tags-change-hook nil
1994 "Hook that is run after the tags in a line have changed.")
1996 (defgroup org-properties nil
1997 "Options concerning properties in Org-mode."
1998 :tag "Org Properties"
1999 :group 'org)
2001 (defcustom org-property-format "%-10s %s"
2002 "How property key/value pairs should be formatted by `indent-line'.
2003 When `indent-line' hits a property definition, it will format the line
2004 according to this format, mainly to make sure that the values are
2005 lined-up with respect to each other."
2006 :group 'org-properties
2007 :type 'string)
2009 (defcustom org-use-property-inheritance nil
2010 "Non-nil means, properties apply also for sublevels.
2012 This setting is chiefly used during property searches. Turning it on can
2013 cause significant overhead when doing a search, which is why it is not
2014 on by default.
2016 When nil, only the properties directly given in the current entry count.
2017 When t, every property is inherited. The value may also be a list of
2018 properties that should have inheritance, or a regular expression matching
2019 properties that should be inherited.
2021 However, note that some special properties use inheritance under special
2022 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2023 and the properties ending in \"_ALL\" when they are used as descriptor
2024 for valid values of a property.
2026 Note for programmers:
2027 When querying an entry with `org-entry-get', you can control if inheritance
2028 should be used. By default, `org-entry-get' looks only at the local
2029 properties. You can request inheritance by setting the inherit argument
2030 to t (to force inheritance) or to `selective' (to respect the setting
2031 in this variable)."
2032 :group 'org-properties
2033 :type '(choice
2034 (const :tag "Not" nil)
2035 (const :tag "Always" t)
2036 (repeat :tag "Specific properties" (string :tag "Property"))
2037 (regexp :tag "Properties matched by regexp")))
2039 (defun org-property-inherit-p (property)
2040 "Check if PROPERTY is one that should be inherited."
2041 (cond
2042 ((eq org-use-property-inheritance t) t)
2043 ((not org-use-property-inheritance) nil)
2044 ((stringp org-use-property-inheritance)
2045 (string-match org-use-property-inheritance property))
2046 ((listp org-use-property-inheritance)
2047 (member property org-use-property-inheritance))
2048 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2050 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2051 "The default column format, if no other format has been defined.
2052 This variable can be set on the per-file basis by inserting a line
2054 #+COLUMNS: %25ITEM ....."
2055 :group 'org-properties
2056 :type 'string)
2058 (defcustom org-columns-ellipses ".."
2059 "The ellipses to be used when a field in column view is truncated.
2060 When this is the empty string, as many characters as possible are shown,
2061 but then there will be no visual indication that the field has been truncated.
2062 When this is a string of length N, the last N characters of a truncated
2063 field are replaced by this string. If the column is narrower than the
2064 ellipses string, only part of the ellipses string will be shown."
2065 :group 'org-properties
2066 :type 'string)
2068 (defcustom org-columns-modify-value-for-display-function nil
2069 "Function that modifies values for display in column view.
2070 For example, it can be used to cut out a certain part from a time stamp.
2071 The function must take 2 arguments:
2073 column-title The title of the column (*not* the property name)
2074 value The value that should be modified.
2076 The function should return the value that should be displayed,
2077 or nil if the normal value should be used."
2078 :group 'org-properties
2079 :type 'function)
2081 (defcustom org-effort-property "Effort"
2082 "The property that is being used to keep track of effort estimates.
2083 Effort estimates given in this property need to have the format H:MM."
2084 :group 'org-properties
2085 :group 'org-progress
2086 :type '(string :tag "Property"))
2088 (defconst org-global-properties-fixed
2089 '(("VISIBILITY_ALL" . "folded children content all"))
2090 "List of property/value pairs that can be inherited by any entry.
2091 These are fixed values, for the preset properties.")
2094 (defcustom org-global-properties nil
2095 "List of property/value pairs that can be inherited by any entry.
2096 You can set buffer-local values for the same purpose in the variable
2097 `org-file-properties' this by adding lines like
2099 #+PROPERTY: NAME VALUE"
2100 :group 'org-properties
2101 :type '(repeat
2102 (cons (string :tag "Property")
2103 (string :tag "Value"))))
2105 (defvar org-file-properties nil
2106 "List of property/value pairs that can be inherited by any entry.
2107 Valid for the current buffer.
2108 This variable is populated from #+PROPERTY lines.")
2109 (make-variable-buffer-local 'org-file-properties)
2111 (defgroup org-agenda nil
2112 "Options concerning agenda views in Org-mode."
2113 :tag "Org Agenda"
2114 :group 'org)
2116 (defvar org-category nil
2117 "Variable used by org files to set a category for agenda display.
2118 Such files should use a file variable to set it, for example
2120 # -*- mode: org; org-category: \"ELisp\"
2122 or contain a special line
2124 #+CATEGORY: ELisp
2126 If the file does not specify a category, then file's base name
2127 is used instead.")
2128 (make-variable-buffer-local 'org-category)
2129 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2131 (defcustom org-agenda-files nil
2132 "The files to be used for agenda display.
2133 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2134 \\[org-remove-file]. You can also use customize to edit the list.
2136 If an entry is a directory, all files in that directory that are matched by
2137 `org-agenda-file-regexp' will be part of the file list.
2139 If the value of the variable is not a list but a single file name, then
2140 the list of agenda files is actually stored and maintained in that file, one
2141 agenda file per line."
2142 :group 'org-agenda
2143 :type '(choice
2144 (repeat :tag "List of files and directories" file)
2145 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2147 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2148 "Regular expression to match files for `org-agenda-files'.
2149 If any element in the list in that variable contains a directory instead
2150 of a normal file, all files in that directory that are matched by this
2151 regular expression will be included."
2152 :group 'org-agenda
2153 :type 'regexp)
2155 (defcustom org-agenda-text-search-extra-files nil
2156 "List of extra files to be searched by text search commands.
2157 These files will be search in addition to the agenda files by the
2158 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2159 Note that these files will only be searched for text search commands,
2160 not for the other agenda views like todo lists, tag searches or the weekly
2161 agenda. This variable is intended to list notes and possibly archive files
2162 that should also be searched by these two commands.
2163 In fact, if the first element in the list is the symbol `agenda-archives',
2164 than all archive files of all agenda files will be added to the search
2165 scope."
2166 :group 'org-agenda
2167 :type '(set :greedy t
2168 (const :tag "Agenda Archives" agenda-archives)
2169 (repeat :inline t (file))))
2171 (if (fboundp 'defvaralias)
2172 (defvaralias 'org-agenda-multi-occur-extra-files
2173 'org-agenda-text-search-extra-files))
2175 (defcustom org-agenda-skip-unavailable-files nil
2176 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2177 A nil value means to remove them, after a query, from the list."
2178 :group 'org-agenda
2179 :type 'boolean)
2181 (defcustom org-calendar-to-agenda-key [?c]
2182 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2183 The command `org-calendar-goto-agenda' will be bound to this key. The
2184 default is the character `c' because then `c' can be used to switch back and
2185 forth between agenda and calendar."
2186 :group 'org-agenda
2187 :type 'sexp)
2189 (defcustom org-calendar-agenda-action-key [?k]
2190 "The key to be installed in `calendar-mode-map' for agenda-action.
2191 The command `org-agenda-action' will be bound to this key. The
2192 default is the character `k' because we use the same key in the agenda."
2193 :group 'org-agenda
2194 :type 'sexp)
2196 (eval-after-load "calendar"
2197 '(progn
2198 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2199 'org-calendar-goto-agenda)
2200 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2201 'org-agenda-action)))
2203 (defgroup org-latex nil
2204 "Options for embedding LaTeX code into Org-mode."
2205 :tag "Org LaTeX"
2206 :group 'org)
2208 (defcustom org-format-latex-options
2209 '(:foreground default :background default :scale 1.0
2210 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2211 :matchers ("begin" "$" "$$" "\\(" "\\["))
2212 "Options for creating images from LaTeX fragments.
2213 This is a property list with the following properties:
2214 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2215 `default' means use the foreground of the default face.
2216 :background the background color, or \"Transparent\".
2217 `default' means use the background of the default face.
2218 :scale a scaling factor for the size of the images.
2219 :html-foreground, :html-background, :html-scale
2220 the same numbers for HTML export.
2221 :matchers a list indicating which matchers should be used to
2222 find LaTeX fragments. Valid members of this list are:
2223 \"begin\" find environments
2224 \"$\" find math expressions surrounded by $...$
2225 \"$$\" find math expressions surrounded by $$....$$
2226 \"\\(\" find math expressions surrounded by \\(...\\)
2227 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2228 :group 'org-latex
2229 :type 'plist)
2231 (defcustom org-format-latex-header "\\documentclass{article}
2232 \\usepackage{fullpage} % do not remove
2233 \\usepackage{amssymb}
2234 \\usepackage[usenames]{color}
2235 \\usepackage{amsmath}
2236 \\usepackage{latexsym}
2237 \\usepackage[mathscr]{eucal}
2238 \\pagestyle{empty} % do not remove"
2239 "The document header used for processing LaTeX fragments."
2240 :group 'org-latex
2241 :type 'string)
2244 (defgroup org-font-lock nil
2245 "Font-lock settings for highlighting in Org-mode."
2246 :tag "Org Font Lock"
2247 :group 'org)
2249 (defcustom org-level-color-stars-only nil
2250 "Non-nil means fontify only the stars in each headline.
2251 When nil, the entire headline is fontified.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified."
2254 :group 'org-font-lock
2255 :type 'boolean)
2257 (defcustom org-hide-leading-stars nil
2258 "Non-nil means, hide the first N-1 stars in a headline.
2259 This works by using the face `org-hide' for these stars. This
2260 face is white for a light background, and black for a dark
2261 background. You may have to customize the face `org-hide' to
2262 make this work.
2263 Changing it requires restart of `font-lock-mode' to become effective
2264 also in regions already fontified.
2265 You may also set this on a per-file basis by adding one of the following
2266 lines to the buffer:
2268 #+STARTUP: hidestars
2269 #+STARTUP: showstars"
2270 :group 'org-font-lock
2271 :type 'boolean)
2273 (defcustom org-fontify-done-headline nil
2274 "Non-nil means, change the face of a headline if it is marked DONE.
2275 Normally, only the TODO/DONE keyword indicates the state of a headline.
2276 When this is non-nil, the headline after the keyword is set to the
2277 `org-headline-done' as an additional indication."
2278 :group 'org-font-lock
2279 :type 'boolean)
2281 (defcustom org-fontify-emphasized-text t
2282 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2283 Changing this variable requires a restart of Emacs to take effect."
2284 :group 'org-font-lock
2285 :type 'boolean)
2287 (defcustom org-highlight-latex-fragments-and-specials nil
2288 "Non-nil means, fontify what is treated specially by the exporters."
2289 :group 'org-font-lock
2290 :type 'boolean)
2292 (defcustom org-hide-emphasis-markers nil
2293 "Non-nil mean font-lock should hide the emphasis marker characters."
2294 :group 'org-font-lock
2295 :type 'boolean)
2297 (defvar org-emph-re nil
2298 "Regular expression for matching emphasis.")
2299 (defvar org-verbatim-re nil
2300 "Regular expression for matching verbatim text.")
2301 (defvar org-emphasis-regexp-components) ; defined just below
2302 (defvar org-emphasis-alist) ; defined just below
2303 (defun org-set-emph-re (var val)
2304 "Set variable and compute the emphasis regular expression."
2305 (set var val)
2306 (when (and (boundp 'org-emphasis-alist)
2307 (boundp 'org-emphasis-regexp-components)
2308 org-emphasis-alist org-emphasis-regexp-components)
2309 (let* ((e org-emphasis-regexp-components)
2310 (pre (car e))
2311 (post (nth 1 e))
2312 (border (nth 2 e))
2313 (body (nth 3 e))
2314 (nl (nth 4 e))
2315 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2316 (body1 (concat body "*?"))
2317 (markers (mapconcat 'car org-emphasis-alist ""))
2318 (vmarkers (mapconcat
2319 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2320 org-emphasis-alist "")))
2321 ;; make sure special characters appear at the right position in the class
2322 (if (string-match "\\^" markers)
2323 (setq markers (concat (replace-match "" t t markers) "^")))
2324 (if (string-match "-" markers)
2325 (setq markers (concat (replace-match "" t t markers) "-")))
2326 (if (string-match "\\^" vmarkers)
2327 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2328 (if (string-match "-" vmarkers)
2329 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2330 (if (> nl 0)
2331 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2332 (int-to-string nl) "\\}")))
2333 ;; Make the regexp
2334 (setq org-emph-re
2335 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2336 "\\("
2337 "\\([" markers "]\\)"
2338 "\\("
2339 "[^" border "]\\|"
2340 "[^" border (if (and nil stacked) markers) "]"
2341 body1
2342 "[^" border (if (and nil stacked) markers) "]"
2343 "\\)"
2344 "\\3\\)"
2345 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2346 (setq org-verbatim-re
2347 (concat "\\([" pre "]\\|^\\)"
2348 "\\("
2349 "\\([" vmarkers "]\\)"
2350 "\\("
2351 "[^" border "]\\|"
2352 "[^" border "]"
2353 body1
2354 "[^" border "]"
2355 "\\)"
2356 "\\3\\)"
2357 "\\([" post "]\\|$\\)")))))
2359 (defcustom org-emphasis-regexp-components
2360 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2361 "Components used to build the regular expression for emphasis.
2362 This is a list with 6 entries. Terminology: In an emphasis string
2363 like \" *strong word* \", we call the initial space PREMATCH, the final
2364 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2365 and \"trong wor\" is the body. The different components in this variable
2366 specify what is allowed/forbidden in each part:
2368 pre Chars allowed as prematch. Beginning of line will be allowed too.
2369 post Chars allowed as postmatch. End of line will be allowed too.
2370 border The chars *forbidden* as border characters.
2371 body-regexp A regexp like \".\" to match a body character. Don't use
2372 non-shy groups here, and don't allow newline here.
2373 newline The maximum number of newlines allowed in an emphasis exp.
2375 Use customize to modify this, or restart Emacs after changing it."
2376 :group 'org-font-lock
2377 :set 'org-set-emph-re
2378 :type '(list
2379 (sexp :tag "Allowed chars in pre ")
2380 (sexp :tag "Allowed chars in post ")
2381 (sexp :tag "Forbidden chars in border ")
2382 (sexp :tag "Regexp for body ")
2383 (integer :tag "number of newlines allowed")
2384 (option (boolean :tag "Please ignore this button"))))
2386 (defcustom org-emphasis-alist
2387 `(("*" bold "<b>" "</b>")
2388 ("/" italic "<i>" "</i>")
2389 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2390 ("=" org-code "<code>" "</code>" verbatim)
2391 ("~" org-verbatim "<code>" "</code>" verbatim)
2392 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2393 "<del>" "</del>")
2395 "Special syntax for emphasized text.
2396 Text starting and ending with a special character will be emphasized, for
2397 example *bold*, _underlined_ and /italic/. This variable sets the marker
2398 characters, the face to be used by font-lock for highlighting in Org-mode
2399 Emacs buffers, and the HTML tags to be used for this.
2400 Use customize to modify this, or restart Emacs after changing it."
2401 :group 'org-font-lock
2402 :set 'org-set-emph-re
2403 :type '(repeat
2404 (list
2405 (string :tag "Marker character")
2406 (choice
2407 (face :tag "Font-lock-face")
2408 (plist :tag "Face property list"))
2409 (string :tag "HTML start tag")
2410 (string :tag "HTML end tag")
2411 (option (const verbatim)))))
2413 ;;; Miscellaneous options
2415 (defgroup org-completion nil
2416 "Completion in Org-mode."
2417 :tag "Org Completion"
2418 :group 'org)
2420 (defcustom org-completion-use-ido nil
2421 "Non-nil means, use ido completion wherever possible.
2422 Note that `ido-mode' must be active for this variable to be relevant.
2423 If you decide to turn this variable on, you might well want to turn off
2424 `org-outline-path-complete-in-steps'."
2425 :group 'org-completion
2426 :type 'boolean)
2428 (defcustom org-completion-fallback-command 'hippie-expand
2429 "The expansion command called by \\[org-complete] in normal context.
2430 Normal means, no org-mode-specific context."
2431 :group 'org-completion
2432 :type 'function)
2434 ;;; Functions and variables from ther packages
2435 ;; Declared here to avoid compiler warnings
2437 ;; XEmacs only
2438 (defvar outline-mode-menu-heading)
2439 (defvar outline-mode-menu-show)
2440 (defvar outline-mode-menu-hide)
2441 (defvar zmacs-regions) ; XEmacs regions
2443 ;; Emacs only
2444 (defvar mark-active)
2446 ;; Various packages
2447 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2448 (declare-function calendar-forward-day "cal-move" (arg))
2449 (declare-function calendar-goto-date "cal-move" (date))
2450 (declare-function calendar-goto-today "cal-move" ())
2451 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2452 (defvar calc-embedded-close-formula)
2453 (defvar calc-embedded-open-formula)
2454 (declare-function cdlatex-tab "ext:cdlatex" ())
2455 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2456 (defvar font-lock-unfontify-region-function)
2457 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2458 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2459 (defvar iswitchb-temp-buflist)
2460 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2461 (declare-function org-agenda-skip "org-agenda" ())
2462 (declare-function org-format-agenda-item "org-agenda"
2463 (extra txt &optional category tags dotime noprefix remove-re))
2464 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2465 (declare-function org-agenda-change-all-lines "org-agenda"
2466 (newhead hdmarker &optional fixface just-this))
2467 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2468 (declare-function org-agenda-maybe-redo "org-agenda" ())
2469 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2470 (beg end))
2471 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2472 (declare-function parse-time-string "parse-time" (string))
2473 (declare-function remember "remember" (&optional initial))
2474 (declare-function remember-buffer-desc "remember" ())
2475 (declare-function remember-finalize "remember" ())
2476 (defvar remember-save-after-remembering)
2477 (defvar remember-data-file)
2478 (defvar remember-register)
2479 (defvar remember-buffer)
2480 (defvar remember-handler-functions)
2481 (defvar remember-annotation-functions)
2482 (defvar texmathp-why)
2483 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2484 (declare-function table--at-cell-p "table" (position &optional object at-column))
2486 (defvar w3m-current-url)
2487 (defvar w3m-current-title)
2489 (defvar org-latex-regexps)
2491 ;;; Autoload and prepare some org modules
2493 ;; Some table stuff that needs to be defined here, because it is used
2494 ;; by the functions setting up org-mode or checking for table context.
2496 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2497 "Detects an org-type or table-type table.")
2498 (defconst org-table-line-regexp "^[ \t]*|"
2499 "Detects an org-type table line.")
2500 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2501 "Detects an org-type table line.")
2502 (defconst org-table-hline-regexp "^[ \t]*|-"
2503 "Detects an org-type table hline.")
2504 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2505 "Detects a table-type table hline.")
2506 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2507 "Searching from within a table (any type) this finds the first line
2508 outside the table.")
2510 ;; Autoload the functions in org-table.el that are needed by functions here.
2512 (eval-and-compile
2513 (org-autoload "org-table"
2514 '(org-table-align org-table-begin org-table-blank-field
2515 org-table-convert org-table-convert-region org-table-copy-down
2516 org-table-copy-region org-table-create
2517 org-table-create-or-convert-from-region
2518 org-table-create-with-table.el org-table-current-dline
2519 org-table-cut-region org-table-delete-column org-table-edit-field
2520 org-table-edit-formulas org-table-end org-table-eval-formula
2521 org-table-export org-table-field-info
2522 org-table-get-stored-formulas org-table-goto-column
2523 org-table-hline-and-move org-table-import org-table-insert-column
2524 org-table-insert-hline org-table-insert-row org-table-iterate
2525 org-table-justify-field-maybe org-table-kill-row
2526 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2527 org-table-move-column org-table-move-column-left
2528 org-table-move-column-right org-table-move-row
2529 org-table-move-row-down org-table-move-row-up
2530 org-table-next-field org-table-next-row org-table-paste-rectangle
2531 org-table-previous-field org-table-recalculate
2532 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2533 org-table-toggle-coordinate-overlays
2534 org-table-toggle-formula-debugger org-table-wrap-region
2535 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2537 (defun org-at-table-p (&optional table-type)
2538 "Return t if the cursor is inside an org-type table.
2539 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2540 (if org-enable-table-editor
2541 (save-excursion
2542 (beginning-of-line 1)
2543 (looking-at (if table-type org-table-any-line-regexp
2544 org-table-line-regexp)))
2545 nil))
2546 (defsubst org-table-p () (org-at-table-p))
2548 (defun org-at-table.el-p ()
2549 "Return t if and only if we are at a table.el table."
2550 (and (org-at-table-p 'any)
2551 (save-excursion
2552 (goto-char (org-table-begin 'any))
2553 (looking-at org-table1-hline-regexp))))
2554 (defun org-table-recognize-table.el ()
2555 "If there is a table.el table nearby, recognize it and move into it."
2556 (if org-table-tab-recognizes-table.el
2557 (if (org-at-table.el-p)
2558 (progn
2559 (beginning-of-line 1)
2560 (if (looking-at org-table-dataline-regexp)
2562 (if (looking-at org-table1-hline-regexp)
2563 (progn
2564 (beginning-of-line 2)
2565 (if (looking-at org-table-any-border-regexp)
2566 (beginning-of-line -1)))))
2567 (if (re-search-forward "|" (org-table-end t) t)
2568 (progn
2569 (require 'table)
2570 (if (table--at-cell-p (point))
2572 (message "recognizing table.el table...")
2573 (table-recognize-table)
2574 (message "recognizing table.el table...done")))
2575 (error "This should not happen..."))
2577 nil)
2578 nil))
2580 (defun org-at-table-hline-p ()
2581 "Return t if the cursor is inside a hline in a table."
2582 (if org-enable-table-editor
2583 (save-excursion
2584 (beginning-of-line 1)
2585 (looking-at org-table-hline-regexp))
2586 nil))
2588 (defvar org-table-clean-did-remove-column nil)
2590 (defun org-table-map-tables (function)
2591 "Apply FUNCTION to the start of all tables in the buffer."
2592 (save-excursion
2593 (save-restriction
2594 (widen)
2595 (goto-char (point-min))
2596 (while (re-search-forward org-table-any-line-regexp nil t)
2597 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2598 (beginning-of-line 1)
2599 (if (looking-at org-table-line-regexp)
2600 (save-excursion (funcall function)))
2601 (re-search-forward org-table-any-border-regexp nil 1))))
2602 (message "Mapping tables: done"))
2604 ;; Declare and autoload functions from org-exp.el
2606 (declare-function org-default-export-plist "org-exp")
2607 (declare-function org-infile-export-plist "org-exp")
2608 (declare-function org-get-current-options "org-exp")
2609 (eval-and-compile
2610 (org-autoload "org-exp"
2611 '(org-export org-export-as-ascii org-export-visible
2612 org-insert-export-options-template org-export-as-html-and-open
2613 org-export-as-html-batch org-export-as-html-to-buffer
2614 org-replace-region-by-html org-export-region-as-html
2615 org-export-as-html org-export-icalendar-this-file
2616 org-export-icalendar-all-agenda-files
2617 org-table-clean-before-export
2618 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2620 ;; Declare and autoload functions from org-agenda.el
2622 (eval-and-compile
2623 (org-autoload "org-agenda"
2624 '(org-agenda org-agenda-list org-search-view
2625 org-todo-list org-tags-view org-agenda-list-stuck-projects
2626 org-diary org-agenda-to-appt)))
2628 ;; Autoload org-remember
2630 (eval-and-compile
2631 (org-autoload "org-remember"
2632 '(org-remember-insinuate org-remember-annotation
2633 org-remember-apply-template org-remember org-remember-handler)))
2635 ;; Autoload org-clock.el
2638 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2639 (beg end))
2640 (declare-function org-update-mode-line "org-clock" ())
2641 (defvar org-clock-start-time)
2642 (defvar org-clock-marker (make-marker)
2643 "Marker recording the last clock-in.")
2645 (eval-and-compile
2646 (org-autoload
2647 "org-clock"
2648 '(org-clock-in org-clock-out org-clock-cancel
2649 org-clock-goto org-clock-sum org-clock-display
2650 org-remove-clock-overlays org-clock-report
2651 org-clocktable-shift org-dblock-write:clocktable
2652 org-get-clocktable)))
2654 (defun org-clock-update-time-maybe ()
2655 "If this is a CLOCK line, update it and return t.
2656 Otherwise, return nil."
2657 (interactive)
2658 (save-excursion
2659 (beginning-of-line 1)
2660 (skip-chars-forward " \t")
2661 (when (looking-at org-clock-string)
2662 (let ((re (concat "[ \t]*" org-clock-string
2663 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2664 "\\([ \t]*=>.*\\)?\\)?"))
2665 ts te h m s neg)
2666 (cond
2667 ((not (looking-at re))
2668 nil)
2669 ((not (match-end 2))
2670 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2671 (> org-clock-marker (point))
2672 (<= org-clock-marker (point-at-eol)))
2673 ;; The clock is running here
2674 (setq org-clock-start-time
2675 (apply 'encode-time
2676 (org-parse-time-string (match-string 1))))
2677 (org-update-mode-line)))
2679 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2680 (end-of-line 1)
2681 (setq ts (match-string 1)
2682 te (match-string 3))
2683 (setq s (- (time-to-seconds
2684 (apply 'encode-time (org-parse-time-string te)))
2685 (time-to-seconds
2686 (apply 'encode-time (org-parse-time-string ts))))
2687 neg (< s 0)
2688 s (abs s)
2689 h (floor (/ s 3600))
2690 s (- s (* 3600 h))
2691 m (floor (/ s 60))
2692 s (- s (* 60 s)))
2693 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2694 t))))))
2696 (defun org-check-running-clock ()
2697 "Check if the current buffer contains the running clock.
2698 If yes, offer to stop it and to save the buffer with the changes."
2699 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2700 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2701 (buffer-name))))
2702 (org-clock-out)
2703 (when (y-or-n-p "Save changed buffer?")
2704 (save-buffer))))
2706 (defun org-clocktable-try-shift (dir n)
2707 "Check if this line starts a clock table, if yes, shift the time block."
2708 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2709 (org-clocktable-shift dir n)))
2711 ;; Autoload org-timer.el
2713 ;(declare-function org-timer "org-timer")
2715 (eval-and-compile
2716 (org-autoload
2717 "org-timer"
2718 '(org-timer-start org-timer org-timer-item
2719 org-timer-change-times-in-region)))
2722 ;; Autoload archiving code
2723 ;; The stuff that is needed for cycling and tags has to be defined here.
2725 (defgroup org-archive nil
2726 "Options concerning archiving in Org-mode."
2727 :tag "Org Archive"
2728 :group 'org-structure)
2730 (defcustom org-archive-location "%s_archive::"
2731 "The location where subtrees should be archived.
2733 The value of this variable is a string, consisting of two parts,
2734 separated by a double-colon. The first part is a filename and
2735 the second part is a headline.
2737 When the filename is omitted, archiving happens in the same file.
2738 %s in the filename will be replaced by the current file
2739 name (without the directory part). Archiving to a different file
2740 is useful to keep archived entries from contributing to the
2741 Org-mode Agenda.
2743 The archived entries will be filed as subtrees of the specified
2744 headline. When the headline is omitted, the subtrees are simply
2745 filed away at the end of the file, as top-level entries.
2747 Here are a few examples:
2748 \"%s_archive::\"
2749 If the current file is Projects.org, archive in file
2750 Projects.org_archive, as top-level trees. This is the default.
2752 \"::* Archived Tasks\"
2753 Archive in the current file, under the top-level headline
2754 \"* Archived Tasks\".
2756 \"~/org/archive.org::\"
2757 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2759 \"basement::** Finished Tasks\"
2760 Archive in file ./basement (relative path), as level 3 trees
2761 below the level 2 heading \"** Finished Tasks\".
2763 You may set this option on a per-file basis by adding to the buffer a
2764 line like
2766 #+ARCHIVE: basement::** Finished Tasks
2768 You may also define it locally for a subtree by setting an ARCHIVE property
2769 in the entry. If such a property is found in an entry, or anywhere up
2770 the hierarchy, it will be used."
2771 :group 'org-archive
2772 :type 'string)
2774 (defcustom org-archive-tag "ARCHIVE"
2775 "The tag that marks a subtree as archived.
2776 An archived subtree does not open during visibility cycling, and does
2777 not contribute to the agenda listings.
2778 After changing this, font-lock must be restarted in the relevant buffers to
2779 get the proper fontification."
2780 :group 'org-archive
2781 :group 'org-keywords
2782 :type 'string)
2784 (defcustom org-agenda-skip-archived-trees t
2785 "Non-nil means, the agenda will skip any items located in archived trees.
2786 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2787 variable is no longer recommended, you should leave it at the value t.
2788 Instead, use the key `v' to cycle the archives-mode in the agenda."
2789 :group 'org-archive
2790 :group 'org-agenda-skip
2791 :type 'boolean)
2793 (defcustom org-cycle-open-archived-trees nil
2794 "Non-nil means, `org-cycle' will open archived trees.
2795 An archived tree is a tree marked with the tag ARCHIVE.
2796 When nil, archived trees will stay folded. You can still open them with
2797 normal outline commands like `show-all', but not with the cycling commands."
2798 :group 'org-archive
2799 :group 'org-cycle
2800 :type 'boolean)
2802 (defcustom org-sparse-tree-open-archived-trees nil
2803 "Non-nil means sparse tree construction shows matches in archived trees.
2804 When nil, matches in these trees are highlighted, but the trees are kept in
2805 collapsed state."
2806 :group 'org-archive
2807 :group 'org-sparse-trees
2808 :type 'boolean)
2810 (defun org-cycle-hide-archived-subtrees (state)
2811 "Re-hide all archived subtrees after a visibility state change."
2812 (when (and (not org-cycle-open-archived-trees)
2813 (not (memq state '(overview folded))))
2814 (save-excursion
2815 (let* ((globalp (memq state '(contents all)))
2816 (beg (if globalp (point-min) (point)))
2817 (end (if globalp (point-max) (org-end-of-subtree t))))
2818 (org-hide-archived-subtrees beg end)
2819 (goto-char beg)
2820 (if (looking-at (concat ".*:" org-archive-tag ":"))
2821 (message "%s" (substitute-command-keys
2822 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2824 (defun org-force-cycle-archived ()
2825 "Cycle subtree even if it is archived."
2826 (interactive)
2827 (setq this-command 'org-cycle)
2828 (let ((org-cycle-open-archived-trees t))
2829 (call-interactively 'org-cycle)))
2831 (defun org-hide-archived-subtrees (beg end)
2832 "Re-hide all archived subtrees after a visibility state change."
2833 (save-excursion
2834 (let* ((re (concat ":" org-archive-tag ":")))
2835 (goto-char beg)
2836 (while (re-search-forward re end t)
2837 (and (org-on-heading-p) (hide-subtree))
2838 (org-end-of-subtree t)))))
2840 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2842 (eval-and-compile
2843 (org-autoload "org-archive"
2844 '(org-add-archive-files org-archive-subtree
2845 org-archive-to-archive-sibling org-toggle-archive-tag)))
2847 ;; Autoload Column View Code
2849 (declare-function org-columns-number-to-string "org-colview")
2850 (declare-function org-columns-get-format-and-top-level "org-colview")
2851 (declare-function org-columns-compute "org-colview")
2853 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2854 '(org-columns-number-to-string org-columns-get-format-and-top-level
2855 org-columns-compute org-agenda-columns org-columns-remove-overlays
2856 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2858 ;; Autoload ID code
2860 (declare-function org-id-store-link "org-id")
2861 (org-autoload "org-id"
2862 '(org-id-get-create org-id-new org-id-copy org-id-get
2863 org-id-get-with-outline-path-completion
2864 org-id-get-with-outline-drilling
2865 org-id-goto org-id-find org-id-store-link))
2867 ;;; Variables for pre-computed regular expressions, all buffer local
2869 (defvar org-drawer-regexp nil
2870 "Matches first line of a hidden block.")
2871 (make-variable-buffer-local 'org-drawer-regexp)
2872 (defvar org-todo-regexp nil
2873 "Matches any of the TODO state keywords.")
2874 (make-variable-buffer-local 'org-todo-regexp)
2875 (defvar org-not-done-regexp nil
2876 "Matches any of the TODO state keywords except the last one.")
2877 (make-variable-buffer-local 'org-not-done-regexp)
2878 (defvar org-todo-line-regexp nil
2879 "Matches a headline and puts TODO state into group 2 if present.")
2880 (make-variable-buffer-local 'org-todo-line-regexp)
2881 (defvar org-complex-heading-regexp nil
2882 "Matches a headline and puts everything into groups:
2883 group 1: the stars
2884 group 2: The todo keyword, maybe
2885 group 3: Priority cookie
2886 group 4: True headline
2887 group 5: Tags")
2888 (make-variable-buffer-local 'org-complex-heading-regexp)
2889 (defvar org-todo-line-tags-regexp nil
2890 "Matches a headline and puts TODO state into group 2 if present.
2891 Also put tags into group 4 if tags are present.")
2892 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2893 (defvar org-nl-done-regexp nil
2894 "Matches newline followed by a headline with the DONE keyword.")
2895 (make-variable-buffer-local 'org-nl-done-regexp)
2896 (defvar org-looking-at-done-regexp nil
2897 "Matches the DONE keyword a point.")
2898 (make-variable-buffer-local 'org-looking-at-done-regexp)
2899 (defvar org-ds-keyword-length 12
2900 "Maximum length of the Deadline and SCHEDULED keywords.")
2901 (make-variable-buffer-local 'org-ds-keyword-length)
2902 (defvar org-deadline-regexp nil
2903 "Matches the DEADLINE keyword.")
2904 (make-variable-buffer-local 'org-deadline-regexp)
2905 (defvar org-deadline-time-regexp nil
2906 "Matches the DEADLINE keyword together with a time stamp.")
2907 (make-variable-buffer-local 'org-deadline-time-regexp)
2908 (defvar org-deadline-line-regexp nil
2909 "Matches the DEADLINE keyword and the rest of the line.")
2910 (make-variable-buffer-local 'org-deadline-line-regexp)
2911 (defvar org-scheduled-regexp nil
2912 "Matches the SCHEDULED keyword.")
2913 (make-variable-buffer-local 'org-scheduled-regexp)
2914 (defvar org-scheduled-time-regexp nil
2915 "Matches the SCHEDULED keyword together with a time stamp.")
2916 (make-variable-buffer-local 'org-scheduled-time-regexp)
2917 (defvar org-closed-time-regexp nil
2918 "Matches the CLOSED keyword together with a time stamp.")
2919 (make-variable-buffer-local 'org-closed-time-regexp)
2921 (defvar org-keyword-time-regexp nil
2922 "Matches any of the 4 keywords, together with the time stamp.")
2923 (make-variable-buffer-local 'org-keyword-time-regexp)
2924 (defvar org-keyword-time-not-clock-regexp nil
2925 "Matches any of the 3 keywords, together with the time stamp.")
2926 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2927 (defvar org-maybe-keyword-time-regexp nil
2928 "Matches a timestamp, possibly preceeded by a keyword.")
2929 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2930 (defvar org-planning-or-clock-line-re nil
2931 "Matches a line with planning or clock info.")
2932 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2934 (defconst org-plain-time-of-day-regexp
2935 (concat
2936 "\\(\\<[012]?[0-9]"
2937 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2938 "\\(--?"
2939 "\\(\\<[012]?[0-9]"
2940 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2941 "\\)?")
2942 "Regular expression to match a plain time or time range.
2943 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2944 groups carry important information:
2945 0 the full match
2946 1 the first time, range or not
2947 8 the second time, if it is a range.")
2949 (defconst org-plain-time-extension-regexp
2950 (concat
2951 "\\(\\<[012]?[0-9]"
2952 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2953 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2954 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2955 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2956 groups carry important information:
2957 0 the full match
2958 7 hours of duration
2959 9 minutes of duration")
2961 (defconst org-stamp-time-of-day-regexp
2962 (concat
2963 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2964 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2965 "\\(--?"
2966 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2967 "Regular expression to match a timestamp time or time range.
2968 After a match, the following groups carry important information:
2969 0 the full match
2970 1 date plus weekday, for backreferencing to make sure both times on same day
2971 2 the first time, range or not
2972 4 the second time, if it is a range.")
2974 (defconst org-startup-options
2975 '(("fold" org-startup-folded t)
2976 ("overview" org-startup-folded t)
2977 ("nofold" org-startup-folded nil)
2978 ("showall" org-startup-folded nil)
2979 ("content" org-startup-folded content)
2980 ("hidestars" org-hide-leading-stars t)
2981 ("showstars" org-hide-leading-stars nil)
2982 ("odd" org-odd-levels-only t)
2983 ("oddeven" org-odd-levels-only nil)
2984 ("align" org-startup-align-all-tables t)
2985 ("noalign" org-startup-align-all-tables nil)
2986 ("customtime" org-display-custom-times t)
2987 ("logdone" org-log-done time)
2988 ("lognotedone" org-log-done note)
2989 ("nologdone" org-log-done nil)
2990 ("lognoteclock-out" org-log-note-clock-out t)
2991 ("nolognoteclock-out" org-log-note-clock-out nil)
2992 ("logrepeat" org-log-repeat state)
2993 ("lognoterepeat" org-log-repeat note)
2994 ("nologrepeat" org-log-repeat nil)
2995 ("constcgs" constants-unit-system cgs)
2996 ("constSI" constants-unit-system SI))
2997 "Variable associated with STARTUP options for org-mode.
2998 Each element is a list of three items: The startup options as written
2999 in the #+STARTUP line, the corresponding variable, and the value to
3000 set this variable to if the option is found. An optional forth element PUSH
3001 means to push this value onto the list in the variable.")
3003 (defun org-set-regexps-and-options ()
3004 "Precompute regular expressions for current buffer."
3005 (when (org-mode-p)
3006 (org-set-local 'org-todo-kwd-alist nil)
3007 (org-set-local 'org-todo-key-alist nil)
3008 (org-set-local 'org-todo-key-trigger nil)
3009 (org-set-local 'org-todo-keywords-1 nil)
3010 (org-set-local 'org-done-keywords nil)
3011 (org-set-local 'org-todo-heads nil)
3012 (org-set-local 'org-todo-sets nil)
3013 (org-set-local 'org-todo-log-states nil)
3014 (org-set-local 'org-file-properties nil)
3015 (org-set-local 'org-file-tags nil)
3016 (let ((re (org-make-options-regexp
3017 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3018 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3019 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3020 (splitre "[ \t]+")
3021 kwds kws0 kwsa key log value cat arch tags const links hw dws
3022 tail sep kws1 prio props ftags drawers
3023 ext-setup-or-nil setup-contents (start 0))
3024 (save-excursion
3025 (save-restriction
3026 (widen)
3027 (goto-char (point-min))
3028 (while (or (and ext-setup-or-nil
3029 (string-match re ext-setup-or-nil start)
3030 (setq start (match-end 0)))
3031 (and (setq ext-setup-or-nil nil start 0)
3032 (re-search-forward re nil t)))
3033 (setq key (upcase (match-string 1 ext-setup-or-nil))
3034 value (org-match-string-no-properties 2 ext-setup-or-nil))
3035 (cond
3036 ((equal key "CATEGORY")
3037 (if (string-match "[ \t]+$" value)
3038 (setq value (replace-match "" t t value)))
3039 (setq cat value))
3040 ((member key '("SEQ_TODO" "TODO"))
3041 (push (cons 'sequence (org-split-string value splitre)) kwds))
3042 ((equal key "TYP_TODO")
3043 (push (cons 'type (org-split-string value splitre)) kwds))
3044 ((equal key "TAGS")
3045 (setq tags (append tags (org-split-string value splitre))))
3046 ((equal key "COLUMNS")
3047 (org-set-local 'org-columns-default-format value))
3048 ((equal key "LINK")
3049 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3050 (push (cons (match-string 1 value)
3051 (org-trim (match-string 2 value)))
3052 links)))
3053 ((equal key "PRIORITIES")
3054 (setq prio (org-split-string value " +")))
3055 ((equal key "PROPERTY")
3056 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3057 (push (cons (match-string 1 value) (match-string 2 value))
3058 props)))
3059 ((equal key "FILETAGS")
3060 (when (string-match "\\S-" value)
3061 (setq ftags
3062 (append
3063 ftags
3064 (apply 'append
3065 (mapcar (lambda (x) (org-split-string x ":"))
3066 (org-split-string value)))))))
3067 ((equal key "DRAWERS")
3068 (setq drawers (org-split-string value splitre)))
3069 ((equal key "CONSTANTS")
3070 (setq const (append const (org-split-string value splitre))))
3071 ((equal key "STARTUP")
3072 (let ((opts (org-split-string value splitre))
3073 l var val)
3074 (while (setq l (pop opts))
3075 (when (setq l (assoc l org-startup-options))
3076 (setq var (nth 1 l) val (nth 2 l))
3077 (if (not (nth 3 l))
3078 (set (make-local-variable var) val)
3079 (if (not (listp (symbol-value var)))
3080 (set (make-local-variable var) nil))
3081 (set (make-local-variable var) (symbol-value var))
3082 (add-to-list var val))))))
3083 ((equal key "ARCHIVE")
3084 (string-match " *$" value)
3085 (setq arch (replace-match "" t t value))
3086 (remove-text-properties 0 (length arch)
3087 '(face t fontified t) arch))
3088 ((equal key "SETUPFILE")
3089 (setq setup-contents (org-file-contents
3090 (expand-file-name
3091 (org-remove-double-quotes value))
3092 'noerror))
3093 (if (not ext-setup-or-nil)
3094 (setq ext-setup-or-nil setup-contents start 0)
3095 (setq ext-setup-or-nil
3096 (concat (substring ext-setup-or-nil 0 start)
3097 "\n" setup-contents "\n"
3098 (substring ext-setup-or-nil start)))))
3099 ))))
3100 (when cat
3101 (org-set-local 'org-category (intern cat))
3102 (push (cons "CATEGORY" cat) props))
3103 (when prio
3104 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3105 (setq prio (mapcar 'string-to-char prio))
3106 (org-set-local 'org-highest-priority (nth 0 prio))
3107 (org-set-local 'org-lowest-priority (nth 1 prio))
3108 (org-set-local 'org-default-priority (nth 2 prio)))
3109 (and props (org-set-local 'org-file-properties (nreverse props)))
3110 (and ftags (org-set-local 'org-file-tags ftags))
3111 (and drawers (org-set-local 'org-drawers drawers))
3112 (and arch (org-set-local 'org-archive-location arch))
3113 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3114 ;; Process the TODO keywords
3115 (unless kwds
3116 ;; Use the global values as if they had been given locally.
3117 (setq kwds (default-value 'org-todo-keywords))
3118 (if (stringp (car kwds))
3119 (setq kwds (list (cons org-todo-interpretation
3120 (default-value 'org-todo-keywords)))))
3121 (setq kwds (reverse kwds)))
3122 (setq kwds (nreverse kwds))
3123 (let (inter kws kw)
3124 (while (setq kws (pop kwds))
3125 (setq inter (pop kws) sep (member "|" kws)
3126 kws0 (delete "|" (copy-sequence kws))
3127 kwsa nil
3128 kws1 (mapcar
3129 (lambda (x)
3130 ;; 1 2
3131 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3132 (progn
3133 (setq kw (match-string 1 x)
3134 key (and (match-end 2) (match-string 2 x))
3135 log (org-extract-log-state-settings x))
3136 (push (cons kw (and key (string-to-char key))) kwsa)
3137 (and log (push log org-todo-log-states))
3139 (error "Invalid TODO keyword %s" x)))
3140 kws0)
3141 kwsa (if kwsa (append '((:startgroup))
3142 (nreverse kwsa)
3143 '((:endgroup))))
3144 hw (car kws1)
3145 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3146 tail (list inter hw (car dws) (org-last dws)))
3147 (add-to-list 'org-todo-heads hw 'append)
3148 (push kws1 org-todo-sets)
3149 (setq org-done-keywords (append org-done-keywords dws nil))
3150 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3151 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3152 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3153 (setq org-todo-sets (nreverse org-todo-sets)
3154 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3155 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3156 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3157 ;; Process the constants
3158 (when const
3159 (let (e cst)
3160 (while (setq e (pop const))
3161 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3162 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3163 (setq org-table-formula-constants-local cst)))
3165 ;; Process the tags.
3166 (when tags
3167 (let (e tgs)
3168 (while (setq e (pop tags))
3169 (cond
3170 ((equal e "{") (push '(:startgroup) tgs))
3171 ((equal e "}") (push '(:endgroup) tgs))
3172 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3173 (push (cons (match-string 1 e)
3174 (string-to-char (match-string 2 e)))
3175 tgs))
3176 (t (push (list e) tgs))))
3177 (org-set-local 'org-tag-alist nil)
3178 (while (setq e (pop tgs))
3179 (or (and (stringp (car e))
3180 (assoc (car e) org-tag-alist))
3181 (push e org-tag-alist)))))
3183 ;; Compute the regular expressions and other local variables
3184 (if (not org-done-keywords)
3185 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3186 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3187 (length org-scheduled-string)
3188 (length org-clock-string)
3189 (length org-closed-string)))
3190 org-drawer-regexp
3191 (concat "^[ \t]*:\\("
3192 (mapconcat 'regexp-quote org-drawers "\\|")
3193 "\\):[ \t]*$")
3194 org-not-done-keywords
3195 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3196 org-todo-regexp
3197 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3198 "\\|") "\\)\\>")
3199 org-not-done-regexp
3200 (concat "\\<\\("
3201 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3202 "\\)\\>")
3203 org-todo-line-regexp
3204 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3205 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3206 "\\)\\>\\)?[ \t]*\\(.*\\)")
3207 org-complex-heading-regexp
3208 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3209 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3210 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3211 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3212 org-nl-done-regexp
3213 (concat "\n\\*+[ \t]+"
3214 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3215 "\\)" "\\>")
3216 org-todo-line-tags-regexp
3217 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3218 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3219 (org-re
3220 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3221 org-looking-at-done-regexp
3222 (concat "^" "\\(?:"
3223 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3224 "\\>")
3225 org-deadline-regexp (concat "\\<" org-deadline-string)
3226 org-deadline-time-regexp
3227 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3228 org-deadline-line-regexp
3229 (concat "\\<\\(" org-deadline-string "\\).*")
3230 org-scheduled-regexp
3231 (concat "\\<" org-scheduled-string)
3232 org-scheduled-time-regexp
3233 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3234 org-closed-time-regexp
3235 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3236 org-keyword-time-regexp
3237 (concat "\\<\\(" org-scheduled-string
3238 "\\|" org-deadline-string
3239 "\\|" org-closed-string
3240 "\\|" org-clock-string "\\)"
3241 " *[[<]\\([^]>]+\\)[]>]")
3242 org-keyword-time-not-clock-regexp
3243 (concat "\\<\\(" org-scheduled-string
3244 "\\|" org-deadline-string
3245 "\\|" org-closed-string
3246 "\\)"
3247 " *[[<]\\([^]>]+\\)[]>]")
3248 org-maybe-keyword-time-regexp
3249 (concat "\\(\\<\\(" org-scheduled-string
3250 "\\|" org-deadline-string
3251 "\\|" org-closed-string
3252 "\\|" org-clock-string "\\)\\)?"
3253 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3254 org-planning-or-clock-line-re
3255 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3256 "\\|" org-deadline-string
3257 "\\|" org-closed-string "\\|" org-clock-string
3258 "\\)\\>\\)")
3260 (org-compute-latex-and-specials-regexp)
3261 (org-set-font-lock-defaults))))
3263 (defun org-file-contents (file &optional noerror)
3264 "Return the contents of FILE, as a string."
3265 (if (or (not file)
3266 (not (file-readable-p file)))
3267 (if noerror
3268 (progn
3269 (message "Cannot read file %s" file)
3270 (ding) (sit-for 2)
3272 (error "Cannot read file %s" file))
3273 (with-temp-buffer
3274 (insert-file-contents file)
3275 (buffer-string))))
3277 (defun org-extract-log-state-settings (x)
3278 "Extract the log state setting from a TODO keyword string.
3279 This will extract info from a string like \"WAIT(w@/!)\"."
3280 (let (kw key log1 log2)
3281 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3282 (setq kw (match-string 1 x)
3283 key (and (match-end 2) (match-string 2 x))
3284 log1 (and (match-end 3) (match-string 3 x))
3285 log2 (and (match-end 4) (match-string 4 x)))
3286 (and (or log1 log2)
3287 (list kw
3288 (and log1 (if (equal log1 "!") 'time 'note))
3289 (and log2 (if (equal log2 "!") 'time 'note)))))))
3291 (defun org-remove-keyword-keys (list)
3292 "Remove a pair of parenthesis at the end of each string in LIST."
3293 (mapcar (lambda (x)
3294 (if (string-match "(.*)$" x)
3295 (substring x 0 (match-beginning 0))
3297 list))
3299 ;; FIXME: this could be done much better, using second characters etc.
3300 (defun org-assign-fast-keys (alist)
3301 "Assign fast keys to a keyword-key alist.
3302 Respect keys that are already there."
3303 (let (new e k c c1 c2 (char ?a))
3304 (while (setq e (pop alist))
3305 (cond
3306 ((equal e '(:startgroup)) (push e new))
3307 ((equal e '(:endgroup)) (push e new))
3309 (setq k (car e) c2 nil)
3310 (if (cdr e)
3311 (setq c (cdr e))
3312 ;; automatically assign a character.
3313 (setq c1 (string-to-char
3314 (downcase (substring
3315 k (if (= (string-to-char k) ?@) 1 0)))))
3316 (if (or (rassoc c1 new) (rassoc c1 alist))
3317 (while (or (rassoc char new) (rassoc char alist))
3318 (setq char (1+ char)))
3319 (setq c2 c1))
3320 (setq c (or c2 char)))
3321 (push (cons k c) new))))
3322 (nreverse new)))
3324 ;;; Some variables used in various places
3326 (defvar org-window-configuration nil
3327 "Used in various places to store a window configuration.")
3328 (defvar org-finish-function nil
3329 "Function to be called when `C-c C-c' is used.
3330 This is for getting out of special buffers like remember.")
3333 ;; FIXME: Occasionally check by commenting these, to make sure
3334 ;; no other functions uses these, forgetting to let-bind them.
3335 (defvar entry)
3336 (defvar state)
3337 (defvar last-state)
3338 (defvar date)
3339 (defvar description)
3341 ;; Defined somewhere in this file, but used before definition.
3342 (defvar org-html-entities)
3343 (defvar org-struct-menu)
3344 (defvar org-org-menu)
3345 (defvar org-tbl-menu)
3346 (defvar org-agenda-keymap)
3348 ;;;; Define the Org-mode
3350 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3351 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3354 ;; We use a before-change function to check if a table might need
3355 ;; an update.
3356 (defvar org-table-may-need-update t
3357 "Indicates that a table might need an update.
3358 This variable is set by `org-before-change-function'.
3359 `org-table-align' sets it back to nil.")
3360 (defun org-before-change-function (beg end)
3361 "Every change indicates that a table might need an update."
3362 (setq org-table-may-need-update t))
3363 (defvar org-mode-map)
3364 (defvar org-mode-hook nil)
3365 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3366 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3367 (defvar org-table-buffer-is-an nil)
3368 (defconst org-outline-regexp "\\*+ ")
3370 ;;;###autoload
3371 (define-derived-mode org-mode outline-mode "Org"
3372 "Outline-based notes management and organizer, alias
3373 \"Carsten's outline-mode for keeping track of everything.\"
3375 Org-mode develops organizational tasks around a NOTES file which
3376 contains information about projects as plain text. Org-mode is
3377 implemented on top of outline-mode, which is ideal to keep the content
3378 of large files well structured. It supports ToDo items, deadlines and
3379 time stamps, which magically appear in the diary listing of the Emacs
3380 calendar. Tables are easily created with a built-in table editor.
3381 Plain text URL-like links connect to websites, emails (VM), Usenet
3382 messages (Gnus), BBDB entries, and any files related to the project.
3383 For printing and sharing of notes, an Org-mode file (or a part of it)
3384 can be exported as a structured ASCII or HTML file.
3386 The following commands are available:
3388 \\{org-mode-map}"
3390 ;; Get rid of Outline menus, they are not needed
3391 ;; Need to do this here because define-derived-mode sets up
3392 ;; the keymap so late. Still, it is a waste to call this each time
3393 ;; we switch another buffer into org-mode.
3394 (if (featurep 'xemacs)
3395 (when (boundp 'outline-mode-menu-heading)
3396 ;; Assume this is Greg's port, it used easymenu
3397 (easy-menu-remove outline-mode-menu-heading)
3398 (easy-menu-remove outline-mode-menu-show)
3399 (easy-menu-remove outline-mode-menu-hide))
3400 (define-key org-mode-map [menu-bar headings] 'undefined)
3401 (define-key org-mode-map [menu-bar hide] 'undefined)
3402 (define-key org-mode-map [menu-bar show] 'undefined))
3404 (org-load-modules-maybe)
3405 (easy-menu-add org-org-menu)
3406 (easy-menu-add org-tbl-menu)
3407 (org-install-agenda-files-menu)
3408 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3409 (org-add-to-invisibility-spec '(org-cwidth))
3410 (when (featurep 'xemacs)
3411 (org-set-local 'line-move-ignore-invisible t))
3412 (org-set-local 'outline-regexp org-outline-regexp)
3413 (org-set-local 'outline-level 'org-outline-level)
3414 (when (and org-ellipsis
3415 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3416 (fboundp 'make-glyph-code))
3417 (unless org-display-table
3418 (setq org-display-table (make-display-table)))
3419 (set-display-table-slot
3420 org-display-table 4
3421 (vconcat (mapcar
3422 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3423 org-ellipsis)))
3424 (if (stringp org-ellipsis) org-ellipsis "..."))))
3425 (setq buffer-display-table org-display-table))
3426 (org-set-regexps-and-options)
3427 (when (and org-tag-faces (not org-tags-special-faces-re))
3428 ;; tag faces set outside customize.... force initialization.
3429 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3430 ;; Calc embedded
3431 (org-set-local 'calc-embedded-open-mode "# ")
3432 (modify-syntax-entry ?# "<")
3433 (modify-syntax-entry ?@ "w")
3434 (if org-startup-truncated (setq truncate-lines t))
3435 (org-set-local 'font-lock-unfontify-region-function
3436 'org-unfontify-region)
3437 ;; Activate before-change-function
3438 (org-set-local 'org-table-may-need-update t)
3439 (org-add-hook 'before-change-functions 'org-before-change-function nil
3440 'local)
3441 ;; Check for running clock before killing a buffer
3442 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3443 ;; Paragraphs and auto-filling
3444 (org-set-autofill-regexps)
3445 (setq indent-line-function 'org-indent-line-function)
3446 (org-update-radio-target-regexp)
3448 ;; Comment characters
3449 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3450 (org-set-local 'comment-padding " ")
3452 ;; Align options lines
3453 (org-set-local
3454 'align-mode-rules-list
3455 '((org-in-buffer-settings
3456 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3457 (modes . '(org-mode)))))
3459 ;; Imenu
3460 (org-set-local 'imenu-create-index-function
3461 'org-imenu-get-tree)
3463 ;; Make isearch reveal context
3464 (if (or (featurep 'xemacs)
3465 (not (boundp 'outline-isearch-open-invisible-function)))
3466 ;; Emacs 21 and XEmacs make use of the hook
3467 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3468 ;; Emacs 22 deals with this through a special variable
3469 (org-set-local 'outline-isearch-open-invisible-function
3470 (lambda (&rest ignore) (org-show-context 'isearch))))
3472 ;; If empty file that did not turn on org-mode automatically, make it to.
3473 (if (and org-insert-mode-line-in-empty-file
3474 (interactive-p)
3475 (= (point-min) (point-max)))
3476 (insert "# -*- mode: org -*-\n\n"))
3478 (unless org-inhibit-startup
3479 (when org-startup-align-all-tables
3480 (let ((bmp (buffer-modified-p)))
3481 (org-table-map-tables 'org-table-align)
3482 (set-buffer-modified-p bmp)))
3483 (org-set-startup-visibility)))
3485 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3487 (defun org-current-time ()
3488 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3489 (if (> (car org-time-stamp-rounding-minutes) 1)
3490 (let ((r (car org-time-stamp-rounding-minutes))
3491 (time (decode-time)))
3492 (apply 'encode-time
3493 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3494 (nthcdr 2 time))))
3495 (current-time)))
3497 ;;;; Font-Lock stuff, including the activators
3499 (defvar org-mouse-map (make-sparse-keymap))
3500 (org-defkey org-mouse-map
3501 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3502 (org-defkey org-mouse-map
3503 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3504 (when org-mouse-1-follows-link
3505 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3506 (when org-tab-follows-link
3507 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3508 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3509 (when org-return-follows-link
3510 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3511 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3513 (require 'font-lock)
3515 (defconst org-non-link-chars "]\t\n\r<>")
3516 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3517 "shell" "elisp"))
3518 (defvar org-link-types-re nil
3519 "Matches a link that has a url-like prefix like \"http:\"")
3520 (defvar org-link-re-with-space nil
3521 "Matches a link with spaces, optional angular brackets around it.")
3522 (defvar org-link-re-with-space2 nil
3523 "Matches a link with spaces, optional angular brackets around it.")
3524 (defvar org-link-re-with-space3 nil
3525 "Matches a link with spaces, only for internal part in bracket links.")
3526 (defvar org-angle-link-re nil
3527 "Matches link with angular brackets, spaces are allowed.")
3528 (defvar org-plain-link-re nil
3529 "Matches plain link, without spaces.")
3530 (defvar org-bracket-link-regexp nil
3531 "Matches a link in double brackets.")
3532 (defvar org-bracket-link-analytic-regexp nil
3533 "Regular expression used to analyze links.
3534 Here is what the match groups contain after a match:
3535 1: http:
3536 2: http
3537 3: path
3538 4: [desc]
3539 5: desc")
3540 (defvar org-bracket-link-analytic-regexp++ nil
3541 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3542 (defvar org-any-link-re nil
3543 "Regular expression matching any link.")
3545 (defun org-make-link-regexps ()
3546 "Update the link regular expressions.
3547 This should be called after the variable `org-link-types' has changed."
3548 (setq org-link-types-re
3549 (concat
3550 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3551 org-link-re-with-space
3552 (concat
3553 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3554 "\\([^" org-non-link-chars " ]"
3555 "[^" org-non-link-chars "]*"
3556 "[^" org-non-link-chars " ]\\)>?")
3557 org-link-re-with-space2
3558 (concat
3559 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3560 "\\([^" org-non-link-chars " ]"
3561 "[^\t\n\r]*"
3562 "[^" org-non-link-chars " ]\\)>?")
3563 org-link-re-with-space3
3564 (concat
3565 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3566 "\\([^" org-non-link-chars " ]"
3567 "[^\t\n\r]*\\)")
3568 org-angle-link-re
3569 (concat
3570 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3571 "\\([^" org-non-link-chars " ]"
3572 "[^" org-non-link-chars "]*"
3573 "\\)>")
3574 org-plain-link-re
3575 (concat
3576 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3577 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3578 org-bracket-link-regexp
3579 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3580 org-bracket-link-analytic-regexp
3581 (concat
3582 "\\[\\["
3583 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3584 "\\([^]]+\\)"
3585 "\\]"
3586 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3587 "\\]")
3588 org-bracket-link-analytic-regexp++
3589 (concat
3590 "\\[\\["
3591 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3592 "\\([^]]+\\)"
3593 "\\]"
3594 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3595 "\\]")
3596 org-any-link-re
3597 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3598 org-angle-link-re "\\)\\|\\("
3599 org-plain-link-re "\\)")))
3601 (org-make-link-regexps)
3603 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3604 "Regular expression for fast time stamp matching.")
3605 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3606 "Regular expression for fast time stamp matching.")
3607 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3608 "Regular expression matching time strings for analysis.
3609 This one does not require the space after the date, so it can be used
3610 on a string that terminates immediately after the date.")
3611 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3612 "Regular expression matching time strings for analysis.")
3613 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3614 "Regular expression matching time stamps, with groups.")
3615 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3616 "Regular expression matching time stamps (also [..]), with groups.")
3617 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3618 "Regular expression matching a time stamp range.")
3619 (defconst org-tr-regexp-both
3620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3621 "Regular expression matching a time stamp range.")
3622 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3623 org-ts-regexp "\\)?")
3624 "Regular expression matching a time stamp or time stamp range.")
3625 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3626 org-ts-regexp-both "\\)?")
3627 "Regular expression matching a time stamp or time stamp range.
3628 The time stamps may be either active or inactive.")
3630 (defvar org-emph-face nil)
3632 (defun org-do-emphasis-faces (limit)
3633 "Run through the buffer and add overlays to links."
3634 (let (rtn)
3635 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3636 (if (not (= (char-after (match-beginning 3))
3637 (char-after (match-beginning 4))))
3638 (progn
3639 (setq rtn t)
3640 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3641 'face
3642 (nth 1 (assoc (match-string 3)
3643 org-emphasis-alist)))
3644 (add-text-properties (match-beginning 2) (match-end 2)
3645 '(font-lock-multiline t))
3646 (when org-hide-emphasis-markers
3647 (add-text-properties (match-end 4) (match-beginning 5)
3648 '(invisible org-link))
3649 (add-text-properties (match-beginning 3) (match-end 3)
3650 '(invisible org-link)))))
3651 (backward-char 1))
3652 rtn))
3654 (defun org-emphasize (&optional char)
3655 "Insert or change an emphasis, i.e. a font like bold or italic.
3656 If there is an active region, change that region to a new emphasis.
3657 If there is no region, just insert the marker characters and position
3658 the cursor between them.
3659 CHAR should be either the marker character, or the first character of the
3660 HTML tag associated with that emphasis. If CHAR is a space, the means
3661 to remove the emphasis of the selected region.
3662 If char is not given (for example in an interactive call) it
3663 will be prompted for."
3664 (interactive)
3665 (let ((eal org-emphasis-alist) e det
3666 (erc org-emphasis-regexp-components)
3667 (prompt "")
3668 (string "") beg end move tag c s)
3669 (if (org-region-active-p)
3670 (setq beg (region-beginning) end (region-end)
3671 string (buffer-substring beg end))
3672 (setq move t))
3674 (while (setq e (pop eal))
3675 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3676 c (aref tag 0))
3677 (push (cons c (string-to-char (car e))) det)
3678 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3679 (substring tag 1)))))
3680 (setq det (nreverse det))
3681 (unless char
3682 (message "%s" (concat "Emphasis marker or tag:" prompt))
3683 (setq char (read-char-exclusive)))
3684 (setq char (or (cdr (assoc char det)) char))
3685 (if (equal char ?\ )
3686 (setq s "" move nil)
3687 (unless (assoc (char-to-string char) org-emphasis-alist)
3688 (error "No such emphasis marker: \"%c\"" char))
3689 (setq s (char-to-string char)))
3690 (while (and (> (length string) 1)
3691 (equal (substring string 0 1) (substring string -1))
3692 (assoc (substring string 0 1) org-emphasis-alist))
3693 (setq string (substring string 1 -1)))
3694 (setq string (concat s string s))
3695 (if beg (delete-region beg end))
3696 (unless (or (bolp)
3697 (string-match (concat "[" (nth 0 erc) "\n]")
3698 (char-to-string (char-before (point)))))
3699 (insert " "))
3700 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3701 (char-to-string (char-after (point))))
3702 (insert " ") (backward-char 1))
3703 (insert string)
3704 (and move (backward-char 1))))
3706 (defconst org-nonsticky-props
3707 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3710 (defun org-activate-plain-links (limit)
3711 "Run through the buffer and add overlays to links."
3712 (catch 'exit
3713 (let (f)
3714 (while (re-search-forward org-plain-link-re limit t)
3715 (setq f (get-text-property (match-beginning 0) 'face))
3716 (if (or (eq f 'org-tag)
3717 (and (listp f) (memq 'org-tag f)))
3719 (add-text-properties (match-beginning 0) (match-end 0)
3720 (list 'mouse-face 'highlight
3721 'rear-nonsticky org-nonsticky-props
3722 'keymap org-mouse-map
3724 (throw 'exit t))))))
3726 (defun org-activate-code (limit)
3727 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3728 (progn
3729 (remove-text-properties (match-beginning 0) (match-end 0)
3730 '(display t invisible t intangible t))
3731 t)))
3733 (defun org-activate-angle-links (limit)
3734 "Run through the buffer and add overlays to links."
3735 (if (re-search-forward org-angle-link-re limit t)
3736 (progn
3737 (add-text-properties (match-beginning 0) (match-end 0)
3738 (list 'mouse-face 'highlight
3739 'rear-nonsticky org-nonsticky-props
3740 'keymap org-mouse-map
3742 t)))
3744 (defun org-activate-bracket-links (limit)
3745 "Run through the buffer and add overlays to bracketed links."
3746 (if (re-search-forward org-bracket-link-regexp limit t)
3747 (let* ((help (concat "LINK: "
3748 (org-match-string-no-properties 1)))
3749 ;; FIXME: above we should remove the escapes.
3750 ;; but that requires another match, protecting match data,
3751 ;; a lot of overhead for font-lock.
3752 (ip (org-maybe-intangible
3753 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3754 'keymap org-mouse-map 'mouse-face 'highlight
3755 'font-lock-multiline t 'help-echo help)))
3756 (vp (list 'rear-nonsticky org-nonsticky-props
3757 'keymap org-mouse-map 'mouse-face 'highlight
3758 ' font-lock-multiline t 'help-echo help)))
3759 ;; We need to remove the invisible property here. Table narrowing
3760 ;; may have made some of this invisible.
3761 (remove-text-properties (match-beginning 0) (match-end 0)
3762 '(invisible nil))
3763 (if (match-end 3)
3764 (progn
3765 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3766 (add-text-properties (match-beginning 3) (match-end 3) vp)
3767 (add-text-properties (match-end 3) (match-end 0) ip))
3768 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3769 (add-text-properties (match-beginning 1) (match-end 1) vp)
3770 (add-text-properties (match-end 1) (match-end 0) ip))
3771 t)))
3773 (defun org-activate-dates (limit)
3774 "Run through the buffer and add overlays to dates."
3775 (if (re-search-forward org-tsr-regexp-both limit t)
3776 (progn
3777 (add-text-properties (match-beginning 0) (match-end 0)
3778 (list 'mouse-face 'highlight
3779 'rear-nonsticky org-nonsticky-props
3780 'keymap org-mouse-map))
3781 (when org-display-custom-times
3782 (if (match-end 3)
3783 (org-display-custom-time (match-beginning 3) (match-end 3)))
3784 (org-display-custom-time (match-beginning 1) (match-end 1)))
3785 t)))
3787 (defvar org-target-link-regexp nil
3788 "Regular expression matching radio targets in plain text.")
3789 (make-variable-buffer-local 'org-target-link-regexp)
3790 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3791 "Regular expression matching a link target.")
3792 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3793 "Regular expression matching a radio target.")
3794 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3795 "Regular expression matching any target.")
3797 (defun org-activate-target-links (limit)
3798 "Run through the buffer and add overlays to target matches."
3799 (when org-target-link-regexp
3800 (let ((case-fold-search t))
3801 (if (re-search-forward org-target-link-regexp limit t)
3802 (progn
3803 (add-text-properties (match-beginning 0) (match-end 0)
3804 (list 'mouse-face 'highlight
3805 'rear-nonsticky org-nonsticky-props
3806 'keymap org-mouse-map
3807 'help-echo "Radio target link"
3808 'org-linked-text t))
3809 t)))))
3811 (defun org-update-radio-target-regexp ()
3812 "Find all radio targets in this file and update the regular expression."
3813 (interactive)
3814 (when (memq 'radio org-activate-links)
3815 (setq org-target-link-regexp
3816 (org-make-target-link-regexp (org-all-targets 'radio)))
3817 (org-restart-font-lock)))
3819 (defun org-hide-wide-columns (limit)
3820 (let (s e)
3821 (setq s (text-property-any (point) (or limit (point-max))
3822 'org-cwidth t))
3823 (when s
3824 (setq e (next-single-property-change s 'org-cwidth))
3825 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3826 (goto-char e)
3827 t)))
3829 (defvar org-latex-and-specials-regexp nil
3830 "Regular expression for highlighting export special stuff.")
3831 (defvar org-match-substring-regexp)
3832 (defvar org-match-substring-with-braces-regexp)
3833 (defvar org-export-html-special-string-regexps)
3835 (defun org-compute-latex-and-specials-regexp ()
3836 "Compute regular expression for stuff treated specially by exporters."
3837 (if (not org-highlight-latex-fragments-and-specials)
3838 (org-set-local 'org-latex-and-specials-regexp nil)
3839 (require 'org-exp)
3840 (let*
3841 ((matchers (plist-get org-format-latex-options :matchers))
3842 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3843 org-latex-regexps)))
3844 (options (org-combine-plists (org-default-export-plist)
3845 (org-infile-export-plist)))
3846 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3847 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3848 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3849 (org-export-html-expand (plist-get options :expand-quoted-html))
3850 (org-export-with-special-strings (plist-get options :special-strings))
3851 (re-sub
3852 (cond
3853 ((equal org-export-with-sub-superscripts '{})
3854 (list org-match-substring-with-braces-regexp))
3855 (org-export-with-sub-superscripts
3856 (list org-match-substring-regexp))
3857 (t nil)))
3858 (re-latex
3859 (if org-export-with-LaTeX-fragments
3860 (mapcar (lambda (x) (nth 1 x)) latexs)))
3861 (re-macros
3862 (if org-export-with-TeX-macros
3863 (list (concat "\\\\"
3864 (regexp-opt
3865 (append (mapcar 'car org-html-entities)
3866 (if (boundp 'org-latex-entities)
3867 org-latex-entities nil))
3868 'words))) ; FIXME
3870 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3871 (re-special (if org-export-with-special-strings
3872 (mapcar (lambda (x) (car x))
3873 org-export-html-special-string-regexps)))
3874 (re-rest
3875 (delq nil
3876 (list
3877 (if org-export-html-expand "@<[^>\n]+>")
3878 ))))
3879 (org-set-local
3880 'org-latex-and-specials-regexp
3881 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3882 re-rest) "\\|")))))
3884 (defun org-do-latex-and-special-faces (limit)
3885 "Run through the buffer and add overlays to links."
3886 (when org-latex-and-specials-regexp
3887 (let (rtn d)
3888 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3889 limit t))
3890 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3891 'face))
3892 '(org-code org-verbatim underline)))
3893 (progn
3894 (setq rtn t
3895 d (cond ((member (char-after (1+ (match-beginning 0)))
3896 '(?_ ?^)) 1)
3897 (t 0)))
3898 (font-lock-prepend-text-property
3899 (+ d (match-beginning 0)) (match-end 0)
3900 'face 'org-latex-and-export-specials)
3901 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3902 '(font-lock-multiline t)))))
3903 rtn)))
3905 (defun org-restart-font-lock ()
3906 "Restart font-lock-mode, to force refontification."
3907 (when (and (boundp 'font-lock-mode) font-lock-mode)
3908 (font-lock-mode -1)
3909 (font-lock-mode 1)))
3911 (defun org-all-targets (&optional radio)
3912 "Return a list of all targets in this file.
3913 With optional argument RADIO, only find radio targets."
3914 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3915 rtn)
3916 (save-excursion
3917 (goto-char (point-min))
3918 (while (re-search-forward re nil t)
3919 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3920 rtn)))
3922 (defun org-make-target-link-regexp (targets)
3923 "Make regular expression matching all strings in TARGETS.
3924 The regular expression finds the targets also if there is a line break
3925 between words."
3926 (and targets
3927 (concat
3928 "\\<\\("
3929 (mapconcat
3930 (lambda (x)
3931 (while (string-match " +" x)
3932 (setq x (replace-match "\\s-+" t t x)))
3934 targets
3935 "\\|")
3936 "\\)\\>")))
3938 (defun org-activate-tags (limit)
3939 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3940 (progn
3941 (add-text-properties (match-beginning 1) (match-end 1)
3942 (list 'mouse-face 'highlight
3943 'rear-nonsticky org-nonsticky-props
3944 'keymap org-mouse-map))
3945 t)))
3947 (defun org-outline-level ()
3948 (save-excursion
3949 (looking-at outline-regexp)
3950 (if (match-beginning 1)
3951 (+ (org-get-string-indentation (match-string 1)) 1000)
3952 (1- (- (match-end 0) (match-beginning 0))))))
3954 (defvar org-font-lock-keywords nil)
3956 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3957 "Regular expression matching a property line.")
3959 (defvar org-font-lock-hook nil
3960 "Functions to be called for special font lock stuff.")
3962 (defun org-font-lock-hook (limit)
3963 (run-hook-with-args 'org-font-lock-hook limit))
3965 (defun org-set-font-lock-defaults ()
3966 (let* ((em org-fontify-emphasized-text)
3967 (lk org-activate-links)
3968 (org-font-lock-extra-keywords
3969 (list
3970 ;; Call the hook
3971 '(org-font-lock-hook)
3972 ;; Headlines
3973 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3974 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3975 ;; Table lines
3976 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3977 (1 'org-table t))
3978 ;; Table internals
3979 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3980 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3981 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3982 ;; Drawers
3983 (list org-drawer-regexp '(0 'org-special-keyword t))
3984 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3985 ;; Properties
3986 (list org-property-re
3987 '(1 'org-special-keyword t)
3988 '(3 'org-property-value t))
3989 (if org-format-transports-properties-p
3990 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3991 ;; Links
3992 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3993 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3994 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3995 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3996 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3997 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3998 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3999 '(org-hide-wide-columns (0 nil append))
4000 ;; TODO lines
4001 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4002 '(1 (org-get-todo-face 1) t))
4003 ;; DONE
4004 (if org-fontify-done-headline
4005 (list (concat "^[*]+ +\\<\\("
4006 (mapconcat 'regexp-quote org-done-keywords "\\|")
4007 "\\)\\(.*\\)")
4008 '(2 'org-headline-done t))
4009 nil)
4010 ;; Priorities
4011 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4012 ;; Tags
4013 '(org-font-lock-add-tag-faces)
4014 ;; Special keywords
4015 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4016 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4017 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4018 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4019 ;; Emphasis
4020 (if em
4021 (if (featurep 'xemacs)
4022 '(org-do-emphasis-faces (0 nil append))
4023 '(org-do-emphasis-faces)))
4024 ;; Checkboxes
4025 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4026 2 'bold prepend)
4027 (if org-provide-checkbox-statistics
4028 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4029 (0 (org-get-checkbox-statistics-face) t)))
4030 ;; Description list items
4031 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4032 2 'bold prepend)
4033 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4034 '(1 'org-archived prepend))
4035 ;; Specials
4036 '(org-do-latex-and-special-faces)
4037 ;; Code
4038 '(org-activate-code (1 'org-code t))
4039 ;; COMMENT
4040 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4041 "\\|" org-quote-string "\\)\\>")
4042 '(1 'org-special-keyword t))
4043 '("^#.*" (0 'font-lock-comment-face t))
4045 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4046 ;; Now set the full font-lock-keywords
4047 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4048 (org-set-local 'font-lock-defaults
4049 '(org-font-lock-keywords t nil nil backward-paragraph))
4050 (kill-local-variable 'font-lock-keywords) nil))
4052 (defvar org-m nil)
4053 (defvar org-l nil)
4054 (defvar org-f nil)
4055 (defun org-get-level-face (n)
4056 "Get the right face for match N in font-lock matching of headlines."
4057 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4058 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4059 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4060 (cond
4061 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4062 ((eq n 2) org-f)
4063 (t (if org-level-color-stars-only nil org-f))))
4065 (defun org-get-todo-face (kwd)
4066 "Get the right face for a TODO keyword KWD.
4067 If KWD is a number, get the corresponding match group."
4068 (if (numberp kwd) (setq kwd (match-string kwd)))
4069 (or (cdr (assoc kwd org-todo-keyword-faces))
4070 (and (member kwd org-done-keywords) 'org-done)
4071 'org-todo))
4073 (defun org-font-lock-add-tag-faces (limit)
4074 "Add the special tag faces."
4075 (when (and org-tag-faces org-tags-special-faces-re)
4076 (while (re-search-forward org-tags-special-faces-re limit t)
4077 (add-text-properties (match-beginning 1) (match-end 1)
4078 (list 'face (org-get-tag-face 1)
4079 'font-lock-fontified t))
4080 (backward-char 1))))
4082 (defun org-get-tag-face (kwd)
4083 "Get the right face for a TODO keyword KWD.
4084 If KWD is a number, get the corresponding match group."
4085 (if (numberp kwd) (setq kwd (match-string kwd)))
4086 (or (cdr (assoc kwd org-tag-faces))
4087 'org-tag))
4089 (defun org-unfontify-region (beg end &optional maybe_loudly)
4090 "Remove fontification and activation overlays from links."
4091 (font-lock-default-unfontify-region beg end)
4092 (let* ((buffer-undo-list t)
4093 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4094 (inhibit-modification-hooks t)
4095 deactivate-mark buffer-file-name buffer-file-truename)
4096 (remove-text-properties beg end
4097 '(mouse-face t keymap t org-linked-text t
4098 invisible t intangible t))))
4100 ;;;; Visibility cycling, including org-goto and indirect buffer
4102 ;;; Cycling
4104 (defvar org-cycle-global-status nil)
4105 (make-variable-buffer-local 'org-cycle-global-status)
4106 (defvar org-cycle-subtree-status nil)
4107 (make-variable-buffer-local 'org-cycle-subtree-status)
4109 ;;;###autoload
4110 (defun org-cycle (&optional arg)
4111 "Visibility cycling for Org-mode.
4113 - When this function is called with a prefix argument, rotate the entire
4114 buffer through 3 states (global cycling)
4115 1. OVERVIEW: Show only top-level headlines.
4116 2. CONTENTS: Show all headlines of all levels, but no body text.
4117 3. SHOW ALL: Show everything.
4118 When called with two C-u C-u prefixes, switch to the startup visibility,
4119 determined by the variable `org-startup-folded', and by any VISIBILITY
4120 properties in the buffer.
4121 When called with three C-u C-u C-u prefixed, show the entire buffer,
4122 including drawers.
4124 - When point is at the beginning of a headline, rotate the subtree started
4125 by this line through 3 different states (local cycling)
4126 1. FOLDED: Only the main headline is shown.
4127 2. CHILDREN: The main headline and the direct children are shown.
4128 From this state, you can move to one of the children
4129 and zoom in further.
4130 3. SUBTREE: Show the entire subtree, including body text.
4132 - When there is a numeric prefix, go up to a heading with level ARG, do
4133 a `show-subtree' and return to the previous cursor position. If ARG
4134 is negative, go up that many levels.
4136 - When point is not at the beginning of a headline, execute the global
4137 binding for TAB, which is re-indenting the line. See the option
4138 `org-cycle-emulate-tab' for details.
4140 - Special case: if point is at the beginning of the buffer and there is
4141 no headline in line 1, this function will act as if called with prefix arg.
4142 But only if also the variable `org-cycle-global-at-bob' is t."
4143 (interactive "P")
4144 (org-load-modules-maybe)
4145 (let* ((outline-regexp
4146 (if (and (org-mode-p) org-cycle-include-plain-lists)
4147 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4148 outline-regexp))
4149 (bob-special (and org-cycle-global-at-bob (bobp)
4150 (not (looking-at outline-regexp))))
4151 (org-cycle-hook
4152 (if bob-special
4153 (delq 'org-optimize-window-after-visibility-change
4154 (copy-sequence org-cycle-hook))
4155 org-cycle-hook))
4156 (pos (point)))
4158 (if (or bob-special (equal arg '(4)))
4159 ;; special case: use global cycling
4160 (setq arg t))
4162 (cond
4164 ((equal arg '(16))
4165 (org-set-startup-visibility)
4166 (message "Startup visibility, plus VISIBILITY properties"))
4168 ((equal arg '(64))
4169 (show-all)
4170 (message "Entire buffer visible, including drawers"))
4172 ((org-at-table-p 'any)
4173 ;; Enter the table or move to the next field in the table
4174 (or (org-table-recognize-table.el)
4175 (progn
4176 (if arg (org-table-edit-field t)
4177 (org-table-justify-field-maybe)
4178 (call-interactively 'org-table-next-field)))))
4180 ((eq arg t) ;; Global cycling
4182 (cond
4183 ((and (eq last-command this-command)
4184 (eq org-cycle-global-status 'overview))
4185 ;; We just created the overview - now do table of contents
4186 ;; This can be slow in very large buffers, so indicate action
4187 (message "CONTENTS...")
4188 (org-content)
4189 (message "CONTENTS...done")
4190 (setq org-cycle-global-status 'contents)
4191 (run-hook-with-args 'org-cycle-hook 'contents))
4193 ((and (eq last-command this-command)
4194 (eq org-cycle-global-status 'contents))
4195 ;; We just showed the table of contents - now show everything
4196 (show-all)
4197 (message "SHOW ALL")
4198 (setq org-cycle-global-status 'all)
4199 (run-hook-with-args 'org-cycle-hook 'all))
4202 ;; Default action: go to overview
4203 (org-overview)
4204 (message "OVERVIEW")
4205 (setq org-cycle-global-status 'overview)
4206 (run-hook-with-args 'org-cycle-hook 'overview))))
4208 ((and org-drawers org-drawer-regexp
4209 (save-excursion
4210 (beginning-of-line 1)
4211 (looking-at org-drawer-regexp)))
4212 ;; Toggle block visibility
4213 (org-flag-drawer
4214 (not (get-char-property (match-end 0) 'invisible))))
4216 ((integerp arg)
4217 ;; Show-subtree, ARG levels up from here.
4218 (save-excursion
4219 (org-back-to-heading)
4220 (outline-up-heading (if (< arg 0) (- arg)
4221 (- (funcall outline-level) arg)))
4222 (org-show-subtree)))
4224 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4225 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4226 ;; At a heading: rotate between three different views
4227 (org-back-to-heading)
4228 (let ((goal-column 0) eoh eol eos)
4229 ;; First, some boundaries
4230 (save-excursion
4231 (org-back-to-heading)
4232 (save-excursion
4233 (beginning-of-line 2)
4234 (while (and (not (eobp)) ;; this is like `next-line'
4235 (get-char-property (1- (point)) 'invisible))
4236 (beginning-of-line 2)) (setq eol (point)))
4237 (outline-end-of-heading) (setq eoh (point))
4238 (org-end-of-subtree t)
4239 (unless (eobp)
4240 (skip-chars-forward " \t\n")
4241 (beginning-of-line 1) ; in case this is an item
4243 (setq eos (1- (point))))
4244 ;; Find out what to do next and set `this-command'
4245 (cond
4246 ((= eos eoh)
4247 ;; Nothing is hidden behind this heading
4248 (message "EMPTY ENTRY")
4249 (setq org-cycle-subtree-status nil)
4250 (save-excursion
4251 (goto-char eos)
4252 (outline-next-heading)
4253 (if (org-invisible-p) (org-flag-heading nil))))
4254 ((or (>= eol eos)
4255 (not (string-match "\\S-" (buffer-substring eol eos))))
4256 ;; Entire subtree is hidden in one line: open it
4257 (org-show-entry)
4258 (show-children)
4259 (message "CHILDREN")
4260 (save-excursion
4261 (goto-char eos)
4262 (outline-next-heading)
4263 (if (org-invisible-p) (org-flag-heading nil)))
4264 (setq org-cycle-subtree-status 'children)
4265 (run-hook-with-args 'org-cycle-hook 'children))
4266 ((and (eq last-command this-command)
4267 (eq org-cycle-subtree-status 'children))
4268 ;; We just showed the children, now show everything.
4269 (org-show-subtree)
4270 (message "SUBTREE")
4271 (setq org-cycle-subtree-status 'subtree)
4272 (run-hook-with-args 'org-cycle-hook 'subtree))
4274 ;; Default action: hide the subtree.
4275 (hide-subtree)
4276 (message "FOLDED")
4277 (setq org-cycle-subtree-status 'folded)
4278 (run-hook-with-args 'org-cycle-hook 'folded)))))
4280 ;; TAB emulation and template completion
4281 (buffer-read-only (org-back-to-heading))
4283 ((org-try-structure-completion))
4285 ((org-try-cdlatex-tab))
4287 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4288 (or (not (bolp))
4289 (not (looking-at outline-regexp))))
4290 (call-interactively (global-key-binding "\t")))
4292 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4293 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4294 (or (and (eq org-cycle-emulate-tab 'white)
4295 (= (match-end 0) (point-at-eol)))
4296 (and (eq org-cycle-emulate-tab 'whitestart)
4297 (>= (match-end 0) pos))))
4299 (eq org-cycle-emulate-tab t))
4300 (call-interactively (global-key-binding "\t")))
4302 (t (save-excursion
4303 (org-back-to-heading)
4304 (org-cycle))))))
4306 ;;;###autoload
4307 (defun org-global-cycle (&optional arg)
4308 "Cycle the global visibility. For details see `org-cycle'.
4309 With C-u prefix arg, switch to startup visibility.
4310 With a numeric prefix, show all headlines up to that level."
4311 (interactive "P")
4312 (let ((org-cycle-include-plain-lists
4313 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4314 (cond
4315 ((integerp arg)
4316 (show-all)
4317 (hide-sublevels arg)
4318 (setq org-cycle-global-status 'contents))
4319 ((equal arg '(4))
4320 (org-set-startup-visibility)
4321 (message "Startup visibility, plus VISIBILITY properties."))
4323 (org-cycle '(4))))))
4325 (defun org-set-startup-visibility ()
4326 "Set the visibility required by startup options and properties."
4327 (cond
4328 ((eq org-startup-folded t)
4329 (org-cycle '(4)))
4330 ((eq org-startup-folded 'content)
4331 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4332 (org-cycle '(4)) (org-cycle '(4)))))
4333 (org-set-visibility-according-to-property 'no-cleanup)
4334 (org-cycle-hide-archived-subtrees 'all)
4335 (org-cycle-hide-drawers 'all)
4336 (org-cycle-show-empty-lines 'all))
4338 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4339 "Switch subtree visibilities according to :VISIBILITY: property."
4340 (interactive)
4341 (let (state)
4342 (save-excursion
4343 (goto-char (point-min))
4344 (while (re-search-forward
4345 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4346 nil t)
4347 (setq state (match-string 1))
4348 (save-excursion
4349 (org-back-to-heading t)
4350 (hide-subtree)
4351 (org-reveal)
4352 (cond
4353 ((equal state '("fold" "folded"))
4354 (hide-subtree))
4355 ((equal state "children")
4356 (org-show-hidden-entry)
4357 (show-children))
4358 ((equal state "content")
4359 (save-excursion
4360 (save-restriction
4361 (org-narrow-to-subtree)
4362 (org-content))))
4363 ((member state '("all" "showall"))
4364 (show-subtree)))))
4365 (unless no-cleanup
4366 (org-cycle-hide-archived-subtrees 'all)
4367 (org-cycle-hide-drawers 'all)
4368 (org-cycle-show-empty-lines 'all)))))
4370 (defun org-overview ()
4371 "Switch to overview mode, showing only top-level headlines.
4372 Really, this shows all headlines with level equal or greater than the level
4373 of the first headline in the buffer. This is important, because if the
4374 first headline is not level one, then (hide-sublevels 1) gives confusing
4375 results."
4376 (interactive)
4377 (let ((level (save-excursion
4378 (goto-char (point-min))
4379 (if (re-search-forward (concat "^" outline-regexp) nil t)
4380 (progn
4381 (goto-char (match-beginning 0))
4382 (funcall outline-level))))))
4383 (and level (hide-sublevels level))))
4385 (defun org-content (&optional arg)
4386 "Show all headlines in the buffer, like a table of contents.
4387 With numerical argument N, show content up to level N."
4388 (interactive "P")
4389 (save-excursion
4390 ;; Visit all headings and show their offspring
4391 (and (integerp arg) (org-overview))
4392 (goto-char (point-max))
4393 (catch 'exit
4394 (while (and (progn (condition-case nil
4395 (outline-previous-visible-heading 1)
4396 (error (goto-char (point-min))))
4398 (looking-at outline-regexp))
4399 (if (integerp arg)
4400 (show-children (1- arg))
4401 (show-branches))
4402 (if (bobp) (throw 'exit nil))))))
4405 (defun org-optimize-window-after-visibility-change (state)
4406 "Adjust the window after a change in outline visibility.
4407 This function is the default value of the hook `org-cycle-hook'."
4408 (when (get-buffer-window (current-buffer))
4409 (cond
4410 ; ((eq state 'overview) (org-first-headline-recenter 1))
4411 ; ((eq state 'overview) (org-beginning-of-line))
4412 ((eq state 'content) nil)
4413 ((eq state 'all) nil)
4414 ((eq state 'folded) nil)
4415 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4416 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4418 (defun org-compact-display-after-subtree-move ()
4419 (let (beg end)
4420 (save-excursion
4421 (if (org-up-heading-safe)
4422 (progn
4423 (hide-subtree)
4424 (show-entry)
4425 (show-children)
4426 (org-cycle-show-empty-lines 'children)
4427 (org-cycle-hide-drawers 'children))
4428 (org-overview)))))
4430 (defun org-cycle-show-empty-lines (state)
4431 "Show empty lines above all visible headlines.
4432 The region to be covered depends on STATE when called through
4433 `org-cycle-hook'. Lisp program can use t for STATE to get the
4434 entire buffer covered. Note that an empty line is only shown if there
4435 are at least `org-cycle-separator-lines' empty lines before the headline."
4436 (when (> org-cycle-separator-lines 0)
4437 (save-excursion
4438 (let* ((n org-cycle-separator-lines)
4439 (re (cond
4440 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4441 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4442 (t (let ((ns (number-to-string (- n 2))))
4443 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4444 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4445 beg end)
4446 (cond
4447 ((memq state '(overview contents t))
4448 (setq beg (point-min) end (point-max)))
4449 ((memq state '(children folded))
4450 (setq beg (point) end (progn (org-end-of-subtree t t)
4451 (beginning-of-line 2)
4452 (point)))))
4453 (when beg
4454 (goto-char beg)
4455 (while (re-search-forward re end t)
4456 (if (not (get-char-property (match-end 1) 'invisible))
4457 (outline-flag-region
4458 (match-beginning 1) (match-end 1) nil)))))))
4459 ;; Never hide empty lines at the end of the file.
4460 (save-excursion
4461 (goto-char (point-max))
4462 (outline-previous-heading)
4463 (outline-end-of-heading)
4464 (if (and (looking-at "[ \t\n]+")
4465 (= (match-end 0) (point-max)))
4466 (outline-flag-region (point) (match-end 0) nil))))
4468 (defun org-show-empty-lines-in-parent ()
4469 "Move to the parent and re-show empty lines before visible headlines."
4470 (save-excursion
4471 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4472 (org-cycle-show-empty-lines context))))
4474 (defun org-cycle-hide-drawers (state)
4475 "Re-hide all drawers after a visibility state change."
4476 (when (and (org-mode-p)
4477 (not (memq state '(overview folded))))
4478 (save-excursion
4479 (let* ((globalp (memq state '(contents all)))
4480 (beg (if globalp (point-min) (point)))
4481 (end (if globalp (point-max) (org-end-of-subtree t))))
4482 (goto-char beg)
4483 (while (re-search-forward org-drawer-regexp end t)
4484 (org-flag-drawer t))))))
4486 (defun org-flag-drawer (flag)
4487 (save-excursion
4488 (beginning-of-line 1)
4489 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4490 (let ((b (match-end 0))
4491 (outline-regexp org-outline-regexp))
4492 (if (re-search-forward
4493 "^[ \t]*:END:"
4494 (save-excursion (outline-next-heading) (point)) t)
4495 (outline-flag-region b (point-at-eol) flag)
4496 (error ":END: line missing"))))))
4498 (defun org-subtree-end-visible-p ()
4499 "Is the end of the current subtree visible?"
4500 (pos-visible-in-window-p
4501 (save-excursion (org-end-of-subtree t) (point))))
4503 (defun org-first-headline-recenter (&optional N)
4504 "Move cursor to the first headline and recenter the headline.
4505 Optional argument N means, put the headline into the Nth line of the window."
4506 (goto-char (point-min))
4507 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4508 (beginning-of-line)
4509 (recenter (prefix-numeric-value N))))
4511 ;;; Org-goto
4513 (defvar org-goto-window-configuration nil)
4514 (defvar org-goto-marker nil)
4515 (defvar org-goto-map
4516 (let ((map (make-sparse-keymap)))
4517 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4518 (while (setq cmd (pop cmds))
4519 (substitute-key-definition cmd cmd map global-map)))
4520 (suppress-keymap map)
4521 (org-defkey map "\C-m" 'org-goto-ret)
4522 (org-defkey map [(return)] 'org-goto-ret)
4523 (org-defkey map [(left)] 'org-goto-left)
4524 (org-defkey map [(right)] 'org-goto-right)
4525 (org-defkey map [(control ?g)] 'org-goto-quit)
4526 (org-defkey map "\C-i" 'org-cycle)
4527 (org-defkey map [(tab)] 'org-cycle)
4528 (org-defkey map [(down)] 'outline-next-visible-heading)
4529 (org-defkey map [(up)] 'outline-previous-visible-heading)
4530 (if org-goto-auto-isearch
4531 (if (fboundp 'define-key-after)
4532 (define-key-after map [t] 'org-goto-local-auto-isearch)
4533 nil)
4534 (org-defkey map "q" 'org-goto-quit)
4535 (org-defkey map "n" 'outline-next-visible-heading)
4536 (org-defkey map "p" 'outline-previous-visible-heading)
4537 (org-defkey map "f" 'outline-forward-same-level)
4538 (org-defkey map "b" 'outline-backward-same-level)
4539 (org-defkey map "u" 'outline-up-heading))
4540 (org-defkey map "/" 'org-occur)
4541 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4542 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4543 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4544 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4545 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4546 map))
4548 (defconst org-goto-help
4549 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4550 RET=jump to location [Q]uit and return to previous location
4551 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4553 (defvar org-goto-start-pos) ; dynamically scoped parameter
4555 ;; FIXME: Docstring doe not mention both interfaces
4556 (defun org-goto (&optional alternative-interface)
4557 "Look up a different location in the current file, keeping current visibility.
4559 When you want look-up or go to a different location in a document, the
4560 fastest way is often to fold the entire buffer and then dive into the tree.
4561 This method has the disadvantage, that the previous location will be folded,
4562 which may not be what you want.
4564 This command works around this by showing a copy of the current buffer
4565 in an indirect buffer, in overview mode. You can dive into the tree in
4566 that copy, use org-occur and incremental search to find a location.
4567 When pressing RET or `Q', the command returns to the original buffer in
4568 which the visibility is still unchanged. After RET is will also jump to
4569 the location selected in the indirect buffer and expose the
4570 the headline hierarchy above."
4571 (interactive "P")
4572 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4573 (org-refile-use-outline-path t)
4574 (interface
4575 (if (not alternative-interface)
4576 org-goto-interface
4577 (if (eq org-goto-interface 'outline)
4578 'outline-path-completion
4579 'outline)))
4580 (org-goto-start-pos (point))
4581 (selected-point
4582 (if (eq interface 'outline)
4583 (car (org-get-location (current-buffer) org-goto-help))
4584 (nth 3 (org-refile-get-location "Goto: ")))))
4585 (if selected-point
4586 (progn
4587 (org-mark-ring-push org-goto-start-pos)
4588 (goto-char selected-point)
4589 (if (or (org-invisible-p) (org-invisible-p2))
4590 (org-show-context 'org-goto)))
4591 (message "Quit"))))
4593 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4594 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4595 (defvar org-goto-local-auto-isearch-map) ; defined below
4597 (defun org-get-location (buf help)
4598 "Let the user select a location in the Org-mode buffer BUF.
4599 This function uses a recursive edit. It returns the selected position
4600 or nil."
4601 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4602 (isearch-hide-immediately nil)
4603 (isearch-search-fun-function
4604 (lambda () 'org-goto-local-search-headings))
4605 (org-goto-selected-point org-goto-exit-command))
4606 (save-excursion
4607 (save-window-excursion
4608 (delete-other-windows)
4609 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4610 (switch-to-buffer
4611 (condition-case nil
4612 (make-indirect-buffer (current-buffer) "*org-goto*")
4613 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4614 (with-output-to-temp-buffer "*Help*"
4615 (princ help))
4616 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4617 (setq buffer-read-only nil)
4618 (let ((org-startup-truncated t)
4619 (org-startup-folded nil)
4620 (org-startup-align-all-tables nil))
4621 (org-mode)
4622 (org-overview))
4623 (setq buffer-read-only t)
4624 (if (and (boundp 'org-goto-start-pos)
4625 (integer-or-marker-p org-goto-start-pos))
4626 (let ((org-show-hierarchy-above t)
4627 (org-show-siblings t)
4628 (org-show-following-heading t))
4629 (goto-char org-goto-start-pos)
4630 (and (org-invisible-p) (org-show-context)))
4631 (goto-char (point-min)))
4632 (org-beginning-of-line)
4633 (message "Select location and press RET")
4634 (use-local-map org-goto-map)
4635 (recursive-edit)
4637 (kill-buffer "*org-goto*")
4638 (cons org-goto-selected-point org-goto-exit-command)))
4640 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4641 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4642 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4643 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4645 (defun org-goto-local-search-headings (string bound noerror)
4646 "Search and make sure that any matches are in headlines."
4647 (catch 'return
4648 (while (if isearch-forward
4649 (search-forward string bound noerror)
4650 (search-backward string bound noerror))
4651 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4652 (and (member :headline context)
4653 (not (member :tags context))))
4654 (throw 'return (point))))))
4656 (defun org-goto-local-auto-isearch ()
4657 "Start isearch."
4658 (interactive)
4659 (goto-char (point-min))
4660 (let ((keys (this-command-keys)))
4661 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4662 (isearch-mode t)
4663 (isearch-process-search-char (string-to-char keys)))))
4665 (defun org-goto-ret (&optional arg)
4666 "Finish `org-goto' by going to the new location."
4667 (interactive "P")
4668 (setq org-goto-selected-point (point)
4669 org-goto-exit-command 'return)
4670 (throw 'exit nil))
4672 (defun org-goto-left ()
4673 "Finish `org-goto' by going to the new location."
4674 (interactive)
4675 (if (org-on-heading-p)
4676 (progn
4677 (beginning-of-line 1)
4678 (setq org-goto-selected-point (point)
4679 org-goto-exit-command 'left)
4680 (throw 'exit nil))
4681 (error "Not on a heading")))
4683 (defun org-goto-right ()
4684 "Finish `org-goto' by going to the new location."
4685 (interactive)
4686 (if (org-on-heading-p)
4687 (progn
4688 (setq org-goto-selected-point (point)
4689 org-goto-exit-command 'right)
4690 (throw 'exit nil))
4691 (error "Not on a heading")))
4693 (defun org-goto-quit ()
4694 "Finish `org-goto' without cursor motion."
4695 (interactive)
4696 (setq org-goto-selected-point nil)
4697 (setq org-goto-exit-command 'quit)
4698 (throw 'exit nil))
4700 ;;; Indirect buffer display of subtrees
4702 (defvar org-indirect-dedicated-frame nil
4703 "This is the frame being used for indirect tree display.")
4704 (defvar org-last-indirect-buffer nil)
4706 (defun org-tree-to-indirect-buffer (&optional arg)
4707 "Create indirect buffer and narrow it to current subtree.
4708 With numerical prefix ARG, go up to this level and then take that tree.
4709 If ARG is negative, go up that many levels.
4710 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4711 indirect buffer previously made with this command, to avoid proliferation of
4712 indirect buffers. However, when you call the command with a `C-u' prefix, or
4713 when `org-indirect-buffer-display' is `new-frame', the last buffer
4714 is kept so that you can work with several indirect buffers at the same time.
4715 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4716 requests that a new frame be made for the new buffer, so that the dedicated
4717 frame is not changed."
4718 (interactive "P")
4719 (let ((cbuf (current-buffer))
4720 (cwin (selected-window))
4721 (pos (point))
4722 beg end level heading ibuf)
4723 (save-excursion
4724 (org-back-to-heading t)
4725 (when (numberp arg)
4726 (setq level (org-outline-level))
4727 (if (< arg 0) (setq arg (+ level arg)))
4728 (while (> (setq level (org-outline-level)) arg)
4729 (outline-up-heading 1 t)))
4730 (setq beg (point)
4731 heading (org-get-heading))
4732 (org-end-of-subtree t) (setq end (point)))
4733 (if (and (buffer-live-p org-last-indirect-buffer)
4734 (not (eq org-indirect-buffer-display 'new-frame))
4735 (not arg))
4736 (kill-buffer org-last-indirect-buffer))
4737 (setq ibuf (org-get-indirect-buffer cbuf)
4738 org-last-indirect-buffer ibuf)
4739 (cond
4740 ((or (eq org-indirect-buffer-display 'new-frame)
4741 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4742 (select-frame (make-frame))
4743 (delete-other-windows)
4744 (switch-to-buffer ibuf)
4745 (org-set-frame-title heading))
4746 ((eq org-indirect-buffer-display 'dedicated-frame)
4747 (raise-frame
4748 (select-frame (or (and org-indirect-dedicated-frame
4749 (frame-live-p org-indirect-dedicated-frame)
4750 org-indirect-dedicated-frame)
4751 (setq org-indirect-dedicated-frame (make-frame)))))
4752 (delete-other-windows)
4753 (switch-to-buffer ibuf)
4754 (org-set-frame-title (concat "Indirect: " heading)))
4755 ((eq org-indirect-buffer-display 'current-window)
4756 (switch-to-buffer ibuf))
4757 ((eq org-indirect-buffer-display 'other-window)
4758 (pop-to-buffer ibuf))
4759 (t (error "Invalid value.")))
4760 (if (featurep 'xemacs)
4761 (save-excursion (org-mode) (turn-on-font-lock)))
4762 (narrow-to-region beg end)
4763 (show-all)
4764 (goto-char pos)
4765 (and (window-live-p cwin) (select-window cwin))))
4767 (defun org-get-indirect-buffer (&optional buffer)
4768 (setq buffer (or buffer (current-buffer)))
4769 (let ((n 1) (base (buffer-name buffer)) bname)
4770 (while (buffer-live-p
4771 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4772 (setq n (1+ n)))
4773 (condition-case nil
4774 (make-indirect-buffer buffer bname 'clone)
4775 (error (make-indirect-buffer buffer bname)))))
4777 (defun org-set-frame-title (title)
4778 "Set the title of the current frame to the string TITLE."
4779 ;; FIXME: how to name a single frame in XEmacs???
4780 (unless (featurep 'xemacs)
4781 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4783 ;;;; Structure editing
4785 ;;; Inserting headlines
4787 (defun org-insert-heading (&optional force-heading)
4788 "Insert a new heading or item with same depth at point.
4789 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4790 If point is at the beginning of a headline, insert a sibling before the
4791 current headline. If point is not at the beginning, do not split the line,
4792 but create the new headline after the current line."
4793 (interactive "P")
4794 (if (= (buffer-size) 0)
4795 (insert "\n* ")
4796 (when (or force-heading (not (org-insert-item)))
4797 (let* ((head (save-excursion
4798 (condition-case nil
4799 (progn
4800 (org-back-to-heading)
4801 (match-string 0))
4802 (error "*"))))
4803 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4804 pos hide-previous previous-pos)
4805 (cond
4806 ((and (org-on-heading-p) (bolp)
4807 (or (bobp)
4808 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4809 ;; insert before the current line
4810 (open-line (if blank 2 1)))
4811 ((and (bolp)
4812 (or (bobp)
4813 (save-excursion
4814 (backward-char 1) (not (org-invisible-p)))))
4815 ;; insert right here
4816 nil)
4818 ;; somewhere in the line
4819 (save-excursion
4820 (setq previous-pos (point-at-bol))
4821 (end-of-line)
4822 (setq hide-previous (org-invisible-p)))
4823 (and org-insert-heading-respect-content (org-show-subtree))
4824 (let ((split
4825 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4826 (save-excursion
4827 (let ((p (point)))
4828 (goto-char (point-at-bol))
4829 (and (looking-at org-complex-heading-regexp)
4830 (> p (match-beginning 4)))))))
4831 tags pos)
4832 (cond
4833 (org-insert-heading-respect-content
4834 (org-end-of-subtree nil t)
4835 (or (bolp) (newline))
4836 (open-line 1))
4837 ((org-on-heading-p)
4838 (when hide-previous
4839 (show-children)
4840 (org-show-entry))
4841 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4842 (setq tags (and (match-end 2) (match-string 2)))
4843 (and (match-end 1)
4844 (delete-region (match-beginning 1) (match-end 1)))
4845 (setq pos (point-at-bol))
4846 (or split (end-of-line 1))
4847 (delete-horizontal-space)
4848 (newline (if blank 2 1))
4849 (when tags
4850 (save-excursion
4851 (goto-char pos)
4852 (end-of-line 1)
4853 (insert " " tags)
4854 (org-set-tags nil 'align))))
4856 (or split (end-of-line 1))
4857 (newline (if blank 2 1)))))))
4858 (insert head) (just-one-space)
4859 (setq pos (point))
4860 (end-of-line 1)
4861 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4862 (when (and org-insert-heading-respect-content hide-previous)
4863 (save-excursion
4864 (goto-char previous-pos)
4865 (hide-subtree)))
4866 (run-hooks 'org-insert-heading-hook)))))
4868 (defun org-get-heading (&optional no-tags)
4869 "Return the heading of the current entry, without the stars."
4870 (save-excursion
4871 (org-back-to-heading t)
4872 (if (looking-at
4873 (if no-tags
4874 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4875 "\\*+[ \t]+\\([^\r\n]*\\)"))
4876 (match-string 1) "")))
4878 (defun org-insert-heading-after-current ()
4879 "Insert a new heading with same level as current, after current subtree."
4880 (interactive)
4881 (org-back-to-heading)
4882 (org-insert-heading)
4883 (org-move-subtree-down)
4884 (end-of-line 1))
4886 (defun org-insert-heading-respect-content ()
4887 (interactive)
4888 (let ((org-insert-heading-respect-content t))
4889 (org-insert-heading t)))
4891 (defun org-insert-todo-heading-respect-content (&optional force-state)
4892 (interactive "P")
4893 (let ((org-insert-heading-respect-content t))
4894 (org-insert-todo-heading force-state t)))
4896 (defun org-insert-todo-heading (arg &optional force-heading)
4897 "Insert a new heading with the same level and TODO state as current heading.
4898 If the heading has no TODO state, or if the state is DONE, use the first
4899 state (TODO by default). Also with prefix arg, force first state."
4900 (interactive "P")
4901 (when (or force-heading (not (org-insert-item 'checkbox)))
4902 (org-insert-heading force-heading)
4903 (save-excursion
4904 (org-back-to-heading)
4905 (outline-previous-heading)
4906 (looking-at org-todo-line-regexp))
4907 (if (or arg
4908 (not (match-beginning 2))
4909 (member (match-string 2) org-done-keywords))
4910 (insert (car org-todo-keywords-1) " ")
4911 (insert (match-string 2) " "))
4912 (when org-provide-todo-statistics
4913 (org-update-parent-todo-statistics))))
4915 (defun org-insert-subheading (arg)
4916 "Insert a new subheading and demote it.
4917 Works for outline headings and for plain lists alike."
4918 (interactive "P")
4919 (org-insert-heading arg)
4920 (cond
4921 ((org-on-heading-p) (org-do-demote))
4922 ((org-at-item-p) (org-indent-item 1))))
4924 (defun org-insert-todo-subheading (arg)
4925 "Insert a new subheading with TODO keyword or checkbox and demote it.
4926 Works for outline headings and for plain lists alike."
4927 (interactive "P")
4928 (org-insert-todo-heading arg)
4929 (cond
4930 ((org-on-heading-p) (org-do-demote))
4931 ((org-at-item-p) (org-indent-item 1))))
4933 ;;; Promotion and Demotion
4935 (defun org-promote-subtree ()
4936 "Promote the entire subtree.
4937 See also `org-promote'."
4938 (interactive)
4939 (save-excursion
4940 (org-map-tree 'org-promote))
4941 (org-fix-position-after-promote))
4943 (defun org-demote-subtree ()
4944 "Demote the entire subtree. See `org-demote'.
4945 See also `org-promote'."
4946 (interactive)
4947 (save-excursion
4948 (org-map-tree 'org-demote))
4949 (org-fix-position-after-promote))
4952 (defun org-do-promote ()
4953 "Promote the current heading higher up the tree.
4954 If the region is active in `transient-mark-mode', promote all headings
4955 in the region."
4956 (interactive)
4957 (save-excursion
4958 (if (org-region-active-p)
4959 (org-map-region 'org-promote (region-beginning) (region-end))
4960 (org-promote)))
4961 (org-fix-position-after-promote))
4963 (defun org-do-demote ()
4964 "Demote the current heading lower down the tree.
4965 If the region is active in `transient-mark-mode', demote all headings
4966 in the region."
4967 (interactive)
4968 (save-excursion
4969 (if (org-region-active-p)
4970 (org-map-region 'org-demote (region-beginning) (region-end))
4971 (org-demote)))
4972 (org-fix-position-after-promote))
4974 (defun org-fix-position-after-promote ()
4975 "Make sure that after pro/demotion cursor position is right."
4976 (let ((pos (point)))
4977 (when (save-excursion
4978 (beginning-of-line 1)
4979 (looking-at org-todo-line-regexp)
4980 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4981 (cond ((eobp) (insert " "))
4982 ((eolp) (insert " "))
4983 ((equal (char-after) ?\ ) (forward-char 1))))))
4985 (defun org-reduced-level (l)
4986 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4988 (defun org-get-valid-level (level &optional change)
4989 "Rectify a level change under the influence of `org-odd-levels-only'
4990 LEVEL is a current level, CHANGE is by how much the level should be
4991 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4992 even level numbers will become the next higher odd number."
4993 (if org-odd-levels-only
4994 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4995 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4996 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4997 (max 1 (+ level change))))
4999 (if (boundp 'define-obsolete-function-alias)
5000 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5001 (define-obsolete-function-alias 'org-get-legal-level
5002 'org-get-valid-level)
5003 (define-obsolete-function-alias 'org-get-legal-level
5004 'org-get-valid-level "23.1")))
5006 (defun org-promote ()
5007 "Promote the current heading higher up the tree.
5008 If the region is active in `transient-mark-mode', promote all headings
5009 in the region."
5010 (org-back-to-heading t)
5011 (let* ((level (save-match-data (funcall outline-level)))
5012 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5013 (diff (abs (- level (length up-head) -1))))
5014 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5015 (replace-match up-head nil t)
5016 ;; Fixup tag positioning
5017 (and org-auto-align-tags (org-set-tags nil t))
5018 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5020 (defun org-demote ()
5021 "Demote the current heading lower down the tree.
5022 If the region is active in `transient-mark-mode', demote all headings
5023 in the region."
5024 (org-back-to-heading t)
5025 (let* ((level (save-match-data (funcall outline-level)))
5026 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5027 (diff (abs (- level (length down-head) -1))))
5028 (replace-match down-head nil t)
5029 ;; Fixup tag positioning
5030 (and org-auto-align-tags (org-set-tags nil t))
5031 (if org-adapt-indentation (org-fixup-indentation diff))))
5033 (defun org-map-tree (fun)
5034 "Call FUN for every heading underneath the current one."
5035 (org-back-to-heading)
5036 (let ((level (funcall outline-level)))
5037 (save-excursion
5038 (funcall fun)
5039 (while (and (progn
5040 (outline-next-heading)
5041 (> (funcall outline-level) level))
5042 (not (eobp)))
5043 (funcall fun)))))
5045 (defun org-map-region (fun beg end)
5046 "Call FUN for every heading between BEG and END."
5047 (let ((org-ignore-region t))
5048 (save-excursion
5049 (setq end (copy-marker end))
5050 (goto-char beg)
5051 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5052 (< (point) end))
5053 (funcall fun))
5054 (while (and (progn
5055 (outline-next-heading)
5056 (< (point) end))
5057 (not (eobp)))
5058 (funcall fun)))))
5060 (defun org-fixup-indentation (diff)
5061 "Change the indentation in the current entry by DIFF
5062 However, if any line in the current entry has no indentation, or if it
5063 would end up with no indentation after the change, nothing at all is done."
5064 (save-excursion
5065 (let ((end (save-excursion (outline-next-heading)
5066 (point-marker)))
5067 (prohibit (if (> diff 0)
5068 "^\\S-"
5069 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5070 col)
5071 (unless (save-excursion (end-of-line 1)
5072 (re-search-forward prohibit end t))
5073 (while (and (< (point) end)
5074 (re-search-forward "^[ \t]+" end t))
5075 (goto-char (match-end 0))
5076 (setq col (current-column))
5077 (if (< diff 0) (replace-match ""))
5078 (org-indent-to-column (+ diff col))))
5079 (move-marker end nil))))
5081 (defun org-convert-to-odd-levels ()
5082 "Convert an org-mode file with all levels allowed to one with odd levels.
5083 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5084 level 5 etc."
5085 (interactive)
5086 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5087 (let ((org-odd-levels-only nil) n)
5088 (save-excursion
5089 (goto-char (point-min))
5090 (while (re-search-forward "^\\*\\*+ " nil t)
5091 (setq n (- (length (match-string 0)) 2))
5092 (while (>= (setq n (1- n)) 0)
5093 (org-demote))
5094 (end-of-line 1))))))
5097 (defun org-convert-to-oddeven-levels ()
5098 "Convert an org-mode file with only odd levels to one with odd and even levels.
5099 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5100 section with an even level, conversion would destroy the structure of the file. An error
5101 is signaled in this case."
5102 (interactive)
5103 (goto-char (point-min))
5104 ;; First check if there are no even levels
5105 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5106 (org-show-context t)
5107 (error "Not all levels are odd in this file. Conversion not possible."))
5108 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5109 (let ((org-odd-levels-only nil) n)
5110 (save-excursion
5111 (goto-char (point-min))
5112 (while (re-search-forward "^\\*\\*+ " nil t)
5113 (setq n (/ (1- (length (match-string 0))) 2))
5114 (while (>= (setq n (1- n)) 0)
5115 (org-promote))
5116 (end-of-line 1))))))
5118 (defun org-tr-level (n)
5119 "Make N odd if required."
5120 (if org-odd-levels-only (1+ (/ n 2)) n))
5122 ;;; Vertical tree motion, cutting and pasting of subtrees
5124 (defun org-move-subtree-up (&optional arg)
5125 "Move the current subtree up past ARG headlines of the same level."
5126 (interactive "p")
5127 (org-move-subtree-down (- (prefix-numeric-value arg))))
5129 (defun org-move-subtree-down (&optional arg)
5130 "Move the current subtree down past ARG headlines of the same level."
5131 (interactive "p")
5132 (setq arg (prefix-numeric-value arg))
5133 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5134 'outline-get-last-sibling))
5135 (ins-point (make-marker))
5136 (cnt (abs arg))
5137 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5138 ;; Select the tree
5139 (org-back-to-heading)
5140 (setq beg0 (point))
5141 (save-excursion
5142 (setq ne-beg (org-back-over-empty-lines))
5143 (setq beg (point)))
5144 (save-match-data
5145 (save-excursion (outline-end-of-heading)
5146 (setq folded (org-invisible-p)))
5147 (outline-end-of-subtree))
5148 (outline-next-heading)
5149 (setq ne-end (org-back-over-empty-lines))
5150 (setq end (point))
5151 (goto-char beg0)
5152 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5153 ;; include less whitespace
5154 (save-excursion
5155 (goto-char beg)
5156 (forward-line (- ne-beg ne-end))
5157 (setq beg (point))))
5158 ;; Find insertion point, with error handling
5159 (while (> cnt 0)
5160 (or (and (funcall movfunc) (looking-at outline-regexp))
5161 (progn (goto-char beg0)
5162 (error "Cannot move past superior level or buffer limit")))
5163 (setq cnt (1- cnt)))
5164 (if (> arg 0)
5165 ;; Moving forward - still need to move over subtree
5166 (progn (org-end-of-subtree t t)
5167 (save-excursion
5168 (org-back-over-empty-lines)
5169 (or (bolp) (newline)))))
5170 (setq ne-ins (org-back-over-empty-lines))
5171 (move-marker ins-point (point))
5172 (setq txt (buffer-substring beg end))
5173 (org-save-markers-in-region beg end)
5174 (delete-region beg end)
5175 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5176 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5177 (let ((bbb (point)))
5178 (insert-before-markers txt)
5179 (org-reinstall-markers-in-region bbb)
5180 (move-marker ins-point bbb))
5181 (or (bolp) (insert "\n"))
5182 (setq ins-end (point))
5183 (goto-char ins-point)
5184 (org-skip-whitespace)
5185 (when (and (< arg 0)
5186 (org-first-sibling-p)
5187 (> ne-ins ne-beg))
5188 ;; Move whitespace back to beginning
5189 (save-excursion
5190 (goto-char ins-end)
5191 (let ((kill-whole-line t))
5192 (kill-line (- ne-ins ne-beg)) (point)))
5193 (insert (make-string (- ne-ins ne-beg) ?\n)))
5194 (move-marker ins-point nil)
5195 (org-compact-display-after-subtree-move)
5196 (org-show-empty-lines-in-parent)
5197 (unless folded
5198 (org-show-entry)
5199 (show-children)
5200 (org-cycle-hide-drawers 'children))))
5202 (defvar org-subtree-clip ""
5203 "Clipboard for cut and paste of subtrees.
5204 This is actually only a copy of the kill, because we use the normal kill
5205 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5207 (defvar org-subtree-clip-folded nil
5208 "Was the last copied subtree folded?
5209 This is used to fold the tree back after pasting.")
5211 (defun org-cut-subtree (&optional n)
5212 "Cut the current subtree into the clipboard.
5213 With prefix arg N, cut this many sequential subtrees.
5214 This is a short-hand for marking the subtree and then cutting it."
5215 (interactive "p")
5216 (org-copy-subtree n 'cut))
5218 (defun org-copy-subtree (&optional n cut force-store-markers)
5219 "Cut the current subtree into the clipboard.
5220 With prefix arg N, cut this many sequential subtrees.
5221 This is a short-hand for marking the subtree and then copying it.
5222 If CUT is non-nil, actually cut the subtree.
5223 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5224 of some markers in the region, even if CUT is non-nil. This is
5225 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5226 (interactive "p")
5227 (let (beg end folded (beg0 (point)))
5228 (if (interactive-p)
5229 (org-back-to-heading nil) ; take what looks like a subtree
5230 (org-back-to-heading t)) ; take what is really there
5231 (org-back-over-empty-lines)
5232 (setq beg (point))
5233 (skip-chars-forward " \t\r\n")
5234 (save-match-data
5235 (save-excursion (outline-end-of-heading)
5236 (setq folded (org-invisible-p)))
5237 (condition-case nil
5238 (outline-forward-same-level (1- n))
5239 (error nil))
5240 (org-end-of-subtree t t))
5241 (org-back-over-empty-lines)
5242 (setq end (point))
5243 (goto-char beg0)
5244 (when (> end beg)
5245 (setq org-subtree-clip-folded folded)
5246 (when (or cut force-store-markers)
5247 (org-save-markers-in-region beg end))
5248 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5249 (setq org-subtree-clip (current-kill 0))
5250 (message "%s: Subtree(s) with %d characters"
5251 (if cut "Cut" "Copied")
5252 (length org-subtree-clip)))))
5254 (defun org-paste-subtree (&optional level tree for-yank)
5255 "Paste the clipboard as a subtree, with modification of headline level.
5256 The entire subtree is promoted or demoted in order to match a new headline
5257 level.
5259 If the cursor is at the beginning of a headline, the same level as
5260 that headline is used to paste the tree
5262 If not, the new level is derived from the *visible* headings
5263 before and after the insertion point, and taken to be the inferior headline
5264 level of the two. So if the previous visible heading is level 3 and the
5265 next is level 4 (or vice versa), level 4 will be used for insertion.
5266 This makes sure that the subtree remains an independent subtree and does
5267 not swallow low level entries.
5269 You can also force a different level, either by using a numeric prefix
5270 argument, or by inserting the heading marker by hand. For example, if the
5271 cursor is after \"*****\", then the tree will be shifted to level 5.
5273 If optional TREE is given, use this text instead of the kill ring.
5275 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5276 move back over whitespace before inserting, and move point to the end of
5277 the inserted text when done."
5278 (interactive "P")
5279 (unless (org-kill-is-subtree-p tree)
5280 (error "%s"
5281 (substitute-command-keys
5282 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5283 (let* ((visp (not (org-invisible-p)))
5284 (txt (or tree (and kill-ring (current-kill 0))))
5285 (^re (concat "^\\(" outline-regexp "\\)"))
5286 (re (concat "\\(" outline-regexp "\\)"))
5287 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5289 (old-level (if (string-match ^re txt)
5290 (- (match-end 0) (match-beginning 0) 1)
5291 -1))
5292 (force-level (cond (level (prefix-numeric-value level))
5293 ((and (looking-at "[ \t]*$")
5294 (string-match
5295 ^re_ (buffer-substring
5296 (point-at-bol) (point))))
5297 (- (match-end 1) (match-beginning 1)))
5298 ((and (bolp)
5299 (looking-at org-outline-regexp))
5300 (- (match-end 0) (point) 1))
5301 (t nil)))
5302 (previous-level (save-excursion
5303 (condition-case nil
5304 (progn
5305 (outline-previous-visible-heading 1)
5306 (if (looking-at re)
5307 (- (match-end 0) (match-beginning 0) 1)
5309 (error 1))))
5310 (next-level (save-excursion
5311 (condition-case nil
5312 (progn
5313 (or (looking-at outline-regexp)
5314 (outline-next-visible-heading 1))
5315 (if (looking-at re)
5316 (- (match-end 0) (match-beginning 0) 1)
5318 (error 1))))
5319 (new-level (or force-level (max previous-level next-level)))
5320 (shift (if (or (= old-level -1)
5321 (= new-level -1)
5322 (= old-level new-level))
5324 (- new-level old-level)))
5325 (delta (if (> shift 0) -1 1))
5326 (func (if (> shift 0) 'org-demote 'org-promote))
5327 (org-odd-levels-only nil)
5328 beg end newend)
5329 ;; Remove the forced level indicator
5330 (if force-level
5331 (delete-region (point-at-bol) (point)))
5332 ;; Paste
5333 (beginning-of-line 1)
5334 (unless for-yank (org-back-over-empty-lines))
5335 (setq beg (point))
5336 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5337 (insert-before-markers txt)
5338 (unless (string-match "\n\\'" txt) (insert "\n"))
5339 (setq newend (point))
5340 (org-reinstall-markers-in-region beg)
5341 (setq end (point))
5342 (goto-char beg)
5343 (skip-chars-forward " \t\n\r")
5344 (setq beg (point))
5345 (if (and (org-invisible-p) visp)
5346 (save-excursion (outline-show-heading)))
5347 ;; Shift if necessary
5348 (unless (= shift 0)
5349 (save-restriction
5350 (narrow-to-region beg end)
5351 (while (not (= shift 0))
5352 (org-map-region func (point-min) (point-max))
5353 (setq shift (+ delta shift)))
5354 (goto-char (point-min))
5355 (setq newend (point-max))))
5356 (when (or (interactive-p) for-yank)
5357 (message "Clipboard pasted as level %d subtree" new-level))
5358 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5359 kill-ring
5360 (eq org-subtree-clip (current-kill 0))
5361 org-subtree-clip-folded)
5362 ;; The tree was folded before it was killed/copied
5363 (hide-subtree))
5364 (and for-yank (goto-char newend))))
5366 (defun org-kill-is-subtree-p (&optional txt)
5367 "Check if the current kill is an outline subtree, or a set of trees.
5368 Returns nil if kill does not start with a headline, or if the first
5369 headline level is not the largest headline level in the tree.
5370 So this will actually accept several entries of equal levels as well,
5371 which is OK for `org-paste-subtree'.
5372 If optional TXT is given, check this string instead of the current kill."
5373 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5374 (start-level (and kill
5375 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5376 org-outline-regexp "\\)")
5377 kill)
5378 (- (match-end 2) (match-beginning 2) 1)))
5379 (re (concat "^" org-outline-regexp))
5380 (start (1+ (or (match-beginning 2) -1))))
5381 (if (not start-level)
5382 (progn
5383 nil) ;; does not even start with a heading
5384 (catch 'exit
5385 (while (setq start (string-match re kill (1+ start)))
5386 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5387 (throw 'exit nil)))
5388 t))))
5390 (defvar org-markers-to-move nil
5391 "Markers that should be moved with a cut-and-paste operation.
5392 Those markers are stored together with their positions relative to
5393 the start of the region.")
5395 (defun org-save-markers-in-region (beg end)
5396 "Check markers in region.
5397 If these markers are between BEG and END, record their position relative
5398 to BEG, so that after moving the block of text, we can put the markers back
5399 into place.
5400 This function gets called just before an entry or tree gets cut from the
5401 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5402 called immediately, to move the markers with the entries."
5403 (setq org-markers-to-move nil)
5404 (when (featurep 'org-clock)
5405 (org-clock-save-markers-for-cut-and-paste beg end))
5406 (when (featurep 'org-agenda)
5407 (org-agenda-save-markers-for-cut-and-paste beg end)))
5409 (defun org-check-and-save-marker (marker beg end)
5410 "Check if MARKER is between BEG and END.
5411 If yes, remember the marker and the distance to BEG."
5412 (when (and (marker-buffer marker)
5413 (equal (marker-buffer marker) (current-buffer)))
5414 (if (and (>= marker beg) (< marker end))
5415 (push (cons marker (- marker beg)) org-markers-to-move))))
5417 (defun org-reinstall-markers-in-region (beg)
5418 "Move all remembered markers to their position relative to BEG."
5419 (mapc (lambda (x)
5420 (move-marker (car x) (+ beg (cdr x))))
5421 org-markers-to-move)
5422 (setq org-markers-to-move nil))
5424 (defun org-narrow-to-subtree ()
5425 "Narrow buffer to the current subtree."
5426 (interactive)
5427 (save-excursion
5428 (save-match-data
5429 (narrow-to-region
5430 (progn (org-back-to-heading) (point))
5431 (progn (org-end-of-subtree t) (point))))))
5434 ;;; Outline Sorting
5436 (defun org-sort (with-case)
5437 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5438 Optional argument WITH-CASE means sort case-sensitively."
5439 (interactive "P")
5440 (if (org-at-table-p)
5441 (org-call-with-arg 'org-table-sort-lines with-case)
5442 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5444 (defun org-sort-remove-invisible (s)
5445 (remove-text-properties 0 (length s) org-rm-props s)
5446 (while (string-match org-bracket-link-regexp s)
5447 (setq s (replace-match (if (match-end 2)
5448 (match-string 3 s)
5449 (match-string 1 s)) t t s)))
5452 (defvar org-priority-regexp) ; defined later in the file
5454 (defun org-sort-entries-or-items
5455 (&optional with-case sorting-type getkey-func compare-func property)
5456 "Sort entries on a certain level of an outline tree.
5457 If there is an active region, the entries in the region are sorted.
5458 Else, if the cursor is before the first entry, sort the top-level items.
5459 Else, the children of the entry at point are sorted.
5461 Sorting can be alphabetically, numerically, and by date/time as given by
5462 the first time stamp in the entry. The command prompts for the sorting
5463 type unless it has been given to the function through the SORTING-TYPE
5464 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5465 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5466 called with point at the beginning of the record. It must return either
5467 a string or a number that should serve as the sorting key for that record.
5469 Comparing entries ignores case by default. However, with an optional argument
5470 WITH-CASE, the sorting considers case as well."
5471 (interactive "P")
5472 (let ((case-func (if with-case 'identity 'downcase))
5473 start beg end stars re re2
5474 txt what tmp plain-list-p)
5475 ;; Find beginning and end of region to sort
5476 (cond
5477 ((org-region-active-p)
5478 ;; we will sort the region
5479 (setq end (region-end)
5480 what "region")
5481 (goto-char (region-beginning))
5482 (if (not (org-on-heading-p)) (outline-next-heading))
5483 (setq start (point)))
5484 ((org-at-item-p)
5485 ;; we will sort this plain list
5486 (org-beginning-of-item-list) (setq start (point))
5487 (org-end-of-item-list) (setq end (point))
5488 (goto-char start)
5489 (setq plain-list-p t
5490 what "plain list"))
5491 ((or (org-on-heading-p)
5492 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5493 ;; we will sort the children of the current headline
5494 (org-back-to-heading)
5495 (setq start (point)
5496 end (progn (org-end-of-subtree t t)
5497 (org-back-over-empty-lines)
5498 (point))
5499 what "children")
5500 (goto-char start)
5501 (show-subtree)
5502 (outline-next-heading))
5504 ;; we will sort the top-level entries in this file
5505 (goto-char (point-min))
5506 (or (org-on-heading-p) (outline-next-heading))
5507 (setq start (point) end (point-max) what "top-level")
5508 (goto-char start)
5509 (show-all)))
5511 (setq beg (point))
5512 (if (>= beg end) (error "Nothing to sort"))
5514 (unless plain-list-p
5515 (looking-at "\\(\\*+\\)")
5516 (setq stars (match-string 1)
5517 re (concat "^" (regexp-quote stars) " +")
5518 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5519 txt (buffer-substring beg end))
5520 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5521 (if (and (not (equal stars "*")) (string-match re2 txt))
5522 (error "Region to sort contains a level above the first entry")))
5524 (unless sorting-type
5525 (message
5526 (if plain-list-p
5527 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5528 "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:")
5529 what)
5530 (setq sorting-type (read-char-exclusive))
5532 (and (= (downcase sorting-type) ?f)
5533 (setq getkey-func
5534 (org-ido-completing-read "Sort using function: "
5535 obarray 'fboundp t nil nil))
5536 (setq getkey-func (intern getkey-func)))
5538 (and (= (downcase sorting-type) ?r)
5539 (setq property
5540 (org-ido-completing-read "Property: "
5541 (mapcar 'list (org-buffer-property-keys t))
5542 nil t))))
5544 (message "Sorting entries...")
5546 (save-restriction
5547 (narrow-to-region start end)
5549 (let ((dcst (downcase sorting-type))
5550 (now (current-time)))
5551 (sort-subr
5552 (/= dcst sorting-type)
5553 ;; This function moves to the beginning character of the "record" to
5554 ;; be sorted.
5555 (if plain-list-p
5556 (lambda nil
5557 (if (org-at-item-p) t (goto-char (point-max))))
5558 (lambda nil
5559 (if (re-search-forward re nil t)
5560 (goto-char (match-beginning 0))
5561 (goto-char (point-max)))))
5562 ;; This function moves to the last character of the "record" being
5563 ;; sorted.
5564 (if plain-list-p
5565 'org-end-of-item
5566 (lambda nil
5567 (save-match-data
5568 (condition-case nil
5569 (outline-forward-same-level 1)
5570 (error
5571 (goto-char (point-max)))))))
5573 ;; This function returns the value that gets sorted against.
5574 (if plain-list-p
5575 (lambda nil
5576 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5577 (cond
5578 ((= dcst ?n)
5579 (string-to-number (buffer-substring (match-end 0)
5580 (point-at-eol))))
5581 ((= dcst ?a)
5582 (buffer-substring (match-end 0) (point-at-eol)))
5583 ((= dcst ?t)
5584 (if (re-search-forward org-ts-regexp
5585 (point-at-eol) t)
5586 (org-time-string-to-time (match-string 0))
5587 now))
5588 ((= dcst ?f)
5589 (if getkey-func
5590 (progn
5591 (setq tmp (funcall getkey-func))
5592 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5593 tmp)
5594 (error "Invalid key function `%s'" getkey-func)))
5595 (t (error "Invalid sorting type `%c'" sorting-type)))))
5596 (lambda nil
5597 (cond
5598 ((= dcst ?n)
5599 (if (looking-at org-complex-heading-regexp)
5600 (string-to-number (match-string 4))
5601 nil))
5602 ((= dcst ?a)
5603 (if (looking-at org-complex-heading-regexp)
5604 (funcall case-func (match-string 4))
5605 nil))
5606 ((= dcst ?t)
5607 (if (re-search-forward org-ts-regexp
5608 (save-excursion
5609 (forward-line 2)
5610 (point)) t)
5611 (org-time-string-to-time (match-string 0))
5612 now))
5613 ((= dcst ?p)
5614 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5615 (string-to-char (match-string 2))
5616 org-default-priority))
5617 ((= dcst ?r)
5618 (or (org-entry-get nil property) ""))
5619 ((= dcst ?o)
5620 (if (looking-at org-complex-heading-regexp)
5621 (- 9999 (length (member (match-string 2)
5622 org-todo-keywords-1)))))
5623 ((= dcst ?f)
5624 (if getkey-func
5625 (progn
5626 (setq tmp (funcall getkey-func))
5627 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5628 tmp)
5629 (error "Invalid key function `%s'" getkey-func)))
5630 (t (error "Invalid sorting type `%c'" sorting-type)))))
5632 (cond
5633 ((= dcst ?a) 'string<)
5634 ((= dcst ?t) 'time-less-p)
5635 ((= dcst ?f) compare-func)
5636 (t nil)))))
5637 (message "Sorting entries...done")))
5639 (defun org-do-sort (table what &optional with-case sorting-type)
5640 "Sort TABLE of WHAT according to SORTING-TYPE.
5641 The user will be prompted for the SORTING-TYPE if the call to this
5642 function does not specify it. WHAT is only for the prompt, to indicate
5643 what is being sorted. The sorting key will be extracted from
5644 the car of the elements of the table.
5645 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5646 (unless sorting-type
5647 (message
5648 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5649 what)
5650 (setq sorting-type (read-char-exclusive)))
5651 (let ((dcst (downcase sorting-type))
5652 extractfun comparefun)
5653 ;; Define the appropriate functions
5654 (cond
5655 ((= dcst ?n)
5656 (setq extractfun 'string-to-number
5657 comparefun (if (= dcst sorting-type) '< '>)))
5658 ((= dcst ?a)
5659 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5660 (lambda(x) (downcase (org-sort-remove-invisible x))))
5661 comparefun (if (= dcst sorting-type)
5662 'string<
5663 (lambda (a b) (and (not (string< a b))
5664 (not (string= a b)))))))
5665 ((= dcst ?t)
5666 (setq extractfun
5667 (lambda (x)
5668 (if (string-match org-ts-regexp x)
5669 (time-to-seconds
5670 (org-time-string-to-time (match-string 0 x)))
5672 comparefun (if (= dcst sorting-type) '< '>)))
5673 (t (error "Invalid sorting type `%c'" sorting-type)))
5675 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5676 table)
5677 (lambda (a b) (funcall comparefun (car a) (car b))))))
5679 ;;; Editing source examples
5681 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5682 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5683 (defvar org-edit-src-force-single-line nil)
5684 (defvar org-edit-src-from-org-mode nil)
5685 (defvar org-edit-src-picture nil)
5687 (define-minor-mode org-exit-edit-mode
5688 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5690 (defun org-edit-src-code ()
5691 "Edit the source code example at point.
5692 An indirect buffer is created, and that buffer is then narrowed to the
5693 example at point and switched to the correct language mode. When done,
5694 exit by killing the buffer with \\[org-edit-src-exit]."
5695 (interactive)
5696 (let ((line (org-current-line))
5697 (case-fold-search t)
5698 (msg (substitute-command-keys
5699 "Edit, then exit with C-c ' (C-c and single quote)"))
5700 (info (org-edit-src-find-region-and-lang))
5701 (org-mode-p (eq major-mode 'org-mode))
5702 beg end lang lang-f single)
5703 (if (not info)
5705 (setq beg (nth 0 info)
5706 end (nth 1 info)
5707 lang (nth 2 info)
5708 single (nth 3 info)
5709 lang-f (intern (concat lang "-mode")))
5710 (unless (functionp lang-f)
5711 (error "No such language mode: %s" lang-f))
5712 (goto-line line)
5713 (if (get-buffer "*Org Edit Src Example*")
5714 (kill-buffer "*Org Edit Src Example*"))
5715 (switch-to-buffer (make-indirect-buffer (current-buffer)
5716 "*Org Edit Src Example*"))
5717 (narrow-to-region beg end)
5718 (remove-text-properties beg end '(display nil invisible nil
5719 intangible nil))
5720 (let ((org-inhibit-startup t))
5721 (funcall lang-f))
5722 (set (make-local-variable 'org-edit-src-force-single-line) single)
5723 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5724 (when org-mode-p
5725 (goto-char (point-min))
5726 (while (re-search-forward "^," nil t)
5727 (replace-match "")))
5728 (goto-line line)
5729 (org-exit-edit-mode)
5730 (org-set-local 'header-line-format msg)
5731 (message "%s" msg)
5732 t)))
5734 (defun org-edit-fixed-width-region ()
5735 "Edit the fixed-width ascii drawing at point.
5736 This must be a region where each line starts with a colon followed by
5737 a space character.
5738 An indirect buffer is created, and that buffer is then narrowed to the
5739 example at point and switched to artist-mode. When done,
5740 exit by killing the buffer with \\[org-edit-src-exit]."
5741 (interactive)
5742 (let ((line (org-current-line))
5743 (case-fold-search t)
5744 (msg (substitute-command-keys
5745 "Edit, then exit with C-c ' (C-c and single quote)"))
5746 (org-mode-p (eq major-mode 'org-mode))
5747 beg end lang lang-f)
5748 (beginning-of-line 1)
5749 (if (looking-at "[ \t]*[^:\n \t]")
5751 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5752 (setq beg (point) end beg)
5753 (save-excursion
5754 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5755 (setq beg (point-at-bol 2))
5756 (setq beg (point))))
5757 (save-excursion
5758 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5759 (setq end (1- (match-beginning 0)))
5760 (setq end (point))))
5761 (goto-line line))
5762 (if (get-buffer "*Org Edit Picture*")
5763 (kill-buffer "*Org Edit Picture*"))
5764 (switch-to-buffer (make-indirect-buffer (current-buffer)
5765 "*Org Edit Picture*"))
5766 (narrow-to-region beg end)
5767 (remove-text-properties beg end '(display nil invisible nil
5768 intangible nil))
5769 (when (fboundp 'font-lock-unfontify-region)
5770 (font-lock-unfontify-region (point-min) (point-max)))
5771 (cond
5772 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5773 (fundamental-mode)
5774 (artist-mode 1))
5775 (t (funcall org-edit-fixed-width-region-mode)))
5776 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5777 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5778 (set (make-local-variable 'org-edit-src-picture) t)
5779 (goto-char (point-min))
5780 (while (re-search-forward "^[ \t]*: ?" nil t)
5781 (replace-match ""))
5782 (goto-line line)
5783 (org-exit-edit-mode)
5784 (org-set-local 'header-line-format msg)
5785 (message "%s" msg)
5786 t)))
5789 (defun org-edit-src-find-region-and-lang ()
5790 "Find the region and language for a local edit.
5791 Return a list with beginning and end of the region, a string representing
5792 the language, a switch telling of the content should be in a single line."
5793 (let ((re-list
5794 (append
5795 org-edit-src-region-extra
5797 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5798 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5799 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5800 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5801 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5802 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5803 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5804 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5805 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5806 ("^#\\+html:" "\n" "html" single-line)
5807 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5808 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5809 ("^#\\+latex:" "\n" "latex" single-line)
5810 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5811 ("^#\\+ascii:" "\n" "ascii" single-line)
5813 (pos (point))
5814 re re1 re2 single beg end lang)
5815 (catch 'exit
5816 (while (setq entry (pop re-list))
5817 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5818 single (nth 3 entry))
5819 (save-excursion
5820 (if (or (looking-at re1)
5821 (re-search-backward re1 nil t))
5822 (progn
5823 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5824 (if (and (re-search-forward re2 nil t)
5825 (>= (match-end 0) pos))
5826 (throw 'exit (list beg (match-beginning 0) lang single))))
5827 (if (or (looking-at re2)
5828 (re-search-forward re2 nil t))
5829 (progn
5830 (setq end (match-beginning 0))
5831 (if (and (re-search-backward re1 nil t)
5832 (<= (match-beginning 0) pos))
5833 (throw 'exit
5834 (list (match-end 0) end
5835 (org-edit-src-get-lang lang) single)))))))))))
5837 (defun org-edit-src-get-lang (lang)
5838 "Extract the src language."
5839 (let ((m (match-string 0)))
5840 (cond
5841 ((stringp lang) lang)
5842 ((integerp lang) (match-string lang))
5843 ((and (eq lang 'lang)
5844 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5845 (match-string 1 m))
5846 ((and (eq lang 'style)
5847 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5848 (match-string 1 m))
5849 (t "fundamental"))))
5851 (defun org-edit-src-exit ()
5852 "Exit special edit and protect problematic lines."
5853 (interactive)
5854 (unless (buffer-base-buffer (current-buffer))
5855 (error "This is not an indirect buffer, something is wrong..."))
5856 (unless (> (point-min) 1)
5857 (error "This buffer is not narrowed, something is wrong..."))
5858 (goto-char (point-min))
5859 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5860 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5861 (when (org-bound-and-true-p org-edit-src-force-single-line)
5862 (goto-char (point-min))
5863 (while (re-search-forward "\n" nil t)
5864 (replace-match " "))
5865 (goto-char (point-min))
5866 (if (looking-at "\\s-*") (replace-match " "))
5867 (if (re-search-forward "\\s-+\\'" nil t)
5868 (replace-match "")))
5869 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5870 (goto-char (point-min))
5871 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5872 (replace-match ",\\1"))
5873 (when font-lock-mode
5874 (font-lock-unfontify-region (point-min) (point-max)))
5875 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5876 (when (org-bound-and-true-p org-edit-src-picture)
5877 (untabify (point-min) (point-max))
5878 (goto-char (point-min))
5879 (while (re-search-forward "^" nil t)
5880 (replace-match ": "))
5881 (when font-lock-mode
5882 (font-lock-unfontify-region (point-min) (point-max)))
5883 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5884 (kill-buffer (current-buffer))
5885 (and (org-mode-p) (org-restart-font-lock)))
5888 ;;; The orgstruct minor mode
5890 ;; Define a minor mode which can be used in other modes in order to
5891 ;; integrate the org-mode structure editing commands.
5893 ;; This is really a hack, because the org-mode structure commands use
5894 ;; keys which normally belong to the major mode. Here is how it
5895 ;; works: The minor mode defines all the keys necessary to operate the
5896 ;; structure commands, but wraps the commands into a function which
5897 ;; tests if the cursor is currently at a headline or a plain list
5898 ;; item. If that is the case, the structure command is used,
5899 ;; temporarily setting many Org-mode variables like regular
5900 ;; expressions for filling etc. However, when any of those keys is
5901 ;; used at a different location, function uses `key-binding' to look
5902 ;; up if the key has an associated command in another currently active
5903 ;; keymap (minor modes, major mode, global), and executes that
5904 ;; command. There might be problems if any of the keys is otherwise
5905 ;; used as a prefix key.
5907 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5908 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5909 ;; addresses this by checking explicitly for both bindings.
5911 (defvar orgstruct-mode-map (make-sparse-keymap)
5912 "Keymap for the minor `orgstruct-mode'.")
5914 (defvar org-local-vars nil
5915 "List of local variables, for use by `orgstruct-mode'")
5917 ;;;###autoload
5918 (define-minor-mode orgstruct-mode
5919 "Toggle the minor more `orgstruct-mode'.
5920 This mode is for using Org-mode structure commands in other modes.
5921 The following key behave as if Org-mode was active, if the cursor
5922 is on a headline, or on a plain list item (both in the definition
5923 of Org-mode).
5925 M-up Move entry/item up
5926 M-down Move entry/item down
5927 M-left Promote
5928 M-right Demote
5929 M-S-up Move entry/item up
5930 M-S-down Move entry/item down
5931 M-S-left Promote subtree
5932 M-S-right Demote subtree
5933 M-q Fill paragraph and items like in Org-mode
5934 C-c ^ Sort entries
5935 C-c - Cycle list bullet
5936 TAB Cycle item visibility
5937 M-RET Insert new heading/item
5938 S-M-RET Insert new TODO heading / Checkbox item
5939 C-c C-c Set tags / toggle checkbox"
5940 nil " OrgStruct" nil
5941 (org-load-modules-maybe)
5942 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5944 ;;;###autoload
5945 (defun turn-on-orgstruct ()
5946 "Unconditionally turn on `orgstruct-mode'."
5947 (orgstruct-mode 1))
5949 ;;;###autoload
5950 (defun turn-on-orgstruct++ ()
5951 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5952 In addition to setting orgstruct-mode, this also exports all indentation and
5953 autofilling variables from org-mode into the buffer. Note that turning
5954 off orgstruct-mode will *not* remove these additional settings."
5955 (orgstruct-mode 1)
5956 (let (var val)
5957 (mapc
5958 (lambda (x)
5959 (when (string-match
5960 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5961 (symbol-name (car x)))
5962 (setq var (car x) val (nth 1 x))
5963 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5964 org-local-vars)))
5966 (defun orgstruct-error ()
5967 "Error when there is no default binding for a structure key."
5968 (interactive)
5969 (error "This key has no function outside structure elements"))
5971 (defun orgstruct-setup ()
5972 "Setup orgstruct keymaps."
5973 (let ((nfunc 0)
5974 (bindings
5975 (list
5976 '([(meta up)] org-metaup)
5977 '([(meta down)] org-metadown)
5978 '([(meta left)] org-metaleft)
5979 '([(meta right)] org-metaright)
5980 '([(meta shift up)] org-shiftmetaup)
5981 '([(meta shift down)] org-shiftmetadown)
5982 '([(meta shift left)] org-shiftmetaleft)
5983 '([(meta shift right)] org-shiftmetaright)
5984 '([(shift up)] org-shiftup)
5985 '([(shift down)] org-shiftdown)
5986 '([(shift left)] org-shiftleft)
5987 '([(shift right)] org-shiftright)
5988 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5989 '("\M-q" fill-paragraph)
5990 '("\C-c^" org-sort)
5991 '("\C-c-" org-cycle-list-bullet)))
5992 elt key fun cmd)
5993 (while (setq elt (pop bindings))
5994 (setq nfunc (1+ nfunc))
5995 (setq key (org-key (car elt))
5996 fun (nth 1 elt)
5997 cmd (orgstruct-make-binding fun nfunc key))
5998 (org-defkey orgstruct-mode-map key cmd))
6000 ;; Special treatment needed for TAB and RET
6001 (org-defkey orgstruct-mode-map [(tab)]
6002 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6003 (org-defkey orgstruct-mode-map "\C-i"
6004 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6006 (org-defkey orgstruct-mode-map "\M-\C-m"
6007 (orgstruct-make-binding 'org-insert-heading 105
6008 "\M-\C-m" [(meta return)]))
6009 (org-defkey orgstruct-mode-map [(meta return)]
6010 (orgstruct-make-binding 'org-insert-heading 106
6011 [(meta return)] "\M-\C-m"))
6013 (org-defkey orgstruct-mode-map [(shift meta return)]
6014 (orgstruct-make-binding 'org-insert-todo-heading 107
6015 [(meta return)] "\M-\C-m"))
6017 (unless org-local-vars
6018 (setq org-local-vars (org-get-local-variables)))
6022 (defun orgstruct-make-binding (fun n &rest keys)
6023 "Create a function for binding in the structure minor mode.
6024 FUN is the command to call inside a table. N is used to create a unique
6025 command name. KEYS are keys that should be checked in for a command
6026 to execute outside of tables."
6027 (eval
6028 (list 'defun
6029 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6030 '(arg)
6031 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6032 "Outside of structure, run the binding of `"
6033 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6034 "'.")
6035 '(interactive "p")
6036 (list 'if
6037 '(org-context-p 'headline 'item)
6038 (list 'org-run-like-in-org-mode (list 'quote fun))
6039 (list 'let '(orgstruct-mode)
6040 (list 'call-interactively
6041 (append '(or)
6042 (mapcar (lambda (k)
6043 (list 'key-binding k))
6044 keys)
6045 '('orgstruct-error))))))))
6047 (defun org-context-p (&rest contexts)
6048 "Check if local context is any of CONTEXTS.
6049 Possible values in the list of contexts are `table', `headline', and `item'."
6050 (let ((pos (point)))
6051 (goto-char (point-at-bol))
6052 (prog1 (or (and (memq 'table contexts)
6053 (looking-at "[ \t]*|"))
6054 (and (memq 'headline contexts)
6055 ;;????????? (looking-at "\\*+"))
6056 (looking-at outline-regexp))
6057 (and (memq 'item contexts)
6058 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6059 (goto-char pos))))
6061 (defun org-get-local-variables ()
6062 "Return a list of all local variables in an org-mode buffer."
6063 (let (varlist)
6064 (with-current-buffer (get-buffer-create "*Org tmp*")
6065 (erase-buffer)
6066 (org-mode)
6067 (setq varlist (buffer-local-variables)))
6068 (kill-buffer "*Org tmp*")
6069 (delq nil
6070 (mapcar
6071 (lambda (x)
6072 (setq x
6073 (if (symbolp x)
6074 (list x)
6075 (list (car x) (list 'quote (cdr x)))))
6076 (if (string-match
6077 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6078 (symbol-name (car x)))
6079 x nil))
6080 varlist))))
6082 ;;;###autoload
6083 (defun org-run-like-in-org-mode (cmd)
6084 (org-load-modules-maybe)
6085 (unless org-local-vars
6086 (setq org-local-vars (org-get-local-variables)))
6087 (eval (list 'let org-local-vars
6088 (list 'call-interactively (list 'quote cmd)))))
6090 ;;;; Archiving
6092 (defun org-get-category (&optional pos)
6093 "Get the category applying to position POS."
6094 (get-text-property (or pos (point)) 'org-category))
6096 (defun org-refresh-category-properties ()
6097 "Refresh category text properties in the buffer."
6098 (let ((def-cat (cond
6099 ((null org-category)
6100 (if buffer-file-name
6101 (file-name-sans-extension
6102 (file-name-nondirectory buffer-file-name))
6103 "???"))
6104 ((symbolp org-category) (symbol-name org-category))
6105 (t org-category)))
6106 beg end cat pos optionp)
6107 (org-unmodified
6108 (save-excursion
6109 (save-restriction
6110 (widen)
6111 (goto-char (point-min))
6112 (put-text-property (point) (point-max) 'org-category def-cat)
6113 (while (re-search-forward
6114 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6115 (setq pos (match-end 0)
6116 optionp (equal (char-after (match-beginning 0)) ?#)
6117 cat (org-trim (match-string 2)))
6118 (if optionp
6119 (setq beg (point-at-bol) end (point-max))
6120 (org-back-to-heading t)
6121 (setq beg (point) end (org-end-of-subtree t t)))
6122 (put-text-property beg end 'org-category cat)
6123 (goto-char pos)))))))
6126 ;;;; Link Stuff
6128 ;;; Link abbreviations
6130 (defun org-link-expand-abbrev (link)
6131 "Apply replacements as defined in `org-link-abbrev-alist."
6132 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6133 (let* ((key (match-string 1 link))
6134 (as (or (assoc key org-link-abbrev-alist-local)
6135 (assoc key org-link-abbrev-alist)))
6136 (tag (and (match-end 2) (match-string 3 link)))
6137 rpl)
6138 (if (not as)
6139 link
6140 (setq rpl (cdr as))
6141 (cond
6142 ((symbolp rpl) (funcall rpl tag))
6143 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6144 ((string-match "%h" rpl)
6145 (replace-match (url-hexify-string (or tag "")) t t rpl))
6146 (t (concat rpl tag)))))
6147 link))
6149 ;;; Storing and inserting links
6151 (defvar org-insert-link-history nil
6152 "Minibuffer history for links inserted with `org-insert-link'.")
6154 (defvar org-stored-links nil
6155 "Contains the links stored with `org-store-link'.")
6157 (defvar org-store-link-plist nil
6158 "Plist with info about the most recently link created with `org-store-link'.")
6160 (defvar org-link-protocols nil
6161 "Link protocols added to Org-mode using `org-add-link-type'.")
6163 (defvar org-store-link-functions nil
6164 "List of functions that are called to create and store a link.
6165 Each function will be called in turn until one returns a non-nil
6166 value. Each function should check if it is responsible for creating
6167 this link (for example by looking at the major mode).
6168 If not, it must exit and return nil.
6169 If yes, it should return a non-nil value after a calling
6170 `org-store-link-props' with a list of properties and values.
6171 Special properties are:
6173 :type The link prefix. like \"http\". This must be given.
6174 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6175 This is obligatory as well.
6176 :description Optional default description for the second pair
6177 of brackets in an Org-mode link. The user can still change
6178 this when inserting this link into an Org-mode buffer.
6180 In addition to these, any additional properties can be specified
6181 and then used in remember templates.")
6183 (defun org-add-link-type (type &optional follow export)
6184 "Add TYPE to the list of `org-link-types'.
6185 Re-compute all regular expressions depending on `org-link-types'
6187 FOLLOW and EXPORT are two functions.
6189 FOLLOW should take the link path as the single argument and do whatever
6190 is necessary to follow the link, for example find a file or display
6191 a mail message.
6193 EXPORT should format the link path for export to one of the export formats.
6194 It should be a function accepting three arguments:
6196 path the path of the link, the text after the prefix (like \"http:\")
6197 desc the description of the link, if any, nil if there was no description
6198 format the export format, a symbol like `html' or `latex'.
6200 The function may use the FORMAT information to return different values
6201 depending on the format. The return value will be put literally into
6202 the exported file.
6203 Org-mode has a built-in default for exporting links. If you are happy with
6204 this default, there is no need to define an export function for the link
6205 type. For a simple example of an export function, see `org-bbdb.el'."
6206 (add-to-list 'org-link-types type t)
6207 (org-make-link-regexps)
6208 (if (assoc type org-link-protocols)
6209 (setcdr (assoc type org-link-protocols) (list follow export))
6210 (push (list type follow export) org-link-protocols)))
6212 ;;;###autoload
6213 (defun org-store-link (arg)
6214 "\\<org-mode-map>Store an org-link to the current location.
6215 This link is added to `org-stored-links' and can later be inserted
6216 into an org-buffer with \\[org-insert-link].
6218 For some link types, a prefix arg is interpreted:
6219 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6220 For file links, arg negates `org-context-in-file-links'."
6221 (interactive "P")
6222 (org-load-modules-maybe)
6223 (setq org-store-link-plist nil) ; reset
6224 (let (link cpltxt desc description search txt)
6225 (cond
6227 ((run-hook-with-args-until-success 'org-store-link-functions)
6228 (setq link (plist-get org-store-link-plist :link)
6229 desc (or (plist-get org-store-link-plist :description) link)))
6231 ((eq major-mode 'calendar-mode)
6232 (let ((cd (calendar-cursor-to-date)))
6233 (setq link
6234 (format-time-string
6235 (car org-time-stamp-formats)
6236 (apply 'encode-time
6237 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6238 nil nil nil))))
6239 (org-store-link-props :type "calendar" :date cd)))
6241 ((eq major-mode 'w3-mode)
6242 (setq cpltxt (url-view-url t)
6243 link (org-make-link cpltxt))
6244 (org-store-link-props :type "w3" :url (url-view-url t)))
6246 ((eq major-mode 'w3m-mode)
6247 (setq cpltxt (or w3m-current-title w3m-current-url)
6248 link (org-make-link w3m-current-url))
6249 (org-store-link-props :type "w3m" :url (url-view-url t)))
6251 ((setq search (run-hook-with-args-until-success
6252 'org-create-file-search-functions))
6253 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6254 "::" search))
6255 (setq cpltxt (or description link)))
6257 ((eq major-mode 'image-mode)
6258 (setq cpltxt (concat "file:"
6259 (abbreviate-file-name buffer-file-name))
6260 link (org-make-link cpltxt))
6261 (org-store-link-props :type "image" :file buffer-file-name))
6263 ((eq major-mode 'dired-mode)
6264 ;; link to the file in the current line
6265 (setq cpltxt (concat "file:"
6266 (abbreviate-file-name
6267 (expand-file-name
6268 (dired-get-filename nil t))))
6269 link (org-make-link cpltxt)))
6271 ((and buffer-file-name (org-mode-p))
6272 (cond
6273 ((org-in-regexp "<<\\(.*?\\)>>")
6274 (setq cpltxt
6275 (concat "file:"
6276 (abbreviate-file-name buffer-file-name)
6277 "::" (match-string 1))
6278 link (org-make-link cpltxt)))
6279 ((and (featurep 'org-id)
6280 (or (eq org-link-to-org-use-id t)
6281 (and (eq org-link-to-org-use-id 'create-if-interactive)
6282 (interactive-p))
6283 (and org-link-to-org-use-id
6284 (condition-case nil
6285 (org-entry-get nil "ID")
6286 (error nil)))))
6287 ;; We can make a link using the ID.
6288 (setq link (condition-case nil
6289 (prog1 (org-id-store-link)
6290 (setq desc (plist-get org-store-link-plist
6291 :description)))
6292 (error
6293 ;; probably before first headline, link to file only
6294 (concat "file:"
6295 (abbreviate-file-name buffer-file-name))))))
6297 ;; Just link to current headline
6298 (setq cpltxt (concat "file:"
6299 (abbreviate-file-name buffer-file-name)))
6300 ;; Add a context search string
6301 (when (org-xor org-context-in-file-links arg)
6302 (setq txt (cond
6303 ((org-on-heading-p) nil)
6304 ((org-region-active-p)
6305 (buffer-substring (region-beginning) (region-end)))
6306 (t nil)))
6307 (when (or (null txt) (string-match "\\S-" txt))
6308 (setq cpltxt
6309 (concat cpltxt "::"
6310 (condition-case nil
6311 (org-make-org-heading-search-string txt)
6312 (error "")))
6313 desc "NONE")))
6314 (if (string-match "::\\'" cpltxt)
6315 (setq cpltxt (substring cpltxt 0 -2)))
6316 (setq link (org-make-link cpltxt)))))
6318 ((buffer-file-name (buffer-base-buffer))
6319 ;; Just link to this file here.
6320 (setq cpltxt (concat "file:"
6321 (abbreviate-file-name
6322 (buffer-file-name (buffer-base-buffer)))))
6323 ;; Add a context string
6324 (when (org-xor org-context-in-file-links arg)
6325 (setq txt (if (org-region-active-p)
6326 (buffer-substring (region-beginning) (region-end))
6327 (buffer-substring (point-at-bol) (point-at-eol))))
6328 ;; Only use search option if there is some text.
6329 (when (string-match "\\S-" txt)
6330 (setq cpltxt
6331 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6332 desc "NONE")))
6333 (setq link (org-make-link cpltxt)))
6335 ((interactive-p)
6336 (error "Cannot link to a buffer which is not visiting a file"))
6338 (t (setq link nil)))
6340 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6341 (setq link (or link cpltxt)
6342 desc (or desc cpltxt))
6343 (if (equal desc "NONE") (setq desc nil))
6345 (if (and (interactive-p) link)
6346 (progn
6347 (setq org-stored-links
6348 (cons (list link desc) org-stored-links))
6349 (message "Stored: %s" (or desc link)))
6350 (and link (org-make-link-string link desc)))))
6352 (defun org-store-link-props (&rest plist)
6353 "Store link properties, extract names and addresses."
6354 (let (x adr)
6355 (when (setq x (plist-get plist :from))
6356 (setq adr (mail-extract-address-components x))
6357 (setq plist (plist-put plist :fromname (car adr)))
6358 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6359 (when (setq x (plist-get plist :to))
6360 (setq adr (mail-extract-address-components x))
6361 (setq plist (plist-put plist :toname (car adr)))
6362 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6363 (let ((from (plist-get plist :from))
6364 (to (plist-get plist :to)))
6365 (when (and from to org-from-is-user-regexp)
6366 (setq plist
6367 (plist-put plist :fromto
6368 (if (string-match org-from-is-user-regexp from)
6369 (concat "to %t")
6370 (concat "from %f"))))))
6371 (setq org-store-link-plist plist))
6373 (defun org-add-link-props (&rest plist)
6374 "Add these properties to the link property list."
6375 (let (key value)
6376 (while plist
6377 (setq key (pop plist) value (pop plist))
6378 (setq org-store-link-plist
6379 (plist-put org-store-link-plist key value)))))
6381 (defun org-email-link-description (&optional fmt)
6382 "Return the description part of an email link.
6383 This takes information from `org-store-link-plist' and formats it
6384 according to FMT (default from `org-email-link-description-format')."
6385 (setq fmt (or fmt org-email-link-description-format))
6386 (let* ((p org-store-link-plist)
6387 (to (plist-get p :toaddress))
6388 (from (plist-get p :fromaddress))
6389 (table
6390 (list
6391 (cons "%c" (plist-get p :fromto))
6392 (cons "%F" (plist-get p :from))
6393 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6394 (cons "%T" (plist-get p :to))
6395 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6396 (cons "%s" (plist-get p :subject))
6397 (cons "%m" (plist-get p :message-id)))))
6398 (when (string-match "%c" fmt)
6399 ;; Check if the user wrote this message
6400 (if (and org-from-is-user-regexp from to
6401 (save-match-data (string-match org-from-is-user-regexp from)))
6402 (setq fmt (replace-match "to %t" t t fmt))
6403 (setq fmt (replace-match "from %f" t t fmt))))
6404 (org-replace-escapes fmt table)))
6406 (defun org-make-org-heading-search-string (&optional string heading)
6407 "Make search string for STRING or current headline."
6408 (interactive)
6409 (let ((s (or string (org-get-heading))))
6410 (unless (and string (not heading))
6411 ;; We are using a headline, clean up garbage in there.
6412 (if (string-match org-todo-regexp s)
6413 (setq s (replace-match "" t t s)))
6414 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6415 (setq s (replace-match "" t t s)))
6416 (setq s (org-trim s))
6417 (if (string-match (concat "^\\(" org-quote-string "\\|"
6418 org-comment-string "\\)") s)
6419 (setq s (replace-match "" t t s)))
6420 (while (string-match org-ts-regexp s)
6421 (setq s (replace-match "" t t s))))
6422 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6423 (setq s (replace-match " " t t s)))
6424 (or string (setq s (concat "*" s))) ; Add * for headlines
6425 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6427 (defun org-make-link (&rest strings)
6428 "Concatenate STRINGS."
6429 (apply 'concat strings))
6431 (defun org-make-link-string (link &optional description)
6432 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6433 (unless (string-match "\\S-" link)
6434 (error "Empty link"))
6435 (when (stringp description)
6436 ;; Remove brackets from the description, they are fatal.
6437 (while (string-match "\\[" description)
6438 (setq description (replace-match "{" t t description)))
6439 (while (string-match "\\]" description)
6440 (setq description (replace-match "}" t t description))))
6441 (when (equal (org-link-escape link) description)
6442 ;; No description needed, it is identical
6443 (setq description nil))
6444 (when (and (not description)
6445 (not (equal link (org-link-escape link))))
6446 (setq description (org-extract-attributes link)))
6447 (concat "[[" (org-link-escape link) "]"
6448 (if description (concat "[" description "]") "")
6449 "]"))
6451 (defconst org-link-escape-chars
6452 '((?\ . "%20")
6453 (?\[ . "%5B")
6454 (?\] . "%5D")
6455 (?\340 . "%E0") ; `a
6456 (?\342 . "%E2") ; ^a
6457 (?\347 . "%E7") ; ,c
6458 (?\350 . "%E8") ; `e
6459 (?\351 . "%E9") ; 'e
6460 (?\352 . "%EA") ; ^e
6461 (?\356 . "%EE") ; ^i
6462 (?\364 . "%F4") ; ^o
6463 (?\371 . "%F9") ; `u
6464 (?\373 . "%FB") ; ^u
6465 (?\; . "%3B")
6466 (?? . "%3F")
6467 (?= . "%3D")
6468 (?+ . "%2B")
6470 "Association list of escapes for some characters problematic in links.
6471 This is the list that is used for internal purposes.")
6473 (defconst org-link-escape-chars-browser
6474 '((?\ . "%20")) ; 32 for the SPC char
6475 "Association list of escapes for some characters problematic in links.
6476 This is the list that is used before handing over to the browser.")
6478 (defun org-link-escape (text &optional table)
6479 "Escape characters in TEXT that are problematic for links."
6480 (setq table (or table org-link-escape-chars))
6481 (when text
6482 (let ((re (mapconcat (lambda (x) (regexp-quote
6483 (char-to-string (car x))))
6484 table "\\|")))
6485 (while (string-match re text)
6486 (setq text
6487 (replace-match
6488 (cdr (assoc (string-to-char (match-string 0 text))
6489 table))
6490 t t text)))
6491 text)))
6493 (defun org-link-unescape (text &optional table)
6494 "Reverse the action of `org-link-escape'."
6495 (setq table (or table org-link-escape-chars))
6496 (when text
6497 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6498 table "\\|")))
6499 (while (string-match re text)
6500 (setq text
6501 (replace-match
6502 (char-to-string (car (rassoc (match-string 0 text) table)))
6503 t t text)))
6504 text)))
6506 (defun org-xor (a b)
6507 "Exclusive or."
6508 (if a (not b) b))
6510 (defun org-get-header (header)
6511 "Find a header field in the current buffer."
6512 (save-excursion
6513 (goto-char (point-min))
6514 (let ((case-fold-search t) s)
6515 (cond
6516 ((eq header 'from)
6517 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6518 (setq s (match-string 1)))
6519 (while (string-match "\"" s)
6520 (setq s (replace-match "" t t s)))
6521 (if (string-match "[<(].*" s)
6522 (setq s (replace-match "" t t s))))
6523 ((eq header 'message-id)
6524 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6525 (setq s (match-string 1))))
6526 ((eq header 'subject)
6527 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6528 (setq s (match-string 1)))))
6529 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6530 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6531 s)))
6534 (defun org-fixup-message-id-for-http (s)
6535 "Replace special characters in a message id, so it can be used in an http query."
6536 (while (string-match "<" s)
6537 (setq s (replace-match "%3C" t t s)))
6538 (while (string-match ">" s)
6539 (setq s (replace-match "%3E" t t s)))
6540 (while (string-match "@" s)
6541 (setq s (replace-match "%40" t t s)))
6544 ;;;###autoload
6545 (defun org-insert-link-global ()
6546 "Insert a link like Org-mode does.
6547 This command can be called in any mode to insert a link in Org-mode syntax."
6548 (interactive)
6549 (org-load-modules-maybe)
6550 (org-run-like-in-org-mode 'org-insert-link))
6552 (defun org-insert-link (&optional complete-file link-location)
6553 "Insert a link. At the prompt, enter the link.
6555 Completion can be used to insert any of the link protocol prefixes like
6556 http or ftp in use.
6558 The history can be used to select a link previously stored with
6559 `org-store-link'. When the empty string is entered (i.e. if you just
6560 press RET at the prompt), the link defaults to the most recently
6561 stored link. As SPC triggers completion in the minibuffer, you need to
6562 use M-SPC or C-q SPC to force the insertion of a space character.
6564 You will also be prompted for a description, and if one is given, it will
6565 be displayed in the buffer instead of the link.
6567 If there is already a link at point, this command will allow you to edit link
6568 and description parts.
6570 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6571 be selected using completion. The path to the file will be relative to the
6572 current directory if the file is in the current directory or a subdirectory.
6573 Otherwise, the link will be the absolute path as completed in the minibuffer
6574 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6575 option `org-link-file-path-type'.
6577 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6578 the current directory or below.
6580 With three \\[universal-argument] prefixes, negate the meaning of
6581 `org-keep-stored-link-after-insertion'.
6583 If `org-make-link-description-function' is non-nil, this function will be
6584 called with the link target, and the result will be the default
6585 link description.
6587 If the LINK-LOCATION parameter is non-nil, this value will be
6588 used as the link location instead of reading one interactively."
6589 (interactive "P")
6590 (let* ((wcf (current-window-configuration))
6591 (region (if (org-region-active-p)
6592 (buffer-substring (region-beginning) (region-end))))
6593 (remove (and region (list (region-beginning) (region-end))))
6594 (desc region)
6595 tmphist ; byte-compile incorrectly complains about this
6596 (link link-location)
6597 entry file)
6598 (cond
6599 (link-location) ; specified by arg, just use it.
6600 ((org-in-regexp org-bracket-link-regexp 1)
6601 ;; We do have a link at point, and we are going to edit it.
6602 (setq remove (list (match-beginning 0) (match-end 0)))
6603 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6604 (setq link (read-string "Link: "
6605 (org-link-unescape
6606 (org-match-string-no-properties 1)))))
6607 ((or (org-in-regexp org-angle-link-re)
6608 (org-in-regexp org-plain-link-re))
6609 ;; Convert to bracket link
6610 (setq remove (list (match-beginning 0) (match-end 0))
6611 link (read-string "Link: "
6612 (org-remove-angle-brackets (match-string 0)))))
6613 ((member complete-file '((4) (16)))
6614 ;; Completing read for file names.
6615 (setq file (read-file-name "File: "))
6616 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6617 (pwd1 (file-name-as-directory (abbreviate-file-name
6618 (expand-file-name ".")))))
6619 (cond
6620 ((equal complete-file '(16))
6621 (setq link (org-make-link
6622 "file:"
6623 (abbreviate-file-name (expand-file-name file)))))
6624 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6625 (setq link (org-make-link "file:" (match-string 1 file))))
6626 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6627 (expand-file-name file))
6628 (setq link (org-make-link
6629 "file:" (match-string 1 (expand-file-name file)))))
6630 (t (setq link (org-make-link "file:" file))))))
6632 ;; Read link, with completion for stored links.
6633 (with-output-to-temp-buffer "*Org Links*"
6634 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6635 (when org-stored-links
6636 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6637 (princ (mapconcat
6638 (lambda (x)
6639 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6640 (reverse org-stored-links) "\n"))))
6641 (let ((cw (selected-window)))
6642 (select-window (get-buffer-window "*Org Links*"))
6643 (org-fit-window-to-buffer)
6644 (setq truncate-lines t)
6645 (select-window cw))
6646 ;; Fake a link history, containing the stored links.
6647 (setq tmphist (append (mapcar 'car org-stored-links)
6648 org-insert-link-history))
6649 (unwind-protect
6650 (setq link (org-completing-read
6651 "Link: "
6652 (append
6653 (mapcar (lambda (x) (list (concat (car x) ":")))
6654 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6655 (mapcar (lambda (x) (list (concat x ":")))
6656 org-link-types))
6657 nil nil nil
6658 'tmphist
6659 (or (car (car org-stored-links)))))
6660 (set-window-configuration wcf)
6661 (kill-buffer "*Org Links*"))
6662 (setq entry (assoc link org-stored-links))
6663 (or entry (push link org-insert-link-history))
6664 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6665 (not org-keep-stored-link-after-insertion))
6666 (setq org-stored-links (delq (assoc link org-stored-links)
6667 org-stored-links)))
6668 (setq desc (or desc (nth 1 entry)))))
6670 (if (string-match org-plain-link-re link)
6671 ;; URL-like link, normalize the use of angular brackets.
6672 (setq link (org-make-link (org-remove-angle-brackets link))))
6674 ;; Check if we are linking to the current file with a search option
6675 ;; If yes, simplify the link by using only the search option.
6676 (when (and buffer-file-name
6677 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6678 (let* ((path (match-string 1 link))
6679 (case-fold-search nil)
6680 (search (match-string 2 link)))
6681 (save-match-data
6682 (if (equal (file-truename buffer-file-name) (file-truename path))
6683 ;; We are linking to this same file, with a search option
6684 (setq link search)))))
6686 ;; Check if we can/should use a relative path. If yes, simplify the link
6687 (when (string-match "^file:\\(.*\\)" link)
6688 (let* ((path (match-string 1 link))
6689 (origpath path)
6690 (case-fold-search nil))
6691 (cond
6692 ((or (eq org-link-file-path-type 'absolute)
6693 (equal complete-file '(16)))
6694 (setq path (abbreviate-file-name (expand-file-name path))))
6695 ((eq org-link-file-path-type 'noabbrev)
6696 (setq path (expand-file-name path)))
6697 ((eq org-link-file-path-type 'relative)
6698 (setq path (file-relative-name path)))
6700 (save-match-data
6701 (if (string-match (concat "^" (regexp-quote
6702 (file-name-as-directory
6703 (expand-file-name "."))))
6704 (expand-file-name path))
6705 ;; We are linking a file with relative path name.
6706 (setq path (substring (expand-file-name path)
6707 (match-end 0)))
6708 (setq path (abbreviate-file-name (expand-file-name path)))))))
6709 (setq link (concat "file:" path))
6710 (if (equal desc origpath)
6711 (setq desc path))))
6713 (if org-make-link-description-function
6714 (setq desc (funcall org-make-link-description-function link desc)))
6716 (setq desc (read-string "Description: " desc))
6717 (unless (string-match "\\S-" desc) (setq desc nil))
6718 (if remove (apply 'delete-region remove))
6719 (insert (org-make-link-string link desc))))
6721 (defun org-completing-read (&rest args)
6722 "Completing-read with SPACE being a normal character."
6723 (let ((minibuffer-local-completion-map
6724 (copy-keymap minibuffer-local-completion-map)))
6725 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6726 (apply 'org-ido-completing-read args)))
6728 (defun org-ido-completing-read (&rest args)
6729 "Completing-read using `ido-mode' speedups if available"
6730 (if (and org-completion-use-ido
6731 (fboundp 'ido-completing-read)
6732 (boundp 'ido-mode) ido-mode
6733 (listp (second args)))
6734 (apply 'ido-completing-read (concat (car args)) (cdr args))
6735 (apply 'completing-read args)))
6737 (defun org-extract-attributes (s)
6738 "Extract the attributes cookie from a string and set as text property."
6739 (let (a attr (start 0) key value)
6740 (save-match-data
6741 (when (string-match "{{\\([^}]+\\)}}$" s)
6742 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6743 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6744 (setq key (match-string 1 a) value (match-string 2 a)
6745 start (match-end 0)
6746 attr (plist-put attr (intern key) value))))
6747 (org-add-props s nil 'org-attr attr))
6750 (defun org-attributes-to-string (plist)
6751 "Format a property list into an HTML attribute list."
6752 (let ((s "") key value)
6753 (while plist
6754 (setq key (pop plist) value (pop plist))
6755 (and value
6756 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6759 ;;; Opening/following a link
6761 (defvar org-link-search-failed nil)
6763 (defun org-next-link ()
6764 "Move forward to the next link.
6765 If the link is in hidden text, expose it."
6766 (interactive)
6767 (when (and org-link-search-failed (eq this-command last-command))
6768 (goto-char (point-min))
6769 (message "Link search wrapped back to beginning of buffer"))
6770 (setq org-link-search-failed nil)
6771 (let* ((pos (point))
6772 (ct (org-context))
6773 (a (assoc :link ct)))
6774 (if a (goto-char (nth 2 a)))
6775 (if (re-search-forward org-any-link-re nil t)
6776 (progn
6777 (goto-char (match-beginning 0))
6778 (if (org-invisible-p) (org-show-context)))
6779 (goto-char pos)
6780 (setq org-link-search-failed t)
6781 (error "No further link found"))))
6783 (defun org-previous-link ()
6784 "Move backward to the previous link.
6785 If the link is in hidden text, expose it."
6786 (interactive)
6787 (when (and org-link-search-failed (eq this-command last-command))
6788 (goto-char (point-max))
6789 (message "Link search wrapped back to end of buffer"))
6790 (setq org-link-search-failed nil)
6791 (let* ((pos (point))
6792 (ct (org-context))
6793 (a (assoc :link ct)))
6794 (if a (goto-char (nth 1 a)))
6795 (if (re-search-backward org-any-link-re nil t)
6796 (progn
6797 (goto-char (match-beginning 0))
6798 (if (org-invisible-p) (org-show-context)))
6799 (goto-char pos)
6800 (setq org-link-search-failed t)
6801 (error "No further link found"))))
6803 (defun org-translate-link (s)
6804 "Translate a link string if a translation function has been defined."
6805 (if (and org-link-translation-function
6806 (fboundp org-link-translation-function)
6807 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6808 (progn
6809 (setq s (funcall org-link-translation-function
6810 (match-string 1) (match-string 2)))
6811 (concat (car s) ":" (cdr s)))
6814 (defun org-translate-link-from-planner (type path)
6815 "Translate a link from Emacs Planner syntax so that Org can follow it.
6816 This is still an experimental function, your mileage may vary."
6817 (cond
6818 ((member type '("http" "https" "news" "ftp"))
6819 ;; standard Internet links are the same.
6820 nil)
6821 ((and (equal type "irc") (string-match "^//" path))
6822 ;; Planner has two / at the beginning of an irc link, we have 1.
6823 ;; We should have zero, actually....
6824 (setq path (substring path 1)))
6825 ((and (equal type "lisp") (string-match "^/" path))
6826 ;; Planner has a slash, we do not.
6827 (setq type "elisp" path (substring path 1)))
6828 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6829 ;; A typical message link. Planner has the id after the fina slash,
6830 ;; we separate it with a hash mark
6831 (setq path (concat (match-string 1 path) "#"
6832 (org-remove-angle-brackets (match-string 2 path)))))
6834 (cons type path))
6836 (defun org-find-file-at-mouse (ev)
6837 "Open file link or URL at mouse."
6838 (interactive "e")
6839 (mouse-set-point ev)
6840 (org-open-at-point 'in-emacs))
6842 (defun org-open-at-mouse (ev)
6843 "Open file link or URL at mouse."
6844 (interactive "e")
6845 (mouse-set-point ev)
6846 (if (eq major-mode 'org-agenda-mode)
6847 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6848 (org-open-at-point))
6850 (defvar org-window-config-before-follow-link nil
6851 "The window configuration before following a link.
6852 This is saved in case the need arises to restore it.")
6854 (defvar org-open-link-marker (make-marker)
6855 "Marker pointing to the location where `org-open-at-point; was called.")
6857 ;;;###autoload
6858 (defun org-open-at-point-global ()
6859 "Follow a link like Org-mode does.
6860 This command can be called in any mode to follow a link that has
6861 Org-mode syntax."
6862 (interactive)
6863 (org-run-like-in-org-mode 'org-open-at-point))
6865 ;;;###autoload
6866 (defun org-open-link-from-string (s &optional arg)
6867 "Open a link in the string S, as if it was in Org-mode."
6868 (interactive "sLink: \nP")
6869 (with-temp-buffer
6870 (let ((org-inhibit-startup t))
6871 (org-mode)
6872 (insert s)
6873 (goto-char (point-min))
6874 (org-open-at-point arg))))
6876 (defun org-open-at-point (&optional in-emacs)
6877 "Open link at or after point.
6878 If there is no link at point, this function will search forward up to
6879 the end of the current subtree.
6880 Normally, files will be opened by an appropriate application. If the
6881 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6882 With a double prefix argument, try to open outside of Emacs, in the
6883 application the system uses for this file type."
6884 (interactive "P")
6885 (org-load-modules-maybe)
6886 (move-marker org-open-link-marker (point))
6887 (setq org-window-config-before-follow-link (current-window-configuration))
6888 (org-remove-occur-highlights nil nil t)
6889 (if (org-at-timestamp-p t)
6890 (org-follow-timestamp-link)
6891 (let (type path link line search (pos (point)))
6892 (catch 'match
6893 (save-excursion
6894 (skip-chars-forward "^]\n\r")
6895 (when (org-in-regexp org-bracket-link-regexp)
6896 (setq link (org-extract-attributes
6897 (org-link-unescape (org-match-string-no-properties 1))))
6898 (while (string-match " *\n *" link)
6899 (setq link (replace-match " " t t link)))
6900 (setq link (org-link-expand-abbrev link))
6901 (cond
6902 ((or (file-name-absolute-p link)
6903 (string-match "^\\.\\.?/" link))
6904 (setq type "file" path link))
6905 ((string-match org-link-re-with-space3 link)
6906 (setq type (match-string 1 link) path (match-string 2 link)))
6907 (t (setq type "thisfile" path link)))
6908 (throw 'match t)))
6910 (when (get-text-property (point) 'org-linked-text)
6911 (setq type "thisfile"
6912 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6913 (1+ (point)) (point))
6914 path (buffer-substring
6915 (previous-single-property-change pos 'org-linked-text)
6916 (next-single-property-change pos 'org-linked-text)))
6917 (throw 'match t))
6919 (save-excursion
6920 (when (or (org-in-regexp org-angle-link-re)
6921 (org-in-regexp org-plain-link-re))
6922 (setq type (match-string 1) path (match-string 2))
6923 (throw 'match t)))
6924 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6925 (setq type "tree-match"
6926 path (match-string 1))
6927 (throw 'match t))
6928 (save-excursion
6929 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6930 (setq type "tags"
6931 path (match-string 1))
6932 (while (string-match ":" path)
6933 (setq path (replace-match "+" t t path)))
6934 (throw 'match t))))
6935 (unless path
6936 (error "No link found"))
6937 ;; Remove any trailing spaces in path
6938 (if (string-match " +\\'" path)
6939 (setq path (replace-match "" t t path)))
6940 (if (and org-link-translation-function
6941 (fboundp org-link-translation-function))
6942 ;; Check if we need to translate the link
6943 (let ((tmp (funcall org-link-translation-function type path)))
6944 (setq type (car tmp) path (cdr tmp))))
6946 (cond
6948 ((assoc type org-link-protocols)
6949 (funcall (nth 1 (assoc type org-link-protocols)) path))
6951 ((equal type "mailto")
6952 (let ((cmd (car org-link-mailto-program))
6953 (args (cdr org-link-mailto-program)) args1
6954 (address path) (subject "") a)
6955 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6956 (setq address (match-string 1 path)
6957 subject (org-link-escape (match-string 2 path))))
6958 (while args
6959 (cond
6960 ((not (stringp (car args))) (push (pop args) args1))
6961 (t (setq a (pop args))
6962 (if (string-match "%a" a)
6963 (setq a (replace-match address t t a)))
6964 (if (string-match "%s" a)
6965 (setq a (replace-match subject t t a)))
6966 (push a args1))))
6967 (apply cmd (nreverse args1))))
6969 ((member type '("http" "https" "ftp" "news"))
6970 (browse-url (concat type ":" (org-link-escape
6971 path org-link-escape-chars-browser))))
6973 ((member type '("message"))
6974 (browse-url (concat type ":" path)))
6976 ((string= type "tags")
6977 (org-tags-view in-emacs path))
6978 ((string= type "thisfile")
6979 (if in-emacs
6980 (switch-to-buffer-other-window
6981 (org-get-buffer-for-internal-link (current-buffer)))
6982 (org-mark-ring-push))
6983 (let ((cmd `(org-link-search
6984 ,path
6985 ,(cond ((equal in-emacs '(4)) 'occur)
6986 ((equal in-emacs '(16)) 'org-occur)
6987 (t nil))
6988 ,pos)))
6989 (condition-case nil (eval cmd)
6990 (error (progn (widen) (eval cmd))))))
6992 ((string= type "tree-match")
6993 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6995 ((string= type "file")
6996 (if (string-match "::\\([0-9]+\\)\\'" path)
6997 (setq line (string-to-number (match-string 1 path))
6998 path (substring path 0 (match-beginning 0)))
6999 (if (string-match "::\\(.+\\)\\'" path)
7000 (setq search (match-string 1 path)
7001 path (substring path 0 (match-beginning 0)))))
7002 (if (string-match "[*?{]" (file-name-nondirectory path))
7003 (dired path)
7004 (org-open-file path in-emacs line search)))
7006 ((string= type "news")
7007 (require 'org-gnus)
7008 (org-gnus-follow-link path))
7010 ((string= type "shell")
7011 (let ((cmd path))
7012 (if (or (not org-confirm-shell-link-function)
7013 (funcall org-confirm-shell-link-function
7014 (format "Execute \"%s\" in shell? "
7015 (org-add-props cmd nil
7016 'face 'org-warning))))
7017 (progn
7018 (message "Executing %s" cmd)
7019 (shell-command cmd))
7020 (error "Abort"))))
7022 ((string= type "elisp")
7023 (let ((cmd path))
7024 (if (or (not org-confirm-elisp-link-function)
7025 (funcall org-confirm-elisp-link-function
7026 (format "Execute \"%s\" as elisp? "
7027 (org-add-props cmd nil
7028 'face 'org-warning))))
7029 (message "%s => %s" cmd
7030 (if (equal (string-to-char cmd) ?\()
7031 (eval (read cmd))
7032 (call-interactively (read cmd))))
7033 (error "Abort"))))
7036 (browse-url-at-point)))))
7037 (move-marker org-open-link-marker nil)
7038 (run-hook-with-args 'org-follow-link-hook))
7040 ;;;; Time estimates
7042 (defun org-get-effort (&optional pom)
7043 "Get the effort estimate for the current entry."
7044 (org-entry-get pom org-effort-property))
7046 ;;; File search
7048 (defvar org-create-file-search-functions nil
7049 "List of functions to construct the right search string for a file link.
7050 These functions are called in turn with point at the location to
7051 which the link should point.
7053 A function in the hook should first test if it would like to
7054 handle this file type, for example by checking the major-mode or
7055 the file extension. If it decides not to handle this file, it
7056 should just return nil to give other functions a chance. If it
7057 does handle the file, it must return the search string to be used
7058 when following the link. The search string will be part of the
7059 file link, given after a double colon, and `org-open-at-point'
7060 will automatically search for it. If special measures must be
7061 taken to make the search successful, another function should be
7062 added to the companion hook `org-execute-file-search-functions',
7063 which see.
7065 A function in this hook may also use `setq' to set the variable
7066 `description' to provide a suggestion for the descriptive text to
7067 be used for this link when it gets inserted into an Org-mode
7068 buffer with \\[org-insert-link].")
7070 (defvar org-execute-file-search-functions nil
7071 "List of functions to execute a file search triggered by a link.
7073 Functions added to this hook must accept a single argument, the
7074 search string that was part of the file link, the part after the
7075 double colon. The function must first check if it would like to
7076 handle this search, for example by checking the major-mode or the
7077 file extension. If it decides not to handle this search, it
7078 should just return nil to give other functions a chance. If it
7079 does handle the search, it must return a non-nil value to keep
7080 other functions from trying.
7082 Each function can access the current prefix argument through the
7083 variable `current-prefix-argument'. Note that a single prefix is
7084 used to force opening a link in Emacs, so it may be good to only
7085 use a numeric or double prefix to guide the search function.
7087 In case this is needed, a function in this hook can also restore
7088 the window configuration before `org-open-at-point' was called using:
7090 (set-window-configuration org-window-config-before-follow-link)")
7092 (defun org-link-search (s &optional type avoid-pos)
7093 "Search for a link search option.
7094 If S is surrounded by forward slashes, it is interpreted as a
7095 regular expression. In org-mode files, this will create an `org-occur'
7096 sparse tree. In ordinary files, `occur' will be used to list matches.
7097 If the current buffer is in `dired-mode', grep will be used to search
7098 in all files. If AVOID-POS is given, ignore matches near that position."
7099 (let ((case-fold-search t)
7100 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7101 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7102 (append '(("") (" ") ("\t") ("\n"))
7103 org-emphasis-alist)
7104 "\\|") "\\)"))
7105 (pos (point))
7106 (pre nil) (post nil)
7107 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7108 (cond
7109 ;; First check if there are any special
7110 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7111 ;; Now try the builtin stuff
7112 ((save-excursion
7113 (goto-char (point-min))
7114 (and
7115 (re-search-forward
7116 (concat "<<" (regexp-quote s0) ">>") nil t)
7117 (setq type 'dedicated
7118 pos (match-beginning 0))))
7119 ;; There is an exact target for this
7120 (goto-char pos))
7121 ((string-match "^/\\(.*\\)/$" s)
7122 ;; A regular expression
7123 (cond
7124 ((org-mode-p)
7125 (org-occur (match-string 1 s)))
7126 ;;((eq major-mode 'dired-mode)
7127 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7128 (t (org-do-occur (match-string 1 s)))))
7130 ;; A normal search strings
7131 (when (equal (string-to-char s) ?*)
7132 ;; Anchor on headlines, post may include tags.
7133 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7134 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7135 s (substring s 1)))
7136 (remove-text-properties
7137 0 (length s)
7138 '(face nil mouse-face nil keymap nil fontified nil) s)
7139 ;; Make a series of regular expressions to find a match
7140 (setq words (org-split-string s "[ \n\r\t]+")
7142 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7143 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7144 "\\)" markers)
7145 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7146 re2a (concat "[ \t\r\n]" re2a_)
7147 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7148 re4 (concat "[^a-zA-Z_]" re4_)
7150 re1 (concat pre re2 post)
7151 re3 (concat pre (if pre re4_ re4) post)
7152 re5 (concat pre ".*" re4)
7153 re2 (concat pre re2)
7154 re2a (concat pre (if pre re2a_ re2a))
7155 re4 (concat pre (if pre re4_ re4))
7156 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7157 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7158 re5 "\\)"
7160 (cond
7161 ((eq type 'org-occur) (org-occur reall))
7162 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7163 (t (goto-char (point-min))
7164 (setq type 'fuzzy)
7165 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7166 (org-search-not-self 1 re1 nil t)
7167 (org-search-not-self 1 re2 nil t)
7168 (org-search-not-self 1 re2a nil t)
7169 (org-search-not-self 1 re3 nil t)
7170 (org-search-not-self 1 re4 nil t)
7171 (org-search-not-self 1 re5 nil t)
7173 (goto-char (match-beginning 1))
7174 (goto-char pos)
7175 (error "No match")))))
7177 ;; Normal string-search
7178 (goto-char (point-min))
7179 (if (search-forward s nil t)
7180 (goto-char (match-beginning 0))
7181 (error "No match"))))
7182 (and (org-mode-p) (org-show-context 'link-search))
7183 type))
7185 (defun org-search-not-self (group &rest args)
7186 "Execute `re-search-forward', but only accept matches that do not
7187 enclose the position of `org-open-link-marker'."
7188 (let ((m org-open-link-marker))
7189 (catch 'exit
7190 (while (apply 're-search-forward args)
7191 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7192 (goto-char (match-end group))
7193 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7194 (> (match-beginning 0) (marker-position m))
7195 (< (match-end 0) (marker-position m)))
7196 (save-match-data
7197 (or (not (org-in-regexp
7198 org-bracket-link-analytic-regexp 1))
7199 (not (match-end 4)) ; no description
7200 (and (<= (match-beginning 4) (point))
7201 (>= (match-end 4) (point))))))
7202 (throw 'exit (point))))))))
7204 (defun org-get-buffer-for-internal-link (buffer)
7205 "Return a buffer to be used for displaying the link target of internal links."
7206 (cond
7207 ((not org-display-internal-link-with-indirect-buffer)
7208 buffer)
7209 ((string-match "(Clone)$" (buffer-name buffer))
7210 (message "Buffer is already a clone, not making another one")
7211 ;; we also do not modify visibility in this case
7212 buffer)
7213 (t ; make a new indirect buffer for displaying the link
7214 (let* ((bn (buffer-name buffer))
7215 (ibn (concat bn "(Clone)"))
7216 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7217 (with-current-buffer ib (org-overview))
7218 ib))))
7220 (defun org-do-occur (regexp &optional cleanup)
7221 "Call the Emacs command `occur'.
7222 If CLEANUP is non-nil, remove the printout of the regular expression
7223 in the *Occur* buffer. This is useful if the regex is long and not useful
7224 to read."
7225 (occur regexp)
7226 (when cleanup
7227 (let ((cwin (selected-window)) win beg end)
7228 (when (setq win (get-buffer-window "*Occur*"))
7229 (select-window win))
7230 (goto-char (point-min))
7231 (when (re-search-forward "match[a-z]+" nil t)
7232 (setq beg (match-end 0))
7233 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7234 (setq end (1- (match-beginning 0)))))
7235 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7236 (goto-char (point-min))
7237 (select-window cwin))))
7239 ;;; The mark ring for links jumps
7241 (defvar org-mark-ring nil
7242 "Mark ring for positions before jumps in Org-mode.")
7243 (defvar org-mark-ring-last-goto nil
7244 "Last position in the mark ring used to go back.")
7245 ;; Fill and close the ring
7246 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7247 (loop for i from 1 to org-mark-ring-length do
7248 (push (make-marker) org-mark-ring))
7249 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7250 org-mark-ring)
7252 (defun org-mark-ring-push (&optional pos buffer)
7253 "Put the current position or POS into the mark ring and rotate it."
7254 (interactive)
7255 (setq pos (or pos (point)))
7256 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7257 (move-marker (car org-mark-ring)
7258 (or pos (point))
7259 (or buffer (current-buffer)))
7260 (message "%s"
7261 (substitute-command-keys
7262 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7264 (defun org-mark-ring-goto (&optional n)
7265 "Jump to the previous position in the mark ring.
7266 With prefix arg N, jump back that many stored positions. When
7267 called several times in succession, walk through the entire ring.
7268 Org-mode commands jumping to a different position in the current file,
7269 or to another Org-mode file, automatically push the old position
7270 onto the ring."
7271 (interactive "p")
7272 (let (p m)
7273 (if (eq last-command this-command)
7274 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7275 (setq p org-mark-ring))
7276 (setq org-mark-ring-last-goto p)
7277 (setq m (car p))
7278 (switch-to-buffer (marker-buffer m))
7279 (goto-char m)
7280 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7282 (defun org-remove-angle-brackets (s)
7283 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7284 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7286 (defun org-add-angle-brackets (s)
7287 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7288 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7290 (defun org-remove-double-quotes (s)
7291 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7292 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7295 ;;; Following specific links
7297 (defun org-follow-timestamp-link ()
7298 (cond
7299 ((org-at-date-range-p t)
7300 (let ((org-agenda-start-on-weekday)
7301 (t1 (match-string 1))
7302 (t2 (match-string 2)))
7303 (setq t1 (time-to-days (org-time-string-to-time t1))
7304 t2 (time-to-days (org-time-string-to-time t2)))
7305 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7306 ((org-at-timestamp-p t)
7307 (org-agenda-list nil (time-to-days (org-time-string-to-time
7308 (substring (match-string 1) 0 10)))
7310 (t (error "This should not happen"))))
7313 ;;; Following file links
7314 (defvar org-wait nil)
7315 (defun org-open-file (path &optional in-emacs line search)
7316 "Open the file at PATH.
7317 First, this expands any special file name abbreviations. Then the
7318 configuration variable `org-file-apps' is checked if it contains an
7319 entry for this file type, and if yes, the corresponding command is launched.
7321 If no application is found, Emacs simply visits the file.
7323 With optional prefix argument IN-EMACS, Emacs will visit the file.
7324 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7325 and o use an external application to visit the file.
7327 Optional LINE specifies a line to go to, optional SEARCH a string to
7328 search for. If LINE or SEARCH is given, the file will always be
7329 opened in Emacs.
7330 If the file does not exist, an error is thrown."
7331 (setq in-emacs (or in-emacs line search))
7332 (let* ((file (if (equal path "")
7333 buffer-file-name
7334 (substitute-in-file-name (expand-file-name path))))
7335 (apps (append org-file-apps (org-default-apps)))
7336 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7337 (dirp (if remp nil (file-directory-p file)))
7338 (file (if (and dirp org-open-directory-means-index-dot-org)
7339 (concat (file-name-as-directory file) "index.org")
7340 file))
7341 (a-m-a-p (assq 'auto-mode apps))
7342 (dfile (downcase file))
7343 (old-buffer (current-buffer))
7344 (old-pos (point))
7345 (old-mode major-mode)
7346 ext cmd)
7347 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7348 (setq ext (match-string 1 dfile))
7349 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7350 (setq ext (match-string 1 dfile))))
7351 (cond
7352 ((equal in-emacs '(16))
7353 (setq cmd (cdr (assoc 'system apps))))
7354 (in-emacs (setq cmd 'emacs))
7356 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7357 (and dirp (cdr (assoc 'directory apps)))
7358 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7359 'string-match)
7360 (cdr (assoc ext apps))
7361 (cdr (assoc t apps))))))
7362 (when (eq cmd 'system)
7363 (setq cmd (cdr (assoc 'system apps))))
7364 (when (eq cmd 'default)
7365 (setq cmd (cdr (assoc t apps))))
7366 (when (eq cmd 'mailcap)
7367 (require 'mailcap)
7368 (mailcap-parse-mailcaps)
7369 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7370 (command (mailcap-mime-info mime-type)))
7371 (if (stringp command)
7372 (setq cmd command)
7373 (setq cmd 'emacs))))
7374 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7375 (not (file-exists-p file))
7376 (not org-open-non-existing-files))
7377 (error "No such file: %s" file))
7378 (cond
7379 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7380 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7381 (while (string-match "['\"]%s['\"]" cmd)
7382 (setq cmd (replace-match "%s" t t cmd)))
7383 (while (string-match "%s" cmd)
7384 (setq cmd (replace-match
7385 (save-match-data
7386 (shell-quote-argument
7387 (convert-standard-filename file)))
7388 t t cmd)))
7389 (save-window-excursion
7390 (start-process-shell-command cmd nil cmd)
7391 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7393 ((or (stringp cmd)
7394 (eq cmd 'emacs))
7395 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7396 (widen)
7397 (if line (goto-line line)
7398 (if search (org-link-search search))))
7399 ((consp cmd)
7400 (let ((file (convert-standard-filename file)))
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 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7418 "Convert extensions to regular expressions in the cars of LIST.
7419 Also, weed out any non-string entries, because the return value is used
7420 only for regexp matching.
7421 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7422 point to the symbol `emacs', indicating that the file should
7423 be opened in Emacs."
7424 (append
7425 (delq nil
7426 (mapcar (lambda (x)
7427 (if (not (stringp (car x)))
7429 (if (string-match "\\W" (car x))
7431 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7432 list))
7433 (if add-auto-mode
7434 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7436 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7437 (defun org-file-remote-p (file)
7438 "Test whether FILE specifies a location on a remote system.
7439 Return non-nil if the location is indeed remote.
7441 For example, the filename \"/user@host:/foo\" specifies a location
7442 on the system \"/user@host:\"."
7443 (cond ((fboundp 'file-remote-p)
7444 (file-remote-p file))
7445 ((fboundp 'tramp-handle-file-remote-p)
7446 (tramp-handle-file-remote-p file))
7447 ((and (boundp 'ange-ftp-name-format)
7448 (string-match (car ange-ftp-name-format) file))
7450 (t nil)))
7453 ;;;; Refiling
7455 (defun org-get-org-file ()
7456 "Read a filename, with default directory `org-directory'."
7457 (let ((default (or org-default-notes-file remember-data-file)))
7458 (read-file-name (format "File name [%s]: " default)
7459 (file-name-as-directory org-directory)
7460 default)))
7462 (defun org-notes-order-reversed-p ()
7463 "Check if the current file should receive notes in reversed order."
7464 (cond
7465 ((not org-reverse-note-order) nil)
7466 ((eq t org-reverse-note-order) t)
7467 ((not (listp org-reverse-note-order)) nil)
7468 (t (catch 'exit
7469 (let ((all org-reverse-note-order)
7470 entry)
7471 (while (setq entry (pop all))
7472 (if (string-match (car entry) buffer-file-name)
7473 (throw 'exit (cdr entry))))
7474 nil)))))
7476 (defvar org-refile-target-table nil
7477 "The list of refile targets, created by `org-refile'.")
7479 (defvar org-agenda-new-buffers nil
7480 "Buffers created to visit agenda files.")
7482 (defun org-get-refile-targets (&optional default-buffer)
7483 "Produce a table with refile targets."
7484 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7485 targets txt re files f desc descre fast-path-p level)
7486 (message "Getting targets...")
7487 (with-current-buffer (or default-buffer (current-buffer))
7488 (while (setq entry (pop entries))
7489 (setq files (car entry) desc (cdr entry))
7490 (setq fast-path-p nil)
7491 (cond
7492 ((null files) (setq files (list (current-buffer))))
7493 ((eq files 'org-agenda-files)
7494 (setq files (org-agenda-files 'unrestricted)))
7495 ((and (symbolp files) (fboundp files))
7496 (setq files (funcall files)))
7497 ((and (symbolp files) (boundp files))
7498 (setq files (symbol-value files))))
7499 (if (stringp files) (setq files (list files)))
7500 (cond
7501 ((eq (car desc) :tag)
7502 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7503 ((eq (car desc) :todo)
7504 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7505 ((eq (car desc) :regexp)
7506 (setq descre (cdr desc)))
7507 ((eq (car desc) :level)
7508 (setq descre (concat "^\\*\\{" (number-to-string
7509 (if org-odd-levels-only
7510 (1- (* 2 (cdr desc)))
7511 (cdr desc)))
7512 "\\}[ \t]")))
7513 ((eq (car desc) :maxlevel)
7514 (setq fast-path-p t)
7515 (setq descre (concat "^\\*\\{1," (number-to-string
7516 (if org-odd-levels-only
7517 (1- (* 2 (cdr desc)))
7518 (cdr desc)))
7519 "\\}[ \t]")))
7520 (t (error "Bad refiling target description %s" desc)))
7521 (while (setq f (pop files))
7522 (save-excursion
7523 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7524 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7525 (setq f (expand-file-name f))
7526 (save-excursion
7527 (save-restriction
7528 (widen)
7529 (goto-char (point-min))
7530 (while (re-search-forward descre nil t)
7531 (goto-char (point-at-bol))
7532 (when (looking-at org-complex-heading-regexp)
7533 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7534 txt (org-link-display-format (match-string 4))
7535 re (concat "^" (regexp-quote
7536 (buffer-substring (match-beginning 1)
7537 (match-end 4)))))
7538 (if (match-end 5) (setq re (concat re "[ \t]+"
7539 (regexp-quote
7540 (match-string 5)))))
7541 (setq re (concat re "[ \t]*$"))
7542 (when org-refile-use-outline-path
7543 (setq txt (mapconcat 'org-protect-slash
7544 (append
7545 (if (eq org-refile-use-outline-path 'file)
7546 (list (file-name-nondirectory
7547 (buffer-file-name (buffer-base-buffer))))
7548 (if (eq org-refile-use-outline-path 'full-file-path)
7549 (list (buffer-file-name (buffer-base-buffer)))))
7550 (org-get-outline-path fast-path-p level txt)
7551 (list txt))
7552 "/")))
7553 (push (list txt f re (point)) targets))
7554 (goto-char (point-at-eol))))))))
7555 (message "Getting targets...done")
7556 (nreverse targets))))
7558 (defun org-protect-slash (s)
7559 (while (string-match "/" s)
7560 (setq s (replace-match "\\" t t s)))
7563 (defvar org-olpa (make-vector 20 nil))
7565 (defun org-get-outline-path (&optional fastp level heading)
7566 "Return the outline path to the current entry, as a list."
7567 (if fastp
7568 (progn
7569 (if (> level 19)
7570 (error "Outline path failure, more than 19 levels."))
7571 (loop for i from level upto 19 do
7572 (aset org-olpa i nil))
7573 (prog1
7574 (delq nil (append org-olpa nil))
7575 (aset org-olpa level heading)))
7576 (let (rtn)
7577 (save-excursion
7578 (while (org-up-heading-safe)
7579 (when (looking-at org-complex-heading-regexp)
7580 (push (org-match-string-no-properties 4) rtn)))
7581 rtn))))
7583 (defvar org-refile-history nil
7584 "History for refiling operations.")
7586 (defun org-refile (&optional goto default-buffer)
7587 "Move the entry at point to another heading.
7588 The list of target headings is compiled using the information in
7589 `org-refile-targets', which see. This list is created before each use
7590 and will therefore always be up-to-date.
7592 At the target location, the entry is filed as a subitem of the target heading.
7593 Depending on `org-reverse-note-order', the new subitem will either be the
7594 first or the last subitem.
7596 If there is an active region, all entries in that region will be moved.
7597 However, the region must fulfil the requirement that the first heading
7598 is the first one sets the top-level of the moved text - at most siblings
7599 below it are allowed.
7601 With prefix arg GOTO, the command will only visit the target location,
7602 not actually move anything.
7603 With a double prefix `C-u C-u', go to the location where the last refiling
7604 operation has put the subtree."
7605 (interactive "P")
7606 (let* ((cbuf (current-buffer))
7607 (regionp (org-region-active-p))
7608 (region-start (and regionp (region-beginning)))
7609 (region-end (and regionp (region-end)))
7610 (region-length (and regionp (- region-end region-start)))
7611 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7612 pos it nbuf file re level reversed)
7613 (when regionp (goto-char region-start)
7614 (unless (org-kill-is-subtree-p
7615 (buffer-substring region-start region-end))
7616 (error "The region is not a (sequence of) subtree(s)")))
7617 (if (equal goto '(16))
7618 (org-refile-goto-last-stored)
7619 (when (setq it (org-refile-get-location
7620 (if goto "Goto: " "Refile to: ") default-buffer))
7621 (setq file (nth 1 it)
7622 re (nth 2 it)
7623 pos (nth 3 it))
7624 (if (and (equal (buffer-file-name) file)
7625 (if regionp
7626 (and (>= pos region-start)
7627 (<= pos region-end))
7628 (and (>= pos (point))
7629 (< pos (save-excursion
7630 (org-end-of-subtree t t))))))
7631 (error "Cannot refile to position inside the tree or region"))
7633 (setq nbuf (or (find-buffer-visiting file)
7634 (find-file-noselect file)))
7635 (if goto
7636 (progn
7637 (switch-to-buffer nbuf)
7638 (goto-char pos)
7639 (org-show-context 'org-goto))
7640 (if regionp
7641 (progn
7642 (kill-new (buffer-substring region-start region-end))
7643 (org-save-markers-in-region region-start region-end))
7644 (org-copy-subtree 1 nil t))
7645 (save-excursion
7646 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7647 (find-file-noselect file))))
7648 (setq reversed (org-notes-order-reversed-p))
7649 (save-excursion
7650 (save-restriction
7651 (widen)
7652 (goto-char pos)
7653 (looking-at outline-regexp)
7654 (setq level (org-get-valid-level (funcall outline-level) 1))
7655 (goto-char
7656 (if reversed
7657 (or (outline-next-heading) (point-max))
7658 (or (save-excursion (outline-get-next-sibling))
7659 (org-end-of-subtree t t)
7660 (point-max))))
7661 (if (not (bolp)) (newline))
7662 (bookmark-set "org-refile-last-stored")
7663 (org-paste-subtree level))))
7664 (if regionp
7665 (delete-region (point) (+ (point) region-length))
7666 (org-cut-subtree))
7667 (setq org-markers-to-move nil)
7668 (message "Refiled to \"%s\"" (car it)))))))
7670 (defun org-refile-goto-last-stored ()
7671 "Go to the location where the last refile was stored."
7672 (interactive)
7673 (bookmark-jump "org-refile-last-stored")
7674 (message "This is the location of the last refile"))
7676 (defun org-refile-get-location (&optional prompt default-buffer)
7677 "Prompt the user for a refile location, using PROMPT."
7678 (let ((org-refile-targets org-refile-targets)
7679 (org-refile-use-outline-path org-refile-use-outline-path))
7680 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7681 (unless org-refile-target-table
7682 (error "No refile targets"))
7683 (let* ((cbuf (current-buffer))
7684 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7685 (cfunc (if (and org-refile-use-outline-path
7686 org-outline-path-complete-in-steps)
7687 'org-olpath-completing-read
7688 'org-ido-completing-read))
7689 (extra (if org-refile-use-outline-path "/" ""))
7690 (filename (and cfn (expand-file-name cfn)))
7691 (tbl (mapcar
7692 (lambda (x)
7693 (if (not (equal filename (nth 1 x)))
7694 (cons (concat (car x) extra " ("
7695 (file-name-nondirectory (nth 1 x)) ")")
7696 (cdr x))
7697 (cons (concat (car x) extra) (cdr x))))
7698 org-refile-target-table))
7699 (completion-ignore-case t))
7700 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7701 tbl)))
7703 (defun org-olpath-completing-read (prompt collection &rest args)
7704 "Read an outline path like a file name."
7705 (let ((thetable collection))
7706 (apply
7707 'org-ido-completing-read prompt
7708 (lambda (string predicate &optional flag)
7709 (let (rtn r s f (l (length string)))
7710 (cond
7711 ((eq flag nil)
7712 ;; try completion
7713 (try-completion string thetable))
7714 ((eq flag t)
7715 ;; all-completions
7716 (setq rtn (all-completions string thetable predicate))
7717 (mapcar
7718 (lambda (x)
7719 (setq r (substring x l))
7720 (if (string-match " ([^)]*)$" x)
7721 (setq f (match-string 0 x))
7722 (setq f ""))
7723 (if (string-match "/" r)
7724 (concat string (substring r 0 (match-end 0)) f)
7726 rtn))
7727 ((eq flag 'lambda)
7728 ;; exact match?
7729 (assoc string thetable)))
7731 args)))
7733 ;;;; Dynamic blocks
7735 (defun org-find-dblock (name)
7736 "Find the first dynamic block with name NAME in the buffer.
7737 If not found, stay at current position and return nil."
7738 (let (pos)
7739 (save-excursion
7740 (goto-char (point-min))
7741 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7742 nil t)
7743 (match-beginning 0))))
7744 (if pos (goto-char pos))
7745 pos))
7747 (defconst org-dblock-start-re
7748 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7749 "Matches the startline of a dynamic block, with parameters.")
7751 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7752 "Matches the end of a dynamic block.")
7754 (defun org-create-dblock (plist)
7755 "Create a dynamic block section, with parameters taken from PLIST.
7756 PLIST must contain a :name entry which is used as name of the block."
7757 (unless (bolp) (newline))
7758 (let ((name (plist-get plist :name)))
7759 (insert "#+BEGIN: " name)
7760 (while plist
7761 (if (eq (car plist) :name)
7762 (setq plist (cddr plist))
7763 (insert " " (prin1-to-string (pop plist)))))
7764 (insert "\n\n#+END:\n")
7765 (beginning-of-line -2)))
7767 (defun org-prepare-dblock ()
7768 "Prepare dynamic block for refresh.
7769 This empties the block, puts the cursor at the insert position and returns
7770 the property list including an extra property :name with the block name."
7771 (unless (looking-at org-dblock-start-re)
7772 (error "Not at a dynamic block"))
7773 (let* ((begdel (1+ (match-end 0)))
7774 (name (org-no-properties (match-string 1)))
7775 (params (append (list :name name)
7776 (read (concat "(" (match-string 3) ")")))))
7777 (unless (re-search-forward org-dblock-end-re nil t)
7778 (error "Dynamic block not terminated"))
7779 (setq params
7780 (append params
7781 (list :content (buffer-substring
7782 begdel (match-beginning 0)))))
7783 (delete-region begdel (match-beginning 0))
7784 (goto-char begdel)
7785 (open-line 1)
7786 params))
7788 (defun org-map-dblocks (&optional command)
7789 "Apply COMMAND to all dynamic blocks in the current buffer.
7790 If COMMAND is not given, use `org-update-dblock'."
7791 (let ((cmd (or command 'org-update-dblock))
7792 pos)
7793 (save-excursion
7794 (goto-char (point-min))
7795 (while (re-search-forward org-dblock-start-re nil t)
7796 (goto-char (setq pos (match-beginning 0)))
7797 (condition-case nil
7798 (funcall cmd)
7799 (error (message "Error during update of dynamic block")))
7800 (goto-char pos)
7801 (unless (re-search-forward org-dblock-end-re nil t)
7802 (error "Dynamic block not terminated"))))))
7804 (defun org-dblock-update (&optional arg)
7805 "User command for updating dynamic blocks.
7806 Update the dynamic block at point. With prefix ARG, update all dynamic
7807 blocks in the buffer."
7808 (interactive "P")
7809 (if arg
7810 (org-update-all-dblocks)
7811 (or (looking-at org-dblock-start-re)
7812 (org-beginning-of-dblock))
7813 (org-update-dblock)))
7815 (defun org-update-dblock ()
7816 "Update the dynamic block at point
7817 This means to empty the block, parse for parameters and then call
7818 the correct writing function."
7819 (save-window-excursion
7820 (let* ((pos (point))
7821 (line (org-current-line))
7822 (params (org-prepare-dblock))
7823 (name (plist-get params :name))
7824 (cmd (intern (concat "org-dblock-write:" name))))
7825 (message "Updating dynamic block `%s' at line %d..." name line)
7826 (funcall cmd params)
7827 (message "Updating dynamic block `%s' at line %d...done" name line)
7828 (goto-char pos))))
7830 (defun org-beginning-of-dblock ()
7831 "Find the beginning of the dynamic block at point.
7832 Error if there is no such block at point."
7833 (let ((pos (point))
7834 beg)
7835 (end-of-line 1)
7836 (if (and (re-search-backward org-dblock-start-re nil t)
7837 (setq beg (match-beginning 0))
7838 (re-search-forward org-dblock-end-re nil t)
7839 (> (match-end 0) pos))
7840 (goto-char beg)
7841 (goto-char pos)
7842 (error "Not in a dynamic block"))))
7844 (defun org-update-all-dblocks ()
7845 "Update all dynamic blocks in the buffer.
7846 This function can be used in a hook."
7847 (when (org-mode-p)
7848 (org-map-dblocks 'org-update-dblock)))
7851 ;;;; Completion
7853 (defconst org-additional-option-like-keywords
7854 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7855 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7856 "BEGIN_EXAMPLE" "END_EXAMPLE"
7857 "BEGIN_QUOTE" "END_QUOTE"
7858 "BEGIN_VERSE" "END_VERSE"
7859 "BEGIN_SRC" "END_SRC"
7860 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7862 (defcustom org-structure-template-alist
7864 ("s" "#+begin_src ?\n\n#+end_src"
7865 "<src lang=\"?\">\n\n</src>")
7866 ("e" "#+begin_example\n?\n#+end_example"
7867 "<example>\n?\n</example>")
7868 ("q" "#+begin_quote\n?\n#+end_quote"
7869 "<quote>\n?\n</quote>")
7870 ("v" "#+begin_verse\n?\n#+end_verse"
7871 "<verse>\n?\n/verse>")
7872 ("l" "#+begin_latex\n?\n#+end_latex"
7873 "<literal style=\"latex\">\n?\n</literal>")
7874 ("L" "#+latex: "
7875 "<literal style=\"latex\">?</literal>")
7876 ("h" "#+begin_html\n?\n#+end_html"
7877 "<literal style=\"html\">\n?\n</literal>")
7878 ("H" "#+html: "
7879 "<literal style=\"html\">?</literal>")
7880 ("a" "#+begin_ascii\n?\n#+end_ascii")
7881 ("A" "#+ascii: ")
7882 ("i" "#+include %file ?"
7883 "<include file=%file markup=\"?\">")
7885 "Structure completion elements.
7886 This is a list of abbreviation keys and values. The value gets inserted
7887 it you type @samp{.} followed by the key and then the completion key,
7888 usually `M-TAB'. %file will be replaced by a file name after prompting
7889 for the file using completion.
7890 There are two templates for each key, the first uses the original Org syntax,
7891 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7892 the default when the /org-mtags.el/ module has been loaded. See also the
7893 variable `org-mtags-prefer-muse-templates'.
7894 This is an experimental feature, it is undecided if it is going to stay in."
7895 :group 'org-completion
7896 :type '(repeat
7897 (string :tag "Key")
7898 (string :tag "Template")
7899 (string :tag "Muse Template")))
7901 (defun org-try-structure-completion ()
7902 "Try to complete a structure template before point.
7903 This looks for strings like \"<e\" on an otherwise empty line and
7904 expands them."
7905 (let ((l (buffer-substring (point-at-bol) (point)))
7907 (when (and (looking-at "[ \t]*$")
7908 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7909 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7910 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7911 (match-beginning 1)) a)
7912 t)))
7914 (defun org-complete-expand-structure-template (start cell)
7915 "Expand a structure template."
7916 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7917 (rpl (nth (if musep 2 1) cell)))
7918 (delete-region start (point))
7919 (when (string-match "\\`#\\+" rpl)
7920 (cond
7921 ((bolp))
7922 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7923 (delete-region (point-at-bol) (point)))
7924 (t (newline))))
7925 (setq start (point))
7926 (if (string-match "%file" rpl)
7927 (setq rpl (replace-match
7928 (concat
7929 "\""
7930 (save-match-data
7931 (abbreviate-file-name (read-file-name "Include file: ")))
7932 "\"")
7933 t t rpl)))
7934 (insert rpl)
7935 (if (re-search-backward "\\?" start t) (delete-char 1))))
7938 (defun org-complete (&optional arg)
7939 "Perform completion on word at point.
7940 At the beginning of a headline, this completes TODO keywords as given in
7941 `org-todo-keywords'.
7942 If the current word is preceded by a backslash, completes the TeX symbols
7943 that are supported for HTML support.
7944 If the current word is preceded by \"#+\", completes special words for
7945 setting file options.
7946 In the line after \"#+STARTUP:, complete valid keywords.\"
7947 At all other locations, this simply calls the value of
7948 `org-completion-fallback-command'."
7949 (interactive "P")
7950 (org-without-partial-completion
7951 (catch 'exit
7952 (let* ((a nil)
7953 (end (point))
7954 (beg1 (save-excursion
7955 (skip-chars-backward (org-re "[:alnum:]_@"))
7956 (point)))
7957 (beg (save-excursion
7958 (skip-chars-backward "a-zA-Z0-9_:$")
7959 (point)))
7960 (confirm (lambda (x) (stringp (car x))))
7961 (searchhead (equal (char-before beg) ?*))
7962 (struct
7963 (when (and (member (char-before beg1) '(?. ?<))
7964 (setq a (assoc (buffer-substring beg1 (point))
7965 org-structure-template-alist)))
7966 (org-complete-expand-structure-template (1- beg1) a)
7967 (throw 'exit t)))
7968 (tag (and (equal (char-before beg1) ?:)
7969 (equal (char-after (point-at-bol)) ?*)))
7970 (prop (and (equal (char-before beg1) ?:)
7971 (not (equal (char-after (point-at-bol)) ?*))))
7972 (texp (equal (char-before beg) ?\\))
7973 (link (equal (char-before beg) ?\[))
7974 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7975 beg)
7976 "#+"))
7977 (startup (string-match "^#\\+STARTUP:.*"
7978 (buffer-substring (point-at-bol) (point))))
7979 (completion-ignore-case opt)
7980 (type nil)
7981 (tbl nil)
7982 (table (cond
7983 (opt
7984 (setq type :opt)
7985 (require 'org-exp)
7986 (append
7987 (mapcar
7988 (lambda (x)
7989 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7990 (cons (match-string 2 x) (match-string 1 x)))
7991 (org-split-string (org-get-current-options) "\n"))
7992 (mapcar 'list org-additional-option-like-keywords)))
7993 (startup
7994 (setq type :startup)
7995 org-startup-options)
7996 (link (append org-link-abbrev-alist-local
7997 org-link-abbrev-alist))
7998 (texp
7999 (setq type :tex)
8000 org-html-entities)
8001 ((string-match "\\`\\*+[ \t]+\\'"
8002 (buffer-substring (point-at-bol) beg))
8003 (setq type :todo)
8004 (mapcar 'list org-todo-keywords-1))
8005 (searchhead
8006 (setq type :searchhead)
8007 (save-excursion
8008 (goto-char (point-min))
8009 (while (re-search-forward org-todo-line-regexp nil t)
8010 (push (list
8011 (org-make-org-heading-search-string
8012 (match-string 3) t))
8013 tbl)))
8014 tbl)
8015 (tag (setq type :tag beg beg1)
8016 (or org-tag-alist (org-get-buffer-tags)))
8017 (prop (setq type :prop beg beg1)
8018 (mapcar 'list (org-buffer-property-keys nil t t)))
8019 (t (progn
8020 (call-interactively org-completion-fallback-command)
8021 (throw 'exit nil)))))
8022 (pattern (buffer-substring-no-properties beg end))
8023 (completion (try-completion pattern table confirm)))
8024 (cond ((eq completion t)
8025 (if (not (assoc (upcase pattern) table))
8026 (message "Already complete")
8027 (if (and (equal type :opt)
8028 (not (member (car (assoc (upcase pattern) table))
8029 org-additional-option-like-keywords)))
8030 (insert (substring (cdr (assoc (upcase pattern) table))
8031 (length pattern)))
8032 (if (memq type '(:tag :prop)) (insert ":")))))
8033 ((null completion)
8034 (message "Can't find completion for \"%s\"" pattern)
8035 (ding))
8036 ((not (string= pattern completion))
8037 (delete-region beg end)
8038 (if (string-match " +$" completion)
8039 (setq completion (replace-match "" t t completion)))
8040 (insert completion)
8041 (if (get-buffer-window "*Completions*")
8042 (delete-window (get-buffer-window "*Completions*")))
8043 (if (assoc completion table)
8044 (if (eq type :todo) (insert " ")
8045 (if (memq type '(:tag :prop)) (insert ":"))))
8046 (if (and (equal type :opt) (assoc completion table))
8047 (message "%s" (substitute-command-keys
8048 "Press \\[org-complete] again to insert example settings"))))
8050 (message "Making completion list...")
8051 (let ((list (sort (all-completions pattern table confirm)
8052 'string<)))
8053 (with-output-to-temp-buffer "*Completions*"
8054 (condition-case nil
8055 ;; Protection needed for XEmacs and emacs 21
8056 (display-completion-list list pattern)
8057 (error (display-completion-list list)))))
8058 (message "Making completion list...%s" "done")))))))
8060 ;;;; TODO, DEADLINE, Comments
8062 (defun org-toggle-comment ()
8063 "Change the COMMENT state of an entry."
8064 (interactive)
8065 (save-excursion
8066 (org-back-to-heading)
8067 (let (case-fold-search)
8068 (if (looking-at (concat outline-regexp
8069 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8070 (replace-match "" t t nil 1)
8071 (if (looking-at outline-regexp)
8072 (progn
8073 (goto-char (match-end 0))
8074 (insert org-comment-string " ")))))))
8076 (defvar org-last-todo-state-is-todo nil
8077 "This is non-nil when the last TODO state change led to a TODO state.
8078 If the last change removed the TODO tag or switched to DONE, then
8079 this is nil.")
8081 (defvar org-setting-tags nil) ; dynamically skipped
8083 (defun org-parse-local-options (string var)
8084 "Parse STRING for startup setting relevant for variable VAR."
8085 (let ((rtn (symbol-value var))
8086 e opts)
8087 (save-match-data
8088 (if (or (not string) (not (string-match "\\S-" string)))
8090 (setq opts (delq nil (mapcar (lambda (x)
8091 (setq e (assoc x org-startup-options))
8092 (if (eq (nth 1 e) var) e nil))
8093 (org-split-string string "[ \t]+"))))
8094 (if (not opts)
8096 (setq rtn nil)
8097 (while (setq e (pop opts))
8098 (if (not (nth 3 e))
8099 (setq rtn (nth 2 e))
8100 (if (not (listp rtn)) (setq rtn nil))
8101 (push (nth 2 e) rtn)))
8102 rtn)))))
8104 (defvar org-blocker-hook nil
8105 "Hook for functions that are allowed to block a state change.
8107 Each function gets as its single argument a property list, see
8108 `org-trigger-hook' for more information about this list.
8110 If any of the functions in this hook returns nil, the state change
8111 is blocked.")
8113 (defvar org-trigger-hook nil
8114 "Hook for functions that are triggered by a state change.
8116 Each function gets as its single argument a property list with at least
8117 the following elements:
8119 (:type type-of-change :position pos-at-entry-start
8120 :from old-state :to new-state)
8122 Depending on the type, more properties may be present.
8124 This mechanism is currently implemented for:
8126 TODO state changes
8127 ------------------
8128 :type todo-state-change
8129 :from previous state (keyword as a string), or nil
8130 :to new state (keyword as a string), or nil")
8132 (defvar org-agenda-headline-snapshot-before-repeat)
8133 (defun org-todo (&optional arg)
8134 "Change the TODO state of an item.
8135 The state of an item is given by a keyword at the start of the heading,
8136 like
8137 *** TODO Write paper
8138 *** DONE Call mom
8140 The different keywords are specified in the variable `org-todo-keywords'.
8141 By default the available states are \"TODO\" and \"DONE\".
8142 So for this example: when the item starts with TODO, it is changed to DONE.
8143 When it starts with DONE, the DONE is removed. And when neither TODO nor
8144 DONE are present, add TODO at the beginning of the heading.
8146 With C-u prefix arg, use completion to determine the new state.
8147 With numeric prefix arg, switch to that state.
8149 For calling through lisp, arg is also interpreted in the following way:
8150 'none -> empty state
8151 \"\"(empty string) -> switch to empty state
8152 'done -> switch to DONE
8153 'nextset -> switch to the next set of keywords
8154 'previousset -> switch to the previous set of keywords
8155 \"WAITING\" -> switch to the specified keyword, but only if it
8156 really is a member of `org-todo-keywords'."
8157 (interactive "P")
8158 (save-excursion
8159 (catch 'exit
8160 (org-back-to-heading)
8161 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8162 (or (looking-at (concat " +" org-todo-regexp " *"))
8163 (looking-at " *"))
8164 (let* ((match-data (match-data))
8165 (startpos (point-at-bol))
8166 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8167 (org-log-done org-log-done)
8168 (org-log-repeat org-log-repeat)
8169 (org-todo-log-states org-todo-log-states)
8170 (this (match-string 1))
8171 (hl-pos (match-beginning 0))
8172 (head (org-get-todo-sequence-head this))
8173 (ass (assoc head org-todo-kwd-alist))
8174 (interpret (nth 1 ass))
8175 (done-word (nth 3 ass))
8176 (final-done-word (nth 4 ass))
8177 (last-state (or this ""))
8178 (completion-ignore-case t)
8179 (member (member this org-todo-keywords-1))
8180 (tail (cdr member))
8181 (state (cond
8182 ((and org-todo-key-trigger
8183 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8184 (and (not arg) org-use-fast-todo-selection
8185 (not (eq org-use-fast-todo-selection 'prefix)))))
8186 ;; Use fast selection
8187 (org-fast-todo-selection))
8188 ((and (equal arg '(4))
8189 (or (not org-use-fast-todo-selection)
8190 (not org-todo-key-trigger)))
8191 ;; Read a state with completion
8192 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8193 org-todo-keywords-1)
8194 nil t))
8195 ((eq arg 'right)
8196 (if this
8197 (if tail (car tail) nil)
8198 (car org-todo-keywords-1)))
8199 ((eq arg 'left)
8200 (if (equal member org-todo-keywords-1)
8202 (if this
8203 (nth (- (length org-todo-keywords-1) (length tail) 2)
8204 org-todo-keywords-1)
8205 (org-last org-todo-keywords-1))))
8206 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8207 (setq arg nil))) ; hack to fall back to cycling
8208 (arg
8209 ;; user or caller requests a specific state
8210 (cond
8211 ((equal arg "") nil)
8212 ((eq arg 'none) nil)
8213 ((eq arg 'done) (or done-word (car org-done-keywords)))
8214 ((eq arg 'nextset)
8215 (or (car (cdr (member head org-todo-heads)))
8216 (car org-todo-heads)))
8217 ((eq arg 'previousset)
8218 (let ((org-todo-heads (reverse org-todo-heads)))
8219 (or (car (cdr (member head org-todo-heads)))
8220 (car org-todo-heads))))
8221 ((car (member arg org-todo-keywords-1)))
8222 ((nth (1- (prefix-numeric-value arg))
8223 org-todo-keywords-1))))
8224 ((null member) (or head (car org-todo-keywords-1)))
8225 ((equal this final-done-word) nil) ;; -> make empty
8226 ((null tail) nil) ;; -> first entry
8227 ((eq interpret 'sequence)
8228 (car tail))
8229 ((memq interpret '(type priority))
8230 (if (eq this-command last-command)
8231 (car tail)
8232 (if (> (length tail) 0)
8233 (or done-word (car org-done-keywords))
8234 nil)))
8235 (t nil)))
8236 (next (if state (concat " " state " ") " "))
8237 (change-plist (list :type 'todo-state-change :from this :to state
8238 :position startpos))
8239 dolog now-done-p)
8240 (when org-blocker-hook
8241 (unless (save-excursion
8242 (save-match-data
8243 (run-hook-with-args-until-failure
8244 'org-blocker-hook change-plist)))
8245 (if (interactive-p)
8246 (error "TODO state change from %s to %s blocked" this state)
8247 ;; fail silently
8248 (message "TODO state change from %s to %s blocked" this state)
8249 (throw 'exit nil))))
8250 (store-match-data match-data)
8251 (replace-match next t t)
8252 (unless (pos-visible-in-window-p hl-pos)
8253 (message "TODO state changed to %s" (org-trim next)))
8254 (unless head
8255 (setq head (org-get-todo-sequence-head state)
8256 ass (assoc head org-todo-kwd-alist)
8257 interpret (nth 1 ass)
8258 done-word (nth 3 ass)
8259 final-done-word (nth 4 ass)))
8260 (when (memq arg '(nextset previousset))
8261 (message "Keyword-Set %d/%d: %s"
8262 (- (length org-todo-sets) -1
8263 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8264 (length org-todo-sets)
8265 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8266 (setq org-last-todo-state-is-todo
8267 (not (member state org-done-keywords)))
8268 (setq now-done-p (and (member state org-done-keywords)
8269 (not (member this org-done-keywords))))
8270 (and logging (org-local-logging logging))
8271 (when (and (or org-todo-log-states org-log-done)
8272 (not (memq arg '(nextset previousset))))
8273 ;; we need to look at recording a time and note
8274 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8275 (nth 2 (assoc this org-todo-log-states))))
8276 (when (and state
8277 (member state org-not-done-keywords)
8278 (not (member this org-not-done-keywords)))
8279 ;; This is now a todo state and was not one before
8280 ;; If there was a CLOSED time stamp, get rid of it.
8281 (org-add-planning-info nil nil 'closed))
8282 (when (and now-done-p org-log-done)
8283 ;; It is now done, and it was not done before
8284 (org-add-planning-info 'closed (org-current-time))
8285 (if (and (not dolog) (eq 'note org-log-done))
8286 (org-add-log-setup 'done state 'findpos 'note)))
8287 (when (and state dolog)
8288 ;; This is a non-nil state, and we need to log it
8289 (org-add-log-setup 'state state 'findpos dolog)))
8290 ;; Fixup tag positioning
8291 (org-todo-trigger-tag-changes state)
8292 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8293 (when org-provide-todo-statistics
8294 (org-update-parent-todo-statistics))
8295 (run-hooks 'org-after-todo-state-change-hook)
8296 (if (and arg (not (member state org-done-keywords)))
8297 (setq head (org-get-todo-sequence-head state)))
8298 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8299 ;; Do we need to trigger a repeat?
8300 (when now-done-p
8301 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8302 ;; This is for the agenda, take a snapshot of the headline.
8303 (save-match-data
8304 (setq org-agenda-headline-snapshot-before-repeat
8305 (org-get-heading))))
8306 (org-auto-repeat-maybe state))
8307 ;; Fixup cursor location if close to the keyword
8308 (if (and (outline-on-heading-p)
8309 (not (bolp))
8310 (save-excursion (beginning-of-line 1)
8311 (looking-at org-todo-line-regexp))
8312 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8313 (progn
8314 (goto-char (or (match-end 2) (match-end 1)))
8315 (just-one-space)))
8316 (when org-trigger-hook
8317 (save-excursion
8318 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8320 (defun org-update-parent-todo-statistics ()
8321 "Update any statistics cookie in the parent of the current headline."
8322 (interactive)
8323 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8324 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8325 (catch 'exit
8326 (save-excursion
8327 (setq level (org-up-heading-safe))
8328 (unless (and level
8329 (re-search-forward box-re (point-at-eol) t))
8330 (throw 'exit nil))
8331 (setq is-percent (match-end 2))
8332 (save-match-data
8333 (unless (outline-next-heading) (throw 'exit nil))
8334 (while (looking-at org-todo-line-regexp)
8335 (setq kwd (match-string 2))
8336 (and kwd (setq cnt-all (1+ cnt-all)))
8337 (and (member kwd org-done-keywords)
8338 (setq cnt-done (1+ cnt-done)))
8339 (condition-case nil
8340 (org-forward-same-level 1)
8341 (error (end-of-line 1)))))
8342 (replace-match
8343 (if is-percent
8344 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8345 (format "[%d/%d]" cnt-done cnt-all)))
8346 (run-hook-with-args 'org-after-todo-statistics-hook
8347 cnt-done (- cnt-all cnt-done))))))
8349 (defvar org-after-todo-statistics-hook nil
8350 "Hook that is called after a TODO statistics cookie has been updated.
8351 Each function is called with two arguments: the number of not-done entries
8352 and the number of done entries.
8354 For example, the following function, when added to this hook, will switch
8355 an entry to DONE when all children are done, and back to TODO when new
8356 entries are set to a TODO status. Note that this hook is only called
8357 when there is a statistics cookie in the headline!
8359 (defun org-summary-todo (n-done n-not-done)
8360 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8361 (let (org-log-done org-log-states) ; turn off logging
8362 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8365 (defun org-todo-trigger-tag-changes (state)
8366 "Apply the changes defined in `org-todo-state-tags-triggers'."
8367 (let ((l org-todo-state-tags-triggers)
8368 changes)
8369 (when (or (not state) (equal state ""))
8370 (setq changes (append changes (cdr (assoc "" l)))))
8371 (when (and (stringp state) (> (length state) 0))
8372 (setq changes (append changes (cdr (assoc state l)))))
8373 (when (member state org-not-done-keywords)
8374 (setq changes (append changes (cdr (assoc 'todo l)))))
8375 (when (member state org-done-keywords)
8376 (setq changes (append changes (cdr (assoc 'done l)))))
8377 (dolist (c changes)
8378 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8380 (defun org-local-logging (value)
8381 "Get logging settings from a property VALUE."
8382 (let* (words w a)
8383 ;; directly set the variables, they are already local.
8384 (setq org-log-done nil
8385 org-log-repeat nil
8386 org-todo-log-states nil)
8387 (setq words (org-split-string value))
8388 (while (setq w (pop words))
8389 (cond
8390 ((setq a (assoc w org-startup-options))
8391 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8392 (set (nth 1 a) (nth 2 a))))
8393 ((setq a (org-extract-log-state-settings w))
8394 (and (member (car a) org-todo-keywords-1)
8395 (push a org-todo-log-states)))))))
8397 (defun org-get-todo-sequence-head (kwd)
8398 "Return the head of the TODO sequence to which KWD belongs.
8399 If KWD is not set, check if there is a text property remembering the
8400 right sequence."
8401 (let (p)
8402 (cond
8403 ((not kwd)
8404 (or (get-text-property (point-at-bol) 'org-todo-head)
8405 (progn
8406 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8407 nil (point-at-eol)))
8408 (get-text-property p 'org-todo-head))))
8409 ((not (member kwd org-todo-keywords-1))
8410 (car org-todo-keywords-1))
8411 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8413 (defun org-fast-todo-selection ()
8414 "Fast TODO keyword selection with single keys.
8415 Returns the new TODO keyword, or nil if no state change should occur."
8416 (let* ((fulltable org-todo-key-alist)
8417 (done-keywords org-done-keywords) ;; needed for the faces.
8418 (maxlen (apply 'max (mapcar
8419 (lambda (x)
8420 (if (stringp (car x)) (string-width (car x)) 0))
8421 fulltable)))
8422 (expert nil)
8423 (fwidth (+ maxlen 3 1 3))
8424 (ncol (/ (- (window-width) 4) fwidth))
8425 tg cnt e c tbl
8426 groups ingroup)
8427 (save-window-excursion
8428 (if expert
8429 (set-buffer (get-buffer-create " *Org todo*"))
8430 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8431 (erase-buffer)
8432 (org-set-local 'org-done-keywords done-keywords)
8433 (setq tbl fulltable cnt 0)
8434 (while (setq e (pop tbl))
8435 (cond
8436 ((equal e '(:startgroup))
8437 (push '() groups) (setq ingroup t)
8438 (when (not (= cnt 0))
8439 (setq cnt 0)
8440 (insert "\n"))
8441 (insert "{ "))
8442 ((equal e '(:endgroup))
8443 (setq ingroup nil cnt 0)
8444 (insert "}\n"))
8446 (setq tg (car e) c (cdr e))
8447 (if ingroup (push tg (car groups)))
8448 (setq tg (org-add-props tg nil 'face
8449 (org-get-todo-face tg)))
8450 (if (and (= cnt 0) (not ingroup)) (insert " "))
8451 (insert "[" c "] " tg (make-string
8452 (- fwidth 4 (length tg)) ?\ ))
8453 (when (= (setq cnt (1+ cnt)) ncol)
8454 (insert "\n")
8455 (if ingroup (insert " "))
8456 (setq cnt 0)))))
8457 (insert "\n")
8458 (goto-char (point-min))
8459 (if (not expert) (org-fit-window-to-buffer))
8460 (message "[a-z..]:Set [SPC]:clear")
8461 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8462 (cond
8463 ((or (= c ?\C-g)
8464 (and (= c ?q) (not (rassoc c fulltable))))
8465 (setq quit-flag t))
8466 ((= c ?\ ) nil)
8467 ((setq e (rassoc c fulltable) tg (car e))
8469 (t (setq quit-flag t))))))
8471 (defun org-entry-is-todo-p ()
8472 (member (org-get-todo-state) org-not-done-keywords))
8474 (defun org-entry-is-done-p ()
8475 (member (org-get-todo-state) org-done-keywords))
8477 (defun org-get-todo-state ()
8478 (save-excursion
8479 (org-back-to-heading t)
8480 (and (looking-at org-todo-line-regexp)
8481 (match-end 2)
8482 (match-string 2))))
8484 (defun org-at-date-range-p (&optional inactive-ok)
8485 "Is the cursor inside a date range?"
8486 (interactive)
8487 (save-excursion
8488 (catch 'exit
8489 (let ((pos (point)))
8490 (skip-chars-backward "^[<\r\n")
8491 (skip-chars-backward "<[")
8492 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8493 (>= (match-end 0) pos)
8494 (throw 'exit t))
8495 (skip-chars-backward "^<[\r\n")
8496 (skip-chars-backward "<[")
8497 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8498 (>= (match-end 0) pos)
8499 (throw 'exit t)))
8500 nil)))
8502 (defun org-get-repeat ()
8503 "Check if there is a deadline/schedule with repeater in this entry."
8504 (save-match-data
8505 (save-excursion
8506 (org-back-to-heading t)
8507 (if (re-search-forward
8508 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8509 (match-string 1)))))
8511 (defvar org-last-changed-timestamp)
8512 (defvar org-last-inserted-timestamp)
8513 (defvar org-log-post-message)
8514 (defvar org-log-note-purpose)
8515 (defvar org-log-note-how)
8516 (defvar org-log-note-extra)
8517 (defun org-auto-repeat-maybe (done-word)
8518 "Check if the current headline contains a repeated deadline/schedule.
8519 If yes, set TODO state back to what it was and change the base date
8520 of repeating deadline/scheduled time stamps to new date.
8521 This function is run automatically after each state change to a DONE state."
8522 ;; last-state is dynamically scoped into this function
8523 (let* ((repeat (org-get-repeat))
8524 (aa (assoc last-state org-todo-kwd-alist))
8525 (interpret (nth 1 aa))
8526 (head (nth 2 aa))
8527 (whata '(("d" . day) ("m" . month) ("y" . year)))
8528 (msg "Entry repeats: ")
8529 (org-log-done nil)
8530 (org-todo-log-states nil)
8531 (nshiftmax 10) (nshift 0)
8532 re type n what ts mb0 time)
8533 (when repeat
8534 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8535 (org-todo (if (eq interpret 'type) last-state head))
8536 (when org-log-repeat
8537 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8538 (memq 'org-add-log-note post-command-hook))
8539 ;; OK, we are already setup for some record
8540 (if (eq org-log-repeat 'note)
8541 ;; make sure we take a note, not only a time stamp
8542 (setq org-log-note-how 'note))
8543 ;; Set up for taking a record
8544 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8545 'findpos org-log-repeat)))
8546 (org-back-to-heading t)
8547 (org-add-planning-info nil nil 'closed)
8548 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8549 org-deadline-time-regexp "\\)\\|\\("
8550 org-ts-regexp "\\)"))
8551 (while (re-search-forward
8552 re (save-excursion (outline-next-heading) (point)) t)
8553 (setq type (if (match-end 1) org-scheduled-string
8554 (if (match-end 3) org-deadline-string "Plain:"))
8555 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8556 mb0 (match-beginning 0))
8557 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8558 (setq n (string-to-number (match-string 2 ts))
8559 what (match-string 3 ts))
8560 (if (equal what "w") (setq n (* n 7) what "d"))
8561 ;; Preparation, see if we need to modify the start date for the change
8562 (when (match-end 1)
8563 (setq time (save-match-data (org-time-string-to-time ts)))
8564 (cond
8565 ((equal (match-string 1 ts) ".")
8566 ;; Shift starting date to today
8567 (org-timestamp-change
8568 (- (time-to-days (current-time)) (time-to-days time))
8569 'day))
8570 ((equal (match-string 1 ts) "+")
8571 (while (or (= nshift 0)
8572 (<= (time-to-days time) (time-to-days (current-time))))
8573 (when (= (incf nshift) nshiftmax)
8574 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8575 (error "Abort")))
8576 (org-timestamp-change n (cdr (assoc what whata)))
8577 (org-at-timestamp-p t)
8578 (setq ts (match-string 1))
8579 (setq time (save-match-data (org-time-string-to-time ts))))
8580 (org-timestamp-change (- n) (cdr (assoc what whata)))
8581 ;; rematch, so that we have everything in place for the real shift
8582 (org-at-timestamp-p t)
8583 (setq ts (match-string 1))
8584 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8585 (org-timestamp-change n (cdr (assoc what whata)))
8586 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8587 (setq org-log-post-message msg)
8588 (message "%s" msg))))
8590 (defun org-show-todo-tree (arg)
8591 "Make a compact tree which shows all headlines marked with TODO.
8592 The tree will show the lines where the regexp matches, and all higher
8593 headlines above the match.
8594 With a \\[universal-argument] prefix, also show the DONE entries.
8595 With a numeric prefix N, construct a sparse tree for the Nth element
8596 of `org-todo-keywords-1'."
8597 (interactive "P")
8598 (let ((case-fold-search nil)
8599 (kwd-re
8600 (cond ((null arg) org-not-done-regexp)
8601 ((equal arg '(4))
8602 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8603 (mapcar 'list org-todo-keywords-1))))
8604 (concat "\\("
8605 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8606 "\\)\\>")))
8607 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8608 (regexp-quote (nth (1- (prefix-numeric-value arg))
8609 org-todo-keywords-1)))
8610 (t (error "Invalid prefix argument: %s" arg)))))
8611 (message "%d TODO entries found"
8612 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8614 (defun org-deadline (&optional remove time)
8615 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8616 With argument REMOVE, remove any deadline from the item.
8617 When TIME is set, it should be an internal time specification, and the
8618 scheduling will use the corresponding date."
8619 (interactive "P")
8620 (if remove
8621 (progn
8622 (org-remove-timestamp-with-keyword org-deadline-string)
8623 (message "Item no longer has a deadline."))
8624 (if (org-get-repeat)
8625 (error "Cannot change deadline on task with repeater, please do that by hand")
8626 (org-add-planning-info 'deadline time 'closed)
8627 (message "Deadline on %s" org-last-inserted-timestamp))))
8629 (defun org-schedule (&optional remove time)
8630 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8631 With argument REMOVE, remove any scheduling date from the item.
8632 When TIME is set, it should be an internal time specification, and the
8633 scheduling will use the corresponding date."
8634 (interactive "P")
8635 (if remove
8636 (progn
8637 (org-remove-timestamp-with-keyword org-scheduled-string)
8638 (message "Item is no longer scheduled."))
8639 (if (org-get-repeat)
8640 (error "Cannot reschedule task with repeater, please do that by hand")
8641 (org-add-planning-info 'scheduled time 'closed)
8642 (message "Scheduled to %s" org-last-inserted-timestamp))))
8644 (defun org-remove-timestamp-with-keyword (keyword)
8645 "Remove all time stamps with KEYWORD in the current entry."
8646 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8647 beg)
8648 (save-excursion
8649 (org-back-to-heading t)
8650 (setq beg (point))
8651 (org-end-of-subtree t t)
8652 (while (re-search-backward re beg t)
8653 (replace-match "")
8654 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8655 (equal (char-before) ?\ ))
8656 (backward-delete-char 1)
8657 (if (string-match "^[ \t]*$" (buffer-substring
8658 (point-at-bol) (point-at-eol)))
8659 (delete-region (point-at-bol)
8660 (min (point-max) (1+ (point-at-eol))))))))))
8662 (defun org-add-planning-info (what &optional time &rest remove)
8663 "Insert new timestamp with keyword in the line directly after the headline.
8664 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8665 If non is given, the user is prompted for a date.
8666 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8667 be removed."
8668 (interactive)
8669 (let (org-time-was-given org-end-time-was-given ts
8670 end default-time default-input)
8672 (when (and (not time) (memq what '(scheduled deadline)))
8673 ;; Try to get a default date/time from existing timestamp
8674 (save-excursion
8675 (org-back-to-heading t)
8676 (setq end (save-excursion (outline-next-heading) (point)))
8677 (when (re-search-forward (if (eq what 'scheduled)
8678 org-scheduled-time-regexp
8679 org-deadline-time-regexp)
8680 end t)
8681 (setq ts (match-string 1)
8682 default-time
8683 (apply 'encode-time (org-parse-time-string ts))
8684 default-input (and ts (org-get-compact-tod ts))))))
8685 (when what
8686 ;; If necessary, get the time from the user
8687 (setq time (or time (org-read-date nil 'to-time nil nil
8688 default-time default-input))))
8690 (when (and org-insert-labeled-timestamps-at-point
8691 (member what '(scheduled deadline)))
8692 (insert
8693 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8694 (org-insert-time-stamp time org-time-was-given
8695 nil nil nil (list org-end-time-was-given))
8696 (setq what nil))
8697 (save-excursion
8698 (save-restriction
8699 (let (col list elt ts buffer-invisibility-spec)
8700 (org-back-to-heading t)
8701 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8702 (goto-char (match-end 1))
8703 (setq col (current-column))
8704 (goto-char (match-end 0))
8705 (if (eobp) (insert "\n") (forward-char 1))
8706 (if (and (not (looking-at outline-regexp))
8707 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8708 "[^\r\n]*"))
8709 (not (equal (match-string 1) org-clock-string)))
8710 (narrow-to-region (match-beginning 0) (match-end 0))
8711 (insert-before-markers "\n")
8712 (backward-char 1)
8713 (narrow-to-region (point) (point))
8714 (and org-adapt-indentation (org-indent-to-column col)))
8715 ;; Check if we have to remove something.
8716 (setq list (cons what remove))
8717 (while list
8718 (setq elt (pop list))
8719 (goto-char (point-min))
8720 (when (or (and (eq elt 'scheduled)
8721 (re-search-forward org-scheduled-time-regexp nil t))
8722 (and (eq elt 'deadline)
8723 (re-search-forward org-deadline-time-regexp nil t))
8724 (and (eq elt 'closed)
8725 (re-search-forward org-closed-time-regexp nil t)))
8726 (replace-match "")
8727 (if (looking-at "--+<[^>]+>") (replace-match ""))
8728 (if (looking-at " +") (replace-match ""))))
8729 (goto-char (point-max))
8730 (when what
8731 (insert
8732 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8733 (cond ((eq what 'scheduled) org-scheduled-string)
8734 ((eq what 'deadline) org-deadline-string)
8735 ((eq what 'closed) org-closed-string))
8736 " ")
8737 (setq ts (org-insert-time-stamp
8738 time
8739 (or org-time-was-given
8740 (and (eq what 'closed) org-log-done-with-time))
8741 (eq what 'closed)
8742 nil nil (list org-end-time-was-given)))
8743 (end-of-line 1))
8744 (goto-char (point-min))
8745 (widen)
8746 (if (and (looking-at "[ \t]+\n")
8747 (equal (char-before) ?\n))
8748 (delete-region (1- (point)) (point-at-eol)))
8749 ts)))))
8751 (defvar org-log-note-marker (make-marker))
8752 (defvar org-log-note-purpose nil)
8753 (defvar org-log-note-state nil)
8754 (defvar org-log-note-how nil)
8755 (defvar org-log-note-extra nil)
8756 (defvar org-log-note-window-configuration nil)
8757 (defvar org-log-note-return-to (make-marker))
8758 (defvar org-log-post-message nil
8759 "Message to be displayed after a log note has been stored.
8760 The auto-repeater uses this.")
8762 (defun org-add-note ()
8763 "Add a note to the current entry.
8764 This is done in the same way as adding a state change note."
8765 (interactive)
8766 (org-add-log-setup 'note nil 'findpos nil))
8768 (defvar org-property-end-re)
8769 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8770 "Set up the post command hook to take a note.
8771 If this is about to TODO state change, the new state is expected in STATE.
8772 When FINDPOS is non-nil, find the correct position for the note in
8773 the current entry. If not, assume that it can be inserted at point.
8774 HOW is an indicator what kind of note should be created.
8775 EXTRA is additional text that will be inserted into the notes buffer."
8776 (save-restriction
8777 (save-excursion
8778 (when findpos
8779 (org-back-to-heading t)
8780 (narrow-to-region (point) (save-excursion
8781 (outline-next-heading) (point)))
8782 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8783 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8784 "[^\r\n]*\\)?"))
8785 (goto-char (match-end 0))
8786 (when (and org-log-state-notes-insert-after-drawers
8787 (save-excursion
8788 (forward-line) (looking-at org-drawer-regexp)))
8789 (progn (forward-line)
8790 (while (looking-at org-drawer-regexp)
8791 (goto-char (match-end 0))
8792 (re-search-forward org-property-end-re (point-max) t)
8793 (forward-line))
8794 (forward-line -1)))
8795 (unless org-log-states-order-reversed
8796 (and (= (char-after) ?\n) (forward-char 1))
8797 (org-skip-over-state-notes)
8798 (skip-chars-backward " \t\n\r")))
8799 (move-marker org-log-note-marker (point))
8800 (setq org-log-note-purpose purpose
8801 org-log-note-state state
8802 org-log-note-how how
8803 org-log-note-extra extra)
8804 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8806 (defun org-skip-over-state-notes ()
8807 "Skip past the list of State notes in an entry."
8808 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8809 (while (looking-at "[ \t]*- State")
8810 (condition-case nil
8811 (org-next-item)
8812 (error (org-end-of-item)))))
8814 (defun org-add-log-note (&optional purpose)
8815 "Pop up a window for taking a note, and add this note later at point."
8816 (remove-hook 'post-command-hook 'org-add-log-note)
8817 (setq org-log-note-window-configuration (current-window-configuration))
8818 (delete-other-windows)
8819 (move-marker org-log-note-return-to (point))
8820 (switch-to-buffer (marker-buffer org-log-note-marker))
8821 (goto-char org-log-note-marker)
8822 (org-switch-to-buffer-other-window "*Org Note*")
8823 (erase-buffer)
8824 (if (memq org-log-note-how '(time state))
8825 (let (current-prefix-arg) (org-store-log-note))
8826 (let ((org-inhibit-startup t)) (org-mode))
8827 (insert (format "# Insert note for %s.
8828 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8829 (cond
8830 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8831 ((eq org-log-note-purpose 'done) "closed todo item")
8832 ((eq org-log-note-purpose 'state)
8833 (format "state change to \"%s\"" org-log-note-state))
8834 ((eq org-log-note-purpose 'note)
8835 "this entry")
8836 (t (error "This should not happen")))))
8837 (if org-log-note-extra (insert org-log-note-extra))
8838 (org-set-local 'org-finish-function 'org-store-log-note)))
8840 (defvar org-note-abort nil) ; dynamically scoped
8841 (defun org-store-log-note ()
8842 "Finish taking a log note, and insert it to where it belongs."
8843 (let ((txt (buffer-string))
8844 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8845 lines ind)
8846 (kill-buffer (current-buffer))
8847 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8848 (setq txt (replace-match "" t t txt)))
8849 (if (string-match "\\s-+\\'" txt)
8850 (setq txt (replace-match "" t t txt)))
8851 (setq lines (org-split-string txt "\n"))
8852 (when (and note (string-match "\\S-" note))
8853 (setq note
8854 (org-replace-escapes
8855 note
8856 (list (cons "%u" (user-login-name))
8857 (cons "%U" user-full-name)
8858 (cons "%t" (format-time-string
8859 (org-time-stamp-format 'long 'inactive)
8860 (current-time)))
8861 (cons "%s" (if org-log-note-state
8862 (concat "\"" org-log-note-state "\"")
8863 "")))))
8864 (if lines (setq note (concat note " \\\\")))
8865 (push note lines))
8866 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8867 (when lines
8868 (save-excursion
8869 (set-buffer (marker-buffer org-log-note-marker))
8870 (save-excursion
8871 (goto-char org-log-note-marker)
8872 (move-marker org-log-note-marker nil)
8873 (end-of-line 1)
8874 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8875 (indent-relative nil)
8876 (insert "- " (pop lines))
8877 (org-indent-line-function)
8878 (beginning-of-line 1)
8879 (looking-at "[ \t]*")
8880 (setq ind (concat (match-string 0) " "))
8881 (end-of-line 1)
8882 (while lines (insert "\n" ind (pop lines)))))))
8883 (set-window-configuration org-log-note-window-configuration)
8884 (with-current-buffer (marker-buffer org-log-note-return-to)
8885 (goto-char org-log-note-return-to))
8886 (move-marker org-log-note-return-to nil)
8887 (and org-log-post-message (message "%s" org-log-post-message)))
8889 (defun org-sparse-tree (&optional arg)
8890 "Create a sparse tree, prompt for the details.
8891 This command can create sparse trees. You first need to select the type
8892 of match used to create the tree:
8894 t Show entries with a specific TODO keyword.
8895 T Show entries selected by a tags match.
8896 p Enter a property name and its value (both with completion on existing
8897 names/values) and show entries with that property.
8898 r Show entries matching a regular expression
8899 d Show deadlines due within `org-deadline-warning-days'."
8900 (interactive "P")
8901 (let (ans kwd value)
8902 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8903 (setq ans (read-char-exclusive))
8904 (cond
8905 ((equal ans ?d)
8906 (call-interactively 'org-check-deadlines))
8907 ((equal ans ?b)
8908 (call-interactively 'org-check-before-date))
8909 ((equal ans ?t)
8910 (org-show-todo-tree '(4)))
8911 ((equal ans ?T)
8912 (call-interactively 'org-tags-sparse-tree))
8913 ((member ans '(?p ?P))
8914 (setq kwd (org-ido-completing-read "Property: "
8915 (mapcar 'list (org-buffer-property-keys))))
8916 (setq value (org-ido-completing-read "Value: "
8917 (mapcar 'list (org-property-values kwd))))
8918 (unless (string-match "\\`{.*}\\'" value)
8919 (setq value (concat "\"" value "\"")))
8920 (org-tags-sparse-tree arg (concat kwd "=" value)))
8921 ((member ans '(?r ?R ?/))
8922 (call-interactively 'org-occur))
8923 (t (error "No such sparse tree command \"%c\"" ans)))))
8925 (defvar org-occur-highlights nil
8926 "List of overlays used for occur matches.")
8927 (make-variable-buffer-local 'org-occur-highlights)
8928 (defvar org-occur-parameters nil
8929 "Parameters of the active org-occur calls.
8930 This is a list, each call to org-occur pushes as cons cell,
8931 containing the regular expression and the callback, onto the list.
8932 The list can contain several entries if `org-occur' has been called
8933 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8934 will only contain one set of parameters. When the highlights are
8935 removed (for example with `C-c C-c', or with the next edit (depending
8936 on `org-remove-highlights-with-change'), this variable is emptied
8937 as well.")
8938 (make-variable-buffer-local 'org-occur-parameters)
8940 (defun org-occur (regexp &optional keep-previous callback)
8941 "Make a compact tree which shows all matches of REGEXP.
8942 The tree will show the lines where the regexp matches, and all higher
8943 headlines above the match. It will also show the heading after the match,
8944 to make sure editing the matching entry is easy.
8945 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8946 call to `org-occur' will be kept, to allow stacking of calls to this
8947 command.
8948 If CALLBACK is non-nil, it is a function which is called to confirm
8949 that the match should indeed be shown."
8950 (interactive "sRegexp: \nP")
8951 (unless keep-previous
8952 (org-remove-occur-highlights nil nil t))
8953 (push (cons regexp callback) org-occur-parameters)
8954 (let ((cnt 0))
8955 (save-excursion
8956 (goto-char (point-min))
8957 (if (or (not keep-previous) ; do not want to keep
8958 (not org-occur-highlights)) ; no previous matches
8959 ;; hide everything
8960 (org-overview))
8961 (while (re-search-forward regexp nil t)
8962 (when (or (not callback)
8963 (save-match-data (funcall callback)))
8964 (setq cnt (1+ cnt))
8965 (when org-highlight-sparse-tree-matches
8966 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8967 (org-show-context 'occur-tree))))
8968 (when org-remove-highlights-with-change
8969 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8970 nil 'local))
8971 (unless org-sparse-tree-open-archived-trees
8972 (org-hide-archived-subtrees (point-min) (point-max)))
8973 (run-hooks 'org-occur-hook)
8974 (if (interactive-p)
8975 (message "%d match(es) for regexp %s" cnt regexp))
8976 cnt))
8978 (defun org-show-context (&optional key)
8979 "Make sure point and context and visible.
8980 How much context is shown depends upon the variables
8981 `org-show-hierarchy-above', `org-show-following-heading'. and
8982 `org-show-siblings'."
8983 (let ((heading-p (org-on-heading-p t))
8984 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8985 (following-p (org-get-alist-option org-show-following-heading key))
8986 (entry-p (org-get-alist-option org-show-entry-below key))
8987 (siblings-p (org-get-alist-option org-show-siblings key)))
8988 (catch 'exit
8989 ;; Show heading or entry text
8990 (if (and heading-p (not entry-p))
8991 (org-flag-heading nil) ; only show the heading
8992 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8993 (org-show-hidden-entry))) ; show entire entry
8994 (when following-p
8995 ;; Show next sibling, or heading below text
8996 (save-excursion
8997 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8998 (org-flag-heading nil))))
8999 (when siblings-p (org-show-siblings))
9000 (when hierarchy-p
9001 ;; show all higher headings, possibly with siblings
9002 (save-excursion
9003 (while (and (condition-case nil
9004 (progn (org-up-heading-all 1) t)
9005 (error nil))
9006 (not (bobp)))
9007 (org-flag-heading nil)
9008 (when siblings-p (org-show-siblings))))))))
9010 (defun org-reveal (&optional siblings)
9011 "Show current entry, hierarchy above it, and the following headline.
9012 This can be used to show a consistent set of context around locations
9013 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9014 not t for the search context.
9016 With optional argument SIBLINGS, on each level of the hierarchy all
9017 siblings are shown. This repairs the tree structure to what it would
9018 look like when opened with hierarchical calls to `org-cycle'."
9019 (interactive "P")
9020 (let ((org-show-hierarchy-above t)
9021 (org-show-following-heading t)
9022 (org-show-siblings (if siblings t org-show-siblings)))
9023 (org-show-context nil)))
9025 (defun org-highlight-new-match (beg end)
9026 "Highlight from BEG to END and mark the highlight is an occur headline."
9027 (let ((ov (org-make-overlay beg end)))
9028 (org-overlay-put ov 'face 'secondary-selection)
9029 (push ov org-occur-highlights)))
9031 (defun org-remove-occur-highlights (&optional beg end noremove)
9032 "Remove the occur highlights from the buffer.
9033 BEG and END are ignored. If NOREMOVE is nil, remove this function
9034 from the `before-change-functions' in the current buffer."
9035 (interactive)
9036 (unless org-inhibit-highlight-removal
9037 (mapc 'org-delete-overlay org-occur-highlights)
9038 (setq org-occur-highlights nil)
9039 (setq org-occur-parameters nil)
9040 (unless noremove
9041 (remove-hook 'before-change-functions
9042 'org-remove-occur-highlights 'local))))
9044 ;;;; Priorities
9046 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9047 "Regular expression matching the priority indicator.")
9049 (defvar org-remove-priority-next-time nil)
9051 (defun org-priority-up ()
9052 "Increase the priority of the current item."
9053 (interactive)
9054 (org-priority 'up))
9056 (defun org-priority-down ()
9057 "Decrease the priority of the current item."
9058 (interactive)
9059 (org-priority 'down))
9061 (defun org-priority (&optional action)
9062 "Change the priority of an item by ARG.
9063 ACTION can be `set', `up', `down', or a character."
9064 (interactive)
9065 (setq action (or action 'set))
9066 (let (current new news have remove)
9067 (save-excursion
9068 (org-back-to-heading)
9069 (if (looking-at org-priority-regexp)
9070 (setq current (string-to-char (match-string 2))
9071 have t)
9072 (setq current org-default-priority))
9073 (cond
9074 ((or (eq action 'set)
9075 (if (featurep 'xemacs) (characterp action) (integerp action)))
9076 (if (not (eq action 'set))
9077 (setq new action)
9078 (message "Priority %c-%c, SPC to remove: "
9079 org-highest-priority org-lowest-priority)
9080 (setq new (read-char-exclusive)))
9081 (if (and (= (upcase org-highest-priority) org-highest-priority)
9082 (= (upcase org-lowest-priority) org-lowest-priority))
9083 (setq new (upcase new)))
9084 (cond ((equal new ?\ ) (setq remove t))
9085 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9086 (error "Priority must be between `%c' and `%c'"
9087 org-highest-priority org-lowest-priority))))
9088 ((eq action 'up)
9089 (if (and (not have) (eq last-command this-command))
9090 (setq new org-lowest-priority)
9091 (setq new (if (and org-priority-start-cycle-with-default (not have))
9092 org-default-priority (1- current)))))
9093 ((eq action 'down)
9094 (if (and (not have) (eq last-command this-command))
9095 (setq new org-highest-priority)
9096 (setq new (if (and org-priority-start-cycle-with-default (not have))
9097 org-default-priority (1+ current)))))
9098 (t (error "Invalid action")))
9099 (if (or (< (upcase new) org-highest-priority)
9100 (> (upcase new) org-lowest-priority))
9101 (setq remove t))
9102 (setq news (format "%c" new))
9103 (if have
9104 (if remove
9105 (replace-match "" t t nil 1)
9106 (replace-match news t t nil 2))
9107 (if remove
9108 (error "No priority cookie found in line")
9109 (looking-at org-todo-line-regexp)
9110 (if (match-end 2)
9111 (progn
9112 (goto-char (match-end 2))
9113 (insert " [#" news "]"))
9114 (goto-char (match-beginning 3))
9115 (insert "[#" news "] ")))))
9116 (org-preserve-lc (org-set-tags nil 'align))
9117 (if remove
9118 (message "Priority removed")
9119 (message "Priority of current item set to %s" news))))
9122 (defun org-get-priority (s)
9123 "Find priority cookie and return priority."
9124 (save-match-data
9125 (if (not (string-match org-priority-regexp s))
9126 (* 1000 (- org-lowest-priority org-default-priority))
9127 (* 1000 (- org-lowest-priority
9128 (string-to-char (match-string 2 s)))))))
9130 ;;;; Tags
9132 (defvar org-agenda-archives-mode)
9133 (defun org-scan-tags (action matcher &optional todo-only)
9134 "Scan headline tags with inheritance and produce output ACTION.
9136 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9137 or `agenda' to produce an entry list for an agenda view. It can also be
9138 a Lisp form or a function that should be called at each matched headline, in
9139 this case the return value is a list of all return values from these calls.
9141 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9142 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9143 only lines with a TODO keyword are included in the output."
9144 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9145 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9146 (org-re
9147 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9148 (props (list 'face 'default
9149 'done-face 'org-done
9150 'undone-face 'default
9151 'mouse-face 'highlight
9152 'org-not-done-regexp org-not-done-regexp
9153 'org-todo-regexp org-todo-regexp
9154 'keymap org-agenda-keymap
9155 'help-echo
9156 (format "mouse-2 or RET jump to org file %s"
9157 (abbreviate-file-name
9158 (or (buffer-file-name (buffer-base-buffer))
9159 (buffer-name (buffer-base-buffer)))))))
9160 (case-fold-search nil)
9161 lspos tags tags-list
9162 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9163 (llast 0) rtn rtn1 level category i txt
9164 todo marker entry priority)
9165 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9166 (setq action (list 'lambda nil action)))
9167 (save-excursion
9168 (goto-char (point-min))
9169 (when (eq action 'sparse-tree)
9170 (org-overview)
9171 (org-remove-occur-highlights))
9172 (while (re-search-forward re nil t)
9173 (catch :skip
9174 (setq todo (if (match-end 1) (match-string 2))
9175 tags (if (match-end 4) (match-string 4)))
9176 (goto-char (setq lspos (1+ (match-beginning 0))))
9177 (setq level (org-reduced-level (funcall outline-level))
9178 category (org-get-category))
9179 (setq i llast llast level)
9180 ;; remove tag lists from same and sublevels
9181 (while (>= i level)
9182 (when (setq entry (assoc i tags-alist))
9183 (setq tags-alist (delete entry tags-alist)))
9184 (setq i (1- i)))
9185 ;; add the next tags
9186 (when tags
9187 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9188 tags-alist
9189 (cons (cons level tags) tags-alist)))
9190 ;; compile tags for current headline
9191 (setq tags-list
9192 (if org-use-tag-inheritance
9193 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9194 tags))
9195 (when org-use-tag-inheritance
9196 (setcdr (car tags-alist)
9197 (mapcar (lambda (x)
9198 (setq x (copy-sequence x))
9199 (org-add-prop-inherited x))
9200 (cdar tags-alist))))
9201 (when (and tags org-use-tag-inheritance
9202 (not (eq t org-use-tag-inheritance)))
9203 ;; selective inheritance, remove uninherited ones
9204 (setcdr (car tags-alist)
9205 (org-remove-uniherited-tags (cdar tags-alist))))
9206 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9207 (let ((case-fold-search t)) (eval matcher))
9209 (not (member org-archive-tag tags-list))
9210 ;; we have an archive tag, should we use this anyway?
9211 (or (not org-agenda-skip-archived-trees)
9212 (and (eq action 'agenda) org-agenda-archives-mode))))
9213 (unless (eq action 'sparse-tree) (org-agenda-skip))
9215 ;; select this headline
9217 (cond
9218 ((eq action 'sparse-tree)
9219 (and org-highlight-sparse-tree-matches
9220 (org-get-heading) (match-end 0)
9221 (org-highlight-new-match
9222 (match-beginning 0) (match-beginning 1)))
9223 (org-show-context 'tags-tree))
9224 ((eq action 'agenda)
9225 (setq txt (org-format-agenda-item
9227 (concat
9228 (if org-tags-match-list-sublevels
9229 (make-string (1- level) ?.) "")
9230 (org-get-heading))
9231 category (org-get-tags-at))
9232 priority (org-get-priority txt))
9233 (goto-char lspos)
9234 (setq marker (org-agenda-new-marker))
9235 (org-add-props txt props
9236 'org-marker marker 'org-hd-marker marker 'org-category category
9237 'priority priority 'type "tagsmatch")
9238 (push txt rtn))
9239 ((functionp action)
9240 (save-excursion
9241 (setq rtn1 (funcall action))
9242 (push rtn1 rtn))
9243 (goto-char (point-at-eol)))
9244 (t (error "Invalid action")))
9246 ;; if we are to skip sublevels, jump to end of subtree
9247 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9248 (when (and (eq action 'sparse-tree)
9249 (not org-sparse-tree-open-archived-trees))
9250 (org-hide-archived-subtrees (point-min) (point-max)))
9251 (nreverse rtn)))
9253 (defun org-remove-uniherited-tags (tags)
9254 "Remove all tags that are not inherited from the list TAGS."
9255 (cond
9256 ((eq org-use-tag-inheritance t)
9257 (if org-tags-exclude-from-inheritance
9258 (org-delete-all org-tags-exclude-from-inheritance tags)
9259 tags))
9260 ((not org-use-tag-inheritance) nil)
9261 ((stringp org-use-tag-inheritance)
9262 (delq nil (mapcar
9263 (lambda (x)
9264 (if (and (string-match org-use-tag-inheritance x)
9265 (not (member x org-tags-exclude-from-inheritance)))
9266 x nil))
9267 tags)))
9268 ((listp org-use-tag-inheritance)
9269 (delq nil (mapcar
9270 (lambda (x)
9271 (if (member x org-use-tag-inheritance) x nil))
9272 tags)))))
9274 (defvar todo-only) ;; dynamically scoped
9276 (defun org-tags-sparse-tree (&optional todo-only match)
9277 "Create a sparse tree according to tags string MATCH.
9278 MATCH can contain positive and negative selection of tags, like
9279 \"+WORK+URGENT-WITHBOSS\".
9280 If optional argument TODO-ONLY is non-nil, only select lines that are
9281 also TODO lines."
9282 (interactive "P")
9283 (org-prepare-agenda-buffers (list (current-buffer)))
9284 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9286 (defvar org-cached-props nil)
9287 (defun org-cached-entry-get (pom property)
9288 (if (or (eq t org-use-property-inheritance)
9289 (and (stringp org-use-property-inheritance)
9290 (string-match org-use-property-inheritance property))
9291 (and (listp org-use-property-inheritance)
9292 (member property org-use-property-inheritance)))
9293 ;; Caching is not possible, check it directly
9294 (org-entry-get pom property 'inherit)
9295 ;; Get all properties, so that we can do complicated checks easily
9296 (cdr (assoc property (or org-cached-props
9297 (setq org-cached-props
9298 (org-entry-properties pom)))))))
9300 (defun org-global-tags-completion-table (&optional files)
9301 "Return the list of all tags in all agenda buffer/files."
9302 (save-excursion
9303 (org-uniquify
9304 (delq nil
9305 (apply 'append
9306 (mapcar
9307 (lambda (file)
9308 (set-buffer (find-file-noselect file))
9309 (append (org-get-buffer-tags)
9310 (mapcar (lambda (x) (if (stringp (car-safe x))
9311 (list (car-safe x)) nil))
9312 org-tag-alist)))
9313 (if (and files (car files))
9314 files
9315 (org-agenda-files))))))))
9317 (defun org-make-tags-matcher (match)
9318 "Create the TAGS//TODO matcher form for the selection string MATCH."
9319 ;; todo-only is scoped dynamically into this function, and the function
9320 ;; may change it if the matcher asks for it.
9321 (unless match
9322 ;; Get a new match request, with completion
9323 (let ((org-last-tags-completion-table
9324 (org-global-tags-completion-table)))
9325 (setq match (org-ido-completing-read
9326 "Match: " 'org-tags-completion-function nil nil nil
9327 'org-tags-history))))
9329 ;; Parse the string and create a lisp form
9330 (let ((match0 match)
9331 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9332 minus tag mm
9333 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9334 orterms term orlist re-p str-p level-p level-op time-p
9335 prop-p pn pv po cat-p gv rest)
9336 (if (string-match "/+" match)
9337 ;; match contains also a todo-matching request
9338 (progn
9339 (setq tagsmatch (substring match 0 (match-beginning 0))
9340 todomatch (substring match (match-end 0)))
9341 (if (string-match "^!" todomatch)
9342 (setq todo-only t todomatch (substring todomatch 1)))
9343 (if (string-match "^\\s-*$" todomatch)
9344 (setq todomatch nil)))
9345 ;; only matching tags
9346 (setq tagsmatch match todomatch nil))
9348 ;; Make the tags matcher
9349 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9350 (setq tagsmatcher t)
9351 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9352 (while (setq term (pop orterms))
9353 (while (and (equal (substring term -1) "\\") orterms)
9354 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9355 (while (string-match re term)
9356 (setq rest (substring term (match-end 0))
9357 minus (and (match-end 1)
9358 (equal (match-string 1 term) "-"))
9359 tag (match-string 2 term)
9360 re-p (equal (string-to-char tag) ?{)
9361 level-p (match-end 4)
9362 prop-p (match-end 5)
9363 mm (cond
9364 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9365 (level-p
9366 (setq level-op (org-op-to-function (match-string 3 term)))
9367 `(,level-op level ,(string-to-number
9368 (match-string 4 term))))
9369 (prop-p
9370 (setq pn (match-string 5 term)
9371 po (match-string 6 term)
9372 pv (match-string 7 term)
9373 cat-p (equal pn "CATEGORY")
9374 re-p (equal (string-to-char pv) ?{)
9375 str-p (equal (string-to-char pv) ?\")
9376 time-p (save-match-data
9377 (string-match "^\"[[<].*[]>]\"$" pv))
9378 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9379 (if time-p (setq pv (org-matcher-time pv)))
9380 (setq po (org-op-to-function po (if time-p 'time str-p)))
9381 (cond
9382 ((equal pn "CATEGORY")
9383 (setq gv '(get-text-property (point) 'org-category)))
9384 ((equal pn "TODO")
9385 (setq gv 'todo))
9387 (setq gv `(org-cached-entry-get nil ,pn))))
9388 (if re-p
9389 (if (eq po 'org<>)
9390 `(not (string-match ,pv (or ,gv "")))
9391 `(string-match ,pv (or ,gv "")))
9392 (if str-p
9393 `(,po (or ,gv "") ,pv)
9394 `(,po (string-to-number (or ,gv ""))
9395 ,(string-to-number pv) ))))
9396 (t `(member ,(downcase tag) tags-list)))
9397 mm (if minus (list 'not mm) mm)
9398 term rest)
9399 (push mm tagsmatcher))
9400 (push (if (> (length tagsmatcher) 1)
9401 (cons 'and tagsmatcher)
9402 (car tagsmatcher))
9403 orlist)
9404 (setq tagsmatcher nil))
9405 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9406 (setq tagsmatcher
9407 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9408 ;; Make the todo matcher
9409 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9410 (setq todomatcher t)
9411 (setq orterms (org-split-string todomatch "|") orlist nil)
9412 (while (setq term (pop orterms))
9413 (while (string-match re term)
9414 (setq minus (and (match-end 1)
9415 (equal (match-string 1 term) "-"))
9416 kwd (match-string 2 term)
9417 re-p (equal (string-to-char kwd) ?{)
9418 term (substring term (match-end 0))
9419 mm (if re-p
9420 `(string-match ,(substring kwd 1 -1) todo)
9421 (list 'equal 'todo kwd))
9422 mm (if minus (list 'not mm) mm))
9423 (push mm todomatcher))
9424 (push (if (> (length todomatcher) 1)
9425 (cons 'and todomatcher)
9426 (car todomatcher))
9427 orlist)
9428 (setq todomatcher nil))
9429 (setq todomatcher (if (> (length orlist) 1)
9430 (cons 'or orlist) (car orlist))))
9432 ;; Return the string and lisp forms of the matcher
9433 (setq matcher (if todomatcher
9434 (list 'and tagsmatcher todomatcher)
9435 tagsmatcher))
9436 (cons match0 matcher)))
9438 (defun org-op-to-function (op &optional stringp)
9439 "Turn an operator into the appropriate function."
9440 (setq op
9441 (cond
9442 ((equal op "<" ) '(< string< org-time<))
9443 ((equal op ">" ) '(> org-string> org-time>))
9444 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9445 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9446 ((member op '("=" "==")) '(= string= org-time=))
9447 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9448 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9450 (defun org<> (a b) (not (= a b)))
9451 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9452 (defun org-string>= (a b) (not (string< a b)))
9453 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9454 (defun org-string<> (a b) (not (string= a b)))
9455 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9456 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9457 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9458 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9459 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9460 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9461 (defun org-2ft (s)
9462 "Convert S to a floating point time.
9463 If S is already a number, just return it. If it is a string, parse
9464 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9465 (cond
9466 ((numberp s) s)
9467 ((stringp s)
9468 (condition-case nil
9469 (float-time (apply 'encode-time (org-parse-time-string s)))
9470 (error 0.)))
9471 (t 0.)))
9473 (defun org-time-today ()
9474 "Time in seconds today at 0:00.
9475 Returns the float number of seconds since the beginning of the
9476 epoch to the beginning of today (00:00)."
9477 (float-time (apply 'encode-time
9478 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9480 (defun org-matcher-time (s)
9481 "Interpret a time comparison value."
9482 (save-match-data
9483 (cond
9484 ((string= s "<now>") (float-time))
9485 ((string= s "<today>") (org-time-today))
9486 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9487 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9488 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9489 (+ (org-time-today)
9490 (* (string-to-number (match-string 1 s))
9491 (cdr (assoc (match-string 2 s)
9492 '(("d" . 86400.0) ("w" . 604800.0)
9493 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9494 (t (org-2ft s)))))
9496 (defun org-match-any-p (re list)
9497 "Does re match any element of list?"
9498 (setq list (mapcar (lambda (x) (string-match re x)) list))
9499 (delq nil list))
9501 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9502 (defvar org-tags-overlay (org-make-overlay 1 1))
9503 (org-detach-overlay org-tags-overlay)
9505 (defun org-get-local-tags-at (&optional pos)
9506 "Get a list of tags defined in the current headline."
9507 (org-get-tags-at pos 'local))
9509 (defun org-get-local-tags ()
9510 "Get a list of tags defined in the current headline."
9511 (org-get-tags-at nil 'local))
9513 (defun org-get-tags-at (&optional pos local)
9514 "Get a list of all headline tags applicable at POS.
9515 POS defaults to point. If tags are inherited, the list contains
9516 the targets in the same sequence as the headlines appear, i.e.
9517 the tags of the current headline come last.
9518 When LOCAL is non-nil, only return tags from the current headline,
9519 ignore inherited ones."
9520 (interactive)
9521 (let (tags ltags lastpos parent)
9522 (save-excursion
9523 (save-restriction
9524 (widen)
9525 (goto-char (or pos (point)))
9526 (save-match-data
9527 (catch 'done
9528 (condition-case nil
9529 (progn
9530 (org-back-to-heading t)
9531 (while (not (equal lastpos (point)))
9532 (setq lastpos (point))
9533 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9534 (setq ltags (org-split-string
9535 (org-match-string-no-properties 1) ":"))
9536 (when parent
9537 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9538 (setq tags (append
9539 (if parent
9540 (org-remove-uniherited-tags ltags)
9541 ltags)
9542 tags)))
9543 (or org-use-tag-inheritance (throw 'done t))
9544 (if local (throw 'done t))
9545 (org-up-heading-all 1)
9546 (setq parent t)))
9547 (error nil)))))
9548 (append (org-remove-uniherited-tags org-file-tags) tags))))
9550 (defun org-add-prop-inherited (s)
9551 (add-text-properties 0 (length s) '(inherited t) s)
9554 (defun org-toggle-tag (tag &optional onoff)
9555 "Toggle the tag TAG for the current line.
9556 If ONOFF is `on' or `off', don't toggle but set to this state."
9557 (let (res current)
9558 (save-excursion
9559 (org-back-to-heading t)
9560 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9561 (point-at-eol) t)
9562 (progn
9563 (setq current (match-string 1))
9564 (replace-match ""))
9565 (setq current ""))
9566 (setq current (nreverse (org-split-string current ":")))
9567 (cond
9568 ((eq onoff 'on)
9569 (setq res t)
9570 (or (member tag current) (push tag current)))
9571 ((eq onoff 'off)
9572 (or (not (member tag current)) (setq current (delete tag current))))
9573 (t (if (member tag current)
9574 (setq current (delete tag current))
9575 (setq res t)
9576 (push tag current))))
9577 (end-of-line 1)
9578 (if current
9579 (progn
9580 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9581 (org-set-tags nil t))
9582 (delete-horizontal-space))
9583 (run-hooks 'org-after-tags-change-hook))
9584 res))
9586 (defun org-align-tags-here (to-col)
9587 ;; Assumes that this is a headline
9588 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9589 (beginning-of-line 1)
9590 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9591 (< pos (match-beginning 2)))
9592 (progn
9593 (setq tags-l (- (match-end 2) (match-beginning 2)))
9594 (goto-char (match-beginning 1))
9595 (insert " ")
9596 (delete-region (point) (1+ (match-beginning 2)))
9597 (setq ncol (max (1+ (current-column))
9598 (1+ col)
9599 (if (> to-col 0)
9600 to-col
9601 (- (abs to-col) tags-l))))
9602 (setq p (point))
9603 (insert (make-string (- ncol (current-column)) ?\ ))
9604 (setq ncol (current-column))
9605 (when indent-tabs-mode (tabify p (point-at-eol)))
9606 (org-move-to-column (min ncol col) t))
9607 (goto-char pos))))
9609 (defun org-set-tags-command (&optional arg just-align)
9610 "Call the set-tags command for the current entry."
9611 (interactive "P")
9612 (if (org-on-heading-p)
9613 (org-set-tags arg just-align)
9614 (save-excursion
9615 (org-back-to-heading t)
9616 (org-set-tags arg just-align))))
9618 (defun org-set-tags (&optional arg just-align)
9619 "Set the tags for the current headline.
9620 With prefix ARG, realign all tags in headings in the current buffer."
9621 (interactive "P")
9622 (let* ((re (concat "^" outline-regexp))
9623 (current (org-get-tags-string))
9624 (col (current-column))
9625 (org-setting-tags t)
9626 table current-tags inherited-tags ; computed below when needed
9627 tags p0 c0 c1 rpl)
9628 (if arg
9629 (save-excursion
9630 (goto-char (point-min))
9631 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9632 (while (re-search-forward re nil t)
9633 (org-set-tags nil t)
9634 (end-of-line 1)))
9635 (message "All tags realigned to column %d" org-tags-column))
9636 (if just-align
9637 (setq tags current)
9638 ;; Get a new set of tags from the user
9639 (save-excursion
9640 (setq table (or org-tag-alist (org-get-buffer-tags))
9641 org-last-tags-completion-table table
9642 current-tags (org-split-string current ":")
9643 inherited-tags (nreverse
9644 (nthcdr (length current-tags)
9645 (nreverse (org-get-tags-at))))
9646 tags
9647 (if (or (eq t org-use-fast-tag-selection)
9648 (and org-use-fast-tag-selection
9649 (delq nil (mapcar 'cdr table))))
9650 (org-fast-tag-selection
9651 current-tags inherited-tags table
9652 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9653 (let ((org-add-colon-after-tag-completion t))
9654 (org-trim
9655 (org-without-partial-completion
9656 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9657 nil nil current 'org-tags-history)))))))
9658 (while (string-match "[-+&]+" tags)
9659 ;; No boolean logic, just a list
9660 (setq tags (replace-match ":" t t tags))))
9662 (if (string-match "\\`[\t ]*\\'" tags)
9663 (setq tags "")
9664 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9665 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9667 ;; Insert new tags at the correct column
9668 (beginning-of-line 1)
9669 (cond
9670 ((and (equal current "") (equal tags "")))
9671 ((re-search-forward
9672 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9673 (point-at-eol) t)
9674 (if (equal tags "")
9675 (setq rpl "")
9676 (goto-char (match-beginning 0))
9677 (setq c0 (current-column) p0 (point)
9678 c1 (max (1+ c0) (if (> org-tags-column 0)
9679 org-tags-column
9680 (- (- org-tags-column) (length tags))))
9681 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9682 (replace-match rpl t t)
9683 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9684 tags)
9685 (t (error "Tags alignment failed")))
9686 (org-move-to-column col)
9687 (unless just-align
9688 (run-hooks 'org-after-tags-change-hook)))))
9690 (defun org-change-tag-in-region (beg end tag off)
9691 "Add or remove TAG for each entry in the region.
9692 This works in the agenda, and also in an org-mode buffer."
9693 (interactive
9694 (list (region-beginning) (region-end)
9695 (let ((org-last-tags-completion-table
9696 (if (org-mode-p)
9697 (org-get-buffer-tags)
9698 (org-global-tags-completion-table))))
9699 (org-ido-completing-read
9700 "Tag: " 'org-tags-completion-function nil nil nil
9701 'org-tags-history))
9702 (progn
9703 (message "[s]et or [r]emove? ")
9704 (equal (read-char-exclusive) ?r))))
9705 (if (fboundp 'deactivate-mark) (deactivate-mark))
9706 (let ((agendap (equal major-mode 'org-agenda-mode))
9707 l1 l2 m buf pos newhead (cnt 0))
9708 (goto-char end)
9709 (setq l2 (1- (org-current-line)))
9710 (goto-char beg)
9711 (setq l1 (org-current-line))
9712 (loop for l from l1 to l2 do
9713 (goto-line l)
9714 (setq m (get-text-property (point) 'org-hd-marker))
9715 (when (or (and (org-mode-p) (org-on-heading-p))
9716 (and agendap m))
9717 (setq buf (if agendap (marker-buffer m) (current-buffer))
9718 pos (if agendap m (point)))
9719 (with-current-buffer buf
9720 (save-excursion
9721 (save-restriction
9722 (goto-char pos)
9723 (setq cnt (1+ cnt))
9724 (org-toggle-tag tag (if off 'off 'on))
9725 (setq newhead (org-get-heading)))))
9726 (and agendap (org-agenda-change-all-lines newhead m))))
9727 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9729 (defun org-tags-completion-function (string predicate &optional flag)
9730 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9731 (confirm (lambda (x) (stringp (car x)))))
9732 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9733 (setq s1 (match-string 1 string)
9734 s2 (match-string 2 string))
9735 (setq s1 "" s2 string))
9736 (cond
9737 ((eq flag nil)
9738 ;; try completion
9739 (setq rtn (try-completion s2 ctable confirm))
9740 (if (stringp rtn)
9741 (setq rtn
9742 (concat s1 s2 (substring rtn (length s2))
9743 (if (and org-add-colon-after-tag-completion
9744 (assoc rtn ctable))
9745 ":" ""))))
9746 rtn)
9747 ((eq flag t)
9748 ;; all-completions
9749 (all-completions s2 ctable confirm)
9751 ((eq flag 'lambda)
9752 ;; exact match?
9753 (assoc s2 ctable)))
9756 (defun org-fast-tag-insert (kwd tags face &optional end)
9757 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9758 (insert (format "%-12s" (concat kwd ":"))
9759 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9760 (or end "")))
9762 (defun org-fast-tag-show-exit (flag)
9763 (save-excursion
9764 (goto-line 3)
9765 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9766 (replace-match ""))
9767 (when flag
9768 (end-of-line 1)
9769 (org-move-to-column (- (window-width) 19) t)
9770 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9772 (defun org-set-current-tags-overlay (current prefix)
9773 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9774 (if (featurep 'xemacs)
9775 (org-overlay-display org-tags-overlay (concat prefix s)
9776 'secondary-selection)
9777 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9778 (org-overlay-display org-tags-overlay (concat prefix s)))))
9780 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9781 "Fast tag selection with single keys.
9782 CURRENT is the current list of tags in the headline, INHERITED is the
9783 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9784 possibly with grouping information. TODO-TABLE is a similar table with
9785 TODO keywords, should these have keys assigned to them.
9786 If the keys are nil, a-z are automatically assigned.
9787 Returns the new tags string, or nil to not change the current settings."
9788 (let* ((fulltable (append table todo-table))
9789 (maxlen (apply 'max (mapcar
9790 (lambda (x)
9791 (if (stringp (car x)) (string-width (car x)) 0))
9792 fulltable)))
9793 (buf (current-buffer))
9794 (expert (eq org-fast-tag-selection-single-key 'expert))
9795 (buffer-tags nil)
9796 (fwidth (+ maxlen 3 1 3))
9797 (ncol (/ (- (window-width) 4) fwidth))
9798 (i-face 'org-done)
9799 (c-face 'org-todo)
9800 tg cnt e c char c1 c2 ntable tbl rtn
9801 ov-start ov-end ov-prefix
9802 (exit-after-next org-fast-tag-selection-single-key)
9803 (done-keywords org-done-keywords)
9804 groups ingroup)
9805 (save-excursion
9806 (beginning-of-line 1)
9807 (if (looking-at
9808 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9809 (setq ov-start (match-beginning 1)
9810 ov-end (match-end 1)
9811 ov-prefix "")
9812 (setq ov-start (1- (point-at-eol))
9813 ov-end (1+ ov-start))
9814 (skip-chars-forward "^\n\r")
9815 (setq ov-prefix
9816 (concat
9817 (buffer-substring (1- (point)) (point))
9818 (if (> (current-column) org-tags-column)
9820 (make-string (- org-tags-column (current-column)) ?\ ))))))
9821 (org-move-overlay org-tags-overlay ov-start ov-end)
9822 (save-window-excursion
9823 (if expert
9824 (set-buffer (get-buffer-create " *Org tags*"))
9825 (delete-other-windows)
9826 (split-window-vertically)
9827 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9828 (erase-buffer)
9829 (org-set-local 'org-done-keywords done-keywords)
9830 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9831 (org-fast-tag-insert "Current" current c-face "\n\n")
9832 (org-fast-tag-show-exit exit-after-next)
9833 (org-set-current-tags-overlay current ov-prefix)
9834 (setq tbl fulltable char ?a cnt 0)
9835 (while (setq e (pop tbl))
9836 (cond
9837 ((equal e '(:startgroup))
9838 (push '() groups) (setq ingroup t)
9839 (when (not (= cnt 0))
9840 (setq cnt 0)
9841 (insert "\n"))
9842 (insert "{ "))
9843 ((equal e '(:endgroup))
9844 (setq ingroup nil cnt 0)
9845 (insert "}\n"))
9847 (setq tg (car e) c2 nil)
9848 (if (cdr e)
9849 (setq c (cdr e))
9850 ;; automatically assign a character.
9851 (setq c1 (string-to-char
9852 (downcase (substring
9853 tg (if (= (string-to-char tg) ?@) 1 0)))))
9854 (if (or (rassoc c1 ntable) (rassoc c1 table))
9855 (while (or (rassoc char ntable) (rassoc char table))
9856 (setq char (1+ char)))
9857 (setq c2 c1))
9858 (setq c (or c2 char)))
9859 (if ingroup (push tg (car groups)))
9860 (setq tg (org-add-props tg nil 'face
9861 (cond
9862 ((not (assoc tg table))
9863 (org-get-todo-face tg))
9864 ((member tg current) c-face)
9865 ((member tg inherited) i-face)
9866 (t nil))))
9867 (if (and (= cnt 0) (not ingroup)) (insert " "))
9868 (insert "[" c "] " tg (make-string
9869 (- fwidth 4 (length tg)) ?\ ))
9870 (push (cons tg c) ntable)
9871 (when (= (setq cnt (1+ cnt)) ncol)
9872 (insert "\n")
9873 (if ingroup (insert " "))
9874 (setq cnt 0)))))
9875 (setq ntable (nreverse ntable))
9876 (insert "\n")
9877 (goto-char (point-min))
9878 (if (not expert) (org-fit-window-to-buffer))
9879 (setq rtn
9880 (catch 'exit
9881 (while t
9882 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9883 (if groups " [!] no groups" " [!]groups")
9884 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9885 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9886 (cond
9887 ((= c ?\r) (throw 'exit t))
9888 ((= c ?!)
9889 (setq groups (not groups))
9890 (goto-char (point-min))
9891 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9892 ((= c ?\C-c)
9893 (if (not expert)
9894 (org-fast-tag-show-exit
9895 (setq exit-after-next (not exit-after-next)))
9896 (setq expert nil)
9897 (delete-other-windows)
9898 (split-window-vertically)
9899 (org-switch-to-buffer-other-window " *Org tags*")
9900 (org-fit-window-to-buffer)))
9901 ((or (= c ?\C-g)
9902 (and (= c ?q) (not (rassoc c ntable))))
9903 (org-detach-overlay org-tags-overlay)
9904 (setq quit-flag t))
9905 ((= c ?\ )
9906 (setq current nil)
9907 (if exit-after-next (setq exit-after-next 'now)))
9908 ((= c ?\t)
9909 (condition-case nil
9910 (setq tg (org-ido-completing-read
9911 "Tag: "
9912 (or buffer-tags
9913 (with-current-buffer buf
9914 (org-get-buffer-tags)))))
9915 (quit (setq tg "")))
9916 (when (string-match "\\S-" tg)
9917 (add-to-list 'buffer-tags (list tg))
9918 (if (member tg current)
9919 (setq current (delete tg current))
9920 (push tg current)))
9921 (if exit-after-next (setq exit-after-next 'now)))
9922 ((setq e (rassoc c todo-table) tg (car e))
9923 (with-current-buffer buf
9924 (save-excursion (org-todo tg)))
9925 (if exit-after-next (setq exit-after-next 'now)))
9926 ((setq e (rassoc c ntable) tg (car e))
9927 (if (member tg current)
9928 (setq current (delete tg current))
9929 (loop for g in groups do
9930 (if (member tg g)
9931 (mapc (lambda (x)
9932 (setq current (delete x current)))
9933 g)))
9934 (push tg current))
9935 (if exit-after-next (setq exit-after-next 'now))))
9937 ;; Create a sorted list
9938 (setq current
9939 (sort current
9940 (lambda (a b)
9941 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9942 (if (eq exit-after-next 'now) (throw 'exit t))
9943 (goto-char (point-min))
9944 (beginning-of-line 2)
9945 (delete-region (point) (point-at-eol))
9946 (org-fast-tag-insert "Current" current c-face)
9947 (org-set-current-tags-overlay current ov-prefix)
9948 (while (re-search-forward
9949 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9950 (setq tg (match-string 1))
9951 (add-text-properties
9952 (match-beginning 1) (match-end 1)
9953 (list 'face
9954 (cond
9955 ((member tg current) c-face)
9956 ((member tg inherited) i-face)
9957 (t (get-text-property (match-beginning 1) 'face))))))
9958 (goto-char (point-min)))))
9959 (org-detach-overlay org-tags-overlay)
9960 (if rtn
9961 (mapconcat 'identity current ":")
9962 nil))))
9964 (defun org-get-tags-string ()
9965 "Get the TAGS string in the current headline."
9966 (unless (org-on-heading-p t)
9967 (error "Not on a heading"))
9968 (save-excursion
9969 (beginning-of-line 1)
9970 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9971 (org-match-string-no-properties 1)
9972 "")))
9974 (defun org-get-tags ()
9975 "Get the list of tags specified in the current headline."
9976 (org-split-string (org-get-tags-string) ":"))
9978 (defun org-get-buffer-tags ()
9979 "Get a table of all tags used in the buffer, for completion."
9980 (let (tags)
9981 (save-excursion
9982 (goto-char (point-min))
9983 (while (re-search-forward
9984 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9985 (when (equal (char-after (point-at-bol 0)) ?*)
9986 (mapc (lambda (x) (add-to-list 'tags x))
9987 (org-split-string (org-match-string-no-properties 1) ":")))))
9988 (mapcar 'list tags)))
9990 ;;;; The mapping API
9992 ;;;###autoload
9993 (defun org-map-entries (func &optional match scope &rest skip)
9994 "Call FUNC at each headline selected by MATCH in SCOPE.
9996 FUNC is a function or a lisp form. The function will be called without
9997 arguments, with the cursor positioned at the beginning of the headline.
9998 The return values of all calls to the function will be collected and
9999 returned as a list.
10001 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10002 Only headlines that are matched by this query will be considered during
10003 the iteration. When MATCH is nil or t, all headlines will be
10004 visited by the iteration.
10006 SCOPE determines the scope of this command. It can be any of:
10008 nil The current buffer, respecting the restriction if any
10009 tree The subtree started with the entry at point
10010 file The current buffer, without restriction
10011 file-with-archives
10012 The current buffer, and any archives associated with it
10013 agenda All agenda files
10014 agenda-with-archives
10015 All agenda files with any archive files associated with them
10016 \(file1 file2 ...)
10017 If this is a list, all files in the list will be scanned
10019 The remaining args are treated as settings for the skipping facilities of
10020 the scanner. The following items can be given here:
10022 archive skip trees with the archive tag.
10023 comment skip trees with the COMMENT keyword
10024 function or Emacs Lisp form:
10025 will be used as value for `org-agenda-skip-function', so whenever
10026 the the function returns t, FUNC will not be called for that
10027 entry and search will continue from the point where the
10028 function leaves it."
10029 (let* ((org-agenda-archives-mode nil) ; just to make sure
10030 (org-agenda-skip-archived-trees (memq 'archive skip))
10031 (org-agenda-skip-comment-trees (memq 'comment skip))
10032 (org-agenda-skip-function
10033 (car (org-delete-all '(comment archive) skip)))
10034 (org-tags-match-list-sublevels t)
10035 matcher pos file res
10036 org-todo-keywords-for-agenda
10037 org-done-keywords-for-agenda
10038 org-todo-keyword-alist-for-agenda
10039 org-tag-alist-for-agenda)
10041 (cond
10042 ((eq match t) (setq matcher t))
10043 ((eq match nil) (setq matcher t))
10044 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10046 (when (eq scope 'tree)
10047 (org-back-to-heading t)
10048 (org-narrow-to-subtree)
10049 (setq scope nil))
10051 (if (not scope)
10052 (progn
10053 (org-prepare-agenda-buffers
10054 (list (buffer-file-name (current-buffer))))
10055 (org-scan-tags func matcher))
10056 ;; Get the right scope
10057 (setq pos (point))
10058 (cond
10059 ((and scope (listp scope) (symbolp (car scope)))
10060 (setq scope (eval scope)))
10061 ((eq scope 'agenda)
10062 (setq scope (org-agenda-files t)))
10063 ((eq scope 'agenda-with-archives)
10064 (setq scope (org-agenda-files t))
10065 (setq scope (org-add-archive-files scope)))
10066 ((eq scope 'file)
10067 (setq scope (list (buffer-file-name))))
10068 ((eq scope 'file-with-archives)
10069 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10070 (org-prepare-agenda-buffers scope)
10071 (while (setq file (pop scope))
10072 (with-current-buffer (org-find-base-buffer-visiting file)
10073 (save-excursion
10074 (save-restriction
10075 (widen)
10076 (goto-char (point-min))
10077 (setq res (append res (org-scan-tags func matcher)))))))
10078 res)))
10080 ;;;; Properties
10082 ;;; Setting and retrieving properties
10084 (defconst org-special-properties
10085 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10086 "TIMESTAMP" "TIMESTAMP_IA")
10087 "The special properties valid in Org-mode.
10089 These are properties that are not defined in the property drawer,
10090 but in some other way.")
10092 (defconst org-default-properties
10093 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10094 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10095 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10096 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10097 "Some properties that are used by Org-mode for various purposes.
10098 Being in this list makes sure that they are offered for completion.")
10100 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10101 "Regular expression matching the first line of a property drawer.")
10103 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10104 "Regular expression matching the first line of a property drawer.")
10106 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10107 "Regular expression matching the first line of a property drawer.")
10109 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10110 "Regular expression matching the first line of a property drawer.")
10112 (defconst org-property-drawer-re
10113 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10114 org-property-end-re "\\)\n?")
10115 "Matches an entire property drawer.")
10117 (defconst org-clock-drawer-re
10118 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10119 org-property-end-re "\\)\n?")
10120 "Matches an entire clock drawer.")
10122 (defun org-property-action ()
10123 "Do an action on properties."
10124 (interactive)
10125 (let (c)
10126 (org-at-property-p)
10127 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10128 (setq c (read-char-exclusive))
10129 (cond
10130 ((equal c ?s)
10131 (call-interactively 'org-set-property))
10132 ((equal c ?d)
10133 (call-interactively 'org-delete-property))
10134 ((equal c ?D)
10135 (call-interactively 'org-delete-property-globally))
10136 ((equal c ?c)
10137 (call-interactively 'org-compute-property-at-point))
10138 (t (error "No such property action %c" c)))))
10140 (defun org-at-property-p ()
10141 "Is the cursor in a property line?"
10142 ;; FIXME: Does not check if we are actually in the drawer.
10143 ;; FIXME: also returns true on any drawers.....
10144 ;; This is used by C-c C-c for property action.
10145 (save-excursion
10146 (beginning-of-line 1)
10147 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10149 (defun org-get-property-block (&optional beg end force)
10150 "Return the (beg . end) range of the body of the property drawer.
10151 BEG and END can be beginning and end of subtree, if not given
10152 they will be found.
10153 If the drawer does not exist and FORCE is non-nil, create the drawer."
10154 (catch 'exit
10155 (save-excursion
10156 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10157 (end (or end (progn (outline-next-heading) (point)))))
10158 (goto-char beg)
10159 (if (re-search-forward org-property-start-re end t)
10160 (setq beg (1+ (match-end 0)))
10161 (if force
10162 (save-excursion
10163 (org-insert-property-drawer)
10164 (setq end (progn (outline-next-heading) (point))))
10165 (throw 'exit nil))
10166 (goto-char beg)
10167 (if (re-search-forward org-property-start-re end t)
10168 (setq beg (1+ (match-end 0)))))
10169 (if (re-search-forward org-property-end-re end t)
10170 (setq end (match-beginning 0))
10171 (or force (throw 'exit nil))
10172 (goto-char beg)
10173 (setq end beg)
10174 (org-indent-line-function)
10175 (insert ":END:\n"))
10176 (cons beg end)))))
10178 (defun org-entry-properties (&optional pom which)
10179 "Get all properties of the entry at point-or-marker POM.
10180 This includes the TODO keyword, the tags, time strings for deadline,
10181 scheduled, and clocking, and any additional properties defined in the
10182 entry. The return value is an alist, keys may occur multiple times
10183 if the property key was used several times.
10184 POM may also be nil, in which case the current entry is used.
10185 If WHICH is nil or `all', get all properties. If WHICH is
10186 `special' or `standard', only get that subclass."
10187 (setq which (or which 'all))
10188 (org-with-point-at pom
10189 (let ((clockstr (substring org-clock-string 0 -1))
10190 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10191 beg end range props sum-props key value string clocksum)
10192 (save-excursion
10193 (when (condition-case nil (org-back-to-heading t) (error nil))
10194 (setq beg (point))
10195 (setq sum-props (get-text-property (point) 'org-summaries))
10196 (setq clocksum (get-text-property (point) :org-clock-minutes))
10197 (outline-next-heading)
10198 (setq end (point))
10199 (when (memq which '(all special))
10200 ;; Get the special properties, like TODO and tags
10201 (goto-char beg)
10202 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10203 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10204 (when (looking-at org-priority-regexp)
10205 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10206 (when (and (setq value (org-get-tags-string))
10207 (string-match "\\S-" value))
10208 (push (cons "TAGS" value) props))
10209 (when (setq value (org-get-tags-at))
10210 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10211 props))
10212 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10213 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10214 string (if (equal key clockstr)
10215 (org-no-properties
10216 (org-trim
10217 (buffer-substring
10218 (match-beginning 3) (goto-char (point-at-eol)))))
10219 (substring (org-match-string-no-properties 3) 1 -1)))
10220 (unless key
10221 (if (= (char-after (match-beginning 3)) ?\[)
10222 (setq key "TIMESTAMP_IA")
10223 (setq key "TIMESTAMP")))
10224 (when (or (equal key clockstr) (not (assoc key props)))
10225 (push (cons key string) props)))
10229 (when (memq which '(all standard))
10230 ;; Get the standard properties, like :PORP: ...
10231 (setq range (org-get-property-block beg end))
10232 (when range
10233 (goto-char (car range))
10234 (while (re-search-forward
10235 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10236 (cdr range) t)
10237 (setq key (org-match-string-no-properties 1)
10238 value (org-trim (or (org-match-string-no-properties 2) "")))
10239 (unless (member key excluded)
10240 (push (cons key (or value "")) props)))))
10241 (if clocksum
10242 (push (cons "CLOCKSUM"
10243 (org-columns-number-to-string (/ (float clocksum) 60.)
10244 'add_times))
10245 props))
10246 (unless (assoc "CATEGORY" props)
10247 (setq value (or (org-get-category)
10248 (progn (org-refresh-category-properties)
10249 (org-get-category))))
10250 (push (cons "CATEGORY" value) props))
10251 (append sum-props (nreverse props)))))))
10253 (defun org-entry-get (pom property &optional inherit)
10254 "Get value of PROPERTY for entry at point-or-marker POM.
10255 If INHERIT is non-nil and the entry does not have the property,
10256 then also check higher levels of the hierarchy.
10257 If INHERIT is the symbol `selective', use inheritance only if the setting
10258 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10259 If the property is present but empty, the return value is the empty string.
10260 If the property is not present at all, nil is returned."
10261 (org-with-point-at pom
10262 (if (and inherit (if (eq inherit 'selective)
10263 (org-property-inherit-p property)
10265 (org-entry-get-with-inheritance property)
10266 (if (member property org-special-properties)
10267 ;; We need a special property. Use brute force, get all properties.
10268 (cdr (assoc property (org-entry-properties nil 'special)))
10269 (let ((range (org-get-property-block)))
10270 (if (and range
10271 (goto-char (car range))
10272 (re-search-forward
10273 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10274 (cdr range) t))
10275 ;; Found the property, return it.
10276 (if (match-end 1)
10277 (org-match-string-no-properties 1)
10278 "")))))))
10280 (defun org-property-or-variable-value (var &optional inherit)
10281 "Check if there is a property fixing the value of VAR.
10282 If yes, return this value. If not, return the current value of the variable."
10283 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10284 (if (and prop (stringp prop) (string-match "\\S-" prop))
10285 (read prop)
10286 (symbol-value var))))
10288 (defun org-entry-delete (pom property)
10289 "Delete the property PROPERTY from entry at point-or-marker POM."
10290 (org-with-point-at pom
10291 (if (member property org-special-properties)
10292 nil ; cannot delete these properties.
10293 (let ((range (org-get-property-block)))
10294 (if (and range
10295 (goto-char (car range))
10296 (re-search-forward
10297 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10298 (cdr range) t))
10299 (progn
10300 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10302 nil)))))
10304 ;; Multi-values properties are properties that contain multiple values
10305 ;; These values are assumed to be single words, separated by whitespace.
10306 (defun org-entry-add-to-multivalued-property (pom property value)
10307 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10308 (let* ((old (org-entry-get pom property))
10309 (values (and old (org-split-string old "[ \t]"))))
10310 (setq value (org-entry-protect-space value))
10311 (unless (member value values)
10312 (setq values (cons value values))
10313 (org-entry-put pom property
10314 (mapconcat 'identity values " ")))))
10316 (defun org-entry-remove-from-multivalued-property (pom property value)
10317 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10318 (let* ((old (org-entry-get pom property))
10319 (values (and old (org-split-string old "[ \t]"))))
10320 (setq value (org-entry-protect-space value))
10321 (when (member value values)
10322 (setq values (delete value values))
10323 (org-entry-put pom property
10324 (mapconcat 'identity values " ")))))
10326 (defun org-entry-member-in-multivalued-property (pom property value)
10327 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10328 (let* ((old (org-entry-get pom property))
10329 (values (and old (org-split-string old "[ \t]"))))
10330 (setq value (org-entry-protect-space value))
10331 (member value values)))
10333 (defun org-entry-get-multivalued-property (pom property)
10334 "Return a list of values in a multivalued property."
10335 (let* ((value (org-entry-get pom property))
10336 (values (and value (org-split-string value "[ \t]"))))
10337 (mapcar 'org-entry-restore-space values)))
10339 (defun org-entry-put-multivalued-property (pom property &rest values)
10340 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10341 VALUES should be a list of strings. Spaces will be protected."
10342 (org-entry-put pom property
10343 (mapconcat 'org-entry-protect-space values " "))
10344 (let* ((value (org-entry-get pom property))
10345 (values (and value (org-split-string value "[ \t]"))))
10346 (mapcar 'org-entry-restore-space values)))
10348 (defun org-entry-protect-space (s)
10349 "Protect spaces and newline in string S."
10350 (while (string-match " " s)
10351 (setq s (replace-match "%20" t t s)))
10352 (while (string-match "\n" s)
10353 (setq s (replace-match "%0A" t t s)))
10356 (defun org-entry-restore-space (s)
10357 "Restore spaces and newline in string S."
10358 (while (string-match "%20" s)
10359 (setq s (replace-match " " t t s)))
10360 (while (string-match "%0A" s)
10361 (setq s (replace-match "\n" t t s)))
10364 (defvar org-entry-property-inherited-from (make-marker)
10365 "Marker pointing to the entry from where a property was inherited.
10366 Each call to `org-entry-get-with-inheritance' will set this marker to the
10367 location of the entry where the inheritance search matched. If there was
10368 no match, the marker will point nowhere.
10369 Note that also `org-entry-get' calls this function, if the INHERIT flag
10370 is set.")
10372 (defun org-entry-get-with-inheritance (property)
10373 "Get entry property, and search higher levels if not present."
10374 (move-marker org-entry-property-inherited-from nil)
10375 (let (tmp)
10376 (save-excursion
10377 (save-restriction
10378 (widen)
10379 (catch 'ex
10380 (while t
10381 (when (setq tmp (org-entry-get nil property))
10382 (org-back-to-heading t)
10383 (move-marker org-entry-property-inherited-from (point))
10384 (throw 'ex tmp))
10385 (or (org-up-heading-safe) (throw 'ex nil)))))
10386 (or tmp
10387 (cdr (assoc property org-file-properties))
10388 (cdr (assoc property org-global-properties))
10389 (cdr (assoc property org-global-properties-fixed))))))
10391 (defun org-entry-put (pom property value)
10392 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10393 (org-with-point-at pom
10394 (org-back-to-heading t)
10395 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10396 range)
10397 (cond
10398 ((equal property "TODO")
10399 (when (and (stringp value) (string-match "\\S-" value)
10400 (not (member value org-todo-keywords-1)))
10401 (error "\"%s\" is not a valid TODO state" value))
10402 (if (or (not value)
10403 (not (string-match "\\S-" value)))
10404 (setq value 'none))
10405 (org-todo value)
10406 (org-set-tags nil 'align))
10407 ((equal property "PRIORITY")
10408 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10409 (string-to-char value) ?\ ))
10410 (org-set-tags nil 'align))
10411 ((equal property "SCHEDULED")
10412 (if (re-search-forward org-scheduled-time-regexp end t)
10413 (cond
10414 ((eq value 'earlier) (org-timestamp-change -1 'day))
10415 ((eq value 'later) (org-timestamp-change 1 'day))
10416 (t (call-interactively 'org-schedule)))
10417 (call-interactively 'org-schedule)))
10418 ((equal property "DEADLINE")
10419 (if (re-search-forward org-deadline-time-regexp end t)
10420 (cond
10421 ((eq value 'earlier) (org-timestamp-change -1 'day))
10422 ((eq value 'later) (org-timestamp-change 1 'day))
10423 (t (call-interactively 'org-deadline)))
10424 (call-interactively 'org-deadline)))
10425 ((member property org-special-properties)
10426 (error "The %s property can not yet be set with `org-entry-put'"
10427 property))
10428 (t ; a non-special property
10429 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10430 (setq range (org-get-property-block beg end 'force))
10431 (goto-char (car range))
10432 (if (re-search-forward
10433 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10434 (progn
10435 (delete-region (match-beginning 1) (match-end 1))
10436 (goto-char (match-beginning 1)))
10437 (goto-char (cdr range))
10438 (insert "\n")
10439 (backward-char 1)
10440 (org-indent-line-function)
10441 (insert ":" property ":"))
10442 (and value (insert " " value))
10443 (org-indent-line-function)))))))
10445 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10446 "Get all property keys in the current buffer.
10447 With INCLUDE-SPECIALS, also list the special properties that reflect things
10448 like tags and TODO state.
10449 With INCLUDE-DEFAULTS, also include properties that has special meaning
10450 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10451 With INCLUDE-COLUMNS, also include property names given in COLUMN
10452 formats in the current buffer."
10453 (let (rtn range cfmt cols s p)
10454 (save-excursion
10455 (save-restriction
10456 (widen)
10457 (goto-char (point-min))
10458 (while (re-search-forward org-property-start-re nil t)
10459 (setq range (org-get-property-block))
10460 (goto-char (car range))
10461 (while (re-search-forward
10462 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10463 (cdr range) t)
10464 (add-to-list 'rtn (org-match-string-no-properties 1)))
10465 (outline-next-heading))))
10467 (when include-specials
10468 (setq rtn (append org-special-properties rtn)))
10470 (when include-defaults
10471 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10473 (when include-columns
10474 (save-excursion
10475 (save-restriction
10476 (widen)
10477 (goto-char (point-min))
10478 (while (re-search-forward
10479 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10480 nil t)
10481 (setq cfmt (match-string 2) s 0)
10482 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10483 cfmt s)
10484 (setq s (match-end 0)
10485 p (match-string 1 cfmt))
10486 (unless (or (equal p "ITEM")
10487 (member p org-special-properties))
10488 (add-to-list 'rtn (match-string 1 cfmt))))))))
10490 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10492 (defun org-property-values (key)
10493 "Return a list of all values of property KEY."
10494 (save-excursion
10495 (save-restriction
10496 (widen)
10497 (goto-char (point-min))
10498 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10499 values)
10500 (while (re-search-forward re nil t)
10501 (add-to-list 'values (org-trim (match-string 1))))
10502 (delete "" values)))))
10504 (defun org-insert-property-drawer ()
10505 "Insert a property drawer into the current entry."
10506 (interactive)
10507 (org-back-to-heading t)
10508 (looking-at outline-regexp)
10509 (let ((indent (- (match-end 0)(match-beginning 0)))
10510 (beg (point))
10511 (re (concat "^[ \t]*" org-keyword-time-regexp))
10512 end hiddenp)
10513 (outline-next-heading)
10514 (setq end (point))
10515 (goto-char beg)
10516 (while (re-search-forward re end t))
10517 (setq hiddenp (org-invisible-p))
10518 (end-of-line 1)
10519 (and (equal (char-after) ?\n) (forward-char 1))
10520 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10521 (beginning-of-line 2))
10522 (org-skip-over-state-notes)
10523 (skip-chars-backward " \t\n\r")
10524 (if (eq (char-before) ?*) (forward-char 1))
10525 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10526 (beginning-of-line 0)
10527 (org-indent-to-column indent)
10528 (beginning-of-line 2)
10529 (org-indent-to-column indent)
10530 (beginning-of-line 0)
10531 (if hiddenp
10532 (save-excursion
10533 (org-back-to-heading t)
10534 (hide-entry))
10535 (org-flag-drawer t))))
10537 (defun org-set-property (property value)
10538 "In the current entry, set PROPERTY to VALUE.
10539 When called interactively, this will prompt for a property name, offering
10540 completion on existing and default properties. And then it will prompt
10541 for a value, offering completion either on allowed values (via an inherited
10542 xxx_ALL property) or on existing values in other instances of this property
10543 in the current file."
10544 (interactive
10545 (let* ((completion-ignore-case t)
10546 (keys (org-buffer-property-keys nil t t))
10547 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10548 (prop (if (member prop0 keys)
10549 prop0
10550 (or (cdr (assoc (downcase prop0)
10551 (mapcar (lambda (x) (cons (downcase x) x))
10552 keys)))
10553 prop0)))
10554 (cur (org-entry-get nil prop))
10555 (allowed (org-property-get-allowed-values nil prop 'table))
10556 (existing (mapcar 'list (org-property-values prop)))
10557 (val (if allowed
10558 (org-completing-read "Value: " allowed nil 'req-match)
10559 (org-completing-read
10560 (concat "Value" (if (and cur (string-match "\\S-" cur))
10561 (concat "[" cur "]") "")
10562 ": ")
10563 existing nil nil "" nil cur))))
10564 (list prop (if (equal val "") cur val))))
10565 (unless (equal (org-entry-get nil property) value)
10566 (org-entry-put nil property value)))
10568 (defun org-delete-property (property)
10569 "In the current entry, delete PROPERTY."
10570 (interactive
10571 (let* ((completion-ignore-case t)
10572 (prop (org-ido-completing-read
10573 "Property: " (org-entry-properties nil 'standard))))
10574 (list prop)))
10575 (message "Property %s %s" property
10576 (if (org-entry-delete nil property)
10577 "deleted"
10578 "was not present in the entry")))
10580 (defun org-delete-property-globally (property)
10581 "Remove PROPERTY globally, from all entries."
10582 (interactive
10583 (let* ((completion-ignore-case t)
10584 (prop (org-ido-completing-read
10585 "Globally remove property: "
10586 (mapcar 'list (org-buffer-property-keys)))))
10587 (list prop)))
10588 (save-excursion
10589 (save-restriction
10590 (widen)
10591 (goto-char (point-min))
10592 (let ((cnt 0))
10593 (while (re-search-forward
10594 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10595 nil t)
10596 (setq cnt (1+ cnt))
10597 (replace-match ""))
10598 (message "Property \"%s\" removed from %d entries" property cnt)))))
10600 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10602 (defun org-compute-property-at-point ()
10603 "Compute the property at point.
10604 This looks for an enclosing column format, extracts the operator and
10605 then applies it to the property in the column format's scope."
10606 (interactive)
10607 (unless (org-at-property-p)
10608 (error "Not at a property"))
10609 (let ((prop (org-match-string-no-properties 2)))
10610 (org-columns-get-format-and-top-level)
10611 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10612 (error "No operator defined for property %s" prop))
10613 (org-columns-compute prop)))
10615 (defun org-property-get-allowed-values (pom property &optional table)
10616 "Get allowed values for the property PROPERTY.
10617 When TABLE is non-nil, return an alist that can directly be used for
10618 completion."
10619 (let (vals)
10620 (cond
10621 ((equal property "TODO")
10622 (setq vals (org-with-point-at pom
10623 (append org-todo-keywords-1 '("")))))
10624 ((equal property "PRIORITY")
10625 (let ((n org-lowest-priority))
10626 (while (>= n org-highest-priority)
10627 (push (char-to-string n) vals)
10628 (setq n (1- n)))))
10629 ((member property org-special-properties))
10631 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10633 (when (and vals (string-match "\\S-" vals))
10634 (setq vals (car (read-from-string (concat "(" vals ")"))))
10635 (setq vals (mapcar (lambda (x)
10636 (cond ((stringp x) x)
10637 ((numberp x) (number-to-string x))
10638 ((symbolp x) (symbol-name x))
10639 (t "???")))
10640 vals)))))
10641 (if table (mapcar 'list vals) vals)))
10643 (defun org-property-previous-allowed-value (&optional previous)
10644 "Switch to the next allowed value for this property."
10645 (interactive)
10646 (org-property-next-allowed-value t))
10648 (defun org-property-next-allowed-value (&optional previous)
10649 "Switch to the next allowed value for this property."
10650 (interactive)
10651 (unless (org-at-property-p)
10652 (error "Not at a property"))
10653 (let* ((key (match-string 2))
10654 (value (match-string 3))
10655 (allowed (or (org-property-get-allowed-values (point) key)
10656 (and (member value '("[ ]" "[-]" "[X]"))
10657 '("[ ]" "[X]"))))
10658 nval)
10659 (unless allowed
10660 (error "Allowed values for this property have not been defined"))
10661 (if previous (setq allowed (reverse allowed)))
10662 (if (member value allowed)
10663 (setq nval (car (cdr (member value allowed)))))
10664 (setq nval (or nval (car allowed)))
10665 (if (equal nval value)
10666 (error "Only one allowed value for this property"))
10667 (org-at-property-p)
10668 (replace-match (concat " :" key ": " nval) t t)
10669 (org-indent-line-function)
10670 (beginning-of-line 1)
10671 (skip-chars-forward " \t")))
10673 (defun org-find-entry-with-id (ident)
10674 "Locate the entry that contains the ID property with exact value IDENT.
10675 IDENT can be a string, a symbol or a number, this function will search for
10676 the string representation of it.
10677 Return the position where this entry starts, or nil if there is no such entry."
10678 (interactive "sID: ")
10679 (let ((id (cond
10680 ((stringp ident) ident)
10681 ((symbol-name ident) (symbol-name ident))
10682 ((numberp ident) (number-to-string ident))
10683 (t (error "IDENT %s must be a string, symbol or number" ident))))
10684 (case-fold-search nil))
10685 (save-excursion
10686 (save-restriction
10687 (widen)
10688 (goto-char (point-min))
10689 (when (re-search-forward
10690 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10691 nil t)
10692 (org-back-to-heading)
10693 (point))))))
10695 ;;;; Timestamps
10697 (defvar org-last-changed-timestamp nil)
10698 (defvar org-last-inserted-timestamp nil
10699 "The last time stamp inserted with `org-insert-time-stamp'.")
10700 (defvar org-time-was-given) ; dynamically scoped parameter
10701 (defvar org-end-time-was-given) ; dynamically scoped parameter
10702 (defvar org-ts-what) ; dynamically scoped parameter
10704 (defun org-time-stamp (arg &optional inactive)
10705 "Prompt for a date/time and insert a time stamp.
10706 If the user specifies a time like HH:MM, or if this command is called
10707 with a prefix argument, the time stamp will contain date and time.
10708 Otherwise, only the date will be included. All parts of a date not
10709 specified by the user will be filled in from the current date/time.
10710 So if you press just return without typing anything, the time stamp
10711 will represent the current date/time. If there is already a timestamp
10712 at the cursor, it will be modified."
10713 (interactive "P")
10714 (let* ((ts nil)
10715 (default-time
10716 ;; Default time is either today, or, when entering a range,
10717 ;; the range start.
10718 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10719 (save-excursion
10720 (re-search-backward
10721 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10722 (- (point) 20) t)))
10723 (apply 'encode-time (org-parse-time-string (match-string 1)))
10724 (current-time)))
10725 (default-input (and ts (org-get-compact-tod ts)))
10726 org-time-was-given org-end-time-was-given time)
10727 (cond
10728 ((and (org-at-timestamp-p t)
10729 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10730 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10731 (insert "--")
10732 (setq time (let ((this-command this-command))
10733 (org-read-date arg 'totime nil nil
10734 default-time default-input)))
10735 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10736 ((org-at-timestamp-p t)
10737 (setq time (let ((this-command this-command))
10738 (org-read-date arg 'totime nil nil default-time default-input)))
10739 (when (org-at-timestamp-p t) ; just to get the match data
10740 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10741 (replace-match "")
10742 (setq org-last-changed-timestamp
10743 (org-insert-time-stamp
10744 time (or org-time-was-given arg)
10745 inactive nil nil (list org-end-time-was-given))))
10746 (message "Timestamp updated"))
10748 (setq time (let ((this-command this-command))
10749 (org-read-date arg 'totime nil nil default-time default-input)))
10750 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10751 nil nil (list org-end-time-was-given))))))
10753 ;; FIXME: can we use this for something else, like computing time differences?
10754 (defun org-get-compact-tod (s)
10755 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10756 (let* ((t1 (match-string 1 s))
10757 (h1 (string-to-number (match-string 2 s)))
10758 (m1 (string-to-number (match-string 3 s)))
10759 (t2 (and (match-end 4) (match-string 5 s)))
10760 (h2 (and t2 (string-to-number (match-string 6 s))))
10761 (m2 (and t2 (string-to-number (match-string 7 s))))
10762 dh dm)
10763 (if (not t2)
10765 (setq dh (- h2 h1) dm (- m2 m1))
10766 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10767 (concat t1 "+" (number-to-string dh)
10768 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10770 (defun org-time-stamp-inactive (&optional arg)
10771 "Insert an inactive time stamp.
10772 An inactive time stamp is enclosed in square brackets instead of angle
10773 brackets. It is inactive in the sense that it does not trigger agenda entries,
10774 does not link to the calendar and cannot be changed with the S-cursor keys.
10775 So these are more for recording a certain time/date."
10776 (interactive "P")
10777 (org-time-stamp arg 'inactive))
10779 (defvar org-date-ovl (org-make-overlay 1 1))
10780 (org-overlay-put org-date-ovl 'face 'org-warning)
10781 (org-detach-overlay org-date-ovl)
10783 (defvar org-ans1) ; dynamically scoped parameter
10784 (defvar org-ans2) ; dynamically scoped parameter
10786 (defvar org-plain-time-of-day-regexp) ; defined below
10788 (defvar org-overriding-default-time nil) ; dynamically scoped
10789 (defvar org-read-date-overlay nil)
10790 (defvar org-dcst nil) ; dynamically scoped
10792 (defun org-read-date (&optional with-time to-time from-string prompt
10793 default-time default-input)
10794 "Read a date, possibly a time, and make things smooth for the user.
10795 The prompt will suggest to enter an ISO date, but you can also enter anything
10796 which will at least partially be understood by `parse-time-string'.
10797 Unrecognized parts of the date will default to the current day, month, year,
10798 hour and minute. If this command is called to replace a timestamp at point,
10799 of to enter the second timestamp of a range, the default time is taken from the
10800 existing stamp. For example,
10801 3-2-5 --> 2003-02-05
10802 feb 15 --> currentyear-02-15
10803 sep 12 9 --> 2009-09-12
10804 12:45 --> today 12:45
10805 22 sept 0:34 --> currentyear-09-22 0:34
10806 12 --> currentyear-currentmonth-12
10807 Fri --> nearest Friday (today or later)
10808 etc.
10810 Furthermore you can specify a relative date by giving, as the *first* thing
10811 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10812 change in days weeks, months, years.
10813 With a single plus or minus, the date is relative to today. With a double
10814 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10815 +4d --> four days from today
10816 +4 --> same as above
10817 +2w --> two weeks from today
10818 ++5 --> five days from default date
10820 The function understands only English month and weekday abbreviations,
10821 but this can be configured with the variables `parse-time-months' and
10822 `parse-time-weekdays'.
10824 While prompting, a calendar is popped up - you can also select the
10825 date with the mouse (button 1). The calendar shows a period of three
10826 months. To scroll it to other months, use the keys `>' and `<'.
10827 If you don't like the calendar, turn it off with
10828 \(setq org-read-date-popup-calendar nil)
10830 With optional argument TO-TIME, the date will immediately be converted
10831 to an internal time.
10832 With an optional argument WITH-TIME, the prompt will suggest to also
10833 insert a time. Note that when WITH-TIME is not set, you can still
10834 enter a time, and this function will inform the calling routine about
10835 this change. The calling routine may then choose to change the format
10836 used to insert the time stamp into the buffer to include the time.
10837 With optional argument FROM-STRING, read from this string instead from
10838 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10839 the time/date that is used for everything that is not specified by the
10840 user."
10841 (require 'parse-time)
10842 (let* ((org-time-stamp-rounding-minutes
10843 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10844 (org-dcst org-display-custom-times)
10845 (ct (org-current-time))
10846 (def (or org-overriding-default-time default-time ct))
10847 (defdecode (decode-time def))
10848 (dummy (progn
10849 (when (< (nth 2 defdecode) org-extend-today-until)
10850 (setcar (nthcdr 2 defdecode) -1)
10851 (setcar (nthcdr 1 defdecode) 59)
10852 (setq def (apply 'encode-time defdecode)
10853 defdecode (decode-time def)))))
10854 (calendar-move-hook nil)
10855 (calendar-view-diary-initially-flag nil)
10856 (view-diary-entries-initially nil)
10857 (calendar-view-holidays-initially-flag nil)
10858 (view-calendar-holidays-initially nil)
10859 (timestr (format-time-string
10860 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10861 (prompt (concat (if prompt (concat prompt " ") "")
10862 (format "Date+time [%s]: " timestr)))
10863 ans (org-ans0 "") org-ans1 org-ans2 final)
10865 (cond
10866 (from-string (setq ans from-string))
10867 (org-read-date-popup-calendar
10868 (save-excursion
10869 (save-window-excursion
10870 (calendar)
10871 (calendar-forward-day (- (time-to-days def)
10872 (calendar-absolute-from-gregorian
10873 (calendar-current-date))))
10874 (org-eval-in-calendar nil t)
10875 (let* ((old-map (current-local-map))
10876 (map (copy-keymap calendar-mode-map))
10877 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10878 (org-defkey map (kbd "RET") 'org-calendar-select)
10879 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10880 'org-calendar-select-mouse)
10881 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10882 'org-calendar-select-mouse)
10883 (org-defkey minibuffer-local-map [(meta shift left)]
10884 (lambda () (interactive)
10885 (org-eval-in-calendar '(calendar-backward-month 1))))
10886 (org-defkey minibuffer-local-map [(meta shift right)]
10887 (lambda () (interactive)
10888 (org-eval-in-calendar '(calendar-forward-month 1))))
10889 (org-defkey minibuffer-local-map [(meta shift up)]
10890 (lambda () (interactive)
10891 (org-eval-in-calendar '(calendar-backward-year 1))))
10892 (org-defkey minibuffer-local-map [(meta shift down)]
10893 (lambda () (interactive)
10894 (org-eval-in-calendar '(calendar-forward-year 1))))
10895 (org-defkey minibuffer-local-map [(shift up)]
10896 (lambda () (interactive)
10897 (org-eval-in-calendar '(calendar-backward-week 1))))
10898 (org-defkey minibuffer-local-map [(shift down)]
10899 (lambda () (interactive)
10900 (org-eval-in-calendar '(calendar-forward-week 1))))
10901 (org-defkey minibuffer-local-map [(shift left)]
10902 (lambda () (interactive)
10903 (org-eval-in-calendar '(calendar-backward-day 1))))
10904 (org-defkey minibuffer-local-map [(shift right)]
10905 (lambda () (interactive)
10906 (org-eval-in-calendar '(calendar-forward-day 1))))
10907 (org-defkey minibuffer-local-map ">"
10908 (lambda () (interactive)
10909 (org-eval-in-calendar '(scroll-calendar-left 1))))
10910 (org-defkey minibuffer-local-map "<"
10911 (lambda () (interactive)
10912 (org-eval-in-calendar '(scroll-calendar-right 1))))
10913 (unwind-protect
10914 (progn
10915 (use-local-map map)
10916 (add-hook 'post-command-hook 'org-read-date-display)
10917 (setq org-ans0 (read-string prompt default-input nil nil))
10918 ;; org-ans0: from prompt
10919 ;; org-ans1: from mouse click
10920 ;; org-ans2: from calendar motion
10921 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10922 (remove-hook 'post-command-hook 'org-read-date-display)
10923 (use-local-map old-map)
10924 (when org-read-date-overlay
10925 (org-delete-overlay org-read-date-overlay)
10926 (setq org-read-date-overlay nil)))))))
10928 (t ; Naked prompt only
10929 (unwind-protect
10930 (setq ans (read-string prompt default-input nil timestr))
10931 (when org-read-date-overlay
10932 (org-delete-overlay org-read-date-overlay)
10933 (setq org-read-date-overlay nil)))))
10935 (setq final (org-read-date-analyze ans def defdecode))
10937 (if to-time
10938 (apply 'encode-time final)
10939 (if (and (boundp 'org-time-was-given) org-time-was-given)
10940 (format "%04d-%02d-%02d %02d:%02d"
10941 (nth 5 final) (nth 4 final) (nth 3 final)
10942 (nth 2 final) (nth 1 final))
10943 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10944 (defvar def)
10945 (defvar defdecode)
10946 (defvar with-time)
10947 (defun org-read-date-display ()
10948 "Display the current date prompt interpretation in the minibuffer."
10949 (when org-read-date-display-live
10950 (when org-read-date-overlay
10951 (org-delete-overlay org-read-date-overlay))
10952 (let ((p (point)))
10953 (end-of-line 1)
10954 (while (not (equal (buffer-substring
10955 (max (point-min) (- (point) 4)) (point))
10956 " "))
10957 (insert " "))
10958 (goto-char p))
10959 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10960 " " (or org-ans1 org-ans2)))
10961 (org-end-time-was-given nil)
10962 (f (org-read-date-analyze ans def defdecode))
10963 (fmts (if org-dcst
10964 org-time-stamp-custom-formats
10965 org-time-stamp-formats))
10966 (fmt (if (or with-time
10967 (and (boundp 'org-time-was-given) org-time-was-given))
10968 (cdr fmts)
10969 (car fmts)))
10970 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10971 (when (and org-end-time-was-given
10972 (string-match org-plain-time-of-day-regexp txt))
10973 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10974 org-end-time-was-given
10975 (substring txt (match-end 0)))))
10976 (setq org-read-date-overlay
10977 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10978 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10980 (defun org-read-date-analyze (ans def defdecode)
10981 "Analyse the combined answer of the date prompt."
10982 ;; FIXME: cleanup and comment
10983 (let (delta deltan deltaw deltadef year month day
10984 hour minute second wday pm h2 m2 tl wday1
10985 iso-year iso-weekday iso-week iso-year iso-date)
10987 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10988 (setq ans "+0"))
10990 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10991 (setq ans (replace-match "" t t ans)
10992 deltan (car delta)
10993 deltaw (nth 1 delta)
10994 deltadef (nth 2 delta)))
10996 ;; Check if there is an iso week date in there
10997 ;; If yes, sore the info and postpone interpreting it until the rest
10998 ;; of the parsing is done
10999 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11000 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11001 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11002 iso-week (string-to-number (match-string 2 ans)))
11003 (setq ans (replace-match "" t t ans)))
11005 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11006 (when (string-match
11007 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11008 (setq year (if (match-end 2)
11009 (string-to-number (match-string 2 ans))
11010 (string-to-number (format-time-string "%Y")))
11011 month (string-to-number (match-string 3 ans))
11012 day (string-to-number (match-string 4 ans)))
11013 (if (< year 100) (setq year (+ 2000 year)))
11014 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11015 t nil ans)))
11016 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11017 ;; If there is a time with am/pm, and *no* time without it, we convert
11018 ;; so that matching will be successful.
11019 (loop for i from 1 to 2 do ; twice, for end time as well
11020 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11021 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11022 (setq hour (string-to-number (match-string 1 ans))
11023 minute (if (match-end 3)
11024 (string-to-number (match-string 3 ans))
11026 pm (equal ?p
11027 (string-to-char (downcase (match-string 4 ans)))))
11028 (if (and (= hour 12) (not pm))
11029 (setq hour 0)
11030 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11031 (setq ans (replace-match (format "%02d:%02d" hour minute)
11032 t t ans))))
11034 ;; Check if a time range is given as a duration
11035 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11036 (setq hour (string-to-number (match-string 1 ans))
11037 h2 (+ hour (string-to-number (match-string 3 ans)))
11038 minute (string-to-number (match-string 2 ans))
11039 m2 (+ minute (if (match-end 5) (string-to-number
11040 (match-string 5 ans))0)))
11041 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11042 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11043 t t ans)))
11045 ;; Check if there is a time range
11046 (when (boundp 'org-end-time-was-given)
11047 (setq org-time-was-given nil)
11048 (when (and (string-match org-plain-time-of-day-regexp ans)
11049 (match-end 8))
11050 (setq org-end-time-was-given (match-string 8 ans))
11051 (setq ans (concat (substring ans 0 (match-beginning 7))
11052 (substring ans (match-end 7))))))
11054 (setq tl (parse-time-string ans)
11055 day (or (nth 3 tl) (nth 3 defdecode))
11056 month (or (nth 4 tl)
11057 (if (and org-read-date-prefer-future
11058 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11059 (1+ (nth 4 defdecode))
11060 (nth 4 defdecode)))
11061 year (or (nth 5 tl)
11062 (if (and org-read-date-prefer-future
11063 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11064 (1+ (nth 5 defdecode))
11065 (nth 5 defdecode)))
11066 hour (or (nth 2 tl) (nth 2 defdecode))
11067 minute (or (nth 1 tl) (nth 1 defdecode))
11068 second (or (nth 0 tl) 0)
11069 wday (nth 6 tl))
11071 ;; Special date definitions below
11072 (cond
11073 (iso-week
11074 ;; There was an iso week
11075 (setq year (or iso-year year)
11076 day (or iso-weekday wday 1)
11077 wday nil ; to make sure that the trigger below does not match
11078 iso-date (calendar-gregorian-from-absolute
11079 (calendar-absolute-from-iso
11080 (list iso-week day year))))
11081 ; FIXME: Should we also push ISO weeks into the future?
11082 ; (when (and org-read-date-prefer-future
11083 ; (not iso-year)
11084 ; (< (calendar-absolute-from-gregorian iso-date)
11085 ; (time-to-days (current-time))))
11086 ; (setq year (1+ year)
11087 ; iso-date (calendar-gregorian-from-absolute
11088 ; (calendar-absolute-from-iso
11089 ; (list iso-week day year)))))
11090 (setq month (car iso-date)
11091 year (nth 2 iso-date)
11092 day (nth 1 iso-date)))
11093 (deltan
11094 (unless deltadef
11095 (let ((now (decode-time (current-time))))
11096 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11097 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11098 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11099 ((equal deltaw "m") (setq month (+ month deltan)))
11100 ((equal deltaw "y") (setq year (+ year deltan)))))
11101 ((and wday (not (nth 3 tl)))
11102 ;; Weekday was given, but no day, so pick that day in the week
11103 ;; on or after the derived date.
11104 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11105 (unless (equal wday wday1)
11106 (setq day (+ day (% (- wday wday1 -7) 7))))))
11107 (if (and (boundp 'org-time-was-given)
11108 (nth 2 tl))
11109 (setq org-time-was-given t))
11110 (if (< year 100) (setq year (+ 2000 year)))
11111 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11112 (list second minute hour day month year)))
11114 (defvar parse-time-weekdays)
11116 (defun org-read-date-get-relative (s today default)
11117 "Check string S for special relative date string.
11118 TODAY and DEFAULT are internal times, for today and for a default.
11119 Return shift list (N what def-flag)
11120 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11121 N is the number of WHATs to shift.
11122 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11123 the DEFAULT date rather than TODAY."
11124 (when (and
11125 (string-match
11126 (concat
11127 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11128 "\\([0-9]+\\)?"
11129 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11130 "\\([ \t]\\|$\\)") s)
11131 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11132 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11133 (string-to-char (substring (match-string 1 s) -1))
11134 ?+))
11135 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11136 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11137 (what (if (match-end 3) (match-string 3 s) "d"))
11138 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11139 (date (if rel default today))
11140 (wday (nth 6 (decode-time date)))
11141 delta)
11142 (if wday1
11143 (progn
11144 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11145 (if (= dir ?-) (setq delta (- delta 7)))
11146 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11147 (list delta "d" rel))
11148 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11150 (defun org-eval-in-calendar (form &optional keepdate)
11151 "Eval FORM in the calendar window and return to current window.
11152 Also, store the cursor date in variable org-ans2."
11153 (let ((sw (selected-window)))
11154 (select-window (get-buffer-window "*Calendar*"))
11155 (eval form)
11156 (when (and (not keepdate) (calendar-cursor-to-date))
11157 (let* ((date (calendar-cursor-to-date))
11158 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11159 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11160 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11161 (select-window sw)))
11163 (defun org-calendar-select ()
11164 "Return to `org-read-date' with the date currently selected.
11165 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11166 (interactive)
11167 (when (calendar-cursor-to-date)
11168 (let* ((date (calendar-cursor-to-date))
11169 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11170 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11171 (if (active-minibuffer-window) (exit-minibuffer))))
11173 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11174 "Insert a date stamp for the date given by the internal TIME.
11175 WITH-HM means, use the stamp format that includes the time of the day.
11176 INACTIVE means use square brackets instead of angular ones, so that the
11177 stamp will not contribute to the agenda.
11178 PRE and POST are optional strings to be inserted before and after the
11179 stamp.
11180 The command returns the inserted time stamp."
11181 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11182 stamp)
11183 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11184 (insert-before-markers (or pre ""))
11185 (insert-before-markers (setq stamp (format-time-string fmt time)))
11186 (when (listp extra)
11187 (setq extra (car extra))
11188 (if (and (stringp extra)
11189 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11190 (setq extra (format "-%02d:%02d"
11191 (string-to-number (match-string 1 extra))
11192 (string-to-number (match-string 2 extra))))
11193 (setq extra nil)))
11194 (when extra
11195 (backward-char 1)
11196 (insert-before-markers extra)
11197 (forward-char 1))
11198 (insert-before-markers (or post ""))
11199 (setq org-last-inserted-timestamp stamp)))
11201 (defun org-toggle-time-stamp-overlays ()
11202 "Toggle the use of custom time stamp formats."
11203 (interactive)
11204 (setq org-display-custom-times (not org-display-custom-times))
11205 (unless org-display-custom-times
11206 (let ((p (point-min)) (bmp (buffer-modified-p)))
11207 (while (setq p (next-single-property-change p 'display))
11208 (if (and (get-text-property p 'display)
11209 (eq (get-text-property p 'face) 'org-date))
11210 (remove-text-properties
11211 p (setq p (next-single-property-change p 'display))
11212 '(display t))))
11213 (set-buffer-modified-p bmp)))
11214 (if (featurep 'xemacs)
11215 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11216 (org-restart-font-lock)
11217 (setq org-table-may-need-update t)
11218 (if org-display-custom-times
11219 (message "Time stamps are overlayed with custom format")
11220 (message "Time stamp overlays removed")))
11222 (defun org-display-custom-time (beg end)
11223 "Overlay modified time stamp format over timestamp between BEG and END."
11224 (let* ((ts (buffer-substring beg end))
11225 t1 w1 with-hm tf time str w2 (off 0))
11226 (save-match-data
11227 (setq t1 (org-parse-time-string ts t))
11228 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11229 (setq off (- (match-end 0) (match-beginning 0)))))
11230 (setq end (- end off))
11231 (setq w1 (- end beg)
11232 with-hm (and (nth 1 t1) (nth 2 t1))
11233 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11234 time (org-fix-decoded-time t1)
11235 str (org-add-props
11236 (format-time-string
11237 (substring tf 1 -1) (apply 'encode-time time))
11238 nil 'mouse-face 'highlight)
11239 w2 (length str))
11240 (if (not (= w2 w1))
11241 (add-text-properties (1+ beg) (+ 2 beg)
11242 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11243 (if (featurep 'xemacs)
11244 (progn
11245 (put-text-property beg end 'invisible t)
11246 (put-text-property beg end 'end-glyph (make-glyph str)))
11247 (put-text-property beg end 'display str))))
11249 (defun org-translate-time (string)
11250 "Translate all timestamps in STRING to custom format.
11251 But do this only if the variable `org-display-custom-times' is set."
11252 (when org-display-custom-times
11253 (save-match-data
11254 (let* ((start 0)
11255 (re org-ts-regexp-both)
11256 t1 with-hm inactive tf time str beg end)
11257 (while (setq start (string-match re string start))
11258 (setq beg (match-beginning 0)
11259 end (match-end 0)
11260 t1 (save-match-data
11261 (org-parse-time-string (substring string beg end) t))
11262 with-hm (and (nth 1 t1) (nth 2 t1))
11263 inactive (equal (substring string beg (1+ beg)) "[")
11264 tf (funcall (if with-hm 'cdr 'car)
11265 org-time-stamp-custom-formats)
11266 time (org-fix-decoded-time t1)
11267 str (format-time-string
11268 (concat
11269 (if inactive "[" "<") (substring tf 1 -1)
11270 (if inactive "]" ">"))
11271 (apply 'encode-time time))
11272 string (replace-match str t t string)
11273 start (+ start (length str)))))))
11274 string)
11276 (defun org-fix-decoded-time (time)
11277 "Set 0 instead of nil for the first 6 elements of time.
11278 Don't touch the rest."
11279 (let ((n 0))
11280 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11282 (defun org-days-to-time (timestamp-string)
11283 "Difference between TIMESTAMP-STRING and now in days."
11284 (- (time-to-days (org-time-string-to-time timestamp-string))
11285 (time-to-days (current-time))))
11287 (defun org-deadline-close (timestamp-string &optional ndays)
11288 "Is the time in TIMESTAMP-STRING close to the current date?"
11289 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11290 (and (< (org-days-to-time timestamp-string) ndays)
11291 (not (org-entry-is-done-p))))
11293 (defun org-get-wdays (ts)
11294 "Get the deadline lead time appropriate for timestring TS."
11295 (cond
11296 ((<= org-deadline-warning-days 0)
11297 ;; 0 or negative, enforce this value no matter what
11298 (- org-deadline-warning-days))
11299 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11300 ;; lead time is specified.
11301 (floor (* (string-to-number (match-string 1 ts))
11302 (cdr (assoc (match-string 2 ts)
11303 '(("d" . 1) ("w" . 7)
11304 ("m" . 30.4) ("y" . 365.25)))))))
11305 ;; go for the default.
11306 (t org-deadline-warning-days)))
11308 (defun org-calendar-select-mouse (ev)
11309 "Return to `org-read-date' with the date currently selected.
11310 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11311 (interactive "e")
11312 (mouse-set-point ev)
11313 (when (calendar-cursor-to-date)
11314 (let* ((date (calendar-cursor-to-date))
11315 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11316 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11317 (if (active-minibuffer-window) (exit-minibuffer))))
11319 (defun org-check-deadlines (ndays)
11320 "Check if there are any deadlines due or past due.
11321 A deadline is considered due if it happens within `org-deadline-warning-days'
11322 days from today's date. If the deadline appears in an entry marked DONE,
11323 it is not shown. The prefix arg NDAYS can be used to test that many
11324 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11325 (interactive "P")
11326 (let* ((org-warn-days
11327 (cond
11328 ((equal ndays '(4)) 100000)
11329 (ndays (prefix-numeric-value ndays))
11330 (t (abs org-deadline-warning-days))))
11331 (case-fold-search nil)
11332 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11333 (callback
11334 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11336 (message "%d deadlines past-due or due within %d days"
11337 (org-occur regexp nil callback)
11338 org-warn-days)))
11340 (defun org-check-before-date (date)
11341 "Check if there are deadlines or scheduled entries before DATE."
11342 (interactive (list (org-read-date)))
11343 (let ((case-fold-search nil)
11344 (regexp (concat "\\<\\(" org-deadline-string
11345 "\\|" org-scheduled-string
11346 "\\) *<\\([^>]+\\)>"))
11347 (callback
11348 (lambda () (time-less-p
11349 (org-time-string-to-time (match-string 2))
11350 (org-time-string-to-time date)))))
11351 (message "%d entries before %s"
11352 (org-occur regexp nil callback) date)))
11354 (defun org-evaluate-time-range (&optional to-buffer)
11355 "Evaluate a time range by computing the difference between start and end.
11356 Normally the result is just printed in the echo area, but with prefix arg
11357 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11358 If the time range is actually in a table, the result is inserted into the
11359 next column.
11360 For time difference computation, a year is assumed to be exactly 365
11361 days in order to avoid rounding problems."
11362 (interactive "P")
11364 (org-clock-update-time-maybe)
11365 (save-excursion
11366 (unless (org-at-date-range-p t)
11367 (goto-char (point-at-bol))
11368 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11369 (if (not (org-at-date-range-p t))
11370 (error "Not at a time-stamp range, and none found in current line")))
11371 (let* ((ts1 (match-string 1))
11372 (ts2 (match-string 2))
11373 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11374 (match-end (match-end 0))
11375 (time1 (org-time-string-to-time ts1))
11376 (time2 (org-time-string-to-time ts2))
11377 (t1 (time-to-seconds time1))
11378 (t2 (time-to-seconds time2))
11379 (diff (abs (- t2 t1)))
11380 (negative (< (- t2 t1) 0))
11381 ;; (ys (floor (* 365 24 60 60)))
11382 (ds (* 24 60 60))
11383 (hs (* 60 60))
11384 (fy "%dy %dd %02d:%02d")
11385 (fy1 "%dy %dd")
11386 (fd "%dd %02d:%02d")
11387 (fd1 "%dd")
11388 (fh "%02d:%02d")
11389 y d h m align)
11390 (if havetime
11391 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11393 d (floor (/ diff ds)) diff (mod diff ds)
11394 h (floor (/ diff hs)) diff (mod diff hs)
11395 m (floor (/ diff 60)))
11396 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11398 d (floor (+ (/ diff ds) 0.5))
11399 h 0 m 0))
11400 (if (not to-buffer)
11401 (message "%s" (org-make-tdiff-string y d h m))
11402 (if (org-at-table-p)
11403 (progn
11404 (goto-char match-end)
11405 (setq align t)
11406 (and (looking-at " *|") (goto-char (match-end 0))))
11407 (goto-char match-end))
11408 (if (looking-at
11409 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11410 (replace-match ""))
11411 (if negative (insert " -"))
11412 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11413 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11414 (insert " " (format fh h m))))
11415 (if align (org-table-align))
11416 (message "Time difference inserted")))))
11418 (defun org-make-tdiff-string (y d h m)
11419 (let ((fmt "")
11420 (l nil))
11421 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11422 l (push y l)))
11423 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11424 l (push d l)))
11425 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11426 l (push h l)))
11427 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11428 l (push m l)))
11429 (apply 'format fmt (nreverse l))))
11431 (defun org-time-string-to-time (s)
11432 (apply 'encode-time (org-parse-time-string s)))
11434 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11435 "Convert a time stamp to an absolute day number.
11436 If there is a specifyer for a cyclic time stamp, get the closest date to
11437 DAYNR.
11438 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11439 (cond
11440 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11441 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11442 daynr
11443 (+ daynr 1000)))
11444 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11445 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11446 (time-to-days (current-time))) (match-string 0 s)
11447 prefer show-all))
11448 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11450 (defun org-days-to-iso-week (days)
11451 "Return the iso week number."
11452 (require 'cal-iso)
11453 (car (calendar-iso-from-absolute days)))
11455 (defun org-small-year-to-year (year)
11456 "Convert 2-digit years into 4-digit years.
11457 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11458 The year 2000 cannot be abbreviated. Any year larger than 99
11459 is returned unchanged."
11460 (if (< year 38)
11461 (setq year (+ 2000 year))
11462 (if (< year 100)
11463 (setq year (+ 1900 year))))
11464 year)
11466 (defun org-time-from-absolute (d)
11467 "Return the time corresponding to date D.
11468 D may be an absolute day number, or a calendar-type list (month day year)."
11469 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11470 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11472 (defun org-calendar-holiday ()
11473 "List of holidays, for Diary display in Org-mode."
11474 (require 'holidays)
11475 (let ((hl (funcall
11476 (if (fboundp 'calendar-check-holidays)
11477 'calendar-check-holidays 'check-calendar-holidays) date)))
11478 (if hl (mapconcat 'identity hl "; "))))
11480 (defun org-diary-sexp-entry (sexp entry date)
11481 "Process a SEXP diary ENTRY for DATE."
11482 (require 'diary-lib)
11483 (let ((result (if calendar-debug-sexp
11484 (let ((stack-trace-on-error t))
11485 (eval (car (read-from-string sexp))))
11486 (condition-case nil
11487 (eval (car (read-from-string sexp)))
11488 (error
11489 (beep)
11490 (message "Bad sexp at line %d in %s: %s"
11491 (org-current-line)
11492 (buffer-file-name) sexp)
11493 (sleep-for 2))))))
11494 (cond ((stringp result) result)
11495 ((and (consp result)
11496 (stringp (cdr result))) (cdr result))
11497 (result entry)
11498 (t nil))))
11500 (defun org-diary-to-ical-string (frombuf)
11501 "Get iCalendar entries from diary entries in buffer FROMBUF.
11502 This uses the icalendar.el library."
11503 (let* ((tmpdir (if (featurep 'xemacs)
11504 (temp-directory)
11505 temporary-file-directory))
11506 (tmpfile (make-temp-name
11507 (expand-file-name "orgics" tmpdir)))
11508 buf rtn b e)
11509 (save-excursion
11510 (set-buffer frombuf)
11511 (icalendar-export-region (point-min) (point-max) tmpfile)
11512 (setq buf (find-buffer-visiting tmpfile))
11513 (set-buffer buf)
11514 (goto-char (point-min))
11515 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11516 (setq b (match-beginning 0)))
11517 (goto-char (point-max))
11518 (if (re-search-backward "^END:VEVENT" nil t)
11519 (setq e (match-end 0)))
11520 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11521 (kill-buffer buf)
11522 (delete-file tmpfile)
11523 rtn))
11525 (defun org-closest-date (start current change prefer show-all)
11526 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11527 When PREFER is `past' return a date that is either CURRENT or past.
11528 When PREFER is `future', return a date that is either CURRENT or future.
11529 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11530 ;; Make the proper lists from the dates
11531 (catch 'exit
11532 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11533 dn dw sday cday n1 n2
11534 d m y y1 y2 date1 date2 nmonths nm ny m2)
11536 (setq start (org-date-to-gregorian start)
11537 current (org-date-to-gregorian
11538 (if show-all
11539 current
11540 (time-to-days (current-time))))
11541 sday (calendar-absolute-from-gregorian start)
11542 cday (calendar-absolute-from-gregorian current))
11544 (if (<= cday sday) (throw 'exit sday))
11546 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11547 (setq dn (string-to-number (match-string 1 change))
11548 dw (cdr (assoc (match-string 2 change) a1)))
11549 (error "Invalid change specifyer: %s" change))
11550 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11551 (cond
11552 ((eq dw 'day)
11553 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11554 n2 (+ n1 dn)))
11555 ((eq dw 'year)
11556 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11557 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11558 (setq date1 (list m d y1)
11559 n1 (calendar-absolute-from-gregorian date1)
11560 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11561 n2 (calendar-absolute-from-gregorian date2)))
11562 ((eq dw 'month)
11563 ;; approx number of month between the two dates
11564 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11565 ;; How often does dn fit in there?
11566 (setq d (nth 1 start) m (car start) y (nth 2 start)
11567 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11568 m (+ m nm)
11569 ny (floor (/ m 12))
11570 y (+ y ny)
11571 m (- m (* ny 12)))
11572 (while (> m 12) (setq m (- m 12) y (1+ y)))
11573 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11574 (setq m2 (+ m dn) y2 y)
11575 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11576 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11577 (while (<= n2 cday)
11578 (setq n1 n2 m m2 y y2)
11579 (setq m2 (+ m dn) y2 y)
11580 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11581 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11582 (if show-all
11583 (cond
11584 ((eq prefer 'past) n1)
11585 ((eq prefer 'future) (if (= cday n1) n1 n2))
11586 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11587 (cond
11588 ((eq prefer 'past) n1)
11589 ((eq prefer 'future) (if (= cday n1) n1 n2))
11590 (t (if (= cday n1) n1 n2)))))))
11592 (defun org-date-to-gregorian (date)
11593 "Turn any specification of DATE into a gregorian date for the calendar."
11594 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11595 ((and (listp date) (= (length date) 3)) date)
11596 ((stringp date)
11597 (setq date (org-parse-time-string date))
11598 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11599 ((listp date)
11600 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11602 (defun org-parse-time-string (s &optional nodefault)
11603 "Parse the standard Org-mode time string.
11604 This should be a lot faster than the normal `parse-time-string'.
11605 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11606 hour and minute fields will be nil if not given."
11607 (if (string-match org-ts-regexp0 s)
11608 (list 0
11609 (if (or (match-beginning 8) (not nodefault))
11610 (string-to-number (or (match-string 8 s) "0")))
11611 (if (or (match-beginning 7) (not nodefault))
11612 (string-to-number (or (match-string 7 s) "0")))
11613 (string-to-number (match-string 4 s))
11614 (string-to-number (match-string 3 s))
11615 (string-to-number (match-string 2 s))
11616 nil nil nil)
11617 (make-list 9 0)))
11619 (defun org-timestamp-up (&optional arg)
11620 "Increase the date item at the cursor by one.
11621 If the cursor is on the year, change the year. If it is on the month or
11622 the day, change that.
11623 With prefix ARG, change by that many units."
11624 (interactive "p")
11625 (org-timestamp-change (prefix-numeric-value arg)))
11627 (defun org-timestamp-down (&optional arg)
11628 "Decrease the date item at the cursor by one.
11629 If the cursor is on the year, change the year. If it is on the month or
11630 the day, change that.
11631 With prefix ARG, change by that many units."
11632 (interactive "p")
11633 (org-timestamp-change (- (prefix-numeric-value arg))))
11635 (defun org-timestamp-up-day (&optional arg)
11636 "Increase the date in the time stamp by one day.
11637 With prefix ARG, change that many days."
11638 (interactive "p")
11639 (if (and (not (org-at-timestamp-p t))
11640 (org-on-heading-p))
11641 (org-todo 'up)
11642 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11644 (defun org-timestamp-down-day (&optional arg)
11645 "Decrease the date in the time stamp by one day.
11646 With prefix ARG, change that many days."
11647 (interactive "p")
11648 (if (and (not (org-at-timestamp-p t))
11649 (org-on-heading-p))
11650 (org-todo 'down)
11651 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11653 (defun org-at-timestamp-p (&optional inactive-ok)
11654 "Determine if the cursor is in or at a timestamp."
11655 (interactive)
11656 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11657 (pos (point))
11658 (ans (or (looking-at tsr)
11659 (save-excursion
11660 (skip-chars-backward "^[<\n\r\t")
11661 (if (> (point) (point-min)) (backward-char 1))
11662 (and (looking-at tsr)
11663 (> (- (match-end 0) pos) -1))))))
11664 (and ans
11665 (boundp 'org-ts-what)
11666 (setq org-ts-what
11667 (cond
11668 ((= pos (match-beginning 0)) 'bracket)
11669 ((= pos (1- (match-end 0))) 'bracket)
11670 ((org-pos-in-match-range pos 2) 'year)
11671 ((org-pos-in-match-range pos 3) 'month)
11672 ((org-pos-in-match-range pos 7) 'hour)
11673 ((org-pos-in-match-range pos 8) 'minute)
11674 ((or (org-pos-in-match-range pos 4)
11675 (org-pos-in-match-range pos 5)) 'day)
11676 ((and (> pos (or (match-end 8) (match-end 5)))
11677 (< pos (match-end 0)))
11678 (- pos (or (match-end 8) (match-end 5))))
11679 (t 'day))))
11680 ans))
11682 (defun org-toggle-timestamp-type ()
11683 "Toggle the type (<active> or [inactive]) of a time stamp."
11684 (interactive)
11685 (when (org-at-timestamp-p t)
11686 (let ((beg (match-beginning 0)) (end (match-end 0))
11687 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11688 (save-excursion
11689 (goto-char beg)
11690 (while (re-search-forward "[][<>]" end t)
11691 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11692 t t)))
11693 (message "Timestamp is now %sactive"
11694 (if (equal (char-after beg) ?<) "" "in")))))
11696 (defun org-timestamp-change (n &optional what)
11697 "Change the date in the time stamp at point.
11698 The date will be changed by N times WHAT. WHAT can be `day', `month',
11699 `year', `minute', `second'. If WHAT is not given, the cursor position
11700 in the timestamp determines what will be changed."
11701 (let ((pos (point))
11702 with-hm inactive
11703 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11704 org-ts-what
11705 extra rem
11706 ts time time0)
11707 (if (not (org-at-timestamp-p t))
11708 (error "Not at a timestamp"))
11709 (if (and (not what) (eq org-ts-what 'bracket))
11710 (org-toggle-timestamp-type)
11711 (if (and (not what) (not (eq org-ts-what 'day))
11712 org-display-custom-times
11713 (get-text-property (point) 'display)
11714 (not (get-text-property (1- (point)) 'display)))
11715 (setq org-ts-what 'day))
11716 (setq org-ts-what (or what org-ts-what)
11717 inactive (= (char-after (match-beginning 0)) ?\[)
11718 ts (match-string 0))
11719 (replace-match "")
11720 (if (string-match
11721 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11723 (setq extra (match-string 1 ts)))
11724 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11725 (setq with-hm t))
11726 (setq time0 (org-parse-time-string ts))
11727 (when (and (eq org-ts-what 'minute)
11728 (eq current-prefix-arg nil))
11729 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11730 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11731 (setcar (cdr time0) (+ (nth 1 time0)
11732 (if (> n 0) (- rem) (- dm rem))))))
11733 (setq time
11734 (encode-time (or (car time0) 0)
11735 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11736 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11737 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11738 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11739 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11740 (nthcdr 6 time0)))
11741 (when (integerp org-ts-what)
11742 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11743 (if (eq what 'calendar)
11744 (let ((cal-date (org-get-date-from-calendar)))
11745 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11746 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11747 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11748 (setcar time0 (or (car time0) 0))
11749 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11750 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11751 (setq time (apply 'encode-time time0))))
11752 (setq org-last-changed-timestamp
11753 (org-insert-time-stamp time with-hm inactive nil nil extra))
11754 (org-clock-update-time-maybe)
11755 (goto-char pos)
11756 ;; Try to recenter the calendar window, if any
11757 (if (and org-calendar-follow-timestamp-change
11758 (get-buffer-window "*Calendar*" t)
11759 (memq org-ts-what '(day month year)))
11760 (org-recenter-calendar (time-to-days time))))))
11762 (defun org-modify-ts-extra (s pos n dm)
11763 "Change the different parts of the lead-time and repeat fields in timestamp."
11764 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11765 ng h m new rem)
11766 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11767 (cond
11768 ((or (org-pos-in-match-range pos 2)
11769 (org-pos-in-match-range pos 3))
11770 (setq m (string-to-number (match-string 3 s))
11771 h (string-to-number (match-string 2 s)))
11772 (if (org-pos-in-match-range pos 2)
11773 (setq h (+ h n))
11774 (setq n (* dm (org-no-warnings (signum n))))
11775 (when (not (= 0 (setq rem (% m dm))))
11776 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11777 (setq m (+ m n)))
11778 (if (< m 0) (setq m (+ m 60) h (1- h)))
11779 (if (> m 59) (setq m (- m 60) h (1+ h)))
11780 (setq h (min 24 (max 0 h)))
11781 (setq ng 1 new (format "-%02d:%02d" h m)))
11782 ((org-pos-in-match-range pos 6)
11783 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11784 ((org-pos-in-match-range pos 5)
11785 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11787 ((org-pos-in-match-range pos 9)
11788 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11789 ((org-pos-in-match-range pos 8)
11790 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11792 (when ng
11793 (setq s (concat
11794 (substring s 0 (match-beginning ng))
11796 (substring s (match-end ng))))))
11799 (defun org-recenter-calendar (date)
11800 "If the calendar is visible, recenter it to DATE."
11801 (let* ((win (selected-window))
11802 (cwin (get-buffer-window "*Calendar*" t))
11803 (calendar-move-hook nil))
11804 (when cwin
11805 (select-window cwin)
11806 (calendar-goto-date (if (listp date) date
11807 (calendar-gregorian-from-absolute date)))
11808 (select-window win))))
11810 (defun org-goto-calendar (&optional arg)
11811 "Go to the Emacs calendar at the current date.
11812 If there is a time stamp in the current line, go to that date.
11813 A prefix ARG can be used to force the current date."
11814 (interactive "P")
11815 (let ((tsr org-ts-regexp) diff
11816 (calendar-move-hook nil)
11817 (calendar-view-holidays-initially-flag nil)
11818 (view-calendar-holidays-initially nil)
11819 (calendar-view-diary-initially-flag nil)
11820 (view-diary-entries-initially nil))
11821 (if (or (org-at-timestamp-p)
11822 (save-excursion
11823 (beginning-of-line 1)
11824 (looking-at (concat ".*" tsr))))
11825 (let ((d1 (time-to-days (current-time)))
11826 (d2 (time-to-days
11827 (org-time-string-to-time (match-string 1)))))
11828 (setq diff (- d2 d1))))
11829 (calendar)
11830 (calendar-goto-today)
11831 (if (and diff (not arg)) (calendar-forward-day diff))))
11833 (defun org-get-date-from-calendar ()
11834 "Return a list (month day year) of date at point in calendar."
11835 (with-current-buffer "*Calendar*"
11836 (save-match-data
11837 (calendar-cursor-to-date))))
11839 (defun org-date-from-calendar ()
11840 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11841 If there is already a time stamp at the cursor position, update it."
11842 (interactive)
11843 (if (org-at-timestamp-p t)
11844 (org-timestamp-change 0 'calendar)
11845 (let ((cal-date (org-get-date-from-calendar)))
11846 (org-insert-time-stamp
11847 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11849 (defun org-minutes-to-hh:mm-string (m)
11850 "Compute H:MM from a number of minutes."
11851 (let ((h (/ m 60)))
11852 (setq m (- m (* 60 h)))
11853 (format org-time-clocksum-format h m)))
11855 (defun org-hh:mm-string-to-minutes (s)
11856 "Convert a string H:MM to a number of minutes."
11857 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11858 (+ (* (string-to-number (match-string 1 s)) 60)
11859 (string-to-number (match-string 2 s)))
11862 ;;;; Agenda files
11864 ;;;###autoload
11865 (defun org-iswitchb (&optional arg)
11866 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11867 With a prefix argument, restrict available to files.
11868 With two prefix arguments, restrict available buffers to agenda files.
11870 Due to some yet unresolved reason, the global function
11871 `iswitchb-mode' needs to be active for this function to work."
11872 (interactive "P")
11873 (require 'iswitchb)
11874 (let ((enabled iswitchb-mode) blist)
11875 (or enabled (iswitchb-mode 1))
11876 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11877 ((equal arg '(16)) (org-buffer-list 'agenda))
11878 (t (org-buffer-list))))
11879 (unwind-protect
11880 (let ((iswitchb-make-buflist-hook
11881 (lambda ()
11882 (setq iswitchb-temp-buflist
11883 (mapcar 'buffer-name blist)))))
11884 (switch-to-buffer
11885 (iswitchb-read-buffer
11886 "Switch-to: " nil t))
11887 (or enabled (iswitchb-mode -1))))))
11889 ;;;###autoload
11890 (defun org-ido-switchb (&optional arg)
11891 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
11892 With a prefix argument, restrict available to files.
11893 With two prefix arguments, restrict available buffers to agenda files."
11894 (interactive "P")
11895 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11896 ((equal arg '(16)) (org-buffer-list 'agenda))
11897 (t (org-buffer-list)))))
11898 (switch-to-buffer
11899 (org-ido-completing-read "Org buffer: "
11900 (mapcar 'buffer-name blist)
11901 nil t))))
11903 (defun org-buffer-list (&optional predicate exclude-tmp)
11904 "Return a list of Org buffers.
11905 PREDICATE can be `export', `files' or `agenda'.
11907 export restrict the list to Export buffers.
11908 files restrict the list to buffers visiting Org files.
11909 agenda restrict the list to buffers visiting agenda files.
11911 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11912 (let* ((bfn nil)
11913 (agenda-files (and (eq predicate 'agenda)
11914 (mapcar 'file-truename (org-agenda-files t))))
11915 (filter
11916 (cond
11917 ((eq predicate 'files)
11918 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11919 ((eq predicate 'export)
11920 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11921 ((eq predicate 'agenda)
11922 (lambda (b)
11923 (with-current-buffer b
11924 (and (eq major-mode 'org-mode)
11925 (setq bfn (buffer-file-name b))
11926 (member (file-truename bfn) agenda-files)))))
11927 (t (lambda (b) (with-current-buffer b
11928 (or (eq major-mode 'org-mode)
11929 (string-match "\*Org .*Export"
11930 (buffer-name b)))))))))
11931 (delq nil
11932 (mapcar
11933 (lambda(b)
11934 (if (and (funcall filter b)
11935 (or (not exclude-tmp)
11936 (not (string-match "tmp" (buffer-name b)))))
11938 nil))
11939 (buffer-list)))))
11941 (defun org-agenda-files (&optional unrestricted archives)
11942 "Get the list of agenda files.
11943 Optional UNRESTRICTED means return the full list even if a restriction
11944 is currently in place.
11945 When ARCHIVES is t, include all archive files hat are really being
11946 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11947 `org-agenda-archives-mode' is t."
11948 (let ((files
11949 (cond
11950 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11951 ((stringp org-agenda-files) (org-read-agenda-file-list))
11952 ((listp org-agenda-files) org-agenda-files)
11953 (t (error "Invalid value of `org-agenda-files'")))))
11954 (setq files (apply 'append
11955 (mapcar (lambda (f)
11956 (if (file-directory-p f)
11957 (directory-files
11958 f t org-agenda-file-regexp)
11959 (list f)))
11960 files)))
11961 (when org-agenda-skip-unavailable-files
11962 (setq files (delq nil
11963 (mapcar (function
11964 (lambda (file)
11965 (and (file-readable-p file) file)))
11966 files))))
11967 (when (or (eq archives t)
11968 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11969 (setq files (org-add-archive-files files)))
11970 files))
11972 (defun org-edit-agenda-file-list ()
11973 "Edit the list of agenda files.
11974 Depending on setup, this either uses customize to edit the variable
11975 `org-agenda-files', or it visits the file that is holding the list. In the
11976 latter case, the buffer is set up in a way that saving it automatically kills
11977 the buffer and restores the previous window configuration."
11978 (interactive)
11979 (if (stringp org-agenda-files)
11980 (let ((cw (current-window-configuration)))
11981 (find-file org-agenda-files)
11982 (org-set-local 'org-window-configuration cw)
11983 (org-add-hook 'after-save-hook
11984 (lambda ()
11985 (set-window-configuration
11986 (prog1 org-window-configuration
11987 (kill-buffer (current-buffer))))
11988 (org-install-agenda-files-menu)
11989 (message "New agenda file list installed"))
11990 nil 'local)
11991 (message "%s" (substitute-command-keys
11992 "Edit list and finish with \\[save-buffer]")))
11993 (customize-variable 'org-agenda-files)))
11995 (defun org-store-new-agenda-file-list (list)
11996 "Set new value for the agenda file list and save it correctly."
11997 (if (stringp org-agenda-files)
11998 (let ((f org-agenda-files) b)
11999 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12000 (with-temp-file f
12001 (insert (mapconcat 'identity list "\n") "\n")))
12002 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12003 (setq org-agenda-files list)
12004 (customize-save-variable 'org-agenda-files org-agenda-files))))
12006 (defun org-read-agenda-file-list ()
12007 "Read the list of agenda files from a file."
12008 (when (file-directory-p org-agenda-files)
12009 (error "`org-agenda-files' cannot be a single directory"))
12010 (when (stringp org-agenda-files)
12011 (with-temp-buffer
12012 (insert-file-contents org-agenda-files)
12013 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12016 ;;;###autoload
12017 (defun org-cycle-agenda-files ()
12018 "Cycle through the files in `org-agenda-files'.
12019 If the current buffer visits an agenda file, find the next one in the list.
12020 If the current buffer does not, find the first agenda file."
12021 (interactive)
12022 (let* ((fs (org-agenda-files t))
12023 (files (append fs (list (car fs))))
12024 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12025 file)
12026 (unless files (error "No agenda files"))
12027 (catch 'exit
12028 (while (setq file (pop files))
12029 (if (equal (file-truename file) tcf)
12030 (when (car files)
12031 (find-file (car files))
12032 (throw 'exit t))))
12033 (find-file (car fs)))
12034 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12036 (defun org-agenda-file-to-front (&optional to-end)
12037 "Move/add the current file to the top of the agenda file list.
12038 If the file is not present in the list, it is added to the front. If it is
12039 present, it is moved there. With optional argument TO-END, add/move to the
12040 end of the list."
12041 (interactive "P")
12042 (let ((org-agenda-skip-unavailable-files nil)
12043 (file-alist (mapcar (lambda (x)
12044 (cons (file-truename x) x))
12045 (org-agenda-files t)))
12046 (ctf (file-truename buffer-file-name))
12047 x had)
12048 (setq x (assoc ctf file-alist) had x)
12050 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12051 (if to-end
12052 (setq file-alist (append (delq x file-alist) (list x)))
12053 (setq file-alist (cons x (delq x file-alist))))
12054 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12055 (org-install-agenda-files-menu)
12056 (message "File %s to %s of agenda file list"
12057 (if had "moved" "added") (if to-end "end" "front"))))
12059 (defun org-remove-file (&optional file)
12060 "Remove current file from the list of files in variable `org-agenda-files'.
12061 These are the files which are being checked for agenda entries.
12062 Optional argument FILE means, use this file instead of the current."
12063 (interactive)
12064 (let* ((org-agenda-skip-unavailable-files nil)
12065 (file (or file buffer-file-name))
12066 (true-file (file-truename file))
12067 (afile (abbreviate-file-name file))
12068 (files (delq nil (mapcar
12069 (lambda (x)
12070 (if (equal true-file
12071 (file-truename x))
12072 nil x))
12073 (org-agenda-files t)))))
12074 (if (not (= (length files) (length (org-agenda-files t))))
12075 (progn
12076 (org-store-new-agenda-file-list files)
12077 (org-install-agenda-files-menu)
12078 (message "Removed file: %s" afile))
12079 (message "File was not in list: %s (not removed)" afile))))
12081 (defun org-file-menu-entry (file)
12082 (vector file (list 'find-file file) t))
12084 (defun org-check-agenda-file (file)
12085 "Make sure FILE exists. If not, ask user what to do."
12086 (when (not (file-exists-p file))
12087 (message "non-existent file %s. [R]emove from list or [A]bort?"
12088 (abbreviate-file-name file))
12089 (let ((r (downcase (read-char-exclusive))))
12090 (cond
12091 ((equal r ?r)
12092 (org-remove-file file)
12093 (throw 'nextfile t))
12094 (t (error "Abort"))))))
12096 (defun org-get-agenda-file-buffer (file)
12097 "Get a buffer visiting FILE. If the buffer needs to be created, add
12098 it to the list of buffers which might be released later."
12099 (let ((buf (org-find-base-buffer-visiting file)))
12100 (if buf
12101 buf ; just return it
12102 ;; Make a new buffer and remember it
12103 (setq buf (find-file-noselect file))
12104 (if buf (push buf org-agenda-new-buffers))
12105 buf)))
12107 (defun org-release-buffers (blist)
12108 "Release all buffers in list, asking the user for confirmation when needed.
12109 When a buffer is unmodified, it is just killed. When modified, it is saved
12110 \(if the user agrees) and then killed."
12111 (let (buf file)
12112 (while (setq buf (pop blist))
12113 (setq file (buffer-file-name buf))
12114 (when (and (buffer-modified-p buf)
12115 file
12116 (y-or-n-p (format "Save file %s? " file)))
12117 (with-current-buffer buf (save-buffer)))
12118 (kill-buffer buf))))
12120 (defun org-prepare-agenda-buffers (files)
12121 "Create buffers for all agenda files, protect archived trees and comments."
12122 (interactive)
12123 (let ((pa '(:org-archived t))
12124 (pc '(:org-comment t))
12125 (pall '(:org-archived t :org-comment t))
12126 (inhibit-read-only t)
12127 (rea (concat ":" org-archive-tag ":"))
12128 bmp file re)
12129 (save-excursion
12130 (save-restriction
12131 (while (setq file (pop files))
12132 (if (bufferp file)
12133 (set-buffer file)
12134 (org-check-agenda-file file)
12135 (set-buffer (org-get-agenda-file-buffer file)))
12136 (widen)
12137 (setq bmp (buffer-modified-p))
12138 (org-refresh-category-properties)
12139 (setq org-todo-keywords-for-agenda
12140 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12141 (setq org-done-keywords-for-agenda
12142 (append org-done-keywords-for-agenda org-done-keywords))
12143 (setq org-todo-keyword-alist-for-agenda
12144 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12145 (setq org-tag-alist-for-agenda
12146 (append org-tag-alist-for-agenda org-tag-alist))
12148 (save-excursion
12149 (remove-text-properties (point-min) (point-max) pall)
12150 (when org-agenda-skip-archived-trees
12151 (goto-char (point-min))
12152 (while (re-search-forward rea nil t)
12153 (if (org-on-heading-p t)
12154 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12155 (goto-char (point-min))
12156 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12157 (while (re-search-forward re nil t)
12158 (add-text-properties
12159 (match-beginning 0) (org-end-of-subtree t) pc)))
12160 (set-buffer-modified-p bmp))))
12161 (setq org-todo-keyword-alist-for-agenda
12162 (org-uniquify org-todo-keyword-alist-for-agenda)
12163 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12165 ;;;; Embedded LaTeX
12167 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12168 "Keymap for the minor `org-cdlatex-mode'.")
12170 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12171 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12172 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12173 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12174 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12176 (defvar org-cdlatex-texmathp-advice-is-done nil
12177 "Flag remembering if we have applied the advice to texmathp already.")
12179 (define-minor-mode org-cdlatex-mode
12180 "Toggle the minor `org-cdlatex-mode'.
12181 This mode supports entering LaTeX environment and math in LaTeX fragments
12182 in Org-mode.
12183 \\{org-cdlatex-mode-map}"
12184 nil " OCDL" nil
12185 (when org-cdlatex-mode (require 'cdlatex))
12186 (unless org-cdlatex-texmathp-advice-is-done
12187 (setq org-cdlatex-texmathp-advice-is-done t)
12188 (defadvice texmathp (around org-math-always-on activate)
12189 "Always return t in org-mode buffers.
12190 This is because we want to insert math symbols without dollars even outside
12191 the LaTeX math segments. If Orgmode thinks that point is actually inside
12192 an embedded LaTeX fragment, let texmathp do its job.
12193 \\[org-cdlatex-mode-map]"
12194 (interactive)
12195 (let (p)
12196 (cond
12197 ((not (org-mode-p)) ad-do-it)
12198 ((eq this-command 'cdlatex-math-symbol)
12199 (setq ad-return-value t
12200 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12202 (let ((p (org-inside-LaTeX-fragment-p)))
12203 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12204 (setq ad-return-value t
12205 texmathp-why '("Org-mode embedded math" . 0))
12206 (if p ad-do-it)))))))))
12208 (defun turn-on-org-cdlatex ()
12209 "Unconditionally turn on `org-cdlatex-mode'."
12210 (org-cdlatex-mode 1))
12212 (defun org-inside-LaTeX-fragment-p ()
12213 "Test if point is inside a LaTeX fragment.
12214 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12215 sequence appearing also before point.
12216 Even though the matchers for math are configurable, this function assumes
12217 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12218 delimiters are skipped when they have been removed by customization.
12219 The return value is nil, or a cons cell with the delimiter and
12220 and the position of this delimiter.
12222 This function does a reasonably good job, but can locally be fooled by
12223 for example currency specifications. For example it will assume being in
12224 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12225 fragments that are properly closed, but during editing, we have to live
12226 with the uncertainty caused by missing closing delimiters. This function
12227 looks only before point, not after."
12228 (catch 'exit
12229 (let ((pos (point))
12230 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12231 (lim (progn
12232 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12233 (point)))
12234 dd-on str (start 0) m re)
12235 (goto-char pos)
12236 (when dodollar
12237 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12238 re (nth 1 (assoc "$" org-latex-regexps)))
12239 (while (string-match re str start)
12240 (cond
12241 ((= (match-end 0) (length str))
12242 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12243 ((= (match-end 0) (- (length str) 5))
12244 (throw 'exit nil))
12245 (t (setq start (match-end 0))))))
12246 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12247 (goto-char pos)
12248 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12249 (and (match-beginning 2) (throw 'exit nil))
12250 ;; count $$
12251 (while (re-search-backward "\\$\\$" lim t)
12252 (setq dd-on (not dd-on)))
12253 (goto-char pos)
12254 (if dd-on (cons "$$" m))))))
12257 (defun org-try-cdlatex-tab ()
12258 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12259 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12260 - inside a LaTeX fragment, or
12261 - after the first word in a line, where an abbreviation expansion could
12262 insert a LaTeX environment."
12263 (when org-cdlatex-mode
12264 (cond
12265 ((save-excursion
12266 (skip-chars-backward "a-zA-Z0-9*")
12267 (skip-chars-backward " \t")
12268 (bolp))
12269 (cdlatex-tab) t)
12270 ((org-inside-LaTeX-fragment-p)
12271 (cdlatex-tab) t)
12272 (t nil))))
12274 (defun org-cdlatex-underscore-caret (&optional arg)
12275 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12276 Revert to the normal definition outside of these fragments."
12277 (interactive "P")
12278 (if (org-inside-LaTeX-fragment-p)
12279 (call-interactively 'cdlatex-sub-superscript)
12280 (let (org-cdlatex-mode)
12281 (call-interactively (key-binding (vector last-input-event))))))
12283 (defun org-cdlatex-math-modify (&optional arg)
12284 "Execute `cdlatex-math-modify' in LaTeX fragments.
12285 Revert to the normal definition outside of these fragments."
12286 (interactive "P")
12287 (if (org-inside-LaTeX-fragment-p)
12288 (call-interactively 'cdlatex-math-modify)
12289 (let (org-cdlatex-mode)
12290 (call-interactively (key-binding (vector last-input-event))))))
12292 (defvar org-latex-fragment-image-overlays nil
12293 "List of overlays carrying the images of latex fragments.")
12294 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12296 (defun org-remove-latex-fragment-image-overlays ()
12297 "Remove all overlays with LaTeX fragment images in current buffer."
12298 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12299 (setq org-latex-fragment-image-overlays nil))
12301 (defun org-preview-latex-fragment (&optional subtree)
12302 "Preview the LaTeX fragment at point, or all locally or globally.
12303 If the cursor is in a LaTeX fragment, create the image and overlay
12304 it over the source code. If there is no fragment at point, display
12305 all fragments in the current text, from one headline to the next. With
12306 prefix SUBTREE, display all fragments in the current subtree. With a
12307 double prefix `C-u C-u', or when the cursor is before the first headline,
12308 display all fragments in the buffer.
12309 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12310 (interactive "P")
12311 (org-remove-latex-fragment-image-overlays)
12312 (save-excursion
12313 (save-restriction
12314 (let (beg end at msg)
12315 (cond
12316 ((or (equal subtree '(16))
12317 (not (save-excursion
12318 (re-search-backward (concat "^" outline-regexp) nil t))))
12319 (setq beg (point-min) end (point-max)
12320 msg "Creating images for buffer...%s"))
12321 ((equal subtree '(4))
12322 (org-back-to-heading)
12323 (setq beg (point) end (org-end-of-subtree t)
12324 msg "Creating images for subtree...%s"))
12326 (if (setq at (org-inside-LaTeX-fragment-p))
12327 (goto-char (max (point-min) (- (cdr at) 2)))
12328 (org-back-to-heading))
12329 (setq beg (point) end (progn (outline-next-heading) (point))
12330 msg (if at "Creating image...%s"
12331 "Creating images for entry...%s"))))
12332 (message msg "")
12333 (narrow-to-region beg end)
12334 (goto-char beg)
12335 (org-format-latex
12336 (concat "ltxpng/" (file-name-sans-extension
12337 (file-name-nondirectory
12338 buffer-file-name)))
12339 default-directory 'overlays msg at 'forbuffer)
12340 (message msg "done. Use `C-c C-c' to remove images.")))))
12342 (defvar org-latex-regexps
12343 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12344 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12345 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12346 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12347 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12348 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12349 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12350 "Regular expressions for matching embedded LaTeX.")
12352 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12353 "Replace LaTeX fragments with links to an image, and produce images."
12354 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12355 (let* ((prefixnodir (file-name-nondirectory prefix))
12356 (absprefix (expand-file-name prefix dir))
12357 (todir (file-name-directory absprefix))
12358 (opt org-format-latex-options)
12359 (matchers (plist-get opt :matchers))
12360 (re-list org-latex-regexps)
12361 (cnt 0) txt link beg end re e checkdir
12362 m n block linkfile movefile ov)
12363 ;; Check if there are old images files with this prefix, and remove them
12364 (when (file-directory-p todir)
12365 (mapc 'delete-file
12366 (directory-files
12367 todir 'full
12368 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12369 ;; Check the different regular expressions
12370 (while (setq e (pop re-list))
12371 (setq m (car e) re (nth 1 e) n (nth 2 e)
12372 block (if (nth 3 e) "\n\n" ""))
12373 (when (member m matchers)
12374 (goto-char (point-min))
12375 (while (re-search-forward re nil t)
12376 (when (or (not at) (equal (cdr at) (match-beginning n)))
12377 (setq txt (match-string n)
12378 beg (match-beginning n) end (match-end n)
12379 cnt (1+ cnt)
12380 linkfile (format "%s_%04d.png" prefix cnt)
12381 movefile (format "%s_%04d.png" absprefix cnt)
12382 link (concat block "[[file:" linkfile "]]" block))
12383 (if msg (message msg cnt))
12384 (goto-char beg)
12385 (unless checkdir ; make sure the directory exists
12386 (setq checkdir t)
12387 (or (file-directory-p todir) (make-directory todir)))
12388 (org-create-formula-image
12389 txt movefile opt forbuffer)
12390 (if overlays
12391 (progn
12392 (setq ov (org-make-overlay beg end))
12393 (if (featurep 'xemacs)
12394 (progn
12395 (org-overlay-put ov 'invisible t)
12396 (org-overlay-put
12397 ov 'end-glyph
12398 (make-glyph (vector 'png :file movefile))))
12399 (org-overlay-put
12400 ov 'display
12401 (list 'image :type 'png :file movefile :ascent 'center)))
12402 (push ov org-latex-fragment-image-overlays)
12403 (goto-char end))
12404 (delete-region beg end)
12405 (insert link))))))))
12407 ;; This function borrows from Ganesh Swami's latex2png.el
12408 (defun org-create-formula-image (string tofile options buffer)
12409 (let* ((tmpdir (if (featurep 'xemacs)
12410 (temp-directory)
12411 temporary-file-directory))
12412 (texfilebase (make-temp-name
12413 (expand-file-name "orgtex" tmpdir)))
12414 (texfile (concat texfilebase ".tex"))
12415 (dvifile (concat texfilebase ".dvi"))
12416 (pngfile (concat texfilebase ".png"))
12417 (fnh (if (featurep 'xemacs)
12418 (font-height (get-face-font 'default))
12419 (face-attribute 'default :height nil)))
12420 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12421 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12422 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12423 "Black"))
12424 (bg (or (plist-get options (if buffer :background :html-background))
12425 "Transparent")))
12426 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12427 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12428 (with-temp-file texfile
12429 (insert org-format-latex-header
12430 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12431 (let ((dir default-directory))
12432 (condition-case nil
12433 (progn
12434 (cd tmpdir)
12435 (call-process "latex" nil nil nil texfile))
12436 (error nil))
12437 (cd dir))
12438 (if (not (file-exists-p dvifile))
12439 (progn (message "Failed to create dvi file from %s" texfile) nil)
12440 (condition-case nil
12441 (call-process "dvipng" nil nil nil
12442 "-E" "-fg" fg "-bg" bg
12443 "-D" dpi
12444 ;;"-x" scale "-y" scale
12445 "-T" "tight"
12446 "-o" pngfile
12447 dvifile)
12448 (error nil))
12449 (if (not (file-exists-p pngfile))
12450 (progn (message "Failed to create png file from %s" texfile) nil)
12451 ;; Use the requested file name and clean up
12452 (copy-file pngfile tofile 'replace)
12453 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12454 (delete-file (concat texfilebase e)))
12455 pngfile))))
12457 (defun org-dvipng-color (attr)
12458 "Return an rgb color specification for dvipng."
12459 (apply 'format "rgb %s %s %s"
12460 (mapcar 'org-normalize-color
12461 (color-values (face-attribute 'default attr nil)))))
12463 (defun org-normalize-color (value)
12464 "Return string to be used as color value for an RGB component."
12465 (format "%g" (/ value 65535.0)))
12468 ;;;; Key bindings
12470 ;; Make `C-c C-x' a prefix key
12471 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12473 ;; TAB key with modifiers
12474 (org-defkey org-mode-map "\C-i" 'org-cycle)
12475 (org-defkey org-mode-map [(tab)] 'org-cycle)
12476 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12477 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12478 (org-defkey org-mode-map "\M-\t" 'org-complete)
12479 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12480 ;; The following line is necessary under Suse GNU/Linux
12481 (unless (featurep 'xemacs)
12482 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12483 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12484 (define-key org-mode-map [backtab] 'org-shifttab)
12486 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12487 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12488 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12490 ;; Cursor keys with modifiers
12491 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12492 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12493 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12494 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12496 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12497 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12498 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12499 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12501 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12502 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12503 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12504 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12506 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12507 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12509 ;;; Extra keys for tty access.
12510 ;; We only set them when really needed because otherwise the
12511 ;; menus don't show the simple keys
12513 (when (or org-use-extra-keys
12514 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12515 (not window-system))
12516 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12517 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12518 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12519 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12520 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12521 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12522 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12523 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12524 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12525 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12526 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12527 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12528 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12529 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12530 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12531 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12532 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12533 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12534 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12535 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12536 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12537 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12539 ;; All the other keys
12541 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12542 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12543 (if (boundp 'narrow-map)
12544 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12545 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12546 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12547 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12548 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12549 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12550 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12551 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12552 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12553 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12554 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12555 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12556 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12557 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12558 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12559 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12560 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12561 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12562 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12563 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12564 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12565 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12566 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12567 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12568 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12569 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12570 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12571 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12572 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12573 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12574 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12575 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12576 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12577 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12578 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12579 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12580 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12581 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12582 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12583 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12584 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12585 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12586 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12587 (org-defkey org-mode-map "\C-c^" 'org-sort)
12588 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12589 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12590 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12591 (org-defkey org-mode-map "\C-m" 'org-return)
12592 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12593 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12594 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12595 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12596 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12597 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12598 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12599 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12600 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12601 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12602 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12603 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12604 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12605 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12606 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12607 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12609 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12610 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12611 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12612 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12614 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12615 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12616 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12617 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12618 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12619 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12620 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12621 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12622 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12623 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12624 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12625 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12627 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12628 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12629 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12631 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12633 (when (featurep 'xemacs)
12634 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12636 (defvar org-table-auto-blank-field) ; defined in org-table.el
12637 (defun org-self-insert-command (N)
12638 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12639 If the cursor is in a table looking at whitespace, the whitespace is
12640 overwritten, and the table is not marked as requiring realignment."
12641 (interactive "p")
12642 (if (and (org-table-p)
12643 (progn
12644 ;; check if we blank the field, and if that triggers align
12645 (and (featurep 'org-table) org-table-auto-blank-field
12646 (member last-command
12647 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12648 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12649 ;; got extra space, this field does not determine column width
12650 (let (org-table-may-need-update) (org-table-blank-field))
12651 ;; no extra space, this field may determine column width
12652 (org-table-blank-field)))
12654 (eq N 1)
12655 (looking-at "[^|\n]* |"))
12656 (let (org-table-may-need-update)
12657 (goto-char (1- (match-end 0)))
12658 (delete-backward-char 1)
12659 (goto-char (match-beginning 0))
12660 (self-insert-command N))
12661 (setq org-table-may-need-update t)
12662 (self-insert-command N)
12663 (org-fix-tags-on-the-fly)))
12665 (defun org-fix-tags-on-the-fly ()
12666 (when (and (equal (char-after (point-at-bol)) ?*)
12667 (org-on-heading-p))
12668 (org-align-tags-here org-tags-column)))
12670 (defun org-delete-backward-char (N)
12671 "Like `delete-backward-char', insert whitespace at field end in tables.
12672 When deleting backwards, in tables this function will insert whitespace in
12673 front of the next \"|\" separator, to keep the table aligned. The table will
12674 still be marked for re-alignment if the field did fill the entire column,
12675 because, in this case the deletion might narrow the column."
12676 (interactive "p")
12677 (if (and (org-table-p)
12678 (eq N 1)
12679 (string-match "|" (buffer-substring (point-at-bol) (point)))
12680 (looking-at ".*?|"))
12681 (let ((pos (point))
12682 (noalign (looking-at "[^|\n\r]* |"))
12683 (c org-table-may-need-update))
12684 (backward-delete-char N)
12685 (skip-chars-forward "^|")
12686 (insert " ")
12687 (goto-char (1- pos))
12688 ;; noalign: if there were two spaces at the end, this field
12689 ;; does not determine the width of the column.
12690 (if noalign (setq org-table-may-need-update c)))
12691 (backward-delete-char N)
12692 (org-fix-tags-on-the-fly)))
12694 (defun org-delete-char (N)
12695 "Like `delete-char', but insert whitespace at field end in tables.
12696 When deleting characters, in tables this function will insert whitespace in
12697 front of the next \"|\" separator, to keep the table aligned. The table will
12698 still be marked for re-alignment if the field did fill the entire column,
12699 because, in this case the deletion might narrow the column."
12700 (interactive "p")
12701 (if (and (org-table-p)
12702 (not (bolp))
12703 (not (= (char-after) ?|))
12704 (eq N 1))
12705 (if (looking-at ".*?|")
12706 (let ((pos (point))
12707 (noalign (looking-at "[^|\n\r]* |"))
12708 (c org-table-may-need-update))
12709 (replace-match (concat
12710 (substring (match-string 0) 1 -1)
12711 " |"))
12712 (goto-char pos)
12713 ;; noalign: if there were two spaces at the end, this field
12714 ;; does not determine the width of the column.
12715 (if noalign (setq org-table-may-need-update c)))
12716 (delete-char N))
12717 (delete-char N)
12718 (org-fix-tags-on-the-fly)))
12720 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12721 (put 'org-self-insert-command 'delete-selection t)
12722 (put 'orgtbl-self-insert-command 'delete-selection t)
12723 (put 'org-delete-char 'delete-selection 'supersede)
12724 (put 'org-delete-backward-char 'delete-selection 'supersede)
12726 ;; Make `flyspell-mode' delay after some commands
12727 (put 'org-self-insert-command 'flyspell-delayed t)
12728 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12729 (put 'org-delete-char 'flyspell-delayed t)
12730 (put 'org-delete-backward-char 'flyspell-delayed t)
12732 ;; Make pabbrev-mode expand after org-mode commands
12733 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12734 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12736 ;; How to do this: Measure non-white length of current string
12737 ;; If equal to column width, we should realign.
12739 (defun org-remap (map &rest commands)
12740 "In MAP, remap the functions given in COMMANDS.
12741 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12742 (let (new old)
12743 (while commands
12744 (setq old (pop commands) new (pop commands))
12745 (if (fboundp 'command-remapping)
12746 (org-defkey map (vector 'remap old) new)
12747 (substitute-key-definition old new map global-map)))))
12749 (when (eq org-enable-table-editor 'optimized)
12750 ;; If the user wants maximum table support, we need to hijack
12751 ;; some standard editing functions
12752 (org-remap org-mode-map
12753 'self-insert-command 'org-self-insert-command
12754 'delete-char 'org-delete-char
12755 'delete-backward-char 'org-delete-backward-char)
12756 (org-defkey org-mode-map "|" 'org-force-self-insert))
12758 (defun org-shiftcursor-error ()
12759 "Throw an error because Shift-Cursor command was applied in wrong context."
12760 (error "This command is active in special context like tables, headlines or timestamps"))
12762 (defun org-shifttab (&optional arg)
12763 "Global visibility cycling or move to previous table field.
12764 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12765 on context.
12766 See the individual commands for more information."
12767 (interactive "P")
12768 (cond
12769 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12770 ((integerp arg)
12771 (message "Content view to level: %d" arg)
12772 (org-content (prefix-numeric-value arg))
12773 (setq org-cycle-global-status 'overview))
12774 (t (call-interactively 'org-global-cycle))))
12776 (defun org-shiftmetaleft ()
12777 "Promote subtree or delete table column.
12778 Calls `org-promote-subtree', `org-outdent-item',
12779 or `org-table-delete-column', depending on context.
12780 See the individual commands for more information."
12781 (interactive)
12782 (cond
12783 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12784 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12785 ((org-at-item-p) (call-interactively 'org-outdent-item))
12786 (t (org-shiftcursor-error))))
12788 (defun org-shiftmetaright ()
12789 "Demote subtree or insert table column.
12790 Calls `org-demote-subtree', `org-indent-item',
12791 or `org-table-insert-column', depending on context.
12792 See the individual commands for more information."
12793 (interactive)
12794 (cond
12795 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12796 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12797 ((org-at-item-p) (call-interactively 'org-indent-item))
12798 (t (org-shiftcursor-error))))
12800 (defun org-shiftmetaup (&optional arg)
12801 "Move subtree up or kill table row.
12802 Calls `org-move-subtree-up' or `org-table-kill-row' or
12803 `org-move-item-up' depending on context. See the individual commands
12804 for more information."
12805 (interactive "P")
12806 (cond
12807 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12808 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12809 ((org-at-item-p) (call-interactively 'org-move-item-up))
12810 (t (org-shiftcursor-error))))
12811 (defun org-shiftmetadown (&optional arg)
12812 "Move subtree down or insert table row.
12813 Calls `org-move-subtree-down' or `org-table-insert-row' or
12814 `org-move-item-down', depending on context. See the individual
12815 commands for more information."
12816 (interactive "P")
12817 (cond
12818 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12819 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12820 ((org-at-item-p) (call-interactively 'org-move-item-down))
12821 (t (org-shiftcursor-error))))
12823 (defun org-metaleft (&optional arg)
12824 "Promote heading or move table column to left.
12825 Calls `org-do-promote' or `org-table-move-column', depending on context.
12826 With no specific context, calls the Emacs default `backward-word'.
12827 See the individual commands for more information."
12828 (interactive "P")
12829 (cond
12830 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12831 ((or (org-on-heading-p) (org-region-active-p))
12832 (call-interactively 'org-do-promote))
12833 ((org-at-item-p) (call-interactively 'org-outdent-item))
12834 (t (call-interactively 'backward-word))))
12836 (defun org-metaright (&optional arg)
12837 "Demote subtree or move table column to right.
12838 Calls `org-do-demote' or `org-table-move-column', depending on context.
12839 With no specific context, calls the Emacs default `forward-word'.
12840 See the individual commands for more information."
12841 (interactive "P")
12842 (cond
12843 ((org-at-table-p) (call-interactively 'org-table-move-column))
12844 ((or (org-on-heading-p) (org-region-active-p))
12845 (call-interactively 'org-do-demote))
12846 ((org-at-item-p) (call-interactively 'org-indent-item))
12847 (t (call-interactively 'forward-word))))
12849 (defun org-metaup (&optional arg)
12850 "Move subtree up or move table row up.
12851 Calls `org-move-subtree-up' or `org-table-move-row' or
12852 `org-move-item-up', depending on context. See the individual commands
12853 for more information."
12854 (interactive "P")
12855 (cond
12856 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12857 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12858 ((org-at-item-p) (call-interactively 'org-move-item-up))
12859 (t (transpose-lines 1) (beginning-of-line -1))))
12861 (defun org-metadown (&optional arg)
12862 "Move subtree down or move table row down.
12863 Calls `org-move-subtree-down' or `org-table-move-row' or
12864 `org-move-item-down', depending on context. See the individual
12865 commands for more information."
12866 (interactive "P")
12867 (cond
12868 ((org-at-table-p) (call-interactively 'org-table-move-row))
12869 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12870 ((org-at-item-p) (call-interactively 'org-move-item-down))
12871 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12873 (defun org-shiftup (&optional arg)
12874 "Increase item in timestamp or increase priority of current headline.
12875 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12876 depending on context. See the individual commands for more information."
12877 (interactive "P")
12878 (cond
12879 ((org-at-timestamp-p t)
12880 (call-interactively (if org-edit-timestamp-down-means-later
12881 'org-timestamp-down 'org-timestamp-up)))
12882 ((org-on-heading-p) (call-interactively 'org-priority-up))
12883 ((org-at-item-p) (call-interactively 'org-previous-item))
12884 ((org-clocktable-try-shift 'up arg))
12885 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12887 (defun org-shiftdown (&optional arg)
12888 "Decrease item in timestamp or decrease priority of current headline.
12889 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12890 depending on context. See the individual commands for more information."
12891 (interactive "P")
12892 (cond
12893 ((org-at-timestamp-p t)
12894 (call-interactively (if org-edit-timestamp-down-means-later
12895 'org-timestamp-up 'org-timestamp-down)))
12896 ((org-on-heading-p) (call-interactively 'org-priority-down))
12897 ((org-clocktable-try-shift 'down arg))
12898 (t (call-interactively 'org-next-item))))
12900 (defun org-shiftright (&optional arg)
12901 "Cycle the thing at point or in the current line, depending on context.
12902 Depending on context, this does one of the following:
12904 - switch a timestamp at point one day into the future
12905 - on a headline, switch to the next TODO keyword.
12906 - on an item, switch entire list to the next bullet type
12907 - on a property line, switch to the next allowed value
12908 - on a clocktable definition line, move time block into the future"
12909 (interactive "P")
12910 (cond
12911 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12912 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12913 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12914 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12915 ((org-clocktable-try-shift 'right arg))
12916 (t (org-shiftcursor-error))))
12918 (defun org-shiftleft (&optional arg)
12919 "Cycle the thing at point or in the current line, depending on context.
12920 Depending on context, this does one of the following:
12922 - switch a timestamp at point one day into the past
12923 - on a headline, switch to the previous TODO keyword.
12924 - on an item, switch entire list to the previous bullet type
12925 - on a property line, switch to the previous allowed value
12926 - on a clocktable definition line, move time block into the past"
12927 (interactive "P")
12928 (cond
12929 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12930 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12931 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12932 ((org-at-property-p)
12933 (call-interactively 'org-property-previous-allowed-value))
12934 ((org-clocktable-try-shift 'left arg))
12935 (t (org-shiftcursor-error))))
12937 (defun org-shiftcontrolright ()
12938 "Switch to next TODO set."
12939 (interactive)
12940 (cond
12941 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12942 (t (org-shiftcursor-error))))
12944 (defun org-shiftcontrolleft ()
12945 "Switch to previous TODO set."
12946 (interactive)
12947 (cond
12948 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12949 (t (org-shiftcursor-error))))
12951 (defun org-ctrl-c-ret ()
12952 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12953 (interactive)
12954 (cond
12955 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12956 (t (call-interactively 'org-insert-heading))))
12958 (defun org-copy-special ()
12959 "Copy region in table or copy current subtree.
12960 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12961 See the individual commands for more information."
12962 (interactive)
12963 (call-interactively
12964 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12966 (defun org-cut-special ()
12967 "Cut region in table or cut current subtree.
12968 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12969 See the individual commands for more information."
12970 (interactive)
12971 (call-interactively
12972 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12974 (defun org-paste-special (arg)
12975 "Paste rectangular region into table, or past subtree relative to level.
12976 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12977 See the individual commands for more information."
12978 (interactive "P")
12979 (if (org-at-table-p)
12980 (org-table-paste-rectangle)
12981 (org-paste-subtree arg)))
12983 (defun org-edit-special ()
12984 "Call a special editor for the stuff at point.
12985 When at a table, call the formula editor with `org-table-edit-formulas'.
12986 When at the first line of an src example, call `org-edit-src-code'.
12987 When in an #+include line, visit the include file. Otherwise call
12988 `ffap' to visit the file at point."
12989 (interactive)
12990 (cond
12991 ((org-at-table-p)
12992 (call-interactively 'org-table-edit-formulas))
12993 ((save-excursion
12994 (beginning-of-line 1)
12995 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12996 (find-file (org-trim (match-string 1))))
12997 ((org-edit-src-code))
12998 ((org-edit-fixed-width-region))
12999 (t (call-interactively 'ffap))))
13001 (defun org-ctrl-c-ctrl-c (&optional arg)
13002 "Set tags in headline, or update according to changed information at point.
13004 This command does many different things, depending on context:
13006 - If the cursor is in a headline, prompt for tags and insert them
13007 into the current line, aligned to `org-tags-column'. When called
13008 with prefix arg, realign all tags in the current buffer.
13010 - If the cursor is in one of the special #+KEYWORD lines, this
13011 triggers scanning the buffer for these lines and updating the
13012 information.
13014 - If the cursor is inside a table, realign the table. This command
13015 works even if the automatic table editor has been turned off.
13017 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13018 the entire table.
13020 - If the cursor is a the beginning of a dynamic block, update it.
13022 - If the cursor is inside a table created by the table.el package,
13023 activate that table.
13025 - If the current buffer is a remember buffer, close note and file
13026 it. A prefix argument of 1 files to the default location
13027 without further interaction. A prefix argument of 2 files to
13028 the currently clocking task.
13030 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13031 links in this buffer.
13033 - If the cursor is on a numbered item in a plain list, renumber the
13034 ordered list.
13036 - If the cursor is on a checkbox, toggle it."
13037 (interactive "P")
13038 (let ((org-enable-table-editor t))
13039 (cond
13040 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13041 org-occur-highlights
13042 org-latex-fragment-image-overlays)
13043 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13044 (org-remove-occur-highlights)
13045 (org-remove-latex-fragment-image-overlays)
13046 (message "Temporary highlights/overlays removed from current buffer"))
13047 ((and (local-variable-p 'org-finish-function (current-buffer))
13048 (fboundp org-finish-function))
13049 (funcall org-finish-function))
13050 ((org-at-property-p)
13051 (call-interactively 'org-property-action))
13052 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13053 ((org-on-heading-p) (call-interactively 'org-set-tags))
13054 ((org-at-table.el-p)
13055 (require 'table)
13056 (beginning-of-line 1)
13057 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13058 (call-interactively 'table-recognize-table))
13059 ((org-at-table-p)
13060 (org-table-maybe-eval-formula)
13061 (if arg
13062 (call-interactively 'org-table-recalculate)
13063 (org-table-maybe-recalculate-line))
13064 (call-interactively 'org-table-align))
13065 ((org-at-item-checkbox-p)
13066 (call-interactively 'org-toggle-checkbox))
13067 ((org-at-item-p)
13068 (call-interactively 'org-maybe-renumber-ordered-list))
13069 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13070 ;; Dynamic block
13071 (beginning-of-line 1)
13072 (save-excursion (org-update-dblock)))
13073 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13074 (cond
13075 ((equal (match-string 1) "TBLFM")
13076 ;; Recalculate the table before this line
13077 (save-excursion
13078 (beginning-of-line 1)
13079 (skip-chars-backward " \r\n\t")
13080 (if (org-at-table-p)
13081 (org-call-with-arg 'org-table-recalculate t))))
13083 ; (org-set-regexps-and-options)
13084 ; (org-restart-font-lock)
13085 (let ((org-inhibit-startup t)) (org-mode-restart))
13086 (message "Local setup has been refreshed"))))
13087 (t (error "C-c C-c can do nothing useful at this location.")))))
13089 (defun org-mode-restart ()
13090 "Restart Org-mode, to scan again for special lines.
13091 Also updates the keyword regular expressions."
13092 (interactive)
13093 (org-mode)
13094 (message "Org-mode restarted"))
13096 (defun org-kill-note-or-show-branches ()
13097 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13098 (interactive)
13099 (if (not org-finish-function)
13100 (call-interactively 'show-branches)
13101 (let ((org-note-abort t))
13102 (funcall org-finish-function))))
13104 (defun org-return (&optional indent)
13105 "Goto next table row or insert a newline.
13106 Calls `org-table-next-row' or `newline', depending on context.
13107 See the individual commands for more information."
13108 (interactive)
13109 (cond
13110 ((bobp) (if indent (newline-and-indent) (newline)))
13111 ((and (org-at-heading-p)
13112 (looking-at
13113 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13114 (org-show-entry)
13115 (end-of-line 1)
13116 (newline))
13117 ((org-at-table-p)
13118 (org-table-justify-field-maybe)
13119 (call-interactively 'org-table-next-row))
13120 (t (if indent (newline-and-indent) (newline)))))
13122 (defun org-return-indent ()
13123 "Goto next table row or insert a newline and indent.
13124 Calls `org-table-next-row' or `newline-and-indent', depending on
13125 context. See the individual commands for more information."
13126 (interactive)
13127 (org-return t))
13129 (defun org-ctrl-c-star ()
13130 "Compute table, or change heading status of lines.
13131 Calls `org-table-recalculate' or `org-toggle-region-headings',
13132 depending on context. This will also turn a plain list item or a normal
13133 line into a subheading."
13134 (interactive)
13135 (cond
13136 ((org-at-table-p)
13137 (call-interactively 'org-table-recalculate))
13138 ((org-region-active-p)
13139 ;; Convert all lines in region to list items
13140 (call-interactively 'org-toggle-region-headings))
13141 ((org-on-heading-p)
13142 (org-toggle-region-headings (point-at-bol)
13143 (min (1+ (point-at-eol)) (point-max))))
13144 ((org-at-item-p)
13145 ;; Convert to heading
13146 (let ((level (save-match-data
13147 (save-excursion
13148 (condition-case nil
13149 (progn
13150 (org-back-to-heading t)
13151 (funcall outline-level))
13152 (error 0))))))
13153 (replace-match
13154 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13155 (t (org-toggle-region-headings (point-at-bol)
13156 (min (1+ (point-at-eol)) (point-max))))))
13158 (defun org-ctrl-c-minus ()
13159 "Insert separator line in table or modify bullet status of line.
13160 Also turns a plain line or a region of lines into list items.
13161 Calls `org-table-insert-hline', `org-toggle-region-items', or
13162 `org-cycle-list-bullet', depending on context."
13163 (interactive)
13164 (cond
13165 ((org-at-table-p)
13166 (call-interactively 'org-table-insert-hline))
13167 ((org-on-heading-p)
13168 ;; Convert to item
13169 (save-excursion
13170 (beginning-of-line 1)
13171 (if (looking-at "\\*+ ")
13172 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13173 ((org-region-active-p)
13174 ;; Convert all lines in region to list items
13175 (call-interactively 'org-toggle-region-items))
13176 ((org-in-item-p)
13177 (call-interactively 'org-cycle-list-bullet))
13178 (t (org-toggle-region-items (point-at-bol)
13179 (min (1+ (point-at-eol)) (point-max))))))
13181 (defun org-toggle-region-items (beg end)
13182 "Convert all lines in region to list items.
13183 If the first line is already an item, convert all list items in the region
13184 to normal lines."
13185 (interactive "r")
13186 (let (l2 l)
13187 (save-excursion
13188 (goto-char end)
13189 (setq l2 (org-current-line))
13190 (goto-char beg)
13191 (beginning-of-line 1)
13192 (setq l (1- (org-current-line)))
13193 (if (org-at-item-p)
13194 ;; We already have items, de-itemize
13195 (while (< (setq l (1+ l)) l2)
13196 (when (org-at-item-p)
13197 (goto-char (match-beginning 2))
13198 (delete-region (match-beginning 2) (match-end 2))
13199 (and (looking-at "[ \t]+") (replace-match "")))
13200 (beginning-of-line 2))
13201 (while (< (setq l (1+ l)) l2)
13202 (unless (org-at-item-p)
13203 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13204 (replace-match "\\1- \\2")))
13205 (beginning-of-line 2))))))
13207 (defun org-toggle-region-headings (beg end)
13208 "Convert all lines in region to list items.
13209 If the first line is already an item, convert all list items in the region
13210 to normal lines."
13211 (interactive "r")
13212 (let (l2 l)
13213 (save-excursion
13214 (goto-char end)
13215 (setq l2 (org-current-line))
13216 (goto-char beg)
13217 (beginning-of-line 1)
13218 (setq l (1- (org-current-line)))
13219 (if (org-on-heading-p)
13220 ;; We already have headlines, de-star them
13221 (while (< (setq l (1+ l)) l2)
13222 (when (org-on-heading-p t)
13223 (and (looking-at outline-regexp) (replace-match "")))
13224 (beginning-of-line 2))
13225 (let* ((stars (save-excursion
13226 (re-search-backward org-complex-heading-regexp nil t)
13227 (or (match-string 1) "*")))
13228 (add-stars (if org-odd-levels-only "**" "*"))
13229 (rpl (concat stars add-stars " \\2")))
13230 (while (< (setq l (1+ l)) l2)
13231 (unless (org-on-heading-p)
13232 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13233 (replace-match rpl)))
13234 (beginning-of-line 2)))))))
13236 (defun org-meta-return (&optional arg)
13237 "Insert a new heading or wrap a region in a table.
13238 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13239 See the individual commands for more information."
13240 (interactive "P")
13241 (cond
13242 ((org-at-table-p)
13243 (call-interactively 'org-table-wrap-region))
13244 (t (call-interactively 'org-insert-heading))))
13246 ;;; Menu entries
13248 ;; Define the Org-mode menus
13249 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13250 '("Tbl"
13251 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13252 ["Next Field" org-cycle (org-at-table-p)]
13253 ["Previous Field" org-shifttab (org-at-table-p)]
13254 ["Next Row" org-return (org-at-table-p)]
13255 "--"
13256 ["Blank Field" org-table-blank-field (org-at-table-p)]
13257 ["Edit Field" org-table-edit-field (org-at-table-p)]
13258 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13259 "--"
13260 ("Column"
13261 ["Move Column Left" org-metaleft (org-at-table-p)]
13262 ["Move Column Right" org-metaright (org-at-table-p)]
13263 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13264 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13265 ("Row"
13266 ["Move Row Up" org-metaup (org-at-table-p)]
13267 ["Move Row Down" org-metadown (org-at-table-p)]
13268 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13269 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13270 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13271 "--"
13272 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13273 ("Rectangle"
13274 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13275 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13276 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13277 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13278 "--"
13279 ("Calculate"
13280 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13281 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13282 ["Edit Formulas" org-edit-special (org-at-table-p)]
13283 "--"
13284 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13285 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13286 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13287 "--"
13288 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13289 "--"
13290 ["Sum Column/Rectangle" org-table-sum
13291 (or (org-at-table-p) (org-region-active-p))]
13292 ["Which Column?" org-table-current-column (org-at-table-p)])
13293 ["Debug Formulas"
13294 org-table-toggle-formula-debugger
13295 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13296 ["Show Col/Row Numbers"
13297 org-table-toggle-coordinate-overlays
13298 :style toggle
13299 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13300 "--"
13301 ["Create" org-table-create (and (not (org-at-table-p))
13302 org-enable-table-editor)]
13303 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13304 ["Import from File" org-table-import (not (org-at-table-p))]
13305 ["Export to File" org-table-export (org-at-table-p)]
13306 "--"
13307 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13309 (easy-menu-define org-org-menu org-mode-map "Org menu"
13310 '("Org"
13311 ("Show/Hide"
13312 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13313 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13314 ["Sparse Tree..." org-sparse-tree t]
13315 ["Reveal Context" org-reveal t]
13316 ["Show All" show-all t]
13317 "--"
13318 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13319 "--"
13320 ["New Heading" org-insert-heading t]
13321 ("Navigate Headings"
13322 ["Up" outline-up-heading t]
13323 ["Next" outline-next-visible-heading t]
13324 ["Previous" outline-previous-visible-heading t]
13325 ["Next Same Level" outline-forward-same-level t]
13326 ["Previous Same Level" outline-backward-same-level t]
13327 "--"
13328 ["Jump" org-goto t])
13329 ("Edit Structure"
13330 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13331 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13332 "--"
13333 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13334 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13335 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13336 "--"
13337 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13338 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13339 ["Demote Heading" org-metaright (not (org-at-table-p))]
13340 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13341 "--"
13342 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13343 "--"
13344 ["Convert to odd levels" org-convert-to-odd-levels t]
13345 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13346 ("Editing"
13347 ["Emphasis..." org-emphasize t]
13348 ["Edit Source Example" org-edit-special t])
13349 ("Archive"
13350 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13351 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13352 ; :active t :keys "C-u C-c C-x C-a"]
13353 ["Sparse trees open ARCHIVE trees"
13354 (setq org-sparse-tree-open-archived-trees
13355 (not org-sparse-tree-open-archived-trees))
13356 :style toggle :selected org-sparse-tree-open-archived-trees]
13357 ["Cycling opens ARCHIVE trees"
13358 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13359 :style toggle :selected org-cycle-open-archived-trees]
13360 "--"
13361 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13362 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13363 ; ["Check and Move Children" (org-archive-subtree '(4))
13364 ; :active t :keys "C-u C-c C-x C-s"]
13366 "--"
13367 ("TODO Lists"
13368 ["TODO/DONE/-" org-todo t]
13369 ("Select keyword"
13370 ["Next keyword" org-shiftright (org-on-heading-p)]
13371 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13372 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13373 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13374 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13375 ["Show TODO Tree" org-show-todo-tree t]
13376 ["Global TODO list" org-todo-list t]
13377 "--"
13378 ["Set Priority" org-priority t]
13379 ["Priority Up" org-shiftup t]
13380 ["Priority Down" org-shiftdown t])
13381 ("TAGS and Properties"
13382 ["Set Tags" org-set-tags-command t]
13383 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13384 "--"
13385 ["Set property" org-set-property t]
13386 ["Column view of properties" org-columns t]
13387 ["Insert Column View DBlock" org-insert-columns-dblock t])
13388 ("Dates and Scheduling"
13389 ["Timestamp" org-time-stamp t]
13390 ["Timestamp (inactive)" org-time-stamp-inactive t]
13391 ("Change Date"
13392 ["1 Day Later" org-shiftright t]
13393 ["1 Day Earlier" org-shiftleft t]
13394 ["1 ... Later" org-shiftup t]
13395 ["1 ... Earlier" org-shiftdown t])
13396 ["Compute Time Range" org-evaluate-time-range t]
13397 ["Schedule Item" org-schedule t]
13398 ["Deadline" org-deadline t]
13399 "--"
13400 ["Custom time format" org-toggle-time-stamp-overlays
13401 :style radio :selected org-display-custom-times]
13402 "--"
13403 ["Goto Calendar" org-goto-calendar t]
13404 ["Date from Calendar" org-date-from-calendar t]
13405 "--"
13406 ["Start/restart timer" org-timer-start t]
13407 ["Insert timer string" org-timer t]
13408 ["Insert timer item" org-timer-item t])
13409 ("Logging work"
13410 ["Clock in" org-clock-in t]
13411 ["Clock out" org-clock-out t]
13412 ["Clock cancel" org-clock-cancel t]
13413 ["Goto running clock" org-clock-goto t]
13414 ["Display times" org-clock-display t]
13415 ["Create clock table" org-clock-report t]
13416 "--"
13417 ["Record DONE time"
13418 (progn (setq org-log-done (not org-log-done))
13419 (message "Switching to %s will %s record a timestamp"
13420 (car org-done-keywords)
13421 (if org-log-done "automatically" "not")))
13422 :style toggle :selected org-log-done])
13423 "--"
13424 ["Agenda Command..." org-agenda t]
13425 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13426 ("File List for Agenda")
13427 ("Special views current file"
13428 ["TODO Tree" org-show-todo-tree t]
13429 ["Check Deadlines" org-check-deadlines t]
13430 ["Timeline" org-timeline t]
13431 ["Tags Tree" org-tags-sparse-tree t])
13432 "--"
13433 ("Hyperlinks"
13434 ["Store Link (Global)" org-store-link t]
13435 ["Insert Link" org-insert-link t]
13436 ["Follow Link" org-open-at-point t]
13437 "--"
13438 ["Next link" org-next-link t]
13439 ["Previous link" org-previous-link t]
13440 "--"
13441 ["Descriptive Links"
13442 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13443 :style radio
13444 :selected (member '(org-link) buffer-invisibility-spec)]
13445 ["Literal Links"
13446 (progn
13447 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13448 :style radio
13449 :selected (not (member '(org-link) buffer-invisibility-spec))])
13450 "--"
13451 ["Export/Publish..." org-export t]
13452 ("LaTeX"
13453 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13454 :selected org-cdlatex-mode]
13455 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13456 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13457 ["Modify math symbol" org-cdlatex-math-modify
13458 (org-inside-LaTeX-fragment-p)]
13459 ["Export LaTeX fragments as images"
13460 (if (featurep 'org-exp)
13461 (setq org-export-with-LaTeX-fragments
13462 (not org-export-with-LaTeX-fragments))
13463 (require 'org-exp))
13464 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13465 org-export-with-LaTeX-fragments)])
13466 "--"
13467 ("Documentation"
13468 ["Show Version" org-version t]
13469 ["Info Documentation" org-info t])
13470 ("Customize"
13471 ["Browse Org Group" org-customize t]
13472 "--"
13473 ["Expand This Menu" org-create-customize-menu
13474 (fboundp 'customize-menu-create)])
13475 "--"
13476 ["Refresh setup" org-mode-restart t]
13479 (defun org-info (&optional node)
13480 "Read documentation for Org-mode in the info system.
13481 With optional NODE, go directly to that node."
13482 (interactive)
13483 (info (format "(org)%s" (or node ""))))
13485 (defun org-install-agenda-files-menu ()
13486 (let ((bl (buffer-list)))
13487 (save-excursion
13488 (while bl
13489 (set-buffer (pop bl))
13490 (if (org-mode-p) (setq bl nil)))
13491 (when (org-mode-p)
13492 (easy-menu-change
13493 '("Org") "File List for Agenda"
13494 (append
13495 (list
13496 ["Edit File List" (org-edit-agenda-file-list) t]
13497 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13498 ["Remove Current File from List" org-remove-file t]
13499 ["Cycle through agenda files" org-cycle-agenda-files t]
13500 ["Occur in all agenda files" org-occur-in-agenda-files t]
13501 "--")
13502 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13504 ;;;; Documentation
13506 ;;;###autoload
13507 (defun org-require-autoloaded-modules ()
13508 (interactive)
13509 (mapc 'require
13510 '(org-agenda org-archive org-clock org-colview
13511 org-exp org-id org-export-latex org-publish
13512 org-remember org-table)))
13514 ;;;###autoload
13515 (defun org-customize ()
13516 "Call the customize function with org as argument."
13517 (interactive)
13518 (org-load-modules-maybe)
13519 (org-require-autoloaded-modules)
13520 (customize-browse 'org))
13522 (defun org-create-customize-menu ()
13523 "Create a full customization menu for Org-mode, insert it into the menu."
13524 (interactive)
13525 (org-load-modules-maybe)
13526 (org-require-autoloaded-modules)
13527 (if (fboundp 'customize-menu-create)
13528 (progn
13529 (easy-menu-change
13530 '("Org") "Customize"
13531 `(["Browse Org group" org-customize t]
13532 "--"
13533 ,(customize-menu-create 'org)
13534 ["Set" Custom-set t]
13535 ["Save" Custom-save t]
13536 ["Reset to Current" Custom-reset-current t]
13537 ["Reset to Saved" Custom-reset-saved t]
13538 ["Reset to Standard Settings" Custom-reset-standard t]))
13539 (message "\"Org\"-menu now contains full customization menu"))
13540 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13542 ;;;; Miscellaneous stuff
13544 ;;; Generally useful functions
13546 (defun org-find-text-property-in-string (prop s)
13547 "Return the first non-nil value of property PROP in string S."
13548 (or (get-text-property 0 prop s)
13549 (get-text-property (or (next-single-property-change 0 prop s) 0)
13550 prop s)))
13552 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13553 "Display the given MESSAGE as a warning."
13554 (if (fboundp 'display-warning)
13555 (display-warning 'org message
13556 (if (featurep 'xemacs)
13557 'warning
13558 :warning))
13559 (let ((buf (get-buffer-create "*Org warnings*")))
13560 (with-current-buffer buf
13561 (goto-char (point-max))
13562 (insert "Warning (Org): " message)
13563 (unless (bolp)
13564 (newline)))
13565 (display-buffer buf)
13566 (sit-for 0))))
13568 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13569 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13570 (if (and marker (marker-buffer marker)
13571 (buffer-live-p (marker-buffer marker)))
13572 (progn
13573 (switch-to-buffer (marker-buffer marker))
13574 (if (or (> marker (point-max)) (< marker (point-min)))
13575 (widen))
13576 (goto-char marker))
13577 (if bookmark
13578 (bookmark-jump bookmark)
13579 (error "Cannot find location"))))
13581 (defun org-quote-csv-field (s)
13582 "Quote field for inclusion in CSV material."
13583 (if (string-match "[\",]" s)
13584 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13587 (defun org-plist-delete (plist property)
13588 "Delete PROPERTY from PLIST.
13589 This is in contrast to merely setting it to 0."
13590 (let (p)
13591 (while plist
13592 (if (not (eq property (car plist)))
13593 (setq p (plist-put p (car plist) (nth 1 plist))))
13594 (setq plist (cddr plist)))
13597 (defun org-force-self-insert (N)
13598 "Needed to enforce self-insert under remapping."
13599 (interactive "p")
13600 (self-insert-command N))
13602 (defun org-string-width (s)
13603 "Compute width of string, ignoring invisible characters.
13604 This ignores character with invisibility property `org-link', and also
13605 characters with property `org-cwidth', because these will become invisible
13606 upon the next fontification round."
13607 (let (b l)
13608 (when (or (eq t buffer-invisibility-spec)
13609 (assq 'org-link buffer-invisibility-spec))
13610 (while (setq b (text-property-any 0 (length s)
13611 'invisible 'org-link s))
13612 (setq s (concat (substring s 0 b)
13613 (substring s (or (next-single-property-change
13614 b 'invisible s) (length s)))))))
13615 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13616 (setq s (concat (substring s 0 b)
13617 (substring s (or (next-single-property-change
13618 b 'org-cwidth s) (length s))))))
13619 (setq l (string-width s) b -1)
13620 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13621 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13624 (defun org-get-indentation (&optional line)
13625 "Get the indentation of the current line, interpreting tabs.
13626 When LINE is given, assume it represents a line and compute its indentation."
13627 (if line
13628 (if (string-match "^ *" (org-remove-tabs line))
13629 (match-end 0))
13630 (save-excursion
13631 (beginning-of-line 1)
13632 (skip-chars-forward " \t")
13633 (current-column))))
13635 (defun org-remove-tabs (s &optional width)
13636 "Replace tabulators in S with spaces.
13637 Assumes that s is a single line, starting in column 0."
13638 (setq width (or width tab-width))
13639 (while (string-match "\t" s)
13640 (setq s (replace-match
13641 (make-string
13642 (- (* width (/ (+ (match-beginning 0) width) width))
13643 (match-beginning 0)) ?\ )
13644 t t s)))
13647 (defun org-fix-indentation (line ind)
13648 "Fix indentation in LINE.
13649 IND is a cons cell with target and minimum indentation.
13650 If the current indentation in LINE is smaller than the minimum,
13651 leave it alone. If it is larger than ind, set it to the target."
13652 (let* ((l (org-remove-tabs line))
13653 (i (org-get-indentation l))
13654 (i1 (car ind)) (i2 (cdr ind)))
13655 (if (>= i i2) (setq l (substring line i2)))
13656 (if (> i1 0)
13657 (concat (make-string i1 ?\ ) l)
13658 l)))
13660 (defun org-base-buffer (buffer)
13661 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13662 (if (not buffer)
13663 buffer
13664 (or (buffer-base-buffer buffer)
13665 buffer)))
13667 (defun org-trim (s)
13668 "Remove whitespace at beginning and end of string."
13669 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13670 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13673 (defun org-wrap (string &optional width lines)
13674 "Wrap string to either a number of lines, or a width in characters.
13675 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13676 that costs. If there is a word longer than WIDTH, the text is actually
13677 wrapped to the length of that word.
13678 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13679 many lines, whatever width that takes.
13680 The return value is a list of lines, without newlines at the end."
13681 (let* ((words (org-split-string string "[ \t\n]+"))
13682 (maxword (apply 'max (mapcar 'org-string-width words)))
13683 w ll)
13684 (cond (width
13685 (org-do-wrap words (max maxword width)))
13686 (lines
13687 (setq w maxword)
13688 (setq ll (org-do-wrap words maxword))
13689 (if (<= (length ll) lines)
13691 (setq ll words)
13692 (while (> (length ll) lines)
13693 (setq w (1+ w))
13694 (setq ll (org-do-wrap words w)))
13695 ll))
13696 (t (error "Cannot wrap this")))))
13698 (defun org-do-wrap (words width)
13699 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13700 (let (lines line)
13701 (while words
13702 (setq line (pop words))
13703 (while (and words (< (+ (length line) (length (car words))) width))
13704 (setq line (concat line " " (pop words))))
13705 (setq lines (push line lines)))
13706 (nreverse lines)))
13708 (defun org-split-string (string &optional separators)
13709 "Splits STRING into substrings at SEPARATORS.
13710 No empty strings are returned if there are matches at the beginning
13711 and end of string."
13712 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13713 (start 0)
13714 notfirst
13715 (list nil))
13716 (while (and (string-match rexp string
13717 (if (and notfirst
13718 (= start (match-beginning 0))
13719 (< start (length string)))
13720 (1+ start) start))
13721 (< (match-beginning 0) (length string)))
13722 (setq notfirst t)
13723 (or (eq (match-beginning 0) 0)
13724 (and (eq (match-beginning 0) (match-end 0))
13725 (eq (match-beginning 0) start))
13726 (setq list
13727 (cons (substring string start (match-beginning 0))
13728 list)))
13729 (setq start (match-end 0)))
13730 (or (eq start (length string))
13731 (setq list
13732 (cons (substring string start)
13733 list)))
13734 (nreverse list)))
13736 (defun org-context ()
13737 "Return a list of contexts of the current cursor position.
13738 If several contexts apply, all are returned.
13739 Each context entry is a list with a symbol naming the context, and
13740 two positions indicating start and end of the context. Possible
13741 contexts are:
13743 :headline anywhere in a headline
13744 :headline-stars on the leading stars in a headline
13745 :todo-keyword on a TODO keyword (including DONE) in a headline
13746 :tags on the TAGS in a headline
13747 :priority on the priority cookie in a headline
13748 :item on the first line of a plain list item
13749 :item-bullet on the bullet/number of a plain list item
13750 :checkbox on the checkbox in a plain list item
13751 :table in an org-mode table
13752 :table-special on a special filed in a table
13753 :table-table in a table.el table
13754 :link on a hyperlink
13755 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13756 :target on a <<target>>
13757 :radio-target on a <<<radio-target>>>
13758 :latex-fragment on a LaTeX fragment
13759 :latex-preview on a LaTeX fragment with overlayed preview image
13761 This function expects the position to be visible because it uses font-lock
13762 faces as a help to recognize the following contexts: :table-special, :link,
13763 and :keyword."
13764 (let* ((f (get-text-property (point) 'face))
13765 (faces (if (listp f) f (list f)))
13766 (p (point)) clist o)
13767 ;; First the large context
13768 (cond
13769 ((org-on-heading-p t)
13770 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13771 (when (progn
13772 (beginning-of-line 1)
13773 (looking-at org-todo-line-tags-regexp))
13774 (push (org-point-in-group p 1 :headline-stars) clist)
13775 (push (org-point-in-group p 2 :todo-keyword) clist)
13776 (push (org-point-in-group p 4 :tags) clist))
13777 (goto-char p)
13778 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13779 (if (looking-at "\\[#[A-Z0-9]\\]")
13780 (push (org-point-in-group p 0 :priority) clist)))
13782 ((org-at-item-p)
13783 (push (org-point-in-group p 2 :item-bullet) clist)
13784 (push (list :item (point-at-bol)
13785 (save-excursion (org-end-of-item) (point)))
13786 clist)
13787 (and (org-at-item-checkbox-p)
13788 (push (org-point-in-group p 0 :checkbox) clist)))
13790 ((org-at-table-p)
13791 (push (list :table (org-table-begin) (org-table-end)) clist)
13792 (if (memq 'org-formula faces)
13793 (push (list :table-special
13794 (previous-single-property-change p 'face)
13795 (next-single-property-change p 'face)) clist)))
13796 ((org-at-table-p 'any)
13797 (push (list :table-table) clist)))
13798 (goto-char p)
13800 ;; Now the small context
13801 (cond
13802 ((org-at-timestamp-p)
13803 (push (org-point-in-group p 0 :timestamp) clist))
13804 ((memq 'org-link faces)
13805 (push (list :link
13806 (previous-single-property-change p 'face)
13807 (next-single-property-change p 'face)) clist))
13808 ((memq 'org-special-keyword faces)
13809 (push (list :keyword
13810 (previous-single-property-change p 'face)
13811 (next-single-property-change p 'face)) clist))
13812 ((org-on-target-p)
13813 (push (org-point-in-group p 0 :target) clist)
13814 (goto-char (1- (match-beginning 0)))
13815 (if (looking-at org-radio-target-regexp)
13816 (push (org-point-in-group p 0 :radio-target) clist))
13817 (goto-char p))
13818 ((setq o (car (delq nil
13819 (mapcar
13820 (lambda (x)
13821 (if (memq x org-latex-fragment-image-overlays) x))
13822 (org-overlays-at (point))))))
13823 (push (list :latex-fragment
13824 (org-overlay-start o) (org-overlay-end o)) clist)
13825 (push (list :latex-preview
13826 (org-overlay-start o) (org-overlay-end o)) clist))
13827 ((org-inside-LaTeX-fragment-p)
13828 ;; FIXME: positions wrong.
13829 (push (list :latex-fragment (point) (point)) clist)))
13831 (setq clist (nreverse (delq nil clist)))
13832 clist))
13834 ;; FIXME: Compare with at-regexp-p Do we need both?
13835 (defun org-in-regexp (re &optional nlines visually)
13836 "Check if point is inside a match of regexp.
13837 Normally only the current line is checked, but you can include NLINES extra
13838 lines both before and after point into the search.
13839 If VISUALLY is set, require that the cursor is not after the match but
13840 really on, so that the block visually is on the match."
13841 (catch 'exit
13842 (let ((pos (point))
13843 (eol (point-at-eol (+ 1 (or nlines 0))))
13844 (inc (if visually 1 0)))
13845 (save-excursion
13846 (beginning-of-line (- 1 (or nlines 0)))
13847 (while (re-search-forward re eol t)
13848 (if (and (<= (match-beginning 0) pos)
13849 (>= (+ inc (match-end 0)) pos))
13850 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13852 (defun org-at-regexp-p (regexp)
13853 "Is point inside a match of REGEXP in the current line?"
13854 (catch 'exit
13855 (save-excursion
13856 (let ((pos (point)) (end (point-at-eol)))
13857 (beginning-of-line 1)
13858 (while (re-search-forward regexp end t)
13859 (if (and (<= (match-beginning 0) pos)
13860 (>= (match-end 0) pos))
13861 (throw 'exit t)))
13862 nil))))
13864 (defun org-occur-in-agenda-files (regexp &optional nlines)
13865 "Call `multi-occur' with buffers for all agenda files."
13866 (interactive "sOrg-files matching: \np")
13867 (let* ((files (org-agenda-files))
13868 (tnames (mapcar 'file-truename files))
13869 (extra org-agenda-text-search-extra-files)
13871 (when (eq (car extra) 'agenda-archives)
13872 (setq extra (cdr extra))
13873 (setq files (org-add-archive-files files)))
13874 (while (setq f (pop extra))
13875 (unless (member (file-truename f) tnames)
13876 (add-to-list 'files f 'append)
13877 (add-to-list 'tnames (file-truename f) 'append)))
13878 (multi-occur
13879 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13880 regexp)))
13882 (if (boundp 'occur-mode-find-occurrence-hook)
13883 ;; Emacs 23
13884 (add-hook 'occur-mode-find-occurrence-hook
13885 (lambda ()
13886 (when (org-mode-p)
13887 (org-reveal))))
13888 ;; Emacs 22
13889 (defadvice occur-mode-goto-occurrence
13890 (after org-occur-reveal activate)
13891 (and (org-mode-p) (org-reveal)))
13892 (defadvice occur-mode-goto-occurrence-other-window
13893 (after org-occur-reveal activate)
13894 (and (org-mode-p) (org-reveal)))
13895 (defadvice occur-mode-display-occurrence
13896 (after org-occur-reveal activate)
13897 (when (org-mode-p)
13898 (let ((pos (occur-mode-find-occurrence)))
13899 (with-current-buffer (marker-buffer pos)
13900 (save-excursion
13901 (goto-char pos)
13902 (org-reveal)))))))
13904 (defun org-uniquify (list)
13905 "Remove duplicate elements from LIST."
13906 (let (res)
13907 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13908 res))
13910 (defun org-delete-all (elts list)
13911 "Remove all elements in ELTS from LIST."
13912 (while elts
13913 (setq list (delete (pop elts) list)))
13914 list)
13916 (defun org-back-over-empty-lines ()
13917 "Move backwards over whitespace, to the beginning of the first empty line.
13918 Returns the number of empty lines passed."
13919 (let ((pos (point)))
13920 (skip-chars-backward " \t\n\r")
13921 (beginning-of-line 2)
13922 (goto-char (min (point) pos))
13923 (count-lines (point) pos)))
13925 (defun org-skip-whitespace ()
13926 (skip-chars-forward " \t\n\r"))
13928 (defun org-point-in-group (point group &optional context)
13929 "Check if POINT is in match-group GROUP.
13930 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13931 match. If the match group does ot exist or point is not inside it,
13932 return nil."
13933 (and (match-beginning group)
13934 (>= point (match-beginning group))
13935 (<= point (match-end group))
13936 (if context
13937 (list context (match-beginning group) (match-end group))
13938 t)))
13940 (defun org-switch-to-buffer-other-window (&rest args)
13941 "Switch to buffer in a second window on the current frame.
13942 In particular, do not allow pop-up frames."
13943 (let (pop-up-frames special-display-buffer-names special-display-regexps
13944 special-display-function)
13945 (apply 'switch-to-buffer-other-window args)))
13947 (defun org-combine-plists (&rest plists)
13948 "Create a single property list from all plists in PLISTS.
13949 The process starts by copying the first list, and then setting properties
13950 from the other lists. Settings in the last list are the most significant
13951 ones and overrule settings in the other lists."
13952 (let ((rtn (copy-sequence (pop plists)))
13953 p v ls)
13954 (while plists
13955 (setq ls (pop plists))
13956 (while ls
13957 (setq p (pop ls) v (pop ls))
13958 (setq rtn (plist-put rtn p v))))
13959 rtn))
13961 (defun org-move-line-down (arg)
13962 "Move the current line down. With prefix argument, move it past ARG lines."
13963 (interactive "p")
13964 (let ((col (current-column))
13965 beg end pos)
13966 (beginning-of-line 1) (setq beg (point))
13967 (beginning-of-line 2) (setq end (point))
13968 (beginning-of-line (+ 1 arg))
13969 (setq pos (move-marker (make-marker) (point)))
13970 (insert (delete-and-extract-region beg end))
13971 (goto-char pos)
13972 (org-move-to-column col)))
13974 (defun org-move-line-up (arg)
13975 "Move the current line up. With prefix argument, move it past ARG lines."
13976 (interactive "p")
13977 (let ((col (current-column))
13978 beg end pos)
13979 (beginning-of-line 1) (setq beg (point))
13980 (beginning-of-line 2) (setq end (point))
13981 (beginning-of-line (- arg))
13982 (setq pos (move-marker (make-marker) (point)))
13983 (insert (delete-and-extract-region beg end))
13984 (goto-char pos)
13985 (org-move-to-column col)))
13987 (defun org-replace-escapes (string table)
13988 "Replace %-escapes in STRING with values in TABLE.
13989 TABLE is an association list with keys like \"%a\" and string values.
13990 The sequences in STRING may contain normal field width and padding information,
13991 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13992 so values can contain further %-escapes if they are define later in TABLE."
13993 (let ((case-fold-search nil)
13994 e re rpl)
13995 (while (setq e (pop table))
13996 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13997 (while (string-match re string)
13998 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13999 (cdr e)))
14000 (setq string (replace-match rpl t t string))))
14001 string))
14004 (defun org-sublist (list start end)
14005 "Return a section of LIST, from START to END.
14006 Counting starts at 1."
14007 (let (rtn (c start))
14008 (setq list (nthcdr (1- start) list))
14009 (while (and list (<= c end))
14010 (push (pop list) rtn)
14011 (setq c (1+ c)))
14012 (nreverse rtn)))
14014 (defun org-find-base-buffer-visiting (file)
14015 "Like `find-buffer-visiting' but alway return the base buffer and
14016 not an indirect buffer."
14017 (let ((buf (find-buffer-visiting file)))
14018 (if buf
14019 (or (buffer-base-buffer buf) buf)
14020 nil)))
14022 (defun org-image-file-name-regexp ()
14023 "Return regexp matching the file names of images."
14024 (if (fboundp 'image-file-name-regexp)
14025 (image-file-name-regexp)
14026 (let ((image-file-name-extensions
14027 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14028 "xbm" "xpm" "pbm" "pgm" "ppm")))
14029 (concat "\\."
14030 (regexp-opt (nconc (mapcar 'upcase
14031 image-file-name-extensions)
14032 image-file-name-extensions)
14034 "\\'"))))
14036 (defun org-file-image-p (file)
14037 "Return non-nil if FILE is an image."
14038 (save-match-data
14039 (string-match (org-image-file-name-regexp) file)))
14041 (defun org-get-cursor-date ()
14042 "Return the date at cursor in as a time.
14043 This works in the calendar and in the agenda, anywhere else it just
14044 returns the current time."
14045 (let (date day defd)
14046 (cond
14047 ((eq major-mode 'calendar-mode)
14048 (setq date (calendar-cursor-to-date)
14049 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14050 ((eq major-mode 'org-agenda-mode)
14051 (setq day (get-text-property (point) 'day))
14052 (if day
14053 (setq date (calendar-gregorian-from-absolute day)
14054 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14055 (nth 2 date))))))
14056 (or defd (current-time))))
14058 (defvar org-agenda-action-marker (make-marker)
14059 "Marker pointing to the entry for the next agenda action.")
14061 (defun org-mark-entry-for-agenda-action ()
14062 "Mark the current entry as target of an agenda action.
14063 Agenda actions are actions executed from the agenda with the key `k',
14064 which make use of the date at the cursor."
14065 (interactive)
14066 (move-marker org-agenda-action-marker
14067 (save-excursion (org-back-to-heading t) (point))
14068 (current-buffer))
14069 (message
14070 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14072 ;;; Paragraph filling stuff.
14073 ;; We want this to be just right, so use the full arsenal.
14075 (defun org-indent-line-function ()
14076 "Indent line like previous, but further if previous was headline or item."
14077 (interactive)
14078 (let* ((pos (point))
14079 (itemp (org-at-item-p))
14080 column bpos bcol tpos tcol bullet btype bullet-type)
14081 ;; Find the previous relevant line
14082 (beginning-of-line 1)
14083 (cond
14084 ((looking-at "#") (setq column 0))
14085 ((looking-at "\\*+ ") (setq column 0))
14087 (beginning-of-line 0)
14088 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14089 (beginning-of-line 0))
14090 (cond
14091 ((looking-at "\\*+[ \t]+")
14092 (if (not org-adapt-indentation)
14093 (setq column 0)
14094 (goto-char (match-end 0))
14095 (setq column (current-column))))
14096 ((org-in-item-p)
14097 (org-beginning-of-item)
14098 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14099 (setq bpos (match-beginning 1) tpos (match-end 0)
14100 bcol (progn (goto-char bpos) (current-column))
14101 tcol (progn (goto-char tpos) (current-column))
14102 bullet (match-string 1)
14103 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14104 (if (> tcol (+ bcol org-description-max-indent))
14105 (setq tcol (+ bcol 5)))
14106 (if (not itemp)
14107 (setq column tcol)
14108 (goto-char pos)
14109 (beginning-of-line 1)
14110 (if (looking-at "\\S-")
14111 (progn
14112 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14113 (setq bullet (match-string 1)
14114 btype (if (string-match "[0-9]" bullet) "n" bullet))
14115 (setq column (if (equal btype bullet-type) bcol tcol)))
14116 (setq column (org-get-indentation)))))
14117 (t (setq column (org-get-indentation))))))
14118 (goto-char pos)
14119 (if (<= (current-column) (current-indentation))
14120 (org-indent-line-to column)
14121 (save-excursion (org-indent-line-to column)))
14122 (setq column (current-column))
14123 (beginning-of-line 1)
14124 (if (looking-at
14125 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14126 (replace-match (concat "\\1" (format org-property-format
14127 (match-string 2) (match-string 3)))
14128 t nil))
14129 (org-move-to-column column)))
14131 (defun org-set-autofill-regexps ()
14132 (interactive)
14133 ;; In the paragraph separator we include headlines, because filling
14134 ;; text in a line directly attached to a headline would otherwise
14135 ;; fill the headline as well.
14136 (org-set-local 'comment-start-skip "^#+[ \t]*")
14137 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14138 ;; The paragraph starter includes hand-formatted lists.
14139 (org-set-local 'paragraph-start
14140 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14141 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14142 ;; But only if the user has not turned off tables or fixed-width regions
14143 (org-set-local
14144 'auto-fill-inhibit-regexp
14145 (concat "\\*+ \\|#\\+"
14146 "\\|[ \t]*" org-keyword-time-regexp
14147 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14148 (concat
14149 "\\|[ \t]*["
14150 (if org-enable-table-editor "|" "")
14151 (if org-enable-fixed-width-editor ":" "")
14152 "]"))))
14153 ;; We use our own fill-paragraph function, to make sure that tables
14154 ;; and fixed-width regions are not wrapped. That function will pass
14155 ;; through to `fill-paragraph' when appropriate.
14156 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14157 ; Adaptive filling: To get full control, first make sure that
14158 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14159 (org-set-local 'adaptive-fill-regexp "\000")
14160 (org-set-local 'adaptive-fill-function
14161 'org-adaptive-fill-function)
14162 (org-set-local
14163 'align-mode-rules-list
14164 '((org-in-buffer-settings
14165 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14166 (modes . '(org-mode))))))
14168 (defun org-fill-paragraph (&optional justify)
14169 "Re-align a table, pass through to fill-paragraph if no table."
14170 (let ((table-p (org-at-table-p))
14171 (table.el-p (org-at-table.el-p)))
14172 (cond ((and (equal (char-after (point-at-bol)) ?*)
14173 (save-excursion (goto-char (point-at-bol))
14174 (looking-at outline-regexp)))
14175 t) ; skip headlines
14176 (table.el-p t) ; skip table.el tables
14177 (table-p (org-table-align) t) ; align org-mode tables
14178 (t nil)))) ; call paragraph-fill
14180 ;; For reference, this is the default value of adaptive-fill-regexp
14181 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14183 (defun org-adaptive-fill-function ()
14184 "Return a fill prefix for org-mode files.
14185 In particular, this makes sure hanging paragraphs for hand-formatted lists
14186 work correctly."
14187 (cond ((looking-at "#[ \t]+")
14188 (match-string 0))
14189 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14190 (save-excursion
14191 (if (> (match-end 1) (+ (match-beginning 1)
14192 org-description-max-indent))
14193 (goto-char (+ (match-beginning 1) 5))
14194 (goto-char (match-end 0)))
14195 (make-string (current-column) ?\ )))
14196 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14197 (save-excursion
14198 (goto-char (match-end 0))
14199 (make-string (current-column) ?\ )))
14200 (t nil)))
14202 ;;; Other stuff.
14204 (defun org-toggle-fixed-width-section (arg)
14205 "Toggle the fixed-width export.
14206 If there is no active region, the QUOTE keyword at the current headline is
14207 inserted or removed. When present, it causes the text between this headline
14208 and the next to be exported as fixed-width text, and unmodified.
14209 If there is an active region, this command adds or removes a colon as the
14210 first character of this line. If the first character of a line is a colon,
14211 this line is also exported in fixed-width font."
14212 (interactive "P")
14213 (let* ((cc 0)
14214 (regionp (org-region-active-p))
14215 (beg (if regionp (region-beginning) (point)))
14216 (end (if regionp (region-end)))
14217 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14218 (case-fold-search nil)
14219 (re "[ \t]*\\(:\\)")
14220 off)
14221 (if regionp
14222 (save-excursion
14223 (goto-char beg)
14224 (setq cc (current-column))
14225 (beginning-of-line 1)
14226 (setq off (looking-at re))
14227 (while (> nlines 0)
14228 (setq nlines (1- nlines))
14229 (beginning-of-line 1)
14230 (cond
14231 (arg
14232 (org-move-to-column cc t)
14233 (insert ":\n")
14234 (forward-line -1))
14235 ((and off (looking-at re))
14236 (replace-match "" t t nil 1))
14237 ((not off) (org-move-to-column cc t) (insert ":")))
14238 (forward-line 1)))
14239 (save-excursion
14240 (org-back-to-heading)
14241 (if (looking-at (concat outline-regexp
14242 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14243 (replace-match "" t t nil 1)
14244 (if (looking-at outline-regexp)
14245 (progn
14246 (goto-char (match-end 0))
14247 (insert org-quote-string " "))))))))
14249 ;;;; Functions extending outline functionality
14251 (defun org-beginning-of-line (&optional arg)
14252 "Go to the beginning of the current line. If that is invisible, continue
14253 to a visible line beginning. This makes the function of C-a more intuitive.
14254 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14255 first attempt, and only move to after the tags when the cursor is already
14256 beyond the end of the headline."
14257 (interactive "P")
14258 (let ((pos (point)) refpos)
14259 (beginning-of-line 1)
14260 (if (bobp)
14262 (backward-char 1)
14263 (if (org-invisible-p)
14264 (while (and (not (bobp)) (org-invisible-p))
14265 (backward-char 1)
14266 (beginning-of-line 1))
14267 (forward-char 1)))
14268 (when org-special-ctrl-a/e
14269 (cond
14270 ((and (looking-at org-complex-heading-regexp)
14271 (= (char-after (match-end 1)) ?\ ))
14272 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14273 (point-at-eol)))
14274 (goto-char
14275 (if (eq org-special-ctrl-a/e t)
14276 (cond ((> pos refpos) refpos)
14277 ((= pos (point)) refpos)
14278 (t (point)))
14279 (cond ((> pos (point)) (point))
14280 ((not (eq last-command this-command)) (point))
14281 (t refpos)))))
14282 ((org-at-item-p)
14283 (goto-char
14284 (if (eq org-special-ctrl-a/e t)
14285 (cond ((> pos (match-end 4)) (match-end 4))
14286 ((= pos (point)) (match-end 4))
14287 (t (point)))
14288 (cond ((> pos (point)) (point))
14289 ((not (eq last-command this-command)) (point))
14290 (t (match-end 4))))))))
14291 (org-no-warnings
14292 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14294 (defun org-end-of-line (&optional arg)
14295 "Go to the end of the line.
14296 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14297 first attempt, and only move to after the tags when the cursor is already
14298 beyond the end of the headline."
14299 (interactive "P")
14300 (if (or (not org-special-ctrl-a/e)
14301 (not (org-on-heading-p)))
14302 (end-of-line arg)
14303 (let ((pos (point)))
14304 (beginning-of-line 1)
14305 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14306 (if (eq org-special-ctrl-a/e t)
14307 (if (or (< pos (match-beginning 1))
14308 (= pos (match-end 0)))
14309 (goto-char (match-beginning 1))
14310 (goto-char (match-end 0)))
14311 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14312 (goto-char (match-end 0))
14313 (goto-char (match-beginning 1))))
14314 (end-of-line arg))))
14315 (org-no-warnings
14316 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14319 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14320 (define-key org-mode-map "\C-e" 'org-end-of-line)
14322 (defun org-kill-line (&optional arg)
14323 "Kill line, to tags or end of line."
14324 (interactive "P")
14325 (cond
14326 ((or (not org-special-ctrl-k)
14327 (bolp)
14328 (not (org-on-heading-p)))
14329 (call-interactively 'kill-line))
14330 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14331 (kill-region (point) (match-beginning 1))
14332 (org-set-tags nil t))
14333 (t (kill-region (point) (point-at-eol)))))
14335 (define-key org-mode-map "\C-k" 'org-kill-line)
14337 (defun org-yank (&optional arg)
14338 "Yank. If the kill is a subtree, treat it specially.
14339 This command will look at the current kill and check if is a single
14340 subtree, or a series of subtrees[1]. If it passes the test, and if the
14341 cursor is at the beginning of a line or after the stars of a currently
14342 empty headline, then the yank is handled specially. How exactly depends
14343 on the value of the following variables, both set by default.
14345 org-yank-folded-subtrees
14346 When set, the subtree(s) will be folded after insertion, but only
14347 if doing so would now swallow text after the yanked text.
14349 org-yank-adjusted-subtrees
14350 When set, the subtree will be promoted or demoted in order to
14351 fit into the local outline tree structure, which means that the level
14352 will be adjusted so that it becomes the smaller one of the two
14353 *visible* surrounding headings.
14355 Any prefix to this command will cause `yank' to be called directly with
14356 no special treatment. In particular, a simple `C-u' prefix will just
14357 plainly yank the text as it is.
14359 \[1] Basically, the test checks if the first non-white line is a heading
14360 and if there are no other headings with fewer stars."
14361 (interactive "P")
14362 (setq this-command 'yank)
14363 (if arg
14364 (call-interactively 'yank)
14365 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14366 (and (org-kill-is-subtree-p)
14367 (or (bolp)
14368 (and (looking-at "[ \t]*$")
14369 (string-match
14370 "\\`\\*+\\'"
14371 (buffer-substring (point-at-bol) (point)))))))
14372 swallowp)
14373 (cond
14374 ((and subtreep org-yank-folded-subtrees)
14375 (let ((beg (point))
14376 end)
14377 (if (and subtreep org-yank-adjusted-subtrees)
14378 (org-paste-subtree nil nil 'for-yank)
14379 (call-interactively 'yank))
14380 (setq end (point))
14381 (goto-char beg)
14382 (when (and (bolp) subtreep
14383 (not (setq swallowp
14384 (org-yank-folding-would-swallow-text beg end))))
14385 (or (looking-at outline-regexp)
14386 (re-search-forward (concat "^" outline-regexp) end t))
14387 (while (and (< (point) end) (looking-at outline-regexp))
14388 (hide-subtree)
14389 (org-cycle-show-empty-lines 'folded)
14390 (condition-case nil
14391 (outline-forward-same-level 1)
14392 (error (goto-char end)))))
14393 (when swallowp
14394 (message
14395 "Yanked text not folded because that would swallow text"))
14396 (goto-char end)
14397 (skip-chars-forward " \t\n\r")
14398 (beginning-of-line 1)
14399 (push-mark beg 'nomsg)))
14400 ((and subtreep org-yank-adjusted-subtrees)
14401 (let ((beg (point-at-bol)))
14402 (org-paste-subtree nil nil 'for-yank)
14403 (push-mark beg 'nomsg)))
14405 (call-interactively 'yank))))))
14407 (defun org-yank-folding-would-swallow-text (beg end)
14408 "Would hide-subtree at BEG swallow any text after END?"
14409 (let (level)
14410 (save-excursion
14411 (goto-char beg)
14412 (when (or (looking-at outline-regexp)
14413 (re-search-forward (concat "^" outline-regexp) end t))
14414 (setq level (org-outline-level)))
14415 (goto-char end)
14416 (skip-chars-forward " \t\r\n\v\f")
14417 (if (or (eobp)
14418 (and (bolp) (looking-at org-outline-regexp)
14419 (<= (org-outline-level) level)))
14420 nil ; Nothing would be swallowed
14421 t)))) ; something would swallow
14423 (define-key org-mode-map "\C-y" 'org-yank)
14425 (defun org-invisible-p ()
14426 "Check if point is at a character currently not visible."
14427 ;; Early versions of noutline don't have `outline-invisible-p'.
14428 (if (fboundp 'outline-invisible-p)
14429 (outline-invisible-p)
14430 (get-char-property (point) 'invisible)))
14432 (defun org-invisible-p2 ()
14433 "Check if point is at a character currently not visible."
14434 (save-excursion
14435 (if (and (eolp) (not (bobp))) (backward-char 1))
14436 ;; Early versions of noutline don't have `outline-invisible-p'.
14437 (if (fboundp 'outline-invisible-p)
14438 (outline-invisible-p)
14439 (get-char-property (point) 'invisible))))
14441 (defun org-back-to-heading (&optional invisible-ok)
14442 "Call `outline-back-to-heading', but provide a better error message."
14443 (condition-case nil
14444 (outline-back-to-heading invisible-ok)
14445 (error (error "Before first headline at position %d in buffer %s"
14446 (point) (current-buffer)))))
14448 (defun org-before-first-heading-p ()
14449 "Before first heading?"
14450 (save-excursion
14451 (null (re-search-backward "^\\*+ " nil t))))
14453 (defalias 'org-on-heading-p 'outline-on-heading-p)
14454 (defalias 'org-at-heading-p 'outline-on-heading-p)
14455 (defun org-at-heading-or-item-p ()
14456 (or (org-on-heading-p) (org-at-item-p)))
14458 (defun org-on-target-p ()
14459 (or (org-in-regexp org-radio-target-regexp)
14460 (org-in-regexp org-target-regexp)))
14462 (defun org-up-heading-all (arg)
14463 "Move to the heading line of which the present line is a subheading.
14464 This function considers both visible and invisible heading lines.
14465 With argument, move up ARG levels."
14466 (if (fboundp 'outline-up-heading-all)
14467 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14468 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14470 (defun org-up-heading-safe ()
14471 "Move to the heading line of which the present line is a subheading.
14472 This version will not throw an error. It will return the level of the
14473 headline found, or nil if no higher level is found."
14474 (let (start-level re)
14475 (org-back-to-heading t)
14476 (setq start-level (funcall outline-level))
14477 (if (equal start-level 1)
14479 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14480 (if (re-search-backward re nil t)
14481 (funcall outline-level)))))
14483 (defun org-first-sibling-p ()
14484 "Is this heading the first child of its parents?"
14485 (interactive)
14486 (let ((re (concat "^" outline-regexp))
14487 level l)
14488 (unless (org-at-heading-p t)
14489 (error "Not at a heading"))
14490 (setq level (funcall outline-level))
14491 (save-excursion
14492 (if (not (re-search-backward re nil t))
14494 (setq l (funcall outline-level))
14495 (< l level)))))
14497 (defun org-goto-sibling (&optional previous)
14498 "Goto the next sibling, even if it is invisible.
14499 When PREVIOUS is set, go to the previous sibling instead. Returns t
14500 when a sibling was found. When none is found, return nil and don't
14501 move point."
14502 (let ((fun (if previous 're-search-backward 're-search-forward))
14503 (pos (point))
14504 (re (concat "^" outline-regexp))
14505 level l)
14506 (when (condition-case nil (org-back-to-heading t) (error nil))
14507 (setq level (funcall outline-level))
14508 (catch 'exit
14509 (or previous (forward-char 1))
14510 (while (funcall fun re nil t)
14511 (setq l (funcall outline-level))
14512 (when (< l level) (goto-char pos) (throw 'exit nil))
14513 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14514 (goto-char pos)
14515 nil))))
14517 (defun org-show-siblings ()
14518 "Show all siblings of the current headline."
14519 (save-excursion
14520 (while (org-goto-sibling) (org-flag-heading nil)))
14521 (save-excursion
14522 (while (org-goto-sibling 'previous)
14523 (org-flag-heading nil))))
14525 (defun org-show-hidden-entry ()
14526 "Show an entry where even the heading is hidden."
14527 (save-excursion
14528 (org-show-entry)))
14530 (defun org-flag-heading (flag &optional entry)
14531 "Flag the current heading. FLAG non-nil means make invisible.
14532 When ENTRY is non-nil, show the entire entry."
14533 (save-excursion
14534 (org-back-to-heading t)
14535 ;; Check if we should show the entire entry
14536 (if entry
14537 (progn
14538 (org-show-entry)
14539 (save-excursion
14540 (and (outline-next-heading)
14541 (org-flag-heading nil))))
14542 (outline-flag-region (max (point-min) (1- (point)))
14543 (save-excursion (outline-end-of-heading) (point))
14544 flag))))
14546 (defun org-forward-same-level (arg)
14547 "Move forward to the ARG'th subheading at same level as this one.
14548 Stop at the first and last subheadings of a superior heading.
14549 This is like outline-forward-same-level, but invisible headings are ok."
14550 (interactive "p")
14551 (org-back-to-heading t)
14552 (while (> arg 0)
14553 (let ((point-to-move-to (save-excursion
14554 (org-get-next-sibling))))
14555 (if point-to-move-to
14556 (progn
14557 (goto-char point-to-move-to)
14558 (setq arg (1- arg)))
14559 (progn
14560 (setq arg 0)
14561 (error "No following same-level heading"))))))
14563 (defun org-get-next-sibling ()
14564 "Move to next heading of the same level, and return point.
14565 If there is no such heading, return nil.
14566 This is like outline-next-sibling, but invisible headings are ok."
14567 (let ((level (funcall outline-level)))
14568 (outline-next-heading)
14569 (while (and (not (eobp)) (> (funcall outline-level) level))
14570 (outline-next-heading))
14571 (if (or (eobp) (< (funcall outline-level) level))
14573 (point))))
14575 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14576 ;; This is an exact copy of the original function, but it uses
14577 ;; `org-back-to-heading', to make it work also in invisible
14578 ;; trees. And is uses an invisible-OK argument.
14579 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14580 (org-back-to-heading invisible-OK)
14581 (let ((first t)
14582 (level (funcall outline-level)))
14583 (while (and (not (eobp))
14584 (or first (> (funcall outline-level) level)))
14585 (setq first nil)
14586 (outline-next-heading))
14587 (unless to-heading
14588 (if (memq (preceding-char) '(?\n ?\^M))
14589 (progn
14590 ;; Go to end of line before heading
14591 (forward-char -1)
14592 (if (memq (preceding-char) '(?\n ?\^M))
14593 ;; leave blank line before heading
14594 (forward-char -1))))))
14595 (point))
14597 (defun org-show-subtree ()
14598 "Show everything after this heading at deeper levels."
14599 (outline-flag-region
14600 (point)
14601 (save-excursion
14602 (outline-end-of-subtree) (outline-next-heading) (point))
14603 nil))
14605 (defun org-show-entry ()
14606 "Show the body directly following this heading.
14607 Show the heading too, if it is currently invisible."
14608 (interactive)
14609 (save-excursion
14610 (condition-case nil
14611 (progn
14612 (org-back-to-heading t)
14613 (outline-flag-region
14614 (max (point-min) (1- (point)))
14615 (save-excursion
14616 (re-search-forward
14617 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14618 (or (match-beginning 1) (point-max)))
14619 nil))
14620 (error nil))))
14622 (defun org-make-options-regexp (kwds)
14623 "Make a regular expression for keyword lines."
14624 (concat
14626 "#?[ \t]*\\+\\("
14627 (mapconcat 'regexp-quote kwds "\\|")
14628 "\\):[ \t]*"
14629 "\\(.+\\)"))
14631 ;; Make isearch reveal the necessary context
14632 (defun org-isearch-end ()
14633 "Reveal context after isearch exits."
14634 (when isearch-success ; only if search was successful
14635 (if (featurep 'xemacs)
14636 ;; Under XEmacs, the hook is run in the correct place,
14637 ;; we directly show the context.
14638 (org-show-context 'isearch)
14639 ;; In Emacs the hook runs *before* restoring the overlays.
14640 ;; So we have to use a one-time post-command-hook to do this.
14641 ;; (Emacs 22 has a special variable, see function `org-mode')
14642 (unless (and (boundp 'isearch-mode-end-hook-quit)
14643 isearch-mode-end-hook-quit)
14644 ;; Only when the isearch was not quitted.
14645 (org-add-hook 'post-command-hook 'org-isearch-post-command
14646 'append 'local)))))
14648 (defun org-isearch-post-command ()
14649 "Remove self from hook, and show context."
14650 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14651 (org-show-context 'isearch))
14654 ;;;; Integration with and fixes for other packages
14656 ;;; Imenu support
14658 (defvar org-imenu-markers nil
14659 "All markers currently used by Imenu.")
14660 (make-variable-buffer-local 'org-imenu-markers)
14662 (defun org-imenu-new-marker (&optional pos)
14663 "Return a new marker for use by Imenu, and remember the marker."
14664 (let ((m (make-marker)))
14665 (move-marker m (or pos (point)))
14666 (push m org-imenu-markers)
14669 (defun org-imenu-get-tree ()
14670 "Produce the index for Imenu."
14671 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14672 (setq org-imenu-markers nil)
14673 (let* ((n org-imenu-depth)
14674 (re (concat "^" outline-regexp))
14675 (subs (make-vector (1+ n) nil))
14676 (last-level 0)
14677 m tree level head)
14678 (save-excursion
14679 (save-restriction
14680 (widen)
14681 (goto-char (point-max))
14682 (while (re-search-backward re nil t)
14683 (setq level (org-reduced-level (funcall outline-level)))
14684 (when (<= level n)
14685 (looking-at org-complex-heading-regexp)
14686 (setq head (org-link-display-format
14687 (org-match-string-no-properties 4))
14688 m (org-imenu-new-marker))
14689 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14690 (if (>= level last-level)
14691 (push (cons head m) (aref subs level))
14692 (push (cons head (aref subs (1+ level))) (aref subs level))
14693 (loop for i from (1+ level) to n do (aset subs i nil)))
14694 (setq last-level level)))))
14695 (aref subs 1)))
14697 (eval-after-load "imenu"
14698 '(progn
14699 (add-hook 'imenu-after-jump-hook
14700 (lambda ()
14701 (if (eq major-mode 'org-mode)
14702 (org-show-context 'org-goto))))))
14704 (defun org-link-display-format (link)
14705 "Replace a link with either the description, or the link target
14706 if no description is present"
14707 (save-match-data
14708 (if (string-match org-bracket-link-analytic-regexp link)
14709 (replace-match (or (match-string 5 link)
14710 (concat (match-string 1 link)
14711 (match-string 3 link)))
14712 nil nil link)
14713 link)))
14715 ;; Speedbar support
14717 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14718 "Overlay marking the agenda restriction line in speedbar.")
14719 (org-overlay-put org-speedbar-restriction-lock-overlay
14720 'face 'org-agenda-restriction-lock)
14721 (org-overlay-put org-speedbar-restriction-lock-overlay
14722 'help-echo "Agendas are currently limited to this item.")
14723 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14725 (defun org-speedbar-set-agenda-restriction ()
14726 "Restrict future agenda commands to the location at point in speedbar.
14727 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14728 (interactive)
14729 (require 'org-agenda)
14730 (let (p m tp np dir txt w)
14731 (cond
14732 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14733 'org-imenu t))
14734 (setq m (get-text-property p 'org-imenu-marker))
14735 (save-excursion
14736 (save-restriction
14737 (set-buffer (marker-buffer m))
14738 (goto-char m)
14739 (org-agenda-set-restriction-lock 'subtree))))
14740 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14741 'speedbar-function 'speedbar-find-file))
14742 (setq tp (previous-single-property-change
14743 (1+ p) 'speedbar-function)
14744 np (next-single-property-change
14745 tp 'speedbar-function)
14746 dir (speedbar-line-directory)
14747 txt (buffer-substring-no-properties (or tp (point-min))
14748 (or np (point-max))))
14749 (save-excursion
14750 (save-restriction
14751 (set-buffer (find-file-noselect
14752 (let ((default-directory dir))
14753 (expand-file-name txt))))
14754 (unless (org-mode-p)
14755 (error "Cannot restrict to non-Org-mode file"))
14756 (org-agenda-set-restriction-lock 'file))))
14757 (t (error "Don't know how to restrict Org-mode's agenda")))
14758 (org-move-overlay org-speedbar-restriction-lock-overlay
14759 (point-at-bol) (point-at-eol))
14760 (setq current-prefix-arg nil)
14761 (org-agenda-maybe-redo)))
14763 (eval-after-load "speedbar"
14764 '(progn
14765 (speedbar-add-supported-extension ".org")
14766 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14767 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14768 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14769 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14770 (add-hook 'speedbar-visiting-tag-hook
14771 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14774 ;;; Fixes and Hacks for problems with other packages
14776 ;; Make flyspell not check words in links, to not mess up our keymap
14777 (defun org-mode-flyspell-verify ()
14778 "Don't let flyspell put overlays at active buttons."
14779 (not (get-text-property (point) 'keymap)))
14781 ;; Make `bookmark-jump' show the jump location if it was hidden.
14782 (eval-after-load "bookmark"
14783 '(if (boundp 'bookmark-after-jump-hook)
14784 ;; We can use the hook
14785 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14786 ;; Hook not available, use advice
14787 (defadvice bookmark-jump (after org-make-visible activate)
14788 "Make the position visible."
14789 (org-bookmark-jump-unhide))))
14791 ;; Make sure saveplace show the location if it was hidden
14792 (eval-after-load "saveplace"
14793 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14794 "Make the position visible."
14795 (org-bookmark-jump-unhide)))
14797 (defun org-bookmark-jump-unhide ()
14798 "Unhide the current position, to show the bookmark location."
14799 (and (org-mode-p)
14800 (or (org-invisible-p)
14801 (save-excursion (goto-char (max (point-min) (1- (point))))
14802 (org-invisible-p)))
14803 (org-show-context 'bookmark-jump)))
14805 ;; Make session.el ignore our circular variable
14806 (eval-after-load "session"
14807 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14809 ;;;; Experimental code
14811 (defun org-closed-in-range ()
14812 "Sparse tree of items closed in a certain time range.
14813 Still experimental, may disappear in the future."
14814 (interactive)
14815 ;; Get the time interval from the user.
14816 (let* ((time1 (time-to-seconds
14817 (org-read-date nil 'to-time nil "Starting date: ")))
14818 (time2 (time-to-seconds
14819 (org-read-date nil 'to-time nil "End date:")))
14820 ;; callback function
14821 (callback (lambda ()
14822 (let ((time
14823 (time-to-seconds
14824 (apply 'encode-time
14825 (org-parse-time-string
14826 (match-string 1))))))
14827 ;; check if time in interval
14828 (and (>= time time1) (<= time time2))))))
14829 ;; make tree, check each match with the callback
14830 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14833 ;;;; Finish up
14835 (provide 'org)
14837 (run-hooks 'org-load-hook)
14839 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14841 ;;; org.el ends here