Document a function.
[org-mode.git] / lisp / org.el
blobdfabe4e0a363255494da74da9bb863c014b62e72
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.13trans
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.13trans"
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 id's 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 Remeber directly from Browser" org-annotation-helper)
180 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
181 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
182 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
183 (const :tag "C eval: Include command output as text" org-eval)
184 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
185 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
186 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
187 (const :tag "C id: Global id's for identifying entries" org-id)
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 standart 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][descritpion]]. 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 brackes 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 %-excapes 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. Unually \"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 mached 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-context-in-file-links t
960 "Non-nil means, file links from `org-store-link' contain context.
961 A search string will be added to the file name with :: as separator and
962 used to find the context when the link is activated by the command
963 `org-open-at-point'.
964 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
965 negates this setting for the duration of the command."
966 :group 'org-link-store
967 :type 'boolean)
969 (defcustom org-keep-stored-link-after-insertion nil
970 "Non-nil means, keep link in list for entire session.
972 The command `org-store-link' adds a link pointing to the current
973 location to an internal list. These links accumulate during a session.
974 The command `org-insert-link' can be used to insert links into any
975 Org-mode file (offering completion for all stored links). When this
976 option is nil, every link which has been inserted once using \\[org-insert-link]
977 will be removed from the list, to make completing the unused links
978 more efficient."
979 :group 'org-link-store
980 :type 'boolean)
982 (defgroup org-link-follow nil
983 "Options concerning following links in Org-mode."
984 :tag "Org Follow Link"
985 :group 'org-link)
987 (defcustom org-link-translation-function nil
988 "Function to translate links with different syntax to Org syntax.
989 This can be used to translate links created for example by the Planner
990 or emacs-wiki packages to Org syntax.
991 The function must accept two parameters, a TYPE containing the link
992 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
993 which is everything after the link protocol. It should return a cons
994 with possibly modifed values of type and path.
995 Org contains a function for this, so if you set this variable to
996 `org-translate-link-from-planner', you should be able follow many
997 links created by planner."
998 :group 'org-link-follow
999 :type 'function)
1001 (defcustom org-follow-link-hook nil
1002 "Hook that is run after a link has been followed."
1003 :group 'org-link-follow
1004 :type 'hook)
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-mouse-1-follows-link
1019 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1020 "Non-nil means, mouse-1 on a link will follow the link.
1021 A longer mouse click will still set point. Does not work on XEmacs.
1022 Needs to be set before org.el is loaded."
1023 :group 'org-link-follow
1024 :type 'boolean)
1026 (defcustom org-mark-ring-length 4
1027 "Number of different positions to be recorded in the ring
1028 Changing this requires a restart of Emacs to work correctly."
1029 :group 'org-link-follow
1030 :type 'interger)
1032 (defcustom org-link-frame-setup
1033 '((vm . vm-visit-folder-other-frame)
1034 (gnus . gnus-other-frame)
1035 (file . find-file-other-window))
1036 "Setup the frame configuration for following links.
1037 When following a link with Emacs, it may often be useful to display
1038 this link in another window or frame. This variable can be used to
1039 set this up for the different types of links.
1040 For VM, use any of
1041 `vm-visit-folder'
1042 `vm-visit-folder-other-frame'
1043 For Gnus, use any of
1044 `gnus'
1045 `gnus-other-frame'
1046 `org-gnus-no-new-news'
1047 For FILE, use any of
1048 `find-file'
1049 `find-file-other-window'
1050 `find-file-other-frame'
1051 For the calendar, use the variable `calendar-setup'.
1052 For BBDB, it is currently only possible to display the matches in
1053 another window."
1054 :group 'org-link-follow
1055 :type '(list
1056 (cons (const vm)
1057 (choice
1058 (const vm-visit-folder)
1059 (const vm-visit-folder-other-window)
1060 (const vm-visit-folder-other-frame)))
1061 (cons (const gnus)
1062 (choice
1063 (const gnus)
1064 (const gnus-other-frame)
1065 (const org-gnus-no-new-news)))
1066 (cons (const file)
1067 (choice
1068 (const find-file)
1069 (const find-file-other-window)
1070 (const find-file-other-frame)))))
1072 (defcustom org-display-internal-link-with-indirect-buffer nil
1073 "Non-nil means, use indirect buffer to display infile links.
1074 Activating internal links (from one location in a file to another location
1075 in the same file) normally just jumps to the location. When the link is
1076 activated with a C-u prefix (or with mouse-3), the link is displayed in
1077 another window. When this option is set, the other window actually displays
1078 an indirect buffer clone of the current buffer, to avoid any visibility
1079 changes to the current buffer."
1080 :group 'org-link-follow
1081 :type 'boolean)
1083 (defcustom org-open-non-existing-files nil
1084 "Non-nil means, `org-open-file' will open non-existing files.
1085 When nil, an error will be generated."
1086 :group 'org-link-follow
1087 :type 'boolean)
1089 (defcustom org-open-directory-means-index-dot-org nil
1090 "Non-nil means, a link to a directory really means to index.org.
1091 When nil, following a directory link will run dired or open a finder/explorer
1092 window on that directory."
1093 :group 'org-link-follow
1094 :type 'boolean)
1096 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1097 "Function and arguments to call for following mailto links.
1098 This is a list with the first element being a lisp function, and the
1099 remaining elements being arguments to the function. In string arguments,
1100 %a will be replaced by the address, and %s will be replaced by the subject
1101 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1102 :group 'org-link-follow
1103 :type '(choice
1104 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1105 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1106 (const :tag "message-mail" (message-mail "%a" "%s"))
1107 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1109 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1110 "Non-nil means, ask for confirmation before executing shell links.
1111 Shell links can be dangerous: just think about a link
1113 [[shell:rm -rf ~/*][Google Search]]
1115 This link would show up in your Org-mode document as \"Google Search\",
1116 but really it would remove your entire home directory.
1117 Therefore we advise against setting this variable to nil.
1118 Just change it to `y-or-n-p' of you want to confirm with a
1119 single keystroke rather than having to type \"yes\"."
1120 :group 'org-link-follow
1121 :type '(choice
1122 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1123 (const :tag "with y-or-n (faster)" y-or-n-p)
1124 (const :tag "no confirmation (dangerous)" nil)))
1126 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1127 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1128 Elisp links can be dangerous: just think about a link
1130 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1132 This link would show up in your Org-mode document as \"Google Search\",
1133 but really it would remove your entire home directory.
1134 Therefore we advise against setting this variable to nil.
1135 Just change it to `y-or-n-p' of you want to confirm with a
1136 single keystroke rather than having to type \"yes\"."
1137 :group 'org-link-follow
1138 :type '(choice
1139 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1140 (const :tag "with y-or-n (faster)" y-or-n-p)
1141 (const :tag "no confirmation (dangerous)" nil)))
1143 (defconst org-file-apps-defaults-gnu
1144 '((remote . emacs)
1145 (system . mailcap)
1146 (t . mailcap))
1147 "Default file applications on a UNIX or GNU/Linux system.
1148 See `org-file-apps'.")
1150 (defconst org-file-apps-defaults-macosx
1151 '((remote . emacs)
1152 (t . "open %s")
1153 (system . "open %s")
1154 ("ps.gz" . "gv %s")
1155 ("eps.gz" . "gv %s")
1156 ("dvi" . "xdvi %s")
1157 ("fig" . "xfig %s"))
1158 "Default file applications on a MacOS X system.
1159 The system \"open\" is known as a default, but we use X11 applications
1160 for some files for which the OS does not have a good default.
1161 See `org-file-apps'.")
1163 (defconst org-file-apps-defaults-windowsnt
1164 (list
1165 '(remote . emacs)
1166 (cons t
1167 (list (if (featurep 'xemacs)
1168 'mswindows-shell-execute
1169 'w32-shell-execute)
1170 "open" 'file))
1171 (cons 'system
1172 (list (if (featurep 'xemacs)
1173 'mswindows-shell-execute
1174 'w32-shell-execute)
1175 "open" 'file)))
1176 "Default file applications on a Windows NT system.
1177 The system \"open\" is used for most files.
1178 See `org-file-apps'.")
1180 (defcustom org-file-apps
1182 (auto-mode . emacs)
1183 ("\\.x?html?\\'" . default)
1184 ("\\.pdf\\'" . default)
1186 "External applications for opening `file:path' items in a document.
1187 Org-mode uses system defaults for different file types, but
1188 you can use this variable to set the application for a given file
1189 extension. The entries in this list are cons cells where the car identifies
1190 files and the cdr the corresponding command. Possible values for the
1191 file identifier are
1192 \"regex\" Regular expression matched against the file name. For backward
1193 compatibility, this can also be a string with only alphanumeric
1194 characters, which is then interpreted as an extension.
1195 `directory' Matches a directory
1196 `remote' Matches a remote file, accessible through tramp or efs.
1197 Remote files most likely should be visited through Emacs
1198 because external applications cannot handle such paths.
1199 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1200 so all files Emacs knows how to handle. Using this with
1201 command `emacs' will open most files in Emacs. Beware that this
1202 will also open html files insite Emacs, unless you add
1203 (\"html\" . default) to the list as well.
1204 t Default for files not matched by any of the other options.
1205 `system' The system command to open files, like `open' on Windows
1206 and Mac OS X, and mailcap under GNU/Linux. This is the command
1207 that will be selected if you call `C-c C-o' with a double
1208 `C-u C-u' prefix.
1210 Possible values for the command are:
1211 `emacs' The file will be visited by the current Emacs process.
1212 `default' Use the default application for this file type, which is the
1213 association for t in the list, most likely in the system-specific
1214 part.
1215 This can be used to overrule an unwanted seting in the
1216 system-specific variable.
1217 `system' Use the system command for opening files, like \"open\".
1218 This command is specified by the entry whose car is `system'.
1219 Most likely, the system-specific version of this variable
1220 does define this command, but you can overrule/replace it
1221 here.
1222 string A command to be executed by a shell; %s will be replaced
1223 by the path to the file.
1224 sexp A Lisp form which will be evaluated. The file path will
1225 be available in the Lisp variable `file'.
1226 For more examples, see the system specific constants
1227 `org-file-apps-defaults-macosx'
1228 `org-file-apps-defaults-windowsnt'
1229 `org-file-apps-defaults-gnu'."
1230 :group 'org-link-follow
1231 :type '(repeat
1232 (cons (choice :value ""
1233 (string :tag "Extension")
1234 (const :tag "System command to open files" system)
1235 (const :tag "Default for unrecognized files" t)
1236 (const :tag "Remote file" remote)
1237 (const :tag "Links to a directory" directory)
1238 (const :tag "Any files that have Emacs modes"
1239 auto-mode))
1240 (choice :value ""
1241 (const :tag "Visit with Emacs" emacs)
1242 (const :tag "Use default" default)
1243 (const :tag "Use the system command" system)
1244 (string :tag "Command")
1245 (sexp :tag "Lisp form")))))
1247 (defgroup org-refile nil
1248 "Options concerning refiling entries in Org-mode."
1249 :tag "Org Refile"
1250 :group 'org)
1252 (defcustom org-directory "~/org"
1253 "Directory with org files.
1254 This directory will be used as default to prompt for org files.
1255 Used by the hooks for remember.el."
1256 :group 'org-refile
1257 :group 'org-remember
1258 :type 'directory)
1260 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1261 "Default target for storing notes.
1262 Used by the hooks for remember.el. This can be a string, or nil to mean
1263 the value of `remember-data-file'.
1264 You can set this on a per-template basis with the variable
1265 `org-remember-templates'."
1266 :group 'org-refile
1267 :group 'org-remember
1268 :type '(choice
1269 (const :tag "Default from remember-data-file" nil)
1270 file))
1272 (defcustom org-goto-interface 'outline
1273 "The default interface to be used for `org-goto'.
1274 Allowed vaues are:
1275 outline The interface shows an outline of the relevant file
1276 and the correct heading is found by moving through
1277 the outline or by searching with incremental search.
1278 outline-path-completion Headlines in the current buffer are offered via
1279 completion. This is the interface also used by
1280 the refile command."
1281 :group 'org-refile
1282 :type '(choice
1283 (const :tag "Outline" outline)
1284 (const :tag "Outline-path-completion" outline-path-completion)))
1286 (defcustom org-reverse-note-order nil
1287 "Non-nil means, store new notes at the beginning of a file or entry.
1288 When nil, new notes will be filed to the end of a file or entry.
1289 This can also be a list with cons cells of regular expressions that
1290 are matched against file names, and values."
1291 :group 'org-remember
1292 :group 'org-refile
1293 :type '(choice
1294 (const :tag "Reverse always" t)
1295 (const :tag "Reverse never" nil)
1296 (repeat :tag "By file name regexp"
1297 (cons regexp boolean))))
1299 (defcustom org-refile-targets nil
1300 "Targets for refiling entries with \\[org-refile].
1301 This is list of cons cells. Each cell contains:
1302 - a specification of the files to be considered, either a list of files,
1303 or a symbol whose function or variable value will be used to retrieve
1304 a file name or a list of file names. Nil means, refile to a different
1305 heading in the current buffer.
1306 - A specification of how to find candidate refile targets. This may be
1307 any of
1308 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1309 This tag has to be present in all target headlines, inheritance will
1310 not be considered.
1311 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1312 todo keyword.
1313 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1314 headlines that are refiling targets.
1315 - a cons cell (:level . N). Any headline of level N is considered a target.
1316 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1318 When this variable is nil, all top-level headlines in the current buffer
1319 are used, equivalent to the value `((nil . (:level . 1))'."
1320 :group 'org-refile
1321 :type '(repeat
1322 (cons
1323 (choice :value org-agenda-files
1324 (const :tag "All agenda files" org-agenda-files)
1325 (const :tag "Current buffer" nil)
1326 (function) (variable) (file))
1327 (choice :tag "Identify target headline by"
1328 (cons :tag "Specific tag" (const :value :tag) (string))
1329 (cons :tag "TODO keyword" (const :value :todo) (string))
1330 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1331 (cons :tag "Level number" (const :value :level) (integer))
1332 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1334 (defcustom org-refile-use-outline-path nil
1335 "Non-nil means, provide refile targets as paths.
1336 So a level 3 headline will be available as level1/level2/level3.
1337 When the value is `file', also include the file name (without directory)
1338 into the path. When `full-file-path', include the full file path."
1339 :group 'org-refile
1340 :type '(choice
1341 (const :tag "Not" nil)
1342 (const :tag "Yes" t)
1343 (const :tag "Start with file name" file)
1344 (const :tag "Start with full file path" full-file-path)))
1346 (defcustom org-outline-path-complete-in-steps t
1347 "Non-nil means, complete the outline path in hierarchical steps.
1348 When Org-mode uses the refile interface to select an outline path
1349 \(see variable `org-refile-use-outline-path'), the completion of
1350 the path can be done is a single go, or if can be done in steps down
1351 the headline hierarchy. Going in steps is probably the best if you
1352 do not use a special completion package like `ido' or `icicles'.
1353 However, when using these packages, going in one step can be very
1354 fast, while still showing the whole path to the entry."
1355 :group 'org-refile
1356 :type 'boolean)
1358 (defgroup org-todo nil
1359 "Options concerning TODO items in Org-mode."
1360 :tag "Org TODO"
1361 :group 'org)
1363 (defgroup org-progress nil
1364 "Options concerning Progress logging in Org-mode."
1365 :tag "Org Progress"
1366 :group 'org-time)
1368 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1369 "List of TODO entry keyword sequences and their interpretation.
1370 \\<org-mode-map>This is a list of sequences.
1372 Each sequence starts with a symbol, either `sequence' or `type',
1373 indicating if the keywords should be interpreted as a sequence of
1374 action steps, or as different types of TODO items. The first
1375 keywords are states requiring action - these states will select a headline
1376 for inclusion into the global TODO list Org-mode produces. If one of
1377 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1378 signify that no further action is necessary. If \"|\" is not found,
1379 the last keyword is treated as the only DONE state of the sequence.
1381 The command \\[org-todo] cycles an entry through these states, and one
1382 additional state where no keyword is present. For details about this
1383 cycling, see the manual.
1385 TODO keywords and interpretation can also be set on a per-file basis with
1386 the special #+SEQ_TODO and #+TYP_TODO lines.
1388 Each keyword can optionally specify a character for fast state selection
1389 \(in combination with the variable `org-use-fast-todo-selection')
1390 and specifiers for state change logging, using the same syntax
1391 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1392 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1393 indicates to record a time stamp each time this state is selected.
1395 Each keyword may also specify if a timestamp or a note should be
1396 recorded when entering or leaving the state, by adding additional
1397 characters in the parenthesis after the keyword. This looks like this:
1398 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1399 record only the time of the state change. With X and Y being either
1400 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1401 Y when leaving the state if and only if the *target* state does not
1402 define X. You may omit any of the fast-selection key or X or /Y,
1403 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1405 For backward compatibility, this variable may also be just a list
1406 of keywords - in this case the interptetation (sequence or type) will be
1407 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1408 :group 'org-todo
1409 :group 'org-keywords
1410 :type '(choice
1411 (repeat :tag "Old syntax, just keywords"
1412 (string :tag "Keyword"))
1413 (repeat :tag "New syntax"
1414 (cons
1415 (choice
1416 :tag "Interpretation"
1417 (const :tag "Sequence (cycling hits every state)" sequence)
1418 (const :tag "Type (cycling directly to DONE)" type))
1419 (repeat
1420 (string :tag "Keyword"))))))
1422 (defvar org-todo-keywords-1 nil
1423 "All TODO and DONE keywords active in a buffer.")
1424 (make-variable-buffer-local 'org-todo-keywords-1)
1425 (defvar org-todo-keywords-for-agenda nil)
1426 (defvar org-done-keywords-for-agenda nil)
1427 (defvar org-todo-keyword-alist-for-agenda nil)
1428 (defvar org-tag-alist-for-agenda nil)
1429 (defvar org-agenda-contributing-files nil)
1430 (defvar org-not-done-keywords nil)
1431 (make-variable-buffer-local 'org-not-done-keywords)
1432 (defvar org-done-keywords nil)
1433 (make-variable-buffer-local 'org-done-keywords)
1434 (defvar org-todo-heads nil)
1435 (make-variable-buffer-local 'org-todo-heads)
1436 (defvar org-todo-sets nil)
1437 (make-variable-buffer-local 'org-todo-sets)
1438 (defvar org-todo-log-states nil)
1439 (make-variable-buffer-local 'org-todo-log-states)
1440 (defvar org-todo-kwd-alist nil)
1441 (make-variable-buffer-local 'org-todo-kwd-alist)
1442 (defvar org-todo-key-alist nil)
1443 (make-variable-buffer-local 'org-todo-key-alist)
1444 (defvar org-todo-key-trigger nil)
1445 (make-variable-buffer-local 'org-todo-key-trigger)
1447 (defcustom org-todo-interpretation 'sequence
1448 "Controls how TODO keywords are interpreted.
1449 This variable is in principle obsolete and is only used for
1450 backward compatibility, if the interpretation of todo keywords is
1451 not given already in `org-todo-keywords'. See that variable for
1452 more information."
1453 :group 'org-todo
1454 :group 'org-keywords
1455 :type '(choice (const sequence)
1456 (const type)))
1458 (defcustom org-use-fast-todo-selection 'prefix
1459 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1460 This variable describes if and under what circumstances the cycling
1461 mechanism for TODO keywords will be replaced by a single-key, direct
1462 selection scheme.
1464 When nil, fast selection is never used.
1466 When the symbol `prefix', it will be used when `org-todo' is called with
1467 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1468 in an agenda buffer.
1470 When t, fast selection is used by default. In this case, the prefix
1471 argument forces cycling instead.
1473 In all cases, the special interface is only used if access keys have actually
1474 been assigned by the user, i.e. if keywords in the configuration are followed
1475 by a letter in parenthesis, like TODO(t)."
1476 :group 'org-todo
1477 :type '(choice
1478 (const :tag "Never" nil)
1479 (const :tag "By default" t)
1480 (const :tag "Only with C-u C-c C-t" prefix)))
1482 (defcustom org-provide-todo-statistics t
1483 "Non-nil means, update todo statistics after insert and toggle.
1484 When this is set, todo statistics is updated in the parent of the current
1485 entry each time a todo state is changed."
1486 :group 'org-todo
1487 :type 'boolean)
1489 (defcustom org-after-todo-state-change-hook nil
1490 "Hook which is run after the state of a TODO item was changed.
1491 The new state (a string with a TODO keyword, or nil) is available in the
1492 Lisp variable `state'."
1493 :group 'org-todo
1494 :type 'hook)
1496 (defcustom org-todo-state-tags-triggers nil
1497 "Tag changes that should be triggered by TODO state changes.
1498 This is a list. Each entry is
1500 (state-change (tag . flag) .......)
1502 State-change can be a string with a state, and empty string to indicate the
1503 state that has no TODO keyword, or it can be one of the symbols `todo'
1504 or `done', meaning any not-done or done state, respectively."
1505 :group 'org-todo
1506 :group 'org-tags
1507 :type '(repeat
1508 (cons (choice :tag "When changing to"
1509 (const :tag "Not-done state" todo)
1510 (const :tag "Done state" done)
1511 (string :tag "State"))
1512 (repeat
1513 (cons :tag "Tag action"
1514 (string :tag "Tag")
1515 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1517 (defcustom org-log-done nil
1518 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1519 When equal to the list (done), also prompt for a closing note.
1520 This can also be configured on a per-file basis by adding one of
1521 the following lines anywhere in the buffer:
1523 #+STARTUP: logdone
1524 #+STARTUP: lognotedone
1525 #+STARTUP: nologdone"
1526 :group 'org-todo
1527 :group 'org-progress
1528 :type '(choice
1529 (const :tag "No logging" nil)
1530 (const :tag "Record CLOSED timestamp" time)
1531 (const :tag "Record CLOSED timestamp with closing note." note)))
1533 ;; Normalize old uses of org-log-done.
1534 (cond
1535 ((eq org-log-done t) (setq org-log-done 'time))
1536 ((and (listp org-log-done) (memq 'done org-log-done))
1537 (setq org-log-done 'note)))
1539 (defcustom org-log-note-clock-out nil
1540 "Non-nil means, record a note when clocking out of an item.
1541 This can also be configured on a per-file basis by adding one of
1542 the following lines anywhere in the buffer:
1544 #+STARTUP: lognoteclock-out
1545 #+STARTUP: nolognoteclock-out"
1546 :group 'org-todo
1547 :group 'org-progress
1548 :type 'boolean)
1550 (defcustom org-log-done-with-time t
1551 "Non-nil means, the CLOSED time stamp will contain date and time.
1552 When nil, only the date will be recorded."
1553 :group 'org-progress
1554 :type 'boolean)
1556 (defcustom org-log-note-headings
1557 '((done . "CLOSING NOTE %t")
1558 (state . "State %-12s %t")
1559 (note . "Note taken on %t")
1560 (clock-out . ""))
1561 "Headings for notes added to entries.
1562 The value is an alist, with the car being a symbol indicating the note
1563 context, and the cdr is the heading to be used. The heading may also be the
1564 empty string.
1565 %t in the heading will be replaced by a time stamp.
1566 %s will be replaced by the new TODO state, in double quotes.
1567 %u will be replaced by the user name.
1568 %U will be replaced by the full user name."
1569 :group 'org-todo
1570 :group 'org-progress
1571 :type '(list :greedy t
1572 (cons (const :tag "Heading when closing an item" done) string)
1573 (cons (const :tag
1574 "Heading when changing todo state (todo sequence only)"
1575 state) string)
1576 (cons (const :tag "Heading when just taking a note" note) string)
1577 (cons (const :tag "Heading when clocking out" clock-out) string)))
1579 (unless (assq 'note org-log-note-headings)
1580 (push '(note . "%t") org-log-note-headings))
1582 (defcustom org-log-state-notes-insert-after-drawers nil
1583 "Non-nil means, insert state change notes after any drawers in entry.
1584 Only the drawers that *immediately* follow the headline and the
1585 deadline/scheduled line are skipped.
1586 When nil, insert notes right after the heading and perhaps the line
1587 with deadline/scheduling if present."
1588 :group 'org-todo
1589 :group 'org-progress
1590 :type 'boolean)
1592 (defcustom org-log-states-order-reversed t
1593 "Non-nil means, the latest state change note will be directly after heading.
1594 When nil, the notes will be orderer according to time."
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type 'boolean)
1599 (defcustom org-log-repeat 'time
1600 "Non-nil means, record moving through the DONE state when triggering repeat.
1601 An auto-repeating tasks is immediately switched back to TODO when marked
1602 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1603 the TODO keyword definition, or recording a closing note by setting
1604 `org-log-done', there will be no record of the task moving through DONE.
1605 This variable forces taking a note anyway. Possible values are:
1607 nil Don't force a record
1608 time Record a time stamp
1609 note Record a note
1611 This option can also be set with on a per-file-basis with
1613 #+STARTUP: logrepeat
1614 #+STARTUP: lognoterepeat
1615 #+STARTUP: nologrepeat
1617 You can have local logging settings for a subtree by setting the LOGGING
1618 property to one or more of these keywords."
1619 :group 'org-todo
1620 :group 'org-progress
1621 :type '(choice
1622 (const :tag "Don't force a record" nil)
1623 (const :tag "Force recording the DONE state" time)
1624 (const :tag "Force recording a note with the DONE state" note)))
1627 (defgroup org-priorities nil
1628 "Priorities in Org-mode."
1629 :tag "Org Priorities"
1630 :group 'org-todo)
1632 (defcustom org-highest-priority ?A
1633 "The highest priority of TODO items. A character like ?A, ?B etc.
1634 Must have a smaller ASCII number than `org-lowest-priority'."
1635 :group 'org-priorities
1636 :type 'character)
1638 (defcustom org-lowest-priority ?C
1639 "The lowest priority of TODO items. A character like ?A, ?B etc.
1640 Must have a larger ASCII number than `org-highest-priority'."
1641 :group 'org-priorities
1642 :type 'character)
1644 (defcustom org-default-priority ?B
1645 "The default priority of TODO items.
1646 This is the priority an item get if no explicit priority is given."
1647 :group 'org-priorities
1648 :type 'character)
1650 (defcustom org-priority-start-cycle-with-default t
1651 "Non-nil means, start with default priority when starting to cycle.
1652 When this is nil, the first step in the cycle will be (depending on the
1653 command used) one higher or lower that the default priority."
1654 :group 'org-priorities
1655 :type 'boolean)
1657 (defgroup org-time nil
1658 "Options concerning time stamps and deadlines in Org-mode."
1659 :tag "Org Time"
1660 :group 'org)
1662 (defcustom org-insert-labeled-timestamps-at-point nil
1663 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1664 When nil, these labeled time stamps are forces into the second line of an
1665 entry, just after the headline. When scheduling from the global TODO list,
1666 the time stamp will always be forced into the second line."
1667 :group 'org-time
1668 :type 'boolean)
1670 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1671 "Formats for `format-time-string' which are used for time stamps.
1672 It is not recommended to change this constant.")
1674 (defcustom org-time-stamp-rounding-minutes '(0 5)
1675 "Number of minutes to round time stamps to.
1676 These are two values, the first applies when first creating a time stamp.
1677 The second applies when changing it with the commands `S-up' and `S-down'.
1678 When changing the time stamp, this means that it will change in steps
1679 of N minutes, as given by the second value.
1681 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1682 numbers should be factors of 60, so for example 5, 10, 15.
1684 When this is larger than 1, you can still force an exact time-stamp by using
1685 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1686 and by using a prefix arg to `S-up/down' to specify the exact number
1687 of minutes to shift."
1688 :group 'org-time
1689 :get '(lambda (var) ; Make sure all entries have 5 elements
1690 (if (integerp (default-value var))
1691 (list (default-value var) 5)
1692 (default-value var)))
1693 :type '(list
1694 (integer :tag "when inserting times")
1695 (integer :tag "when modifying times")))
1697 ;; Normalize old customizations of this variable.
1698 (when (integerp org-time-stamp-rounding-minutes)
1699 (setq org-time-stamp-rounding-minutes
1700 (list org-time-stamp-rounding-minutes
1701 org-time-stamp-rounding-minutes)))
1703 (defcustom org-display-custom-times nil
1704 "Non-nil means, overlay custom formats over all time stamps.
1705 The formats are defined through the variable `org-time-stamp-custom-formats'.
1706 To turn this on on a per-file basis, insert anywhere in the file:
1707 #+STARTUP: customtime"
1708 :group 'org-time
1709 :set 'set-default
1710 :type 'sexp)
1711 (make-variable-buffer-local 'org-display-custom-times)
1713 (defcustom org-time-stamp-custom-formats
1714 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1715 "Custom formats for time stamps. See `format-time-string' for the syntax.
1716 These are overlayed over the default ISO format if the variable
1717 `org-display-custom-times' is set. Time like %H:%M should be at the
1718 end of the second format."
1719 :group 'org-time
1720 :type 'sexp)
1722 (defun org-time-stamp-format (&optional long inactive)
1723 "Get the right format for a time string."
1724 (let ((f (if long (cdr org-time-stamp-formats)
1725 (car org-time-stamp-formats))))
1726 (if inactive
1727 (concat "[" (substring f 1 -1) "]")
1728 f)))
1730 (defcustom org-time-clocksum-format "%d:%02d"
1731 "The format string used when creating CLOCKSUM lines, or when
1732 org-mode generates a time duration."
1733 :group 'org-time
1734 :type 'string)
1736 (defcustom org-deadline-warning-days 14
1737 "No. of days before expiration during which a deadline becomes active.
1738 This variable governs the display in sparse trees and in the agenda.
1739 When 0 or negative, it means use this number (the absolute value of it)
1740 even if a deadline has a different individual lead time specified."
1741 :group 'org-time
1742 :group 'org-agenda-daily/weekly
1743 :type 'number)
1745 (defcustom org-read-date-prefer-future t
1746 "Non-nil means, assume future for incomplete date input from user.
1747 This affects the following situations:
1748 1. The user gives a day, but no month.
1749 For example, if today is the 15th, and you enter \"3\", Org-mode will
1750 read this as the third of *next* month. However, if you enter \"17\",
1751 it will be considered as *this* month.
1752 2. The user gives a month but not a year.
1753 For example, if it is april and you enter \"feb 2\", this will be read
1754 as feb 2, *next* year. \"May 5\", however, will be this year.
1756 Currently this does not work for ISO week specifications.
1758 When this option is nil, the current month and year will always be used
1759 as defaults."
1760 :group 'org-time
1761 :type 'boolean)
1763 (defcustom org-read-date-display-live t
1764 "Non-nil means, display current interpretation of date prompt live.
1765 This display will be in an overlay, in the minibuffer."
1766 :group 'org-time
1767 :type 'boolean)
1769 (defcustom org-read-date-popup-calendar t
1770 "Non-nil means, pop up a calendar when prompting for a date.
1771 In the calendar, the date can be selected with mouse-1. However, the
1772 minibuffer will also be active, and you can simply enter the date as well.
1773 When nil, only the minibuffer will be available."
1774 :group 'org-time
1775 :type 'boolean)
1776 (if (fboundp 'defvaralias)
1777 (defvaralias 'org-popup-calendar-for-date-prompt
1778 'org-read-date-popup-calendar))
1780 (defcustom org-extend-today-until 0
1781 "The hour when your day really ends. Must be an integer.
1782 This has influence for the following applications:
1783 - When switching the agenda to \"today\". It it is still earlier than
1784 the time given here, the day recognized as TODAY is actually yesterday.
1785 - When a date is read from the user and it is still before the time given
1786 here, the current date and time will be assumed to be yesterday, 23:59.
1787 Also, timestamps inserted in remember templates follow this rule.
1789 IMPORTANT: This is a feature whose implementation is and likely will
1790 remain incomplete. Really, it is only here because past midnight seems to
1791 be the favorite working time of John Wiegley :-)"
1792 :group 'org-time
1793 :type 'number)
1795 (defcustom org-edit-timestamp-down-means-later nil
1796 "Non-nil means, S-down will increase the time in a time stamp.
1797 When nil, S-up will increase."
1798 :group 'org-time
1799 :type 'boolean)
1801 (defcustom org-calendar-follow-timestamp-change t
1802 "Non-nil means, make the calendar window follow timestamp changes.
1803 When a timestamp is modified and the calendar window is visible, it will be
1804 moved to the new date."
1805 :group 'org-time
1806 :type 'boolean)
1808 (defgroup org-tags nil
1809 "Options concerning tags in Org-mode."
1810 :tag "Org Tags"
1811 :group 'org)
1813 (defcustom org-tag-alist nil
1814 "List of tags allowed in Org-mode files.
1815 When this list is nil, Org-mode will base TAG input on what is already in the
1816 buffer.
1817 The value of this variable is an alist, the car of each entry must be a
1818 keyword as a string, the cdr may be a character that is used to select
1819 that tag through the fast-tag-selection interface.
1820 See the manual for details."
1821 :group 'org-tags
1822 :type '(repeat
1823 (choice
1824 (cons (string :tag "Tag name")
1825 (character :tag "Access char"))
1826 (const :tag "Start radio group" (:startgroup))
1827 (const :tag "End radio group" (:endgroup)))))
1829 (defvar org-file-tags nil
1830 "List of tags that can be inherited by all entries in the file.
1831 The tags will be inherited if the variable `org-use-tag-inheritance'
1832 says they should be.
1833 This variable is populated from #+TAG lines.")
1835 (defcustom org-use-fast-tag-selection 'auto
1836 "Non-nil means, use fast tag selection scheme.
1837 This is a special interface to select and deselect tags with single keys.
1838 When nil, fast selection is never used.
1839 When the symbol `auto', fast selection is used if and only if selection
1840 characters for tags have been configured, either through the variable
1841 `org-tag-alist' or through a #+TAGS line in the buffer.
1842 When t, fast selection is always used and selection keys are assigned
1843 automatically if necessary."
1844 :group 'org-tags
1845 :type '(choice
1846 (const :tag "Always" t)
1847 (const :tag "Never" nil)
1848 (const :tag "When selection characters are configured" 'auto)))
1850 (defcustom org-fast-tag-selection-single-key nil
1851 "Non-nil means, fast tag selection exits after first change.
1852 When nil, you have to press RET to exit it.
1853 During fast tag selection, you can toggle this flag with `C-c'.
1854 This variable can also have the value `expert'. In this case, the window
1855 displaying the tags menu is not even shown, until you press C-c again."
1856 :group 'org-tags
1857 :type '(choice
1858 (const :tag "No" nil)
1859 (const :tag "Yes" t)
1860 (const :tag "Expert" expert)))
1862 (defvar org-fast-tag-selection-include-todo nil
1863 "Non-nil means, fast tags selection interface will also offer TODO states.
1864 This is an undocumented feature, you should not rely on it.")
1866 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1867 "The column to which tags should be indented in a headline.
1868 If this number is positive, it specifies the column. If it is negative,
1869 it means that the tags should be flushright to that column. For example,
1870 -80 works well for a normal 80 character screen."
1871 :group 'org-tags
1872 :type 'integer)
1874 (defcustom org-auto-align-tags t
1875 "Non-nil means, realign tags after pro/demotion of TODO state change.
1876 These operations change the length of a headline and therefore shift
1877 the tags around. With this options turned on, after each such operation
1878 the tags are again aligned to `org-tags-column'."
1879 :group 'org-tags
1880 :type 'boolean)
1882 (defcustom org-use-tag-inheritance t
1883 "Non-nil means, tags in levels apply also for sublevels.
1884 When nil, only the tags directly given in a specific line apply there.
1885 This may also be a list of tags that should be inherited, or a regexp that
1886 matches tags that should be inherited. Additional control is possible
1887 with the variable `org-tags-exclude-from-inheritance' which gives an
1888 explicit list of tags to be excluded from inheritance., even if the value of
1889 `org-use-tag-inheritance' would select it for inheritance.
1891 If this option is t, a match early-on in a tree can lead to a large
1892 number of matches in the subtree when constructing the agenda or creating
1893 a sparse tree. If you only want to see the first match in a tree during
1894 a search, check out the variable `org-tags-match-list-sublevels'."
1895 :group 'org-tags
1896 :type '(choice
1897 (const :tag "Not" nil)
1898 (const :tag "Always" t)
1899 (repeat :tag "Specific tags" (string :tag "Tag"))
1900 (regexp :tag "Tags matched by regexp")))
1902 (defcustom org-tags-exclude-from-inheritance nil
1903 "List of tags that should never be inherited.
1904 This is a way to exclude a few tags from inheritance. For way to do
1905 the opposite, to actively allow inheritance for selected tags,
1906 see the variable `org-use-tag-inheritance'."
1907 :group 'org-tags
1908 :type '(repeat (string :tag "Tag")))
1910 (defun org-tag-inherit-p (tag)
1911 "Check if TAG is one that should be inherited."
1912 (cond
1913 ((member tag org-tags-exclude-from-inheritance) nil)
1914 ((eq org-use-tag-inheritance t) t)
1915 ((not org-use-tag-inheritance) nil)
1916 ((stringp org-use-tag-inheritance)
1917 (string-match org-use-tag-inheritance tag))
1918 ((listp org-use-tag-inheritance)
1919 (member tag org-use-tag-inheritance))
1920 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1922 (defcustom org-tags-match-list-sublevels t
1923 "Non-nil means list also sublevels of headlines matching tag search.
1924 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1925 the sublevels of a headline matching a tag search often also match
1926 the same search. Listing all of them can create very long lists.
1927 Setting this variable to nil causes subtrees of a match to be skipped.
1928 This option is off by default, because inheritance in on. If you turn
1929 inheritance off, you very likely want to turn this option on.
1931 As a special case, if the tag search is restricted to TODO items, the
1932 value of this variable is ignored and sublevels are always checked, to
1933 make sure all corresponding TODO items find their way into the list.
1935 This variable is semi-obsolete and probably should always be true. It
1936 is better to limit inheritance to certain tags using the variables
1937 `org-use-tag-inheritanc'e and `org-tags-exclude-from-inheritance'."
1938 :group 'org-tags
1939 :type 'boolean)
1941 (defvar org-tags-history nil
1942 "History of minibuffer reads for tags.")
1943 (defvar org-last-tags-completion-table nil
1944 "The last used completion table for tags.")
1945 (defvar org-after-tags-change-hook nil
1946 "Hook that is run after the tags in a line have changed.")
1948 (defgroup org-properties nil
1949 "Options concerning properties in Org-mode."
1950 :tag "Org Properties"
1951 :group 'org)
1953 (defcustom org-property-format "%-10s %s"
1954 "How property key/value pairs should be formatted by `indent-line'.
1955 When `indent-line' hits a property definition, it will format the line
1956 according to this format, mainly to make sure that the values are
1957 lined-up with respect to each other."
1958 :group 'org-properties
1959 :type 'string)
1961 (defcustom org-use-property-inheritance nil
1962 "Non-nil means, properties apply also for sublevels.
1964 This setting is chiefly used during property searches. Turning it on can
1965 cause significant overhead when doing a search, which is why it is not
1966 on by default.
1968 When nil, only the properties directly given in the current entry count.
1969 When t, every property is inherited. The value may also be a list of
1970 properties that should have inheritance, or a regular expression matching
1971 properties that should be inherited.
1973 However, note that some special properties use inheritance under special
1974 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1975 and the properties ending in \"_ALL\" when they are used as descriptor
1976 for valid values of a property.
1978 Note for programmers:
1979 When querying an entry with `org-entry-get', you can control if inheritance
1980 should be used. By default, `org-entry-get' looks only at the local
1981 properties. You can request inheritance by setting the inherit argument
1982 to t (to force inheritance) or to `selective' (to respect the setting
1983 in this variable)."
1984 :group 'org-properties
1985 :type '(choice
1986 (const :tag "Not" nil)
1987 (const :tag "Always" t)
1988 (repeat :tag "Specific properties" (string :tag "Property"))
1989 (regexp :tag "Properties matched by regexp")))
1991 (defun org-property-inherit-p (property)
1992 "Check if PROPERTY is one that should be inherited."
1993 (cond
1994 ((eq org-use-property-inheritance t) t)
1995 ((not org-use-property-inheritance) nil)
1996 ((stringp org-use-property-inheritance)
1997 (string-match org-use-property-inheritance property))
1998 ((listp org-use-property-inheritance)
1999 (member property org-use-property-inheritance))
2000 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2002 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2003 "The default column format, if no other format has been defined.
2004 This variable can be set on the per-file basis by inserting a line
2006 #+COLUMNS: %25ITEM ....."
2007 :group 'org-properties
2008 :type 'string)
2010 (defcustom org-columns-ellipses ".."
2011 "The ellipses to be used when a field in column view is truncated.
2012 When this is the empty string, as many characters as possible are shown,
2013 but then there will be no visual indication that the field has been truncated.
2014 When this is a string of length N, the last N characters of a truncated
2015 field are replaced by this string. If the column is narrower than the
2016 ellipses string, only part of the ellipses string will be shown."
2017 :group 'org-properties
2018 :type 'string)
2020 (defcustom org-columns-modify-value-for-display-function nil
2021 "Function that modifies values for display in column view.
2022 For example, it can be used to cut out a certain part from a time stamp.
2023 The function must take 2 arguments:
2025 column-title The tite of the column (*not* the property name)
2026 value The value that should be modified.
2028 The function should return the value that should be displayed,
2029 or nil if the normal value should be used."
2030 :group 'org-properties
2031 :type 'function)
2033 (defcustom org-effort-property "Effort"
2034 "The property that is being used to keep track of effort estimates.
2035 Effort estimates given in this property need to have the format H:MM."
2036 :group 'org-properties
2037 :group 'org-progress
2038 :type '(string :tag "Property"))
2040 (defconst org-global-properties-fixed
2041 '(("VISIBILITY_ALL" . "folded children content all"))
2042 "List of property/value pairs that can be inherited by any entry.
2043 These are fixed values, for the preset properties.")
2046 (defcustom org-global-properties nil
2047 "List of property/value pairs that can be inherited by any entry.
2048 You can set buffer-local values for the same purpose in the variable
2049 `org-file-properties' this by adding lines like
2051 #+PROPERTY: NAME VALUE"
2052 :group 'org-properties
2053 :type '(repeat
2054 (cons (string :tag "Property")
2055 (string :tag "Value"))))
2057 (defvar org-file-properties nil
2058 "List of property/value pairs that can be inherited by any entry.
2059 Valid for the current buffer.
2060 This variable is populated from #+PROPERTY lines.")
2061 (make-variable-buffer-local 'org-file-properties)
2063 (defgroup org-agenda nil
2064 "Options concerning agenda views in Org-mode."
2065 :tag "Org Agenda"
2066 :group 'org)
2068 (defvar org-category nil
2069 "Variable used by org files to set a category for agenda display.
2070 Such files should use a file variable to set it, for example
2072 # -*- mode: org; org-category: \"ELisp\"
2074 or contain a special line
2076 #+CATEGORY: ELisp
2078 If the file does not specify a category, then file's base name
2079 is used instead.")
2080 (make-variable-buffer-local 'org-category)
2081 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2083 (defcustom org-agenda-files nil
2084 "The files to be used for agenda display.
2085 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2086 \\[org-remove-file]. You can also use customize to edit the list.
2088 If an entry is a directory, all files in that directory that are matched by
2089 `org-agenda-file-regexp' will be part of the file list.
2091 If the value of the variable is not a list but a single file name, then
2092 the list of agenda files is actually stored and maintained in that file, one
2093 agenda file per line."
2094 :group 'org-agenda
2095 :type '(choice
2096 (repeat :tag "List of files and directories" file)
2097 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2099 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2100 "Regular expression to match files for `org-agenda-files'.
2101 If any element in the list in that variable contains a directory instead
2102 of a normal file, all files in that directory that are matched by this
2103 regular expression will be included."
2104 :group 'org-agenda
2105 :type 'regexp)
2107 (defcustom org-agenda-text-search-extra-files nil
2108 "List of extra files to be searched by text search commands.
2109 These files will be search in addition to the agenda files by the
2110 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2111 Note that these files will only be searched for text search commands,
2112 not for the other agenda views like todo lists, tag searches or the weekly
2113 agenda. This variable is intended to list notes and possibly archive files
2114 that should also be searched by these two commands.
2115 In fact, if the first element in the list is the symbol `agenda-archives',
2116 than all archive files of all agenda files will be added to the search
2117 scope."
2118 :group 'org-agenda
2119 :type '(set :greedy t
2120 (const :tag "Agenda Archives" agenda-archives)
2121 (repeat :inline t (file))))
2123 (if (fboundp 'defvaralias)
2124 (defvaralias 'org-agenda-multi-occur-extra-files
2125 'org-agenda-text-search-extra-files))
2127 (defcustom org-agenda-skip-unavailable-files nil
2128 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2129 A nil value means to remove them, after a query, from the list."
2130 :group 'org-agenda
2131 :type 'boolean)
2133 (defcustom org-calendar-to-agenda-key [?c]
2134 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2135 The command `org-calendar-goto-agenda' will be bound to this key. The
2136 default is the character `c' because then `c' can be used to switch back and
2137 forth between agenda and calendar."
2138 :group 'org-agenda
2139 :type 'sexp)
2141 (defcustom org-calendar-agenda-action-key [?k]
2142 "The key to be installed in `calendar-mode-map' for agenda-action.
2143 The command `org-agenda-action' will be bound to this key. The
2144 default is the character `k' because we use the same key in the agenda."
2145 :group 'org-agenda
2146 :type 'sexp)
2148 (eval-after-load "calendar"
2149 '(progn
2150 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2151 'org-calendar-goto-agenda)
2152 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2153 'org-agenda-action)))
2155 (defgroup org-latex nil
2156 "Options for embedding LaTeX code into Org-mode."
2157 :tag "Org LaTeX"
2158 :group 'org)
2160 (defcustom org-format-latex-options
2161 '(:foreground default :background default :scale 1.0
2162 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2163 :matchers ("begin" "$" "$$" "\\(" "\\["))
2164 "Options for creating images from LaTeX fragments.
2165 This is a property list with the following properties:
2166 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2167 `default' means use the foreground of the default face.
2168 :background the background color, or \"Transparent\".
2169 `default' means use the background of the default face.
2170 :scale a scaling factor for the size of the images.
2171 :html-foreground, :html-background, :html-scale
2172 the same numbers for HTML export.
2173 :matchers a list indicating which matchers should be used to
2174 find LaTeX fragments. Valid members of this list are:
2175 \"begin\" find environments
2176 \"$\" find math expressions surrounded by $...$
2177 \"$$\" find math expressions surrounded by $$....$$
2178 \"\\(\" find math expressions surrounded by \\(...\\)
2179 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2180 :group 'org-latex
2181 :type 'plist)
2183 (defcustom org-format-latex-header "\\documentclass{article}
2184 \\usepackage{fullpage} % do not remove
2185 \\usepackage{amssymb}
2186 \\usepackage[usenames]{color}
2187 \\usepackage{amsmath}
2188 \\usepackage{latexsym}
2189 \\usepackage[mathscr]{eucal}
2190 \\pagestyle{empty} % do not remove"
2191 "The document header used for processing LaTeX fragments."
2192 :group 'org-latex
2193 :type 'string)
2196 (defgroup org-font-lock nil
2197 "Font-lock settings for highlighting in Org-mode."
2198 :tag "Org Font Lock"
2199 :group 'org)
2201 (defcustom org-level-color-stars-only nil
2202 "Non-nil means fontify only the stars in each headline.
2203 When nil, the entire headline is fontified.
2204 Changing it requires restart of `font-lock-mode' to become effective
2205 also in regions already fontified."
2206 :group 'org-font-lock
2207 :type 'boolean)
2209 (defcustom org-hide-leading-stars nil
2210 "Non-nil means, hide the first N-1 stars in a headline.
2211 This works by using the face `org-hide' for these stars. This
2212 face is white for a light background, and black for a dark
2213 background. You may have to customize the face `org-hide' to
2214 make this work.
2215 Changing it requires restart of `font-lock-mode' to become effective
2216 also in regions already fontified.
2217 You may also set this on a per-file basis by adding one of the following
2218 lines to the buffer:
2220 #+STARTUP: hidestars
2221 #+STARTUP: showstars"
2222 :group 'org-font-lock
2223 :type 'boolean)
2225 (defcustom org-fontify-done-headline nil
2226 "Non-nil means, change the face of a headline if it is marked DONE.
2227 Normally, only the TODO/DONE keyword indicates the state of a headline.
2228 When this is non-nil, the headline after the keyword is set to the
2229 `org-headline-done' as an additional indication."
2230 :group 'org-font-lock
2231 :type 'boolean)
2233 (defcustom org-fontify-emphasized-text t
2234 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2235 Changing this variable requires a restart of Emacs to take effect."
2236 :group 'org-font-lock
2237 :type 'boolean)
2239 (defcustom org-highlight-latex-fragments-and-specials nil
2240 "Non-nil means, fontify what is treated specially by the exporters."
2241 :group 'org-font-lock
2242 :type 'boolean)
2244 (defcustom org-hide-emphasis-markers nil
2245 "Non-nil mean font-lock should hide the emphasis marker characters."
2246 :group 'org-font-lock
2247 :type 'boolean)
2249 (defvar org-emph-re nil
2250 "Regular expression for matching emphasis.")
2251 (defvar org-verbatim-re nil
2252 "Regular expression for matching verbatim text.")
2253 (defvar org-emphasis-regexp-components) ; defined just below
2254 (defvar org-emphasis-alist) ; defined just below
2255 (defun org-set-emph-re (var val)
2256 "Set variable and compute the emphasis regular expression."
2257 (set var val)
2258 (when (and (boundp 'org-emphasis-alist)
2259 (boundp 'org-emphasis-regexp-components)
2260 org-emphasis-alist org-emphasis-regexp-components)
2261 (let* ((e org-emphasis-regexp-components)
2262 (pre (car e))
2263 (post (nth 1 e))
2264 (border (nth 2 e))
2265 (body (nth 3 e))
2266 (nl (nth 4 e))
2267 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2268 (body1 (concat body "*?"))
2269 (markers (mapconcat 'car org-emphasis-alist ""))
2270 (vmarkers (mapconcat
2271 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2272 org-emphasis-alist "")))
2273 ;; make sure special characters appear at the right position in the class
2274 (if (string-match "\\^" markers)
2275 (setq markers (concat (replace-match "" t t markers) "^")))
2276 (if (string-match "-" markers)
2277 (setq markers (concat (replace-match "" t t markers) "-")))
2278 (if (string-match "\\^" vmarkers)
2279 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2280 (if (string-match "-" vmarkers)
2281 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2282 (if (> nl 0)
2283 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2284 (int-to-string nl) "\\}")))
2285 ;; Make the regexp
2286 (setq org-emph-re
2287 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2288 "\\("
2289 "\\([" markers "]\\)"
2290 "\\("
2291 "[^" border "]\\|"
2292 "[^" border (if (and nil stacked) markers) "]"
2293 body1
2294 "[^" border (if (and nil stacked) markers) "]"
2295 "\\)"
2296 "\\3\\)"
2297 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2298 (setq org-verbatim-re
2299 (concat "\\([" pre "]\\|^\\)"
2300 "\\("
2301 "\\([" vmarkers "]\\)"
2302 "\\("
2303 "[^" border "]\\|"
2304 "[^" border "]"
2305 body1
2306 "[^" border "]"
2307 "\\)"
2308 "\\3\\)"
2309 "\\([" post "]\\|$\\)")))))
2311 (defcustom org-emphasis-regexp-components
2312 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2313 "Components used to build the regular expression for emphasis.
2314 This is a list with 6 entries. Terminology: In an emphasis string
2315 like \" *strong word* \", we call the initial space PREMATCH, the final
2316 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2317 and \"trong wor\" is the body. The different components in this variable
2318 specify what is allowed/forbidden in each part:
2320 pre Chars allowed as prematch. Beginning of line will be allowed too.
2321 post Chars allowed as postmatch. End of line will be allowed too.
2322 border The chars *forbidden* as border characters.
2323 body-regexp A regexp like \".\" to match a body character. Don't use
2324 non-shy groups here, and don't allow newline here.
2325 newline The maximum number of newlines allowed in an emphasis exp.
2327 Use customize to modify this, or restart Emacs after changing it."
2328 :group 'org-font-lock
2329 :set 'org-set-emph-re
2330 :type '(list
2331 (sexp :tag "Allowed chars in pre ")
2332 (sexp :tag "Allowed chars in post ")
2333 (sexp :tag "Forbidden chars in border ")
2334 (sexp :tag "Regexp for body ")
2335 (integer :tag "number of newlines allowed")
2336 (option (boolean :tag "Please ignore this button"))))
2338 (defcustom org-emphasis-alist
2339 `(("*" bold "<b>" "</b>")
2340 ("/" italic "<i>" "</i>")
2341 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2342 ("=" org-code "<code>" "</code>" verbatim)
2343 ("~" org-verbatim "<code>" "</code>" verbatim)
2344 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2345 "<del>" "</del>")
2347 "Special syntax for emphasized text.
2348 Text starting and ending with a special character will be emphasized, for
2349 example *bold*, _underlined_ and /italic/. This variable sets the marker
2350 characters, the face to be used by font-lock for highlighting in Org-mode
2351 Emacs buffers, and the HTML tags to be used for this.
2352 Use customize to modify this, or restart Emacs after changing it."
2353 :group 'org-font-lock
2354 :set 'org-set-emph-re
2355 :type '(repeat
2356 (list
2357 (string :tag "Marker character")
2358 (choice
2359 (face :tag "Font-lock-face")
2360 (plist :tag "Face property list"))
2361 (string :tag "HTML start tag")
2362 (string :tag "HTML end tag")
2363 (option (const verbatim)))))
2365 ;;; Miscellaneous options
2367 (defgroup org-completion nil
2368 "Completion in Org-mode."
2369 :tag "Org Completion"
2370 :group 'org)
2372 (defcustom org-completion-use-ido nil
2373 "Non-nil means, use ido completion wherever possible."
2374 :group 'org-completion
2375 :type 'boolean)
2377 (defcustom org-completion-fallback-command 'hippie-expand
2378 "The expansion command called by \\[org-complete] in normal context.
2379 Normal means, no org-mode-specific context."
2380 :group 'org-completion
2381 :type 'function)
2383 ;;; Functions and variables from ther packages
2384 ;; Declared here to avoid compiler warnings
2386 ;; XEmacs only
2387 (defvar outline-mode-menu-heading)
2388 (defvar outline-mode-menu-show)
2389 (defvar outline-mode-menu-hide)
2390 (defvar zmacs-regions) ; XEmacs regions
2392 ;; Emacs only
2393 (defvar mark-active)
2395 ;; Various packages
2396 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2397 (declare-function calendar-forward-day "cal-move" (arg))
2398 (declare-function calendar-goto-date "cal-move" (date))
2399 (declare-function calendar-goto-today "cal-move" ())
2400 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2401 (defvar calc-embedded-close-formula)
2402 (defvar calc-embedded-open-formula)
2403 (declare-function cdlatex-tab "ext:cdlatex" ())
2404 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2405 (defvar font-lock-unfontify-region-function)
2406 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2407 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2408 (defvar iswitchb-temp-buflist)
2409 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2410 (declare-function org-agenda-skip "org-agenda" ())
2411 (declare-function org-format-agenda-item "org-agenda"
2412 (extra txt &optional category tags dotime noprefix remove-re))
2413 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2414 (declare-function org-agenda-change-all-lines "org-agenda"
2415 (newhead hdmarker &optional fixface just-this))
2416 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2417 (declare-function org-agenda-maybe-redo "org-agenda" ())
2418 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2419 (beg end))
2420 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2421 (declare-function parse-time-string "parse-time" (string))
2422 (declare-function remember "remember" (&optional initial))
2423 (declare-function remember-buffer-desc "remember" ())
2424 (declare-function remember-finalize "remember" ())
2425 (defvar remember-save-after-remembering)
2426 (defvar remember-data-file)
2427 (defvar remember-register)
2428 (defvar remember-buffer)
2429 (defvar remember-handler-functions)
2430 (defvar remember-annotation-functions)
2431 (defvar texmathp-why)
2432 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2433 (declare-function table--at-cell-p "table" (position &optional object at-column))
2435 (defvar w3m-current-url)
2436 (defvar w3m-current-title)
2438 (defvar org-latex-regexps)
2440 ;;; Autoload and prepare some org modules
2442 ;; Some table stuff that needs to be defined here, because it is used
2443 ;; by the functions setting up org-mode or checking for table context.
2445 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2446 "Detects an org-type or table-type table.")
2447 (defconst org-table-line-regexp "^[ \t]*|"
2448 "Detects an org-type table line.")
2449 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2450 "Detects an org-type table line.")
2451 (defconst org-table-hline-regexp "^[ \t]*|-"
2452 "Detects an org-type table hline.")
2453 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2454 "Detects a table-type table hline.")
2455 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2456 "Searching from within a table (any type) this finds the first line
2457 outside the table.")
2459 ;; Autoload the functions in org-table.el that are needed by functions here.
2461 (eval-and-compile
2462 (org-autoload "org-table"
2463 '(org-table-align org-table-begin org-table-blank-field
2464 org-table-convert org-table-convert-region org-table-copy-down
2465 org-table-copy-region org-table-create
2466 org-table-create-or-convert-from-region
2467 org-table-create-with-table.el org-table-current-dline
2468 org-table-cut-region org-table-delete-column org-table-edit-field
2469 org-table-edit-formulas org-table-end org-table-eval-formula
2470 org-table-export org-table-field-info
2471 org-table-get-stored-formulas org-table-goto-column
2472 org-table-hline-and-move org-table-import org-table-insert-column
2473 org-table-insert-hline org-table-insert-row org-table-iterate
2474 org-table-justify-field-maybe org-table-kill-row
2475 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2476 org-table-move-column org-table-move-column-left
2477 org-table-move-column-right org-table-move-row
2478 org-table-move-row-down org-table-move-row-up
2479 org-table-next-field org-table-next-row org-table-paste-rectangle
2480 org-table-previous-field org-table-recalculate
2481 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2482 org-table-toggle-coordinate-overlays
2483 org-table-toggle-formula-debugger org-table-wrap-region
2484 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2486 (defun org-at-table-p (&optional table-type)
2487 "Return t if the cursor is inside an org-type table.
2488 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2489 (if org-enable-table-editor
2490 (save-excursion
2491 (beginning-of-line 1)
2492 (looking-at (if table-type org-table-any-line-regexp
2493 org-table-line-regexp)))
2494 nil))
2495 (defsubst org-table-p () (org-at-table-p))
2497 (defun org-at-table.el-p ()
2498 "Return t if and only if we are at a table.el table."
2499 (and (org-at-table-p 'any)
2500 (save-excursion
2501 (goto-char (org-table-begin 'any))
2502 (looking-at org-table1-hline-regexp))))
2503 (defun org-table-recognize-table.el ()
2504 "If there is a table.el table nearby, recognize it and move into it."
2505 (if org-table-tab-recognizes-table.el
2506 (if (org-at-table.el-p)
2507 (progn
2508 (beginning-of-line 1)
2509 (if (looking-at org-table-dataline-regexp)
2511 (if (looking-at org-table1-hline-regexp)
2512 (progn
2513 (beginning-of-line 2)
2514 (if (looking-at org-table-any-border-regexp)
2515 (beginning-of-line -1)))))
2516 (if (re-search-forward "|" (org-table-end t) t)
2517 (progn
2518 (require 'table)
2519 (if (table--at-cell-p (point))
2521 (message "recognizing table.el table...")
2522 (table-recognize-table)
2523 (message "recognizing table.el table...done")))
2524 (error "This should not happen..."))
2526 nil)
2527 nil))
2529 (defun org-at-table-hline-p ()
2530 "Return t if the cursor is inside a hline in a table."
2531 (if org-enable-table-editor
2532 (save-excursion
2533 (beginning-of-line 1)
2534 (looking-at org-table-hline-regexp))
2535 nil))
2537 (defvar org-table-clean-did-remove-column nil)
2539 (defun org-table-map-tables (function)
2540 "Apply FUNCTION to the start of all tables in the buffer."
2541 (save-excursion
2542 (save-restriction
2543 (widen)
2544 (goto-char (point-min))
2545 (while (re-search-forward org-table-any-line-regexp nil t)
2546 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2547 (beginning-of-line 1)
2548 (if (looking-at org-table-line-regexp)
2549 (save-excursion (funcall function)))
2550 (re-search-forward org-table-any-border-regexp nil 1))))
2551 (message "Mapping tables: done"))
2553 ;; Declare and autoload functions from org-exp.el
2555 (declare-function org-default-export-plist "org-exp")
2556 (declare-function org-infile-export-plist "org-exp")
2557 (declare-function org-get-current-options "org-exp")
2558 (eval-and-compile
2559 (org-autoload "org-exp"
2560 '(org-export org-export-as-ascii org-export-visible
2561 org-insert-export-options-template org-export-as-html-and-open
2562 org-export-as-html-batch org-export-as-html-to-buffer
2563 org-replace-region-by-html org-export-region-as-html
2564 org-export-as-html org-export-icalendar-this-file
2565 org-export-icalendar-all-agenda-files
2566 org-table-clean-before-export
2567 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2569 ;; Declare and autoload functions from org-agenda.el
2571 (eval-and-compile
2572 (org-autoload "org-agenda"
2573 '(org-agenda org-agenda-list org-search-view
2574 org-todo-list org-tags-view org-agenda-list-stuck-projects
2575 org-diary org-agenda-to-appt)))
2577 ;; Autoload org-remember
2579 (eval-and-compile
2580 (org-autoload "org-remember"
2581 '(org-remember-insinuate org-remember-annotation
2582 org-remember-apply-template org-remember org-remember-handler)))
2584 ;; Autoload org-clock.el
2587 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2588 (beg end))
2589 (declare-function org-update-mode-line "org-clock" ())
2590 (defvar org-clock-start-time)
2591 (defvar org-clock-marker (make-marker)
2592 "Marker recording the last clock-in.")
2594 (eval-and-compile
2595 (org-autoload
2596 "org-clock"
2597 '(org-clock-in org-clock-out org-clock-cancel
2598 org-clock-goto org-clock-sum org-clock-display
2599 org-remove-clock-overlays org-clock-report
2600 org-clocktable-shift org-dblock-write:clocktable
2601 org-get-clocktable)))
2603 (defun org-clock-update-time-maybe ()
2604 "If this is a CLOCK line, update it and return t.
2605 Otherwise, return nil."
2606 (interactive)
2607 (save-excursion
2608 (beginning-of-line 1)
2609 (skip-chars-forward " \t")
2610 (when (looking-at org-clock-string)
2611 (let ((re (concat "[ \t]*" org-clock-string
2612 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2613 "\\([ \t]*=>.*\\)?\\)?"))
2614 ts te h m s neg)
2615 (cond
2616 ((not (looking-at re))
2617 nil)
2618 ((not (match-end 2))
2619 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2620 (> org-clock-marker (point))
2621 (<= org-clock-marker (point-at-eol)))
2622 ;; The clock is running here
2623 (setq org-clock-start-time
2624 (apply 'encode-time
2625 (org-parse-time-string (match-string 1))))
2626 (org-update-mode-line)))
2628 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2629 (end-of-line 1)
2630 (setq ts (match-string 1)
2631 te (match-string 3))
2632 (setq s (- (time-to-seconds
2633 (apply 'encode-time (org-parse-time-string te)))
2634 (time-to-seconds
2635 (apply 'encode-time (org-parse-time-string ts))))
2636 neg (< s 0)
2637 s (abs s)
2638 h (floor (/ s 3600))
2639 s (- s (* 3600 h))
2640 m (floor (/ s 60))
2641 s (- s (* 60 s)))
2642 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2643 t))))))
2645 (defun org-check-running-clock ()
2646 "Check if the current buffer contains the running clock.
2647 If yes, offer to stop it and to save the buffer with the changes."
2648 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2649 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2650 (buffer-name))))
2651 (org-clock-out)
2652 (when (y-or-n-p "Save changed buffer?")
2653 (save-buffer))))
2655 (defun org-clocktable-try-shift (dir n)
2656 "Check if this line starts a clock table, if yes, shift the time block."
2657 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2658 (org-clocktable-shift dir n)))
2660 ;; Autoload org-timer.el
2662 ;(declare-function org-timer "org-timer")
2664 (eval-and-compile
2665 (org-autoload
2666 "org-timer"
2667 '(org-timer-start org-timer org-timer-item
2668 org-timer-change-times-in-region)))
2671 ;; Autoload archiving code
2672 ;; The stuff that is needed for cycling and tags has to be defined here.
2674 (defgroup org-archive nil
2675 "Options concerning archiving in Org-mode."
2676 :tag "Org Archive"
2677 :group 'org-structure)
2679 (defcustom org-archive-location "%s_archive::"
2680 "The location where subtrees should be archived.
2682 The value of this variable is a string, consisting of two parts,
2683 separated by a double-colon. The first part is a filename and
2684 the second part is a headline.
2686 When the filename is omitted, archiving happens in the same file.
2687 %s in the filename will be replaced by the current file
2688 name (without the directory part). Archiving to a different file
2689 is useful to keep archived entries from contributing to the
2690 Org-mode Agenda.
2692 The archived entries will be filed as subtrees of the specified
2693 headline. When the headline is omitted, the subtrees are simply
2694 filed away at the end of the file, as top-level entries.
2696 Here are a few examples:
2697 \"%s_archive::\"
2698 If the current file is Projects.org, archive in file
2699 Projects.org_archive, as top-level trees. This is the default.
2701 \"::* Archived Tasks\"
2702 Archive in the current file, under the top-level headline
2703 \"* Archived Tasks\".
2705 \"~/org/archive.org::\"
2706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2708 \"basement::** Finished Tasks\"
2709 Archive in file ./basement (relative path), as level 3 trees
2710 below the level 2 heading \"** Finished Tasks\".
2712 You may set this option on a per-file basis by adding to the buffer a
2713 line like
2715 #+ARCHIVE: basement::** Finished Tasks
2717 You may also define it locally for a subtree by setting an ARCHIVE property
2718 in the entry. If such a property is found in an entry, or anywhere up
2719 the hierarchy, it will be used."
2720 :group 'org-archive
2721 :type 'string)
2723 (defcustom org-archive-tag "ARCHIVE"
2724 "The tag that marks a subtree as archived.
2725 An archived subtree does not open during visibility cycling, and does
2726 not contribute to the agenda listings.
2727 After changing this, font-lock must be restarted in the relevant buffers to
2728 get the proper fontification."
2729 :group 'org-archive
2730 :group 'org-keywords
2731 :type 'string)
2733 (defcustom org-agenda-skip-archived-trees t
2734 "Non-nil means, the agenda will skip any items located in archived trees.
2735 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2736 variable is no longer recommended, you should leave it at the value t.
2737 Instead, use the key `v' to cycle the archives-mode in the agenda."
2738 :group 'org-archive
2739 :group 'org-agenda-skip
2740 :type 'boolean)
2742 (defcustom org-cycle-open-archived-trees nil
2743 "Non-nil means, `org-cycle' will open archived trees.
2744 An archived tree is a tree marked with the tag ARCHIVE.
2745 When nil, archived trees will stay folded. You can still open them with
2746 normal outline commands like `show-all', but not with the cycling commands."
2747 :group 'org-archive
2748 :group 'org-cycle
2749 :type 'boolean)
2751 (defcustom org-sparse-tree-open-archived-trees nil
2752 "Non-nil means sparse tree construction shows matches in archived trees.
2753 When nil, matches in these trees are highlighted, but the trees are kept in
2754 collapsed state."
2755 :group 'org-archive
2756 :group 'org-sparse-trees
2757 :type 'boolean)
2759 (defun org-cycle-hide-archived-subtrees (state)
2760 "Re-hide all archived subtrees after a visibility state change."
2761 (when (and (not org-cycle-open-archived-trees)
2762 (not (memq state '(overview folded))))
2763 (save-excursion
2764 (let* ((globalp (memq state '(contents all)))
2765 (beg (if globalp (point-min) (point)))
2766 (end (if globalp (point-max) (org-end-of-subtree t))))
2767 (org-hide-archived-subtrees beg end)
2768 (goto-char beg)
2769 (if (looking-at (concat ".*:" org-archive-tag ":"))
2770 (message "%s" (substitute-command-keys
2771 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2773 (defun org-force-cycle-archived ()
2774 "Cycle subtree even if it is archived."
2775 (interactive)
2776 (setq this-command 'org-cycle)
2777 (let ((org-cycle-open-archived-trees t))
2778 (call-interactively 'org-cycle)))
2780 (defun org-hide-archived-subtrees (beg end)
2781 "Re-hide all archived subtrees after a visibility state change."
2782 (save-excursion
2783 (let* ((re (concat ":" org-archive-tag ":")))
2784 (goto-char beg)
2785 (while (re-search-forward re end t)
2786 (and (org-on-heading-p) (hide-subtree))
2787 (org-end-of-subtree t)))))
2789 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2791 (eval-and-compile
2792 (org-autoload "org-archive"
2793 '(org-add-archive-files org-archive-subtree
2794 org-archive-to-archive-sibling org-toggle-archive-tag)))
2796 ;; Autoload Column View Code
2798 (declare-function org-columns-number-to-string "org-colview")
2799 (declare-function org-columns-get-format-and-top-level "org-colview")
2800 (declare-function org-columns-compute "org-colview")
2802 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2803 '(org-columns-number-to-string org-columns-get-format-and-top-level
2804 org-columns-compute org-agenda-columns org-columns-remove-overlays
2805 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2807 ;; Autoload ID code
2809 (org-autoload "org-id"
2810 '(org-id-get-create org-id-new org-id-copy org-id-get
2811 org-id-get-with-outline-path-completion
2812 org-id-get-with-outline-drilling
2813 org-id-goto org-id-find))
2815 ;;; Variables for pre-computed regular expressions, all buffer local
2817 (defvar org-drawer-regexp nil
2818 "Matches first line of a hidden block.")
2819 (make-variable-buffer-local 'org-drawer-regexp)
2820 (defvar org-todo-regexp nil
2821 "Matches any of the TODO state keywords.")
2822 (make-variable-buffer-local 'org-todo-regexp)
2823 (defvar org-not-done-regexp nil
2824 "Matches any of the TODO state keywords except the last one.")
2825 (make-variable-buffer-local 'org-not-done-regexp)
2826 (defvar org-todo-line-regexp nil
2827 "Matches a headline and puts TODO state into group 2 if present.")
2828 (make-variable-buffer-local 'org-todo-line-regexp)
2829 (defvar org-complex-heading-regexp nil
2830 "Matches a headline and puts everything into groups:
2831 group 1: the stars
2832 group 2: The todo keyword, maybe
2833 group 3: Priority cookie
2834 group 4: True headline
2835 group 5: Tags")
2836 (make-variable-buffer-local 'org-complex-heading-regexp)
2837 (defvar org-todo-line-tags-regexp nil
2838 "Matches a headline and puts TODO state into group 2 if present.
2839 Also put tags into group 4 if tags are present.")
2840 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2841 (defvar org-nl-done-regexp nil
2842 "Matches newline followed by a headline with the DONE keyword.")
2843 (make-variable-buffer-local 'org-nl-done-regexp)
2844 (defvar org-looking-at-done-regexp nil
2845 "Matches the DONE keyword a point.")
2846 (make-variable-buffer-local 'org-looking-at-done-regexp)
2847 (defvar org-ds-keyword-length 12
2848 "Maximum length of the Deadline and SCHEDULED keywords.")
2849 (make-variable-buffer-local 'org-ds-keyword-length)
2850 (defvar org-deadline-regexp nil
2851 "Matches the DEADLINE keyword.")
2852 (make-variable-buffer-local 'org-deadline-regexp)
2853 (defvar org-deadline-time-regexp nil
2854 "Matches the DEADLINE keyword together with a time stamp.")
2855 (make-variable-buffer-local 'org-deadline-time-regexp)
2856 (defvar org-deadline-line-regexp nil
2857 "Matches the DEADLINE keyword and the rest of the line.")
2858 (make-variable-buffer-local 'org-deadline-line-regexp)
2859 (defvar org-scheduled-regexp nil
2860 "Matches the SCHEDULED keyword.")
2861 (make-variable-buffer-local 'org-scheduled-regexp)
2862 (defvar org-scheduled-time-regexp nil
2863 "Matches the SCHEDULED keyword together with a time stamp.")
2864 (make-variable-buffer-local 'org-scheduled-time-regexp)
2865 (defvar org-closed-time-regexp nil
2866 "Matches the CLOSED keyword together with a time stamp.")
2867 (make-variable-buffer-local 'org-closed-time-regexp)
2869 (defvar org-keyword-time-regexp nil
2870 "Matches any of the 4 keywords, together with the time stamp.")
2871 (make-variable-buffer-local 'org-keyword-time-regexp)
2872 (defvar org-keyword-time-not-clock-regexp nil
2873 "Matches any of the 3 keywords, together with the time stamp.")
2874 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2875 (defvar org-maybe-keyword-time-regexp nil
2876 "Matches a timestamp, possibly preceeded by a keyword.")
2877 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2878 (defvar org-planning-or-clock-line-re nil
2879 "Matches a line with planning or clock info.")
2880 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2882 (defconst org-plain-time-of-day-regexp
2883 (concat
2884 "\\(\\<[012]?[0-9]"
2885 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2886 "\\(--?"
2887 "\\(\\<[012]?[0-9]"
2888 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2889 "\\)?")
2890 "Regular expression to match a plain time or time range.
2891 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2892 groups carry important information:
2893 0 the full match
2894 1 the first time, range or not
2895 8 the second time, if it is a range.")
2897 (defconst org-plain-time-extension-regexp
2898 (concat
2899 "\\(\\<[012]?[0-9]"
2900 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2901 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2902 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2903 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2904 groups carry important information:
2905 0 the full match
2906 7 hours of duration
2907 9 minutes of duration")
2909 (defconst org-stamp-time-of-day-regexp
2910 (concat
2911 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2912 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2913 "\\(--?"
2914 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2915 "Regular expression to match a timestamp time or time range.
2916 After a match, the following groups carry important information:
2917 0 the full match
2918 1 date plus weekday, for backreferencing to make sure both times on same day
2919 2 the first time, range or not
2920 4 the second time, if it is a range.")
2922 (defconst org-startup-options
2923 '(("fold" org-startup-folded t)
2924 ("overview" org-startup-folded t)
2925 ("nofold" org-startup-folded nil)
2926 ("showall" org-startup-folded nil)
2927 ("content" org-startup-folded content)
2928 ("hidestars" org-hide-leading-stars t)
2929 ("showstars" org-hide-leading-stars nil)
2930 ("odd" org-odd-levels-only t)
2931 ("oddeven" org-odd-levels-only nil)
2932 ("align" org-startup-align-all-tables t)
2933 ("noalign" org-startup-align-all-tables nil)
2934 ("customtime" org-display-custom-times t)
2935 ("logdone" org-log-done time)
2936 ("lognotedone" org-log-done note)
2937 ("nologdone" org-log-done nil)
2938 ("lognoteclock-out" org-log-note-clock-out t)
2939 ("nolognoteclock-out" org-log-note-clock-out nil)
2940 ("logrepeat" org-log-repeat state)
2941 ("lognoterepeat" org-log-repeat note)
2942 ("nologrepeat" org-log-repeat nil)
2943 ("constcgs" constants-unit-system cgs)
2944 ("constSI" constants-unit-system SI))
2945 "Variable associated with STARTUP options for org-mode.
2946 Each element is a list of three items: The startup options as written
2947 in the #+STARTUP line, the corresponding variable, and the value to
2948 set this variable to if the option is found. An optional forth element PUSH
2949 means to push this value onto the list in the variable.")
2951 (defun org-set-regexps-and-options ()
2952 "Precompute regular expressions for current buffer."
2953 (when (org-mode-p)
2954 (org-set-local 'org-todo-kwd-alist nil)
2955 (org-set-local 'org-todo-key-alist nil)
2956 (org-set-local 'org-todo-key-trigger nil)
2957 (org-set-local 'org-todo-keywords-1 nil)
2958 (org-set-local 'org-done-keywords nil)
2959 (org-set-local 'org-todo-heads nil)
2960 (org-set-local 'org-todo-sets nil)
2961 (org-set-local 'org-todo-log-states nil)
2962 (org-set-local 'org-file-properties nil)
2963 (org-set-local 'org-file-tags nil)
2964 (let ((re (org-make-options-regexp
2965 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2966 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2967 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2968 (splitre "[ \t]+")
2969 kwds kws0 kwsa key log value cat arch tags const links hw dws
2970 tail sep kws1 prio props ftags drawers
2971 ext-setup-or-nil setup-contents (start 0))
2972 (save-excursion
2973 (save-restriction
2974 (widen)
2975 (goto-char (point-min))
2976 (while (or (and ext-setup-or-nil
2977 (string-match re ext-setup-or-nil start)
2978 (setq start (match-end 0)))
2979 (and (setq ext-setup-or-nil nil start 0)
2980 (re-search-forward re nil t)))
2981 (setq key (upcase (match-string 1 ext-setup-or-nil))
2982 value (org-match-string-no-properties 2 ext-setup-or-nil))
2983 (cond
2984 ((equal key "CATEGORY")
2985 (if (string-match "[ \t]+$" value)
2986 (setq value (replace-match "" t t value)))
2987 (setq cat value))
2988 ((member key '("SEQ_TODO" "TODO"))
2989 (push (cons 'sequence (org-split-string value splitre)) kwds))
2990 ((equal key "TYP_TODO")
2991 (push (cons 'type (org-split-string value splitre)) kwds))
2992 ((equal key "TAGS")
2993 (setq tags (append tags (org-split-string value splitre))))
2994 ((equal key "COLUMNS")
2995 (org-set-local 'org-columns-default-format value))
2996 ((equal key "LINK")
2997 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2998 (push (cons (match-string 1 value)
2999 (org-trim (match-string 2 value)))
3000 links)))
3001 ((equal key "PRIORITIES")
3002 (setq prio (org-split-string value " +")))
3003 ((equal key "PROPERTY")
3004 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3005 (push (cons (match-string 1 value) (match-string 2 value))
3006 props)))
3007 ((equal key "FILETAGS")
3008 (when (string-match "\\S-" value)
3009 (setq ftags
3010 (append
3011 ftags
3012 (apply 'append
3013 (mapcar (lambda (x) (org-split-string x ":"))
3014 (org-split-string value)))))))
3015 ((equal key "DRAWERS")
3016 (setq drawers (org-split-string value splitre)))
3017 ((equal key "CONSTANTS")
3018 (setq const (append const (org-split-string value splitre))))
3019 ((equal key "STARTUP")
3020 (let ((opts (org-split-string value splitre))
3021 l var val)
3022 (while (setq l (pop opts))
3023 (when (setq l (assoc l org-startup-options))
3024 (setq var (nth 1 l) val (nth 2 l))
3025 (if (not (nth 3 l))
3026 (set (make-local-variable var) val)
3027 (if (not (listp (symbol-value var)))
3028 (set (make-local-variable var) nil))
3029 (set (make-local-variable var) (symbol-value var))
3030 (add-to-list var val))))))
3031 ((equal key "ARCHIVE")
3032 (string-match " *$" value)
3033 (setq arch (replace-match "" t t value))
3034 (remove-text-properties 0 (length arch)
3035 '(face t fontified t) arch))
3036 ((equal key "SETUPFILE")
3037 (setq setup-contents (org-file-contents
3038 (expand-file-name
3039 (org-remove-double-quotes value))
3040 'noerror))
3041 (if (not ext-setup-or-nil)
3042 (setq ext-setup-or-nil setup-contents start 0)
3043 (setq ext-setup-or-nil
3044 (concat (substring ext-setup-or-nil 0 start)
3045 "\n" setup-contents "\n"
3046 (substring ext-setup-or-nil start)))))
3047 ))))
3048 (when cat
3049 (org-set-local 'org-category (intern cat))
3050 (push (cons "CATEGORY" cat) props))
3051 (when prio
3052 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3053 (setq prio (mapcar 'string-to-char prio))
3054 (org-set-local 'org-highest-priority (nth 0 prio))
3055 (org-set-local 'org-lowest-priority (nth 1 prio))
3056 (org-set-local 'org-default-priority (nth 2 prio)))
3057 (and props (org-set-local 'org-file-properties (nreverse props)))
3058 (and ftags (org-set-local 'org-file-tags ftags))
3059 (and drawers (org-set-local 'org-drawers drawers))
3060 (and arch (org-set-local 'org-archive-location arch))
3061 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3062 ;; Process the TODO keywords
3063 (unless kwds
3064 ;; Use the global values as if they had been given locally.
3065 (setq kwds (default-value 'org-todo-keywords))
3066 (if (stringp (car kwds))
3067 (setq kwds (list (cons org-todo-interpretation
3068 (default-value 'org-todo-keywords)))))
3069 (setq kwds (reverse kwds)))
3070 (setq kwds (nreverse kwds))
3071 (let (inter kws kw)
3072 (while (setq kws (pop kwds))
3073 (setq inter (pop kws) sep (member "|" kws)
3074 kws0 (delete "|" (copy-sequence kws))
3075 kwsa nil
3076 kws1 (mapcar
3077 (lambda (x)
3078 ;; 1 2
3079 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3080 (progn
3081 (setq kw (match-string 1 x)
3082 key (and (match-end 2) (match-string 2 x))
3083 log (org-extract-log-state-settings x))
3084 (push (cons kw (and key (string-to-char key))) kwsa)
3085 (and log (push log org-todo-log-states))
3087 (error "Invalid TODO keyword %s" x)))
3088 kws0)
3089 kwsa (if kwsa (append '((:startgroup))
3090 (nreverse kwsa)
3091 '((:endgroup))))
3092 hw (car kws1)
3093 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3094 tail (list inter hw (car dws) (org-last dws)))
3095 (add-to-list 'org-todo-heads hw 'append)
3096 (push kws1 org-todo-sets)
3097 (setq org-done-keywords (append org-done-keywords dws nil))
3098 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3099 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3100 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3101 (setq org-todo-sets (nreverse org-todo-sets)
3102 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3103 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3104 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3105 ;; Process the constants
3106 (when const
3107 (let (e cst)
3108 (while (setq e (pop const))
3109 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3110 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3111 (setq org-table-formula-constants-local cst)))
3113 ;; Process the tags.
3114 (when tags
3115 (let (e tgs)
3116 (while (setq e (pop tags))
3117 (cond
3118 ((equal e "{") (push '(:startgroup) tgs))
3119 ((equal e "}") (push '(:endgroup) tgs))
3120 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3121 (push (cons (match-string 1 e)
3122 (string-to-char (match-string 2 e)))
3123 tgs))
3124 (t (push (list e) tgs))))
3125 (org-set-local 'org-tag-alist nil)
3126 (while (setq e (pop tgs))
3127 (or (and (stringp (car e))
3128 (assoc (car e) org-tag-alist))
3129 (push e org-tag-alist)))))
3131 ;; Compute the regular expressions and other local variables
3132 (if (not org-done-keywords)
3133 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3134 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3135 (length org-scheduled-string)
3136 (length org-clock-string)
3137 (length org-closed-string)))
3138 org-drawer-regexp
3139 (concat "^[ \t]*:\\("
3140 (mapconcat 'regexp-quote org-drawers "\\|")
3141 "\\):[ \t]*$")
3142 org-not-done-keywords
3143 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3144 org-todo-regexp
3145 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3146 "\\|") "\\)\\>")
3147 org-not-done-regexp
3148 (concat "\\<\\("
3149 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3150 "\\)\\>")
3151 org-todo-line-regexp
3152 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3153 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3154 "\\)\\>\\)?[ \t]*\\(.*\\)")
3155 org-complex-heading-regexp
3156 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3157 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3158 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3159 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3160 org-nl-done-regexp
3161 (concat "\n\\*+[ \t]+"
3162 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3163 "\\)" "\\>")
3164 org-todo-line-tags-regexp
3165 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3166 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3167 (org-re
3168 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3169 org-looking-at-done-regexp
3170 (concat "^" "\\(?:"
3171 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3172 "\\>")
3173 org-deadline-regexp (concat "\\<" org-deadline-string)
3174 org-deadline-time-regexp
3175 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3176 org-deadline-line-regexp
3177 (concat "\\<\\(" org-deadline-string "\\).*")
3178 org-scheduled-regexp
3179 (concat "\\<" org-scheduled-string)
3180 org-scheduled-time-regexp
3181 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3182 org-closed-time-regexp
3183 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3184 org-keyword-time-regexp
3185 (concat "\\<\\(" org-scheduled-string
3186 "\\|" org-deadline-string
3187 "\\|" org-closed-string
3188 "\\|" org-clock-string "\\)"
3189 " *[[<]\\([^]>]+\\)[]>]")
3190 org-keyword-time-not-clock-regexp
3191 (concat "\\<\\(" org-scheduled-string
3192 "\\|" org-deadline-string
3193 "\\|" org-closed-string
3194 "\\)"
3195 " *[[<]\\([^]>]+\\)[]>]")
3196 org-maybe-keyword-time-regexp
3197 (concat "\\(\\<\\(" org-scheduled-string
3198 "\\|" org-deadline-string
3199 "\\|" org-closed-string
3200 "\\|" org-clock-string "\\)\\)?"
3201 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3202 org-planning-or-clock-line-re
3203 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3204 "\\|" org-deadline-string
3205 "\\|" org-closed-string "\\|" org-clock-string
3206 "\\)\\>\\)")
3208 (org-compute-latex-and-specials-regexp)
3209 (org-set-font-lock-defaults))))
3211 (defun org-file-contents (file &optional noerror)
3212 "Return the contents of FILE, as a string."
3213 (if (or (not file)
3214 (not (file-readable-p file)))
3215 (if noerror
3216 (progn
3217 (message "Cannot read file %s" file)
3218 (ding) (sit-for 2)
3220 (error "Cannot read file %s" file))
3221 (with-temp-buffer
3222 (insert-file-contents file)
3223 (buffer-string))))
3225 (defun org-extract-log-state-settings (x)
3226 "Extract the log state setting from a TODO keyword string.
3227 This will extract info from a string like \"WAIT(w@/!)\"."
3228 (let (kw key log1 log2)
3229 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3230 (setq kw (match-string 1 x)
3231 key (and (match-end 2) (match-string 2 x))
3232 log1 (and (match-end 3) (match-string 3 x))
3233 log2 (and (match-end 4) (match-string 4 x)))
3234 (and (or log1 log2)
3235 (list kw
3236 (and log1 (if (equal log1 "!") 'time 'note))
3237 (and log2 (if (equal log2 "!") 'time 'note)))))))
3239 (defun org-remove-keyword-keys (list)
3240 "Remove a pair of parenthesis at the end of each string in LIST."
3241 (mapcar (lambda (x)
3242 (if (string-match "(.*)$" x)
3243 (substring x 0 (match-beginning 0))
3245 list))
3247 ;; FIXME: this could be done much better, using second characters etc.
3248 (defun org-assign-fast-keys (alist)
3249 "Assign fast keys to a keyword-key alist.
3250 Respect keys that are already there."
3251 (let (new e k c c1 c2 (char ?a))
3252 (while (setq e (pop alist))
3253 (cond
3254 ((equal e '(:startgroup)) (push e new))
3255 ((equal e '(:endgroup)) (push e new))
3257 (setq k (car e) c2 nil)
3258 (if (cdr e)
3259 (setq c (cdr e))
3260 ;; automatically assign a character.
3261 (setq c1 (string-to-char
3262 (downcase (substring
3263 k (if (= (string-to-char k) ?@) 1 0)))))
3264 (if (or (rassoc c1 new) (rassoc c1 alist))
3265 (while (or (rassoc char new) (rassoc char alist))
3266 (setq char (1+ char)))
3267 (setq c2 c1))
3268 (setq c (or c2 char)))
3269 (push (cons k c) new))))
3270 (nreverse new)))
3272 ;;; Some variables used in various places
3274 (defvar org-window-configuration nil
3275 "Used in various places to store a window configuration.")
3276 (defvar org-finish-function nil
3277 "Function to be called when `C-c C-c' is used.
3278 This is for getting out of special buffers like remember.")
3281 ;; FIXME: Occasionally check by commenting these, to make sure
3282 ;; no other functions uses these, forgetting to let-bind them.
3283 (defvar entry)
3284 (defvar state)
3285 (defvar last-state)
3286 (defvar date)
3287 (defvar description)
3289 ;; Defined somewhere in this file, but used before definition.
3290 (defvar org-html-entities)
3291 (defvar org-struct-menu)
3292 (defvar org-org-menu)
3293 (defvar org-tbl-menu)
3294 (defvar org-agenda-keymap)
3296 ;;;; Define the Org-mode
3298 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3299 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3302 ;; We use a before-change function to check if a table might need
3303 ;; an update.
3304 (defvar org-table-may-need-update t
3305 "Indicates that a table might need an update.
3306 This variable is set by `org-before-change-function'.
3307 `org-table-align' sets it back to nil.")
3308 (defun org-before-change-function (beg end)
3309 "Every change indicates that a table might need an update."
3310 (setq org-table-may-need-update t))
3311 (defvar org-mode-map)
3312 (defvar org-mode-hook nil)
3313 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3314 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3315 (defvar org-table-buffer-is-an nil)
3316 (defconst org-outline-regexp "\\*+ ")
3318 ;;;###autoload
3319 (define-derived-mode org-mode outline-mode "Org"
3320 "Outline-based notes management and organizer, alias
3321 \"Carsten's outline-mode for keeping track of everything.\"
3323 Org-mode develops organizational tasks around a NOTES file which
3324 contains information about projects as plain text. Org-mode is
3325 implemented on top of outline-mode, which is ideal to keep the content
3326 of large files well structured. It supports ToDo items, deadlines and
3327 time stamps, which magically appear in the diary listing of the Emacs
3328 calendar. Tables are easily created with a built-in table editor.
3329 Plain text URL-like links connect to websites, emails (VM), Usenet
3330 messages (Gnus), BBDB entries, and any files related to the project.
3331 For printing and sharing of notes, an Org-mode file (or a part of it)
3332 can be exported as a structured ASCII or HTML file.
3334 The following commands are available:
3336 \\{org-mode-map}"
3338 ;; Get rid of Outline menus, they are not needed
3339 ;; Need to do this here because define-derived-mode sets up
3340 ;; the keymap so late. Still, it is a waste to call this each time
3341 ;; we switch another buffer into org-mode.
3342 (if (featurep 'xemacs)
3343 (when (boundp 'outline-mode-menu-heading)
3344 ;; Assume this is Greg's port, it used easymenu
3345 (easy-menu-remove outline-mode-menu-heading)
3346 (easy-menu-remove outline-mode-menu-show)
3347 (easy-menu-remove outline-mode-menu-hide))
3348 (define-key org-mode-map [menu-bar headings] 'undefined)
3349 (define-key org-mode-map [menu-bar hide] 'undefined)
3350 (define-key org-mode-map [menu-bar show] 'undefined))
3352 (org-load-modules-maybe)
3353 (easy-menu-add org-org-menu)
3354 (easy-menu-add org-tbl-menu)
3355 (org-install-agenda-files-menu)
3356 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3357 (org-add-to-invisibility-spec '(org-cwidth))
3358 (when (featurep 'xemacs)
3359 (org-set-local 'line-move-ignore-invisible t))
3360 (org-set-local 'outline-regexp org-outline-regexp)
3361 (org-set-local 'outline-level 'org-outline-level)
3362 (when (and org-ellipsis
3363 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3364 (fboundp 'make-glyph-code))
3365 (unless org-display-table
3366 (setq org-display-table (make-display-table)))
3367 (set-display-table-slot
3368 org-display-table 4
3369 (vconcat (mapcar
3370 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3371 org-ellipsis)))
3372 (if (stringp org-ellipsis) org-ellipsis "..."))))
3373 (setq buffer-display-table org-display-table))
3374 (org-set-regexps-and-options)
3375 ;; Calc embedded
3376 (org-set-local 'calc-embedded-open-mode "# ")
3377 (modify-syntax-entry ?# "<")
3378 (modify-syntax-entry ?@ "w")
3379 (if org-startup-truncated (setq truncate-lines t))
3380 (org-set-local 'font-lock-unfontify-region-function
3381 'org-unfontify-region)
3382 ;; Activate before-change-function
3383 (org-set-local 'org-table-may-need-update t)
3384 (org-add-hook 'before-change-functions 'org-before-change-function nil
3385 'local)
3386 ;; Check for running clock before killing a buffer
3387 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3388 ;; Paragraphs and auto-filling
3389 (org-set-autofill-regexps)
3390 (setq indent-line-function 'org-indent-line-function)
3391 (org-update-radio-target-regexp)
3393 ;; Comment characters
3394 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3395 (org-set-local 'comment-padding " ")
3397 ;; Align options lines
3398 (org-set-local
3399 'align-mode-rules-list
3400 '((org-in-buffer-settings
3401 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3402 (modes . '(org-mode)))))
3404 ;; Imenu
3405 (org-set-local 'imenu-create-index-function
3406 'org-imenu-get-tree)
3408 ;; Make isearch reveal context
3409 (if (or (featurep 'xemacs)
3410 (not (boundp 'outline-isearch-open-invisible-function)))
3411 ;; Emacs 21 and XEmacs make use of the hook
3412 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3413 ;; Emacs 22 deals with this through a special variable
3414 (org-set-local 'outline-isearch-open-invisible-function
3415 (lambda (&rest ignore) (org-show-context 'isearch))))
3417 ;; If empty file that did not turn on org-mode automatically, make it to.
3418 (if (and org-insert-mode-line-in-empty-file
3419 (interactive-p)
3420 (= (point-min) (point-max)))
3421 (insert "# -*- mode: org -*-\n\n"))
3423 (unless org-inhibit-startup
3424 (when org-startup-align-all-tables
3425 (let ((bmp (buffer-modified-p)))
3426 (org-table-map-tables 'org-table-align)
3427 (set-buffer-modified-p bmp)))
3428 (org-set-startup-visibility)))
3430 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3432 (defun org-current-time ()
3433 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3434 (if (> (car org-time-stamp-rounding-minutes) 1)
3435 (let ((r (car org-time-stamp-rounding-minutes))
3436 (time (decode-time)))
3437 (apply 'encode-time
3438 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3439 (nthcdr 2 time))))
3440 (current-time)))
3442 ;;;; Font-Lock stuff, including the activators
3444 (defvar org-mouse-map (make-sparse-keymap))
3445 (org-defkey org-mouse-map
3446 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3447 (org-defkey org-mouse-map
3448 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3449 (when org-mouse-1-follows-link
3450 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3451 (when org-tab-follows-link
3452 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3453 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3454 (when org-return-follows-link
3455 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3456 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3458 (require 'font-lock)
3460 (defconst org-non-link-chars "]\t\n\r<>")
3461 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3462 "shell" "elisp"))
3463 (defvar org-link-types-re nil
3464 "Matches a link that has a url-like prefix like \"http:\"")
3465 (defvar org-link-re-with-space nil
3466 "Matches a link with spaces, optional angular brackets around it.")
3467 (defvar org-link-re-with-space2 nil
3468 "Matches a link with spaces, optional angular brackets around it.")
3469 (defvar org-link-re-with-space3 nil
3470 "Matches a link with spaces, only for internal part in bracket links.")
3471 (defvar org-angle-link-re nil
3472 "Matches link with angular brackets, spaces are allowed.")
3473 (defvar org-plain-link-re nil
3474 "Matches plain link, without spaces.")
3475 (defvar org-bracket-link-regexp nil
3476 "Matches a link in double brackets.")
3477 (defvar org-bracket-link-analytic-regexp nil
3478 "Regular expression used to analyze links.
3479 Here is what the match groups contain after a match:
3480 1: http:
3481 2: http
3482 3: path
3483 4: [desc]
3484 5: desc")
3485 (defvar org-any-link-re nil
3486 "Regular expression matching any link.")
3488 (defun org-make-link-regexps ()
3489 "Update the link regular expressions.
3490 This should be called after the variable `org-link-types' has changed."
3491 (setq org-link-types-re
3492 (concat
3493 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3494 org-link-re-with-space
3495 (concat
3496 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3497 "\\([^" org-non-link-chars " ]"
3498 "[^" org-non-link-chars "]*"
3499 "[^" org-non-link-chars " ]\\)>?")
3500 org-link-re-with-space2
3501 (concat
3502 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3503 "\\([^" org-non-link-chars " ]"
3504 "[^\t\n\r]*"
3505 "[^" org-non-link-chars " ]\\)>?")
3506 org-link-re-with-space3
3507 (concat
3508 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3509 "\\([^" org-non-link-chars " ]"
3510 "[^\t\n\r]*\\)")
3511 org-angle-link-re
3512 (concat
3513 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3514 "\\([^" org-non-link-chars " ]"
3515 "[^" org-non-link-chars "]*"
3516 "\\)>")
3517 org-plain-link-re
3518 (concat
3519 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3520 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3521 org-bracket-link-regexp
3522 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3523 org-bracket-link-analytic-regexp
3524 (concat
3525 "\\[\\["
3526 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3527 "\\([^]]+\\)"
3528 "\\]"
3529 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3530 "\\]")
3531 org-any-link-re
3532 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3533 org-angle-link-re "\\)\\|\\("
3534 org-plain-link-re "\\)")))
3536 (org-make-link-regexps)
3538 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3539 "Regular expression for fast time stamp matching.")
3540 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3541 "Regular expression for fast time stamp matching.")
3542 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3543 "Regular expression matching time strings for analysis.
3544 This one does not require the space after the date, so it can be used
3545 on a string that terminates immediately after the date.")
3546 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3547 "Regular expression matching time strings for analysis.")
3548 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3549 "Regular expression matching time stamps, with groups.")
3550 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3551 "Regular expression matching time stamps (also [..]), with groups.")
3552 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3553 "Regular expression matching a time stamp range.")
3554 (defconst org-tr-regexp-both
3555 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3556 "Regular expression matching a time stamp range.")
3557 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3558 org-ts-regexp "\\)?")
3559 "Regular expression matching a time stamp or time stamp range.")
3560 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3561 org-ts-regexp-both "\\)?")
3562 "Regular expression matching a time stamp or time stamp range.
3563 The time stamps may be either active or inactive.")
3565 (defvar org-emph-face nil)
3567 (defun org-do-emphasis-faces (limit)
3568 "Run through the buffer and add overlays to links."
3569 (let (rtn)
3570 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3571 (if (not (= (char-after (match-beginning 3))
3572 (char-after (match-beginning 4))))
3573 (progn
3574 (setq rtn t)
3575 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3576 'face
3577 (nth 1 (assoc (match-string 3)
3578 org-emphasis-alist)))
3579 (add-text-properties (match-beginning 2) (match-end 2)
3580 '(font-lock-multiline t))
3581 (when org-hide-emphasis-markers
3582 (add-text-properties (match-end 4) (match-beginning 5)
3583 '(invisible org-link))
3584 (add-text-properties (match-beginning 3) (match-end 3)
3585 '(invisible org-link)))))
3586 (backward-char 1))
3587 rtn))
3589 (defun org-emphasize (&optional char)
3590 "Insert or change an emphasis, i.e. a font like bold or italic.
3591 If there is an active region, change that region to a new emphasis.
3592 If there is no region, just insert the marker characters and position
3593 the cursor between them.
3594 CHAR should be either the marker character, or the first character of the
3595 HTML tag associated with that emphasis. If CHAR is a space, the means
3596 to remove the emphasis of the selected region.
3597 If char is not given (for example in an interactive call) it
3598 will be prompted for."
3599 (interactive)
3600 (let ((eal org-emphasis-alist) e det
3601 (erc org-emphasis-regexp-components)
3602 (prompt "")
3603 (string "") beg end move tag c s)
3604 (if (org-region-active-p)
3605 (setq beg (region-beginning) end (region-end)
3606 string (buffer-substring beg end))
3607 (setq move t))
3609 (while (setq e (pop eal))
3610 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3611 c (aref tag 0))
3612 (push (cons c (string-to-char (car e))) det)
3613 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3614 (substring tag 1)))))
3615 (setq det (nreverse det))
3616 (unless char
3617 (message "%s" (concat "Emphasis marker or tag:" prompt))
3618 (setq char (read-char-exclusive)))
3619 (setq char (or (cdr (assoc char det)) char))
3620 (if (equal char ?\ )
3621 (setq s "" move nil)
3622 (unless (assoc (char-to-string char) org-emphasis-alist)
3623 (error "No such emphasis marker: \"%c\"" char))
3624 (setq s (char-to-string char)))
3625 (while (and (> (length string) 1)
3626 (equal (substring string 0 1) (substring string -1))
3627 (assoc (substring string 0 1) org-emphasis-alist))
3628 (setq string (substring string 1 -1)))
3629 (setq string (concat s string s))
3630 (if beg (delete-region beg end))
3631 (unless (or (bolp)
3632 (string-match (concat "[" (nth 0 erc) "\n]")
3633 (char-to-string (char-before (point)))))
3634 (insert " "))
3635 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3636 (char-to-string (char-after (point))))
3637 (insert " ") (backward-char 1))
3638 (insert string)
3639 (and move (backward-char 1))))
3641 (defconst org-nonsticky-props
3642 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3645 (defun org-activate-plain-links (limit)
3646 "Run through the buffer and add overlays to links."
3647 (catch 'exit
3648 (let (f)
3649 (while (re-search-forward org-plain-link-re limit t)
3650 (setq f (get-text-property (match-beginning 0) 'face))
3651 (if (or (eq f 'org-tag)
3652 (and (listp f) (memq 'org-tag f)))
3654 (add-text-properties (match-beginning 0) (match-end 0)
3655 (list 'mouse-face 'highlight
3656 'rear-nonsticky org-nonsticky-props
3657 'keymap org-mouse-map
3659 (throw 'exit t))))))
3661 (defun org-activate-code (limit)
3662 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3663 (progn
3664 (remove-text-properties (match-beginning 0) (match-end 0)
3665 '(display t invisible t intangible t))
3666 t)))
3668 (defun org-activate-angle-links (limit)
3669 "Run through the buffer and add overlays to links."
3670 (if (re-search-forward org-angle-link-re limit t)
3671 (progn
3672 (add-text-properties (match-beginning 0) (match-end 0)
3673 (list 'mouse-face 'highlight
3674 'rear-nonsticky org-nonsticky-props
3675 'keymap org-mouse-map
3677 t)))
3679 (defun org-activate-bracket-links (limit)
3680 "Run through the buffer and add overlays to bracketed links."
3681 (if (re-search-forward org-bracket-link-regexp limit t)
3682 (let* ((help (concat "LINK: "
3683 (org-match-string-no-properties 1)))
3684 ;; FIXME: above we should remove the escapes.
3685 ;; but that requires another match, protecting match data,
3686 ;; a lot of overhead for font-lock.
3687 (ip (org-maybe-intangible
3688 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3689 'keymap org-mouse-map 'mouse-face 'highlight
3690 'font-lock-multiline t 'help-echo help)))
3691 (vp (list 'rear-nonsticky org-nonsticky-props
3692 'keymap org-mouse-map 'mouse-face 'highlight
3693 ' font-lock-multiline t 'help-echo help)))
3694 ;; We need to remove the invisible property here. Table narrowing
3695 ;; may have made some of this invisible.
3696 (remove-text-properties (match-beginning 0) (match-end 0)
3697 '(invisible nil))
3698 (if (match-end 3)
3699 (progn
3700 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3701 (add-text-properties (match-beginning 3) (match-end 3) vp)
3702 (add-text-properties (match-end 3) (match-end 0) ip))
3703 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3704 (add-text-properties (match-beginning 1) (match-end 1) vp)
3705 (add-text-properties (match-end 1) (match-end 0) ip))
3706 t)))
3708 (defun org-activate-dates (limit)
3709 "Run through the buffer and add overlays to dates."
3710 (if (re-search-forward org-tsr-regexp-both limit t)
3711 (progn
3712 (add-text-properties (match-beginning 0) (match-end 0)
3713 (list 'mouse-face 'highlight
3714 'rear-nonsticky org-nonsticky-props
3715 'keymap org-mouse-map))
3716 (when org-display-custom-times
3717 (if (match-end 3)
3718 (org-display-custom-time (match-beginning 3) (match-end 3)))
3719 (org-display-custom-time (match-beginning 1) (match-end 1)))
3720 t)))
3722 (defvar org-target-link-regexp nil
3723 "Regular expression matching radio targets in plain text.")
3724 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3725 "Regular expression matching a link target.")
3726 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3727 "Regular expression matching a radio target.")
3728 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3729 "Regular expression matching any target.")
3731 (defun org-activate-target-links (limit)
3732 "Run through the buffer and add overlays to target matches."
3733 (when org-target-link-regexp
3734 (let ((case-fold-search t))
3735 (if (re-search-forward org-target-link-regexp 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
3741 'help-echo "Radio target link"
3742 'org-linked-text t))
3743 t)))))
3745 (defun org-update-radio-target-regexp ()
3746 "Find all radio targets in this file and update the regular expression."
3747 (interactive)
3748 (when (memq 'radio org-activate-links)
3749 (setq org-target-link-regexp
3750 (org-make-target-link-regexp (org-all-targets 'radio)))
3751 (org-restart-font-lock)))
3753 (defun org-hide-wide-columns (limit)
3754 (let (s e)
3755 (setq s (text-property-any (point) (or limit (point-max))
3756 'org-cwidth t))
3757 (when s
3758 (setq e (next-single-property-change s 'org-cwidth))
3759 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3760 (goto-char e)
3761 t)))
3763 (defvar org-latex-and-specials-regexp nil
3764 "Regular expression for highlighting export special stuff.")
3765 (defvar org-match-substring-regexp)
3766 (defvar org-match-substring-with-braces-regexp)
3767 (defvar org-export-html-special-string-regexps)
3769 (defun org-compute-latex-and-specials-regexp ()
3770 "Compute regular expression for stuff treated specially by exporters."
3771 (if (not org-highlight-latex-fragments-and-specials)
3772 (org-set-local 'org-latex-and-specials-regexp nil)
3773 (require 'org-exp)
3774 (let*
3775 ((matchers (plist-get org-format-latex-options :matchers))
3776 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3777 org-latex-regexps)))
3778 (options (org-combine-plists (org-default-export-plist)
3779 (org-infile-export-plist)))
3780 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3781 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3782 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3783 (org-export-html-expand (plist-get options :expand-quoted-html))
3784 (org-export-with-special-strings (plist-get options :special-strings))
3785 (re-sub
3786 (cond
3787 ((equal org-export-with-sub-superscripts '{})
3788 (list org-match-substring-with-braces-regexp))
3789 (org-export-with-sub-superscripts
3790 (list org-match-substring-regexp))
3791 (t nil)))
3792 (re-latex
3793 (if org-export-with-LaTeX-fragments
3794 (mapcar (lambda (x) (nth 1 x)) latexs)))
3795 (re-macros
3796 (if org-export-with-TeX-macros
3797 (list (concat "\\\\"
3798 (regexp-opt
3799 (append (mapcar 'car org-html-entities)
3800 (if (boundp 'org-latex-entities)
3801 org-latex-entities nil))
3802 'words))) ; FIXME
3804 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3805 (re-special (if org-export-with-special-strings
3806 (mapcar (lambda (x) (car x))
3807 org-export-html-special-string-regexps)))
3808 (re-rest
3809 (delq nil
3810 (list
3811 (if org-export-html-expand "@<[^>\n]+>")
3812 ))))
3813 (org-set-local
3814 'org-latex-and-specials-regexp
3815 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3816 re-rest) "\\|")))))
3818 (defun org-do-latex-and-special-faces (limit)
3819 "Run through the buffer and add overlays to links."
3820 (when org-latex-and-specials-regexp
3821 (let (rtn d)
3822 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3823 limit t))
3824 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3825 'face))
3826 '(org-code org-verbatim underline)))
3827 (progn
3828 (setq rtn t
3829 d (cond ((member (char-after (1+ (match-beginning 0)))
3830 '(?_ ?^)) 1)
3831 (t 0)))
3832 (font-lock-prepend-text-property
3833 (+ d (match-beginning 0)) (match-end 0)
3834 'face 'org-latex-and-export-specials)
3835 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3836 '(font-lock-multiline t)))))
3837 rtn)))
3839 (defun org-restart-font-lock ()
3840 "Restart font-lock-mode, to force refontification."
3841 (when (and (boundp 'font-lock-mode) font-lock-mode)
3842 (font-lock-mode -1)
3843 (font-lock-mode 1)))
3845 (defun org-all-targets (&optional radio)
3846 "Return a list of all targets in this file.
3847 With optional argument RADIO, only find radio targets."
3848 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3849 rtn)
3850 (save-excursion
3851 (goto-char (point-min))
3852 (while (re-search-forward re nil t)
3853 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3854 rtn)))
3856 (defun org-make-target-link-regexp (targets)
3857 "Make regular expression matching all strings in TARGETS.
3858 The regular expression finds the targets also if there is a line break
3859 between words."
3860 (and targets
3861 (concat
3862 "\\<\\("
3863 (mapconcat
3864 (lambda (x)
3865 (while (string-match " +" x)
3866 (setq x (replace-match "\\s-+" t t x)))
3868 targets
3869 "\\|")
3870 "\\)\\>")))
3872 (defun org-activate-tags (limit)
3873 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3874 (progn
3875 (add-text-properties (match-beginning 1) (match-end 1)
3876 (list 'mouse-face 'highlight
3877 'rear-nonsticky org-nonsticky-props
3878 'keymap org-mouse-map))
3879 t)))
3881 (defun org-outline-level ()
3882 (save-excursion
3883 (looking-at outline-regexp)
3884 (if (match-beginning 1)
3885 (+ (org-get-string-indentation (match-string 1)) 1000)
3886 (1- (- (match-end 0) (match-beginning 0))))))
3888 (defvar org-font-lock-keywords nil)
3890 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3891 "Regular expression matching a property line.")
3893 (defvar org-font-lock-hook nil
3894 "Functions to be called for special font lock stuff.")
3896 (defun org-font-lock-hook (limit)
3897 (run-hook-with-args 'org-font-lock-hook limit))
3899 (defun org-set-font-lock-defaults ()
3900 (let* ((em org-fontify-emphasized-text)
3901 (lk org-activate-links)
3902 (org-font-lock-extra-keywords
3903 (list
3904 ;; Call the hook
3905 '(org-font-lock-hook)
3906 ;; Headlines
3907 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3908 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3909 ;; Table lines
3910 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3911 (1 'org-table t))
3912 ;; Table internals
3913 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3914 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3915 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3916 ;; Drawers
3917 (list org-drawer-regexp '(0 'org-special-keyword t))
3918 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3919 ;; Properties
3920 (list org-property-re
3921 '(1 'org-special-keyword t)
3922 '(3 'org-property-value t))
3923 (if org-format-transports-properties-p
3924 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3925 ;; Links
3926 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3927 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3928 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3929 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3930 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3931 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3932 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3933 '(org-hide-wide-columns (0 nil append))
3934 ;; TODO lines
3935 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3936 '(1 (org-get-todo-face 1) t))
3937 ;; DONE
3938 (if org-fontify-done-headline
3939 (list (concat "^[*]+ +\\<\\("
3940 (mapconcat 'regexp-quote org-done-keywords "\\|")
3941 "\\)\\(.*\\)")
3942 '(2 'org-headline-done t))
3943 nil)
3944 ;; Priorities
3945 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3946 ;; Special keywords
3947 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3948 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3949 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3950 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3951 ;; Emphasis
3952 (if em
3953 (if (featurep 'xemacs)
3954 '(org-do-emphasis-faces (0 nil append))
3955 '(org-do-emphasis-faces)))
3956 ;; Checkboxes
3957 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3958 2 'bold prepend)
3959 (if org-provide-checkbox-statistics
3960 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3961 (0 (org-get-checkbox-statistics-face) t)))
3962 ;; Description list items
3963 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3964 2 'bold prepend)
3965 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3966 '(1 'org-archived prepend))
3967 ;; Specials
3968 '(org-do-latex-and-special-faces)
3969 ;; Code
3970 '(org-activate-code (1 'org-code t))
3971 ;; COMMENT
3972 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3973 "\\|" org-quote-string "\\)\\>")
3974 '(1 'org-special-keyword t))
3975 '("^#.*" (0 'font-lock-comment-face t))
3977 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3978 ;; Now set the full font-lock-keywords
3979 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3980 (org-set-local 'font-lock-defaults
3981 '(org-font-lock-keywords t nil nil backward-paragraph))
3982 (kill-local-variable 'font-lock-keywords) nil))
3984 (defvar org-m nil)
3985 (defvar org-l nil)
3986 (defvar org-f nil)
3987 (defun org-get-level-face (n)
3988 "Get the right face for match N in font-lock matching of healdines."
3989 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3990 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3991 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3992 (cond
3993 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3994 ((eq n 2) org-f)
3995 (t (if org-level-color-stars-only nil org-f))))
3997 (defun org-get-todo-face (kwd)
3998 "Get the right face for a TODO keyword KWD.
3999 If KWD is a number, get the corresponding match group."
4000 (if (numberp kwd) (setq kwd (match-string kwd)))
4001 (or (cdr (assoc kwd org-todo-keyword-faces))
4002 (and (member kwd org-done-keywords) 'org-done)
4003 'org-todo))
4005 (defun org-unfontify-region (beg end &optional maybe_loudly)
4006 "Remove fontification and activation overlays from links."
4007 (font-lock-default-unfontify-region beg end)
4008 (let* ((buffer-undo-list t)
4009 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4010 (inhibit-modification-hooks t)
4011 deactivate-mark buffer-file-name buffer-file-truename)
4012 (remove-text-properties beg end
4013 '(mouse-face t keymap t org-linked-text t
4014 invisible t intangible t))))
4016 ;;;; Visibility cycling, including org-goto and indirect buffer
4018 ;;; Cycling
4020 (defvar org-cycle-global-status nil)
4021 (make-variable-buffer-local 'org-cycle-global-status)
4022 (defvar org-cycle-subtree-status nil)
4023 (make-variable-buffer-local 'org-cycle-subtree-status)
4025 ;;;###autoload
4026 (defun org-cycle (&optional arg)
4027 "Visibility cycling for Org-mode.
4029 - When this function is called with a prefix argument, rotate the entire
4030 buffer through 3 states (global cycling)
4031 1. OVERVIEW: Show only top-level headlines.
4032 2. CONTENTS: Show all headlines of all levels, but no body text.
4033 3. SHOW ALL: Show everything.
4034 When called with two C-u C-u prefixes, switch to the startup visibility,
4035 determined by the variable `org-startup-folded', and by any VISIBILITY
4036 properties in the buffer.
4037 When called with three C-u C-u C-u prefixed, show the entire buffer,
4038 including drawers.
4040 - When point is at the beginning of a headline, rotate the subtree started
4041 by this line through 3 different states (local cycling)
4042 1. FOLDED: Only the main headline is shown.
4043 2. CHILDREN: The main headline and the direct children are shown.
4044 From this state, you can move to one of the children
4045 and zoom in further.
4046 3. SUBTREE: Show the entire subtree, including body text.
4048 - When there is a numeric prefix, go up to a heading with level ARG, do
4049 a `show-subtree' and return to the previous cursor position. If ARG
4050 is negative, go up that many levels.
4052 - When point is not at the beginning of a headline, execute the global
4053 binding for TAB, which is re-indenting the line. See the option
4054 `org-cycle-emulate-tab' for details.
4056 - Special case: if point is at the beginning of the buffer and there is
4057 no headline in line 1, this function will act as if called with prefix arg.
4058 But only if also the variable `org-cycle-global-at-bob' is t."
4059 (interactive "P")
4060 (org-load-modules-maybe)
4061 (let* ((outline-regexp
4062 (if (and (org-mode-p) org-cycle-include-plain-lists)
4063 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4064 outline-regexp))
4065 (bob-special (and org-cycle-global-at-bob (bobp)
4066 (not (looking-at outline-regexp))))
4067 (org-cycle-hook
4068 (if bob-special
4069 (delq 'org-optimize-window-after-visibility-change
4070 (copy-sequence org-cycle-hook))
4071 org-cycle-hook))
4072 (pos (point)))
4074 (if (or bob-special (equal arg '(4)))
4075 ;; special case: use global cycling
4076 (setq arg t))
4078 (cond
4080 ((equal arg '(16))
4081 (org-set-startup-visibility)
4082 (message "Startup visibility, plus VISIBILITY properties"))
4084 ((equal arg '(64))
4085 (show-all)
4086 (message "Entire buffer visible, including drawers"))
4088 ((org-at-table-p 'any)
4089 ;; Enter the table or move to the next field in the table
4090 (or (org-table-recognize-table.el)
4091 (progn
4092 (if arg (org-table-edit-field t)
4093 (org-table-justify-field-maybe)
4094 (call-interactively 'org-table-next-field)))))
4096 ((eq arg t) ;; Global cycling
4098 (cond
4099 ((and (eq last-command this-command)
4100 (eq org-cycle-global-status 'overview))
4101 ;; We just created the overview - now do table of contents
4102 ;; This can be slow in very large buffers, so indicate action
4103 (message "CONTENTS...")
4104 (org-content)
4105 (message "CONTENTS...done")
4106 (setq org-cycle-global-status 'contents)
4107 (run-hook-with-args 'org-cycle-hook 'contents))
4109 ((and (eq last-command this-command)
4110 (eq org-cycle-global-status 'contents))
4111 ;; We just showed the table of contents - now show everything
4112 (show-all)
4113 (message "SHOW ALL")
4114 (setq org-cycle-global-status 'all)
4115 (run-hook-with-args 'org-cycle-hook 'all))
4118 ;; Default action: go to overview
4119 (org-overview)
4120 (message "OVERVIEW")
4121 (setq org-cycle-global-status 'overview)
4122 (run-hook-with-args 'org-cycle-hook 'overview))))
4124 ((and org-drawers org-drawer-regexp
4125 (save-excursion
4126 (beginning-of-line 1)
4127 (looking-at org-drawer-regexp)))
4128 ;; Toggle block visibility
4129 (org-flag-drawer
4130 (not (get-char-property (match-end 0) 'invisible))))
4132 ((integerp arg)
4133 ;; Show-subtree, ARG levels up from here.
4134 (save-excursion
4135 (org-back-to-heading)
4136 (outline-up-heading (if (< arg 0) (- arg)
4137 (- (funcall outline-level) arg)))
4138 (org-show-subtree)))
4140 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4141 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4142 ;; At a heading: rotate between three different views
4143 (org-back-to-heading)
4144 (let ((goal-column 0) eoh eol eos)
4145 ;; First, some boundaries
4146 (save-excursion
4147 (org-back-to-heading)
4148 (save-excursion
4149 (beginning-of-line 2)
4150 (while (and (not (eobp)) ;; this is like `next-line'
4151 (get-char-property (1- (point)) 'invisible))
4152 (beginning-of-line 2)) (setq eol (point)))
4153 (outline-end-of-heading) (setq eoh (point))
4154 (org-end-of-subtree t)
4155 (unless (eobp)
4156 (skip-chars-forward " \t\n")
4157 (beginning-of-line 1) ; in case this is an item
4159 (setq eos (1- (point))))
4160 ;; Find out what to do next and set `this-command'
4161 (cond
4162 ((= eos eoh)
4163 ;; Nothing is hidden behind this heading
4164 (message "EMPTY ENTRY")
4165 (setq org-cycle-subtree-status nil)
4166 (save-excursion
4167 (goto-char eos)
4168 (outline-next-heading)
4169 (if (org-invisible-p) (org-flag-heading nil))))
4170 ((or (>= eol eos)
4171 (not (string-match "\\S-" (buffer-substring eol eos))))
4172 ;; Entire subtree is hidden in one line: open it
4173 (org-show-entry)
4174 (show-children)
4175 (message "CHILDREN")
4176 (save-excursion
4177 (goto-char eos)
4178 (outline-next-heading)
4179 (if (org-invisible-p) (org-flag-heading nil)))
4180 (setq org-cycle-subtree-status 'children)
4181 (run-hook-with-args 'org-cycle-hook 'children))
4182 ((and (eq last-command this-command)
4183 (eq org-cycle-subtree-status 'children))
4184 ;; We just showed the children, now show everything.
4185 (org-show-subtree)
4186 (message "SUBTREE")
4187 (setq org-cycle-subtree-status 'subtree)
4188 (run-hook-with-args 'org-cycle-hook 'subtree))
4190 ;; Default action: hide the subtree.
4191 (hide-subtree)
4192 (message "FOLDED")
4193 (setq org-cycle-subtree-status 'folded)
4194 (run-hook-with-args 'org-cycle-hook 'folded)))))
4196 ;; TAB emulation and template completion
4197 (buffer-read-only (org-back-to-heading))
4199 ((org-try-structure-completion))
4201 ((org-try-cdlatex-tab))
4203 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4204 (or (not (bolp))
4205 (not (looking-at outline-regexp))))
4206 (call-interactively (global-key-binding "\t")))
4208 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4209 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4210 (or (and (eq org-cycle-emulate-tab 'white)
4211 (= (match-end 0) (point-at-eol)))
4212 (and (eq org-cycle-emulate-tab 'whitestart)
4213 (>= (match-end 0) pos))))
4215 (eq org-cycle-emulate-tab t))
4216 (call-interactively (global-key-binding "\t")))
4218 (t (save-excursion
4219 (org-back-to-heading)
4220 (org-cycle))))))
4222 ;;;###autoload
4223 (defun org-global-cycle (&optional arg)
4224 "Cycle the global visibility. For details see `org-cycle'.
4225 With C-u prefix arg, switch to startup visibility.
4226 With a numeric prefix, show all headlines up to that level."
4227 (interactive "P")
4228 (let ((org-cycle-include-plain-lists
4229 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4230 (cond
4231 ((integerp arg)
4232 (show-all)
4233 (hide-sublevels arg)
4234 (setq org-cycle-global-status 'contents))
4235 ((equal arg '(4))
4236 (org-set-startup-visibility)
4237 (message "Startup visibility, plus VISIBILITY properties."))
4239 (org-cycle '(4))))))
4241 (defun org-set-startup-visibility ()
4242 "Set the visibility required by startup options and properties."
4243 (cond
4244 ((eq org-startup-folded t)
4245 (org-cycle '(4)))
4246 ((eq org-startup-folded 'content)
4247 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4248 (org-cycle '(4)) (org-cycle '(4)))))
4249 (org-set-visibility-according-to-property 'no-cleanup)
4250 (org-cycle-hide-archived-subtrees 'all)
4251 (org-cycle-hide-drawers 'all)
4252 (org-cycle-show-empty-lines 'all))
4254 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4255 "Switch subtree visibilities according to :VISIBILITY: property."
4256 (interactive)
4257 (let (state)
4258 (save-excursion
4259 (goto-char (point-min))
4260 (while (re-search-forward
4261 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4262 nil t)
4263 (setq state (match-string 1))
4264 (save-excursion
4265 (org-back-to-heading t)
4266 (hide-subtree)
4267 (org-reveal)
4268 (cond
4269 ((equal state '("fold" "folded"))
4270 (hide-subtree))
4271 ((equal state "children")
4272 (org-show-hidden-entry)
4273 (show-children))
4274 ((equal state "content")
4275 (save-excursion
4276 (save-restriction
4277 (org-narrow-to-subtree)
4278 (org-content))))
4279 ((member state '("all" "showall"))
4280 (show-subtree)))))
4281 (unless no-cleanup
4282 (org-cycle-hide-archived-subtrees 'all)
4283 (org-cycle-hide-drawers 'all)
4284 (org-cycle-show-empty-lines 'all)))))
4286 (defun org-overview ()
4287 "Switch to overview mode, shoing only top-level headlines.
4288 Really, this shows all headlines with level equal or greater than the level
4289 of the first headline in the buffer. This is important, because if the
4290 first headline is not level one, then (hide-sublevels 1) gives confusing
4291 results."
4292 (interactive)
4293 (let ((level (save-excursion
4294 (goto-char (point-min))
4295 (if (re-search-forward (concat "^" outline-regexp) nil t)
4296 (progn
4297 (goto-char (match-beginning 0))
4298 (funcall outline-level))))))
4299 (and level (hide-sublevels level))))
4301 (defun org-content (&optional arg)
4302 "Show all headlines in the buffer, like a table of contents.
4303 With numerical argument N, show content up to level N."
4304 (interactive "P")
4305 (save-excursion
4306 ;; Visit all headings and show their offspring
4307 (and (integerp arg) (org-overview))
4308 (goto-char (point-max))
4309 (catch 'exit
4310 (while (and (progn (condition-case nil
4311 (outline-previous-visible-heading 1)
4312 (error (goto-char (point-min))))
4314 (looking-at outline-regexp))
4315 (if (integerp arg)
4316 (show-children (1- arg))
4317 (show-branches))
4318 (if (bobp) (throw 'exit nil))))))
4321 (defun org-optimize-window-after-visibility-change (state)
4322 "Adjust the window after a change in outline visibility.
4323 This function is the default value of the hook `org-cycle-hook'."
4324 (when (get-buffer-window (current-buffer))
4325 (cond
4326 ; ((eq state 'overview) (org-first-headline-recenter 1))
4327 ; ((eq state 'overview) (org-beginning-of-line))
4328 ((eq state 'content) nil)
4329 ((eq state 'all) nil)
4330 ((eq state 'folded) nil)
4331 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4332 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4334 (defun org-compact-display-after-subtree-move ()
4335 (let (beg end)
4336 (save-excursion
4337 (if (org-up-heading-safe)
4338 (progn
4339 (hide-subtree)
4340 (show-entry)
4341 (show-children)
4342 (org-cycle-show-empty-lines 'children)
4343 (org-cycle-hide-drawers 'children))
4344 (org-overview)))))
4346 (defun org-cycle-show-empty-lines (state)
4347 "Show empty lines above all visible headlines.
4348 The region to be covered depends on STATE when called through
4349 `org-cycle-hook'. Lisp program can use t for STATE to get the
4350 entire buffer covered. Note that an empty line is only shown if there
4351 are at least `org-cycle-separator-lines' empty lines before the headeline."
4352 (when (> org-cycle-separator-lines 0)
4353 (save-excursion
4354 (let* ((n org-cycle-separator-lines)
4355 (re (cond
4356 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4357 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4358 (t (let ((ns (number-to-string (- n 2))))
4359 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4360 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4361 beg end)
4362 (cond
4363 ((memq state '(overview contents t))
4364 (setq beg (point-min) end (point-max)))
4365 ((memq state '(children folded))
4366 (setq beg (point) end (progn (org-end-of-subtree t t)
4367 (beginning-of-line 2)
4368 (point)))))
4369 (when beg
4370 (goto-char beg)
4371 (while (re-search-forward re end t)
4372 (if (not (get-char-property (match-end 1) 'invisible))
4373 (outline-flag-region
4374 (match-beginning 1) (match-end 1) nil)))))))
4375 ;; Never hide empty lines at the end of the file.
4376 (save-excursion
4377 (goto-char (point-max))
4378 (outline-previous-heading)
4379 (outline-end-of-heading)
4380 (if (and (looking-at "[ \t\n]+")
4381 (= (match-end 0) (point-max)))
4382 (outline-flag-region (point) (match-end 0) nil))))
4384 (defun org-show-empty-lines-in-parent ()
4385 "Move to the parent and re-show empty lines before visible headlines."
4386 (save-excursion
4387 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4388 (org-cycle-show-empty-lines context))))
4390 (defun org-cycle-hide-drawers (state)
4391 "Re-hide all drawers after a visibility state change."
4392 (when (and (org-mode-p)
4393 (not (memq state '(overview folded))))
4394 (save-excursion
4395 (let* ((globalp (memq state '(contents all)))
4396 (beg (if globalp (point-min) (point)))
4397 (end (if globalp (point-max) (org-end-of-subtree t))))
4398 (goto-char beg)
4399 (while (re-search-forward org-drawer-regexp end t)
4400 (org-flag-drawer t))))))
4402 (defun org-flag-drawer (flag)
4403 (save-excursion
4404 (beginning-of-line 1)
4405 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4406 (let ((b (match-end 0))
4407 (outline-regexp org-outline-regexp))
4408 (if (re-search-forward
4409 "^[ \t]*:END:"
4410 (save-excursion (outline-next-heading) (point)) t)
4411 (outline-flag-region b (point-at-eol) flag)
4412 (error ":END: line missing"))))))
4414 (defun org-subtree-end-visible-p ()
4415 "Is the end of the current subtree visible?"
4416 (pos-visible-in-window-p
4417 (save-excursion (org-end-of-subtree t) (point))))
4419 (defun org-first-headline-recenter (&optional N)
4420 "Move cursor to the first headline and recenter the headline.
4421 Optional argument N means, put the headline into the Nth line of the window."
4422 (goto-char (point-min))
4423 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4424 (beginning-of-line)
4425 (recenter (prefix-numeric-value N))))
4427 ;;; Org-goto
4429 (defvar org-goto-window-configuration nil)
4430 (defvar org-goto-marker nil)
4431 (defvar org-goto-map
4432 (let ((map (make-sparse-keymap)))
4433 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4434 (while (setq cmd (pop cmds))
4435 (substitute-key-definition cmd cmd map global-map)))
4436 (suppress-keymap map)
4437 (org-defkey map "\C-m" 'org-goto-ret)
4438 (org-defkey map [(return)] 'org-goto-ret)
4439 (org-defkey map [(left)] 'org-goto-left)
4440 (org-defkey map [(right)] 'org-goto-right)
4441 (org-defkey map [(control ?g)] 'org-goto-quit)
4442 (org-defkey map "\C-i" 'org-cycle)
4443 (org-defkey map [(tab)] 'org-cycle)
4444 (org-defkey map [(down)] 'outline-next-visible-heading)
4445 (org-defkey map [(up)] 'outline-previous-visible-heading)
4446 (if org-goto-auto-isearch
4447 (if (fboundp 'define-key-after)
4448 (define-key-after map [t] 'org-goto-local-auto-isearch)
4449 nil)
4450 (org-defkey map "q" 'org-goto-quit)
4451 (org-defkey map "n" 'outline-next-visible-heading)
4452 (org-defkey map "p" 'outline-previous-visible-heading)
4453 (org-defkey map "f" 'outline-forward-same-level)
4454 (org-defkey map "b" 'outline-backward-same-level)
4455 (org-defkey map "u" 'outline-up-heading))
4456 (org-defkey map "/" 'org-occur)
4457 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4458 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4459 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4460 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4461 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4462 map))
4464 (defconst org-goto-help
4465 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4466 RET=jump to location [Q]uit and return to previous location
4467 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4469 (defvar org-goto-start-pos) ; dynamically scoped parameter
4471 ;; FIXME: Docstring doe not mention both interfaces
4472 (defun org-goto (&optional alternative-interface)
4473 "Look up a different location in the current file, keeping current visibility.
4475 When you want look-up or go to a different location in a document, the
4476 fastest way is often to fold the entire buffer and then dive into the tree.
4477 This method has the disadvantage, that the previous location will be folded,
4478 which may not be what you want.
4480 This command works around this by showing a copy of the current buffer
4481 in an indirect buffer, in overview mode. You can dive into the tree in
4482 that copy, use org-occur and incremental search to find a location.
4483 When pressing RET or `Q', the command returns to the original buffer in
4484 which the visibility is still unchanged. After RET is will also jump to
4485 the location selected in the indirect buffer and expose the
4486 the headline hierarchy above."
4487 (interactive "P")
4488 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4489 (org-refile-use-outline-path t)
4490 (interface
4491 (if (not alternative-interface)
4492 org-goto-interface
4493 (if (eq org-goto-interface 'outline)
4494 'outline-path-completion
4495 'outline)))
4496 (org-goto-start-pos (point))
4497 (selected-point
4498 (if (eq interface 'outline)
4499 (car (org-get-location (current-buffer) org-goto-help))
4500 (nth 3 (org-refile-get-location "Goto: ")))))
4501 (if selected-point
4502 (progn
4503 (org-mark-ring-push org-goto-start-pos)
4504 (goto-char selected-point)
4505 (if (or (org-invisible-p) (org-invisible-p2))
4506 (org-show-context 'org-goto)))
4507 (message "Quit"))))
4509 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4510 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4511 (defvar org-goto-local-auto-isearch-map) ; defined below
4513 (defun org-get-location (buf help)
4514 "Let the user select a location in the Org-mode buffer BUF.
4515 This function uses a recursive edit. It returns the selected position
4516 or nil."
4517 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4518 (isearch-hide-immediately nil)
4519 (isearch-search-fun-function
4520 (lambda () 'org-goto-local-search-headings))
4521 (org-goto-selected-point org-goto-exit-command))
4522 (save-excursion
4523 (save-window-excursion
4524 (delete-other-windows)
4525 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4526 (switch-to-buffer
4527 (condition-case nil
4528 (make-indirect-buffer (current-buffer) "*org-goto*")
4529 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4530 (with-output-to-temp-buffer "*Help*"
4531 (princ help))
4532 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4533 (setq buffer-read-only nil)
4534 (let ((org-startup-truncated t)
4535 (org-startup-folded nil)
4536 (org-startup-align-all-tables nil))
4537 (org-mode)
4538 (org-overview))
4539 (setq buffer-read-only t)
4540 (if (and (boundp 'org-goto-start-pos)
4541 (integer-or-marker-p org-goto-start-pos))
4542 (let ((org-show-hierarchy-above t)
4543 (org-show-siblings t)
4544 (org-show-following-heading t))
4545 (goto-char org-goto-start-pos)
4546 (and (org-invisible-p) (org-show-context)))
4547 (goto-char (point-min)))
4548 (org-beginning-of-line)
4549 (message "Select location and press RET")
4550 (use-local-map org-goto-map)
4551 (recursive-edit)
4553 (kill-buffer "*org-goto*")
4554 (cons org-goto-selected-point org-goto-exit-command)))
4556 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4557 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4558 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4559 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4561 (defun org-goto-local-search-headings (string bound noerror)
4562 "Search and make sure that any matches are in headlines."
4563 (catch 'return
4564 (while (if isearch-forward
4565 (search-forward string bound noerror)
4566 (search-backward string bound noerror))
4567 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4568 (and (member :headline context)
4569 (not (member :tags context))))
4570 (throw 'return (point))))))
4572 (defun org-goto-local-auto-isearch ()
4573 "Start isearch."
4574 (interactive)
4575 (goto-char (point-min))
4576 (let ((keys (this-command-keys)))
4577 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4578 (isearch-mode t)
4579 (isearch-process-search-char (string-to-char keys)))))
4581 (defun org-goto-ret (&optional arg)
4582 "Finish `org-goto' by going to the new location."
4583 (interactive "P")
4584 (setq org-goto-selected-point (point)
4585 org-goto-exit-command 'return)
4586 (throw 'exit nil))
4588 (defun org-goto-left ()
4589 "Finish `org-goto' by going to the new location."
4590 (interactive)
4591 (if (org-on-heading-p)
4592 (progn
4593 (beginning-of-line 1)
4594 (setq org-goto-selected-point (point)
4595 org-goto-exit-command 'left)
4596 (throw 'exit nil))
4597 (error "Not on a heading")))
4599 (defun org-goto-right ()
4600 "Finish `org-goto' by going to the new location."
4601 (interactive)
4602 (if (org-on-heading-p)
4603 (progn
4604 (setq org-goto-selected-point (point)
4605 org-goto-exit-command 'right)
4606 (throw 'exit nil))
4607 (error "Not on a heading")))
4609 (defun org-goto-quit ()
4610 "Finish `org-goto' without cursor motion."
4611 (interactive)
4612 (setq org-goto-selected-point nil)
4613 (setq org-goto-exit-command 'quit)
4614 (throw 'exit nil))
4616 ;;; Indirect buffer display of subtrees
4618 (defvar org-indirect-dedicated-frame nil
4619 "This is the frame being used for indirect tree display.")
4620 (defvar org-last-indirect-buffer nil)
4622 (defun org-tree-to-indirect-buffer (&optional arg)
4623 "Create indirect buffer and narrow it to current subtree.
4624 With numerical prefix ARG, go up to this level and then take that tree.
4625 If ARG is negative, go up that many levels.
4626 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4627 indirect buffer previously made with this command, to avoid proliferation of
4628 indirect buffers. However, when you call the command with a `C-u' prefix, or
4629 when `org-indirect-buffer-display' is `new-frame', the last buffer
4630 is kept so that you can work with several indirect buffers at the same time.
4631 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4632 requests that a new frame be made for the new buffer, so that the dedicated
4633 frame is not changed."
4634 (interactive "P")
4635 (let ((cbuf (current-buffer))
4636 (cwin (selected-window))
4637 (pos (point))
4638 beg end level heading ibuf)
4639 (save-excursion
4640 (org-back-to-heading t)
4641 (when (numberp arg)
4642 (setq level (org-outline-level))
4643 (if (< arg 0) (setq arg (+ level arg)))
4644 (while (> (setq level (org-outline-level)) arg)
4645 (outline-up-heading 1 t)))
4646 (setq beg (point)
4647 heading (org-get-heading))
4648 (org-end-of-subtree t) (setq end (point)))
4649 (if (and (buffer-live-p org-last-indirect-buffer)
4650 (not (eq org-indirect-buffer-display 'new-frame))
4651 (not arg))
4652 (kill-buffer org-last-indirect-buffer))
4653 (setq ibuf (org-get-indirect-buffer cbuf)
4654 org-last-indirect-buffer ibuf)
4655 (cond
4656 ((or (eq org-indirect-buffer-display 'new-frame)
4657 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4658 (select-frame (make-frame))
4659 (delete-other-windows)
4660 (switch-to-buffer ibuf)
4661 (org-set-frame-title heading))
4662 ((eq org-indirect-buffer-display 'dedicated-frame)
4663 (raise-frame
4664 (select-frame (or (and org-indirect-dedicated-frame
4665 (frame-live-p org-indirect-dedicated-frame)
4666 org-indirect-dedicated-frame)
4667 (setq org-indirect-dedicated-frame (make-frame)))))
4668 (delete-other-windows)
4669 (switch-to-buffer ibuf)
4670 (org-set-frame-title (concat "Indirect: " heading)))
4671 ((eq org-indirect-buffer-display 'current-window)
4672 (switch-to-buffer ibuf))
4673 ((eq org-indirect-buffer-display 'other-window)
4674 (pop-to-buffer ibuf))
4675 (t (error "Invalid value.")))
4676 (if (featurep 'xemacs)
4677 (save-excursion (org-mode) (turn-on-font-lock)))
4678 (narrow-to-region beg end)
4679 (show-all)
4680 (goto-char pos)
4681 (and (window-live-p cwin) (select-window cwin))))
4683 (defun org-get-indirect-buffer (&optional buffer)
4684 (setq buffer (or buffer (current-buffer)))
4685 (let ((n 1) (base (buffer-name buffer)) bname)
4686 (while (buffer-live-p
4687 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4688 (setq n (1+ n)))
4689 (condition-case nil
4690 (make-indirect-buffer buffer bname 'clone)
4691 (error (make-indirect-buffer buffer bname)))))
4693 (defun org-set-frame-title (title)
4694 "Set the title of the current frame to the string TITLE."
4695 ;; FIXME: how to name a single frame in XEmacs???
4696 (unless (featurep 'xemacs)
4697 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4699 ;;;; Structure editing
4701 ;;; Inserting headlines
4703 (defun org-insert-heading (&optional force-heading)
4704 "Insert a new heading or item with same depth at point.
4705 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4706 If point is at the beginning of a headline, insert a sibling before the
4707 current headline. If point is not at the beginning, do not split the line,
4708 but create the new headline after the current line."
4709 (interactive "P")
4710 (if (= (buffer-size) 0)
4711 (insert "\n* ")
4712 (when (or force-heading (not (org-insert-item)))
4713 (let* ((head (save-excursion
4714 (condition-case nil
4715 (progn
4716 (org-back-to-heading)
4717 (match-string 0))
4718 (error "*"))))
4719 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4720 pos hide-previous previous-pos)
4721 (cond
4722 ((and (org-on-heading-p) (bolp)
4723 (or (bobp)
4724 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4725 ;; insert before the current line
4726 (open-line (if blank 2 1)))
4727 ((and (bolp)
4728 (or (bobp)
4729 (save-excursion
4730 (backward-char 1) (not (org-invisible-p)))))
4731 ;; insert right here
4732 nil)
4734 ;; somewhere in the line
4735 (save-excursion
4736 (setq previous-pos (point-at-bol))
4737 (end-of-line)
4738 (setq hide-previous (org-invisible-p)))
4739 (and org-insert-heading-respect-content (org-show-subtree))
4740 (let ((split
4741 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4742 (save-excursion
4743 (let ((p (point)))
4744 (goto-char (point-at-bol))
4745 (and (looking-at org-complex-heading-regexp)
4746 (> p (match-beginning 4)))))))
4747 tags pos)
4748 (cond
4749 (org-insert-heading-respect-content
4750 (org-end-of-subtree nil t)
4751 (or (bolp) (newline))
4752 (open-line 1))
4753 ((org-on-heading-p)
4754 (when hide-previous
4755 (show-children)
4756 (org-show-entry))
4757 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4758 (setq tags (and (match-end 2) (match-string 2)))
4759 (and (match-end 1)
4760 (delete-region (match-beginning 1) (match-end 1)))
4761 (setq pos (point-at-bol))
4762 (or split (end-of-line 1))
4763 (delete-horizontal-space)
4764 (newline (if blank 2 1))
4765 (when tags
4766 (save-excursion
4767 (goto-char pos)
4768 (end-of-line 1)
4769 (insert " " tags)
4770 (org-set-tags nil 'align))))
4772 (or split (end-of-line 1))
4773 (newline (if blank 2 1)))))))
4774 (insert head) (just-one-space)
4775 (setq pos (point))
4776 (end-of-line 1)
4777 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4778 (when (and org-insert-heading-respect-content hide-previous)
4779 (save-excursion
4780 (goto-char previous-pos)
4781 (hide-subtree)))
4782 (run-hooks 'org-insert-heading-hook)))))
4784 (defun org-get-heading (&optional no-tags)
4785 "Return the heading of the current entry, without the stars."
4786 (save-excursion
4787 (org-back-to-heading t)
4788 (if (looking-at
4789 (if no-tags
4790 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4791 "\\*+[ \t]+\\([^\r\n]*\\)"))
4792 (match-string 1) "")))
4794 (defun org-insert-heading-after-current ()
4795 "Insert a new heading with same level as current, after current subtree."
4796 (interactive)
4797 (org-back-to-heading)
4798 (org-insert-heading)
4799 (org-move-subtree-down)
4800 (end-of-line 1))
4802 (defun org-insert-heading-respect-content ()
4803 (interactive)
4804 (let ((org-insert-heading-respect-content t))
4805 (org-insert-heading t)))
4807 (defun org-insert-todo-heading-respect-content (&optional force-state)
4808 (interactive "P")
4809 (let ((org-insert-heading-respect-content t))
4810 (org-insert-todo-heading force-state t)))
4812 (defun org-insert-todo-heading (arg &optional force-heading)
4813 "Insert a new heading with the same level and TODO state as current heading.
4814 If the heading has no TODO state, or if the state is DONE, use the first
4815 state (TODO by default). Also with prefix arg, force first state."
4816 (interactive "P")
4817 (when (or force-heading (not (org-insert-item 'checkbox)))
4818 (org-insert-heading force-heading)
4819 (save-excursion
4820 (org-back-to-heading)
4821 (outline-previous-heading)
4822 (looking-at org-todo-line-regexp))
4823 (if (or arg
4824 (not (match-beginning 2))
4825 (member (match-string 2) org-done-keywords))
4826 (insert (car org-todo-keywords-1) " ")
4827 (insert (match-string 2) " "))
4828 (when org-provide-todo-statistics
4829 (org-update-parent-todo-statistics))))
4831 (defun org-insert-subheading (arg)
4832 "Insert a new subheading and demote it.
4833 Works for outline headings and for plain lists alike."
4834 (interactive "P")
4835 (org-insert-heading arg)
4836 (cond
4837 ((org-on-heading-p) (org-do-demote))
4838 ((org-at-item-p) (org-indent-item 1))))
4840 (defun org-insert-todo-subheading (arg)
4841 "Insert a new subheading with TODO keyword or checkbox and demote it.
4842 Works for outline headings and for plain lists alike."
4843 (interactive "P")
4844 (org-insert-todo-heading arg)
4845 (cond
4846 ((org-on-heading-p) (org-do-demote))
4847 ((org-at-item-p) (org-indent-item 1))))
4849 ;;; Promotion and Demotion
4851 (defun org-promote-subtree ()
4852 "Promote the entire subtree.
4853 See also `org-promote'."
4854 (interactive)
4855 (save-excursion
4856 (org-map-tree 'org-promote))
4857 (org-fix-position-after-promote))
4859 (defun org-demote-subtree ()
4860 "Demote the entire subtree. See `org-demote'.
4861 See also `org-promote'."
4862 (interactive)
4863 (save-excursion
4864 (org-map-tree 'org-demote))
4865 (org-fix-position-after-promote))
4868 (defun org-do-promote ()
4869 "Promote the current heading higher up the tree.
4870 If the region is active in `transient-mark-mode', promote all headings
4871 in the region."
4872 (interactive)
4873 (save-excursion
4874 (if (org-region-active-p)
4875 (org-map-region 'org-promote (region-beginning) (region-end))
4876 (org-promote)))
4877 (org-fix-position-after-promote))
4879 (defun org-do-demote ()
4880 "Demote the current heading lower down the tree.
4881 If the region is active in `transient-mark-mode', demote all headings
4882 in the region."
4883 (interactive)
4884 (save-excursion
4885 (if (org-region-active-p)
4886 (org-map-region 'org-demote (region-beginning) (region-end))
4887 (org-demote)))
4888 (org-fix-position-after-promote))
4890 (defun org-fix-position-after-promote ()
4891 "Make sure that after pro/demotion cursor position is right."
4892 (let ((pos (point)))
4893 (when (save-excursion
4894 (beginning-of-line 1)
4895 (looking-at org-todo-line-regexp)
4896 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4897 (cond ((eobp) (insert " "))
4898 ((eolp) (insert " "))
4899 ((equal (char-after) ?\ ) (forward-char 1))))))
4901 (defun org-reduced-level (l)
4902 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4904 (defun org-get-valid-level (level &optional change)
4905 "Rectify a level change under the influence of `org-odd-levels-only'
4906 LEVEL is a current level, CHANGE is by how much the level should be
4907 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4908 even level numbers will become the next higher odd number."
4909 (if org-odd-levels-only
4910 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4911 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4912 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4913 (max 1 (+ level change))))
4915 (if (boundp 'define-obsolete-function-alias)
4916 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4917 (define-obsolete-function-alias 'org-get-legal-level
4918 'org-get-valid-level)
4919 (define-obsolete-function-alias 'org-get-legal-level
4920 'org-get-valid-level "23.1")))
4922 (defun org-promote ()
4923 "Promote the current heading higher up the tree.
4924 If the region is active in `transient-mark-mode', promote all headings
4925 in the region."
4926 (org-back-to-heading t)
4927 (let* ((level (save-match-data (funcall outline-level)))
4928 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4929 (diff (abs (- level (length up-head) -1))))
4930 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4931 (replace-match up-head nil t)
4932 ;; Fixup tag positioning
4933 (and org-auto-align-tags (org-set-tags nil t))
4934 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4936 (defun org-demote ()
4937 "Demote the current heading lower down the tree.
4938 If the region is active in `transient-mark-mode', demote all headings
4939 in the region."
4940 (org-back-to-heading t)
4941 (let* ((level (save-match-data (funcall outline-level)))
4942 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4943 (diff (abs (- level (length down-head) -1))))
4944 (replace-match down-head nil t)
4945 ;; Fixup tag positioning
4946 (and org-auto-align-tags (org-set-tags nil t))
4947 (if org-adapt-indentation (org-fixup-indentation diff))))
4949 (defun org-map-tree (fun)
4950 "Call FUN for every heading underneath the current one."
4951 (org-back-to-heading)
4952 (let ((level (funcall outline-level)))
4953 (save-excursion
4954 (funcall fun)
4955 (while (and (progn
4956 (outline-next-heading)
4957 (> (funcall outline-level) level))
4958 (not (eobp)))
4959 (funcall fun)))))
4961 (defun org-map-region (fun beg end)
4962 "Call FUN for every heading between BEG and END."
4963 (let ((org-ignore-region t))
4964 (save-excursion
4965 (setq end (copy-marker end))
4966 (goto-char beg)
4967 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4968 (< (point) end))
4969 (funcall fun))
4970 (while (and (progn
4971 (outline-next-heading)
4972 (< (point) end))
4973 (not (eobp)))
4974 (funcall fun)))))
4976 (defun org-fixup-indentation (diff)
4977 "Change the indentation in the current entry by DIFF
4978 However, if any line in the current entry has no indentation, or if it
4979 would end up with no indentation after the change, nothing at all is done."
4980 (save-excursion
4981 (let ((end (save-excursion (outline-next-heading)
4982 (point-marker)))
4983 (prohibit (if (> diff 0)
4984 "^\\S-"
4985 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4986 col)
4987 (unless (save-excursion (end-of-line 1)
4988 (re-search-forward prohibit end t))
4989 (while (and (< (point) end)
4990 (re-search-forward "^[ \t]+" end t))
4991 (goto-char (match-end 0))
4992 (setq col (current-column))
4993 (if (< diff 0) (replace-match ""))
4994 (org-indent-to-column (+ diff col))))
4995 (move-marker end nil))))
4997 (defun org-convert-to-odd-levels ()
4998 "Convert an org-mode file with all levels allowed to one with odd levels.
4999 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5000 level 5 etc."
5001 (interactive)
5002 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5003 (let ((org-odd-levels-only nil) n)
5004 (save-excursion
5005 (goto-char (point-min))
5006 (while (re-search-forward "^\\*\\*+ " nil t)
5007 (setq n (- (length (match-string 0)) 2))
5008 (while (>= (setq n (1- n)) 0)
5009 (org-demote))
5010 (end-of-line 1))))))
5013 (defun org-convert-to-oddeven-levels ()
5014 "Convert an org-mode file with only odd levels to one with odd and even levels.
5015 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5016 section with an even level, conversion would destroy the structure of the file. An error
5017 is signaled in this case."
5018 (interactive)
5019 (goto-char (point-min))
5020 ;; First check if there are no even levels
5021 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5022 (org-show-context t)
5023 (error "Not all levels are odd in this file. Conversion not possible."))
5024 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5025 (let ((org-odd-levels-only nil) n)
5026 (save-excursion
5027 (goto-char (point-min))
5028 (while (re-search-forward "^\\*\\*+ " nil t)
5029 (setq n (/ (1- (length (match-string 0))) 2))
5030 (while (>= (setq n (1- n)) 0)
5031 (org-promote))
5032 (end-of-line 1))))))
5034 (defun org-tr-level (n)
5035 "Make N odd if required."
5036 (if org-odd-levels-only (1+ (/ n 2)) n))
5038 ;;; Vertical tree motion, cutting and pasting of subtrees
5040 (defun org-move-subtree-up (&optional arg)
5041 "Move the current subtree up past ARG headlines of the same level."
5042 (interactive "p")
5043 (org-move-subtree-down (- (prefix-numeric-value arg))))
5045 (defun org-move-subtree-down (&optional arg)
5046 "Move the current subtree down past ARG headlines of the same level."
5047 (interactive "p")
5048 (setq arg (prefix-numeric-value arg))
5049 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5050 'outline-get-last-sibling))
5051 (ins-point (make-marker))
5052 (cnt (abs arg))
5053 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5054 ;; Select the tree
5055 (org-back-to-heading)
5056 (setq beg0 (point))
5057 (save-excursion
5058 (setq ne-beg (org-back-over-empty-lines))
5059 (setq beg (point)))
5060 (save-match-data
5061 (save-excursion (outline-end-of-heading)
5062 (setq folded (org-invisible-p)))
5063 (outline-end-of-subtree))
5064 (outline-next-heading)
5065 (setq ne-end (org-back-over-empty-lines))
5066 (setq end (point))
5067 (goto-char beg0)
5068 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5069 ;; include less whitespace
5070 (save-excursion
5071 (goto-char beg)
5072 (forward-line (- ne-beg ne-end))
5073 (setq beg (point))))
5074 ;; Find insertion point, with error handling
5075 (while (> cnt 0)
5076 (or (and (funcall movfunc) (looking-at outline-regexp))
5077 (progn (goto-char beg0)
5078 (error "Cannot move past superior level or buffer limit")))
5079 (setq cnt (1- cnt)))
5080 (if (> arg 0)
5081 ;; Moving forward - still need to move over subtree
5082 (progn (org-end-of-subtree t t)
5083 (save-excursion
5084 (org-back-over-empty-lines)
5085 (or (bolp) (newline)))))
5086 (setq ne-ins (org-back-over-empty-lines))
5087 (move-marker ins-point (point))
5088 (setq txt (buffer-substring beg end))
5089 (org-save-markers-in-region beg end)
5090 (delete-region beg end)
5091 (outline-flag-region (1- beg) beg nil)
5092 (outline-flag-region (1- (point)) (point) nil)
5093 (let ((bbb (point)))
5094 (insert-before-markers txt)
5095 (org-reinstall-markers-in-region bbb)
5096 (move-marker ins-point bbb))
5097 (or (bolp) (insert "\n"))
5098 (setq ins-end (point))
5099 (goto-char ins-point)
5100 (org-skip-whitespace)
5101 (when (and (< arg 0)
5102 (org-first-sibling-p)
5103 (> ne-ins ne-beg))
5104 ;; Move whitespace back to beginning
5105 (save-excursion
5106 (goto-char ins-end)
5107 (let ((kill-whole-line t))
5108 (kill-line (- ne-ins ne-beg)) (point)))
5109 (insert (make-string (- ne-ins ne-beg) ?\n)))
5110 (move-marker ins-point nil)
5111 (org-compact-display-after-subtree-move)
5112 (org-show-empty-lines-in-parent)
5113 (unless folded
5114 (org-show-entry)
5115 (show-children)
5116 (org-cycle-hide-drawers 'children))))
5118 (defvar org-subtree-clip ""
5119 "Clipboard for cut and paste of subtrees.
5120 This is actually only a copy of the kill, because we use the normal kill
5121 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5123 (defvar org-subtree-clip-folded nil
5124 "Was the last copied subtree folded?
5125 This is used to fold the tree back after pasting.")
5127 (defun org-cut-subtree (&optional n)
5128 "Cut the current subtree into the clipboard.
5129 With prefix arg N, cut this many sequential subtrees.
5130 This is a short-hand for marking the subtree and then cutting it."
5131 (interactive "p")
5132 (org-copy-subtree n 'cut))
5134 (defun org-copy-subtree (&optional n cut force-store-markers)
5135 "Cut the current subtree into the clipboard.
5136 With prefix arg N, cut this many sequential subtrees.
5137 This is a short-hand for marking the subtree and then copying it.
5138 If CUT is non-nil, actually cut the subtree.
5139 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5140 of some markers in the region, even if CUT is non-nil. This is
5141 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5142 (interactive "p")
5143 (let (beg end folded (beg0 (point)))
5144 (if (interactive-p)
5145 (org-back-to-heading nil) ; take what looks like a subtree
5146 (org-back-to-heading t)) ; take what is really there
5147 (org-back-over-empty-lines)
5148 (setq beg (point))
5149 (skip-chars-forward " \t\r\n")
5150 (save-match-data
5151 (save-excursion (outline-end-of-heading)
5152 (setq folded (org-invisible-p)))
5153 (condition-case nil
5154 (outline-forward-same-level (1- n))
5155 (error nil))
5156 (org-end-of-subtree t t))
5157 (org-back-over-empty-lines)
5158 (setq end (point))
5159 (goto-char beg0)
5160 (when (> end beg)
5161 (setq org-subtree-clip-folded folded)
5162 (when (or cut force-store-markers)
5163 (org-save-markers-in-region beg end))
5164 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5165 (setq org-subtree-clip (current-kill 0))
5166 (message "%s: Subtree(s) with %d characters"
5167 (if cut "Cut" "Copied")
5168 (length org-subtree-clip)))))
5170 (defun org-paste-subtree (&optional level tree for-yank)
5171 "Paste the clipboard as a subtree, with modification of headline level.
5172 The entire subtree is promoted or demoted in order to match a new headline
5173 level.
5175 If the cursor is at the beginning of a headline, the same level as
5176 that headline is used to paste the tree
5178 If not, the new level is derived from the *visible* headings
5179 before and after the insertion point, and taken to be the inferior headline
5180 level of the two. So if the previous visible heading is level 3 and the
5181 next is level 4 (or vice versa), level 4 will be used for insertion.
5182 This makes sure that the subtree remains an independent subtree and does
5183 not swallow low level entries.
5185 You can also force a different level, either by using a numeric prefix
5186 argument, or by inserting the heading marker by hand. For example, if the
5187 cursor is after \"*****\", then the tree will be shifted to level 5.
5189 If optional TREE is given, use this text instead of the kill ring.
5191 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5192 move back over whitespace before inserting, and move point to the end of
5193 the inserted text when done."
5194 (interactive "P")
5195 (unless (org-kill-is-subtree-p tree)
5196 (error "%s"
5197 (substitute-command-keys
5198 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5199 (let* ((visp (not (org-invisible-p)))
5200 (txt (or tree (and kill-ring (current-kill 0))))
5201 (^re (concat "^\\(" outline-regexp "\\)"))
5202 (re (concat "\\(" outline-regexp "\\)"))
5203 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5205 (old-level (if (string-match ^re txt)
5206 (- (match-end 0) (match-beginning 0) 1)
5207 -1))
5208 (force-level (cond (level (prefix-numeric-value level))
5209 ((and (looking-at "[ \t]*$")
5210 (string-match
5211 ^re_ (buffer-substring
5212 (point-at-bol) (point))))
5213 (- (match-end 1) (match-beginning 1)))
5214 ((and (bolp)
5215 (looking-at org-outline-regexp))
5216 (- (match-end 0) (point) 1))
5217 (t nil)))
5218 (previous-level (save-excursion
5219 (condition-case nil
5220 (progn
5221 (outline-previous-visible-heading 1)
5222 (if (looking-at re)
5223 (- (match-end 0) (match-beginning 0) 1)
5225 (error 1))))
5226 (next-level (save-excursion
5227 (condition-case nil
5228 (progn
5229 (or (looking-at outline-regexp)
5230 (outline-next-visible-heading 1))
5231 (if (looking-at re)
5232 (- (match-end 0) (match-beginning 0) 1)
5234 (error 1))))
5235 (new-level (or force-level (max previous-level next-level)))
5236 (shift (if (or (= old-level -1)
5237 (= new-level -1)
5238 (= old-level new-level))
5240 (- new-level old-level)))
5241 (delta (if (> shift 0) -1 1))
5242 (func (if (> shift 0) 'org-demote 'org-promote))
5243 (org-odd-levels-only nil)
5244 beg end newend)
5245 ;; Remove the forced level indicator
5246 (if force-level
5247 (delete-region (point-at-bol) (point)))
5248 ;; Paste
5249 (beginning-of-line 1)
5250 (unless for-yank (org-back-over-empty-lines))
5251 (setq beg (point))
5252 (insert-before-markers txt)
5253 (unless (string-match "\n\\'" txt) (insert "\n"))
5254 (setq newend (point))
5255 (org-reinstall-markers-in-region beg)
5256 (setq end (point))
5257 (goto-char beg)
5258 (skip-chars-forward " \t\n\r")
5259 (setq beg (point))
5260 (if (and (org-invisible-p) visp)
5261 (save-excursion (outline-show-heading)))
5262 ;; Shift if necessary
5263 (unless (= shift 0)
5264 (save-restriction
5265 (narrow-to-region beg end)
5266 (while (not (= shift 0))
5267 (org-map-region func (point-min) (point-max))
5268 (setq shift (+ delta shift)))
5269 (goto-char (point-min))
5270 (setq newend (point-max))))
5271 (when (or (interactive-p) for-yank)
5272 (message "Clipboard pasted as level %d subtree" new-level))
5273 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5274 kill-ring
5275 (eq org-subtree-clip (current-kill 0))
5276 org-subtree-clip-folded)
5277 ;; The tree was folded before it was killed/copied
5278 (hide-subtree))
5279 (and for-yank (goto-char newend))))
5281 (defun org-kill-is-subtree-p (&optional txt)
5282 "Check if the current kill is an outline subtree, or a set of trees.
5283 Returns nil if kill does not start with a headline, or if the first
5284 headline level is not the largest headline level in the tree.
5285 So this will actually accept several entries of equal levels as well,
5286 which is OK for `org-paste-subtree'.
5287 If optional TXT is given, check this string instead of the current kill."
5288 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5289 (start-level (and kill
5290 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5291 org-outline-regexp "\\)")
5292 kill)
5293 (- (match-end 2) (match-beginning 2) 1)))
5294 (re (concat "^" org-outline-regexp))
5295 (start (1+ (or (match-beginning 2) -1))))
5296 (if (not start-level)
5297 (progn
5298 nil) ;; does not even start with a heading
5299 (catch 'exit
5300 (while (setq start (string-match re kill (1+ start)))
5301 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5302 (throw 'exit nil)))
5303 t))))
5305 (defvar org-markers-to-move nil
5306 "Markers that should be moved with a cut-and-paste operation.
5307 Those markers are stored together with their positions relative to
5308 the start of the region.")
5310 (defun org-save-markers-in-region (beg end)
5311 "Check markers in region.
5312 If these markers are between BEG and END, record their position relative
5313 to BEG, so that after moving the block of text, we can put the markers back
5314 into place.
5315 This function gets called just before an entry or tree gets cut from the
5316 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5317 called immediately, to move the markers with the entries."
5318 (setq org-markers-to-move nil)
5319 (when (featurep 'org-clock)
5320 (org-clock-save-markers-for-cut-and-paste beg end))
5321 (when (featurep 'org-agenda)
5322 (org-agenda-save-markers-for-cut-and-paste beg end)))
5324 (defun org-check-and-save-marker (marker beg end)
5325 "Check if MARKER is between BEG and END.
5326 If yes, remember the marker and the distance to BEG."
5327 (when (and (marker-buffer marker)
5328 (equal (marker-buffer marker) (current-buffer)))
5329 (if (and (>= marker beg) (< marker end))
5330 (push (cons marker (- marker beg)) org-markers-to-move))))
5332 (defun org-reinstall-markers-in-region (beg)
5333 "Move all remembered markers to their position relative to BEG."
5334 (mapc (lambda (x)
5335 (move-marker (car x) (+ beg (cdr x))))
5336 org-markers-to-move)
5337 (setq org-markers-to-move nil))
5339 (defun org-narrow-to-subtree ()
5340 "Narrow buffer to the current subtree."
5341 (interactive)
5342 (save-excursion
5343 (save-match-data
5344 (narrow-to-region
5345 (progn (org-back-to-heading) (point))
5346 (progn (org-end-of-subtree t) (point))))))
5349 ;;; Outline Sorting
5351 (defun org-sort (with-case)
5352 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5353 Optional argument WITH-CASE means sort case-sensitively."
5354 (interactive "P")
5355 (if (org-at-table-p)
5356 (org-call-with-arg 'org-table-sort-lines with-case)
5357 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5359 (defun org-sort-remove-invisible (s)
5360 (remove-text-properties 0 (length s) org-rm-props s)
5361 (while (string-match org-bracket-link-regexp s)
5362 (setq s (replace-match (if (match-end 2)
5363 (match-string 3 s)
5364 (match-string 1 s)) t t s)))
5367 (defvar org-priority-regexp) ; defined later in the file
5369 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5370 "Sort entries on a certain level of an outline tree.
5371 If there is an active region, the entries in the region are sorted.
5372 Else, if the cursor is before the first entry, sort the top-level items.
5373 Else, the children of the entry at point are sorted.
5375 Sorting can be alphabetically, numerically, and by date/time as given by
5376 the first time stamp in the entry. The command prompts for the sorting
5377 type unless it has been given to the function through the SORTING-TYPE
5378 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5379 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5380 called with point at the beginning of the record. It must return either
5381 a string or a number that should serve as the sorting key for that record.
5383 Comparing entries ignores case by default. However, with an optional argument
5384 WITH-CASE, the sorting considers case as well."
5385 (interactive "P")
5386 (let ((case-func (if with-case 'identity 'downcase))
5387 start beg end stars re re2
5388 txt what tmp plain-list-p)
5389 ;; Find beginning and end of region to sort
5390 (cond
5391 ((org-region-active-p)
5392 ;; we will sort the region
5393 (setq end (region-end)
5394 what "region")
5395 (goto-char (region-beginning))
5396 (if (not (org-on-heading-p)) (outline-next-heading))
5397 (setq start (point)))
5398 ((org-at-item-p)
5399 ;; we will sort this plain list
5400 (org-beginning-of-item-list) (setq start (point))
5401 (org-end-of-item-list) (setq end (point))
5402 (goto-char start)
5403 (setq plain-list-p t
5404 what "plain list"))
5405 ((or (org-on-heading-p)
5406 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5407 ;; we will sort the children of the current headline
5408 (org-back-to-heading)
5409 (setq start (point)
5410 end (progn (org-end-of-subtree t t)
5411 (org-back-over-empty-lines)
5412 (point))
5413 what "children")
5414 (goto-char start)
5415 (show-subtree)
5416 (outline-next-heading))
5418 ;; we will sort the top-level entries in this file
5419 (goto-char (point-min))
5420 (or (org-on-heading-p) (outline-next-heading))
5421 (setq start (point) end (point-max) what "top-level")
5422 (goto-char start)
5423 (show-all)))
5425 (setq beg (point))
5426 (if (>= beg end) (error "Nothing to sort"))
5428 (unless plain-list-p
5429 (looking-at "\\(\\*+\\)")
5430 (setq stars (match-string 1)
5431 re (concat "^" (regexp-quote stars) " +")
5432 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5433 txt (buffer-substring beg end))
5434 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5435 (if (and (not (equal stars "*")) (string-match re2 txt))
5436 (error "Region to sort contains a level above the first entry")))
5438 (unless sorting-type
5439 (message
5440 (if plain-list-p
5441 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5442 "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:")
5443 what)
5444 (setq sorting-type (read-char-exclusive))
5446 (and (= (downcase sorting-type) ?f)
5447 (setq getkey-func
5448 (org-ido-completing-read "Sort using function: "
5449 obarray 'fboundp t nil nil))
5450 (setq getkey-func (intern getkey-func)))
5452 (and (= (downcase sorting-type) ?r)
5453 (setq property
5454 (org-ido-completing-read "Property: "
5455 (mapcar 'list (org-buffer-property-keys t))
5456 nil t))))
5458 (message "Sorting entries...")
5460 (save-restriction
5461 (narrow-to-region start end)
5463 (let ((dcst (downcase sorting-type))
5464 (now (current-time)))
5465 (sort-subr
5466 (/= dcst sorting-type)
5467 ;; This function moves to the beginning character of the "record" to
5468 ;; be sorted.
5469 (if plain-list-p
5470 (lambda nil
5471 (if (org-at-item-p) t (goto-char (point-max))))
5472 (lambda nil
5473 (if (re-search-forward re nil t)
5474 (goto-char (match-beginning 0))
5475 (goto-char (point-max)))))
5476 ;; This function moves to the last character of the "record" being
5477 ;; sorted.
5478 (if plain-list-p
5479 'org-end-of-item
5480 (lambda nil
5481 (save-match-data
5482 (condition-case nil
5483 (outline-forward-same-level 1)
5484 (error
5485 (goto-char (point-max)))))))
5487 ;; This function returns the value that gets sorted against.
5488 (if plain-list-p
5489 (lambda nil
5490 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5491 (cond
5492 ((= dcst ?n)
5493 (string-to-number (buffer-substring (match-end 0)
5494 (point-at-eol))))
5495 ((= dcst ?a)
5496 (buffer-substring (match-end 0) (point-at-eol)))
5497 ((= dcst ?t)
5498 (if (re-search-forward org-ts-regexp
5499 (point-at-eol) t)
5500 (org-time-string-to-time (match-string 0))
5501 now))
5502 ((= dcst ?f)
5503 (if getkey-func
5504 (progn
5505 (setq tmp (funcall getkey-func))
5506 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5507 tmp)
5508 (error "Invalid key function `%s'" getkey-func)))
5509 (t (error "Invalid sorting type `%c'" sorting-type)))))
5510 (lambda nil
5511 (cond
5512 ((= dcst ?n)
5513 (if (looking-at org-complex-heading-regexp)
5514 (string-to-number (match-string 4))
5515 nil))
5516 ((= dcst ?a)
5517 (if (looking-at org-complex-heading-regexp)
5518 (funcall case-func (match-string 4))
5519 nil))
5520 ((= dcst ?t)
5521 (if (re-search-forward org-ts-regexp
5522 (save-excursion
5523 (forward-line 2)
5524 (point)) t)
5525 (org-time-string-to-time (match-string 0))
5526 now))
5527 ((= dcst ?p)
5528 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5529 (string-to-char (match-string 2))
5530 org-default-priority))
5531 ((= dcst ?r)
5532 (or (org-entry-get nil property) ""))
5533 ((= dcst ?o)
5534 (if (looking-at org-complex-heading-regexp)
5535 (- 9999 (length (member (match-string 2)
5536 org-todo-keywords-1)))))
5537 ((= dcst ?f)
5538 (if getkey-func
5539 (progn
5540 (setq tmp (funcall getkey-func))
5541 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5542 tmp)
5543 (error "Invalid key function `%s'" getkey-func)))
5544 (t (error "Invalid sorting type `%c'" sorting-type)))))
5546 (cond
5547 ((= dcst ?a) 'string<)
5548 ((= dcst ?t) 'time-less-p)
5549 (t nil)))))
5550 (message "Sorting entries...done")))
5552 (defun org-do-sort (table what &optional with-case sorting-type)
5553 "Sort TABLE of WHAT according to SORTING-TYPE.
5554 The user will be prompted for the SORTING-TYPE if the call to this
5555 function does not specify it. WHAT is only for the prompt, to indicate
5556 what is being sorted. The sorting key will be extracted from
5557 the car of the elements of the table.
5558 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5559 (unless sorting-type
5560 (message
5561 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5562 what)
5563 (setq sorting-type (read-char-exclusive)))
5564 (let ((dcst (downcase sorting-type))
5565 extractfun comparefun)
5566 ;; Define the appropriate functions
5567 (cond
5568 ((= dcst ?n)
5569 (setq extractfun 'string-to-number
5570 comparefun (if (= dcst sorting-type) '< '>)))
5571 ((= dcst ?a)
5572 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5573 (lambda(x) (downcase (org-sort-remove-invisible x))))
5574 comparefun (if (= dcst sorting-type)
5575 'string<
5576 (lambda (a b) (and (not (string< a b))
5577 (not (string= a b)))))))
5578 ((= dcst ?t)
5579 (setq extractfun
5580 (lambda (x)
5581 (if (string-match org-ts-regexp x)
5582 (time-to-seconds
5583 (org-time-string-to-time (match-string 0 x)))
5585 comparefun (if (= dcst sorting-type) '< '>)))
5586 (t (error "Invalid sorting type `%c'" sorting-type)))
5588 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5589 table)
5590 (lambda (a b) (funcall comparefun (car a) (car b))))))
5592 ;;; Editing source examples
5594 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5595 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5596 (defvar org-edit-src-force-single-line nil)
5597 (defvar org-edit-src-from-org-mode nil)
5598 (defvar org-edit-src-picture nil)
5600 (define-minor-mode org-exit-edit-mode
5601 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5603 (defun org-edit-src-code ()
5604 "Edit the source code example at point.
5605 An indirect buffer is created, and that buffer is then narrowed to the
5606 example at point and switched to the correct language mode. When done,
5607 exit by killing the buffer with \\[org-edit-src-exit]."
5608 (interactive)
5609 (let ((line (org-current-line))
5610 (case-fold-search t)
5611 (msg (substitute-command-keys
5612 "Edit, then exit with C-c ' (C-c and single quote)"))
5613 (info (org-edit-src-find-region-and-lang))
5614 (org-mode-p (eq major-mode 'org-mode))
5615 beg end lang lang-f single)
5616 (if (not info)
5618 (setq beg (nth 0 info)
5619 end (nth 1 info)
5620 lang (nth 2 info)
5621 single (nth 3 info)
5622 lang-f (intern (concat lang "-mode")))
5623 (unless (functionp lang-f)
5624 (error "No such language mode: %s" lang-f))
5625 (goto-line line)
5626 (if (get-buffer "*Org Edit Src Example*")
5627 (kill-buffer "*Org Edit Src Example*"))
5628 (switch-to-buffer (make-indirect-buffer (current-buffer)
5629 "*Org Edit Src Example*"))
5630 (narrow-to-region beg end)
5631 (remove-text-properties beg end '(display nil invisible nil
5632 intangible nil))
5633 (let ((org-inhibit-startup t))
5634 (funcall lang-f))
5635 (set (make-local-variable 'org-edit-src-force-single-line) single)
5636 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5637 (when org-mode-p
5638 (goto-char (point-min))
5639 (while (re-search-forward "^," nil t)
5640 (replace-match "")))
5641 (goto-line line)
5642 (org-exit-edit-mode)
5643 (org-set-local 'header-line-format msg)
5644 (message "%s" msg)
5645 t)))
5647 (defun org-edit-fixed-width-region ()
5648 "Edit the fixed-width ascii drawing at point.
5649 This must be a region where each line starts with ca colon followed by
5650 a space character.
5651 An indirect buffer is created, and that buffer is then narrowed to the
5652 example at point and switched to artist-mode. When done,
5653 exit by killing the buffer with \\[org-edit-src-exit]."
5654 (interactive)
5655 (let ((line (org-current-line))
5656 (case-fold-search t)
5657 (msg (substitute-command-keys
5658 "Edit, then exit with C-c ' (C-c and single quote)"))
5659 (org-mode-p (eq major-mode 'org-mode))
5660 beg end lang lang-f)
5661 (beginning-of-line 1)
5662 (if (looking-at "[ \t]*[^:\n \t]")
5664 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5665 (setq beg (point) end beg)
5666 (save-excursion
5667 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5668 (setq beg (point-at-bol 2))
5669 (setq beg (point))))
5670 (save-excursion
5671 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5672 (setq end (1- (match-beginning 0)))
5673 (setq end (point))))
5674 (goto-line line))
5675 (if (get-buffer "*Org Edit Picture*")
5676 (kill-buffer "*Org Edit Picture*"))
5677 (switch-to-buffer (make-indirect-buffer (current-buffer)
5678 "*Org Edit Picture*"))
5679 (narrow-to-region beg end)
5680 (remove-text-properties beg end '(display nil invisible nil
5681 intangible nil))
5682 (when (fboundp 'font-lock-unfontify-region)
5683 (font-lock-unfontify-region (point-min) (point-max)))
5684 (cond
5685 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5686 (fundamental-mode)
5687 (artist-mode 1))
5688 (t (funcall org-edit-fixed-width-region-mode)))
5689 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5690 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5691 (set (make-local-variable 'org-edit-src-picture) t)
5692 (goto-char (point-min))
5693 (while (re-search-forward "^[ \t]*: ?" nil t)
5694 (replace-match ""))
5695 (goto-line line)
5696 (org-exit-edit-mode)
5697 (org-set-local 'header-line-format msg)
5698 (message "%s" msg)
5699 t)))
5702 (defun org-edit-src-find-region-and-lang ()
5703 "Find the region and language for a local edit.
5704 Return a list with beginning and end of the region, a string representing
5705 the language, a switch telling of the content should be in a single line."
5706 (let ((re-list
5707 (append
5708 org-edit-src-region-extra
5710 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5711 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5712 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5713 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5714 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5715 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5716 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5717 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5718 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5719 ("^#\\+html:" "\n" "html" single-line)
5720 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5721 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5722 ("^#\\+latex:" "\n" "latex" single-line)
5723 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5724 ("^#\\+ascii:" "\n" "ascii" single-line)
5726 (pos (point))
5727 re re1 re2 single beg end lang)
5728 (catch 'exit
5729 (while (setq entry (pop re-list))
5730 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5731 single (nth 3 entry))
5732 (save-excursion
5733 (if (or (looking-at re1)
5734 (re-search-backward re1 nil t))
5735 (progn
5736 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5737 (if (and (re-search-forward re2 nil t)
5738 (>= (match-end 0) pos))
5739 (throw 'exit (list beg (match-beginning 0) lang single))))
5740 (if (or (looking-at re2)
5741 (re-search-forward re2 nil t))
5742 (progn
5743 (setq end (match-beginning 0))
5744 (if (and (re-search-backward re1 nil t)
5745 (<= (match-beginning 0) pos))
5746 (throw 'exit
5747 (list (match-end 0) end
5748 (org-edit-src-get-lang lang) single)))))))))))
5750 (defun org-edit-src-get-lang (lang)
5751 "Extract the src language."
5752 (let ((m (match-string 0)))
5753 (cond
5754 ((stringp lang) lang)
5755 ((integerp lang) (match-string lang))
5756 ((and (eq lang 'lang)
5757 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5758 (match-string 1 m))
5759 ((and (eq lang 'style)
5760 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5761 (match-string 1 m))
5762 (t "fundamental"))))
5764 (defun org-edit-src-exit ()
5765 "Exit special edit and protect problematic lines."
5766 (interactive)
5767 (unless (buffer-base-buffer (current-buffer))
5768 (error "This is not an indirect buffer, something is wrong..."))
5769 (unless (> (point-min) 1)
5770 (error "This buffer is not narrowed, something is wrong..."))
5771 (goto-char (point-min))
5772 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5773 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5774 (when (org-bound-and-true-p org-edit-src-force-single-line)
5775 (goto-char (point-min))
5776 (while (re-search-forward "\n" nil t)
5777 (replace-match " "))
5778 (goto-char (point-min))
5779 (if (looking-at "\\s-*") (replace-match " "))
5780 (if (re-search-forward "\\s-+\\'" nil t)
5781 (replace-match "")))
5782 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5783 (goto-char (point-min))
5784 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5785 (replace-match ",\\1"))
5786 (when font-lock-mode
5787 (font-lock-unfontify-region (point-min) (point-max)))
5788 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5789 (when (org-bound-and-true-p org-edit-src-picture)
5790 (untabify (point-min) (point-max))
5791 (goto-char (point-min))
5792 (while (re-search-forward "^" nil t)
5793 (replace-match ": "))
5794 (when font-lock-mode
5795 (font-lock-unfontify-region (point-min) (point-max)))
5796 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5797 (kill-buffer (current-buffer))
5798 (and (org-mode-p) (org-restart-font-lock)))
5801 ;;; The orgstruct minor mode
5803 ;; Define a minor mode which can be used in other modes in order to
5804 ;; integrate the org-mode structure editing commands.
5806 ;; This is really a hack, because the org-mode structure commands use
5807 ;; keys which normally belong to the major mode. Here is how it
5808 ;; works: The minor mode defines all the keys necessary to operate the
5809 ;; structure commands, but wraps the commands into a function which
5810 ;; tests if the cursor is currently at a headline or a plain list
5811 ;; item. If that is the case, the structure command is used,
5812 ;; temporarily setting many Org-mode variables like regular
5813 ;; expressions for filling etc. However, when any of those keys is
5814 ;; used at a different location, function uses `key-binding' to look
5815 ;; up if the key has an associated command in another currently active
5816 ;; keymap (minor modes, major mode, global), and executes that
5817 ;; command. There might be problems if any of the keys is otherwise
5818 ;; used as a prefix key.
5820 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5821 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5822 ;; addresses this by checking explicitly for both bindings.
5824 (defvar orgstruct-mode-map (make-sparse-keymap)
5825 "Keymap for the minor `orgstruct-mode'.")
5827 (defvar org-local-vars nil
5828 "List of local variables, for use by `orgstruct-mode'")
5830 ;;;###autoload
5831 (define-minor-mode orgstruct-mode
5832 "Toggle the minor more `orgstruct-mode'.
5833 This mode is for using Org-mode structure commands in other modes.
5834 The following key behave as if Org-mode was active, if the cursor
5835 is on a headline, or on a plain list item (both in the definition
5836 of Org-mode).
5838 M-up Move entry/item up
5839 M-down Move entry/item down
5840 M-left Promote
5841 M-right Demote
5842 M-S-up Move entry/item up
5843 M-S-down Move entry/item down
5844 M-S-left Promote subtree
5845 M-S-right Demote subtree
5846 M-q Fill paragraph and items like in Org-mode
5847 C-c ^ Sort entries
5848 C-c - Cycle list bullet
5849 TAB Cycle item visibility
5850 M-RET Insert new heading/item
5851 S-M-RET Insert new TODO heading / Chekbox item
5852 C-c C-c Set tags / toggle checkbox"
5853 nil " OrgStruct" nil
5854 (org-load-modules-maybe)
5855 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5857 ;;;###autoload
5858 (defun turn-on-orgstruct ()
5859 "Unconditionally turn on `orgstruct-mode'."
5860 (orgstruct-mode 1))
5862 ;;;###autoload
5863 (defun turn-on-orgstruct++ ()
5864 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5865 In addition to setting orgstruct-mode, this also exports all indentation and
5866 autofilling variables from org-mode into the buffer. Note that turning
5867 off orgstruct-mode will *not* remove these additional settings."
5868 (orgstruct-mode 1)
5869 (let (var val)
5870 (mapc
5871 (lambda (x)
5872 (when (string-match
5873 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5874 (symbol-name (car x)))
5875 (setq var (car x) val (nth 1 x))
5876 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5877 org-local-vars)))
5879 (defun orgstruct-error ()
5880 "Error when there is no default binding for a structure key."
5881 (interactive)
5882 (error "This key has no function outside structure elements"))
5884 (defun orgstruct-setup ()
5885 "Setup orgstruct keymaps."
5886 (let ((nfunc 0)
5887 (bindings
5888 (list
5889 '([(meta up)] org-metaup)
5890 '([(meta down)] org-metadown)
5891 '([(meta left)] org-metaleft)
5892 '([(meta right)] org-metaright)
5893 '([(meta shift up)] org-shiftmetaup)
5894 '([(meta shift down)] org-shiftmetadown)
5895 '([(meta shift left)] org-shiftmetaleft)
5896 '([(meta shift right)] org-shiftmetaright)
5897 '([(shift up)] org-shiftup)
5898 '([(shift down)] org-shiftdown)
5899 '([(shift left)] org-shiftleft)
5900 '([(shift right)] org-shiftright)
5901 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5902 '("\M-q" fill-paragraph)
5903 '("\C-c^" org-sort)
5904 '("\C-c-" org-cycle-list-bullet)))
5905 elt key fun cmd)
5906 (while (setq elt (pop bindings))
5907 (setq nfunc (1+ nfunc))
5908 (setq key (org-key (car elt))
5909 fun (nth 1 elt)
5910 cmd (orgstruct-make-binding fun nfunc key))
5911 (org-defkey orgstruct-mode-map key cmd))
5913 ;; Special treatment needed for TAB and RET
5914 (org-defkey orgstruct-mode-map [(tab)]
5915 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5916 (org-defkey orgstruct-mode-map "\C-i"
5917 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5919 (org-defkey orgstruct-mode-map "\M-\C-m"
5920 (orgstruct-make-binding 'org-insert-heading 105
5921 "\M-\C-m" [(meta return)]))
5922 (org-defkey orgstruct-mode-map [(meta return)]
5923 (orgstruct-make-binding 'org-insert-heading 106
5924 [(meta return)] "\M-\C-m"))
5926 (org-defkey orgstruct-mode-map [(shift meta return)]
5927 (orgstruct-make-binding 'org-insert-todo-heading 107
5928 [(meta return)] "\M-\C-m"))
5930 (unless org-local-vars
5931 (setq org-local-vars (org-get-local-variables)))
5935 (defun orgstruct-make-binding (fun n &rest keys)
5936 "Create a function for binding in the structure minor mode.
5937 FUN is the command to call inside a table. N is used to create a unique
5938 command name. KEYS are keys that should be checked in for a command
5939 to execute outside of tables."
5940 (eval
5941 (list 'defun
5942 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5943 '(arg)
5944 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5945 "Outside of structure, run the binding of `"
5946 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5947 "'.")
5948 '(interactive "p")
5949 (list 'if
5950 '(org-context-p 'headline 'item)
5951 (list 'org-run-like-in-org-mode (list 'quote fun))
5952 (list 'let '(orgstruct-mode)
5953 (list 'call-interactively
5954 (append '(or)
5955 (mapcar (lambda (k)
5956 (list 'key-binding k))
5957 keys)
5958 '('orgstruct-error))))))))
5960 (defun org-context-p (&rest contexts)
5961 "Check if local context is any of CONTEXTS.
5962 Possible values in the list of contexts are `table', `headline', and `item'."
5963 (let ((pos (point)))
5964 (goto-char (point-at-bol))
5965 (prog1 (or (and (memq 'table contexts)
5966 (looking-at "[ \t]*|"))
5967 (and (memq 'headline contexts)
5968 ;;????????? (looking-at "\\*+"))
5969 (looking-at outline-regexp))
5970 (and (memq 'item contexts)
5971 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5972 (goto-char pos))))
5974 (defun org-get-local-variables ()
5975 "Return a list of all local variables in an org-mode buffer."
5976 (let (varlist)
5977 (with-current-buffer (get-buffer-create "*Org tmp*")
5978 (erase-buffer)
5979 (org-mode)
5980 (setq varlist (buffer-local-variables)))
5981 (kill-buffer "*Org tmp*")
5982 (delq nil
5983 (mapcar
5984 (lambda (x)
5985 (setq x
5986 (if (symbolp x)
5987 (list x)
5988 (list (car x) (list 'quote (cdr x)))))
5989 (if (string-match
5990 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5991 (symbol-name (car x)))
5992 x nil))
5993 varlist))))
5995 ;;;###autoload
5996 (defun org-run-like-in-org-mode (cmd)
5997 (org-load-modules-maybe)
5998 (unless org-local-vars
5999 (setq org-local-vars (org-get-local-variables)))
6000 (eval (list 'let org-local-vars
6001 (list 'call-interactively (list 'quote cmd)))))
6003 ;;;; Archiving
6005 (defun org-get-category (&optional pos)
6006 "Get the category applying to position POS."
6007 (get-text-property (or pos (point)) 'org-category))
6009 (defun org-refresh-category-properties ()
6010 "Refresh category text properties in the buffer."
6011 (let ((def-cat (cond
6012 ((null org-category)
6013 (if buffer-file-name
6014 (file-name-sans-extension
6015 (file-name-nondirectory buffer-file-name))
6016 "???"))
6017 ((symbolp org-category) (symbol-name org-category))
6018 (t org-category)))
6019 beg end cat pos optionp)
6020 (org-unmodified
6021 (save-excursion
6022 (save-restriction
6023 (widen)
6024 (goto-char (point-min))
6025 (put-text-property (point) (point-max) 'org-category def-cat)
6026 (while (re-search-forward
6027 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6028 (setq pos (match-end 0)
6029 optionp (equal (char-after (match-beginning 0)) ?#)
6030 cat (org-trim (match-string 2)))
6031 (if optionp
6032 (setq beg (point-at-bol) end (point-max))
6033 (org-back-to-heading t)
6034 (setq beg (point) end (org-end-of-subtree t t)))
6035 (put-text-property beg end 'org-category cat)
6036 (goto-char pos)))))))
6039 ;;;; Link Stuff
6041 ;;; Link abbreviations
6043 (defun org-link-expand-abbrev (link)
6044 "Apply replacements as defined in `org-link-abbrev-alist."
6045 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6046 (let* ((key (match-string 1 link))
6047 (as (or (assoc key org-link-abbrev-alist-local)
6048 (assoc key org-link-abbrev-alist)))
6049 (tag (and (match-end 2) (match-string 3 link)))
6050 rpl)
6051 (if (not as)
6052 link
6053 (setq rpl (cdr as))
6054 (cond
6055 ((symbolp rpl) (funcall rpl tag))
6056 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6057 ((string-match "%h" rpl)
6058 (replace-match (url-hexify-string (or tag "")) t t rpl))
6059 (t (concat rpl tag)))))
6060 link))
6062 ;;; Storing and inserting links
6064 (defvar org-insert-link-history nil
6065 "Minibuffer history for links inserted with `org-insert-link'.")
6067 (defvar org-stored-links nil
6068 "Contains the links stored with `org-store-link'.")
6070 (defvar org-store-link-plist nil
6071 "Plist with info about the most recently link created with `org-store-link'.")
6073 (defvar org-link-protocols nil
6074 "Link protocols added to Org-mode using `org-add-link-type'.")
6076 (defvar org-store-link-functions nil
6077 "List of functions that are called to create and store a link.
6078 Each function will be called in turn until one returns a non-nil
6079 value. Each function should check if it is responsible for creating
6080 this link (for example by looking at the major mode).
6081 If not, it must exit and return nil.
6082 If yes, it should return a non-nil value after a calling
6083 `org-store-link-props' with a list of properties and values.
6084 Special properties are:
6086 :type The link prefix. like \"http\". This must be given.
6087 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6088 This is obligatory as well.
6089 :description Optional default description for the second pair
6090 of brackets in an Org-mode link. The user can still change
6091 this when inserting this link into an Org-mode buffer.
6093 In addition to these, any additional properties can be specified
6094 and then used in remember templates.")
6096 (defun org-add-link-type (type &optional follow export)
6097 "Add TYPE to the list of `org-link-types'.
6098 Re-compute all regular expressions depending on `org-link-types'
6100 FOLLOW and EXPORT are two functions.
6102 FOLLOW should take the link path as the single argument and do whatever
6103 is necessary to follow the link, for example find a file or display
6104 a mail message.
6106 EXPORT should format the link path for export to one of the export formats.
6107 It should be a function accepting three arguments:
6109 path the path of the link, the text after the prefix (like \"http:\")
6110 desc the description of the link, if any, nil if there was no descripton
6111 format the export format, a symbol like `html' or `latex'.
6113 The function may use the FORMAT information to return different values
6114 depending on the format. The return value will be put literally into
6115 the exported file.
6116 Org-mode has a built-in default for exporting links. If you are happy with
6117 this default, there is no need to define an export function for the link
6118 type. For a simple example of an export function, see `org-bbdb.el'."
6119 (add-to-list 'org-link-types type t)
6120 (org-make-link-regexps)
6121 (if (assoc type org-link-protocols)
6122 (setcdr (assoc type org-link-protocols) (list follow export))
6123 (push (list type follow export) org-link-protocols)))
6126 ;;;###autoload
6127 (defun org-store-link (arg)
6128 "\\<org-mode-map>Store an org-link to the current location.
6129 This link is added to `org-stored-links' and can later be inserted
6130 into an org-buffer with \\[org-insert-link].
6132 For some link types, a prefix arg is interpreted:
6133 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6134 For file links, arg negates `org-context-in-file-links'."
6135 (interactive "P")
6136 (org-load-modules-maybe)
6137 (setq org-store-link-plist nil) ; reset
6138 (let (link cpltxt desc description search txt)
6139 (cond
6141 ((run-hook-with-args-until-success 'org-store-link-functions)
6142 (setq link (plist-get org-store-link-plist :link)
6143 desc (or (plist-get org-store-link-plist :description) link)))
6145 ((eq major-mode 'calendar-mode)
6146 (let ((cd (calendar-cursor-to-date)))
6147 (setq link
6148 (format-time-string
6149 (car org-time-stamp-formats)
6150 (apply 'encode-time
6151 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6152 nil nil nil))))
6153 (org-store-link-props :type "calendar" :date cd)))
6155 ((eq major-mode 'w3-mode)
6156 (setq cpltxt (url-view-url t)
6157 link (org-make-link cpltxt))
6158 (org-store-link-props :type "w3" :url (url-view-url t)))
6160 ((eq major-mode 'w3m-mode)
6161 (setq cpltxt (or w3m-current-title w3m-current-url)
6162 link (org-make-link w3m-current-url))
6163 (org-store-link-props :type "w3m" :url (url-view-url t)))
6165 ((setq search (run-hook-with-args-until-success
6166 'org-create-file-search-functions))
6167 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6168 "::" search))
6169 (setq cpltxt (or description link)))
6171 ((eq major-mode 'image-mode)
6172 (setq cpltxt (concat "file:"
6173 (abbreviate-file-name buffer-file-name))
6174 link (org-make-link cpltxt))
6175 (org-store-link-props :type "image" :file buffer-file-name))
6177 ((eq major-mode 'dired-mode)
6178 ;; link to the file in the current line
6179 (setq cpltxt (concat "file:"
6180 (abbreviate-file-name
6181 (expand-file-name
6182 (dired-get-filename nil t))))
6183 link (org-make-link cpltxt)))
6185 ((and buffer-file-name (org-mode-p))
6186 ;; Just link to current headline
6187 (setq cpltxt (concat "file:"
6188 (abbreviate-file-name buffer-file-name)))
6189 ;; Add a context search string
6190 (when (org-xor org-context-in-file-links arg)
6191 ;; Check if we are on a target
6192 (if (org-in-regexp "<<\\(.*?\\)>>")
6193 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6194 (setq txt (cond
6195 ((org-on-heading-p) nil)
6196 ((org-region-active-p)
6197 (buffer-substring (region-beginning) (region-end)))
6198 (t nil)))
6199 (when (or (null txt) (string-match "\\S-" txt))
6200 (setq cpltxt
6201 (concat cpltxt "::"
6202 (condition-case nil
6203 (org-make-org-heading-search-string txt)
6204 (error "")))
6205 desc "NONE"))))
6206 (if (string-match "::\\'" cpltxt)
6207 (setq cpltxt (substring cpltxt 0 -2)))
6208 (setq link (org-make-link cpltxt)))
6210 ((buffer-file-name (buffer-base-buffer))
6211 ;; Just link to this file here.
6212 (setq cpltxt (concat "file:"
6213 (abbreviate-file-name
6214 (buffer-file-name (buffer-base-buffer)))))
6215 ;; Add a context string
6216 (when (org-xor org-context-in-file-links arg)
6217 (setq txt (if (org-region-active-p)
6218 (buffer-substring (region-beginning) (region-end))
6219 (buffer-substring (point-at-bol) (point-at-eol))))
6220 ;; Only use search option if there is some text.
6221 (when (string-match "\\S-" txt)
6222 (setq cpltxt
6223 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6224 desc "NONE")))
6225 (setq link (org-make-link cpltxt)))
6227 ((interactive-p)
6228 (error "Cannot link to a buffer which is not visiting a file"))
6230 (t (setq link nil)))
6232 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6233 (setq link (or link cpltxt)
6234 desc (or desc cpltxt))
6235 (if (equal desc "NONE") (setq desc nil))
6237 (if (and (interactive-p) link)
6238 (progn
6239 (setq org-stored-links
6240 (cons (list link desc) org-stored-links))
6241 (message "Stored: %s" (or desc link)))
6242 (and link (org-make-link-string link desc)))))
6244 (defun org-store-link-props (&rest plist)
6245 "Store link properties, extract names and addresses."
6246 (let (x adr)
6247 (when (setq x (plist-get plist :from))
6248 (setq adr (mail-extract-address-components x))
6249 (setq plist (plist-put plist :fromname (car adr)))
6250 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6251 (when (setq x (plist-get plist :to))
6252 (setq adr (mail-extract-address-components x))
6253 (setq plist (plist-put plist :toname (car adr)))
6254 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6255 (let ((from (plist-get plist :from))
6256 (to (plist-get plist :to)))
6257 (when (and from to org-from-is-user-regexp)
6258 (setq plist
6259 (plist-put plist :fromto
6260 (if (string-match org-from-is-user-regexp from)
6261 (concat "to %t")
6262 (concat "from %f"))))))
6263 (setq org-store-link-plist plist))
6265 (defun org-add-link-props (&rest plist)
6266 "Add these properties to the link property list."
6267 (let (key value)
6268 (while plist
6269 (setq key (pop plist) value (pop plist))
6270 (setq org-store-link-plist
6271 (plist-put org-store-link-plist key value)))))
6273 (defun org-email-link-description (&optional fmt)
6274 "Return the description part of an email link.
6275 This takes information from `org-store-link-plist' and formats it
6276 according to FMT (default from `org-email-link-description-format')."
6277 (setq fmt (or fmt org-email-link-description-format))
6278 (let* ((p org-store-link-plist)
6279 (to (plist-get p :toaddress))
6280 (from (plist-get p :fromaddress))
6281 (table
6282 (list
6283 (cons "%c" (plist-get p :fromto))
6284 (cons "%F" (plist-get p :from))
6285 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6286 (cons "%T" (plist-get p :to))
6287 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6288 (cons "%s" (plist-get p :subject))
6289 (cons "%m" (plist-get p :message-id)))))
6290 (when (string-match "%c" fmt)
6291 ;; Check if the user wrote this message
6292 (if (and org-from-is-user-regexp from to
6293 (save-match-data (string-match org-from-is-user-regexp from)))
6294 (setq fmt (replace-match "to %t" t t fmt))
6295 (setq fmt (replace-match "from %f" t t fmt))))
6296 (org-replace-escapes fmt table)))
6298 (defun org-make-org-heading-search-string (&optional string heading)
6299 "Make search string for STRING or current headline."
6300 (interactive)
6301 (let ((s (or string (org-get-heading))))
6302 (unless (and string (not heading))
6303 ;; We are using a headline, clean up garbage in there.
6304 (if (string-match org-todo-regexp s)
6305 (setq s (replace-match "" t t s)))
6306 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6307 (setq s (replace-match "" t t s)))
6308 (setq s (org-trim s))
6309 (if (string-match (concat "^\\(" org-quote-string "\\|"
6310 org-comment-string "\\)") s)
6311 (setq s (replace-match "" t t s)))
6312 (while (string-match org-ts-regexp s)
6313 (setq s (replace-match "" t t s))))
6314 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6315 (setq s (replace-match " " t t s)))
6316 (or string (setq s (concat "*" s))) ; Add * for headlines
6317 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6319 (defun org-make-link (&rest strings)
6320 "Concatenate STRINGS."
6321 (apply 'concat strings))
6323 (defun org-make-link-string (link &optional description)
6324 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6325 (unless (string-match "\\S-" link)
6326 (error "Empty link"))
6327 (when (stringp description)
6328 ;; Remove brackets from the description, they are fatal.
6329 (while (string-match "\\[" description)
6330 (setq description (replace-match "{" t t description)))
6331 (while (string-match "\\]" description)
6332 (setq description (replace-match "}" t t description))))
6333 (when (equal (org-link-escape link) description)
6334 ;; No description needed, it is identical
6335 (setq description nil))
6336 (when (and (not description)
6337 (not (equal link (org-link-escape link))))
6338 (setq description (org-extract-attributes link)))
6339 (concat "[[" (org-link-escape link) "]"
6340 (if description (concat "[" description "]") "")
6341 "]"))
6343 (defconst org-link-escape-chars
6344 '((?\ . "%20")
6345 (?\[ . "%5B")
6346 (?\] . "%5D")
6347 (?\340 . "%E0") ; `a
6348 (?\342 . "%E2") ; ^a
6349 (?\347 . "%E7") ; ,c
6350 (?\350 . "%E8") ; `e
6351 (?\351 . "%E9") ; 'e
6352 (?\352 . "%EA") ; ^e
6353 (?\356 . "%EE") ; ^i
6354 (?\364 . "%F4") ; ^o
6355 (?\371 . "%F9") ; `u
6356 (?\373 . "%FB") ; ^u
6357 (?\; . "%3B")
6358 (?? . "%3F")
6359 (?= . "%3D")
6360 (?+ . "%2B")
6362 "Association list of escapes for some characters problematic in links.
6363 This is the list that is used for internal purposes.")
6365 (defconst org-link-escape-chars-browser
6366 '((?\ . "%20")) ; 32 for the SPC char
6367 "Association list of escapes for some characters problematic in links.
6368 This is the list that is used before handing over to the browser.")
6370 (defun org-link-escape (text &optional table)
6371 "Escape characters in TEXT that are problematic for links."
6372 (setq table (or table org-link-escape-chars))
6373 (when text
6374 (let ((re (mapconcat (lambda (x) (regexp-quote
6375 (char-to-string (car x))))
6376 table "\\|")))
6377 (while (string-match re text)
6378 (setq text
6379 (replace-match
6380 (cdr (assoc (string-to-char (match-string 0 text))
6381 table))
6382 t t text)))
6383 text)))
6385 (defun org-link-unescape (text &optional table)
6386 "Reverse the action of `org-link-escape'."
6387 (setq table (or table org-link-escape-chars))
6388 (when text
6389 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6390 table "\\|")))
6391 (while (string-match re text)
6392 (setq text
6393 (replace-match
6394 (char-to-string (car (rassoc (match-string 0 text) table)))
6395 t t text)))
6396 text)))
6398 (defun org-xor (a b)
6399 "Exclusive or."
6400 (if a (not b) b))
6402 (defun org-get-header (header)
6403 "Find a header field in the current buffer."
6404 (save-excursion
6405 (goto-char (point-min))
6406 (let ((case-fold-search t) s)
6407 (cond
6408 ((eq header 'from)
6409 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6410 (setq s (match-string 1)))
6411 (while (string-match "\"" s)
6412 (setq s (replace-match "" t t s)))
6413 (if (string-match "[<(].*" s)
6414 (setq s (replace-match "" t t s))))
6415 ((eq header 'message-id)
6416 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6417 (setq s (match-string 1))))
6418 ((eq header 'subject)
6419 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6420 (setq s (match-string 1)))))
6421 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6422 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6423 s)))
6426 (defun org-fixup-message-id-for-http (s)
6427 "Replace special characters in a message id, so it can be used in an http query."
6428 (while (string-match "<" s)
6429 (setq s (replace-match "%3C" t t s)))
6430 (while (string-match ">" s)
6431 (setq s (replace-match "%3E" t t s)))
6432 (while (string-match "@" s)
6433 (setq s (replace-match "%40" t t s)))
6436 ;;;###autoload
6437 (defun org-insert-link-global ()
6438 "Insert a link like Org-mode does.
6439 This command can be called in any mode to insert a link in Org-mode syntax."
6440 (interactive)
6441 (org-load-modules-maybe)
6442 (org-run-like-in-org-mode 'org-insert-link))
6444 (defun org-insert-link (&optional complete-file link-location)
6445 "Insert a link. At the prompt, enter the link.
6447 Completion can be used to insert any of the link protocol prefixes like
6448 http or ftp in use.
6450 The history can be used to select a link previously stored with
6451 `org-store-link'. When the empty string is entered (i.e. if you just
6452 press RET at the prompt), the link defaults to the most recently
6453 stored link. As SPC triggers completion in the minibuffer, you need to
6454 use M-SPC or C-q SPC to force the insertion of a space character.
6456 You will also be prompted for a description, and if one is given, it will
6457 be displayed in the buffer instead of the link.
6459 If there is already a link at point, this command will allow you to edit link
6460 and description parts.
6462 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6463 be selected using completion. The path to the file will be relative to the
6464 current directory if the file is in the current directory or a subdirectory.
6465 Otherwise, the link will be the absolute path as completed in the minibuffer
6466 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6467 option `org-link-file-path-type'.
6469 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6470 the current directory or below.
6472 With three \\[universal-argument] prefixes, negate the meaning of
6473 `org-keep-stored-link-after-insertion'.
6475 If `org-make-link-description-function' is non-nil, this function will be
6476 called with the link target, and the result will be the default
6477 link description.
6479 If the LINK-LOCATION parameter is non-nil, this value will be
6480 used as the link location instead of reading one interactively."
6481 (interactive "P")
6482 (let* ((wcf (current-window-configuration))
6483 (region (if (org-region-active-p)
6484 (buffer-substring (region-beginning) (region-end))))
6485 (remove (and region (list (region-beginning) (region-end))))
6486 (desc region)
6487 tmphist ; byte-compile incorrectly complains about this
6488 (link link-location)
6489 entry file)
6490 (cond
6491 (link-location) ; specified by arg, just use it.
6492 ((org-in-regexp org-bracket-link-regexp 1)
6493 ;; We do have a link at point, and we are going to edit it.
6494 (setq remove (list (match-beginning 0) (match-end 0)))
6495 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6496 (setq link (read-string "Link: "
6497 (org-link-unescape
6498 (org-match-string-no-properties 1)))))
6499 ((or (org-in-regexp org-angle-link-re)
6500 (org-in-regexp org-plain-link-re))
6501 ;; Convert to bracket link
6502 (setq remove (list (match-beginning 0) (match-end 0))
6503 link (read-string "Link: "
6504 (org-remove-angle-brackets (match-string 0)))))
6505 ((member complete-file '((4) (16)))
6506 ;; Completing read for file names.
6507 (setq file (read-file-name "File: "))
6508 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6509 (pwd1 (file-name-as-directory (abbreviate-file-name
6510 (expand-file-name ".")))))
6511 (cond
6512 ((equal complete-file '(16))
6513 (setq link (org-make-link
6514 "file:"
6515 (abbreviate-file-name (expand-file-name file)))))
6516 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6517 (setq link (org-make-link "file:" (match-string 1 file))))
6518 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6519 (expand-file-name file))
6520 (setq link (org-make-link
6521 "file:" (match-string 1 (expand-file-name file)))))
6522 (t (setq link (org-make-link "file:" file))))))
6524 ;; Read link, with completion for stored links.
6525 (with-output-to-temp-buffer "*Org Links*"
6526 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6527 (when org-stored-links
6528 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6529 (princ (mapconcat
6530 (lambda (x)
6531 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6532 (reverse org-stored-links) "\n"))))
6533 (let ((cw (selected-window)))
6534 (select-window (get-buffer-window "*Org Links*"))
6535 (org-fit-window-to-buffer)
6536 (setq truncate-lines t)
6537 (select-window cw))
6538 ;; Fake a link history, containing the stored links.
6539 (setq tmphist (append (mapcar 'car org-stored-links)
6540 org-insert-link-history))
6541 (unwind-protect
6542 (setq link (org-completing-read
6543 "Link: "
6544 (append
6545 (mapcar (lambda (x) (list (concat (car x) ":")))
6546 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6547 (mapcar (lambda (x) (list (concat x ":")))
6548 org-link-types))
6549 nil nil nil
6550 'tmphist
6551 (or (car (car org-stored-links)))))
6552 (set-window-configuration wcf)
6553 (kill-buffer "*Org Links*"))
6554 (setq entry (assoc link org-stored-links))
6555 (or entry (push link org-insert-link-history))
6556 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6557 (not org-keep-stored-link-after-insertion))
6558 (setq org-stored-links (delq (assoc link org-stored-links)
6559 org-stored-links)))
6560 (setq desc (or desc (nth 1 entry)))))
6562 (if (string-match org-plain-link-re link)
6563 ;; URL-like link, normalize the use of angular brackets.
6564 (setq link (org-make-link (org-remove-angle-brackets link))))
6566 ;; Check if we are linking to the current file with a search option
6567 ;; If yes, simplify the link by using only the search option.
6568 (when (and buffer-file-name
6569 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6570 (let* ((path (match-string 1 link))
6571 (case-fold-search nil)
6572 (search (match-string 2 link)))
6573 (save-match-data
6574 (if (equal (file-truename buffer-file-name) (file-truename path))
6575 ;; We are linking to this same file, with a search option
6576 (setq link search)))))
6578 ;; Check if we can/should use a relative path. If yes, simplify the link
6579 (when (string-match "^file:\\(.*\\)" link)
6580 (let* ((path (match-string 1 link))
6581 (origpath path)
6582 (case-fold-search nil))
6583 (cond
6584 ((or (eq org-link-file-path-type 'absolute)
6585 (equal complete-file '(16)))
6586 (setq path (abbreviate-file-name (expand-file-name path))))
6587 ((eq org-link-file-path-type 'noabbrev)
6588 (setq path (expand-file-name path)))
6589 ((eq org-link-file-path-type 'relative)
6590 (setq path (file-relative-name path)))
6592 (save-match-data
6593 (if (string-match (concat "^" (regexp-quote
6594 (file-name-as-directory
6595 (expand-file-name "."))))
6596 (expand-file-name path))
6597 ;; We are linking a file with relative path name.
6598 (setq path (substring (expand-file-name path)
6599 (match-end 0)))
6600 (setq path (abbreviate-file-name (expand-file-name path)))))))
6601 (setq link (concat "file:" path))
6602 (if (equal desc origpath)
6603 (setq desc path))))
6605 (if org-make-link-description-function
6606 (setq desc (funcall org-make-link-description-function link desc)))
6608 (setq desc (read-string "Description: " desc))
6609 (unless (string-match "\\S-" desc) (setq desc nil))
6610 (if remove (apply 'delete-region remove))
6611 (insert (org-make-link-string link desc))))
6613 (defun org-completing-read (&rest args)
6614 "Completing-read with SPACE being a normal character."
6615 (let ((minibuffer-local-completion-map
6616 (copy-keymap minibuffer-local-completion-map)))
6617 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6618 (apply 'org-ido-completing-read args)))
6620 (defun org-ido-completing-read (&rest args)
6621 "Completing-read using `ido-mode' speedups if available"
6622 (if (and org-completion-use-ido
6623 (fboundp 'ido-completing-read)
6624 (boundp 'ido-mode) ido-mode
6625 (listp (second args)))
6626 (apply 'ido-completing-read (concat (car args)) (cdr args))
6627 (apply 'completing-read args)))
6629 (defun org-extract-attributes (s)
6630 "Extract the attributes cookie from a string and set as text property."
6631 (let (a attr (start 0) key value)
6632 (save-match-data
6633 (when (string-match "{{\\([^}]+\\)}}$" s)
6634 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6635 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6636 (setq key (match-string 1 a) value (match-string 2 a)
6637 start (match-end 0)
6638 attr (plist-put attr (intern key) value))))
6639 (org-add-props s nil 'org-attributes attr))
6642 (defun org-attributes-to-string (plist)
6643 "Format a property list into an HTML attribute list."
6644 (let ((s "") key value)
6645 (while plist
6646 (setq key (pop plist) value (pop plist))
6647 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6650 ;;; Opening/following a link
6652 (defvar org-link-search-failed nil)
6654 (defun org-next-link ()
6655 "Move forward to the next link.
6656 If the link is in hidden text, expose it."
6657 (interactive)
6658 (when (and org-link-search-failed (eq this-command last-command))
6659 (goto-char (point-min))
6660 (message "Link search wrapped back to beginning of buffer"))
6661 (setq org-link-search-failed nil)
6662 (let* ((pos (point))
6663 (ct (org-context))
6664 (a (assoc :link ct)))
6665 (if a (goto-char (nth 2 a)))
6666 (if (re-search-forward org-any-link-re nil t)
6667 (progn
6668 (goto-char (match-beginning 0))
6669 (if (org-invisible-p) (org-show-context)))
6670 (goto-char pos)
6671 (setq org-link-search-failed t)
6672 (error "No further link found"))))
6674 (defun org-previous-link ()
6675 "Move backward to the previous link.
6676 If the link is in hidden text, expose it."
6677 (interactive)
6678 (when (and org-link-search-failed (eq this-command last-command))
6679 (goto-char (point-max))
6680 (message "Link search wrapped back to end of buffer"))
6681 (setq org-link-search-failed nil)
6682 (let* ((pos (point))
6683 (ct (org-context))
6684 (a (assoc :link ct)))
6685 (if a (goto-char (nth 1 a)))
6686 (if (re-search-backward org-any-link-re nil t)
6687 (progn
6688 (goto-char (match-beginning 0))
6689 (if (org-invisible-p) (org-show-context)))
6690 (goto-char pos)
6691 (setq org-link-search-failed t)
6692 (error "No further link found"))))
6694 (defun org-translate-link (s)
6695 "Translate a link string if a translation function has been defined."
6696 (if (and org-link-translation-function
6697 (fboundp org-link-translation-function)
6698 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6699 (progn
6700 (setq s (funcall org-link-translation-function
6701 (match-string 1) (match-string 2)))
6702 (concat (car s) ":" (cdr s)))
6705 (defun org-translate-link-from-planner (type path)
6706 "Translate a link from Emacs Planner syntax so that Org can follow it.
6707 This is still an experimental function, your mileage may vary."
6708 (cond
6709 ((member type '("http" "https" "news" "ftp"))
6710 ;; standard Internet links are the same.
6711 nil)
6712 ((and (equal type "irc") (string-match "^//" path))
6713 ;; Planner has two / at the beginning of an irc link, we have 1.
6714 ;; We should have zero, actually....
6715 (setq path (substring path 1)))
6716 ((and (equal type "lisp") (string-match "^/" path))
6717 ;; Planner has a slash, we do not.
6718 (setq type "elisp" path (substring path 1)))
6719 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6720 ;; A typical message link. Planner has the id after the fina slash,
6721 ;; we separate it with a hash mark
6722 (setq path (concat (match-string 1 path) "#"
6723 (org-remove-angle-brackets (match-string 2 path)))))
6725 (cons type path))
6727 (defun org-find-file-at-mouse (ev)
6728 "Open file link or URL at mouse."
6729 (interactive "e")
6730 (mouse-set-point ev)
6731 (org-open-at-point 'in-emacs))
6733 (defun org-open-at-mouse (ev)
6734 "Open file link or URL at mouse."
6735 (interactive "e")
6736 (mouse-set-point ev)
6737 (if (eq major-mode 'org-agenda-mode)
6738 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6739 (org-open-at-point))
6741 (defvar org-window-config-before-follow-link nil
6742 "The window configuration before following a link.
6743 This is saved in case the need arises to restore it.")
6745 (defvar org-open-link-marker (make-marker)
6746 "Marker pointing to the location where `org-open-at-point; was called.")
6748 ;;;###autoload
6749 (defun org-open-at-point-global ()
6750 "Follow a link like Org-mode does.
6751 This command can be called in any mode to follow a link that has
6752 Org-mode syntax."
6753 (interactive)
6754 (org-run-like-in-org-mode 'org-open-at-point))
6756 ;;;###autoload
6757 (defun org-open-link-from-string (s &optional arg)
6758 "Open a link in the string S, as if it was in Org-mode."
6759 (interactive "sLink: \nP")
6760 (with-temp-buffer
6761 (let ((org-inhibit-startup t))
6762 (org-mode)
6763 (insert s)
6764 (goto-char (point-min))
6765 (org-open-at-point arg))))
6767 (defun org-open-at-point (&optional in-emacs)
6768 "Open link at or after point.
6769 If there is no link at point, this function will search forward up to
6770 the end of the current subtree.
6771 Normally, files will be opened by an appropriate application. If the
6772 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6773 With a double prefix argument, try to open outside of Emacs, in the
6774 application the system uses for this file type."
6775 (interactive "P")
6776 (org-load-modules-maybe)
6777 (move-marker org-open-link-marker (point))
6778 (setq org-window-config-before-follow-link (current-window-configuration))
6779 (org-remove-occur-highlights nil nil t)
6780 (if (org-at-timestamp-p t)
6781 (org-follow-timestamp-link)
6782 (let (type path link line search (pos (point)))
6783 (catch 'match
6784 (save-excursion
6785 (skip-chars-forward "^]\n\r")
6786 (when (org-in-regexp org-bracket-link-regexp)
6787 (setq link (org-extract-attributes
6788 (org-link-unescape (org-match-string-no-properties 1))))
6789 (while (string-match " *\n *" link)
6790 (setq link (replace-match " " t t link)))
6791 (setq link (org-link-expand-abbrev link))
6792 (cond
6793 ((or (file-name-absolute-p link)
6794 (string-match "^\\.\\.?/" link))
6795 (setq type "file" path link))
6796 ((string-match org-link-re-with-space3 link)
6797 (setq type (match-string 1 link) path (match-string 2 link)))
6798 (t (setq type "thisfile" path link)))
6799 (throw 'match t)))
6801 (when (get-text-property (point) 'org-linked-text)
6802 (setq type "thisfile"
6803 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6804 (1+ (point)) (point))
6805 path (buffer-substring
6806 (previous-single-property-change pos 'org-linked-text)
6807 (next-single-property-change pos 'org-linked-text)))
6808 (throw 'match t))
6810 (save-excursion
6811 (when (or (org-in-regexp org-angle-link-re)
6812 (org-in-regexp org-plain-link-re))
6813 (setq type (match-string 1) path (match-string 2))
6814 (throw 'match t)))
6815 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6816 (setq type "tree-match"
6817 path (match-string 1))
6818 (throw 'match t))
6819 (save-excursion
6820 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6821 (setq type "tags"
6822 path (match-string 1))
6823 (while (string-match ":" path)
6824 (setq path (replace-match "+" t t path)))
6825 (throw 'match t))))
6826 (unless path
6827 (error "No link found"))
6828 ;; Remove any trailing spaces in path
6829 (if (string-match " +\\'" path)
6830 (setq path (replace-match "" t t path)))
6831 (if (and org-link-translation-function
6832 (fboundp org-link-translation-function))
6833 ;; Check if we need to translate the link
6834 (let ((tmp (funcall org-link-translation-function type path)))
6835 (setq type (car tmp) path (cdr tmp))))
6837 (cond
6839 ((assoc type org-link-protocols)
6840 (funcall (nth 1 (assoc type org-link-protocols)) path))
6842 ((equal type "mailto")
6843 (let ((cmd (car org-link-mailto-program))
6844 (args (cdr org-link-mailto-program)) args1
6845 (address path) (subject "") a)
6846 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6847 (setq address (match-string 1 path)
6848 subject (org-link-escape (match-string 2 path))))
6849 (while args
6850 (cond
6851 ((not (stringp (car args))) (push (pop args) args1))
6852 (t (setq a (pop args))
6853 (if (string-match "%a" a)
6854 (setq a (replace-match address t t a)))
6855 (if (string-match "%s" a)
6856 (setq a (replace-match subject t t a)))
6857 (push a args1))))
6858 (apply cmd (nreverse args1))))
6860 ((member type '("http" "https" "ftp" "news"))
6861 (browse-url (concat type ":" (org-link-escape
6862 path org-link-escape-chars-browser))))
6864 ((member type '("message"))
6865 (browse-url (concat type ":" path)))
6867 ((string= type "tags")
6868 (org-tags-view in-emacs path))
6869 ((string= type "thisfile")
6870 (if in-emacs
6871 (switch-to-buffer-other-window
6872 (org-get-buffer-for-internal-link (current-buffer)))
6873 (org-mark-ring-push))
6874 (let ((cmd `(org-link-search
6875 ,path
6876 ,(cond ((equal in-emacs '(4)) 'occur)
6877 ((equal in-emacs '(16)) 'org-occur)
6878 (t nil))
6879 ,pos)))
6880 (condition-case nil (eval cmd)
6881 (error (progn (widen) (eval cmd))))))
6883 ((string= type "tree-match")
6884 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6886 ((string= type "file")
6887 (if (string-match "::\\([0-9]+\\)\\'" path)
6888 (setq line (string-to-number (match-string 1 path))
6889 path (substring path 0 (match-beginning 0)))
6890 (if (string-match "::\\(.+\\)\\'" path)
6891 (setq search (match-string 1 path)
6892 path (substring path 0 (match-beginning 0)))))
6893 (if (string-match "[*?{]" (file-name-nondirectory path))
6894 (dired path)
6895 (org-open-file path in-emacs line search)))
6897 ((string= type "news")
6898 (require 'org-gnus)
6899 (org-gnus-follow-link path))
6901 ((string= type "shell")
6902 (let ((cmd path))
6903 (if (or (not org-confirm-shell-link-function)
6904 (funcall org-confirm-shell-link-function
6905 (format "Execute \"%s\" in shell? "
6906 (org-add-props cmd nil
6907 'face 'org-warning))))
6908 (progn
6909 (message "Executing %s" cmd)
6910 (shell-command cmd))
6911 (error "Abort"))))
6913 ((string= type "elisp")
6914 (let ((cmd path))
6915 (if (or (not org-confirm-elisp-link-function)
6916 (funcall org-confirm-elisp-link-function
6917 (format "Execute \"%s\" as elisp? "
6918 (org-add-props cmd nil
6919 'face 'org-warning))))
6920 (message "%s => %s" cmd
6921 (if (equal (string-to-char cmd) ?\()
6922 (eval (read cmd))
6923 (call-interactively (read cmd))))
6924 (error "Abort"))))
6927 (browse-url-at-point)))))
6928 (move-marker org-open-link-marker nil)
6929 (run-hook-with-args 'org-follow-link-hook))
6931 ;;;; Time estimates
6933 (defun org-get-effort (&optional pom)
6934 "Get the effort estimate for the current entry."
6935 (org-entry-get pom org-effort-property))
6937 ;;; File search
6939 (defvar org-create-file-search-functions nil
6940 "List of functions to construct the right search string for a file link.
6941 These functions are called in turn with point at the location to
6942 which the link should point.
6944 A function in the hook should first test if it would like to
6945 handle this file type, for example by checking the major-mode or
6946 the file extension. If it decides not to handle this file, it
6947 should just return nil to give other functions a chance. If it
6948 does handle the file, it must return the search string to be used
6949 when following the link. The search string will be part of the
6950 file link, given after a double colon, and `org-open-at-point'
6951 will automatically search for it. If special measures must be
6952 taken to make the search successful, another function should be
6953 added to the companion hook `org-execute-file-search-functions',
6954 which see.
6956 A function in this hook may also use `setq' to set the variable
6957 `description' to provide a suggestion for the descriptive text to
6958 be used for this link when it gets inserted into an Org-mode
6959 buffer with \\[org-insert-link].")
6961 (defvar org-execute-file-search-functions nil
6962 "List of functions to execute a file search triggered by a link.
6964 Functions added to this hook must accept a single argument, the
6965 search string that was part of the file link, the part after the
6966 double colon. The function must first check if it would like to
6967 handle this search, for example by checking the major-mode or the
6968 file extension. If it decides not to handle this search, it
6969 should just return nil to give other functions a chance. If it
6970 does handle the search, it must return a non-nil value to keep
6971 other functions from trying.
6973 Each function can access the current prefix argument through the
6974 variable `current-prefix-argument'. Note that a single prefix is
6975 used to force opening a link in Emacs, so it may be good to only
6976 use a numeric or double prefix to guide the search function.
6978 In case this is needed, a function in this hook can also restore
6979 the window configuration before `org-open-at-point' was called using:
6981 (set-window-configuration org-window-config-before-follow-link)")
6983 (defun org-link-search (s &optional type avoid-pos)
6984 "Search for a link search option.
6985 If S is surrounded by forward slashes, it is interpreted as a
6986 regular expression. In org-mode files, this will create an `org-occur'
6987 sparse tree. In ordinary files, `occur' will be used to list matches.
6988 If the current buffer is in `dired-mode', grep will be used to search
6989 in all files. If AVOID-POS is given, ignore matches near that position."
6990 (let ((case-fold-search t)
6991 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6992 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6993 (append '(("") (" ") ("\t") ("\n"))
6994 org-emphasis-alist)
6995 "\\|") "\\)"))
6996 (pos (point))
6997 (pre nil) (post nil)
6998 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6999 (cond
7000 ;; First check if there are any special
7001 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7002 ;; Now try the builtin stuff
7003 ((save-excursion
7004 (goto-char (point-min))
7005 (and
7006 (re-search-forward
7007 (concat "<<" (regexp-quote s0) ">>") nil t)
7008 (setq type 'dedicated
7009 pos (match-beginning 0))))
7010 ;; There is an exact target for this
7011 (goto-char pos))
7012 ((string-match "^/\\(.*\\)/$" s)
7013 ;; A regular expression
7014 (cond
7015 ((org-mode-p)
7016 (org-occur (match-string 1 s)))
7017 ;;((eq major-mode 'dired-mode)
7018 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7019 (t (org-do-occur (match-string 1 s)))))
7021 ;; A normal search strings
7022 (when (equal (string-to-char s) ?*)
7023 ;; Anchor on headlines, post may include tags.
7024 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7025 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7026 s (substring s 1)))
7027 (remove-text-properties
7028 0 (length s)
7029 '(face nil mouse-face nil keymap nil fontified nil) s)
7030 ;; Make a series of regular expressions to find a match
7031 (setq words (org-split-string s "[ \n\r\t]+")
7033 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7034 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7035 "\\)" markers)
7036 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7037 re2a (concat "[ \t\r\n]" re2a_)
7038 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7039 re4 (concat "[^a-zA-Z_]" re4_)
7041 re1 (concat pre re2 post)
7042 re3 (concat pre (if pre re4_ re4) post)
7043 re5 (concat pre ".*" re4)
7044 re2 (concat pre re2)
7045 re2a (concat pre (if pre re2a_ re2a))
7046 re4 (concat pre (if pre re4_ re4))
7047 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7048 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7049 re5 "\\)"
7051 (cond
7052 ((eq type 'org-occur) (org-occur reall))
7053 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7054 (t (goto-char (point-min))
7055 (setq type 'fuzzy)
7056 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7057 (org-search-not-self 1 re1 nil t)
7058 (org-search-not-self 1 re2 nil t)
7059 (org-search-not-self 1 re2a nil t)
7060 (org-search-not-self 1 re3 nil t)
7061 (org-search-not-self 1 re4 nil t)
7062 (org-search-not-self 1 re5 nil t)
7064 (goto-char (match-beginning 1))
7065 (goto-char pos)
7066 (error "No match")))))
7068 ;; Normal string-search
7069 (goto-char (point-min))
7070 (if (search-forward s nil t)
7071 (goto-char (match-beginning 0))
7072 (error "No match"))))
7073 (and (org-mode-p) (org-show-context 'link-search))
7074 type))
7076 (defun org-search-not-self (group &rest args)
7077 "Execute `re-search-forward', but only accept matches that do not
7078 enclose the position of `org-open-link-marker'."
7079 (let ((m org-open-link-marker))
7080 (catch 'exit
7081 (while (apply 're-search-forward args)
7082 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7083 (goto-char (match-end group))
7084 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7085 (> (match-beginning 0) (marker-position m))
7086 (< (match-end 0) (marker-position m)))
7087 (save-match-data
7088 (or (not (org-in-regexp
7089 org-bracket-link-analytic-regexp 1))
7090 (not (match-end 4)) ; no description
7091 (and (<= (match-beginning 4) (point))
7092 (>= (match-end 4) (point))))))
7093 (throw 'exit (point))))))))
7095 (defun org-get-buffer-for-internal-link (buffer)
7096 "Return a buffer to be used for displaying the link target of internal links."
7097 (cond
7098 ((not org-display-internal-link-with-indirect-buffer)
7099 buffer)
7100 ((string-match "(Clone)$" (buffer-name buffer))
7101 (message "Buffer is already a clone, not making another one")
7102 ;; we also do not modify visibility in this case
7103 buffer)
7104 (t ; make a new indirect buffer for displaying the link
7105 (let* ((bn (buffer-name buffer))
7106 (ibn (concat bn "(Clone)"))
7107 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7108 (with-current-buffer ib (org-overview))
7109 ib))))
7111 (defun org-do-occur (regexp &optional cleanup)
7112 "Call the Emacs command `occur'.
7113 If CLEANUP is non-nil, remove the printout of the regular expression
7114 in the *Occur* buffer. This is useful if the regex is long and not useful
7115 to read."
7116 (occur regexp)
7117 (when cleanup
7118 (let ((cwin (selected-window)) win beg end)
7119 (when (setq win (get-buffer-window "*Occur*"))
7120 (select-window win))
7121 (goto-char (point-min))
7122 (when (re-search-forward "match[a-z]+" nil t)
7123 (setq beg (match-end 0))
7124 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7125 (setq end (1- (match-beginning 0)))))
7126 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7127 (goto-char (point-min))
7128 (select-window cwin))))
7130 ;;; The mark ring for links jumps
7132 (defvar org-mark-ring nil
7133 "Mark ring for positions before jumps in Org-mode.")
7134 (defvar org-mark-ring-last-goto nil
7135 "Last position in the mark ring used to go back.")
7136 ;; Fill and close the ring
7137 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7138 (loop for i from 1 to org-mark-ring-length do
7139 (push (make-marker) org-mark-ring))
7140 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7141 org-mark-ring)
7143 (defun org-mark-ring-push (&optional pos buffer)
7144 "Put the current position or POS into the mark ring and rotate it."
7145 (interactive)
7146 (setq pos (or pos (point)))
7147 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7148 (move-marker (car org-mark-ring)
7149 (or pos (point))
7150 (or buffer (current-buffer)))
7151 (message "%s"
7152 (substitute-command-keys
7153 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7155 (defun org-mark-ring-goto (&optional n)
7156 "Jump to the previous position in the mark ring.
7157 With prefix arg N, jump back that many stored positions. When
7158 called several times in succession, walk through the entire ring.
7159 Org-mode commands jumping to a different position in the current file,
7160 or to another Org-mode file, automatically push the old position
7161 onto the ring."
7162 (interactive "p")
7163 (let (p m)
7164 (if (eq last-command this-command)
7165 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7166 (setq p org-mark-ring))
7167 (setq org-mark-ring-last-goto p)
7168 (setq m (car p))
7169 (switch-to-buffer (marker-buffer m))
7170 (goto-char m)
7171 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7173 (defun org-remove-angle-brackets (s)
7174 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7175 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7177 (defun org-add-angle-brackets (s)
7178 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7179 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7181 (defun org-remove-double-quotes (s)
7182 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7183 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7186 ;;; Following specific links
7188 (defun org-follow-timestamp-link ()
7189 (cond
7190 ((org-at-date-range-p t)
7191 (let ((org-agenda-start-on-weekday)
7192 (t1 (match-string 1))
7193 (t2 (match-string 2)))
7194 (setq t1 (time-to-days (org-time-string-to-time t1))
7195 t2 (time-to-days (org-time-string-to-time t2)))
7196 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7197 ((org-at-timestamp-p t)
7198 (org-agenda-list nil (time-to-days (org-time-string-to-time
7199 (substring (match-string 1) 0 10)))
7201 (t (error "This should not happen"))))
7204 ;;; Following file links
7205 (defvar org-wait nil)
7206 (defun org-open-file (path &optional in-emacs line search)
7207 "Open the file at PATH.
7208 First, this expands any special file name abbreviations. Then the
7209 configuration variable `org-file-apps' is checked if it contains an
7210 entry for this file type, and if yes, the corresponding command is launched.
7212 If no application is found, Emacs simply visits the file.
7214 With optional prefix argument IN-EMACS, Emacs will visit the file.
7215 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7216 and o use an external application to visit the file.
7218 Optional LINE specifies a line to go to, optional SEARCH a string to
7219 search for. If LINE or SEARCH is given, the file will always be
7220 opened in Emacs.
7221 If the file does not exist, an error is thrown."
7222 (setq in-emacs (or in-emacs line search))
7223 (let* ((file (if (equal path "")
7224 buffer-file-name
7225 (substitute-in-file-name (expand-file-name path))))
7226 (apps (append org-file-apps (org-default-apps)))
7227 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7228 (dirp (if remp nil (file-directory-p file)))
7229 (file (if (and dirp org-open-directory-means-index-dot-org)
7230 (concat (file-name-as-directory file) "index.org")
7231 file))
7232 (a-m-a-p (assq 'auto-mode apps))
7233 (dfile (downcase file))
7234 (old-buffer (current-buffer))
7235 (old-pos (point))
7236 (old-mode major-mode)
7237 ext cmd)
7238 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7239 (setq ext (match-string 1 dfile))
7240 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7241 (setq ext (match-string 1 dfile))))
7242 (cond
7243 ((equal in-emacs '(16))
7244 (setq cmd (cdr (assoc 'system apps))))
7245 (in-emacs (setq cmd 'emacs))
7247 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7248 (and dirp (cdr (assoc 'directory apps)))
7249 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7250 'string-match)
7251 (cdr (assoc ext apps))
7252 (cdr (assoc t apps))))))
7253 (when (eq cmd 'system)
7254 (setq cmd (cdr (assoc 'system apps))))
7255 (when (eq cmd 'default)
7256 (setq cmd (cdr (assoc t apps))))
7257 (when (eq cmd 'mailcap)
7258 (require 'mailcap)
7259 (mailcap-parse-mailcaps)
7260 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7261 (command (mailcap-mime-info mime-type)))
7262 (if (stringp command)
7263 (setq cmd command)
7264 (setq cmd 'emacs))))
7265 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7266 (not (file-exists-p file))
7267 (not org-open-non-existing-files))
7268 (error "No such file: %s" file))
7269 (cond
7270 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7271 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7272 (while (string-match "['\"]%s['\"]" cmd)
7273 (setq cmd (replace-match "%s" t t cmd)))
7274 (while (string-match "%s" cmd)
7275 (setq cmd (replace-match
7276 (save-match-data
7277 (shell-quote-argument
7278 (convert-standard-filename file)))
7279 t t cmd)))
7280 (save-window-excursion
7281 (start-process-shell-command cmd nil cmd)
7282 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7284 ((or (stringp cmd)
7285 (eq cmd 'emacs))
7286 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7287 (widen)
7288 (if line (goto-line line)
7289 (if search (org-link-search search))))
7290 ((consp cmd)
7291 (let ((file (convert-standard-filename file)))
7292 (eval cmd)))
7293 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7294 (and (org-mode-p) (eq old-mode 'org-mode)
7295 (or (not (equal old-buffer (current-buffer)))
7296 (not (equal old-pos (point))))
7297 (org-mark-ring-push old-pos old-buffer))))
7299 (defun org-default-apps ()
7300 "Return the default applications for this operating system."
7301 (cond
7302 ((eq system-type 'darwin)
7303 org-file-apps-defaults-macosx)
7304 ((eq system-type 'windows-nt)
7305 org-file-apps-defaults-windowsnt)
7306 (t org-file-apps-defaults-gnu)))
7308 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7309 "Convert extensions to regular expressions in the cars of LIST.
7310 Also, weed out any non-string entries, because the return value is used
7311 only for regexp matching.
7312 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7313 point to the symbol `emacs', indicating that the file should
7314 be opened in Emacs."
7315 (append
7316 (delq nil
7317 (mapcar (lambda (x)
7318 (if (not (stringp (car x)))
7320 (if (string-match "\\W" (car x))
7322 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7323 list))
7324 (if add-auto-mode
7325 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7327 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7328 (defun org-file-remote-p (file)
7329 "Test whether FILE specifies a location on a remote system.
7330 Return non-nil if the location is indeed remote.
7332 For example, the filename \"/user@host:/foo\" specifies a location
7333 on the system \"/user@host:\"."
7334 (cond ((fboundp 'file-remote-p)
7335 (file-remote-p file))
7336 ((fboundp 'tramp-handle-file-remote-p)
7337 (tramp-handle-file-remote-p file))
7338 ((and (boundp 'ange-ftp-name-format)
7339 (string-match (car ange-ftp-name-format) file))
7341 (t nil)))
7344 ;;;; Refiling
7346 (defun org-get-org-file ()
7347 "Read a filename, with default directory `org-directory'."
7348 (let ((default (or org-default-notes-file remember-data-file)))
7349 (read-file-name (format "File name [%s]: " default)
7350 (file-name-as-directory org-directory)
7351 default)))
7353 (defun org-notes-order-reversed-p ()
7354 "Check if the current file should receive notes in reversed order."
7355 (cond
7356 ((not org-reverse-note-order) nil)
7357 ((eq t org-reverse-note-order) t)
7358 ((not (listp org-reverse-note-order)) nil)
7359 (t (catch 'exit
7360 (let ((all org-reverse-note-order)
7361 entry)
7362 (while (setq entry (pop all))
7363 (if (string-match (car entry) buffer-file-name)
7364 (throw 'exit (cdr entry))))
7365 nil)))))
7367 (defvar org-refile-target-table nil
7368 "The list of refile targets, created by `org-refile'.")
7370 (defvar org-agenda-new-buffers nil
7371 "Buffers created to visit agenda files.")
7373 (defun org-get-refile-targets (&optional default-buffer)
7374 "Produce a table with refile targets."
7375 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7376 targets txt re files f desc descre)
7377 (with-current-buffer (or default-buffer (current-buffer))
7378 (while (setq entry (pop entries))
7379 (setq files (car entry) desc (cdr entry))
7380 (cond
7381 ((null files) (setq files (list (current-buffer))))
7382 ((eq files 'org-agenda-files)
7383 (setq files (org-agenda-files 'unrestricted)))
7384 ((and (symbolp files) (fboundp files))
7385 (setq files (funcall files)))
7386 ((and (symbolp files) (boundp files))
7387 (setq files (symbol-value files))))
7388 (if (stringp files) (setq files (list files)))
7389 (cond
7390 ((eq (car desc) :tag)
7391 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7392 ((eq (car desc) :todo)
7393 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7394 ((eq (car desc) :regexp)
7395 (setq descre (cdr desc)))
7396 ((eq (car desc) :level)
7397 (setq descre (concat "^\\*\\{" (number-to-string
7398 (if org-odd-levels-only
7399 (1- (* 2 (cdr desc)))
7400 (cdr desc)))
7401 "\\}[ \t]")))
7402 ((eq (car desc) :maxlevel)
7403 (setq descre (concat "^\\*\\{1," (number-to-string
7404 (if org-odd-levels-only
7405 (1- (* 2 (cdr desc)))
7406 (cdr desc)))
7407 "\\}[ \t]")))
7408 (t (error "Bad refiling target description %s" desc)))
7409 (while (setq f (pop files))
7410 (save-excursion
7411 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7412 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7413 (save-excursion
7414 (save-restriction
7415 (widen)
7416 (goto-char (point-min))
7417 (while (re-search-forward descre nil t)
7418 (goto-char (point-at-bol))
7419 (when (looking-at org-complex-heading-regexp)
7420 (setq txt (org-link-display-format (match-string 4))
7421 re (concat "^" (regexp-quote
7422 (buffer-substring (match-beginning 1)
7423 (match-end 4)))))
7424 (if (match-end 5) (setq re (concat re "[ \t]+"
7425 (regexp-quote
7426 (match-string 5)))))
7427 (setq re (concat re "[ \t]*$"))
7428 (when org-refile-use-outline-path
7429 (setq txt (mapconcat 'org-protect-slash
7430 (append
7431 (if (eq org-refile-use-outline-path 'file)
7432 (list (file-name-nondirectory
7433 (buffer-file-name (buffer-base-buffer))))
7434 (if (eq org-refile-use-outline-path 'full-file-path)
7435 (list (buffer-file-name (buffer-base-buffer)))))
7436 (org-get-outline-path)
7437 (list txt))
7438 "/")))
7439 (push (list txt f re (point)) targets))
7440 (goto-char (point-at-eol))))))))
7441 (nreverse targets))))
7443 (defun org-protect-slash (s)
7444 (while (string-match "/" s)
7445 (setq s (replace-match "\\" t t s)))
7448 (defun org-get-outline-path ()
7449 "Return the outline path to the current entry, as a list."
7450 (let (rtn)
7451 (save-excursion
7452 (while (org-up-heading-safe)
7453 (when (looking-at org-complex-heading-regexp)
7454 (push (org-match-string-no-properties 4) rtn)))
7455 rtn)))
7457 (defvar org-refile-history nil
7458 "History for refiling operations.")
7460 (defun org-refile (&optional goto default-buffer)
7461 "Move the entry at point to another heading.
7462 The list of target headings is compiled using the information in
7463 `org-refile-targets', which see. This list is created before each use
7464 and will therefore always be up-to-date.
7466 At the target location, the entry is filed as a subitem of the target heading.
7467 Depending on `org-reverse-note-order', the new subitem will either be the
7468 first or the last subitem.
7470 If there is an active region, all entries in that region will be moved.
7471 However, the region must fulfil the requirement that the first heading
7472 is the first one sets the top-level of the moved text - at most siblings
7473 below it are allowed.
7475 With prefix arg GOTO, the command will only visit the target location,
7476 not actually move anything.
7477 With a double prefix `C-u C-u', go to the location where the last refiling
7478 operation has put the subtree."
7479 (interactive "P")
7480 (let* ((cbuf (current-buffer))
7481 (regionp (org-region-active-p))
7482 (region-start (and regionp (region-beginning)))
7483 (region-end (and regionp (region-end)))
7484 (region-length (and regionp (- region-end region-start)))
7485 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7486 pos it nbuf file re level reversed)
7487 (when regionp (goto-char region-start)
7488 (unless (org-kill-is-subtree-p
7489 (buffer-substring region-start region-end))
7490 (error "The region is not a (sequence of) subtree(s)")))
7491 (if (equal goto '(16))
7492 (org-refile-goto-last-stored)
7493 (when (setq it (org-refile-get-location
7494 (if goto "Goto: " "Refile to: ") default-buffer))
7495 (setq file (nth 1 it)
7496 re (nth 2 it)
7497 pos (nth 3 it))
7498 (setq nbuf (or (find-buffer-visiting file)
7499 (find-file-noselect file)))
7500 (if goto
7501 (progn
7502 (switch-to-buffer nbuf)
7503 (goto-char pos)
7504 (org-show-context 'org-goto))
7505 (if regionp
7506 (progn
7507 (kill-new (buffer-substring region-start region-end))
7508 (org-save-markers-in-region region-start region-end))
7509 (org-copy-subtree 1 nil t))
7510 (save-excursion
7511 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7512 (find-file-noselect file))))
7513 (setq reversed (org-notes-order-reversed-p))
7514 (save-excursion
7515 (save-restriction
7516 (widen)
7517 (goto-char pos)
7518 (looking-at outline-regexp)
7519 (setq level (org-get-valid-level (funcall outline-level) 1))
7520 (goto-char
7521 (if reversed
7522 (or (outline-next-heading) (point-max))
7523 (or (save-excursion (outline-get-next-sibling))
7524 (org-end-of-subtree t t)
7525 (point-max))))
7526 (if (not (bolp)) (newline))
7527 (bookmark-set "org-refile-last-stored")
7528 (org-paste-subtree level))))
7529 (if regionp
7530 (delete-region (point) (+ (point) region-length))
7531 (org-cut-subtree))
7532 (setq org-markers-to-move nil)
7533 (message "Refiled to \"%s\"" (car it)))))))
7535 (defun org-refile-goto-last-stored ()
7536 "Go to the location where the last refile was stored."
7537 (interactive)
7538 (bookmark-jump "org-refile-last-stored")
7539 (message "This is the location of the last refile"))
7541 (defun org-refile-get-location (&optional prompt default-buffer)
7542 "Prompt the user for a refile location, using PROMPT."
7543 (let ((org-refile-targets org-refile-targets)
7544 (org-refile-use-outline-path org-refile-use-outline-path))
7545 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7546 (unless org-refile-target-table
7547 (error "No refile targets"))
7548 (let* ((cbuf (current-buffer))
7549 (cfunc (if (and org-refile-use-outline-path
7550 org-outline-path-complete-in-steps)
7551 'org-olpath-completing-read
7552 'org-ido-completing-read))
7553 (extra (if org-refile-use-outline-path "/" ""))
7554 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7555 (fname (and filename (file-truename filename)))
7556 (tbl (mapcar
7557 (lambda (x)
7558 (if (not (equal fname (file-truename (nth 1 x))))
7559 (cons (concat (car x) extra " ("
7560 (file-name-nondirectory (nth 1 x)) ")")
7561 (cdr x))
7562 (cons (concat (car x) extra) (cdr x))))
7563 org-refile-target-table))
7564 (completion-ignore-case t))
7565 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7566 tbl)))
7568 (defun org-olpath-completing-read (prompt collection &rest args)
7569 "Read an outline path like a file name."
7570 (let ((thetable collection))
7571 (apply
7572 'org-ido-completing-read prompt
7573 (lambda (string predicate &optional flag)
7574 (let (rtn r s f (l (length string)))
7575 (cond
7576 ((eq flag nil)
7577 ;; try completion
7578 (try-completion string thetable))
7579 ((eq flag t)
7580 ;; all-completions
7581 (setq rtn (all-completions string thetable predicate))
7582 (mapcar
7583 (lambda (x)
7584 (setq r (substring x l))
7585 (if (string-match " ([^)]*)$" x)
7586 (setq f (match-string 0 x))
7587 (setq f ""))
7588 (if (string-match "/" r)
7589 (concat string (substring r 0 (match-end 0)) f)
7591 rtn))
7592 ((eq flag 'lambda)
7593 ;; exact match?
7594 (assoc string thetable)))
7596 args)))
7598 ;;;; Dynamic blocks
7600 (defun org-find-dblock (name)
7601 "Find the first dynamic block with name NAME in the buffer.
7602 If not found, stay at current position and return nil."
7603 (let (pos)
7604 (save-excursion
7605 (goto-char (point-min))
7606 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7607 nil t)
7608 (match-beginning 0))))
7609 (if pos (goto-char pos))
7610 pos))
7612 (defconst org-dblock-start-re
7613 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7614 "Matches the startline of a dynamic block, with parameters.")
7616 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7617 "Matches the end of a dyhamic block.")
7619 (defun org-create-dblock (plist)
7620 "Create a dynamic block section, with parameters taken from PLIST.
7621 PLIST must containe a :name entry which is used as name of the block."
7622 (unless (bolp) (newline))
7623 (let ((name (plist-get plist :name)))
7624 (insert "#+BEGIN: " name)
7625 (while plist
7626 (if (eq (car plist) :name)
7627 (setq plist (cddr plist))
7628 (insert " " (prin1-to-string (pop plist)))))
7629 (insert "\n\n#+END:\n")
7630 (beginning-of-line -2)))
7632 (defun org-prepare-dblock ()
7633 "Prepare dynamic block for refresh.
7634 This empties the block, puts the cursor at the insert position and returns
7635 the property list including an extra property :name with the block name."
7636 (unless (looking-at org-dblock-start-re)
7637 (error "Not at a dynamic block"))
7638 (let* ((begdel (1+ (match-end 0)))
7639 (name (org-no-properties (match-string 1)))
7640 (params (append (list :name name)
7641 (read (concat "(" (match-string 3) ")")))))
7642 (unless (re-search-forward org-dblock-end-re nil t)
7643 (error "Dynamic block not terminated"))
7644 (setq params
7645 (append params
7646 (list :content (buffer-substring
7647 begdel (match-beginning 0)))))
7648 (delete-region begdel (match-beginning 0))
7649 (goto-char begdel)
7650 (open-line 1)
7651 params))
7653 (defun org-map-dblocks (&optional command)
7654 "Apply COMMAND to all dynamic blocks in the current buffer.
7655 If COMMAND is not given, use `org-update-dblock'."
7656 (let ((cmd (or command 'org-update-dblock))
7657 pos)
7658 (save-excursion
7659 (goto-char (point-min))
7660 (while (re-search-forward org-dblock-start-re nil t)
7661 (goto-char (setq pos (match-beginning 0)))
7662 (condition-case nil
7663 (funcall cmd)
7664 (error (message "Error during update of dynamic block")))
7665 (goto-char pos)
7666 (unless (re-search-forward org-dblock-end-re nil t)
7667 (error "Dynamic block not terminated"))))))
7669 (defun org-dblock-update (&optional arg)
7670 "User command for updating dynamic blocks.
7671 Update the dynamic block at point. With prefix ARG, update all dynamic
7672 blocks in the buffer."
7673 (interactive "P")
7674 (if arg
7675 (org-update-all-dblocks)
7676 (or (looking-at org-dblock-start-re)
7677 (org-beginning-of-dblock))
7678 (org-update-dblock)))
7680 (defun org-update-dblock ()
7681 "Update the dynamic block at point
7682 This means to empty the block, parse for parameters and then call
7683 the correct writing function."
7684 (save-window-excursion
7685 (let* ((pos (point))
7686 (line (org-current-line))
7687 (params (org-prepare-dblock))
7688 (name (plist-get params :name))
7689 (cmd (intern (concat "org-dblock-write:" name))))
7690 (message "Updating dynamic block `%s' at line %d..." name line)
7691 (funcall cmd params)
7692 (message "Updating dynamic block `%s' at line %d...done" name line)
7693 (goto-char pos))))
7695 (defun org-beginning-of-dblock ()
7696 "Find the beginning of the dynamic block at point.
7697 Error if there is no scuh block at point."
7698 (let ((pos (point))
7699 beg)
7700 (end-of-line 1)
7701 (if (and (re-search-backward org-dblock-start-re nil t)
7702 (setq beg (match-beginning 0))
7703 (re-search-forward org-dblock-end-re nil t)
7704 (> (match-end 0) pos))
7705 (goto-char beg)
7706 (goto-char pos)
7707 (error "Not in a dynamic block"))))
7709 (defun org-update-all-dblocks ()
7710 "Update all dynamic blocks in the buffer.
7711 This function can be used in a hook."
7712 (when (org-mode-p)
7713 (org-map-dblocks 'org-update-dblock)))
7716 ;;;; Completion
7718 (defconst org-additional-option-like-keywords
7719 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7720 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7721 "BEGIN_EXAMPLE" "END_EXAMPLE"
7722 "BEGIN_QUOTE" "END_QUOTE"
7723 "BEGIN_VERSE" "END_VERSE"
7724 "BEGIN_SRC" "END_SRC"))
7726 (defcustom org-structure-template-alist
7728 ("s" "#+begin_src ?\n\n#+end_src"
7729 "<src lang=\"?\">\n\n</src>")
7730 ("e" "#+begin_example\n?\n#+end_example"
7731 "<example>\n?\n</example>")
7732 ("q" "#+begin_quote\n?\n#+end_quote"
7733 "<quote>\n?\n</quote>")
7734 ("v" "#+begin_verse\n?\n#+end_verse"
7735 "<verse>\n?\n/verse>")
7736 ("l" "#+begin_latex\n?\n#+end_latex"
7737 "<literal style=\"latex\">\n?\n</literal>")
7738 ("L" "#+latex: "
7739 "<literal style=\"latex\">?</literal>")
7740 ("h" "#+begin_html\n?\n#+end_html"
7741 "<literal style=\"html\">\n?\n</literal>")
7742 ("H" "#+html: "
7743 "<literal style=\"html\">?</literal>")
7744 ("a" "#+begin_ascii\n?\n#+end_ascii")
7745 ("A" "#+ascii: ")
7746 ("i" "#+include %file ?"
7747 "<include file=%file markup=\"?\">")
7749 "Structure completion elements.
7750 This is a list of abbreviation keys and values. The value gets inserted
7751 it you type @samp{.} followed by the key and then the completion key,
7752 usually `M-TAB'. %file will be replaced by a file name after prompting
7753 for the file uning completion.
7754 There are two templates for each key, the first uses the original Org syntax,
7755 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7756 the default when the /org-mtags.el/ module has been loaded. See also the
7757 variable `org-mtags-prefer-muse-templates'.
7758 This is an experimental feature, it is undecided if it is going to stay in."
7759 :group 'org-completion
7760 :type '(repeat
7761 (string :tag "Key")
7762 (string :tag "Template")
7763 (string :tag "Muse Template")))
7765 (defun org-try-structure-completion ()
7766 "Try to complete a structure template before point.
7767 This looks for strings like \"<e\" on an otherwise empty line and
7768 expands them."
7769 (let ((l (buffer-substring (point-at-bol) (point)))
7771 (when (and (looking-at "[ \t]*$")
7772 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7773 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7774 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7775 (match-beginning 1)) a)
7776 t)))
7778 (defun org-complete-expand-structure-template (start cell)
7779 "Expand a structure template."
7780 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7781 (rpl (nth (if musep 2 1) cell)))
7782 (delete-region start (point))
7783 (when (string-match "\\`#\\+" rpl)
7784 (cond
7785 ((bolp))
7786 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7787 (delete-region (point-at-bol) (point)))
7788 (t (newline))))
7789 (setq start (point))
7790 (if (string-match "%file" rpl)
7791 (setq rpl (replace-match
7792 (concat
7793 "\""
7794 (save-match-data
7795 (abbreviate-file-name (read-file-name "Include file: ")))
7796 "\"")
7797 t t rpl)))
7798 (insert rpl)
7799 (if (re-search-backward "\\?" start t) (delete-char 1))))
7802 (defun org-complete (&optional arg)
7803 "Perform completion on word at point.
7804 At the beginning of a headline, this completes TODO keywords as given in
7805 `org-todo-keywords'.
7806 If the current word is preceded by a backslash, completes the TeX symbols
7807 that are supported for HTML support.
7808 If the current word is preceded by \"#+\", completes special words for
7809 setting file options.
7810 In the line after \"#+STARTUP:, complete valid keywords.\"
7811 At all other locations, this simply calls the value of
7812 `org-completion-fallback-command'."
7813 (interactive "P")
7814 (org-without-partial-completion
7815 (catch 'exit
7816 (let* ((a nil)
7817 (end (point))
7818 (beg1 (save-excursion
7819 (skip-chars-backward (org-re "[:alnum:]_@"))
7820 (point)))
7821 (beg (save-excursion
7822 (skip-chars-backward "a-zA-Z0-9_:$")
7823 (point)))
7824 (confirm (lambda (x) (stringp (car x))))
7825 (searchhead (equal (char-before beg) ?*))
7826 (struct
7827 (when (and (member (char-before beg1) '(?. ?<))
7828 (setq a (assoc (buffer-substring beg1 (point))
7829 org-structure-template-alist)))
7830 (org-complete-expand-structure-template (1- beg1) a)
7831 (throw 'exit t)))
7832 (tag (and (equal (char-before beg1) ?:)
7833 (equal (char-after (point-at-bol)) ?*)))
7834 (prop (and (equal (char-before beg1) ?:)
7835 (not (equal (char-after (point-at-bol)) ?*))))
7836 (texp (equal (char-before beg) ?\\))
7837 (link (equal (char-before beg) ?\[))
7838 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7839 beg)
7840 "#+"))
7841 (startup (string-match "^#\\+STARTUP:.*"
7842 (buffer-substring (point-at-bol) (point))))
7843 (completion-ignore-case opt)
7844 (type nil)
7845 (tbl nil)
7846 (table (cond
7847 (opt
7848 (setq type :opt)
7849 (require 'org-exp)
7850 (append
7851 (mapcar
7852 (lambda (x)
7853 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7854 (cons (match-string 2 x) (match-string 1 x)))
7855 (org-split-string (org-get-current-options) "\n"))
7856 (mapcar 'list org-additional-option-like-keywords)))
7857 (startup
7858 (setq type :startup)
7859 org-startup-options)
7860 (link (append org-link-abbrev-alist-local
7861 org-link-abbrev-alist))
7862 (texp
7863 (setq type :tex)
7864 org-html-entities)
7865 ((string-match "\\`\\*+[ \t]+\\'"
7866 (buffer-substring (point-at-bol) beg))
7867 (setq type :todo)
7868 (mapcar 'list org-todo-keywords-1))
7869 (searchhead
7870 (setq type :searchhead)
7871 (save-excursion
7872 (goto-char (point-min))
7873 (while (re-search-forward org-todo-line-regexp nil t)
7874 (push (list
7875 (org-make-org-heading-search-string
7876 (match-string 3) t))
7877 tbl)))
7878 tbl)
7879 (tag (setq type :tag beg beg1)
7880 (or org-tag-alist (org-get-buffer-tags)))
7881 (prop (setq type :prop beg beg1)
7882 (mapcar 'list (org-buffer-property-keys nil t t)))
7883 (t (progn
7884 (call-interactively org-completion-fallback-command)
7885 (throw 'exit nil)))))
7886 (pattern (buffer-substring-no-properties beg end))
7887 (completion (try-completion pattern table confirm)))
7888 (cond ((eq completion t)
7889 (if (not (assoc (upcase pattern) table))
7890 (message "Already complete")
7891 (if (and (equal type :opt)
7892 (not (member (car (assoc (upcase pattern) table))
7893 org-additional-option-like-keywords)))
7894 (insert (substring (cdr (assoc (upcase pattern) table))
7895 (length pattern)))
7896 (if (memq type '(:tag :prop)) (insert ":")))))
7897 ((null completion)
7898 (message "Can't find completion for \"%s\"" pattern)
7899 (ding))
7900 ((not (string= pattern completion))
7901 (delete-region beg end)
7902 (if (string-match " +$" completion)
7903 (setq completion (replace-match "" t t completion)))
7904 (insert completion)
7905 (if (get-buffer-window "*Completions*")
7906 (delete-window (get-buffer-window "*Completions*")))
7907 (if (assoc completion table)
7908 (if (eq type :todo) (insert " ")
7909 (if (memq type '(:tag :prop)) (insert ":"))))
7910 (if (and (equal type :opt) (assoc completion table))
7911 (message "%s" (substitute-command-keys
7912 "Press \\[org-complete] again to insert example settings"))))
7914 (message "Making completion list...")
7915 (let ((list (sort (all-completions pattern table confirm)
7916 'string<)))
7917 (with-output-to-temp-buffer "*Completions*"
7918 (condition-case nil
7919 ;; Protection needed for XEmacs and emacs 21
7920 (display-completion-list list pattern)
7921 (error (display-completion-list list)))))
7922 (message "Making completion list...%s" "done")))))))
7924 ;;;; TODO, DEADLINE, Comments
7926 (defun org-toggle-comment ()
7927 "Change the COMMENT state of an entry."
7928 (interactive)
7929 (save-excursion
7930 (org-back-to-heading)
7931 (let (case-fold-search)
7932 (if (looking-at (concat outline-regexp
7933 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7934 (replace-match "" t t nil 1)
7935 (if (looking-at outline-regexp)
7936 (progn
7937 (goto-char (match-end 0))
7938 (insert org-comment-string " ")))))))
7940 (defvar org-last-todo-state-is-todo nil
7941 "This is non-nil when the last TODO state change led to a TODO state.
7942 If the last change removed the TODO tag or switched to DONE, then
7943 this is nil.")
7945 (defvar org-setting-tags nil) ; dynamically skiped
7947 (defun org-parse-local-options (string var)
7948 "Parse STRING for startup setting relevant for variable VAR."
7949 (let ((rtn (symbol-value var))
7950 e opts)
7951 (save-match-data
7952 (if (or (not string) (not (string-match "\\S-" string)))
7954 (setq opts (delq nil (mapcar (lambda (x)
7955 (setq e (assoc x org-startup-options))
7956 (if (eq (nth 1 e) var) e nil))
7957 (org-split-string string "[ \t]+"))))
7958 (if (not opts)
7960 (setq rtn nil)
7961 (while (setq e (pop opts))
7962 (if (not (nth 3 e))
7963 (setq rtn (nth 2 e))
7964 (if (not (listp rtn)) (setq rtn nil))
7965 (push (nth 2 e) rtn)))
7966 rtn)))))
7968 (defvar org-blocker-hook nil
7969 "Hook for functions that are allowed to block a state change.
7971 Each function gets as its single argument a property list, see
7972 `org-trigger-hook' for more information about this list.
7974 If any of the functions in this hook returns nil, the state change
7975 is blocked.")
7977 (defvar org-trigger-hook nil
7978 "Hook for functions that are triggered by a state change.
7980 Each function gets as its single argument a property list with at least
7981 the following elements:
7983 (:type type-of-change :position pos-at-entry-start
7984 :from old-state :to new-state)
7986 Depending on the type, more properties may be present.
7988 This mechanism is currently implemented for:
7990 TODO state changes
7991 ------------------
7992 :type todo-state-change
7993 :from previous state (keyword as a string), or nil
7994 :to new state (keyword as a string), or nil")
7996 (defvar org-agenda-headline-snapshot-before-repeat)
7997 (defun org-todo (&optional arg)
7998 "Change the TODO state of an item.
7999 The state of an item is given by a keyword at the start of the heading,
8000 like
8001 *** TODO Write paper
8002 *** DONE Call mom
8004 The different keywords are specified in the variable `org-todo-keywords'.
8005 By default the available states are \"TODO\" and \"DONE\".
8006 So for this example: when the item starts with TODO, it is changed to DONE.
8007 When it starts with DONE, the DONE is removed. And when neither TODO nor
8008 DONE are present, add TODO at the beginning of the heading.
8010 With C-u prefix arg, use completion to determine the new state.
8011 With numeric prefix arg, switch to that state.
8013 For calling through lisp, arg is also interpreted in the following way:
8014 'none -> empty state
8015 \"\"(empty string) -> switch to empty state
8016 'done -> switch to DONE
8017 'nextset -> switch to the next set of keywords
8018 'previousset -> switch to the previous set of keywords
8019 \"WAITING\" -> switch to the specified keyword, but only if it
8020 really is a member of `org-todo-keywords'."
8021 (interactive "P")
8022 (save-excursion
8023 (catch 'exit
8024 (org-back-to-heading)
8025 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8026 (or (looking-at (concat " +" org-todo-regexp " *"))
8027 (looking-at " *"))
8028 (let* ((match-data (match-data))
8029 (startpos (point-at-bol))
8030 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8031 (org-log-done org-log-done)
8032 (org-log-repeat org-log-repeat)
8033 (org-todo-log-states org-todo-log-states)
8034 (this (match-string 1))
8035 (hl-pos (match-beginning 0))
8036 (head (org-get-todo-sequence-head this))
8037 (ass (assoc head org-todo-kwd-alist))
8038 (interpret (nth 1 ass))
8039 (done-word (nth 3 ass))
8040 (final-done-word (nth 4 ass))
8041 (last-state (or this ""))
8042 (completion-ignore-case t)
8043 (member (member this org-todo-keywords-1))
8044 (tail (cdr member))
8045 (state (cond
8046 ((and org-todo-key-trigger
8047 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8048 (and (not arg) org-use-fast-todo-selection
8049 (not (eq org-use-fast-todo-selection 'prefix)))))
8050 ;; Use fast selection
8051 (org-fast-todo-selection))
8052 ((and (equal arg '(4))
8053 (or (not org-use-fast-todo-selection)
8054 (not org-todo-key-trigger)))
8055 ;; Read a state with completion
8056 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8057 org-todo-keywords-1)
8058 nil t))
8059 ((eq arg 'right)
8060 (if this
8061 (if tail (car tail) nil)
8062 (car org-todo-keywords-1)))
8063 ((eq arg 'left)
8064 (if (equal member org-todo-keywords-1)
8066 (if this
8067 (nth (- (length org-todo-keywords-1) (length tail) 2)
8068 org-todo-keywords-1)
8069 (org-last org-todo-keywords-1))))
8070 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8071 (setq arg nil))) ; hack to fall back to cycling
8072 (arg
8073 ;; user or caller requests a specific state
8074 (cond
8075 ((equal arg "") nil)
8076 ((eq arg 'none) nil)
8077 ((eq arg 'done) (or done-word (car org-done-keywords)))
8078 ((eq arg 'nextset)
8079 (or (car (cdr (member head org-todo-heads)))
8080 (car org-todo-heads)))
8081 ((eq arg 'previousset)
8082 (let ((org-todo-heads (reverse org-todo-heads)))
8083 (or (car (cdr (member head org-todo-heads)))
8084 (car org-todo-heads))))
8085 ((car (member arg org-todo-keywords-1)))
8086 ((nth (1- (prefix-numeric-value arg))
8087 org-todo-keywords-1))))
8088 ((null member) (or head (car org-todo-keywords-1)))
8089 ((equal this final-done-word) nil) ;; -> make empty
8090 ((null tail) nil) ;; -> first entry
8091 ((eq interpret 'sequence)
8092 (car tail))
8093 ((memq interpret '(type priority))
8094 (if (eq this-command last-command)
8095 (car tail)
8096 (if (> (length tail) 0)
8097 (or done-word (car org-done-keywords))
8098 nil)))
8099 (t nil)))
8100 (next (if state (concat " " state " ") " "))
8101 (change-plist (list :type 'todo-state-change :from this :to state
8102 :position startpos))
8103 dolog now-done-p)
8104 (when org-blocker-hook
8105 (unless (save-excursion
8106 (save-match-data
8107 (run-hook-with-args-until-failure
8108 'org-blocker-hook change-plist)))
8109 (if (interactive-p)
8110 (error "TODO state change from %s to %s blocked" this state)
8111 ;; fail silently
8112 (message "TODO state change from %s to %s blocked" this state)
8113 (throw 'exit nil))))
8114 (store-match-data match-data)
8115 (replace-match next t t)
8116 (unless (pos-visible-in-window-p hl-pos)
8117 (message "TODO state changed to %s" (org-trim next)))
8118 (unless head
8119 (setq head (org-get-todo-sequence-head state)
8120 ass (assoc head org-todo-kwd-alist)
8121 interpret (nth 1 ass)
8122 done-word (nth 3 ass)
8123 final-done-word (nth 4 ass)))
8124 (when (memq arg '(nextset previousset))
8125 (message "Keyword-Set %d/%d: %s"
8126 (- (length org-todo-sets) -1
8127 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8128 (length org-todo-sets)
8129 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8130 (setq org-last-todo-state-is-todo
8131 (not (member state org-done-keywords)))
8132 (setq now-done-p (and (member state org-done-keywords)
8133 (not (member this org-done-keywords))))
8134 (and logging (org-local-logging logging))
8135 (when (and (or org-todo-log-states org-log-done)
8136 (not (memq arg '(nextset previousset))))
8137 ;; we need to look at recording a time and note
8138 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8139 (nth 2 (assoc this org-todo-log-states))))
8140 (when (and state
8141 (member state org-not-done-keywords)
8142 (not (member this org-not-done-keywords)))
8143 ;; This is now a todo state and was not one before
8144 ;; If there was a CLOSED time stamp, get rid of it.
8145 (org-add-planning-info nil nil 'closed))
8146 (when (and now-done-p org-log-done)
8147 ;; It is now done, and it was not done before
8148 (org-add-planning-info 'closed (org-current-time))
8149 (if (and (not dolog) (eq 'note org-log-done))
8150 (org-add-log-setup 'done state 'findpos 'note)))
8151 (when (and state dolog)
8152 ;; This is a non-nil state, and we need to log it
8153 (org-add-log-setup 'state state 'findpos dolog)))
8154 ;; Fixup tag positioning
8155 (org-todo-trigger-tag-changes state)
8156 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8157 (when org-provide-todo-statistics
8158 (org-update-parent-todo-statistics))
8159 (run-hooks 'org-after-todo-state-change-hook)
8160 (if (and arg (not (member state org-done-keywords)))
8161 (setq head (org-get-todo-sequence-head state)))
8162 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8163 ;; Do we need to trigger a repeat?
8164 (when now-done-p
8165 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8166 ;; This is for the agenda, take a snapshot of the headline.
8167 (save-match-data
8168 (setq org-agenda-headline-snapshot-before-repeat
8169 (org-get-heading))))
8170 (org-auto-repeat-maybe state))
8171 ;; Fixup cursor location if close to the keyword
8172 (if (and (outline-on-heading-p)
8173 (not (bolp))
8174 (save-excursion (beginning-of-line 1)
8175 (looking-at org-todo-line-regexp))
8176 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8177 (progn
8178 (goto-char (or (match-end 2) (match-end 1)))
8179 (just-one-space)))
8180 (when org-trigger-hook
8181 (save-excursion
8182 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8184 (defun org-update-parent-todo-statistics ()
8185 "Update any statistics cookie in the parent of the current headline."
8186 (interactive)
8187 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8188 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8189 (catch 'exit
8190 (save-excursion
8191 (setq level (org-up-heading-safe))
8192 (unless (and level
8193 (re-search-forward box-re (point-at-eol) t))
8194 (throw 'exit nil))
8195 (setq is-percent (match-end 2))
8196 (save-match-data
8197 (unless (outline-next-heading) (throw 'exit nil))
8198 (while (looking-at org-todo-line-regexp)
8199 (setq kwd (match-string 2))
8200 (and kwd (setq cnt-all (1+ cnt-all)))
8201 (and (member kwd org-done-keywords)
8202 (setq cnt-done (1+ cnt-done)))
8203 (condition-case nil
8204 (org-forward-same-level 1)
8205 (error (end-of-line 1)))))
8206 (replace-match
8207 (if is-percent
8208 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8209 (format "[%d/%d]" cnt-done cnt-all)))
8210 (run-hook-with-args 'org-after-todo-statistics-hook
8211 cnt-done (- cnt-all cnt-done))))))
8213 (defvar org-after-todo-statistics-hook nil
8214 "Hook that is called after a TODO statistics cookie has been updated.
8215 Each function is called with two arguments: the number of not-done entries
8216 and the number of done entries.
8218 For example, the following function, when added to this hook, will switch
8219 an entry to DONE when all children are done, and back to TODO when new
8220 entries are set to a TODO status. Note that this hook is only called
8221 when there is a statistics cookie in the headline!
8223 (defun org-summary-todo (n-done n-not-done)
8224 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8225 (let (org-log-done org-log-states) ; turn off logging
8226 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8229 (defun org-todo-trigger-tag-changes (state)
8230 "Apply the changes defined in `org-todo-state-tags-triggers'."
8231 (let ((l org-todo-state-tags-triggers)
8232 changes)
8233 (when (or (not state) (equal state ""))
8234 (setq changes (append changes (cdr (assoc "" l)))))
8235 (when (and (stringp state) (> (length state) 0))
8236 (setq changes (append changes (cdr (assoc state l)))))
8237 (when (member state org-not-done-keywords)
8238 (setq changes (append changes (cdr (assoc 'todo l)))))
8239 (when (member state org-done-keywords)
8240 (setq changes (append changes (cdr (assoc 'done l)))))
8241 (dolist (c changes)
8242 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8244 (defun org-local-logging (value)
8245 "Get logging settings from a property VALUE."
8246 (let* (words w a)
8247 ;; directly set the variables, they are already local.
8248 (setq org-log-done nil
8249 org-log-repeat nil
8250 org-todo-log-states nil)
8251 (setq words (org-split-string value))
8252 (while (setq w (pop words))
8253 (cond
8254 ((setq a (assoc w org-startup-options))
8255 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8256 (set (nth 1 a) (nth 2 a))))
8257 ((setq a (org-extract-log-state-settings w))
8258 (and (member (car a) org-todo-keywords-1)
8259 (push a org-todo-log-states)))))))
8261 (defun org-get-todo-sequence-head (kwd)
8262 "Return the head of the TODO sequence to which KWD belongs.
8263 If KWD is not set, check if there is a text property remembering the
8264 right sequence."
8265 (let (p)
8266 (cond
8267 ((not kwd)
8268 (or (get-text-property (point-at-bol) 'org-todo-head)
8269 (progn
8270 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8271 nil (point-at-eol)))
8272 (get-text-property p 'org-todo-head))))
8273 ((not (member kwd org-todo-keywords-1))
8274 (car org-todo-keywords-1))
8275 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8277 (defun org-fast-todo-selection ()
8278 "Fast TODO keyword selection with single keys.
8279 Returns the new TODO keyword, or nil if no state change should occur."
8280 (let* ((fulltable org-todo-key-alist)
8281 (done-keywords org-done-keywords) ;; needed for the faces.
8282 (maxlen (apply 'max (mapcar
8283 (lambda (x)
8284 (if (stringp (car x)) (string-width (car x)) 0))
8285 fulltable)))
8286 (expert nil)
8287 (fwidth (+ maxlen 3 1 3))
8288 (ncol (/ (- (window-width) 4) fwidth))
8289 tg cnt e c tbl
8290 groups ingroup)
8291 (save-window-excursion
8292 (if expert
8293 (set-buffer (get-buffer-create " *Org todo*"))
8294 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8295 (erase-buffer)
8296 (org-set-local 'org-done-keywords done-keywords)
8297 (setq tbl fulltable cnt 0)
8298 (while (setq e (pop tbl))
8299 (cond
8300 ((equal e '(:startgroup))
8301 (push '() groups) (setq ingroup t)
8302 (when (not (= cnt 0))
8303 (setq cnt 0)
8304 (insert "\n"))
8305 (insert "{ "))
8306 ((equal e '(:endgroup))
8307 (setq ingroup nil cnt 0)
8308 (insert "}\n"))
8310 (setq tg (car e) c (cdr e))
8311 (if ingroup (push tg (car groups)))
8312 (setq tg (org-add-props tg nil 'face
8313 (org-get-todo-face tg)))
8314 (if (and (= cnt 0) (not ingroup)) (insert " "))
8315 (insert "[" c "] " tg (make-string
8316 (- fwidth 4 (length tg)) ?\ ))
8317 (when (= (setq cnt (1+ cnt)) ncol)
8318 (insert "\n")
8319 (if ingroup (insert " "))
8320 (setq cnt 0)))))
8321 (insert "\n")
8322 (goto-char (point-min))
8323 (if (not expert) (org-fit-window-to-buffer))
8324 (message "[a-z..]:Set [SPC]:clear")
8325 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8326 (cond
8327 ((or (= c ?\C-g)
8328 (and (= c ?q) (not (rassoc c fulltable))))
8329 (setq quit-flag t))
8330 ((= c ?\ ) nil)
8331 ((setq e (rassoc c fulltable) tg (car e))
8333 (t (setq quit-flag t))))))
8335 (defun org-entry-is-todo-p ()
8336 (member (org-get-todo-state) org-not-done-keywords))
8338 (defun org-entry-is-done-p ()
8339 (member (org-get-todo-state) org-done-keywords))
8341 (defun org-get-todo-state ()
8342 (save-excursion
8343 (org-back-to-heading t)
8344 (and (looking-at org-todo-line-regexp)
8345 (match-end 2)
8346 (match-string 2))))
8348 (defun org-at-date-range-p (&optional inactive-ok)
8349 "Is the cursor inside a date range?"
8350 (interactive)
8351 (save-excursion
8352 (catch 'exit
8353 (let ((pos (point)))
8354 (skip-chars-backward "^[<\r\n")
8355 (skip-chars-backward "<[")
8356 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8357 (>= (match-end 0) pos)
8358 (throw 'exit t))
8359 (skip-chars-backward "^<[\r\n")
8360 (skip-chars-backward "<[")
8361 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8362 (>= (match-end 0) pos)
8363 (throw 'exit t)))
8364 nil)))
8366 (defun org-get-repeat ()
8367 "Check if there is a deadline/schedule with repeater in this entry."
8368 (save-match-data
8369 (save-excursion
8370 (org-back-to-heading t)
8371 (if (re-search-forward
8372 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8373 (match-string 1)))))
8375 (defvar org-last-changed-timestamp)
8376 (defvar org-last-inserted-timestamp)
8377 (defvar org-log-post-message)
8378 (defvar org-log-note-purpose)
8379 (defvar org-log-note-how)
8380 (defvar org-log-note-extra)
8381 (defun org-auto-repeat-maybe (done-word)
8382 "Check if the current headline contains a repeated deadline/schedule.
8383 If yes, set TODO state back to what it was and change the base date
8384 of repeating deadline/scheduled time stamps to new date.
8385 This function is run automatically after each state change to a DONE state."
8386 ;; last-state is dynamically scoped into this function
8387 (let* ((repeat (org-get-repeat))
8388 (aa (assoc last-state org-todo-kwd-alist))
8389 (interpret (nth 1 aa))
8390 (head (nth 2 aa))
8391 (whata '(("d" . day) ("m" . month) ("y" . year)))
8392 (msg "Entry repeats: ")
8393 (org-log-done nil)
8394 (org-todo-log-states nil)
8395 (nshiftmax 10) (nshift 0)
8396 re type n what ts mb0 time)
8397 (when repeat
8398 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8399 (org-todo (if (eq interpret 'type) last-state head))
8400 (when org-log-repeat
8401 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8402 (memq 'org-add-log-note post-command-hook))
8403 ;; OK, we are already setup for some record
8404 (if (eq org-log-repeat 'note)
8405 ;; make sure we take a note, not only a time stamp
8406 (setq org-log-note-how 'note))
8407 ;; Set up for taking a record
8408 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8409 'findpos org-log-repeat)))
8410 (org-back-to-heading t)
8411 (org-add-planning-info nil nil 'closed)
8412 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8413 org-deadline-time-regexp "\\)\\|\\("
8414 org-ts-regexp "\\)"))
8415 (while (re-search-forward
8416 re (save-excursion (outline-next-heading) (point)) t)
8417 (setq type (if (match-end 1) org-scheduled-string
8418 (if (match-end 3) org-deadline-string "Plain:"))
8419 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8420 mb0 (match-beginning 0))
8421 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8422 (setq n (string-to-number (match-string 2 ts))
8423 what (match-string 3 ts))
8424 (if (equal what "w") (setq n (* n 7) what "d"))
8425 ;; Preparation, see if we need to modify the start date for the change
8426 (when (match-end 1)
8427 (setq time (save-match-data (org-time-string-to-time ts)))
8428 (cond
8429 ((equal (match-string 1 ts) ".")
8430 ;; Shift starting date to today
8431 (org-timestamp-change
8432 (- (time-to-days (current-time)) (time-to-days time))
8433 'day))
8434 ((equal (match-string 1 ts) "+")
8435 (while (or (= nshift 0)
8436 (<= (time-to-days time) (time-to-days (current-time))))
8437 (when (= (incf nshift) nshiftmax)
8438 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8439 (error "Abort")))
8440 (org-timestamp-change n (cdr (assoc what whata)))
8441 (org-at-timestamp-p t)
8442 (setq ts (match-string 1))
8443 (setq time (save-match-data (org-time-string-to-time ts))))
8444 (org-timestamp-change (- n) (cdr (assoc what whata)))
8445 ;; rematch, so that we have everything in place for the real shift
8446 (org-at-timestamp-p t)
8447 (setq ts (match-string 1))
8448 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8449 (org-timestamp-change n (cdr (assoc what whata)))
8450 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8451 (setq org-log-post-message msg)
8452 (message "%s" msg))))
8454 (defun org-show-todo-tree (arg)
8455 "Make a compact tree which shows all headlines marked with TODO.
8456 The tree will show the lines where the regexp matches, and all higher
8457 headlines above the match.
8458 With a \\[universal-argument] prefix, also show the DONE entries.
8459 With a numeric prefix N, construct a sparse tree for the Nth element
8460 of `org-todo-keywords-1'."
8461 (interactive "P")
8462 (let ((case-fold-search nil)
8463 (kwd-re
8464 (cond ((null arg) org-not-done-regexp)
8465 ((equal arg '(4))
8466 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8467 (mapcar 'list org-todo-keywords-1))))
8468 (concat "\\("
8469 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8470 "\\)\\>")))
8471 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8472 (regexp-quote (nth (1- (prefix-numeric-value arg))
8473 org-todo-keywords-1)))
8474 (t (error "Invalid prefix argument: %s" arg)))))
8475 (message "%d TODO entries found"
8476 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8478 (defun org-deadline (&optional remove time)
8479 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8480 With argument REMOVE, remove any deadline from the item.
8481 When TIME is set, it should be an internal time specification, and the
8482 scheduling will use the corresponding date."
8483 (interactive "P")
8484 (if remove
8485 (progn
8486 (org-remove-timestamp-with-keyword org-deadline-string)
8487 (message "Item no longer has a deadline."))
8488 (if (org-get-repeat)
8489 (error "Cannot change deadline on task with repeater, please do that by hand")
8490 (org-add-planning-info 'deadline time 'closed)
8491 (message "Deadline on %s" org-last-inserted-timestamp))))
8493 (defun org-schedule (&optional remove time)
8494 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8495 With argument REMOVE, remove any scheduling date from the item.
8496 When TIME is set, it should be an internal time specification, and the
8497 scheduling will use the corresponding date."
8498 (interactive "P")
8499 (if remove
8500 (progn
8501 (org-remove-timestamp-with-keyword org-scheduled-string)
8502 (message "Item is no longer scheduled."))
8503 (if (org-get-repeat)
8504 (error "Cannot reschedule task with repeater, please do that by hand")
8505 (org-add-planning-info 'scheduled time 'closed)
8506 (message "Scheduled to %s" org-last-inserted-timestamp))))
8508 (defun org-remove-timestamp-with-keyword (keyword)
8509 "Remove all time stamps with KEYWORD in the current entry."
8510 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8511 beg)
8512 (save-excursion
8513 (org-back-to-heading t)
8514 (setq beg (point))
8515 (org-end-of-subtree t t)
8516 (while (re-search-backward re beg t)
8517 (replace-match "")
8518 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8519 (equal (char-before) ?\ ))
8520 (backward-delete-char 1)
8521 (if (string-match "^[ \t]*$" (buffer-substring
8522 (point-at-bol) (point-at-eol)))
8523 (delete-region (point-at-bol)
8524 (min (point-max) (1+ (point-at-eol))))))))))
8526 (defun org-add-planning-info (what &optional time &rest remove)
8527 "Insert new timestamp with keyword in the line directly after the headline.
8528 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8529 If non is given, the user is prompted for a date.
8530 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8531 be removed."
8532 (interactive)
8533 (let (org-time-was-given org-end-time-was-given ts
8534 end default-time default-input)
8536 (when (and (not time) (memq what '(scheduled deadline)))
8537 ;; Try to get a default date/time from existing timestamp
8538 (save-excursion
8539 (org-back-to-heading t)
8540 (setq end (save-excursion (outline-next-heading) (point)))
8541 (when (re-search-forward (if (eq what 'scheduled)
8542 org-scheduled-time-regexp
8543 org-deadline-time-regexp)
8544 end t)
8545 (setq ts (match-string 1)
8546 default-time
8547 (apply 'encode-time (org-parse-time-string ts))
8548 default-input (and ts (org-get-compact-tod ts))))))
8549 (when what
8550 ;; If necessary, get the time from the user
8551 (setq time (or time (org-read-date nil 'to-time nil nil
8552 default-time default-input))))
8554 (when (and org-insert-labeled-timestamps-at-point
8555 (member what '(scheduled deadline)))
8556 (insert
8557 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8558 (org-insert-time-stamp time org-time-was-given
8559 nil nil nil (list org-end-time-was-given))
8560 (setq what nil))
8561 (save-excursion
8562 (save-restriction
8563 (let (col list elt ts buffer-invisibility-spec)
8564 (org-back-to-heading t)
8565 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8566 (goto-char (match-end 1))
8567 (setq col (current-column))
8568 (goto-char (match-end 0))
8569 (if (eobp) (insert "\n") (forward-char 1))
8570 (if (and (not (looking-at outline-regexp))
8571 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8572 "[^\r\n]*"))
8573 (not (equal (match-string 1) org-clock-string)))
8574 (narrow-to-region (match-beginning 0) (match-end 0))
8575 (insert-before-markers "\n")
8576 (backward-char 1)
8577 (narrow-to-region (point) (point))
8578 (and org-adapt-indentation (org-indent-to-column col)))
8579 ;; Check if we have to remove something.
8580 (setq list (cons what remove))
8581 (while list
8582 (setq elt (pop list))
8583 (goto-char (point-min))
8584 (when (or (and (eq elt 'scheduled)
8585 (re-search-forward org-scheduled-time-regexp nil t))
8586 (and (eq elt 'deadline)
8587 (re-search-forward org-deadline-time-regexp nil t))
8588 (and (eq elt 'closed)
8589 (re-search-forward org-closed-time-regexp nil t)))
8590 (replace-match "")
8591 (if (looking-at "--+<[^>]+>") (replace-match ""))
8592 (if (looking-at " +") (replace-match ""))))
8593 (goto-char (point-max))
8594 (when what
8595 (insert
8596 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8597 (cond ((eq what 'scheduled) org-scheduled-string)
8598 ((eq what 'deadline) org-deadline-string)
8599 ((eq what 'closed) org-closed-string))
8600 " ")
8601 (setq ts (org-insert-time-stamp
8602 time
8603 (or org-time-was-given
8604 (and (eq what 'closed) org-log-done-with-time))
8605 (eq what 'closed)
8606 nil nil (list org-end-time-was-given)))
8607 (end-of-line 1))
8608 (goto-char (point-min))
8609 (widen)
8610 (if (and (looking-at "[ \t]+\n")
8611 (equal (char-before) ?\n))
8612 (delete-region (1- (point)) (point-at-eol)))
8613 ts)))))
8615 (defvar org-log-note-marker (make-marker))
8616 (defvar org-log-note-purpose nil)
8617 (defvar org-log-note-state nil)
8618 (defvar org-log-note-how nil)
8619 (defvar org-log-note-extra nil)
8620 (defvar org-log-note-window-configuration nil)
8621 (defvar org-log-note-return-to (make-marker))
8622 (defvar org-log-post-message nil
8623 "Message to be displayed after a log note has been stored.
8624 The auto-repeater uses this.")
8626 (defun org-add-note ()
8627 "Add a note to the current entry.
8628 This is done in the same way as adding a state change note."
8629 (interactive)
8630 (org-add-log-setup 'note nil 'findpos nil))
8632 (defvar org-property-end-re)
8633 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8634 "Set up the post command hook to take a note.
8635 If this is about to TODO state change, the new state is expected in STATE.
8636 When FINDPOS is non-nil, find the correct position for the note in
8637 the current entry. If not, assume that it can be inserted at point.
8638 HOW is an indicator what kind of note should be created.
8639 EXTRA is additional text that will be inserted into the notes buffer."
8640 (save-restriction
8641 (save-excursion
8642 (when findpos
8643 (org-back-to-heading t)
8644 (narrow-to-region (point) (save-excursion
8645 (outline-next-heading) (point)))
8646 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8647 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8648 "[^\r\n]*\\)?"))
8649 (goto-char (match-end 0))
8650 (when (and org-log-state-notes-insert-after-drawers
8651 (save-excursion
8652 (forward-line) (looking-at org-drawer-regexp)))
8653 (progn (forward-line)
8654 (while (looking-at org-drawer-regexp)
8655 (goto-char (match-end 0))
8656 (re-search-forward org-property-end-re (point-max) t)
8657 (forward-line))
8658 (forward-line -1)))
8659 (unless org-log-states-order-reversed
8660 (and (= (char-after) ?\n) (forward-char 1))
8661 (org-skip-over-state-notes)
8662 (skip-chars-backward " \t\n\r")))
8663 (move-marker org-log-note-marker (point))
8664 (setq org-log-note-purpose purpose
8665 org-log-note-state state
8666 org-log-note-how how
8667 org-log-note-extra extra)
8668 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8670 (defun org-skip-over-state-notes ()
8671 "Skip past the list of State notes in an entry."
8672 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8673 (while (looking-at "[ \t]*- State")
8674 (condition-case nil
8675 (org-next-item)
8676 (error (org-end-of-item)))))
8678 (defun org-add-log-note (&optional purpose)
8679 "Pop up a window for taking a note, and add this note later at point."
8680 (remove-hook 'post-command-hook 'org-add-log-note)
8681 (setq org-log-note-window-configuration (current-window-configuration))
8682 (delete-other-windows)
8683 (move-marker org-log-note-return-to (point))
8684 (switch-to-buffer (marker-buffer org-log-note-marker))
8685 (goto-char org-log-note-marker)
8686 (org-switch-to-buffer-other-window "*Org Note*")
8687 (erase-buffer)
8688 (if (memq org-log-note-how '(time state))
8689 (let (current-prefix-arg) (org-store-log-note))
8690 (let ((org-inhibit-startup t)) (org-mode))
8691 (insert (format "# Insert note for %s.
8692 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8693 (cond
8694 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8695 ((eq org-log-note-purpose 'done) "closed todo item")
8696 ((eq org-log-note-purpose 'state)
8697 (format "state change to \"%s\"" org-log-note-state))
8698 ((eq org-log-note-purpose 'note)
8699 "this entry")
8700 (t (error "This should not happen")))))
8701 (if org-log-note-extra (insert org-log-note-extra))
8702 (org-set-local 'org-finish-function 'org-store-log-note)))
8704 (defvar org-note-abort nil) ; dynamically scoped
8705 (defun org-store-log-note ()
8706 "Finish taking a log note, and insert it to where it belongs."
8707 (let ((txt (buffer-string))
8708 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8709 lines ind)
8710 (kill-buffer (current-buffer))
8711 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8712 (setq txt (replace-match "" t t txt)))
8713 (if (string-match "\\s-+\\'" txt)
8714 (setq txt (replace-match "" t t txt)))
8715 (setq lines (org-split-string txt "\n"))
8716 (when (and note (string-match "\\S-" note))
8717 (setq note
8718 (org-replace-escapes
8719 note
8720 (list (cons "%u" (user-login-name))
8721 (cons "%U" user-full-name)
8722 (cons "%t" (format-time-string
8723 (org-time-stamp-format 'long 'inactive)
8724 (current-time)))
8725 (cons "%s" (if org-log-note-state
8726 (concat "\"" org-log-note-state "\"")
8727 "")))))
8728 (if lines (setq note (concat note " \\\\")))
8729 (push note lines))
8730 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8731 (when lines
8732 (save-excursion
8733 (set-buffer (marker-buffer org-log-note-marker))
8734 (save-excursion
8735 (goto-char org-log-note-marker)
8736 (move-marker org-log-note-marker nil)
8737 (end-of-line 1)
8738 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8739 (indent-relative nil)
8740 (insert "- " (pop lines))
8741 (org-indent-line-function)
8742 (beginning-of-line 1)
8743 (looking-at "[ \t]*")
8744 (setq ind (concat (match-string 0) " "))
8745 (end-of-line 1)
8746 (while lines (insert "\n" ind (pop lines)))))))
8747 (set-window-configuration org-log-note-window-configuration)
8748 (with-current-buffer (marker-buffer org-log-note-return-to)
8749 (goto-char org-log-note-return-to))
8750 (move-marker org-log-note-return-to nil)
8751 (and org-log-post-message (message "%s" org-log-post-message)))
8753 (defun org-sparse-tree (&optional arg)
8754 "Create a sparse tree, prompt for the details.
8755 This command can create sparse trees. You first need to select the type
8756 of match used to create the tree:
8758 t Show entries with a specific TODO keyword.
8759 T Show entries selected by a tags match.
8760 p Enter a property name and its value (both with completion on existing
8761 names/values) and show entries with that property.
8762 r Show entries matching a regular expression
8763 d Show deadlines due within `org-deadline-warning-days'."
8764 (interactive "P")
8765 (let (ans kwd value)
8766 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8767 (setq ans (read-char-exclusive))
8768 (cond
8769 ((equal ans ?d)
8770 (call-interactively 'org-check-deadlines))
8771 ((equal ans ?b)
8772 (call-interactively 'org-check-before-date))
8773 ((equal ans ?t)
8774 (org-show-todo-tree '(4)))
8775 ((equal ans ?T)
8776 (call-interactively 'org-tags-sparse-tree))
8777 ((member ans '(?p ?P))
8778 (setq kwd (org-ido-completing-read "Property: "
8779 (mapcar 'list (org-buffer-property-keys))))
8780 (setq value (org-ido-completing-read "Value: "
8781 (mapcar 'list (org-property-values kwd))))
8782 (unless (string-match "\\`{.*}\\'" value)
8783 (setq value (concat "\"" value "\"")))
8784 (org-tags-sparse-tree arg (concat kwd "=" value)))
8785 ((member ans '(?r ?R ?/))
8786 (call-interactively 'org-occur))
8787 (t (error "No such sparse tree command \"%c\"" ans)))))
8789 (defvar org-occur-highlights nil
8790 "List of overlays used for occur matches.")
8791 (make-variable-buffer-local 'org-occur-highlights)
8792 (defvar org-occur-parameters nil
8793 "Parameters of the active org-occur calls.
8794 This is a list, each call to org-occur pushes as cons cell,
8795 containing the regular expression and the callback, onto the list.
8796 The list can contain several entries if `org-occur' has been called
8797 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8798 will only contain one set of parameters. When the highlights are
8799 removed (for example with `C-c C-c', or with the next edit (depending
8800 on `org-remove-highlights-with-change'), this variable is emptied
8801 as well.")
8802 (make-variable-buffer-local 'org-occur-parameters)
8804 (defun org-occur (regexp &optional keep-previous callback)
8805 "Make a compact tree which shows all matches of REGEXP.
8806 The tree will show the lines where the regexp matches, and all higher
8807 headlines above the match. It will also show the heading after the match,
8808 to make sure editing the matching entry is easy.
8809 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8810 call to `org-occur' will be kept, to allow stacking of calls to this
8811 command.
8812 If CALLBACK is non-nil, it is a function which is called to confirm
8813 that the match should indeed be shown."
8814 (interactive "sRegexp: \nP")
8815 (unless keep-previous
8816 (org-remove-occur-highlights nil nil t))
8817 (push (cons regexp callback) org-occur-parameters)
8818 (let ((cnt 0))
8819 (save-excursion
8820 (goto-char (point-min))
8821 (if (or (not keep-previous) ; do not want to keep
8822 (not org-occur-highlights)) ; no previous matches
8823 ;; hide everything
8824 (org-overview))
8825 (while (re-search-forward regexp nil t)
8826 (when (or (not callback)
8827 (save-match-data (funcall callback)))
8828 (setq cnt (1+ cnt))
8829 (when org-highlight-sparse-tree-matches
8830 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8831 (org-show-context 'occur-tree))))
8832 (when org-remove-highlights-with-change
8833 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8834 nil 'local))
8835 (unless org-sparse-tree-open-archived-trees
8836 (org-hide-archived-subtrees (point-min) (point-max)))
8837 (run-hooks 'org-occur-hook)
8838 (if (interactive-p)
8839 (message "%d match(es) for regexp %s" cnt regexp))
8840 cnt))
8842 (defun org-show-context (&optional key)
8843 "Make sure point and context and visible.
8844 How much context is shown depends upon the variables
8845 `org-show-hierarchy-above', `org-show-following-heading'. and
8846 `org-show-siblings'."
8847 (let ((heading-p (org-on-heading-p t))
8848 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8849 (following-p (org-get-alist-option org-show-following-heading key))
8850 (entry-p (org-get-alist-option org-show-entry-below key))
8851 (siblings-p (org-get-alist-option org-show-siblings key)))
8852 (catch 'exit
8853 ;; Show heading or entry text
8854 (if (and heading-p (not entry-p))
8855 (org-flag-heading nil) ; only show the heading
8856 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8857 (org-show-hidden-entry))) ; show entire entry
8858 (when following-p
8859 ;; Show next sibling, or heading below text
8860 (save-excursion
8861 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8862 (org-flag-heading nil))))
8863 (when siblings-p (org-show-siblings))
8864 (when hierarchy-p
8865 ;; show all higher headings, possibly with siblings
8866 (save-excursion
8867 (while (and (condition-case nil
8868 (progn (org-up-heading-all 1) t)
8869 (error nil))
8870 (not (bobp)))
8871 (org-flag-heading nil)
8872 (when siblings-p (org-show-siblings))))))))
8874 (defun org-reveal (&optional siblings)
8875 "Show current entry, hierarchy above it, and the following headline.
8876 This can be used to show a consistent set of context around locations
8877 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8878 not t for the search context.
8880 With optional argument SIBLINGS, on each level of the hierarchy all
8881 siblings are shown. This repairs the tree structure to what it would
8882 look like when opened with hierarchical calls to `org-cycle'."
8883 (interactive "P")
8884 (let ((org-show-hierarchy-above t)
8885 (org-show-following-heading t)
8886 (org-show-siblings (if siblings t org-show-siblings)))
8887 (org-show-context nil)))
8889 (defun org-highlight-new-match (beg end)
8890 "Highlight from BEG to END and mark the highlight is an occur headline."
8891 (let ((ov (org-make-overlay beg end)))
8892 (org-overlay-put ov 'face 'secondary-selection)
8893 (push ov org-occur-highlights)))
8895 (defun org-remove-occur-highlights (&optional beg end noremove)
8896 "Remove the occur highlights from the buffer.
8897 BEG and END are ignored. If NOREMOVE is nil, remove this function
8898 from the `before-change-functions' in the current buffer."
8899 (interactive)
8900 (unless org-inhibit-highlight-removal
8901 (mapc 'org-delete-overlay org-occur-highlights)
8902 (setq org-occur-highlights nil)
8903 (setq org-occur-parameters nil)
8904 (unless noremove
8905 (remove-hook 'before-change-functions
8906 'org-remove-occur-highlights 'local))))
8908 ;;;; Priorities
8910 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8911 "Regular expression matching the priority indicator.")
8913 (defvar org-remove-priority-next-time nil)
8915 (defun org-priority-up ()
8916 "Increase the priority of the current item."
8917 (interactive)
8918 (org-priority 'up))
8920 (defun org-priority-down ()
8921 "Decrease the priority of the current item."
8922 (interactive)
8923 (org-priority 'down))
8925 (defun org-priority (&optional action)
8926 "Change the priority of an item by ARG.
8927 ACTION can be `set', `up', `down', or a character."
8928 (interactive)
8929 (setq action (or action 'set))
8930 (let (current new news have remove)
8931 (save-excursion
8932 (org-back-to-heading)
8933 (if (looking-at org-priority-regexp)
8934 (setq current (string-to-char (match-string 2))
8935 have t)
8936 (setq current org-default-priority))
8937 (cond
8938 ((or (eq action 'set)
8939 (if (featurep 'xemacs) (characterp action) (integerp action)))
8940 (if (not (eq action 'set))
8941 (setq new action)
8942 (message "Priority %c-%c, SPC to remove: "
8943 org-highest-priority org-lowest-priority)
8944 (setq new (read-char-exclusive)))
8945 (if (and (= (upcase org-highest-priority) org-highest-priority)
8946 (= (upcase org-lowest-priority) org-lowest-priority))
8947 (setq new (upcase new)))
8948 (cond ((equal new ?\ ) (setq remove t))
8949 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8950 (error "Priority must be between `%c' and `%c'"
8951 org-highest-priority org-lowest-priority))))
8952 ((eq action 'up)
8953 (if (and (not have) (eq last-command this-command))
8954 (setq new org-lowest-priority)
8955 (setq new (if (and org-priority-start-cycle-with-default (not have))
8956 org-default-priority (1- current)))))
8957 ((eq action 'down)
8958 (if (and (not have) (eq last-command this-command))
8959 (setq new org-highest-priority)
8960 (setq new (if (and org-priority-start-cycle-with-default (not have))
8961 org-default-priority (1+ current)))))
8962 (t (error "Invalid action")))
8963 (if (or (< (upcase new) org-highest-priority)
8964 (> (upcase new) org-lowest-priority))
8965 (setq remove t))
8966 (setq news (format "%c" new))
8967 (if have
8968 (if remove
8969 (replace-match "" t t nil 1)
8970 (replace-match news t t nil 2))
8971 (if remove
8972 (error "No priority cookie found in line")
8973 (looking-at org-todo-line-regexp)
8974 (if (match-end 2)
8975 (progn
8976 (goto-char (match-end 2))
8977 (insert " [#" news "]"))
8978 (goto-char (match-beginning 3))
8979 (insert "[#" news "] ")))))
8980 (org-preserve-lc (org-set-tags nil 'align))
8981 (if remove
8982 (message "Priority removed")
8983 (message "Priority of current item set to %s" news))))
8986 (defun org-get-priority (s)
8987 "Find priority cookie and return priority."
8988 (save-match-data
8989 (if (not (string-match org-priority-regexp s))
8990 (* 1000 (- org-lowest-priority org-default-priority))
8991 (* 1000 (- org-lowest-priority
8992 (string-to-char (match-string 2 s)))))))
8994 ;;;; Tags
8996 (defvar org-agenda-archives-mode)
8997 (defun org-scan-tags (action matcher &optional todo-only)
8998 "Scan headline tags with inheritance and produce output ACTION.
9000 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9001 or `agenda' to produce an entry list for an agenda view. It can also be
9002 a Lisp form or a function that should be called at each matched headline, in
9003 this case the return value is a list of all return values from these calls.
9005 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9006 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9007 only lines with a TODO keyword are included in the output."
9008 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9009 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9010 (org-re
9011 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9012 (props (list 'face 'default
9013 'done-face 'org-done
9014 'undone-face 'default
9015 'mouse-face 'highlight
9016 'org-not-done-regexp org-not-done-regexp
9017 'org-todo-regexp org-todo-regexp
9018 'keymap org-agenda-keymap
9019 'help-echo
9020 (format "mouse-2 or RET jump to org file %s"
9021 (abbreviate-file-name
9022 (or (buffer-file-name (buffer-base-buffer))
9023 (buffer-name (buffer-base-buffer)))))))
9024 (case-fold-search nil)
9025 lspos tags tags-list
9026 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9027 (llast 0) rtn rtn1 level category i txt
9028 todo marker entry priority)
9029 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9030 (setq action (list 'lambda nil action)))
9031 (save-excursion
9032 (goto-char (point-min))
9033 (when (eq action 'sparse-tree)
9034 (org-overview)
9035 (org-remove-occur-highlights))
9036 (while (re-search-forward re nil t)
9037 (catch :skip
9038 (setq todo (if (match-end 1) (match-string 2))
9039 tags (if (match-end 4) (match-string 4)))
9040 (goto-char (setq lspos (1+ (match-beginning 0))))
9041 (setq level (org-reduced-level (funcall outline-level))
9042 category (org-get-category))
9043 (setq i llast llast level)
9044 ;; remove tag lists from same and sublevels
9045 (while (>= i level)
9046 (when (setq entry (assoc i tags-alist))
9047 (setq tags-alist (delete entry tags-alist)))
9048 (setq i (1- i)))
9049 ;; add the next tags
9050 (when tags
9051 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9052 tags-alist
9053 (cons (cons level tags) tags-alist)))
9054 ;; compile tags for current headline
9055 (setq tags-list
9056 (if org-use-tag-inheritance
9057 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9058 tags))
9059 (when org-use-tag-inheritance
9060 (setcdr (car tags-alist)
9061 (mapcar (lambda (x)
9062 (setq x (copy-sequence x))
9063 (org-add-prop-inherited x))
9064 (cdar tags-alist))))
9065 (when (and tags org-use-tag-inheritance
9066 (not (eq t org-use-tag-inheritance)))
9067 ;; selective inheritance, remove uninherited ones
9068 (setcdr (car tags-alist)
9069 (org-remove-uniherited-tags (cdar tags-alist))))
9070 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9071 (let ((case-fold-search t)) (eval matcher))
9073 (not (member org-archive-tag tags-list))
9074 ;; we have an archive tag, should we use this anyway?
9075 (or (not org-agenda-skip-archived-trees)
9076 (and (eq action 'agenda) org-agenda-archives-mode))))
9077 (unless (eq action 'sparse-tree) (org-agenda-skip))
9079 ;; select this headline
9081 (cond
9082 ((eq action 'sparse-tree)
9083 (and org-highlight-sparse-tree-matches
9084 (org-get-heading) (match-end 0)
9085 (org-highlight-new-match
9086 (match-beginning 0) (match-beginning 1)))
9087 (org-show-context 'tags-tree))
9088 ((eq action 'agenda)
9089 (setq txt (org-format-agenda-item
9091 (concat
9092 (if org-tags-match-list-sublevels
9093 (make-string (1- level) ?.) "")
9094 (org-get-heading))
9095 category tags-list)
9096 priority (org-get-priority txt))
9097 (goto-char lspos)
9098 (setq marker (org-agenda-new-marker))
9099 (org-add-props txt props
9100 'org-marker marker 'org-hd-marker marker 'org-category category
9101 'priority priority 'type "tagsmatch")
9102 (push txt rtn))
9103 ((functionp action)
9104 (save-excursion
9105 (setq rtn1 (funcall action))
9106 (push rtn1 rtn))
9107 (goto-char (point-at-eol)))
9108 (t (error "Invalid action")))
9110 ;; if we are to skip sublevels, jump to end of subtree
9111 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9112 (when (and (eq action 'sparse-tree)
9113 (not org-sparse-tree-open-archived-trees))
9114 (org-hide-archived-subtrees (point-min) (point-max)))
9115 (nreverse rtn)))
9117 (defun org-remove-uniherited-tags (tags)
9118 "Remove all tags that are not inherited from the list TAGS."
9119 (cond
9120 ((eq org-use-tag-inheritance t)
9121 (if org-tags-exclude-from-inheritance
9122 (org-delete-all org-tags-exclude-from-inheritance tags)
9123 tags))
9124 ((not org-use-tag-inheritance) nil)
9125 ((stringp org-use-tag-inheritance)
9126 (delq nil (mapcar
9127 (lambda (x)
9128 (if (and (string-match org-use-tag-inheritance x)
9129 (not (member x org-tags-exclude-from-inheritance)))
9130 x nil))
9131 tags)))
9132 ((listp org-use-tag-inheritance)
9133 (delq nil (mapcar
9134 (lambda (x)
9135 (if (member x org-use-tag-inheritance) x nil))
9136 tags)))))
9138 (defvar todo-only) ;; dynamically scoped
9140 (defun org-tags-sparse-tree (&optional todo-only match)
9141 "Create a sparse tree according to tags string MATCH.
9142 MATCH can contain positive and negative selection of tags, like
9143 \"+WORK+URGENT-WITHBOSS\".
9144 If optional argument TODO-ONLY is non-nil, only select lines that are
9145 also TODO lines."
9146 (interactive "P")
9147 (org-prepare-agenda-buffers (list (current-buffer)))
9148 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9150 (defvar org-cached-props nil)
9151 (defun org-cached-entry-get (pom property)
9152 (if (or (eq t org-use-property-inheritance)
9153 (and (stringp org-use-property-inheritance)
9154 (string-match org-use-property-inheritance property))
9155 (and (listp org-use-property-inheritance)
9156 (member property org-use-property-inheritance)))
9157 ;; Caching is not possible, check it directly
9158 (org-entry-get pom property 'inherit)
9159 ;; Get all properties, so that we can do complicated checks easily
9160 (cdr (assoc property (or org-cached-props
9161 (setq org-cached-props
9162 (org-entry-properties pom)))))))
9164 (defun org-global-tags-completion-table (&optional files)
9165 "Return the list of all tags in all agenda buffer/files."
9166 (save-excursion
9167 (org-uniquify
9168 (delq nil
9169 (apply 'append
9170 (mapcar
9171 (lambda (file)
9172 (set-buffer (find-file-noselect file))
9173 (append (org-get-buffer-tags)
9174 (mapcar (lambda (x) (if (stringp (car-safe x))
9175 (list (car-safe x)) nil))
9176 org-tag-alist)))
9177 (if (and files (car files))
9178 files
9179 (org-agenda-files))))))))
9181 (defun org-make-tags-matcher (match)
9182 "Create the TAGS//TODO matcher form for the selection string MATCH."
9183 ;; todo-only is scoped dynamically into this function, and the function
9184 ;; may change it it the matcher asksk for it.
9185 (unless match
9186 ;; Get a new match request, with completion
9187 (let ((org-last-tags-completion-table
9188 (org-global-tags-completion-table)))
9189 (setq match (org-ido-completing-read
9190 "Match: " 'org-tags-completion-function nil nil nil
9191 'org-tags-history))))
9193 ;; Parse the string and create a lisp form
9194 (let ((match0 match)
9195 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9196 minus tag mm
9197 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9198 orterms term orlist re-p str-p level-p level-op time-p
9199 prop-p pn pv po cat-p gv rest)
9200 (if (string-match "/+" match)
9201 ;; match contains also a todo-matching request
9202 (progn
9203 (setq tagsmatch (substring match 0 (match-beginning 0))
9204 todomatch (substring match (match-end 0)))
9205 (if (string-match "^!" todomatch)
9206 (setq todo-only t todomatch (substring todomatch 1)))
9207 (if (string-match "^\\s-*$" todomatch)
9208 (setq todomatch nil)))
9209 ;; only matching tags
9210 (setq tagsmatch match todomatch nil))
9212 ;; Make the tags matcher
9213 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9214 (setq tagsmatcher t)
9215 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9216 (while (setq term (pop orterms))
9217 (while (and (equal (substring term -1) "\\") orterms)
9218 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9219 (while (string-match re term)
9220 (setq rest (substring term (match-end 0))
9221 minus (and (match-end 1)
9222 (equal (match-string 1 term) "-"))
9223 tag (match-string 2 term)
9224 re-p (equal (string-to-char tag) ?{)
9225 level-p (match-end 4)
9226 prop-p (match-end 5)
9227 mm (cond
9228 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9229 (level-p
9230 (setq level-op (org-op-to-function (match-string 3 term)))
9231 `(,level-op level ,(string-to-number
9232 (match-string 4 term))))
9233 (prop-p
9234 (setq pn (match-string 5 term)
9235 po (match-string 6 term)
9236 pv (match-string 7 term)
9237 cat-p (equal pn "CATEGORY")
9238 re-p (equal (string-to-char pv) ?{)
9239 str-p (equal (string-to-char pv) ?\")
9240 time-p (save-match-data
9241 (string-match "^\"[[<].*[]>]\"$" pv))
9242 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9243 (if time-p (setq pv (org-matcher-time pv)))
9244 (setq po (org-op-to-function po (if time-p 'time str-p)))
9245 (cond
9246 ((equal pn "CATEGORY")
9247 (setq gv '(get-text-property (point) 'org-category)))
9248 ((equal pn "TODO")
9249 (setq gv 'todo))
9251 (setq gv `(org-cached-entry-get nil ,pn))))
9252 (if re-p
9253 (if (eq po 'org<>)
9254 `(not (string-match ,pv (or ,gv "")))
9255 `(string-match ,pv (or ,gv "")))
9256 (if str-p
9257 `(,po (or ,gv "") ,pv)
9258 `(,po (string-to-number (or ,gv ""))
9259 ,(string-to-number pv) ))))
9260 (t `(member ,(downcase tag) tags-list)))
9261 mm (if minus (list 'not mm) mm)
9262 term rest)
9263 (push mm tagsmatcher))
9264 (push (if (> (length tagsmatcher) 1)
9265 (cons 'and tagsmatcher)
9266 (car tagsmatcher))
9267 orlist)
9268 (setq tagsmatcher nil))
9269 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9270 (setq tagsmatcher
9271 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9272 ;; Make the todo matcher
9273 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9274 (setq todomatcher t)
9275 (setq orterms (org-split-string todomatch "|") orlist nil)
9276 (while (setq term (pop orterms))
9277 (while (string-match re term)
9278 (setq minus (and (match-end 1)
9279 (equal (match-string 1 term) "-"))
9280 kwd (match-string 2 term)
9281 re-p (equal (string-to-char kwd) ?{)
9282 term (substring term (match-end 0))
9283 mm (if re-p
9284 `(string-match ,(substring kwd 1 -1) todo)
9285 (list 'equal 'todo kwd))
9286 mm (if minus (list 'not mm) mm))
9287 (push mm todomatcher))
9288 (push (if (> (length todomatcher) 1)
9289 (cons 'and todomatcher)
9290 (car todomatcher))
9291 orlist)
9292 (setq todomatcher nil))
9293 (setq todomatcher (if (> (length orlist) 1)
9294 (cons 'or orlist) (car orlist))))
9296 ;; Return the string and lisp forms of the matcher
9297 (setq matcher (if todomatcher
9298 (list 'and tagsmatcher todomatcher)
9299 tagsmatcher))
9300 (cons match0 matcher)))
9302 (defun org-op-to-function (op &optional stringp)
9303 "Turn an operator into the appropriate function."
9304 (setq op
9305 (cond
9306 ((equal op "<" ) '(< string< org-time<))
9307 ((equal op ">" ) '(> org-string> org-time>))
9308 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9309 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9310 ((member op '("=" "==")) '(= string= org-time=))
9311 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9312 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9314 (defun org<> (a b) (not (= a b)))
9315 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9316 (defun org-string>= (a b) (not (string< a b)))
9317 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9318 (defun org-string<> (a b) (not (string= a b)))
9319 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9320 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9321 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9322 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9323 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9324 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9325 (defun org-2ft (s)
9326 "Convert S to a floating point time.
9327 If S is already a number, just return it. If it is a string, parse
9328 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9329 (cond
9330 ((numberp s) s)
9331 ((stringp s)
9332 (condition-case nil
9333 (float-time (apply 'encode-time (org-parse-time-string s)))
9334 (error 0.)))
9335 (t 0.)))
9337 (defun org-time-today ()
9338 "Time in seconds today at 0:00.
9339 Returns the float number of seconds since the beginning of the
9340 epoch to the beginning of today (00:00)."
9341 (float-time (apply 'encode-time
9342 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9344 (defun org-matcher-time (s)
9345 "Interprete a time comparison value."
9346 (save-match-data
9347 (cond
9348 ((string= s "<now>") (float-time))
9349 ((string= s "<today>") (org-time-today))
9350 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9351 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9352 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9353 (+ (org-time-today)
9354 (* (string-to-number (match-string 1 s))
9355 (cdr (assoc (match-string 2 s)
9356 '(("d" . 86400.0) ("w" . 604800.0)
9357 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9358 (t (org-2ft s)))))
9360 (defun org-match-any-p (re list)
9361 "Does re match any element of list?"
9362 (setq list (mapcar (lambda (x) (string-match re x)) list))
9363 (delq nil list))
9365 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9366 (defvar org-tags-overlay (org-make-overlay 1 1))
9367 (org-detach-overlay org-tags-overlay)
9369 (defun org-get-local-tags-at (&optional pos)
9370 "Get a list of tags defined in the current headline."
9371 (org-get-tags-at pos 'local))
9373 (defun org-get-local-tags ()
9374 "Get a list of tags defined in the current headline."
9375 (org-get-tags-at nil 'local))
9377 (defun org-get-tags-at (&optional pos local)
9378 "Get a list of all headline tags applicable at POS.
9379 POS defaults to point. If tags are inherited, the list contains
9380 the targets in the same sequence as the headlines appear, i.e.
9381 the tags of the current headline come last.
9382 When LOCAL is non-nil, only return tags from the current headline,
9383 ignore inherited ones."
9384 (interactive)
9385 (let (tags ltags lastpos parent)
9386 (save-excursion
9387 (save-restriction
9388 (widen)
9389 (goto-char (or pos (point)))
9390 (save-match-data
9391 (catch 'done
9392 (condition-case nil
9393 (progn
9394 (org-back-to-heading t)
9395 (while (not (equal lastpos (point)))
9396 (setq lastpos (point))
9397 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9398 (setq ltags (org-split-string
9399 (org-match-string-no-properties 1) ":"))
9400 (when parent
9401 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9402 (setq tags (append
9403 (if parent
9404 (org-remove-uniherited-tags ltags)
9405 ltags)
9406 tags)))
9407 (or org-use-tag-inheritance (throw 'done t))
9408 (if local (throw 'done t))
9409 (org-up-heading-all 1)
9410 (setq parent t)))
9411 (error nil)))))
9412 (append (org-remove-uniherited-tags org-file-tags) tags))))
9414 (defun org-add-prop-inherited (s)
9415 (add-text-properties 0 (length s) '(inherited t) s)
9418 (defun org-toggle-tag (tag &optional onoff)
9419 "Toggle the tag TAG for the current line.
9420 If ONOFF is `on' or `off', don't toggle but set to this state."
9421 (unless (org-on-heading-p t) (error "Not on headling"))
9422 (let (res current)
9423 (save-excursion
9424 (beginning-of-line)
9425 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9426 (point-at-eol) t)
9427 (progn
9428 (setq current (match-string 1))
9429 (replace-match ""))
9430 (setq current ""))
9431 (setq current (nreverse (org-split-string current ":")))
9432 (cond
9433 ((eq onoff 'on)
9434 (setq res t)
9435 (or (member tag current) (push tag current)))
9436 ((eq onoff 'off)
9437 (or (not (member tag current)) (setq current (delete tag current))))
9438 (t (if (member tag current)
9439 (setq current (delete tag current))
9440 (setq res t)
9441 (push tag current))))
9442 (end-of-line 1)
9443 (if current
9444 (progn
9445 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9446 (org-set-tags nil t))
9447 (delete-horizontal-space))
9448 (run-hooks 'org-after-tags-change-hook))
9449 res))
9451 (defun org-align-tags-here (to-col)
9452 ;; Assumes that this is a headline
9453 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9454 (beginning-of-line 1)
9455 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9456 (< pos (match-beginning 2)))
9457 (progn
9458 (setq tags-l (- (match-end 2) (match-beginning 2)))
9459 (goto-char (match-beginning 1))
9460 (insert " ")
9461 (delete-region (point) (1+ (match-beginning 2)))
9462 (setq ncol (max (1+ (current-column))
9463 (1+ col)
9464 (if (> to-col 0)
9465 to-col
9466 (- (abs to-col) tags-l))))
9467 (setq p (point))
9468 (insert (make-string (- ncol (current-column)) ?\ ))
9469 (setq ncol (current-column))
9470 (when indent-tabs-mode (tabify p (point-at-eol)))
9471 (org-move-to-column (min ncol col) t))
9472 (goto-char pos))))
9474 (defun org-set-tags-command (&optional arg just-align)
9475 "Call the set-tags command for the current entry."
9476 (interactive "P")
9477 (if (org-on-heading-p)
9478 (org-set-tags arg just-align)
9479 (save-excursion
9480 (org-back-to-heading t)
9481 (org-set-tags arg just-align))))
9483 (defun org-set-tags (&optional arg just-align)
9484 "Set the tags for the current headline.
9485 With prefix ARG, realign all tags in headings in the current buffer."
9486 (interactive "P")
9487 (let* ((re (concat "^" outline-regexp))
9488 (current (org-get-tags-string))
9489 (col (current-column))
9490 (org-setting-tags t)
9491 table current-tags inherited-tags ; computed below when needed
9492 tags p0 c0 c1 rpl)
9493 (if arg
9494 (save-excursion
9495 (goto-char (point-min))
9496 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9497 (while (re-search-forward re nil t)
9498 (org-set-tags nil t)
9499 (end-of-line 1)))
9500 (message "All tags realigned to column %d" org-tags-column))
9501 (if just-align
9502 (setq tags current)
9503 ;; Get a new set of tags from the user
9504 (save-excursion
9505 (setq table (or org-tag-alist (org-get-buffer-tags))
9506 org-last-tags-completion-table table
9507 current-tags (org-split-string current ":")
9508 inherited-tags (nreverse
9509 (nthcdr (length current-tags)
9510 (nreverse (org-get-tags-at))))
9511 tags
9512 (if (or (eq t org-use-fast-tag-selection)
9513 (and org-use-fast-tag-selection
9514 (delq nil (mapcar 'cdr table))))
9515 (org-fast-tag-selection
9516 current-tags inherited-tags table
9517 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9518 (let ((org-add-colon-after-tag-completion t))
9519 (org-trim
9520 (org-without-partial-completion
9521 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9522 nil nil current 'org-tags-history)))))))
9523 (while (string-match "[-+&]+" tags)
9524 ;; No boolean logic, just a list
9525 (setq tags (replace-match ":" t t tags))))
9527 (if (string-match "\\`[\t ]*\\'" tags)
9528 (setq tags "")
9529 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9530 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9532 ;; Insert new tags at the correct column
9533 (beginning-of-line 1)
9534 (cond
9535 ((and (equal current "") (equal tags "")))
9536 ((re-search-forward
9537 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9538 (point-at-eol) t)
9539 (if (equal tags "")
9540 (setq rpl "")
9541 (goto-char (match-beginning 0))
9542 (setq c0 (current-column) p0 (point)
9543 c1 (max (1+ c0) (if (> org-tags-column 0)
9544 org-tags-column
9545 (- (- org-tags-column) (length tags))))
9546 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9547 (replace-match rpl t t)
9548 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9549 tags)
9550 (t (error "Tags alignment failed")))
9551 (org-move-to-column col)
9552 (unless just-align
9553 (run-hooks 'org-after-tags-change-hook)))))
9555 (defun org-change-tag-in-region (beg end tag off)
9556 "Add or remove TAG for each entry in the region.
9557 This works in the agenda, and also in an org-mode buffer."
9558 (interactive
9559 (list (region-beginning) (region-end)
9560 (let ((org-last-tags-completion-table
9561 (if (org-mode-p)
9562 (org-get-buffer-tags)
9563 (org-global-tags-completion-table))))
9564 (org-ido-completing-read
9565 "Tag: " 'org-tags-completion-function nil nil nil
9566 'org-tags-history))
9567 (progn
9568 (message "[s]et or [r]emove? ")
9569 (equal (read-char-exclusive) ?r))))
9570 (if (fboundp 'deactivate-mark) (deactivate-mark))
9571 (let ((agendap (equal major-mode 'org-agenda-mode))
9572 l1 l2 m buf pos newhead (cnt 0))
9573 (goto-char end)
9574 (setq l2 (1- (org-current-line)))
9575 (goto-char beg)
9576 (setq l1 (org-current-line))
9577 (loop for l from l1 to l2 do
9578 (goto-line l)
9579 (setq m (get-text-property (point) 'org-hd-marker))
9580 (when (or (and (org-mode-p) (org-on-heading-p))
9581 (and agendap m))
9582 (setq buf (if agendap (marker-buffer m) (current-buffer))
9583 pos (if agendap m (point)))
9584 (with-current-buffer buf
9585 (save-excursion
9586 (save-restriction
9587 (goto-char pos)
9588 (setq cnt (1+ cnt))
9589 (org-toggle-tag tag (if off 'off 'on))
9590 (setq newhead (org-get-heading)))))
9591 (and agendap (org-agenda-change-all-lines newhead m))))
9592 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9594 (defun org-tags-completion-function (string predicate &optional flag)
9595 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9596 (confirm (lambda (x) (stringp (car x)))))
9597 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9598 (setq s1 (match-string 1 string)
9599 s2 (match-string 2 string))
9600 (setq s1 "" s2 string))
9601 (cond
9602 ((eq flag nil)
9603 ;; try completion
9604 (setq rtn (try-completion s2 ctable confirm))
9605 (if (stringp rtn)
9606 (setq rtn
9607 (concat s1 s2 (substring rtn (length s2))
9608 (if (and org-add-colon-after-tag-completion
9609 (assoc rtn ctable))
9610 ":" ""))))
9611 rtn)
9612 ((eq flag t)
9613 ;; all-completions
9614 (all-completions s2 ctable confirm)
9616 ((eq flag 'lambda)
9617 ;; exact match?
9618 (assoc s2 ctable)))
9621 (defun org-fast-tag-insert (kwd tags face &optional end)
9622 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9623 (insert (format "%-12s" (concat kwd ":"))
9624 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9625 (or end "")))
9627 (defun org-fast-tag-show-exit (flag)
9628 (save-excursion
9629 (goto-line 3)
9630 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9631 (replace-match ""))
9632 (when flag
9633 (end-of-line 1)
9634 (org-move-to-column (- (window-width) 19) t)
9635 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9637 (defun org-set-current-tags-overlay (current prefix)
9638 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9639 (if (featurep 'xemacs)
9640 (org-overlay-display org-tags-overlay (concat prefix s)
9641 'secondary-selection)
9642 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9643 (org-overlay-display org-tags-overlay (concat prefix s)))))
9645 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9646 "Fast tag selection with single keys.
9647 CURRENT is the current list of tags in the headline, INHERITED is the
9648 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9649 possibly with grouping information. TODO-TABLE is a similar table with
9650 TODO keywords, should these have keys assigned to them.
9651 If the keys are nil, a-z are automatically assigned.
9652 Returns the new tags string, or nil to not change the current settings."
9653 (let* ((fulltable (append table todo-table))
9654 (maxlen (apply 'max (mapcar
9655 (lambda (x)
9656 (if (stringp (car x)) (string-width (car x)) 0))
9657 fulltable)))
9658 (buf (current-buffer))
9659 (expert (eq org-fast-tag-selection-single-key 'expert))
9660 (buffer-tags nil)
9661 (fwidth (+ maxlen 3 1 3))
9662 (ncol (/ (- (window-width) 4) fwidth))
9663 (i-face 'org-done)
9664 (c-face 'org-todo)
9665 tg cnt e c char c1 c2 ntable tbl rtn
9666 ov-start ov-end ov-prefix
9667 (exit-after-next org-fast-tag-selection-single-key)
9668 (done-keywords org-done-keywords)
9669 groups ingroup)
9670 (save-excursion
9671 (beginning-of-line 1)
9672 (if (looking-at
9673 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9674 (setq ov-start (match-beginning 1)
9675 ov-end (match-end 1)
9676 ov-prefix "")
9677 (setq ov-start (1- (point-at-eol))
9678 ov-end (1+ ov-start))
9679 (skip-chars-forward "^\n\r")
9680 (setq ov-prefix
9681 (concat
9682 (buffer-substring (1- (point)) (point))
9683 (if (> (current-column) org-tags-column)
9685 (make-string (- org-tags-column (current-column)) ?\ ))))))
9686 (org-move-overlay org-tags-overlay ov-start ov-end)
9687 (save-window-excursion
9688 (if expert
9689 (set-buffer (get-buffer-create " *Org tags*"))
9690 (delete-other-windows)
9691 (split-window-vertically)
9692 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9693 (erase-buffer)
9694 (org-set-local 'org-done-keywords done-keywords)
9695 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9696 (org-fast-tag-insert "Current" current c-face "\n\n")
9697 (org-fast-tag-show-exit exit-after-next)
9698 (org-set-current-tags-overlay current ov-prefix)
9699 (setq tbl fulltable char ?a cnt 0)
9700 (while (setq e (pop tbl))
9701 (cond
9702 ((equal e '(:startgroup))
9703 (push '() groups) (setq ingroup t)
9704 (when (not (= cnt 0))
9705 (setq cnt 0)
9706 (insert "\n"))
9707 (insert "{ "))
9708 ((equal e '(:endgroup))
9709 (setq ingroup nil cnt 0)
9710 (insert "}\n"))
9712 (setq tg (car e) c2 nil)
9713 (if (cdr e)
9714 (setq c (cdr e))
9715 ;; automatically assign a character.
9716 (setq c1 (string-to-char
9717 (downcase (substring
9718 tg (if (= (string-to-char tg) ?@) 1 0)))))
9719 (if (or (rassoc c1 ntable) (rassoc c1 table))
9720 (while (or (rassoc char ntable) (rassoc char table))
9721 (setq char (1+ char)))
9722 (setq c2 c1))
9723 (setq c (or c2 char)))
9724 (if ingroup (push tg (car groups)))
9725 (setq tg (org-add-props tg nil 'face
9726 (cond
9727 ((not (assoc tg table))
9728 (org-get-todo-face tg))
9729 ((member tg current) c-face)
9730 ((member tg inherited) i-face)
9731 (t nil))))
9732 (if (and (= cnt 0) (not ingroup)) (insert " "))
9733 (insert "[" c "] " tg (make-string
9734 (- fwidth 4 (length tg)) ?\ ))
9735 (push (cons tg c) ntable)
9736 (when (= (setq cnt (1+ cnt)) ncol)
9737 (insert "\n")
9738 (if ingroup (insert " "))
9739 (setq cnt 0)))))
9740 (setq ntable (nreverse ntable))
9741 (insert "\n")
9742 (goto-char (point-min))
9743 (if (not expert) (org-fit-window-to-buffer))
9744 (setq rtn
9745 (catch 'exit
9746 (while t
9747 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9748 (if groups " [!] no groups" " [!]groups")
9749 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9750 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9751 (cond
9752 ((= c ?\r) (throw 'exit t))
9753 ((= c ?!)
9754 (setq groups (not groups))
9755 (goto-char (point-min))
9756 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9757 ((= c ?\C-c)
9758 (if (not expert)
9759 (org-fast-tag-show-exit
9760 (setq exit-after-next (not exit-after-next)))
9761 (setq expert nil)
9762 (delete-other-windows)
9763 (split-window-vertically)
9764 (org-switch-to-buffer-other-window " *Org tags*")
9765 (org-fit-window-to-buffer)))
9766 ((or (= c ?\C-g)
9767 (and (= c ?q) (not (rassoc c ntable))))
9768 (org-detach-overlay org-tags-overlay)
9769 (setq quit-flag t))
9770 ((= c ?\ )
9771 (setq current nil)
9772 (if exit-after-next (setq exit-after-next 'now)))
9773 ((= c ?\t)
9774 (condition-case nil
9775 (setq tg (org-ido-completing-read
9776 "Tag: "
9777 (or buffer-tags
9778 (with-current-buffer buf
9779 (org-get-buffer-tags)))))
9780 (quit (setq tg "")))
9781 (when (string-match "\\S-" tg)
9782 (add-to-list 'buffer-tags (list tg))
9783 (if (member tg current)
9784 (setq current (delete tg current))
9785 (push tg current)))
9786 (if exit-after-next (setq exit-after-next 'now)))
9787 ((setq e (rassoc c todo-table) tg (car e))
9788 (with-current-buffer buf
9789 (save-excursion (org-todo tg)))
9790 (if exit-after-next (setq exit-after-next 'now)))
9791 ((setq e (rassoc c ntable) tg (car e))
9792 (if (member tg current)
9793 (setq current (delete tg current))
9794 (loop for g in groups do
9795 (if (member tg g)
9796 (mapc (lambda (x)
9797 (setq current (delete x current)))
9798 g)))
9799 (push tg current))
9800 (if exit-after-next (setq exit-after-next 'now))))
9802 ;; Create a sorted list
9803 (setq current
9804 (sort current
9805 (lambda (a b)
9806 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9807 (if (eq exit-after-next 'now) (throw 'exit t))
9808 (goto-char (point-min))
9809 (beginning-of-line 2)
9810 (delete-region (point) (point-at-eol))
9811 (org-fast-tag-insert "Current" current c-face)
9812 (org-set-current-tags-overlay current ov-prefix)
9813 (while (re-search-forward
9814 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9815 (setq tg (match-string 1))
9816 (add-text-properties
9817 (match-beginning 1) (match-end 1)
9818 (list 'face
9819 (cond
9820 ((member tg current) c-face)
9821 ((member tg inherited) i-face)
9822 (t (get-text-property (match-beginning 1) 'face))))))
9823 (goto-char (point-min)))))
9824 (org-detach-overlay org-tags-overlay)
9825 (if rtn
9826 (mapconcat 'identity current ":")
9827 nil))))
9829 (defun org-get-tags-string ()
9830 "Get the TAGS string in the current headline."
9831 (unless (org-on-heading-p t)
9832 (error "Not on a heading"))
9833 (save-excursion
9834 (beginning-of-line 1)
9835 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9836 (org-match-string-no-properties 1)
9837 "")))
9839 (defun org-get-tags ()
9840 "Get the list of tags specified in the current headline."
9841 (org-split-string (org-get-tags-string) ":"))
9843 (defun org-get-buffer-tags ()
9844 "Get a table of all tags used in the buffer, for completion."
9845 (let (tags)
9846 (save-excursion
9847 (goto-char (point-min))
9848 (while (re-search-forward
9849 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9850 (when (equal (char-after (point-at-bol 0)) ?*)
9851 (mapc (lambda (x) (add-to-list 'tags x))
9852 (org-split-string (org-match-string-no-properties 1) ":")))))
9853 (mapcar 'list tags)))
9855 ;;;; The mapping API
9857 ;;;###autoload
9858 (defun org-map-entries (func &optional match scope &rest skip)
9859 "Call FUNC at each headline selected by MATCH in SCOPE.
9861 FUNC is a function or a lisp form. The function will be called without
9862 arguments, with the cursor positioned at the beginning of the headline.
9863 The return values of all calls to the function will be collected and
9864 returned as a list.
9866 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9867 Only headlines that are matched by this query will be considered during
9868 the iteration. When MATCH is nil or t, all headlines will be
9869 visited by the iteration.
9871 SCOPE determines the scope of this command. It can be any of:
9873 nil The current buffer, respecting the restriction if any
9874 tree The subtree started with the entry at point
9875 file The current buffer, without restriction
9876 file-with-archives
9877 The current buffer, and any archives associated with it
9878 agenda All agenda files
9879 agenda-with-archives
9880 All agenda files with any archive files associated with them
9881 \(file1 file2 ...)
9882 If this is a list, all files in the list will be scanned
9884 The remaining args are treated as settings for the skipping facilities of
9885 the scanner. The following items can be given here:
9887 archive skip trees with the archive tag.
9888 comment skip trees with the COMMENT keyword
9889 function or Emacs Lisp form:
9890 will be used as value for `org-agenda-skip-function', so whenever
9891 the the function returns t, FUNC will not be called for that
9892 entry and search will continue from the point where the
9893 function leaves it."
9894 (let* ((org-agenda-archives-mode nil) ; just to make sure
9895 (org-agenda-skip-archived-trees (memq 'archive skip))
9896 (org-agenda-skip-comment-trees (memq 'comment skip))
9897 (org-agenda-skip-function
9898 (car (org-delete-all '(comment archive) skip)))
9899 (org-tags-match-list-sublevels t)
9900 matcher pos file res
9901 org-todo-keywords-for-agenda
9902 org-done-keywords-for-agenda
9903 org-todo-keyword-alist-for-agenda
9904 org-tag-alist-for-agenda)
9906 (cond
9907 ((eq match t) (setq matcher t))
9908 ((eq match nil) (setq matcher t))
9909 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
9911 (when (eq scope 'tree)
9912 (org-back-to-heading t)
9913 (org-narrow-to-subtree)
9914 (setq scope nil))
9916 (if (not scope)
9917 (progn
9918 (org-prepare-agenda-buffers
9919 (list (buffer-file-name (current-buffer))))
9920 (org-scan-tags func matcher))
9921 ;; Get the right scope
9922 (setq pos (point))
9923 (cond
9924 ((and scope (listp scope) (symbolp (car scope)))
9925 (setq scope (eval scope)))
9926 ((eq scope 'agenda)
9927 (setq scope (org-agenda-files t)))
9928 ((eq scope 'agenda-with-archives)
9929 (setq scope (org-agenda-files t))
9930 (setq scope (org-add-archive-files scope)))
9931 ((eq scope 'file)
9932 (setq scope (list (buffer-file-name))))
9933 ((eq scope 'file-with-archives)
9934 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9935 (org-prepare-agenda-buffers scope)
9936 (while (setq file (pop scope))
9937 (with-current-buffer (org-find-base-buffer-visiting file)
9938 (save-excursion
9939 (save-restriction
9940 (widen)
9941 (goto-char (point-min))
9942 (setq res (append res (org-scan-tags func matcher)))))))
9943 res)))
9945 ;;;; Properties
9947 ;;; Setting and retrieving properties
9949 (defconst org-special-properties
9950 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9951 "TIMESTAMP" "TIMESTAMP_IA")
9952 "The special properties valid in Org-mode.
9954 These are properties that are not defined in the property drawer,
9955 but in some other way.")
9957 (defconst org-default-properties
9958 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9959 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9960 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9961 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9962 "Some properties that are used by Org-mode for various purposes.
9963 Being in this list makes sure that they are offered for completion.")
9965 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9966 "Regular expression matching the first line of a property drawer.")
9968 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9969 "Regular expression matching the first line of a property drawer.")
9971 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9972 "Regular expression matching the first line of a property drawer.")
9974 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9975 "Regular expression matching the first line of a property drawer.")
9977 (defconst org-property-drawer-re
9978 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9979 org-property-end-re "\\)\n?")
9980 "Matches an entire property drawer.")
9982 (defconst org-clock-drawer-re
9983 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9984 org-property-end-re "\\)\n?")
9985 "Matches an entire clock drawer.")
9987 (defun org-property-action ()
9988 "Do an action on properties."
9989 (interactive)
9990 (let (c)
9991 (org-at-property-p)
9992 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9993 (setq c (read-char-exclusive))
9994 (cond
9995 ((equal c ?s)
9996 (call-interactively 'org-set-property))
9997 ((equal c ?d)
9998 (call-interactively 'org-delete-property))
9999 ((equal c ?D)
10000 (call-interactively 'org-delete-property-globally))
10001 ((equal c ?c)
10002 (call-interactively 'org-compute-property-at-point))
10003 (t (error "No such property action %c" c)))))
10005 (defun org-at-property-p ()
10006 "Is the cursor in a property line?"
10007 ;; FIXME: Does not check if we are actually in the drawer.
10008 ;; FIXME: also returns true on any drawers.....
10009 ;; This is used by C-c C-c for property action.
10010 (save-excursion
10011 (beginning-of-line 1)
10012 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10014 (defun org-get-property-block (&optional beg end force)
10015 "Return the (beg . end) range of the body of the property drawer.
10016 BEG and END can be beginning and end of subtree, if not given
10017 they will be found.
10018 If the drawer does not exist and FORCE is non-nil, create the drawer."
10019 (catch 'exit
10020 (save-excursion
10021 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10022 (end (or end (progn (outline-next-heading) (point)))))
10023 (goto-char beg)
10024 (if (re-search-forward org-property-start-re end t)
10025 (setq beg (1+ (match-end 0)))
10026 (if force
10027 (save-excursion
10028 (org-insert-property-drawer)
10029 (setq end (progn (outline-next-heading) (point))))
10030 (throw 'exit nil))
10031 (goto-char beg)
10032 (if (re-search-forward org-property-start-re end t)
10033 (setq beg (1+ (match-end 0)))))
10034 (if (re-search-forward org-property-end-re end t)
10035 (setq end (match-beginning 0))
10036 (or force (throw 'exit nil))
10037 (goto-char beg)
10038 (setq end beg)
10039 (org-indent-line-function)
10040 (insert ":END:\n"))
10041 (cons beg end)))))
10043 (defun org-entry-properties (&optional pom which)
10044 "Get all properties of the entry at point-or-marker POM.
10045 This includes the TODO keyword, the tags, time strings for deadline,
10046 scheduled, and clocking, and any additional properties defined in the
10047 entry. The return value is an alist, keys may occur multiple times
10048 if the property key was used several times.
10049 POM may also be nil, in which case the current entry is used.
10050 If WHICH is nil or `all', get all properties. If WHICH is
10051 `special' or `standard', only get that subclass."
10052 (setq which (or which 'all))
10053 (org-with-point-at pom
10054 (let ((clockstr (substring org-clock-string 0 -1))
10055 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10056 beg end range props sum-props key value string clocksum)
10057 (save-excursion
10058 (when (condition-case nil (org-back-to-heading t) (error nil))
10059 (setq beg (point))
10060 (setq sum-props (get-text-property (point) 'org-summaries))
10061 (setq clocksum (get-text-property (point) :org-clock-minutes))
10062 (outline-next-heading)
10063 (setq end (point))
10064 (when (memq which '(all special))
10065 ;; Get the special properties, like TODO and tags
10066 (goto-char beg)
10067 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10068 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10069 (when (looking-at org-priority-regexp)
10070 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10071 (when (and (setq value (org-get-tags-string))
10072 (string-match "\\S-" value))
10073 (push (cons "TAGS" value) props))
10074 (when (setq value (org-get-tags-at))
10075 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10076 props))
10077 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10078 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10079 string (if (equal key clockstr)
10080 (org-no-properties
10081 (org-trim
10082 (buffer-substring
10083 (match-beginning 3) (goto-char (point-at-eol)))))
10084 (substring (org-match-string-no-properties 3) 1 -1)))
10085 (unless key
10086 (if (= (char-after (match-beginning 3)) ?\[)
10087 (setq key "TIMESTAMP_IA")
10088 (setq key "TIMESTAMP")))
10089 (when (or (equal key clockstr) (not (assoc key props)))
10090 (push (cons key string) props)))
10094 (when (memq which '(all standard))
10095 ;; Get the standard properties, like :PORP: ...
10096 (setq range (org-get-property-block beg end))
10097 (when range
10098 (goto-char (car range))
10099 (while (re-search-forward
10100 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10101 (cdr range) t)
10102 (setq key (org-match-string-no-properties 1)
10103 value (org-trim (or (org-match-string-no-properties 2) "")))
10104 (unless (member key excluded)
10105 (push (cons key (or value "")) props)))))
10106 (if clocksum
10107 (push (cons "CLOCKSUM"
10108 (org-columns-number-to-string (/ (float clocksum) 60.)
10109 'add_times))
10110 props))
10111 (unless (assoc "CATEGORY" props)
10112 (setq value (or (org-get-category)
10113 (progn (org-refresh-category-properties)
10114 (org-get-category))))
10115 (push (cons "CATEGORY" value) props))
10116 (append sum-props (nreverse props)))))))
10118 (defun org-entry-get (pom property &optional inherit)
10119 "Get value of PROPERTY for entry at point-or-marker POM.
10120 If INHERIT is non-nil and the entry does not have the property,
10121 then also check higher levels of the hierarchy.
10122 If INHERIT is the symbol `selective', use inheritance only if the setting
10123 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10124 If the property is present but empty, the return value is the empty string.
10125 If the property is not present at all, nil is returned."
10126 (org-with-point-at pom
10127 (if (and inherit (if (eq inherit 'selective)
10128 (org-property-inherit-p property)
10130 (org-entry-get-with-inheritance property)
10131 (if (member property org-special-properties)
10132 ;; We need a special property. Use brute force, get all properties.
10133 (cdr (assoc property (org-entry-properties nil 'special)))
10134 (let ((range (org-get-property-block)))
10135 (if (and range
10136 (goto-char (car range))
10137 (re-search-forward
10138 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10139 (cdr range) t))
10140 ;; Found the property, return it.
10141 (if (match-end 1)
10142 (org-match-string-no-properties 1)
10143 "")))))))
10145 (defun org-property-or-variable-value (var &optional inherit)
10146 "Check if there is a property fixing the value of VAR.
10147 If yes, return this value. If not, return the current value of the variable."
10148 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10149 (if (and prop (stringp prop) (string-match "\\S-" prop))
10150 (read prop)
10151 (symbol-value var))))
10153 (defun org-entry-delete (pom property)
10154 "Delete the property PROPERTY from entry at point-or-marker POM."
10155 (org-with-point-at pom
10156 (if (member property org-special-properties)
10157 nil ; cannot delete these properties.
10158 (let ((range (org-get-property-block)))
10159 (if (and range
10160 (goto-char (car range))
10161 (re-search-forward
10162 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10163 (cdr range) t))
10164 (progn
10165 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10167 nil)))))
10169 ;; Multi-values properties are properties that contain multiple values
10170 ;; These values are assumed to be single words, separated by whitespace.
10171 (defun org-entry-add-to-multivalued-property (pom property value)
10172 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10173 (let* ((old (org-entry-get pom property))
10174 (values (and old (org-split-string old "[ \t]"))))
10175 (setq value (org-entry-protect-space value))
10176 (unless (member value values)
10177 (setq values (cons value values))
10178 (org-entry-put pom property
10179 (mapconcat 'identity values " ")))))
10181 (defun org-entry-remove-from-multivalued-property (pom property value)
10182 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10183 (let* ((old (org-entry-get pom property))
10184 (values (and old (org-split-string old "[ \t]"))))
10185 (setq value (org-entry-protect-space value))
10186 (when (member value values)
10187 (setq values (delete value values))
10188 (org-entry-put pom property
10189 (mapconcat 'identity values " ")))))
10191 (defun org-entry-member-in-multivalued-property (pom property value)
10192 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10193 (let* ((old (org-entry-get pom property))
10194 (values (and old (org-split-string old "[ \t]"))))
10195 (setq value (org-entry-protect-space value))
10196 (member value values)))
10198 (defun org-entry-get-multivalued-property (pom property)
10199 "Return a list of values in a multivalued property."
10200 (let* ((value (org-entry-get pom property))
10201 (values (and value (org-split-string value "[ \t]"))))
10202 (mapcar 'org-entry-restore-space values)))
10204 (defun org-entry-put-multivalued-property (pom property &rest values)
10205 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10206 VALUES should be a list of strings. Spaces will be protected."
10207 (org-entry-put pom property
10208 (mapconcat 'org-entry-protect-space values " "))
10209 (let* ((value (org-entry-get pom property))
10210 (values (and value (org-split-string value "[ \t]"))))
10211 (mapcar 'org-entry-restore-space values)))
10213 (defun org-entry-protect-space (s)
10214 "Protect spaces and newline in string S."
10215 (while (string-match " " s)
10216 (setq s (replace-match "%20" t t s)))
10217 (while (string-match "\n" s)
10218 (setq s (replace-match "%0A" t t s)))
10221 (defun org-entry-restore-space (s)
10222 "Restore spaces and newline in string S."
10223 (while (string-match "%20" s)
10224 (setq s (replace-match " " t t s)))
10225 (while (string-match "%0A" s)
10226 (setq s (replace-match "\n" t t s)))
10229 (defvar org-entry-property-inherited-from (make-marker)
10230 "Marker pointing to the entry from where a proerty was inherited.
10231 Each call to `org-entry-get-with-inheritance' will set this marker to the
10232 location of the entry where the inheriance search matched. If there was
10233 no match, the marker will point nowhere.
10234 Note that also `org-entry-get' calls this function, if the INHERIT flag
10235 is set.")
10237 (defun org-entry-get-with-inheritance (property)
10238 "Get entry property, and search higher levels if not present."
10239 (move-marker org-entry-property-inherited-from nil)
10240 (let (tmp)
10241 (save-excursion
10242 (save-restriction
10243 (widen)
10244 (catch 'ex
10245 (while t
10246 (when (setq tmp (org-entry-get nil property))
10247 (org-back-to-heading t)
10248 (move-marker org-entry-property-inherited-from (point))
10249 (throw 'ex tmp))
10250 (or (org-up-heading-safe) (throw 'ex nil)))))
10251 (or tmp
10252 (cdr (assoc property org-file-properties))
10253 (cdr (assoc property org-global-properties))
10254 (cdr (assoc property org-global-properties-fixed))))))
10256 (defun org-entry-put (pom property value)
10257 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10258 (org-with-point-at pom
10259 (org-back-to-heading t)
10260 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10261 range)
10262 (cond
10263 ((equal property "TODO")
10264 (when (and (stringp value) (string-match "\\S-" value)
10265 (not (member value org-todo-keywords-1)))
10266 (error "\"%s\" is not a valid TODO state" value))
10267 (if (or (not value)
10268 (not (string-match "\\S-" value)))
10269 (setq value 'none))
10270 (org-todo value)
10271 (org-set-tags nil 'align))
10272 ((equal property "PRIORITY")
10273 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10274 (string-to-char value) ?\ ))
10275 (org-set-tags nil 'align))
10276 ((equal property "SCHEDULED")
10277 (if (re-search-forward org-scheduled-time-regexp end t)
10278 (cond
10279 ((eq value 'earlier) (org-timestamp-change -1 'day))
10280 ((eq value 'later) (org-timestamp-change 1 'day))
10281 (t (call-interactively 'org-schedule)))
10282 (call-interactively 'org-schedule)))
10283 ((equal property "DEADLINE")
10284 (if (re-search-forward org-deadline-time-regexp end t)
10285 (cond
10286 ((eq value 'earlier) (org-timestamp-change -1 'day))
10287 ((eq value 'later) (org-timestamp-change 1 'day))
10288 (t (call-interactively 'org-deadline)))
10289 (call-interactively 'org-deadline)))
10290 ((member property org-special-properties)
10291 (error "The %s property can not yet be set with `org-entry-put'"
10292 property))
10293 (t ; a non-special property
10294 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10295 (setq range (org-get-property-block beg end 'force))
10296 (goto-char (car range))
10297 (if (re-search-forward
10298 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10299 (progn
10300 (delete-region (match-beginning 1) (match-end 1))
10301 (goto-char (match-beginning 1)))
10302 (goto-char (cdr range))
10303 (insert "\n")
10304 (backward-char 1)
10305 (org-indent-line-function)
10306 (insert ":" property ":"))
10307 (and value (insert " " value))
10308 (org-indent-line-function)))))))
10310 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10311 "Get all property keys in the current buffer.
10312 With INCLUDE-SPECIALS, also list the special properties that relect things
10313 like tags and TODO state.
10314 With INCLUDE-DEFAULTS, also include properties that has special meaning
10315 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10316 With INCLUDE-COLUMNS, also include property names given in COLUMN
10317 formats in the current buffer."
10318 (let (rtn range cfmt cols s p)
10319 (save-excursion
10320 (save-restriction
10321 (widen)
10322 (goto-char (point-min))
10323 (while (re-search-forward org-property-start-re nil t)
10324 (setq range (org-get-property-block))
10325 (goto-char (car range))
10326 (while (re-search-forward
10327 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10328 (cdr range) t)
10329 (add-to-list 'rtn (org-match-string-no-properties 1)))
10330 (outline-next-heading))))
10332 (when include-specials
10333 (setq rtn (append org-special-properties rtn)))
10335 (when include-defaults
10336 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10338 (when include-columns
10339 (save-excursion
10340 (save-restriction
10341 (widen)
10342 (goto-char (point-min))
10343 (while (re-search-forward
10344 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10345 nil t)
10346 (setq cfmt (match-string 2) s 0)
10347 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10348 cfmt s)
10349 (setq s (match-end 0)
10350 p (match-string 1 cfmt))
10351 (unless (or (equal p "ITEM")
10352 (member p org-special-properties))
10353 (add-to-list 'rtn (match-string 1 cfmt))))))))
10355 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10357 (defun org-property-values (key)
10358 "Return a list of all values of property KEY."
10359 (save-excursion
10360 (save-restriction
10361 (widen)
10362 (goto-char (point-min))
10363 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10364 values)
10365 (while (re-search-forward re nil t)
10366 (add-to-list 'values (org-trim (match-string 1))))
10367 (delete "" values)))))
10369 (defun org-insert-property-drawer ()
10370 "Insert a property drawer into the current entry."
10371 (interactive)
10372 (org-back-to-heading t)
10373 (looking-at outline-regexp)
10374 (let ((indent (- (match-end 0)(match-beginning 0)))
10375 (beg (point))
10376 (re (concat "^[ \t]*" org-keyword-time-regexp))
10377 end hiddenp)
10378 (outline-next-heading)
10379 (setq end (point))
10380 (goto-char beg)
10381 (while (re-search-forward re end t))
10382 (setq hiddenp (org-invisible-p))
10383 (end-of-line 1)
10384 (and (equal (char-after) ?\n) (forward-char 1))
10385 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10386 (beginning-of-line 2))
10387 (org-skip-over-state-notes)
10388 (skip-chars-backward " \t\n\r")
10389 (if (eq (char-before) ?*) (forward-char 1))
10390 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10391 (beginning-of-line 0)
10392 (org-indent-to-column indent)
10393 (beginning-of-line 2)
10394 (org-indent-to-column indent)
10395 (beginning-of-line 0)
10396 (if hiddenp
10397 (save-excursion
10398 (org-back-to-heading t)
10399 (hide-entry))
10400 (org-flag-drawer t))))
10402 (defun org-set-property (property value)
10403 "In the current entry, set PROPERTY to VALUE.
10404 When called interactively, this will prompt for a property name, offering
10405 completion on existing and default properties. And then it will prompt
10406 for a value, offering competion either on allowed values (via an inherited
10407 xxx_ALL property) or on existing values in other instances of this property
10408 in the current file."
10409 (interactive
10410 (let* ((completion-ignore-case t)
10411 (keys (org-buffer-property-keys nil t t))
10412 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10413 (prop (if (member prop0 keys)
10414 prop0
10415 (or (cdr (assoc (downcase prop0)
10416 (mapcar (lambda (x) (cons (downcase x) x))
10417 keys)))
10418 prop0)))
10419 (cur (org-entry-get nil prop))
10420 (allowed (org-property-get-allowed-values nil prop 'table))
10421 (existing (mapcar 'list (org-property-values prop)))
10422 (val (if allowed
10423 (org-completing-read "Value: " allowed nil 'req-match)
10424 (org-completing-read
10425 (concat "Value" (if (and cur (string-match "\\S-" cur))
10426 (concat "[" cur "]") "")
10427 ": ")
10428 existing nil nil "" nil cur))))
10429 (list prop (if (equal val "") cur val))))
10430 (unless (equal (org-entry-get nil property) value)
10431 (org-entry-put nil property value)))
10433 (defun org-delete-property (property)
10434 "In the current entry, delete PROPERTY."
10435 (interactive
10436 (let* ((completion-ignore-case t)
10437 (prop (org-ido-completing-read
10438 "Property: " (org-entry-properties nil 'standard))))
10439 (list prop)))
10440 (message "Property %s %s" property
10441 (if (org-entry-delete nil property)
10442 "deleted"
10443 "was not present in the entry")))
10445 (defun org-delete-property-globally (property)
10446 "Remove PROPERTY globally, from all entries."
10447 (interactive
10448 (let* ((completion-ignore-case t)
10449 (prop (org-ido-completing-read
10450 "Globally remove property: "
10451 (mapcar 'list (org-buffer-property-keys)))))
10452 (list prop)))
10453 (save-excursion
10454 (save-restriction
10455 (widen)
10456 (goto-char (point-min))
10457 (let ((cnt 0))
10458 (while (re-search-forward
10459 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10460 nil t)
10461 (setq cnt (1+ cnt))
10462 (replace-match ""))
10463 (message "Property \"%s\" removed from %d entries" property cnt)))))
10465 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10467 (defun org-compute-property-at-point ()
10468 "Compute the property at point.
10469 This looks for an enclosing column format, extracts the operator and
10470 then applies it to the proerty in the column format's scope."
10471 (interactive)
10472 (unless (org-at-property-p)
10473 (error "Not at a property"))
10474 (let ((prop (org-match-string-no-properties 2)))
10475 (org-columns-get-format-and-top-level)
10476 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10477 (error "No operator defined for property %s" prop))
10478 (org-columns-compute prop)))
10480 (defun org-property-get-allowed-values (pom property &optional table)
10481 "Get allowed values for the property PROPERTY.
10482 When TABLE is non-nil, return an alist that can directly be used for
10483 completion."
10484 (let (vals)
10485 (cond
10486 ((equal property "TODO")
10487 (setq vals (org-with-point-at pom
10488 (append org-todo-keywords-1 '("")))))
10489 ((equal property "PRIORITY")
10490 (let ((n org-lowest-priority))
10491 (while (>= n org-highest-priority)
10492 (push (char-to-string n) vals)
10493 (setq n (1- n)))))
10494 ((member property org-special-properties))
10496 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10498 (when (and vals (string-match "\\S-" vals))
10499 (setq vals (car (read-from-string (concat "(" vals ")"))))
10500 (setq vals (mapcar (lambda (x)
10501 (cond ((stringp x) x)
10502 ((numberp x) (number-to-string x))
10503 ((symbolp x) (symbol-name x))
10504 (t "???")))
10505 vals)))))
10506 (if table (mapcar 'list vals) vals)))
10508 (defun org-property-previous-allowed-value (&optional previous)
10509 "Switch to the next allowed value for this property."
10510 (interactive)
10511 (org-property-next-allowed-value t))
10513 (defun org-property-next-allowed-value (&optional previous)
10514 "Switch to the next allowed value for this property."
10515 (interactive)
10516 (unless (org-at-property-p)
10517 (error "Not at a property"))
10518 (let* ((key (match-string 2))
10519 (value (match-string 3))
10520 (allowed (or (org-property-get-allowed-values (point) key)
10521 (and (member value '("[ ]" "[-]" "[X]"))
10522 '("[ ]" "[X]"))))
10523 nval)
10524 (unless allowed
10525 (error "Allowed values for this property have not been defined"))
10526 (if previous (setq allowed (reverse allowed)))
10527 (if (member value allowed)
10528 (setq nval (car (cdr (member value allowed)))))
10529 (setq nval (or nval (car allowed)))
10530 (if (equal nval value)
10531 (error "Only one allowed value for this property"))
10532 (org-at-property-p)
10533 (replace-match (concat " :" key ": " nval) t t)
10534 (org-indent-line-function)
10535 (beginning-of-line 1)
10536 (skip-chars-forward " \t")))
10538 (defun org-find-entry-with-id (ident)
10539 "Locate the entry that contains the ID property with exact value IDENT.
10540 IDENT can be a string, a symbol or a number, this function will search for
10541 the string representation of it.
10542 Return the position where this entry starts, or nil if there is no such entry."
10543 (let ((id (cond
10544 ((stringp ident) ident)
10545 ((symbol-name ident) (symbol-name ident))
10546 ((numberp ident) (number-to-string ident))
10547 (t (error "IDENT %s must be a string, symbol or number" ident))))
10548 (case-fold-search nil))
10549 (save-excursion
10550 (save-restriction
10551 (widen)
10552 (goto-char (point-min))
10553 (when (re-search-forward
10554 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10555 nil t)
10556 (org-back-to-heading)
10557 (point))))))
10559 ;;;; Timestamps
10561 (defvar org-last-changed-timestamp nil)
10562 (defvar org-last-inserted-timestamp nil
10563 "The last time stamp inserted with `org-insert-time-stamp'.")
10564 (defvar org-time-was-given) ; dynamically scoped parameter
10565 (defvar org-end-time-was-given) ; dynamically scoped parameter
10566 (defvar org-ts-what) ; dynamically scoped parameter
10568 (defun org-time-stamp (arg &optional inactive)
10569 "Prompt for a date/time and insert a time stamp.
10570 If the user specifies a time like HH:MM, or if this command is called
10571 with a prefix argument, the time stamp will contain date and time.
10572 Otherwise, only the date will be included. All parts of a date not
10573 specified by the user will be filled in from the current date/time.
10574 So if you press just return without typing anything, the time stamp
10575 will represent the current date/time. If there is already a timestamp
10576 at the cursor, it will be modified."
10577 (interactive "P")
10578 (let* ((ts nil)
10579 (default-time
10580 ;; Default time is either today, or, when entering a range,
10581 ;; the range start.
10582 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10583 (save-excursion
10584 (re-search-backward
10585 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10586 (- (point) 20) t)))
10587 (apply 'encode-time (org-parse-time-string (match-string 1)))
10588 (current-time)))
10589 (default-input (and ts (org-get-compact-tod ts)))
10590 org-time-was-given org-end-time-was-given time)
10591 (cond
10592 ((and (org-at-timestamp-p t)
10593 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10594 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10595 (insert "--")
10596 (setq time (let ((this-command this-command))
10597 (org-read-date arg 'totime nil nil
10598 default-time default-input)))
10599 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10600 ((org-at-timestamp-p t)
10601 (setq time (let ((this-command this-command))
10602 (org-read-date arg 'totime nil nil default-time default-input)))
10603 (when (org-at-timestamp-p t) ; just to get the match data
10604 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10605 (replace-match "")
10606 (setq org-last-changed-timestamp
10607 (org-insert-time-stamp
10608 time (or org-time-was-given arg)
10609 inactive nil nil (list org-end-time-was-given))))
10610 (message "Timestamp updated"))
10612 (setq time (let ((this-command this-command))
10613 (org-read-date arg 'totime nil nil default-time default-input)))
10614 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10615 nil nil (list org-end-time-was-given))))))
10617 ;; FIXME: can we use this for something else, like computing time differences?
10618 (defun org-get-compact-tod (s)
10619 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10620 (let* ((t1 (match-string 1 s))
10621 (h1 (string-to-number (match-string 2 s)))
10622 (m1 (string-to-number (match-string 3 s)))
10623 (t2 (and (match-end 4) (match-string 5 s)))
10624 (h2 (and t2 (string-to-number (match-string 6 s))))
10625 (m2 (and t2 (string-to-number (match-string 7 s))))
10626 dh dm)
10627 (if (not t2)
10629 (setq dh (- h2 h1) dm (- m2 m1))
10630 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10631 (concat t1 "+" (number-to-string dh)
10632 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10634 (defun org-time-stamp-inactive (&optional arg)
10635 "Insert an inactive time stamp.
10636 An inactive time stamp is enclosed in square brackets instead of angle
10637 brackets. It is inactive in the sense that it does not trigger agenda entries,
10638 does not link to the calendar and cannot be changed with the S-cursor keys.
10639 So these are more for recording a certain time/date."
10640 (interactive "P")
10641 (org-time-stamp arg 'inactive))
10643 (defvar org-date-ovl (org-make-overlay 1 1))
10644 (org-overlay-put org-date-ovl 'face 'org-warning)
10645 (org-detach-overlay org-date-ovl)
10647 (defvar org-ans1) ; dynamically scoped parameter
10648 (defvar org-ans2) ; dynamically scoped parameter
10650 (defvar org-plain-time-of-day-regexp) ; defined below
10652 (defvar org-overriding-default-time nil) ; dynamically scoped
10653 (defvar org-read-date-overlay nil)
10654 (defvar org-dcst nil) ; dynamically scoped
10656 (defun org-read-date (&optional with-time to-time from-string prompt
10657 default-time default-input)
10658 "Read a date, possibly a time, and make things smooth for the user.
10659 The prompt will suggest to enter an ISO date, but you can also enter anything
10660 which will at least partially be understood by `parse-time-string'.
10661 Unrecognized parts of the date will default to the current day, month, year,
10662 hour and minute. If this command is called to replace a timestamp at point,
10663 of to enter the second timestamp of a range, the default time is taken from the
10664 existing stamp. For example,
10665 3-2-5 --> 2003-02-05
10666 feb 15 --> currentyear-02-15
10667 sep 12 9 --> 2009-09-12
10668 12:45 --> today 12:45
10669 22 sept 0:34 --> currentyear-09-22 0:34
10670 12 --> currentyear-currentmonth-12
10671 Fri --> nearest Friday (today or later)
10672 etc.
10674 Furthermore you can specify a relative date by giving, as the *first* thing
10675 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10676 change in days weeks, months, years.
10677 With a single plus or minus, the date is relative to today. With a double
10678 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10679 +4d --> four days from today
10680 +4 --> same as above
10681 +2w --> two weeks from today
10682 ++5 --> five days from default date
10684 The function understands only English month and weekday abbreviations,
10685 but this can be configured with the variables `parse-time-months' and
10686 `parse-time-weekdays'.
10688 While prompting, a calendar is popped up - you can also select the
10689 date with the mouse (button 1). The calendar shows a period of three
10690 months. To scroll it to other months, use the keys `>' and `<'.
10691 If you don't like the calendar, turn it off with
10692 \(setq org-read-date-popup-calendar nil)
10694 With optional argument TO-TIME, the date will immediately be converted
10695 to an internal time.
10696 With an optional argument WITH-TIME, the prompt will suggest to also
10697 insert a time. Note that when WITH-TIME is not set, you can still
10698 enter a time, and this function will inform the calling routine about
10699 this change. The calling routine may then choose to change the format
10700 used to insert the time stamp into the buffer to include the time.
10701 With optional argument FROM-STRING, read from this string instead from
10702 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10703 the time/date that is used for everything that is not specified by the
10704 user."
10705 (require 'parse-time)
10706 (let* ((org-time-stamp-rounding-minutes
10707 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10708 (org-dcst org-display-custom-times)
10709 (ct (org-current-time))
10710 (def (or org-overriding-default-time default-time ct))
10711 (defdecode (decode-time def))
10712 (dummy (progn
10713 (when (< (nth 2 defdecode) org-extend-today-until)
10714 (setcar (nthcdr 2 defdecode) -1)
10715 (setcar (nthcdr 1 defdecode) 59)
10716 (setq def (apply 'encode-time defdecode)
10717 defdecode (decode-time def)))))
10718 (calendar-move-hook nil)
10719 (calendar-view-diary-initially-flag nil)
10720 (view-diary-entries-initially nil)
10721 (calendar-view-holidays-initially-flag nil)
10722 (view-calendar-holidays-initially nil)
10723 (timestr (format-time-string
10724 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10725 (prompt (concat (if prompt (concat prompt " ") "")
10726 (format "Date+time [%s]: " timestr)))
10727 ans (org-ans0 "") org-ans1 org-ans2 final)
10729 (cond
10730 (from-string (setq ans from-string))
10731 (org-read-date-popup-calendar
10732 (save-excursion
10733 (save-window-excursion
10734 (calendar)
10735 (calendar-forward-day (- (time-to-days def)
10736 (calendar-absolute-from-gregorian
10737 (calendar-current-date))))
10738 (org-eval-in-calendar nil t)
10739 (let* ((old-map (current-local-map))
10740 (map (copy-keymap calendar-mode-map))
10741 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10742 (org-defkey map (kbd "RET") 'org-calendar-select)
10743 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10744 'org-calendar-select-mouse)
10745 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10746 'org-calendar-select-mouse)
10747 (org-defkey minibuffer-local-map [(meta shift left)]
10748 (lambda () (interactive)
10749 (org-eval-in-calendar '(calendar-backward-month 1))))
10750 (org-defkey minibuffer-local-map [(meta shift right)]
10751 (lambda () (interactive)
10752 (org-eval-in-calendar '(calendar-forward-month 1))))
10753 (org-defkey minibuffer-local-map [(meta shift up)]
10754 (lambda () (interactive)
10755 (org-eval-in-calendar '(calendar-backward-year 1))))
10756 (org-defkey minibuffer-local-map [(meta shift down)]
10757 (lambda () (interactive)
10758 (org-eval-in-calendar '(calendar-forward-year 1))))
10759 (org-defkey minibuffer-local-map [(shift up)]
10760 (lambda () (interactive)
10761 (org-eval-in-calendar '(calendar-backward-week 1))))
10762 (org-defkey minibuffer-local-map [(shift down)]
10763 (lambda () (interactive)
10764 (org-eval-in-calendar '(calendar-forward-week 1))))
10765 (org-defkey minibuffer-local-map [(shift left)]
10766 (lambda () (interactive)
10767 (org-eval-in-calendar '(calendar-backward-day 1))))
10768 (org-defkey minibuffer-local-map [(shift right)]
10769 (lambda () (interactive)
10770 (org-eval-in-calendar '(calendar-forward-day 1))))
10771 (org-defkey minibuffer-local-map ">"
10772 (lambda () (interactive)
10773 (org-eval-in-calendar '(scroll-calendar-left 1))))
10774 (org-defkey minibuffer-local-map "<"
10775 (lambda () (interactive)
10776 (org-eval-in-calendar '(scroll-calendar-right 1))))
10777 (unwind-protect
10778 (progn
10779 (use-local-map map)
10780 (add-hook 'post-command-hook 'org-read-date-display)
10781 (setq org-ans0 (read-string prompt default-input nil nil))
10782 ;; org-ans0: from prompt
10783 ;; org-ans1: from mouse click
10784 ;; org-ans2: from calendar motion
10785 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10786 (remove-hook 'post-command-hook 'org-read-date-display)
10787 (use-local-map old-map)
10788 (when org-read-date-overlay
10789 (org-delete-overlay org-read-date-overlay)
10790 (setq org-read-date-overlay nil)))))))
10792 (t ; Naked prompt only
10793 (unwind-protect
10794 (setq ans (read-string prompt default-input nil timestr))
10795 (when org-read-date-overlay
10796 (org-delete-overlay org-read-date-overlay)
10797 (setq org-read-date-overlay nil)))))
10799 (setq final (org-read-date-analyze ans def defdecode))
10801 (if to-time
10802 (apply 'encode-time final)
10803 (if (and (boundp 'org-time-was-given) org-time-was-given)
10804 (format "%04d-%02d-%02d %02d:%02d"
10805 (nth 5 final) (nth 4 final) (nth 3 final)
10806 (nth 2 final) (nth 1 final))
10807 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10808 (defvar def)
10809 (defvar defdecode)
10810 (defvar with-time)
10811 (defun org-read-date-display ()
10812 "Display the currrent date prompt interpretation in the minibuffer."
10813 (when org-read-date-display-live
10814 (when org-read-date-overlay
10815 (org-delete-overlay org-read-date-overlay))
10816 (let ((p (point)))
10817 (end-of-line 1)
10818 (while (not (equal (buffer-substring
10819 (max (point-min) (- (point) 4)) (point))
10820 " "))
10821 (insert " "))
10822 (goto-char p))
10823 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10824 " " (or org-ans1 org-ans2)))
10825 (org-end-time-was-given nil)
10826 (f (org-read-date-analyze ans def defdecode))
10827 (fmts (if org-dcst
10828 org-time-stamp-custom-formats
10829 org-time-stamp-formats))
10830 (fmt (if (or with-time
10831 (and (boundp 'org-time-was-given) org-time-was-given))
10832 (cdr fmts)
10833 (car fmts)))
10834 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10835 (when (and org-end-time-was-given
10836 (string-match org-plain-time-of-day-regexp txt))
10837 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10838 org-end-time-was-given
10839 (substring txt (match-end 0)))))
10840 (setq org-read-date-overlay
10841 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10842 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10844 (defun org-read-date-analyze (ans def defdecode)
10845 "Analyze the combined answer of the date prompt."
10846 ;; FIXME: cleanup and comment
10847 (let (delta deltan deltaw deltadef year month day
10848 hour minute second wday pm h2 m2 tl wday1
10849 iso-year iso-weekday iso-week iso-year iso-date)
10851 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10852 (setq ans "+0"))
10854 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10855 (setq ans (replace-match "" t t ans)
10856 deltan (car delta)
10857 deltaw (nth 1 delta)
10858 deltadef (nth 2 delta)))
10860 ;; Check if there is an iso week date in there
10861 ;; If yes, sore the info and ostpone interpreting it until the rest
10862 ;; of the parsing is done
10863 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10864 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10865 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10866 iso-week (string-to-number (match-string 2 ans)))
10867 (setq ans (replace-match "" t t ans)))
10869 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10870 (when (string-match
10871 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10872 (setq year (if (match-end 2)
10873 (string-to-number (match-string 2 ans))
10874 (string-to-number (format-time-string "%Y")))
10875 month (string-to-number (match-string 3 ans))
10876 day (string-to-number (match-string 4 ans)))
10877 (if (< year 100) (setq year (+ 2000 year)))
10878 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10879 t nil ans)))
10880 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10881 ;; If there is a time with am/pm, and *no* time without it, we convert
10882 ;; so that matching will be successful.
10883 (loop for i from 1 to 2 do ; twice, for end time as well
10884 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10885 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10886 (setq hour (string-to-number (match-string 1 ans))
10887 minute (if (match-end 3)
10888 (string-to-number (match-string 3 ans))
10890 pm (equal ?p
10891 (string-to-char (downcase (match-string 4 ans)))))
10892 (if (and (= hour 12) (not pm))
10893 (setq hour 0)
10894 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10895 (setq ans (replace-match (format "%02d:%02d" hour minute)
10896 t t ans))))
10898 ;; Check if a time range is given as a duration
10899 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10900 (setq hour (string-to-number (match-string 1 ans))
10901 h2 (+ hour (string-to-number (match-string 3 ans)))
10902 minute (string-to-number (match-string 2 ans))
10903 m2 (+ minute (if (match-end 5) (string-to-number
10904 (match-string 5 ans))0)))
10905 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10906 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10907 t t ans)))
10909 ;; Check if there is a time range
10910 (when (boundp 'org-end-time-was-given)
10911 (setq org-time-was-given nil)
10912 (when (and (string-match org-plain-time-of-day-regexp ans)
10913 (match-end 8))
10914 (setq org-end-time-was-given (match-string 8 ans))
10915 (setq ans (concat (substring ans 0 (match-beginning 7))
10916 (substring ans (match-end 7))))))
10918 (setq tl (parse-time-string ans)
10919 day (or (nth 3 tl) (nth 3 defdecode))
10920 month (or (nth 4 tl)
10921 (if (and org-read-date-prefer-future
10922 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10923 (1+ (nth 4 defdecode))
10924 (nth 4 defdecode)))
10925 year (or (nth 5 tl)
10926 (if (and org-read-date-prefer-future
10927 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10928 (1+ (nth 5 defdecode))
10929 (nth 5 defdecode)))
10930 hour (or (nth 2 tl) (nth 2 defdecode))
10931 minute (or (nth 1 tl) (nth 1 defdecode))
10932 second (or (nth 0 tl) 0)
10933 wday (nth 6 tl))
10935 ;; Special date definitions below
10936 (cond
10937 (iso-week
10938 ;; There was an iso week
10939 (setq year (or iso-year year)
10940 day (or iso-weekday wday 1)
10941 wday nil ; to make sure that the trigger below does not match
10942 iso-date (calendar-gregorian-from-absolute
10943 (calendar-absolute-from-iso
10944 (list iso-week day year))))
10945 ; FIXME: Should we also push ISO weeks into the future?
10946 ; (when (and org-read-date-prefer-future
10947 ; (not iso-year)
10948 ; (< (calendar-absolute-from-gregorian iso-date)
10949 ; (time-to-days (current-time))))
10950 ; (setq year (1+ year)
10951 ; iso-date (calendar-gregorian-from-absolute
10952 ; (calendar-absolute-from-iso
10953 ; (list iso-week day year)))))
10954 (setq month (car iso-date)
10955 year (nth 2 iso-date)
10956 day (nth 1 iso-date)))
10957 (deltan
10958 (unless deltadef
10959 (let ((now (decode-time (current-time))))
10960 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10961 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10962 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10963 ((equal deltaw "m") (setq month (+ month deltan)))
10964 ((equal deltaw "y") (setq year (+ year deltan)))))
10965 ((and wday (not (nth 3 tl)))
10966 ;; Weekday was given, but no day, so pick that day in the week
10967 ;; on or after the derived date.
10968 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10969 (unless (equal wday wday1)
10970 (setq day (+ day (% (- wday wday1 -7) 7))))))
10971 (if (and (boundp 'org-time-was-given)
10972 (nth 2 tl))
10973 (setq org-time-was-given t))
10974 (if (< year 100) (setq year (+ 2000 year)))
10975 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10976 (list second minute hour day month year)))
10978 (defvar parse-time-weekdays)
10980 (defun org-read-date-get-relative (s today default)
10981 "Check string S for special relative date string.
10982 TODAY and DEFAULT are internal times, for today and for a default.
10983 Return shift list (N what def-flag)
10984 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10985 N is the number of WHATs to shift.
10986 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10987 the DEFAULT date rather than TODAY."
10988 (when (and
10989 (string-match
10990 (concat
10991 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10992 "\\([0-9]+\\)?"
10993 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10994 "\\([ \t]\\|$\\)") s)
10995 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10996 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10997 (string-to-char (substring (match-string 1 s) -1))
10998 ?+))
10999 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11000 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11001 (what (if (match-end 3) (match-string 3 s) "d"))
11002 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11003 (date (if rel default today))
11004 (wday (nth 6 (decode-time date)))
11005 delta)
11006 (if wday1
11007 (progn
11008 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11009 (if (= dir ?-) (setq delta (- delta 7)))
11010 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11011 (list delta "d" rel))
11012 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11014 (defun org-eval-in-calendar (form &optional keepdate)
11015 "Eval FORM in the calendar window and return to current window.
11016 Also, store the cursor date in variable org-ans2."
11017 (let ((sw (selected-window)))
11018 (select-window (get-buffer-window "*Calendar*"))
11019 (eval form)
11020 (when (and (not keepdate) (calendar-cursor-to-date))
11021 (let* ((date (calendar-cursor-to-date))
11022 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11023 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11024 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11025 (select-window sw)))
11027 (defun org-calendar-select ()
11028 "Return to `org-read-date' with the date currently selected.
11029 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11030 (interactive)
11031 (when (calendar-cursor-to-date)
11032 (let* ((date (calendar-cursor-to-date))
11033 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11034 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11035 (if (active-minibuffer-window) (exit-minibuffer))))
11037 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11038 "Insert a date stamp for the date given by the internal TIME.
11039 WITH-HM means, use the stamp format that includes the time of the day.
11040 INACTIVE means use square brackets instead of angular ones, so that the
11041 stamp will not contribute to the agenda.
11042 PRE and POST are optional strings to be inserted before and after the
11043 stamp.
11044 The command returns the inserted time stamp."
11045 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11046 stamp)
11047 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11048 (insert-before-markers (or pre ""))
11049 (insert-before-markers (setq stamp (format-time-string fmt time)))
11050 (when (listp extra)
11051 (setq extra (car extra))
11052 (if (and (stringp extra)
11053 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11054 (setq extra (format "-%02d:%02d"
11055 (string-to-number (match-string 1 extra))
11056 (string-to-number (match-string 2 extra))))
11057 (setq extra nil)))
11058 (when extra
11059 (backward-char 1)
11060 (insert-before-markers extra)
11061 (forward-char 1))
11062 (insert-before-markers (or post ""))
11063 (setq org-last-inserted-timestamp stamp)))
11065 (defun org-toggle-time-stamp-overlays ()
11066 "Toggle the use of custom time stamp formats."
11067 (interactive)
11068 (setq org-display-custom-times (not org-display-custom-times))
11069 (unless org-display-custom-times
11070 (let ((p (point-min)) (bmp (buffer-modified-p)))
11071 (while (setq p (next-single-property-change p 'display))
11072 (if (and (get-text-property p 'display)
11073 (eq (get-text-property p 'face) 'org-date))
11074 (remove-text-properties
11075 p (setq p (next-single-property-change p 'display))
11076 '(display t))))
11077 (set-buffer-modified-p bmp)))
11078 (if (featurep 'xemacs)
11079 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11080 (org-restart-font-lock)
11081 (setq org-table-may-need-update t)
11082 (if org-display-custom-times
11083 (message "Time stamps are overlayed with custom format")
11084 (message "Time stamp overlays removed")))
11086 (defun org-display-custom-time (beg end)
11087 "Overlay modified time stamp format over timestamp between BEG and END."
11088 (let* ((ts (buffer-substring beg end))
11089 t1 w1 with-hm tf time str w2 (off 0))
11090 (save-match-data
11091 (setq t1 (org-parse-time-string ts t))
11092 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11093 (setq off (- (match-end 0) (match-beginning 0)))))
11094 (setq end (- end off))
11095 (setq w1 (- end beg)
11096 with-hm (and (nth 1 t1) (nth 2 t1))
11097 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11098 time (org-fix-decoded-time t1)
11099 str (org-add-props
11100 (format-time-string
11101 (substring tf 1 -1) (apply 'encode-time time))
11102 nil 'mouse-face 'highlight)
11103 w2 (length str))
11104 (if (not (= w2 w1))
11105 (add-text-properties (1+ beg) (+ 2 beg)
11106 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11107 (if (featurep 'xemacs)
11108 (progn
11109 (put-text-property beg end 'invisible t)
11110 (put-text-property beg end 'end-glyph (make-glyph str)))
11111 (put-text-property beg end 'display str))))
11113 (defun org-translate-time (string)
11114 "Translate all timestamps in STRING to custom format.
11115 But do this only if the variable `org-display-custom-times' is set."
11116 (when org-display-custom-times
11117 (save-match-data
11118 (let* ((start 0)
11119 (re org-ts-regexp-both)
11120 t1 with-hm inactive tf time str beg end)
11121 (while (setq start (string-match re string start))
11122 (setq beg (match-beginning 0)
11123 end (match-end 0)
11124 t1 (save-match-data
11125 (org-parse-time-string (substring string beg end) t))
11126 with-hm (and (nth 1 t1) (nth 2 t1))
11127 inactive (equal (substring string beg (1+ beg)) "[")
11128 tf (funcall (if with-hm 'cdr 'car)
11129 org-time-stamp-custom-formats)
11130 time (org-fix-decoded-time t1)
11131 str (format-time-string
11132 (concat
11133 (if inactive "[" "<") (substring tf 1 -1)
11134 (if inactive "]" ">"))
11135 (apply 'encode-time time))
11136 string (replace-match str t t string)
11137 start (+ start (length str)))))))
11138 string)
11140 (defun org-fix-decoded-time (time)
11141 "Set 0 instead of nil for the first 6 elements of time.
11142 Don't touch the rest."
11143 (let ((n 0))
11144 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11146 (defun org-days-to-time (timestamp-string)
11147 "Difference between TIMESTAMP-STRING and now in days."
11148 (- (time-to-days (org-time-string-to-time timestamp-string))
11149 (time-to-days (current-time))))
11151 (defun org-deadline-close (timestamp-string &optional ndays)
11152 "Is the time in TIMESTAMP-STRING close to the current date?"
11153 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11154 (and (< (org-days-to-time timestamp-string) ndays)
11155 (not (org-entry-is-done-p))))
11157 (defun org-get-wdays (ts)
11158 "Get the deadline lead time appropriate for timestring TS."
11159 (cond
11160 ((<= org-deadline-warning-days 0)
11161 ;; 0 or negative, enforce this value no matter what
11162 (- org-deadline-warning-days))
11163 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11164 ;; lead time is specified.
11165 (floor (* (string-to-number (match-string 1 ts))
11166 (cdr (assoc (match-string 2 ts)
11167 '(("d" . 1) ("w" . 7)
11168 ("m" . 30.4) ("y" . 365.25)))))))
11169 ;; go for the default.
11170 (t org-deadline-warning-days)))
11172 (defun org-calendar-select-mouse (ev)
11173 "Return to `org-read-date' with the date currently selected.
11174 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11175 (interactive "e")
11176 (mouse-set-point ev)
11177 (when (calendar-cursor-to-date)
11178 (let* ((date (calendar-cursor-to-date))
11179 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11180 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11181 (if (active-minibuffer-window) (exit-minibuffer))))
11183 (defun org-check-deadlines (ndays)
11184 "Check if there are any deadlines due or past due.
11185 A deadline is considered due if it happens within `org-deadline-warning-days'
11186 days from today's date. If the deadline appears in an entry marked DONE,
11187 it is not shown. The prefix arg NDAYS can be used to test that many
11188 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11189 (interactive "P")
11190 (let* ((org-warn-days
11191 (cond
11192 ((equal ndays '(4)) 100000)
11193 (ndays (prefix-numeric-value ndays))
11194 (t (abs org-deadline-warning-days))))
11195 (case-fold-search nil)
11196 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11197 (callback
11198 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11200 (message "%d deadlines past-due or due within %d days"
11201 (org-occur regexp nil callback)
11202 org-warn-days)))
11204 (defun org-check-before-date (date)
11205 "Check if there are deadlines or scheduled entries before DATE."
11206 (interactive (list (org-read-date)))
11207 (let ((case-fold-search nil)
11208 (regexp (concat "\\<\\(" org-deadline-string
11209 "\\|" org-scheduled-string
11210 "\\) *<\\([^>]+\\)>"))
11211 (callback
11212 (lambda () (time-less-p
11213 (org-time-string-to-time (match-string 2))
11214 (org-time-string-to-time date)))))
11215 (message "%d entries before %s"
11216 (org-occur regexp nil callback) date)))
11218 (defun org-evaluate-time-range (&optional to-buffer)
11219 "Evaluate a time range by computing the difference between start and end.
11220 Normally the result is just printed in the echo area, but with prefix arg
11221 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11222 If the time range is actually in a table, the result is inserted into the
11223 next column.
11224 For time difference computation, a year is assumed to be exactly 365
11225 days in order to avoid rounding problems."
11226 (interactive "P")
11228 (org-clock-update-time-maybe)
11229 (save-excursion
11230 (unless (org-at-date-range-p t)
11231 (goto-char (point-at-bol))
11232 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11233 (if (not (org-at-date-range-p t))
11234 (error "Not at a time-stamp range, and none found in current line")))
11235 (let* ((ts1 (match-string 1))
11236 (ts2 (match-string 2))
11237 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11238 (match-end (match-end 0))
11239 (time1 (org-time-string-to-time ts1))
11240 (time2 (org-time-string-to-time ts2))
11241 (t1 (time-to-seconds time1))
11242 (t2 (time-to-seconds time2))
11243 (diff (abs (- t2 t1)))
11244 (negative (< (- t2 t1) 0))
11245 ;; (ys (floor (* 365 24 60 60)))
11246 (ds (* 24 60 60))
11247 (hs (* 60 60))
11248 (fy "%dy %dd %02d:%02d")
11249 (fy1 "%dy %dd")
11250 (fd "%dd %02d:%02d")
11251 (fd1 "%dd")
11252 (fh "%02d:%02d")
11253 y d h m align)
11254 (if havetime
11255 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11257 d (floor (/ diff ds)) diff (mod diff ds)
11258 h (floor (/ diff hs)) diff (mod diff hs)
11259 m (floor (/ diff 60)))
11260 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11262 d (floor (+ (/ diff ds) 0.5))
11263 h 0 m 0))
11264 (if (not to-buffer)
11265 (message "%s" (org-make-tdiff-string y d h m))
11266 (if (org-at-table-p)
11267 (progn
11268 (goto-char match-end)
11269 (setq align t)
11270 (and (looking-at " *|") (goto-char (match-end 0))))
11271 (goto-char match-end))
11272 (if (looking-at
11273 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11274 (replace-match ""))
11275 (if negative (insert " -"))
11276 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11277 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11278 (insert " " (format fh h m))))
11279 (if align (org-table-align))
11280 (message "Time difference inserted")))))
11282 (defun org-make-tdiff-string (y d h m)
11283 (let ((fmt "")
11284 (l nil))
11285 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11286 l (push y l)))
11287 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11288 l (push d l)))
11289 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11290 l (push h l)))
11291 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11292 l (push m l)))
11293 (apply 'format fmt (nreverse l))))
11295 (defun org-time-string-to-time (s)
11296 (apply 'encode-time (org-parse-time-string s)))
11298 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11299 "Convert a time stamp to an absolute day number.
11300 If there is a specifyer for a cyclic time stamp, get the closest date to
11301 DAYNR.
11302 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11303 (cond
11304 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11305 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11306 daynr
11307 (+ daynr 1000)))
11308 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11309 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11310 (time-to-days (current-time))) (match-string 0 s)
11311 prefer show-all))
11312 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11314 (defun org-days-to-iso-week (days)
11315 "Return the iso week number."
11316 (require 'cal-iso)
11317 (car (calendar-iso-from-absolute days)))
11319 (defun org-small-year-to-year (year)
11320 "Convert 2-digit years into 4-digit years.
11321 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11322 The year 2000 cannot be abbreviated. Any year larger than 99
11323 is returned unchanged."
11324 (if (< year 38)
11325 (setq year (+ 2000 year))
11326 (if (< year 100)
11327 (setq year (+ 1900 year))))
11328 year)
11330 (defun org-time-from-absolute (d)
11331 "Return the time corresponding to date D.
11332 D may be an absolute day number, or a calendar-type list (month day year)."
11333 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11334 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11336 (defun org-calendar-holiday ()
11337 "List of holidays, for Diary display in Org-mode."
11338 (require 'holidays)
11339 (let ((hl (funcall
11340 (if (fboundp 'calendar-check-holidays)
11341 'calendar-check-holidays 'check-calendar-holidays) date)))
11342 (if hl (mapconcat 'identity hl "; "))))
11344 (defun org-diary-sexp-entry (sexp entry date)
11345 "Process a SEXP diary ENTRY for DATE."
11346 (require 'diary-lib)
11347 (let ((result (if calendar-debug-sexp
11348 (let ((stack-trace-on-error t))
11349 (eval (car (read-from-string sexp))))
11350 (condition-case nil
11351 (eval (car (read-from-string sexp)))
11352 (error
11353 (beep)
11354 (message "Bad sexp at line %d in %s: %s"
11355 (org-current-line)
11356 (buffer-file-name) sexp)
11357 (sleep-for 2))))))
11358 (cond ((stringp result) result)
11359 ((and (consp result)
11360 (stringp (cdr result))) (cdr result))
11361 (result entry)
11362 (t nil))))
11364 (defun org-diary-to-ical-string (frombuf)
11365 "Get iCalendar entries from diary entries in buffer FROMBUF.
11366 This uses the icalendar.el library."
11367 (let* ((tmpdir (if (featurep 'xemacs)
11368 (temp-directory)
11369 temporary-file-directory))
11370 (tmpfile (make-temp-name
11371 (expand-file-name "orgics" tmpdir)))
11372 buf rtn b e)
11373 (save-excursion
11374 (set-buffer frombuf)
11375 (icalendar-export-region (point-min) (point-max) tmpfile)
11376 (setq buf (find-buffer-visiting tmpfile))
11377 (set-buffer buf)
11378 (goto-char (point-min))
11379 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11380 (setq b (match-beginning 0)))
11381 (goto-char (point-max))
11382 (if (re-search-backward "^END:VEVENT" nil t)
11383 (setq e (match-end 0)))
11384 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11385 (kill-buffer buf)
11386 (delete-file tmpfile)
11387 rtn))
11389 (defun org-closest-date (start current change prefer show-all)
11390 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11391 When PREFER is `past' return a date that is either CURRENT or past.
11392 When PREFER is `future', return a date that is either CURRENT or future.
11393 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11394 ;; Make the proper lists from the dates
11395 (catch 'exit
11396 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11397 dn dw sday cday n1 n2
11398 d m y y1 y2 date1 date2 nmonths nm ny m2)
11400 (setq start (org-date-to-gregorian start)
11401 current (org-date-to-gregorian
11402 (if show-all
11403 current
11404 (time-to-days (current-time))))
11405 sday (calendar-absolute-from-gregorian start)
11406 cday (calendar-absolute-from-gregorian current))
11408 (if (<= cday sday) (throw 'exit sday))
11410 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11411 (setq dn (string-to-number (match-string 1 change))
11412 dw (cdr (assoc (match-string 2 change) a1)))
11413 (error "Invalid change specifyer: %s" change))
11414 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11415 (cond
11416 ((eq dw 'day)
11417 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11418 n2 (+ n1 dn)))
11419 ((eq dw 'year)
11420 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11421 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11422 (setq date1 (list m d y1)
11423 n1 (calendar-absolute-from-gregorian date1)
11424 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11425 n2 (calendar-absolute-from-gregorian date2)))
11426 ((eq dw 'month)
11427 ;; approx number of month between the two dates
11428 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11429 ;; How often does dn fit in there?
11430 (setq d (nth 1 start) m (car start) y (nth 2 start)
11431 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11432 m (+ m nm)
11433 ny (floor (/ m 12))
11434 y (+ y ny)
11435 m (- m (* ny 12)))
11436 (while (> m 12) (setq m (- m 12) y (1+ y)))
11437 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11438 (setq m2 (+ m dn) y2 y)
11439 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11440 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11441 (while (<= n2 cday)
11442 (setq n1 n2 m m2 y y2)
11443 (setq m2 (+ m dn) y2 y)
11444 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11445 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11446 (if show-all
11447 (cond
11448 ((eq prefer 'past) n1)
11449 ((eq prefer 'future) (if (= cday n1) n1 n2))
11450 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11451 (cond
11452 ((eq prefer 'past) n1)
11453 ((eq prefer 'future) (if (= cday n1) n1 n2))
11454 (t (if (= cday n1) n1 n2)))))))
11456 (defun org-date-to-gregorian (date)
11457 "Turn any specification of DATE into a gregorian date for the calendar."
11458 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11459 ((and (listp date) (= (length date) 3)) date)
11460 ((stringp date)
11461 (setq date (org-parse-time-string date))
11462 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11463 ((listp date)
11464 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11466 (defun org-parse-time-string (s &optional nodefault)
11467 "Parse the standard Org-mode time string.
11468 This should be a lot faster than the normal `parse-time-string'.
11469 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11470 hour and minute fields will be nil if not given."
11471 (if (string-match org-ts-regexp0 s)
11472 (list 0
11473 (if (or (match-beginning 8) (not nodefault))
11474 (string-to-number (or (match-string 8 s) "0")))
11475 (if (or (match-beginning 7) (not nodefault))
11476 (string-to-number (or (match-string 7 s) "0")))
11477 (string-to-number (match-string 4 s))
11478 (string-to-number (match-string 3 s))
11479 (string-to-number (match-string 2 s))
11480 nil nil nil)
11481 (make-list 9 0)))
11483 (defun org-timestamp-up (&optional arg)
11484 "Increase the date item at the cursor by one.
11485 If the cursor is on the year, change the year. If it is on the month or
11486 the day, change that.
11487 With prefix ARG, change by that many units."
11488 (interactive "p")
11489 (org-timestamp-change (prefix-numeric-value arg)))
11491 (defun org-timestamp-down (&optional arg)
11492 "Decrease the date item at the cursor by one.
11493 If the cursor is on the year, change the year. If it is on the month or
11494 the day, change that.
11495 With prefix ARG, change by that many units."
11496 (interactive "p")
11497 (org-timestamp-change (- (prefix-numeric-value arg))))
11499 (defun org-timestamp-up-day (&optional arg)
11500 "Increase the date in the time stamp by one day.
11501 With prefix ARG, change that many days."
11502 (interactive "p")
11503 (if (and (not (org-at-timestamp-p t))
11504 (org-on-heading-p))
11505 (org-todo 'up)
11506 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11508 (defun org-timestamp-down-day (&optional arg)
11509 "Decrease the date in the time stamp by one day.
11510 With prefix ARG, change that many days."
11511 (interactive "p")
11512 (if (and (not (org-at-timestamp-p t))
11513 (org-on-heading-p))
11514 (org-todo 'down)
11515 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11517 (defun org-at-timestamp-p (&optional inactive-ok)
11518 "Determine if the cursor is in or at a timestamp."
11519 (interactive)
11520 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11521 (pos (point))
11522 (ans (or (looking-at tsr)
11523 (save-excursion
11524 (skip-chars-backward "^[<\n\r\t")
11525 (if (> (point) (point-min)) (backward-char 1))
11526 (and (looking-at tsr)
11527 (> (- (match-end 0) pos) -1))))))
11528 (and ans
11529 (boundp 'org-ts-what)
11530 (setq org-ts-what
11531 (cond
11532 ((= pos (match-beginning 0)) 'bracket)
11533 ((= pos (1- (match-end 0))) 'bracket)
11534 ((org-pos-in-match-range pos 2) 'year)
11535 ((org-pos-in-match-range pos 3) 'month)
11536 ((org-pos-in-match-range pos 7) 'hour)
11537 ((org-pos-in-match-range pos 8) 'minute)
11538 ((or (org-pos-in-match-range pos 4)
11539 (org-pos-in-match-range pos 5)) 'day)
11540 ((and (> pos (or (match-end 8) (match-end 5)))
11541 (< pos (match-end 0)))
11542 (- pos (or (match-end 8) (match-end 5))))
11543 (t 'day))))
11544 ans))
11546 (defun org-toggle-timestamp-type ()
11547 "Toggle the type (<active> or [inactive]) of a time stamp."
11548 (interactive)
11549 (when (org-at-timestamp-p t)
11550 (let ((beg (match-beginning 0)) (end (match-end 0))
11551 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11552 (save-excursion
11553 (goto-char beg)
11554 (while (re-search-forward "[][<>]" end t)
11555 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11556 t t)))
11557 (message "Timestamp is now %sactive"
11558 (if (equal (char-after beg) ?<) "" "in")))))
11560 (defun org-timestamp-change (n &optional what)
11561 "Change the date in the time stamp at point.
11562 The date will be changed by N times WHAT. WHAT can be `day', `month',
11563 `year', `minute', `second'. If WHAT is not given, the cursor position
11564 in the timestamp determines what will be changed."
11565 (let ((pos (point))
11566 with-hm inactive
11567 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11568 org-ts-what
11569 extra rem
11570 ts time time0)
11571 (if (not (org-at-timestamp-p t))
11572 (error "Not at a timestamp"))
11573 (if (and (not what) (eq org-ts-what 'bracket))
11574 (org-toggle-timestamp-type)
11575 (if (and (not what) (not (eq org-ts-what 'day))
11576 org-display-custom-times
11577 (get-text-property (point) 'display)
11578 (not (get-text-property (1- (point)) 'display)))
11579 (setq org-ts-what 'day))
11580 (setq org-ts-what (or what org-ts-what)
11581 inactive (= (char-after (match-beginning 0)) ?\[)
11582 ts (match-string 0))
11583 (replace-match "")
11584 (if (string-match
11585 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11587 (setq extra (match-string 1 ts)))
11588 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11589 (setq with-hm t))
11590 (setq time0 (org-parse-time-string ts))
11591 (when (and (eq org-ts-what 'minute)
11592 (eq current-prefix-arg nil))
11593 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11594 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11595 (setcar (cdr time0) (+ (nth 1 time0)
11596 (if (> n 0) (- rem) (- dm rem))))))
11597 (setq time
11598 (encode-time (or (car time0) 0)
11599 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11600 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11601 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11602 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11603 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11604 (nthcdr 6 time0)))
11605 (when (integerp org-ts-what)
11606 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11607 (if (eq what 'calendar)
11608 (let ((cal-date (org-get-date-from-calendar)))
11609 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11610 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11611 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11612 (setcar time0 (or (car time0) 0))
11613 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11614 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11615 (setq time (apply 'encode-time time0))))
11616 (setq org-last-changed-timestamp
11617 (org-insert-time-stamp time with-hm inactive nil nil extra))
11618 (org-clock-update-time-maybe)
11619 (goto-char pos)
11620 ;; Try to recenter the calendar window, if any
11621 (if (and org-calendar-follow-timestamp-change
11622 (get-buffer-window "*Calendar*" t)
11623 (memq org-ts-what '(day month year)))
11624 (org-recenter-calendar (time-to-days time))))))
11626 (defun org-modify-ts-extra (s pos n dm)
11627 "Change the different parts of the lead-time and repeat fields in timestamp."
11628 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11629 ng h m new rem)
11630 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11631 (cond
11632 ((or (org-pos-in-match-range pos 2)
11633 (org-pos-in-match-range pos 3))
11634 (setq m (string-to-number (match-string 3 s))
11635 h (string-to-number (match-string 2 s)))
11636 (if (org-pos-in-match-range pos 2)
11637 (setq h (+ h n))
11638 (setq n (* dm (org-no-warnings (signum n))))
11639 (when (not (= 0 (setq rem (% m dm))))
11640 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11641 (setq m (+ m n)))
11642 (if (< m 0) (setq m (+ m 60) h (1- h)))
11643 (if (> m 59) (setq m (- m 60) h (1+ h)))
11644 (setq h (min 24 (max 0 h)))
11645 (setq ng 1 new (format "-%02d:%02d" h m)))
11646 ((org-pos-in-match-range pos 6)
11647 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11648 ((org-pos-in-match-range pos 5)
11649 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11651 ((org-pos-in-match-range pos 9)
11652 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11653 ((org-pos-in-match-range pos 8)
11654 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11656 (when ng
11657 (setq s (concat
11658 (substring s 0 (match-beginning ng))
11660 (substring s (match-end ng))))))
11663 (defun org-recenter-calendar (date)
11664 "If the calendar is visible, recenter it to DATE."
11665 (let* ((win (selected-window))
11666 (cwin (get-buffer-window "*Calendar*" t))
11667 (calendar-move-hook nil))
11668 (when cwin
11669 (select-window cwin)
11670 (calendar-goto-date (if (listp date) date
11671 (calendar-gregorian-from-absolute date)))
11672 (select-window win))))
11674 (defun org-goto-calendar (&optional arg)
11675 "Go to the Emacs calendar at the current date.
11676 If there is a time stamp in the current line, go to that date.
11677 A prefix ARG can be used to force the current date."
11678 (interactive "P")
11679 (let ((tsr org-ts-regexp) diff
11680 (calendar-move-hook nil)
11681 (calendar-view-holidays-initially-flag nil)
11682 (view-calendar-holidays-initially nil)
11683 (calendar-view-diary-initially-flag nil)
11684 (view-diary-entries-initially nil))
11685 (if (or (org-at-timestamp-p)
11686 (save-excursion
11687 (beginning-of-line 1)
11688 (looking-at (concat ".*" tsr))))
11689 (let ((d1 (time-to-days (current-time)))
11690 (d2 (time-to-days
11691 (org-time-string-to-time (match-string 1)))))
11692 (setq diff (- d2 d1))))
11693 (calendar)
11694 (calendar-goto-today)
11695 (if (and diff (not arg)) (calendar-forward-day diff))))
11697 (defun org-get-date-from-calendar ()
11698 "Return a list (month day year) of date at point in calendar."
11699 (with-current-buffer "*Calendar*"
11700 (save-match-data
11701 (calendar-cursor-to-date))))
11703 (defun org-date-from-calendar ()
11704 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11705 If there is already a time stamp at the cursor position, update it."
11706 (interactive)
11707 (if (org-at-timestamp-p t)
11708 (org-timestamp-change 0 'calendar)
11709 (let ((cal-date (org-get-date-from-calendar)))
11710 (org-insert-time-stamp
11711 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11713 (defun org-minutes-to-hh:mm-string (m)
11714 "Compute H:MM from a number of minutes."
11715 (let ((h (/ m 60)))
11716 (setq m (- m (* 60 h)))
11717 (format org-time-clocksum-format h m)))
11719 (defun org-hh:mm-string-to-minutes (s)
11720 "Convert a string H:MM to a number of minutes."
11721 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11722 (+ (* (string-to-number (match-string 1 s)) 60)
11723 (string-to-number (match-string 2 s)))
11726 ;;;; Agenda files
11728 ;;;###autoload
11729 (defun org-iswitchb (&optional arg)
11730 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11731 With a prefix argument, restrict available to files.
11732 With two prefix arguments, restrict available buffers to agenda files.
11734 Due to some yet unresolved reason, the global function
11735 `iswitchb-mode' needs to be active for this function to work."
11736 (interactive "P")
11737 (require 'iswitchb)
11738 (let ((enabled iswitchb-mode) blist)
11739 (or enabled (iswitchb-mode 1))
11740 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11741 ((equal arg '(16)) (org-buffer-list 'agenda))
11742 (t (org-buffer-list))))
11743 (unwind-protect
11744 (let ((iswitchb-make-buflist-hook
11745 (lambda ()
11746 (setq iswitchb-temp-buflist
11747 (mapcar 'buffer-name blist)))))
11748 (switch-to-buffer
11749 (iswitchb-read-buffer
11750 "Switch-to: " nil t))
11751 (or enabled (iswitchb-mode -1))))))
11753 (defun org-buffer-list (&optional predicate exclude-tmp)
11754 "Return a list of Org buffers.
11755 PREDICATE can be `export', `files' or `agenda'.
11757 export restrict the list to Export buffers.
11758 files restrict the list to buffers visiting Org files.
11759 agenda restrict the list to buffers visiting agenda files.
11761 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11762 (let* ((bfn nil)
11763 (agenda-files (and (eq predicate 'agenda)
11764 (mapcar 'file-truename (org-agenda-files t))))
11765 (filter
11766 (cond
11767 ((eq predicate 'files)
11768 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11769 ((eq predicate 'export)
11770 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11771 ((eq predicate 'agenda)
11772 (lambda (b)
11773 (with-current-buffer b
11774 (and (eq major-mode 'org-mode)
11775 (setq bfn (buffer-file-name b))
11776 (member (file-truename bfn) agenda-files)))))
11777 (t (lambda (b) (with-current-buffer b
11778 (or (eq major-mode 'org-mode)
11779 (string-match "\*Org .*Export"
11780 (buffer-name b)))))))))
11781 (delq nil
11782 (mapcar
11783 (lambda(b)
11784 (if (and (funcall filter b)
11785 (or (not exclude-tmp)
11786 (not (string-match "tmp" (buffer-name b)))))
11788 nil))
11789 (buffer-list)))))
11791 (defun org-agenda-files (&optional unrestricted archives)
11792 "Get the list of agenda files.
11793 Optional UNRESTRICTED means return the full list even if a restriction
11794 is currently in place.
11795 When ARCHIVES is t, include all archive files hat are really being
11796 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11797 `org-agenda-archives-mode' is t."
11798 (let ((files
11799 (cond
11800 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11801 ((stringp org-agenda-files) (org-read-agenda-file-list))
11802 ((listp org-agenda-files) org-agenda-files)
11803 (t (error "Invalid value of `org-agenda-files'")))))
11804 (setq files (apply 'append
11805 (mapcar (lambda (f)
11806 (if (file-directory-p f)
11807 (directory-files
11808 f t org-agenda-file-regexp)
11809 (list f)))
11810 files)))
11811 (when org-agenda-skip-unavailable-files
11812 (setq files (delq nil
11813 (mapcar (function
11814 (lambda (file)
11815 (and (file-readable-p file) file)))
11816 files))))
11817 (when (or (eq archives t)
11818 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11819 (setq files (org-add-archive-files files)))
11820 files))
11822 (defun org-edit-agenda-file-list ()
11823 "Edit the list of agenda files.
11824 Depending on setup, this either uses customize to edit the variable
11825 `org-agenda-files', or it visits the file that is holding the list. In the
11826 latter case, the buffer is set up in a way that saving it automatically kills
11827 the buffer and restores the previous window configuration."
11828 (interactive)
11829 (if (stringp org-agenda-files)
11830 (let ((cw (current-window-configuration)))
11831 (find-file org-agenda-files)
11832 (org-set-local 'org-window-configuration cw)
11833 (org-add-hook 'after-save-hook
11834 (lambda ()
11835 (set-window-configuration
11836 (prog1 org-window-configuration
11837 (kill-buffer (current-buffer))))
11838 (org-install-agenda-files-menu)
11839 (message "New agenda file list installed"))
11840 nil 'local)
11841 (message "%s" (substitute-command-keys
11842 "Edit list and finish with \\[save-buffer]")))
11843 (customize-variable 'org-agenda-files)))
11845 (defun org-store-new-agenda-file-list (list)
11846 "Set new value for the agenda file list and save it correcly."
11847 (if (stringp org-agenda-files)
11848 (let ((f org-agenda-files) b)
11849 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11850 (with-temp-file f
11851 (insert (mapconcat 'identity list "\n") "\n")))
11852 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11853 (setq org-agenda-files list)
11854 (customize-save-variable 'org-agenda-files org-agenda-files))))
11856 (defun org-read-agenda-file-list ()
11857 "Read the list of agenda files from a file."
11858 (when (file-directory-p org-agenda-files)
11859 (error "`org-agenda-files' cannot be a single directory"))
11860 (when (stringp org-agenda-files)
11861 (with-temp-buffer
11862 (insert-file-contents org-agenda-files)
11863 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11866 ;;;###autoload
11867 (defun org-cycle-agenda-files ()
11868 "Cycle through the files in `org-agenda-files'.
11869 If the current buffer visits an agenda file, find the next one in the list.
11870 If the current buffer does not, find the first agenda file."
11871 (interactive)
11872 (let* ((fs (org-agenda-files t))
11873 (files (append fs (list (car fs))))
11874 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11875 file)
11876 (unless files (error "No agenda files"))
11877 (catch 'exit
11878 (while (setq file (pop files))
11879 (if (equal (file-truename file) tcf)
11880 (when (car files)
11881 (find-file (car files))
11882 (throw 'exit t))))
11883 (find-file (car fs)))
11884 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11886 (defun org-agenda-file-to-front (&optional to-end)
11887 "Move/add the current file to the top of the agenda file list.
11888 If the file is not present in the list, it is added to the front. If it is
11889 present, it is moved there. With optional argument TO-END, add/move to the
11890 end of the list."
11891 (interactive "P")
11892 (let ((org-agenda-skip-unavailable-files nil)
11893 (file-alist (mapcar (lambda (x)
11894 (cons (file-truename x) x))
11895 (org-agenda-files t)))
11896 (ctf (file-truename buffer-file-name))
11897 x had)
11898 (setq x (assoc ctf file-alist) had x)
11900 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11901 (if to-end
11902 (setq file-alist (append (delq x file-alist) (list x)))
11903 (setq file-alist (cons x (delq x file-alist))))
11904 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11905 (org-install-agenda-files-menu)
11906 (message "File %s to %s of agenda file list"
11907 (if had "moved" "added") (if to-end "end" "front"))))
11909 (defun org-remove-file (&optional file)
11910 "Remove current file from the list of files in variable `org-agenda-files'.
11911 These are the files which are being checked for agenda entries.
11912 Optional argument FILE means, use this file instead of the current."
11913 (interactive)
11914 (let* ((org-agenda-skip-unavailable-files nil)
11915 (file (or file buffer-file-name))
11916 (true-file (file-truename file))
11917 (afile (abbreviate-file-name file))
11918 (files (delq nil (mapcar
11919 (lambda (x)
11920 (if (equal true-file
11921 (file-truename x))
11922 nil x))
11923 (org-agenda-files t)))))
11924 (if (not (= (length files) (length (org-agenda-files t))))
11925 (progn
11926 (org-store-new-agenda-file-list files)
11927 (org-install-agenda-files-menu)
11928 (message "Removed file: %s" afile))
11929 (message "File was not in list: %s (not removed)" afile))))
11931 (defun org-file-menu-entry (file)
11932 (vector file (list 'find-file file) t))
11934 (defun org-check-agenda-file (file)
11935 "Make sure FILE exists. If not, ask user what to do."
11936 (when (not (file-exists-p file))
11937 (message "non-existent file %s. [R]emove from list or [A]bort?"
11938 (abbreviate-file-name file))
11939 (let ((r (downcase (read-char-exclusive))))
11940 (cond
11941 ((equal r ?r)
11942 (org-remove-file file)
11943 (throw 'nextfile t))
11944 (t (error "Abort"))))))
11946 (defun org-get-agenda-file-buffer (file)
11947 "Get a buffer visiting FILE. If the buffer needs to be created, add
11948 it to the list of buffers which might be released later."
11949 (let ((buf (org-find-base-buffer-visiting file)))
11950 (if buf
11951 buf ; just return it
11952 ;; Make a new buffer and remember it
11953 (setq buf (find-file-noselect file))
11954 (if buf (push buf org-agenda-new-buffers))
11955 buf)))
11957 (defun org-release-buffers (blist)
11958 "Release all buffers in list, asking the user for confirmation when needed.
11959 When a buffer is unmodified, it is just killed. When modified, it is saved
11960 \(if the user agrees) and then killed."
11961 (let (buf file)
11962 (while (setq buf (pop blist))
11963 (setq file (buffer-file-name buf))
11964 (when (and (buffer-modified-p buf)
11965 file
11966 (y-or-n-p (format "Save file %s? " file)))
11967 (with-current-buffer buf (save-buffer)))
11968 (kill-buffer buf))))
11970 (defun org-prepare-agenda-buffers (files)
11971 "Create buffers for all agenda files, protect archived trees and comments."
11972 (interactive)
11973 (let ((pa '(:org-archived t))
11974 (pc '(:org-comment t))
11975 (pall '(:org-archived t :org-comment t))
11976 (inhibit-read-only t)
11977 (rea (concat ":" org-archive-tag ":"))
11978 bmp file re)
11979 (save-excursion
11980 (save-restriction
11981 (while (setq file (pop files))
11982 (if (bufferp file)
11983 (set-buffer file)
11984 (org-check-agenda-file file)
11985 (set-buffer (org-get-agenda-file-buffer file)))
11986 (widen)
11987 (setq bmp (buffer-modified-p))
11988 (org-refresh-category-properties)
11989 (setq org-todo-keywords-for-agenda
11990 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11991 (setq org-done-keywords-for-agenda
11992 (append org-done-keywords-for-agenda org-done-keywords))
11993 (setq org-todo-keyword-alist-for-agenda
11994 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11995 (setq org-tag-alist-for-agenda
11996 (append org-tag-alist-for-agenda org-tag-alist))
11998 (save-excursion
11999 (remove-text-properties (point-min) (point-max) pall)
12000 (when org-agenda-skip-archived-trees
12001 (goto-char (point-min))
12002 (while (re-search-forward rea nil t)
12003 (if (org-on-heading-p t)
12004 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12005 (goto-char (point-min))
12006 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12007 (while (re-search-forward re nil t)
12008 (add-text-properties
12009 (match-beginning 0) (org-end-of-subtree t) pc)))
12010 (set-buffer-modified-p bmp))))
12011 (setq org-todo-keyword-alist-for-agenda
12012 (org-uniquify org-todo-keyword-alist-for-agenda)
12013 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12015 ;;;; Embedded LaTeX
12017 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12018 "Keymap for the minor `org-cdlatex-mode'.")
12020 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12021 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12022 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12023 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12024 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12026 (defvar org-cdlatex-texmathp-advice-is-done nil
12027 "Flag remembering if we have applied the advice to texmathp already.")
12029 (define-minor-mode org-cdlatex-mode
12030 "Toggle the minor `org-cdlatex-mode'.
12031 This mode supports entering LaTeX environment and math in LaTeX fragments
12032 in Org-mode.
12033 \\{org-cdlatex-mode-map}"
12034 nil " OCDL" nil
12035 (when org-cdlatex-mode (require 'cdlatex))
12036 (unless org-cdlatex-texmathp-advice-is-done
12037 (setq org-cdlatex-texmathp-advice-is-done t)
12038 (defadvice texmathp (around org-math-always-on activate)
12039 "Always return t in org-mode buffers.
12040 This is because we want to insert math symbols without dollars even outside
12041 the LaTeX math segments. If Orgmode thinks that point is actually inside
12042 en embedded LaTeX fragement, let texmathp do its job.
12043 \\[org-cdlatex-mode-map]"
12044 (interactive)
12045 (let (p)
12046 (cond
12047 ((not (org-mode-p)) ad-do-it)
12048 ((eq this-command 'cdlatex-math-symbol)
12049 (setq ad-return-value t
12050 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12052 (let ((p (org-inside-LaTeX-fragment-p)))
12053 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12054 (setq ad-return-value t
12055 texmathp-why '("Org-mode embedded math" . 0))
12056 (if p ad-do-it)))))))))
12058 (defun turn-on-org-cdlatex ()
12059 "Unconditionally turn on `org-cdlatex-mode'."
12060 (org-cdlatex-mode 1))
12062 (defun org-inside-LaTeX-fragment-p ()
12063 "Test if point is inside a LaTeX fragment.
12064 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12065 sequence appearing also before point.
12066 Even though the matchers for math are configurable, this function assumes
12067 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12068 delimiters are skipped when they have been removed by customization.
12069 The return value is nil, or a cons cell with the delimiter and
12070 and the position of this delimiter.
12072 This function does a reasonably good job, but can locally be fooled by
12073 for example currency specifications. For example it will assume being in
12074 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12075 fragments that are properly closed, but during editing, we have to live
12076 with the uncertainty caused by missing closing delimiters. This function
12077 looks only before point, not after."
12078 (catch 'exit
12079 (let ((pos (point))
12080 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12081 (lim (progn
12082 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12083 (point)))
12084 dd-on str (start 0) m re)
12085 (goto-char pos)
12086 (when dodollar
12087 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12088 re (nth 1 (assoc "$" org-latex-regexps)))
12089 (while (string-match re str start)
12090 (cond
12091 ((= (match-end 0) (length str))
12092 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12093 ((= (match-end 0) (- (length str) 5))
12094 (throw 'exit nil))
12095 (t (setq start (match-end 0))))))
12096 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12097 (goto-char pos)
12098 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12099 (and (match-beginning 2) (throw 'exit nil))
12100 ;; count $$
12101 (while (re-search-backward "\\$\\$" lim t)
12102 (setq dd-on (not dd-on)))
12103 (goto-char pos)
12104 (if dd-on (cons "$$" m))))))
12107 (defun org-try-cdlatex-tab ()
12108 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12109 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12110 - inside a LaTeX fragment, or
12111 - after the first word in a line, where an abbreviation expansion could
12112 insert a LaTeX environment."
12113 (when org-cdlatex-mode
12114 (cond
12115 ((save-excursion
12116 (skip-chars-backward "a-zA-Z0-9*")
12117 (skip-chars-backward " \t")
12118 (bolp))
12119 (cdlatex-tab) t)
12120 ((org-inside-LaTeX-fragment-p)
12121 (cdlatex-tab) t)
12122 (t nil))))
12124 (defun org-cdlatex-underscore-caret (&optional arg)
12125 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12126 Revert to the normal definition outside of these fragments."
12127 (interactive "P")
12128 (if (org-inside-LaTeX-fragment-p)
12129 (call-interactively 'cdlatex-sub-superscript)
12130 (let (org-cdlatex-mode)
12131 (call-interactively (key-binding (vector last-input-event))))))
12133 (defun org-cdlatex-math-modify (&optional arg)
12134 "Execute `cdlatex-math-modify' in LaTeX fragments.
12135 Revert to the normal definition outside of these fragments."
12136 (interactive "P")
12137 (if (org-inside-LaTeX-fragment-p)
12138 (call-interactively 'cdlatex-math-modify)
12139 (let (org-cdlatex-mode)
12140 (call-interactively (key-binding (vector last-input-event))))))
12142 (defvar org-latex-fragment-image-overlays nil
12143 "List of overlays carrying the images of latex fragments.")
12144 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12146 (defun org-remove-latex-fragment-image-overlays ()
12147 "Remove all overlays with LaTeX fragment images in current buffer."
12148 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12149 (setq org-latex-fragment-image-overlays nil))
12151 (defun org-preview-latex-fragment (&optional subtree)
12152 "Preview the LaTeX fragment at point, or all locally or globally.
12153 If the cursor is in a LaTeX fragment, create the image and overlay
12154 it over the source code. If there is no fragment at point, display
12155 all fragments in the current text, from one headline to the next. With
12156 prefix SUBTREE, display all fragments in the current subtree. With a
12157 double prefix `C-u C-u', or when the cursor is before the first headline,
12158 display all fragments in the buffer.
12159 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12160 (interactive "P")
12161 (org-remove-latex-fragment-image-overlays)
12162 (save-excursion
12163 (save-restriction
12164 (let (beg end at msg)
12165 (cond
12166 ((or (equal subtree '(16))
12167 (not (save-excursion
12168 (re-search-backward (concat "^" outline-regexp) nil t))))
12169 (setq beg (point-min) end (point-max)
12170 msg "Creating images for buffer...%s"))
12171 ((equal subtree '(4))
12172 (org-back-to-heading)
12173 (setq beg (point) end (org-end-of-subtree t)
12174 msg "Creating images for subtree...%s"))
12176 (if (setq at (org-inside-LaTeX-fragment-p))
12177 (goto-char (max (point-min) (- (cdr at) 2)))
12178 (org-back-to-heading))
12179 (setq beg (point) end (progn (outline-next-heading) (point))
12180 msg (if at "Creating image...%s"
12181 "Creating images for entry...%s"))))
12182 (message msg "")
12183 (narrow-to-region beg end)
12184 (goto-char beg)
12185 (org-format-latex
12186 (concat "ltxpng/" (file-name-sans-extension
12187 (file-name-nondirectory
12188 buffer-file-name)))
12189 default-directory 'overlays msg at 'forbuffer)
12190 (message msg "done. Use `C-c C-c' to remove images.")))))
12192 (defvar org-latex-regexps
12193 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12194 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12195 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12196 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12197 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12198 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12199 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12200 "Regular expressions for matching embedded LaTeX.")
12202 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12203 "Replace LaTeX fragments with links to an image, and produce images."
12204 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12205 (let* ((prefixnodir (file-name-nondirectory prefix))
12206 (absprefix (expand-file-name prefix dir))
12207 (todir (file-name-directory absprefix))
12208 (opt org-format-latex-options)
12209 (matchers (plist-get opt :matchers))
12210 (re-list org-latex-regexps)
12211 (cnt 0) txt link beg end re e checkdir
12212 m n block linkfile movefile ov)
12213 ;; Check if there are old images files with this prefix, and remove them
12214 (when (file-directory-p todir)
12215 (mapc 'delete-file
12216 (directory-files
12217 todir 'full
12218 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12219 ;; Check the different regular expressions
12220 (while (setq e (pop re-list))
12221 (setq m (car e) re (nth 1 e) n (nth 2 e)
12222 block (if (nth 3 e) "\n\n" ""))
12223 (when (member m matchers)
12224 (goto-char (point-min))
12225 (while (re-search-forward re nil t)
12226 (when (or (not at) (equal (cdr at) (match-beginning n)))
12227 (setq txt (match-string n)
12228 beg (match-beginning n) end (match-end n)
12229 cnt (1+ cnt)
12230 linkfile (format "%s_%04d.png" prefix cnt)
12231 movefile (format "%s_%04d.png" absprefix cnt)
12232 link (concat block "[[file:" linkfile "]]" block))
12233 (if msg (message msg cnt))
12234 (goto-char beg)
12235 (unless checkdir ; make sure the directory exists
12236 (setq checkdir t)
12237 (or (file-directory-p todir) (make-directory todir)))
12238 (org-create-formula-image
12239 txt movefile opt forbuffer)
12240 (if overlays
12241 (progn
12242 (setq ov (org-make-overlay beg end))
12243 (if (featurep 'xemacs)
12244 (progn
12245 (org-overlay-put ov 'invisible t)
12246 (org-overlay-put
12247 ov 'end-glyph
12248 (make-glyph (vector 'png :file movefile))))
12249 (org-overlay-put
12250 ov 'display
12251 (list 'image :type 'png :file movefile :ascent 'center)))
12252 (push ov org-latex-fragment-image-overlays)
12253 (goto-char end))
12254 (delete-region beg end)
12255 (insert link))))))))
12257 ;; This function borrows from Ganesh Swami's latex2png.el
12258 (defun org-create-formula-image (string tofile options buffer)
12259 (let* ((tmpdir (if (featurep 'xemacs)
12260 (temp-directory)
12261 temporary-file-directory))
12262 (texfilebase (make-temp-name
12263 (expand-file-name "orgtex" tmpdir)))
12264 (texfile (concat texfilebase ".tex"))
12265 (dvifile (concat texfilebase ".dvi"))
12266 (pngfile (concat texfilebase ".png"))
12267 (fnh (if (featurep 'xemacs)
12268 (font-height (get-face-font 'default))
12269 (face-attribute 'default :height nil)))
12270 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12271 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12272 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12273 "Black"))
12274 (bg (or (plist-get options (if buffer :background :html-background))
12275 "Transparent")))
12276 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12277 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12278 (with-temp-file texfile
12279 (insert org-format-latex-header
12280 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12281 (let ((dir default-directory))
12282 (condition-case nil
12283 (progn
12284 (cd tmpdir)
12285 (call-process "latex" nil nil nil texfile))
12286 (error nil))
12287 (cd dir))
12288 (if (not (file-exists-p dvifile))
12289 (progn (message "Failed to create dvi file from %s" texfile) nil)
12290 (condition-case nil
12291 (call-process "dvipng" nil nil nil
12292 "-E" "-fg" fg "-bg" bg
12293 "-D" dpi
12294 ;;"-x" scale "-y" scale
12295 "-T" "tight"
12296 "-o" pngfile
12297 dvifile)
12298 (error nil))
12299 (if (not (file-exists-p pngfile))
12300 (progn (message "Failed to create png file from %s" texfile) nil)
12301 ;; Use the requested file name and clean up
12302 (copy-file pngfile tofile 'replace)
12303 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12304 (delete-file (concat texfilebase e)))
12305 pngfile))))
12307 (defun org-dvipng-color (attr)
12308 "Return an rgb color specification for dvipng."
12309 (apply 'format "rgb %s %s %s"
12310 (mapcar 'org-normalize-color
12311 (color-values (face-attribute 'default attr nil)))))
12313 (defun org-normalize-color (value)
12314 "Return string to be used as color value for an RGB component."
12315 (format "%g" (/ value 65535.0)))
12318 ;;;; Key bindings
12320 ;; Make `C-c C-x' a prefix key
12321 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12323 ;; TAB key with modifiers
12324 (org-defkey org-mode-map "\C-i" 'org-cycle)
12325 (org-defkey org-mode-map [(tab)] 'org-cycle)
12326 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12327 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12328 (org-defkey org-mode-map "\M-\t" 'org-complete)
12329 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12330 ;; The following line is necessary under Suse GNU/Linux
12331 (unless (featurep 'xemacs)
12332 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12333 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12334 (define-key org-mode-map [backtab] 'org-shifttab)
12336 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12337 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12338 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12340 ;; Cursor keys with modifiers
12341 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12342 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12343 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12344 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12346 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12347 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12348 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12349 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12351 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12352 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12353 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12354 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12356 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12357 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12359 ;;; Extra keys for tty access.
12360 ;; We only set them when really needed because otherwise the
12361 ;; menus don't show the simple keys
12363 (when (or org-use-extra-keys
12364 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12365 (not window-system))
12366 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12367 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12368 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12369 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12370 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12371 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12372 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12373 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12374 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12375 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12376 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12377 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12378 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12379 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12380 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12381 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12382 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12383 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12384 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12385 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12386 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12387 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12389 ;; All the other keys
12391 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12392 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12393 (if (boundp 'narrow-map)
12394 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12395 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12396 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12397 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12398 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12399 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12400 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12401 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12402 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12403 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12404 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12405 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12406 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12407 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12408 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12409 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12410 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12411 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12412 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12413 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12414 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12415 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12416 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12417 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12418 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12419 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12420 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12421 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12422 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12423 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12424 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12425 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12426 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12427 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12428 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12429 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12430 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12431 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12432 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12433 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12434 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12435 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12436 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12437 (org-defkey org-mode-map "\C-c^" 'org-sort)
12438 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12439 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12440 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12441 (org-defkey org-mode-map "\C-m" 'org-return)
12442 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12443 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12444 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12445 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12446 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12447 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12448 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12449 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12450 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12451 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12452 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12453 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12454 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12455 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12456 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12457 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12459 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12460 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12461 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12462 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12464 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12465 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12466 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12467 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12468 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12469 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12470 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12471 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12472 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12473 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12474 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12475 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12477 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12478 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12479 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12481 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12483 (when (featurep 'xemacs)
12484 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12486 (defvar org-table-auto-blank-field) ; defined in org-table.el
12487 (defun org-self-insert-command (N)
12488 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12489 If the cursor is in a table looking at whitespace, the whitespace is
12490 overwritten, and the table is not marked as requiring realignment."
12491 (interactive "p")
12492 (if (and (org-table-p)
12493 (progn
12494 ;; check if we blank the field, and if that triggers align
12495 (and (featurep 'org-table) org-table-auto-blank-field
12496 (member last-command
12497 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12498 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12499 ;; got extra space, this field does not determine column width
12500 (let (org-table-may-need-update) (org-table-blank-field))
12501 ;; no extra space, this field may determine column width
12502 (org-table-blank-field)))
12504 (eq N 1)
12505 (looking-at "[^|\n]* |"))
12506 (let (org-table-may-need-update)
12507 (goto-char (1- (match-end 0)))
12508 (delete-backward-char 1)
12509 (goto-char (match-beginning 0))
12510 (self-insert-command N))
12511 (setq org-table-may-need-update t)
12512 (self-insert-command N)
12513 (org-fix-tags-on-the-fly)))
12515 (defun org-fix-tags-on-the-fly ()
12516 (when (and (equal (char-after (point-at-bol)) ?*)
12517 (org-on-heading-p))
12518 (org-align-tags-here org-tags-column)))
12520 (defun org-delete-backward-char (N)
12521 "Like `delete-backward-char', insert whitespace at field end in tables.
12522 When deleting backwards, in tables this function will insert whitespace in
12523 front of the next \"|\" separator, to keep the table aligned. The table will
12524 still be marked for re-alignment if the field did fill the entire column,
12525 because, in this case the deletion might narrow the column."
12526 (interactive "p")
12527 (if (and (org-table-p)
12528 (eq N 1)
12529 (string-match "|" (buffer-substring (point-at-bol) (point)))
12530 (looking-at ".*?|"))
12531 (let ((pos (point))
12532 (noalign (looking-at "[^|\n\r]* |"))
12533 (c org-table-may-need-update))
12534 (backward-delete-char N)
12535 (skip-chars-forward "^|")
12536 (insert " ")
12537 (goto-char (1- pos))
12538 ;; noalign: if there were two spaces at the end, this field
12539 ;; does not determine the width of the column.
12540 (if noalign (setq org-table-may-need-update c)))
12541 (backward-delete-char N)
12542 (org-fix-tags-on-the-fly)))
12544 (defun org-delete-char (N)
12545 "Like `delete-char', but insert whitespace at field end in tables.
12546 When deleting characters, in tables this function will insert whitespace in
12547 front of the next \"|\" separator, to keep the table aligned. The table will
12548 still be marked for re-alignment if the field did fill the entire column,
12549 because, in this case the deletion might narrow the column."
12550 (interactive "p")
12551 (if (and (org-table-p)
12552 (not (bolp))
12553 (not (= (char-after) ?|))
12554 (eq N 1))
12555 (if (looking-at ".*?|")
12556 (let ((pos (point))
12557 (noalign (looking-at "[^|\n\r]* |"))
12558 (c org-table-may-need-update))
12559 (replace-match (concat
12560 (substring (match-string 0) 1 -1)
12561 " |"))
12562 (goto-char pos)
12563 ;; noalign: if there were two spaces at the end, this field
12564 ;; does not determine the width of the column.
12565 (if noalign (setq org-table-may-need-update c)))
12566 (delete-char N))
12567 (delete-char N)
12568 (org-fix-tags-on-the-fly)))
12570 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12571 (put 'org-self-insert-command 'delete-selection t)
12572 (put 'orgtbl-self-insert-command 'delete-selection t)
12573 (put 'org-delete-char 'delete-selection 'supersede)
12574 (put 'org-delete-backward-char 'delete-selection 'supersede)
12576 ;; Make `flyspell-mode' delay after some commands
12577 (put 'org-self-insert-command 'flyspell-delayed t)
12578 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12579 (put 'org-delete-char 'flyspell-delayed t)
12580 (put 'org-delete-backward-char 'flyspell-delayed t)
12582 ;; Make pabbrev-mode expand after org-mode commands
12583 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12584 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12586 ;; How to do this: Measure non-white length of current string
12587 ;; If equal to column width, we should realign.
12589 (defun org-remap (map &rest commands)
12590 "In MAP, remap the functions given in COMMANDS.
12591 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12592 (let (new old)
12593 (while commands
12594 (setq old (pop commands) new (pop commands))
12595 (if (fboundp 'command-remapping)
12596 (org-defkey map (vector 'remap old) new)
12597 (substitute-key-definition old new map global-map)))))
12599 (when (eq org-enable-table-editor 'optimized)
12600 ;; If the user wants maximum table support, we need to hijack
12601 ;; some standard editing functions
12602 (org-remap org-mode-map
12603 'self-insert-command 'org-self-insert-command
12604 'delete-char 'org-delete-char
12605 'delete-backward-char 'org-delete-backward-char)
12606 (org-defkey org-mode-map "|" 'org-force-self-insert))
12608 (defun org-shiftcursor-error ()
12609 "Throw an error because Shift-Cursor command was applied in wrong context."
12610 (error "This command is active in special context like tables, headlines or timestamps"))
12612 (defun org-shifttab (&optional arg)
12613 "Global visibility cycling or move to previous table field.
12614 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12615 on context.
12616 See the individual commands for more information."
12617 (interactive "P")
12618 (cond
12619 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12620 ((integerp arg)
12621 (message "Content view to level: %d" arg)
12622 (org-content (prefix-numeric-value arg))
12623 (setq org-cycle-global-status 'overview))
12624 (t (call-interactively 'org-global-cycle))))
12626 (defun org-shiftmetaleft ()
12627 "Promote subtree or delete table column.
12628 Calls `org-promote-subtree', `org-outdent-item',
12629 or `org-table-delete-column', depending on context.
12630 See the individual commands for more information."
12631 (interactive)
12632 (cond
12633 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12634 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12635 ((org-at-item-p) (call-interactively 'org-outdent-item))
12636 (t (org-shiftcursor-error))))
12638 (defun org-shiftmetaright ()
12639 "Demote subtree or insert table column.
12640 Calls `org-demote-subtree', `org-indent-item',
12641 or `org-table-insert-column', depending on context.
12642 See the individual commands for more information."
12643 (interactive)
12644 (cond
12645 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12646 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12647 ((org-at-item-p) (call-interactively 'org-indent-item))
12648 (t (org-shiftcursor-error))))
12650 (defun org-shiftmetaup (&optional arg)
12651 "Move subtree up or kill table row.
12652 Calls `org-move-subtree-up' or `org-table-kill-row' or
12653 `org-move-item-up' depending on context. See the individual commands
12654 for more information."
12655 (interactive "P")
12656 (cond
12657 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12658 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12659 ((org-at-item-p) (call-interactively 'org-move-item-up))
12660 (t (org-shiftcursor-error))))
12661 (defun org-shiftmetadown (&optional arg)
12662 "Move subtree down or insert table row.
12663 Calls `org-move-subtree-down' or `org-table-insert-row' or
12664 `org-move-item-down', depending on context. See the individual
12665 commands for more information."
12666 (interactive "P")
12667 (cond
12668 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12669 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12670 ((org-at-item-p) (call-interactively 'org-move-item-down))
12671 (t (org-shiftcursor-error))))
12673 (defun org-metaleft (&optional arg)
12674 "Promote heading or move table column to left.
12675 Calls `org-do-promote' or `org-table-move-column', depending on context.
12676 With no specific context, calls the Emacs default `backward-word'.
12677 See the individual commands for more information."
12678 (interactive "P")
12679 (cond
12680 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12681 ((or (org-on-heading-p) (org-region-active-p))
12682 (call-interactively 'org-do-promote))
12683 ((org-at-item-p) (call-interactively 'org-outdent-item))
12684 (t (call-interactively 'backward-word))))
12686 (defun org-metaright (&optional arg)
12687 "Demote subtree or move table column to right.
12688 Calls `org-do-demote' or `org-table-move-column', depending on context.
12689 With no specific context, calls the Emacs default `forward-word'.
12690 See the individual commands for more information."
12691 (interactive "P")
12692 (cond
12693 ((org-at-table-p) (call-interactively 'org-table-move-column))
12694 ((or (org-on-heading-p) (org-region-active-p))
12695 (call-interactively 'org-do-demote))
12696 ((org-at-item-p) (call-interactively 'org-indent-item))
12697 (t (call-interactively 'forward-word))))
12699 (defun org-metaup (&optional arg)
12700 "Move subtree up or move table row up.
12701 Calls `org-move-subtree-up' or `org-table-move-row' or
12702 `org-move-item-up', depending on context. See the individual commands
12703 for more information."
12704 (interactive "P")
12705 (cond
12706 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12707 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12708 ((org-at-item-p) (call-interactively 'org-move-item-up))
12709 (t (transpose-lines 1) (beginning-of-line -1))))
12711 (defun org-metadown (&optional arg)
12712 "Move subtree down or move table row down.
12713 Calls `org-move-subtree-down' or `org-table-move-row' or
12714 `org-move-item-down', depending on context. See the individual
12715 commands for more information."
12716 (interactive "P")
12717 (cond
12718 ((org-at-table-p) (call-interactively 'org-table-move-row))
12719 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12720 ((org-at-item-p) (call-interactively 'org-move-item-down))
12721 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12723 (defun org-shiftup (&optional arg)
12724 "Increase item in timestamp or increase priority of current headline.
12725 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12726 depending on context. See the individual commands for more information."
12727 (interactive "P")
12728 (cond
12729 ((org-at-timestamp-p t)
12730 (call-interactively (if org-edit-timestamp-down-means-later
12731 'org-timestamp-down 'org-timestamp-up)))
12732 ((org-on-heading-p) (call-interactively 'org-priority-up))
12733 ((org-at-item-p) (call-interactively 'org-previous-item))
12734 ((org-clocktable-try-shift 'up arg))
12735 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12737 (defun org-shiftdown (&optional arg)
12738 "Decrease item in timestamp or decrease priority of current headline.
12739 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12740 depending on context. See the individual commands for more information."
12741 (interactive "P")
12742 (cond
12743 ((org-at-timestamp-p t)
12744 (call-interactively (if org-edit-timestamp-down-means-later
12745 'org-timestamp-up 'org-timestamp-down)))
12746 ((org-on-heading-p) (call-interactively 'org-priority-down))
12747 ((org-clocktable-try-shift 'down arg))
12748 (t (call-interactively 'org-next-item))))
12750 (defun org-shiftright (&optional arg)
12751 "Cycle the thing at point or in the current line, depending on context.
12752 Depending on context, this does one of the following:
12754 - switch a timestamp at point one day into the future
12755 - on a headline, switch to the next TODO keyword.
12756 - on an item, switch entire list to the next bullet type
12757 - on a property line, switch to the next allowed value
12758 - on a clocktable definition line, move time block into the future"
12759 (interactive "P")
12760 (cond
12761 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12762 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12763 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12764 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12765 ((org-clocktable-try-shift 'right arg))
12766 (t (org-shiftcursor-error))))
12768 (defun org-shiftleft (&optional arg)
12769 "Cycle the thing at point or in the current line, depending on context.
12770 Depending on context, this does one of the following:
12772 - switch a timestamp at point one day into the past
12773 - on a headline, switch to the previous TODO keyword.
12774 - on an item, switch entire list to the previous bullet type
12775 - on a property line, switch to the previous allowed value
12776 - on a clocktable definition line, move time block into the past"
12777 (interactive "P")
12778 (cond
12779 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12780 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12781 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12782 ((org-at-property-p)
12783 (call-interactively 'org-property-previous-allowed-value))
12784 ((org-clocktable-try-shift 'left arg))
12785 (t (org-shiftcursor-error))))
12787 (defun org-shiftcontrolright ()
12788 "Switch to next TODO set."
12789 (interactive)
12790 (cond
12791 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12792 (t (org-shiftcursor-error))))
12794 (defun org-shiftcontrolleft ()
12795 "Switch to previous TODO set."
12796 (interactive)
12797 (cond
12798 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12799 (t (org-shiftcursor-error))))
12801 (defun org-ctrl-c-ret ()
12802 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12803 (interactive)
12804 (cond
12805 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12806 (t (call-interactively 'org-insert-heading))))
12808 (defun org-copy-special ()
12809 "Copy region in table or copy current subtree.
12810 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12811 See the individual commands for more information."
12812 (interactive)
12813 (call-interactively
12814 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12816 (defun org-cut-special ()
12817 "Cut region in table or cut current subtree.
12818 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12819 See the individual commands for more information."
12820 (interactive)
12821 (call-interactively
12822 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12824 (defun org-paste-special (arg)
12825 "Paste rectangular region into table, or past subtree relative to level.
12826 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12827 See the individual commands for more information."
12828 (interactive "P")
12829 (if (org-at-table-p)
12830 (org-table-paste-rectangle)
12831 (org-paste-subtree arg)))
12833 (defun org-edit-special ()
12834 "Call a special editor for the stuff at point.
12835 When at a table, call the formula editor with `org-table-edit-formulas'.
12836 When at the first line of an src example, call `org-edit-src-code'.
12837 When in an #+include line, visit the include file. Otherwise call
12838 `ffap' to visit the file at point."
12839 (interactive)
12840 (cond
12841 ((org-at-table-p)
12842 (call-interactively 'org-table-edit-formulas))
12843 ((save-excursion
12844 (beginning-of-line 1)
12845 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12846 (find-file (org-trim (match-string 1))))
12847 ((org-edit-src-code))
12848 ((org-edit-fixed-width-region))
12849 (t (call-interactively 'ffap))))
12851 (defun org-ctrl-c-ctrl-c (&optional arg)
12852 "Set tags in headline, or update according to changed information at point.
12854 This command does many different things, depending on context:
12856 - If the cursor is in a headline, prompt for tags and insert them
12857 into the current line, aligned to `org-tags-column'. When called
12858 with prefix arg, realign all tags in the current buffer.
12860 - If the cursor is in one of the special #+KEYWORD lines, this
12861 triggers scanning the buffer for these lines and updating the
12862 information.
12864 - If the cursor is inside a table, realign the table. This command
12865 works even if the automatic table editor has been turned off.
12867 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12868 the entire table.
12870 - If the cursor is a the beginning of a dynamic block, update it.
12872 - If the cursor is inside a table created by the table.el package,
12873 activate that table.
12875 - If the current buffer is a remember buffer, close note and file
12876 it. A prefix argument of 1 files to the default location
12877 without further interaction. A prefix argument of 2 files to
12878 the currently clocking task.
12880 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12881 links in this buffer.
12883 - If the cursor is on a numbered item in a plain list, renumber the
12884 ordered list.
12886 - If the cursor is on a checkbox, toggle it."
12887 (interactive "P")
12888 (let ((org-enable-table-editor t))
12889 (cond
12890 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12891 org-occur-highlights
12892 org-latex-fragment-image-overlays)
12893 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12894 (org-remove-occur-highlights)
12895 (org-remove-latex-fragment-image-overlays)
12896 (message "Temporary highlights/overlays removed from current buffer"))
12897 ((and (local-variable-p 'org-finish-function (current-buffer))
12898 (fboundp org-finish-function))
12899 (funcall org-finish-function))
12900 ((org-at-property-p)
12901 (call-interactively 'org-property-action))
12902 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12903 ((org-on-heading-p) (call-interactively 'org-set-tags))
12904 ((org-at-table.el-p)
12905 (require 'table)
12906 (beginning-of-line 1)
12907 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12908 (call-interactively 'table-recognize-table))
12909 ((org-at-table-p)
12910 (org-table-maybe-eval-formula)
12911 (if arg
12912 (call-interactively 'org-table-recalculate)
12913 (org-table-maybe-recalculate-line))
12914 (call-interactively 'org-table-align))
12915 ((org-at-item-checkbox-p)
12916 (call-interactively 'org-toggle-checkbox))
12917 ((org-at-item-p)
12918 (call-interactively 'org-maybe-renumber-ordered-list))
12919 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12920 ;; Dynamic block
12921 (beginning-of-line 1)
12922 (save-excursion (org-update-dblock)))
12923 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12924 (cond
12925 ((equal (match-string 1) "TBLFM")
12926 ;; Recalculate the table before this line
12927 (save-excursion
12928 (beginning-of-line 1)
12929 (skip-chars-backward " \r\n\t")
12930 (if (org-at-table-p)
12931 (org-call-with-arg 'org-table-recalculate t))))
12933 ; (org-set-regexps-and-options)
12934 ; (org-restart-font-lock)
12935 (let ((org-inhibit-startup t)) (org-mode-restart))
12936 (message "Local setup has been refreshed"))))
12937 (t (error "C-c C-c can do nothing useful at this location.")))))
12939 (defun org-mode-restart ()
12940 "Restart Org-mode, to scan again for special lines.
12941 Also updates the keyword regular expressions."
12942 (interactive)
12943 (org-mode)
12944 (message "Org-mode restarted"))
12946 (defun org-kill-note-or-show-branches ()
12947 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12948 (interactive)
12949 (if (not org-finish-function)
12950 (call-interactively 'show-branches)
12951 (let ((org-note-abort t))
12952 (funcall org-finish-function))))
12954 (defun org-return (&optional indent)
12955 "Goto next table row or insert a newline.
12956 Calls `org-table-next-row' or `newline', depending on context.
12957 See the individual commands for more information."
12958 (interactive)
12959 (cond
12960 ((bobp) (if indent (newline-and-indent) (newline)))
12961 ((and (org-at-heading-p)
12962 (looking-at
12963 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12964 (org-show-entry)
12965 (end-of-line 1)
12966 (newline))
12967 ((org-at-table-p)
12968 (org-table-justify-field-maybe)
12969 (call-interactively 'org-table-next-row))
12970 (t (if indent (newline-and-indent) (newline)))))
12972 (defun org-return-indent ()
12973 "Goto next table row or insert a newline and indent.
12974 Calls `org-table-next-row' or `newline-and-indent', depending on
12975 context. See the individual commands for more information."
12976 (interactive)
12977 (org-return t))
12979 (defun org-ctrl-c-star ()
12980 "Compute table, or change heading status of lines.
12981 Calls `org-table-recalculate' or `org-toggle-region-headings',
12982 depending on context. This will also turn a plain list item or a normal
12983 line into a subheading."
12984 (interactive)
12985 (cond
12986 ((org-at-table-p)
12987 (call-interactively 'org-table-recalculate))
12988 ((org-region-active-p)
12989 ;; Convert all lines in region to list items
12990 (call-interactively 'org-toggle-region-headings))
12991 ((org-on-heading-p)
12992 (org-toggle-region-headings (point-at-bol)
12993 (min (1+ (point-at-eol)) (point-max))))
12994 ((org-at-item-p)
12995 ;; Convert to heading
12996 (let ((level (save-match-data
12997 (save-excursion
12998 (condition-case nil
12999 (progn
13000 (org-back-to-heading t)
13001 (funcall outline-level))
13002 (error 0))))))
13003 (replace-match
13004 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13005 (t (org-toggle-region-headings (point-at-bol)
13006 (min (1+ (point-at-eol)) (point-max))))))
13008 (defun org-ctrl-c-minus ()
13009 "Insert separator line in table or modify bullet status of line.
13010 Also turns a plain line or a region of lines into list items.
13011 Calls `org-table-insert-hline', `org-toggle-region-items', or
13012 `org-cycle-list-bullet', depending on context."
13013 (interactive)
13014 (cond
13015 ((org-at-table-p)
13016 (call-interactively 'org-table-insert-hline))
13017 ((org-on-heading-p)
13018 ;; Convert to item
13019 (save-excursion
13020 (beginning-of-line 1)
13021 (if (looking-at "\\*+ ")
13022 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13023 ((org-region-active-p)
13024 ;; Convert all lines in region to list items
13025 (call-interactively 'org-toggle-region-items))
13026 ((org-in-item-p)
13027 (call-interactively 'org-cycle-list-bullet))
13028 (t (org-toggle-region-items (point-at-bol)
13029 (min (1+ (point-at-eol)) (point-max))))))
13031 (defun org-toggle-region-items (beg end)
13032 "Convert all lines in region to list items.
13033 If the first line is already an item, convert all list items in the region
13034 to normal lines."
13035 (interactive "r")
13036 (let (l2 l)
13037 (save-excursion
13038 (goto-char end)
13039 (setq l2 (org-current-line))
13040 (goto-char beg)
13041 (beginning-of-line 1)
13042 (setq l (1- (org-current-line)))
13043 (if (org-at-item-p)
13044 ;; We already have items, de-itemize
13045 (while (< (setq l (1+ l)) l2)
13046 (when (org-at-item-p)
13047 (goto-char (match-beginning 2))
13048 (delete-region (match-beginning 2) (match-end 2))
13049 (and (looking-at "[ \t]+") (replace-match "")))
13050 (beginning-of-line 2))
13051 (while (< (setq l (1+ l)) l2)
13052 (unless (org-at-item-p)
13053 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13054 (replace-match "\\1- \\2")))
13055 (beginning-of-line 2))))))
13057 (defun org-toggle-region-headings (beg end)
13058 "Convert all lines in region to list items.
13059 If the first line is already an item, convert all list items in the region
13060 to normal lines."
13061 (interactive "r")
13062 (let (l2 l)
13063 (save-excursion
13064 (goto-char end)
13065 (setq l2 (org-current-line))
13066 (goto-char beg)
13067 (beginning-of-line 1)
13068 (setq l (1- (org-current-line)))
13069 (if (org-on-heading-p)
13070 ;; We already have headlines, de-star them
13071 (while (< (setq l (1+ l)) l2)
13072 (when (org-on-heading-p t)
13073 (and (looking-at outline-regexp) (replace-match "")))
13074 (beginning-of-line 2))
13075 (let* ((stars (save-excursion
13076 (re-search-backward org-complex-heading-regexp nil t)
13077 (or (match-string 1) "*")))
13078 (add-stars (if org-odd-levels-only "**" "*"))
13079 (rpl (concat stars add-stars " \\2")))
13080 (while (< (setq l (1+ l)) l2)
13081 (unless (org-on-heading-p)
13082 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13083 (replace-match rpl)))
13084 (beginning-of-line 2)))))))
13086 (defun org-meta-return (&optional arg)
13087 "Insert a new heading or wrap a region in a table.
13088 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13089 See the individual commands for more information."
13090 (interactive "P")
13091 (cond
13092 ((org-at-table-p)
13093 (call-interactively 'org-table-wrap-region))
13094 (t (call-interactively 'org-insert-heading))))
13096 ;;; Menu entries
13098 ;; Define the Org-mode menus
13099 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13100 '("Tbl"
13101 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13102 ["Next Field" org-cycle (org-at-table-p)]
13103 ["Previous Field" org-shifttab (org-at-table-p)]
13104 ["Next Row" org-return (org-at-table-p)]
13105 "--"
13106 ["Blank Field" org-table-blank-field (org-at-table-p)]
13107 ["Edit Field" org-table-edit-field (org-at-table-p)]
13108 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13109 "--"
13110 ("Column"
13111 ["Move Column Left" org-metaleft (org-at-table-p)]
13112 ["Move Column Right" org-metaright (org-at-table-p)]
13113 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13114 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13115 ("Row"
13116 ["Move Row Up" org-metaup (org-at-table-p)]
13117 ["Move Row Down" org-metadown (org-at-table-p)]
13118 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13119 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13120 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13121 "--"
13122 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13123 ("Rectangle"
13124 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13125 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13126 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13127 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13128 "--"
13129 ("Calculate"
13130 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13131 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13132 ["Edit Formulas" org-edit-special (org-at-table-p)]
13133 "--"
13134 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13135 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13136 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13137 "--"
13138 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13139 "--"
13140 ["Sum Column/Rectangle" org-table-sum
13141 (or (org-at-table-p) (org-region-active-p))]
13142 ["Which Column?" org-table-current-column (org-at-table-p)])
13143 ["Debug Formulas"
13144 org-table-toggle-formula-debugger
13145 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13146 ["Show Col/Row Numbers"
13147 org-table-toggle-coordinate-overlays
13148 :style toggle
13149 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13150 "--"
13151 ["Create" org-table-create (and (not (org-at-table-p))
13152 org-enable-table-editor)]
13153 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13154 ["Import from File" org-table-import (not (org-at-table-p))]
13155 ["Export to File" org-table-export (org-at-table-p)]
13156 "--"
13157 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13159 (easy-menu-define org-org-menu org-mode-map "Org menu"
13160 '("Org"
13161 ("Show/Hide"
13162 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13163 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13164 ["Sparse Tree..." org-sparse-tree t]
13165 ["Reveal Context" org-reveal t]
13166 ["Show All" show-all t]
13167 "--"
13168 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13169 "--"
13170 ["New Heading" org-insert-heading t]
13171 ("Navigate Headings"
13172 ["Up" outline-up-heading t]
13173 ["Next" outline-next-visible-heading t]
13174 ["Previous" outline-previous-visible-heading t]
13175 ["Next Same Level" outline-forward-same-level t]
13176 ["Previous Same Level" outline-backward-same-level t]
13177 "--"
13178 ["Jump" org-goto t])
13179 ("Edit Structure"
13180 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13181 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13182 "--"
13183 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13184 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13185 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13186 "--"
13187 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13188 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13189 ["Demote Heading" org-metaright (not (org-at-table-p))]
13190 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13191 "--"
13192 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13193 "--"
13194 ["Convert to odd levels" org-convert-to-odd-levels t]
13195 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13196 ("Editing"
13197 ["Emphasis..." org-emphasize t]
13198 ["Edit Source Example" org-edit-special t])
13199 ("Archive"
13200 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13201 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13202 ; :active t :keys "C-u C-c C-x C-a"]
13203 ["Sparse trees open ARCHIVE trees"
13204 (setq org-sparse-tree-open-archived-trees
13205 (not org-sparse-tree-open-archived-trees))
13206 :style toggle :selected org-sparse-tree-open-archived-trees]
13207 ["Cycling opens ARCHIVE trees"
13208 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13209 :style toggle :selected org-cycle-open-archived-trees]
13210 "--"
13211 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13212 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13213 ; ["Check and Move Children" (org-archive-subtree '(4))
13214 ; :active t :keys "C-u C-c C-x C-s"]
13216 "--"
13217 ("TODO Lists"
13218 ["TODO/DONE/-" org-todo t]
13219 ("Select keyword"
13220 ["Next keyword" org-shiftright (org-on-heading-p)]
13221 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13222 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13223 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13224 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13225 ["Show TODO Tree" org-show-todo-tree t]
13226 ["Global TODO list" org-todo-list t]
13227 "--"
13228 ["Set Priority" org-priority t]
13229 ["Priority Up" org-shiftup t]
13230 ["Priority Down" org-shiftdown t])
13231 ("TAGS and Properties"
13232 ["Set Tags" 'org-set-tags-command t]
13233 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13234 "--"
13235 ["Set property" 'org-set-property t]
13236 ["Column view of properties" org-columns t]
13237 ["Insert Column View DBlock" org-insert-columns-dblock t])
13238 ("Dates and Scheduling"
13239 ["Timestamp" org-time-stamp t]
13240 ["Timestamp (inactive)" org-time-stamp-inactive t]
13241 ("Change Date"
13242 ["1 Day Later" org-shiftright t]
13243 ["1 Day Earlier" org-shiftleft t]
13244 ["1 ... Later" org-shiftup t]
13245 ["1 ... Earlier" org-shiftdown t])
13246 ["Compute Time Range" org-evaluate-time-range t]
13247 ["Schedule Item" org-schedule t]
13248 ["Deadline" org-deadline t]
13249 "--"
13250 ["Custom time format" org-toggle-time-stamp-overlays
13251 :style radio :selected org-display-custom-times]
13252 "--"
13253 ["Goto Calendar" org-goto-calendar t]
13254 ["Date from Calendar" org-date-from-calendar t]
13255 "--"
13256 ["Start/restart timer" org-timer-start t]
13257 ["Insert timer string" org-timer t]
13258 ["Insert timer item" org-timer-item t])
13259 ("Logging work"
13260 ["Clock in" org-clock-in t]
13261 ["Clock out" org-clock-out t]
13262 ["Clock cancel" org-clock-cancel t]
13263 ["Goto running clock" org-clock-goto t]
13264 ["Display times" org-clock-display t]
13265 ["Create clock table" org-clock-report t]
13266 "--"
13267 ["Record DONE time"
13268 (progn (setq org-log-done (not org-log-done))
13269 (message "Switching to %s will %s record a timestamp"
13270 (car org-done-keywords)
13271 (if org-log-done "automatically" "not")))
13272 :style toggle :selected org-log-done])
13273 "--"
13274 ["Agenda Command..." org-agenda t]
13275 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13276 ("File List for Agenda")
13277 ("Special views current file"
13278 ["TODO Tree" org-show-todo-tree t]
13279 ["Check Deadlines" org-check-deadlines t]
13280 ["Timeline" org-timeline t]
13281 ["Tags Tree" org-tags-sparse-tree t])
13282 "--"
13283 ("Hyperlinks"
13284 ["Store Link (Global)" org-store-link t]
13285 ["Insert Link" org-insert-link t]
13286 ["Follow Link" org-open-at-point t]
13287 "--"
13288 ["Next link" org-next-link t]
13289 ["Previous link" org-previous-link t]
13290 "--"
13291 ["Descriptive Links"
13292 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13293 :style radio
13294 :selected (member '(org-link) buffer-invisibility-spec)]
13295 ["Literal Links"
13296 (progn
13297 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13298 :style radio
13299 :selected (not (member '(org-link) buffer-invisibility-spec))])
13300 "--"
13301 ["Export/Publish..." org-export t]
13302 ("LaTeX"
13303 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13304 :selected org-cdlatex-mode]
13305 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13306 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13307 ["Modify math symbol" org-cdlatex-math-modify
13308 (org-inside-LaTeX-fragment-p)]
13309 ["Export LaTeX fragments as images"
13310 (if (featurep 'org-exp)
13311 (setq org-export-with-LaTeX-fragments
13312 (not org-export-with-LaTeX-fragments))
13313 (require 'org-exp))
13314 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13315 org-export-with-LaTeX-fragments)])
13316 "--"
13317 ("Documentation"
13318 ["Show Version" org-version t]
13319 ["Info Documentation" org-info t])
13320 ("Customize"
13321 ["Browse Org Group" org-customize t]
13322 "--"
13323 ["Expand This Menu" org-create-customize-menu
13324 (fboundp 'customize-menu-create)])
13325 "--"
13326 ["Refresh setup" org-mode-restart t]
13329 (defun org-info (&optional node)
13330 "Read documentation for Org-mode in the info system.
13331 With optional NODE, go directly to that node."
13332 (interactive)
13333 (info (format "(org)%s" (or node ""))))
13335 (defun org-install-agenda-files-menu ()
13336 (let ((bl (buffer-list)))
13337 (save-excursion
13338 (while bl
13339 (set-buffer (pop bl))
13340 (if (org-mode-p) (setq bl nil)))
13341 (when (org-mode-p)
13342 (easy-menu-change
13343 '("Org") "File List for Agenda"
13344 (append
13345 (list
13346 ["Edit File List" (org-edit-agenda-file-list) t]
13347 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13348 ["Remove Current File from List" org-remove-file t]
13349 ["Cycle through agenda files" org-cycle-agenda-files t]
13350 ["Occur in all agenda files" org-occur-in-agenda-files t]
13351 "--")
13352 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13354 ;;;; Documentation
13356 ;;;###autoload
13357 (defun org-require-autoloaded-modules ()
13358 (interactive)
13359 (mapc 'require
13360 '(org-agenda org-archive org-clock org-colview
13361 org-exp org-id org-export-latex org-publish
13362 org-remember org-table)))
13364 ;;;###autoload
13365 (defun org-customize ()
13366 "Call the customize function with org as argument."
13367 (interactive)
13368 (org-load-modules-maybe)
13369 (org-require-autoloaded-modules)
13370 (customize-browse 'org))
13372 (defun org-create-customize-menu ()
13373 "Create a full customization menu for Org-mode, insert it into the menu."
13374 (interactive)
13375 (org-load-modules-maybe)
13376 (org-require-autoloaded-modules)
13377 (if (fboundp 'customize-menu-create)
13378 (progn
13379 (easy-menu-change
13380 '("Org") "Customize"
13381 `(["Browse Org group" org-customize t]
13382 "--"
13383 ,(customize-menu-create 'org)
13384 ["Set" Custom-set t]
13385 ["Save" Custom-save t]
13386 ["Reset to Current" Custom-reset-current t]
13387 ["Reset to Saved" Custom-reset-saved t]
13388 ["Reset to Standard Settings" Custom-reset-standard t]))
13389 (message "\"Org\"-menu now contains full customization menu"))
13390 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13392 ;;;; Miscellaneous stuff
13394 ;;; Generally useful functions
13396 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13397 "Display the given MESSAGE as a warning."
13398 (if (fboundp 'display-warning)
13399 (display-warning 'org message
13400 (if (featurep 'xemacs)
13401 'warning
13402 :warning))
13403 (let ((buf (get-buffer-create "*Org warnings*")))
13404 (with-current-buffer buf
13405 (goto-char (point-max))
13406 (insert "Warning (Org): " message)
13407 (unless (bolp)
13408 (newline)))
13409 (display-buffer buf)
13410 (sit-for 0))))
13412 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13413 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13414 (if (and marker (marker-buffer marker)
13415 (buffer-live-p (marker-buffer marker)))
13416 (progn
13417 (switch-to-buffer (marker-buffer marker))
13418 (if (or (> marker (point-max)) (< marker (point-min)))
13419 (widen))
13420 (goto-char marker))
13421 (if bookmark
13422 (bookmark-jump bookmark)
13423 (error "Cannot find location"))))
13425 (defun org-quote-csv-field (s)
13426 "Quote field for inclusion in CSV material."
13427 (if (string-match "[\",]" s)
13428 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13431 (defun org-plist-delete (plist property)
13432 "Delete PROPERTY from PLIST.
13433 This is in contrast to merely setting it to 0."
13434 (let (p)
13435 (while plist
13436 (if (not (eq property (car plist)))
13437 (setq p (plist-put p (car plist) (nth 1 plist))))
13438 (setq plist (cddr plist)))
13441 (defun org-force-self-insert (N)
13442 "Needed to enforce self-insert under remapping."
13443 (interactive "p")
13444 (self-insert-command N))
13446 (defun org-string-width (s)
13447 "Compute width of string, ignoring invisible characters.
13448 This ignores character with invisibility property `org-link', and also
13449 characters with property `org-cwidth', because these will become invisible
13450 upon the next fontification round."
13451 (let (b l)
13452 (when (or (eq t buffer-invisibility-spec)
13453 (assq 'org-link buffer-invisibility-spec))
13454 (while (setq b (text-property-any 0 (length s)
13455 'invisible 'org-link s))
13456 (setq s (concat (substring s 0 b)
13457 (substring s (or (next-single-property-change
13458 b 'invisible s) (length s)))))))
13459 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13460 (setq s (concat (substring s 0 b)
13461 (substring s (or (next-single-property-change
13462 b 'org-cwidth s) (length s))))))
13463 (setq l (string-width s) b -1)
13464 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13465 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13468 (defun org-get-indentation (&optional line)
13469 "Get the indentation of the current line, interpreting tabs.
13470 When LINE is given, assume it represents a line and compute its indentation."
13471 (if line
13472 (if (string-match "^ *" (org-remove-tabs line))
13473 (match-end 0))
13474 (save-excursion
13475 (beginning-of-line 1)
13476 (skip-chars-forward " \t")
13477 (current-column))))
13479 (defun org-remove-tabs (s &optional width)
13480 "Replace tabulators in S with spaces.
13481 Assumes that s is a single line, starting in column 0."
13482 (setq width (or width tab-width))
13483 (while (string-match "\t" s)
13484 (setq s (replace-match
13485 (make-string
13486 (- (* width (/ (+ (match-beginning 0) width) width))
13487 (match-beginning 0)) ?\ )
13488 t t s)))
13491 (defun org-fix-indentation (line ind)
13492 "Fix indentation in LINE.
13493 IND is a cons cell with target and minimum indentation.
13494 If the current indenation in LINE is smaller than the minimum,
13495 leave it alone. If it is larger than ind, set it to the target."
13496 (let* ((l (org-remove-tabs line))
13497 (i (org-get-indentation l))
13498 (i1 (car ind)) (i2 (cdr ind)))
13499 (if (>= i i2) (setq l (substring line i2)))
13500 (if (> i1 0)
13501 (concat (make-string i1 ?\ ) l)
13502 l)))
13504 (defun org-base-buffer (buffer)
13505 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13506 (if (not buffer)
13507 buffer
13508 (or (buffer-base-buffer buffer)
13509 buffer)))
13511 (defun org-trim (s)
13512 "Remove whitespace at beginning and end of string."
13513 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13514 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13517 (defun org-wrap (string &optional width lines)
13518 "Wrap string to either a number of lines, or a width in characters.
13519 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13520 that costs. If there is a word longer than WIDTH, the text is actually
13521 wrapped to the length of that word.
13522 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13523 many lines, whatever width that takes.
13524 The return value is a list of lines, without newlines at the end."
13525 (let* ((words (org-split-string string "[ \t\n]+"))
13526 (maxword (apply 'max (mapcar 'org-string-width words)))
13527 w ll)
13528 (cond (width
13529 (org-do-wrap words (max maxword width)))
13530 (lines
13531 (setq w maxword)
13532 (setq ll (org-do-wrap words maxword))
13533 (if (<= (length ll) lines)
13535 (setq ll words)
13536 (while (> (length ll) lines)
13537 (setq w (1+ w))
13538 (setq ll (org-do-wrap words w)))
13539 ll))
13540 (t (error "Cannot wrap this")))))
13542 (defun org-do-wrap (words width)
13543 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13544 (let (lines line)
13545 (while words
13546 (setq line (pop words))
13547 (while (and words (< (+ (length line) (length (car words))) width))
13548 (setq line (concat line " " (pop words))))
13549 (setq lines (push line lines)))
13550 (nreverse lines)))
13552 (defun org-split-string (string &optional separators)
13553 "Splits STRING into substrings at SEPARATORS.
13554 No empty strings are returned if there are matches at the beginning
13555 and end of string."
13556 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13557 (start 0)
13558 notfirst
13559 (list nil))
13560 (while (and (string-match rexp string
13561 (if (and notfirst
13562 (= start (match-beginning 0))
13563 (< start (length string)))
13564 (1+ start) start))
13565 (< (match-beginning 0) (length string)))
13566 (setq notfirst t)
13567 (or (eq (match-beginning 0) 0)
13568 (and (eq (match-beginning 0) (match-end 0))
13569 (eq (match-beginning 0) start))
13570 (setq list
13571 (cons (substring string start (match-beginning 0))
13572 list)))
13573 (setq start (match-end 0)))
13574 (or (eq start (length string))
13575 (setq list
13576 (cons (substring string start)
13577 list)))
13578 (nreverse list)))
13580 (defun org-context ()
13581 "Return a list of contexts of the current cursor position.
13582 If several contexts apply, all are returned.
13583 Each context entry is a list with a symbol naming the context, and
13584 two positions indicating start and end of the context. Possible
13585 contexts are:
13587 :headline anywhere in a headline
13588 :headline-stars on the leading stars in a headline
13589 :todo-keyword on a TODO keyword (including DONE) in a headline
13590 :tags on the TAGS in a headline
13591 :priority on the priority cookie in a headline
13592 :item on the first line of a plain list item
13593 :item-bullet on the bullet/number of a plain list item
13594 :checkbox on the checkbox in a plain list item
13595 :table in an org-mode table
13596 :table-special on a special filed in a table
13597 :table-table in a table.el table
13598 :link on a hyperlink
13599 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13600 :target on a <<target>>
13601 :radio-target on a <<<radio-target>>>
13602 :latex-fragment on a LaTeX fragment
13603 :latex-preview on a LaTeX fragment with overlayed preview image
13605 This function expects the position to be visible because it uses font-lock
13606 faces as a help to recognize the following contexts: :table-special, :link,
13607 and :keyword."
13608 (let* ((f (get-text-property (point) 'face))
13609 (faces (if (listp f) f (list f)))
13610 (p (point)) clist o)
13611 ;; First the large context
13612 (cond
13613 ((org-on-heading-p t)
13614 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13615 (when (progn
13616 (beginning-of-line 1)
13617 (looking-at org-todo-line-tags-regexp))
13618 (push (org-point-in-group p 1 :headline-stars) clist)
13619 (push (org-point-in-group p 2 :todo-keyword) clist)
13620 (push (org-point-in-group p 4 :tags) clist))
13621 (goto-char p)
13622 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13623 (if (looking-at "\\[#[A-Z0-9]\\]")
13624 (push (org-point-in-group p 0 :priority) clist)))
13626 ((org-at-item-p)
13627 (push (org-point-in-group p 2 :item-bullet) clist)
13628 (push (list :item (point-at-bol)
13629 (save-excursion (org-end-of-item) (point)))
13630 clist)
13631 (and (org-at-item-checkbox-p)
13632 (push (org-point-in-group p 0 :checkbox) clist)))
13634 ((org-at-table-p)
13635 (push (list :table (org-table-begin) (org-table-end)) clist)
13636 (if (memq 'org-formula faces)
13637 (push (list :table-special
13638 (previous-single-property-change p 'face)
13639 (next-single-property-change p 'face)) clist)))
13640 ((org-at-table-p 'any)
13641 (push (list :table-table) clist)))
13642 (goto-char p)
13644 ;; Now the small context
13645 (cond
13646 ((org-at-timestamp-p)
13647 (push (org-point-in-group p 0 :timestamp) clist))
13648 ((memq 'org-link faces)
13649 (push (list :link
13650 (previous-single-property-change p 'face)
13651 (next-single-property-change p 'face)) clist))
13652 ((memq 'org-special-keyword faces)
13653 (push (list :keyword
13654 (previous-single-property-change p 'face)
13655 (next-single-property-change p 'face)) clist))
13656 ((org-on-target-p)
13657 (push (org-point-in-group p 0 :target) clist)
13658 (goto-char (1- (match-beginning 0)))
13659 (if (looking-at org-radio-target-regexp)
13660 (push (org-point-in-group p 0 :radio-target) clist))
13661 (goto-char p))
13662 ((setq o (car (delq nil
13663 (mapcar
13664 (lambda (x)
13665 (if (memq x org-latex-fragment-image-overlays) x))
13666 (org-overlays-at (point))))))
13667 (push (list :latex-fragment
13668 (org-overlay-start o) (org-overlay-end o)) clist)
13669 (push (list :latex-preview
13670 (org-overlay-start o) (org-overlay-end o)) clist))
13671 ((org-inside-LaTeX-fragment-p)
13672 ;; FIXME: positions wrong.
13673 (push (list :latex-fragment (point) (point)) clist)))
13675 (setq clist (nreverse (delq nil clist)))
13676 clist))
13678 ;; FIXME: Compare with at-regexp-p Do we need both?
13679 (defun org-in-regexp (re &optional nlines visually)
13680 "Check if point is inside a match of regexp.
13681 Normally only the current line is checked, but you can include NLINES extra
13682 lines both before and after point into the search.
13683 If VISUALLY is set, require that the cursor is not after the match but
13684 really on, so that the block visually is on the match."
13685 (catch 'exit
13686 (let ((pos (point))
13687 (eol (point-at-eol (+ 1 (or nlines 0))))
13688 (inc (if visually 1 0)))
13689 (save-excursion
13690 (beginning-of-line (- 1 (or nlines 0)))
13691 (while (re-search-forward re eol t)
13692 (if (and (<= (match-beginning 0) pos)
13693 (>= (+ inc (match-end 0)) pos))
13694 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13696 (defun org-at-regexp-p (regexp)
13697 "Is point inside a match of REGEXP in the current line?"
13698 (catch 'exit
13699 (save-excursion
13700 (let ((pos (point)) (end (point-at-eol)))
13701 (beginning-of-line 1)
13702 (while (re-search-forward regexp end t)
13703 (if (and (<= (match-beginning 0) pos)
13704 (>= (match-end 0) pos))
13705 (throw 'exit t)))
13706 nil))))
13708 (defun org-occur-in-agenda-files (regexp &optional nlines)
13709 "Call `multi-occur' with buffers for all agenda files."
13710 (interactive "sOrg-files matching: \np")
13711 (let* ((files (org-agenda-files))
13712 (tnames (mapcar 'file-truename files))
13713 (extra org-agenda-text-search-extra-files)
13715 (when (eq (car extra) 'agenda-archives)
13716 (setq extra (cdr extra))
13717 (setq files (org-add-archive-files files)))
13718 (while (setq f (pop extra))
13719 (unless (member (file-truename f) tnames)
13720 (add-to-list 'files f 'append)
13721 (add-to-list 'tnames (file-truename f) 'append)))
13722 (multi-occur
13723 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13724 regexp)))
13726 (if (boundp 'occur-mode-find-occurrence-hook)
13727 ;; Emacs 23
13728 (add-hook 'occur-mode-find-occurrence-hook
13729 (lambda ()
13730 (when (org-mode-p)
13731 (org-reveal))))
13732 ;; Emacs 22
13733 (defadvice occur-mode-goto-occurrence
13734 (after org-occur-reveal activate)
13735 (and (org-mode-p) (org-reveal)))
13736 (defadvice occur-mode-goto-occurrence-other-window
13737 (after org-occur-reveal activate)
13738 (and (org-mode-p) (org-reveal)))
13739 (defadvice occur-mode-display-occurrence
13740 (after org-occur-reveal activate)
13741 (when (org-mode-p)
13742 (let ((pos (occur-mode-find-occurrence)))
13743 (with-current-buffer (marker-buffer pos)
13744 (save-excursion
13745 (goto-char pos)
13746 (org-reveal)))))))
13748 (defun org-uniquify (list)
13749 "Remove duplicate elements from LIST."
13750 (let (res)
13751 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13752 res))
13754 (defun org-delete-all (elts list)
13755 "Remove all elements in ELTS from LIST."
13756 (while elts
13757 (setq list (delete (pop elts) list)))
13758 list)
13760 (defun org-back-over-empty-lines ()
13761 "Move backwards over witespace, to the beginning of the first empty line.
13762 Returns the number of empty lines passed."
13763 (let ((pos (point)))
13764 (skip-chars-backward " \t\n\r")
13765 (beginning-of-line 2)
13766 (goto-char (min (point) pos))
13767 (count-lines (point) pos)))
13769 (defun org-skip-whitespace ()
13770 (skip-chars-forward " \t\n\r"))
13772 (defun org-point-in-group (point group &optional context)
13773 "Check if POINT is in match-group GROUP.
13774 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13775 match. If the match group does ot exist or point is not inside it,
13776 return nil."
13777 (and (match-beginning group)
13778 (>= point (match-beginning group))
13779 (<= point (match-end group))
13780 (if context
13781 (list context (match-beginning group) (match-end group))
13782 t)))
13784 (defun org-switch-to-buffer-other-window (&rest args)
13785 "Switch to buffer in a second window on the current frame.
13786 In particular, do not allow pop-up frames."
13787 (let (pop-up-frames special-display-buffer-names special-display-regexps
13788 special-display-function)
13789 (apply 'switch-to-buffer-other-window args)))
13791 (defun org-combine-plists (&rest plists)
13792 "Create a single property list from all plists in PLISTS.
13793 The process starts by copying the first list, and then setting properties
13794 from the other lists. Settings in the last list are the most significant
13795 ones and overrule settings in the other lists."
13796 (let ((rtn (copy-sequence (pop plists)))
13797 p v ls)
13798 (while plists
13799 (setq ls (pop plists))
13800 (while ls
13801 (setq p (pop ls) v (pop ls))
13802 (setq rtn (plist-put rtn p v))))
13803 rtn))
13805 (defun org-move-line-down (arg)
13806 "Move the current line down. With prefix argument, move it past ARG lines."
13807 (interactive "p")
13808 (let ((col (current-column))
13809 beg end pos)
13810 (beginning-of-line 1) (setq beg (point))
13811 (beginning-of-line 2) (setq end (point))
13812 (beginning-of-line (+ 1 arg))
13813 (setq pos (move-marker (make-marker) (point)))
13814 (insert (delete-and-extract-region beg end))
13815 (goto-char pos)
13816 (org-move-to-column col)))
13818 (defun org-move-line-up (arg)
13819 "Move the current line up. With prefix argument, move it past ARG lines."
13820 (interactive "p")
13821 (let ((col (current-column))
13822 beg end pos)
13823 (beginning-of-line 1) (setq beg (point))
13824 (beginning-of-line 2) (setq end (point))
13825 (beginning-of-line (- arg))
13826 (setq pos (move-marker (make-marker) (point)))
13827 (insert (delete-and-extract-region beg end))
13828 (goto-char pos)
13829 (org-move-to-column col)))
13831 (defun org-replace-escapes (string table)
13832 "Replace %-escapes in STRING with values in TABLE.
13833 TABLE is an association list with keys like \"%a\" and string values.
13834 The sequences in STRING may contain normal field width and padding information,
13835 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13836 so values can contain further %-escapes if they are define later in TABLE."
13837 (let ((case-fold-search nil)
13838 e re rpl)
13839 (while (setq e (pop table))
13840 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13841 (while (string-match re string)
13842 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13843 (cdr e)))
13844 (setq string (replace-match rpl t t string))))
13845 string))
13848 (defun org-sublist (list start end)
13849 "Return a section of LIST, from START to END.
13850 Counting starts at 1."
13851 (let (rtn (c start))
13852 (setq list (nthcdr (1- start) list))
13853 (while (and list (<= c end))
13854 (push (pop list) rtn)
13855 (setq c (1+ c)))
13856 (nreverse rtn)))
13858 (defun org-find-base-buffer-visiting (file)
13859 "Like `find-buffer-visiting' but alway return the base buffer and
13860 not an indirect buffer."
13861 (let ((buf (find-buffer-visiting file)))
13862 (if buf
13863 (or (buffer-base-buffer buf) buf)
13864 nil)))
13866 (defun org-image-file-name-regexp ()
13867 "Return regexp matching the file names of images."
13868 (if (fboundp 'image-file-name-regexp)
13869 (image-file-name-regexp)
13870 (let ((image-file-name-extensions
13871 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13872 "xbm" "xpm" "pbm" "pgm" "ppm")))
13873 (concat "\\."
13874 (regexp-opt (nconc (mapcar 'upcase
13875 image-file-name-extensions)
13876 image-file-name-extensions)
13878 "\\'"))))
13880 (defun org-file-image-p (file)
13881 "Return non-nil if FILE is an image."
13882 (save-match-data
13883 (string-match (org-image-file-name-regexp) file)))
13885 (defun org-get-cursor-date ()
13886 "Return the date at cursor in as a time.
13887 This works in the calendar and in the agenda, anywhere else it just
13888 returns the current time."
13889 (let (date day defd)
13890 (cond
13891 ((eq major-mode 'calendar-mode)
13892 (setq date (calendar-cursor-to-date)
13893 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13894 ((eq major-mode 'org-agenda-mode)
13895 (setq day (get-text-property (point) 'day))
13896 (if day
13897 (setq date (calendar-gregorian-from-absolute day)
13898 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13899 (nth 2 date))))))
13900 (or defd (current-time))))
13902 (defvar org-agenda-action-marker (make-marker)
13903 "Marker pointing to the entry for the next agenda action.")
13905 (defun org-mark-entry-for-agenda-action ()
13906 "Mark the current entry as target of an agenda action.
13907 Agenda actions are actions executed from the agenda with the key `k',
13908 which make use of the date at the cursor."
13909 (interactive)
13910 (move-marker org-agenda-action-marker
13911 (save-excursion (org-back-to-heading t) (point))
13912 (current-buffer))
13913 (message
13914 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13916 ;;; Paragraph filling stuff.
13917 ;; We want this to be just right, so use the full arsenal.
13919 (defun org-indent-line-function ()
13920 "Indent line like previous, but further if previous was headline or item."
13921 (interactive)
13922 (let* ((pos (point))
13923 (itemp (org-at-item-p))
13924 column bpos bcol tpos tcol bullet btype bullet-type)
13925 ;; Find the previous relevant line
13926 (beginning-of-line 1)
13927 (cond
13928 ((looking-at "#") (setq column 0))
13929 ((looking-at "\\*+ ") (setq column 0))
13931 (beginning-of-line 0)
13932 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13933 (beginning-of-line 0))
13934 (cond
13935 ((looking-at "\\*+[ \t]+")
13936 (if (not org-adapt-indentation)
13937 (setq column 0)
13938 (goto-char (match-end 0))
13939 (setq column (current-column))))
13940 ((org-in-item-p)
13941 (org-beginning-of-item)
13942 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13943 (setq bpos (match-beginning 1) tpos (match-end 0)
13944 bcol (progn (goto-char bpos) (current-column))
13945 tcol (progn (goto-char tpos) (current-column))
13946 bullet (match-string 1)
13947 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13948 (if (> tcol (+ bcol org-description-max-indent))
13949 (setq tcol (+ bcol 5)))
13950 (if (not itemp)
13951 (setq column tcol)
13952 (goto-char pos)
13953 (beginning-of-line 1)
13954 (if (looking-at "\\S-")
13955 (progn
13956 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13957 (setq bullet (match-string 1)
13958 btype (if (string-match "[0-9]" bullet) "n" bullet))
13959 (setq column (if (equal btype bullet-type) bcol tcol)))
13960 (setq column (org-get-indentation)))))
13961 (t (setq column (org-get-indentation))))))
13962 (goto-char pos)
13963 (if (<= (current-column) (current-indentation))
13964 (org-indent-line-to column)
13965 (save-excursion (org-indent-line-to column)))
13966 (setq column (current-column))
13967 (beginning-of-line 1)
13968 (if (looking-at
13969 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13970 (replace-match (concat "\\1" (format org-property-format
13971 (match-string 2) (match-string 3)))
13972 t nil))
13973 (org-move-to-column column)))
13975 (defun org-set-autofill-regexps ()
13976 (interactive)
13977 ;; In the paragraph separator we include headlines, because filling
13978 ;; text in a line directly attached to a headline would otherwise
13979 ;; fill the headline as well.
13980 (org-set-local 'comment-start-skip "^#+[ \t]*")
13981 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13982 ;; The paragraph starter includes hand-formatted lists.
13983 (org-set-local 'paragraph-start
13984 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13985 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13986 ;; But only if the user has not turned off tables or fixed-width regions
13987 (org-set-local
13988 'auto-fill-inhibit-regexp
13989 (concat "\\*+ \\|#\\+"
13990 "\\|[ \t]*" org-keyword-time-regexp
13991 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13992 (concat
13993 "\\|[ \t]*["
13994 (if org-enable-table-editor "|" "")
13995 (if org-enable-fixed-width-editor ":" "")
13996 "]"))))
13997 ;; We use our own fill-paragraph function, to make sure that tables
13998 ;; and fixed-width regions are not wrapped. That function will pass
13999 ;; through to `fill-paragraph' when appropriate.
14000 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14001 ; Adaptive filling: To get full control, first make sure that
14002 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14003 (org-set-local 'adaptive-fill-regexp "\000")
14004 (org-set-local 'adaptive-fill-function
14005 'org-adaptive-fill-function)
14006 (org-set-local
14007 'align-mode-rules-list
14008 '((org-in-buffer-settings
14009 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14010 (modes . '(org-mode))))))
14012 (defun org-fill-paragraph (&optional justify)
14013 "Re-align a table, pass through to fill-paragraph if no table."
14014 (let ((table-p (org-at-table-p))
14015 (table.el-p (org-at-table.el-p)))
14016 (cond ((and (equal (char-after (point-at-bol)) ?*)
14017 (save-excursion (goto-char (point-at-bol))
14018 (looking-at outline-regexp)))
14019 t) ; skip headlines
14020 (table.el-p t) ; skip table.el tables
14021 (table-p (org-table-align) t) ; align org-mode tables
14022 (t nil)))) ; call paragraph-fill
14024 ;; For reference, this is the default value of adaptive-fill-regexp
14025 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14027 (defun org-adaptive-fill-function ()
14028 "Return a fill prefix for org-mode files.
14029 In particular, this makes sure hanging paragraphs for hand-formatted lists
14030 work correctly."
14031 (cond ((looking-at "#[ \t]+")
14032 (match-string 0))
14033 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14034 (save-excursion
14035 (if (> (match-end 1) (+ (match-beginning 1)
14036 org-description-max-indent))
14037 (goto-char (+ (match-beginning 1) 5))
14038 (goto-char (match-end 0)))
14039 (make-string (current-column) ?\ )))
14040 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14041 (save-excursion
14042 (goto-char (match-end 0))
14043 (make-string (current-column) ?\ )))
14044 (t nil)))
14046 ;;; Other stuff.
14048 (defun org-toggle-fixed-width-section (arg)
14049 "Toggle the fixed-width export.
14050 If there is no active region, the QUOTE keyword at the current headline is
14051 inserted or removed. When present, it causes the text between this headline
14052 and the next to be exported as fixed-width text, and unmodified.
14053 If there is an active region, this command adds or removes a colon as the
14054 first character of this line. If the first character of a line is a colon,
14055 this line is also exported in fixed-width font."
14056 (interactive "P")
14057 (let* ((cc 0)
14058 (regionp (org-region-active-p))
14059 (beg (if regionp (region-beginning) (point)))
14060 (end (if regionp (region-end)))
14061 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14062 (case-fold-search nil)
14063 (re "[ \t]*\\(:\\)")
14064 off)
14065 (if regionp
14066 (save-excursion
14067 (goto-char beg)
14068 (setq cc (current-column))
14069 (beginning-of-line 1)
14070 (setq off (looking-at re))
14071 (while (> nlines 0)
14072 (setq nlines (1- nlines))
14073 (beginning-of-line 1)
14074 (cond
14075 (arg
14076 (org-move-to-column cc t)
14077 (insert ":\n")
14078 (forward-line -1))
14079 ((and off (looking-at re))
14080 (replace-match "" t t nil 1))
14081 ((not off) (org-move-to-column cc t) (insert ":")))
14082 (forward-line 1)))
14083 (save-excursion
14084 (org-back-to-heading)
14085 (if (looking-at (concat outline-regexp
14086 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14087 (replace-match "" t t nil 1)
14088 (if (looking-at outline-regexp)
14089 (progn
14090 (goto-char (match-end 0))
14091 (insert org-quote-string " "))))))))
14093 ;;;; Functions extending outline functionality
14095 (defun org-beginning-of-line (&optional arg)
14096 "Go to the beginning of the current line. If that is invisible, continue
14097 to a visible line beginning. This makes the function of C-a more intuitive.
14098 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14099 first attempt, and only move to after the tags when the cursor is already
14100 beyond the end of the headline."
14101 (interactive "P")
14102 (let ((pos (point)) refpos)
14103 (beginning-of-line 1)
14104 (if (bobp)
14106 (backward-char 1)
14107 (if (org-invisible-p)
14108 (while (and (not (bobp)) (org-invisible-p))
14109 (backward-char 1)
14110 (beginning-of-line 1))
14111 (forward-char 1)))
14112 (when org-special-ctrl-a/e
14113 (cond
14114 ((and (looking-at org-complex-heading-regexp)
14115 (= (char-after (match-end 1)) ?\ ))
14116 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14117 (point-at-eol)))
14118 (goto-char
14119 (if (eq org-special-ctrl-a/e t)
14120 (cond ((> pos refpos) refpos)
14121 ((= pos (point)) refpos)
14122 (t (point)))
14123 (cond ((> pos (point)) (point))
14124 ((not (eq last-command this-command)) (point))
14125 (t refpos)))))
14126 ((org-at-item-p)
14127 (goto-char
14128 (if (eq org-special-ctrl-a/e t)
14129 (cond ((> pos (match-end 4)) (match-end 4))
14130 ((= pos (point)) (match-end 4))
14131 (t (point)))
14132 (cond ((> pos (point)) (point))
14133 ((not (eq last-command this-command)) (point))
14134 (t (match-end 4))))))))
14135 (org-no-warnings
14136 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14138 (defun org-end-of-line (&optional arg)
14139 "Go to the end of the line.
14140 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14141 first attempt, and only move to after the tags when the cursor is already
14142 beyond the end of the headline."
14143 (interactive "P")
14144 (if (or (not org-special-ctrl-a/e)
14145 (not (org-on-heading-p)))
14146 (end-of-line arg)
14147 (let ((pos (point)))
14148 (beginning-of-line 1)
14149 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14150 (if (eq org-special-ctrl-a/e t)
14151 (if (or (< pos (match-beginning 1))
14152 (= pos (match-end 0)))
14153 (goto-char (match-beginning 1))
14154 (goto-char (match-end 0)))
14155 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14156 (goto-char (match-end 0))
14157 (goto-char (match-beginning 1))))
14158 (end-of-line arg))))
14159 (org-no-warnings
14160 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14163 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14164 (define-key org-mode-map "\C-e" 'org-end-of-line)
14166 (defun org-kill-line (&optional arg)
14167 "Kill line, to tags or end of line."
14168 (interactive "P")
14169 (cond
14170 ((or (not org-special-ctrl-k)
14171 (bolp)
14172 (not (org-on-heading-p)))
14173 (call-interactively 'kill-line))
14174 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14175 (kill-region (point) (match-beginning 1))
14176 (org-set-tags nil t))
14177 (t (kill-region (point) (point-at-eol)))))
14179 (define-key org-mode-map "\C-k" 'org-kill-line)
14181 (defun org-yank (&optional arg)
14182 "Yank. If the kill is a subtree, treat it specially.
14183 This command will look at the current kill and check if is a single
14184 subtree, or a series of subtrees[1]. If it passes the test, and if the
14185 cursor is at the beginning of a line or after the stars of a currently
14186 empty headline, then the yank is handeled specially. How exactly depends
14187 on the value of the following variables, both set by default.
14189 org-yank-folded-subtrees
14190 When set, the subree(s) will be folded after insertion, but only
14191 if doing so would now swallow text after the yanked text.
14193 org-yank-adjusted-subtrees
14194 When set, the subtree will be promoted or demoted in order to
14195 fit into the local outline tree structure, which means that the level
14196 will be adjusted so that it becomes the smaller one of the two
14197 *visible* surrounding headings.
14199 Any prefix to this command will cause `yank' to be called directly with
14200 no special treatment. In particular, a simple `C-u' prefix will just
14201 plainly yank the text as it is.
14203 \[1] Basically, the test checks if the first non-white line is a heading
14204 and if there are no other headings with fewer stars."
14205 (interactive "P")
14206 (setq this-command 'yank)
14207 (if arg
14208 (call-interactively 'yank)
14209 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14210 (and (org-kill-is-subtree-p)
14211 (or (bolp)
14212 (and (looking-at "[ \t]*$")
14213 (string-match
14214 "\\`\\*+\\'"
14215 (buffer-substring (point-at-bol) (point)))))))
14216 swallowp)
14217 (cond
14218 ((and subtreep org-yank-folded-subtrees)
14219 (let ((beg (point))
14220 end)
14221 (if (and subtreep org-yank-adjusted-subtrees)
14222 (org-paste-subtree nil nil 'for-yank)
14223 (call-interactively 'yank))
14224 (setq end (point))
14225 (goto-char beg)
14226 (when (and (bolp) subtreep
14227 (not (setq swallowp
14228 (org-yank-folding-would-swallow-text beg end))))
14229 (or (looking-at outline-regexp)
14230 (re-search-forward (concat "^" outline-regexp) end t))
14231 (while (and (< (point) end) (looking-at outline-regexp))
14232 (hide-subtree)
14233 (org-cycle-show-empty-lines 'folded)
14234 (condition-case nil
14235 (outline-forward-same-level 1)
14236 (error (goto-char end)))))
14237 (when swallowp
14238 (message
14239 "Yanked text not folded because that would swallow text"))
14240 (goto-char end)
14241 (skip-chars-forward " \t\n\r")
14242 (beginning-of-line 1)
14243 (push-mark beg 'nomsg)))
14244 ((and subtreep org-yank-adjusted-subtrees)
14245 (let ((beg (point-at-bol)))
14246 (org-paste-subtree nil nil 'for-yank)
14247 (push-mark beg 'nomsg)))
14249 (call-interactively 'yank))))))
14251 (defun org-yank-folding-would-swallow-text (beg end)
14252 "Would hide-subtree at BEG swallow any text after END?"
14253 (let (level)
14254 (save-excursion
14255 (goto-char beg)
14256 (when (or (looking-at outline-regexp)
14257 (re-search-forward (concat "^" outline-regexp) end t))
14258 (setq level (org-outline-level)))
14259 (goto-char end)
14260 (skip-chars-forward " \t\r\n\v\f")
14261 (if (or (eobp)
14262 (and (bolp) (looking-at org-outline-regexp)
14263 (<= (org-outline-level) level)))
14264 nil ; Nothing would be swallowed
14265 t)))) ; something would swallow
14267 (define-key org-mode-map "\C-y" 'org-yank)
14269 (defun org-invisible-p ()
14270 "Check if point is at a character currently not visible."
14271 ;; Early versions of noutline don't have `outline-invisible-p'.
14272 (if (fboundp 'outline-invisible-p)
14273 (outline-invisible-p)
14274 (get-char-property (point) 'invisible)))
14276 (defun org-invisible-p2 ()
14277 "Check if point is at a character currently not visible."
14278 (save-excursion
14279 (if (and (eolp) (not (bobp))) (backward-char 1))
14280 ;; Early versions of noutline don't have `outline-invisible-p'.
14281 (if (fboundp 'outline-invisible-p)
14282 (outline-invisible-p)
14283 (get-char-property (point) 'invisible))))
14285 (defun org-back-to-heading (&optional invisible-ok)
14286 "Call `outline-back-to-heading', but provide a better error message."
14287 (condition-case nil
14288 (outline-back-to-heading invisible-ok)
14289 (error (error "Before first headline at position %d in buffer %s"
14290 (point) (current-buffer)))))
14292 (defalias 'org-on-heading-p 'outline-on-heading-p)
14293 (defalias 'org-at-heading-p 'outline-on-heading-p)
14294 (defun org-at-heading-or-item-p ()
14295 (or (org-on-heading-p) (org-at-item-p)))
14297 (defun org-on-target-p ()
14298 (or (org-in-regexp org-radio-target-regexp)
14299 (org-in-regexp org-target-regexp)))
14301 (defun org-up-heading-all (arg)
14302 "Move to the heading line of which the present line is a subheading.
14303 This function considers both visible and invisible heading lines.
14304 With argument, move up ARG levels."
14305 (if (fboundp 'outline-up-heading-all)
14306 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14307 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14309 (defun org-up-heading-safe ()
14310 "Move to the heading line of which the present line is a subheading.
14311 This version will not throw an error. It will return the level of the
14312 headline found, or nil if no higher level is found."
14313 (let ((pos (point)) start-level level
14314 (re (concat "^" outline-regexp)))
14315 (catch 'exit
14316 (org-back-to-heading t)
14317 (setq start-level (funcall outline-level))
14318 (if (equal start-level 1) (throw 'exit nil))
14319 (while (re-search-backward re nil t)
14320 (setq level (funcall outline-level))
14321 (if (< level start-level) (throw 'exit level)))
14322 nil)))
14324 (defun org-first-sibling-p ()
14325 "Is this heading the first child of its parents?"
14326 (interactive)
14327 (let ((re (concat "^" outline-regexp))
14328 level l)
14329 (unless (org-at-heading-p t)
14330 (error "Not at a heading"))
14331 (setq level (funcall outline-level))
14332 (save-excursion
14333 (if (not (re-search-backward re nil t))
14335 (setq l (funcall outline-level))
14336 (< l level)))))
14338 (defun org-goto-sibling (&optional previous)
14339 "Goto the next sibling, even if it is invisible.
14340 When PREVIOUS is set, go to the previous sibling instead. Returns t
14341 when a sibling was found. When none is found, return nil and don't
14342 move point."
14343 (let ((fun (if previous 're-search-backward 're-search-forward))
14344 (pos (point))
14345 (re (concat "^" outline-regexp))
14346 level l)
14347 (when (condition-case nil (org-back-to-heading t) (error nil))
14348 (setq level (funcall outline-level))
14349 (catch 'exit
14350 (or previous (forward-char 1))
14351 (while (funcall fun re nil t)
14352 (setq l (funcall outline-level))
14353 (when (< l level) (goto-char pos) (throw 'exit nil))
14354 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14355 (goto-char pos)
14356 nil))))
14358 (defun org-show-siblings ()
14359 "Show all siblings of the current headline."
14360 (save-excursion
14361 (while (org-goto-sibling) (org-flag-heading nil)))
14362 (save-excursion
14363 (while (org-goto-sibling 'previous)
14364 (org-flag-heading nil))))
14366 (defun org-show-hidden-entry ()
14367 "Show an entry where even the heading is hidden."
14368 (save-excursion
14369 (org-show-entry)))
14371 (defun org-flag-heading (flag &optional entry)
14372 "Flag the current heading. FLAG non-nil means make invisible.
14373 When ENTRY is non-nil, show the entire entry."
14374 (save-excursion
14375 (org-back-to-heading t)
14376 ;; Check if we should show the entire entry
14377 (if entry
14378 (progn
14379 (org-show-entry)
14380 (save-excursion
14381 (and (outline-next-heading)
14382 (org-flag-heading nil))))
14383 (outline-flag-region (max (point-min) (1- (point)))
14384 (save-excursion (outline-end-of-heading) (point))
14385 flag))))
14387 (defun org-forward-same-level (arg)
14388 "Move forward to the ARG'th subheading at same level as this one.
14389 Stop at the first and last subheadings of a superior heading.
14390 This is like outline-forward-same-level, but invisible headings are ok."
14391 (interactive "p")
14392 (org-back-to-heading t)
14393 (while (> arg 0)
14394 (let ((point-to-move-to (save-excursion
14395 (org-get-next-sibling))))
14396 (if point-to-move-to
14397 (progn
14398 (goto-char point-to-move-to)
14399 (setq arg (1- arg)))
14400 (progn
14401 (setq arg 0)
14402 (error "No following same-level heading"))))))
14404 (defun org-get-next-sibling ()
14405 "Move to next heading of the same level, and return point.
14406 If there is no such heading, return nil.
14407 This is like outline-next-sibling, but invisible headings are ok."
14408 (let ((level (funcall outline-level)))
14409 (outline-next-heading)
14410 (while (and (not (eobp)) (> (funcall outline-level) level))
14411 (outline-next-heading))
14412 (if (or (eobp) (< (funcall outline-level) level))
14414 (point))))
14416 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14417 ;; This is an exact copy of the original function, but it uses
14418 ;; `org-back-to-heading', to make it work also in invisible
14419 ;; trees. And is uses an invisible-OK argument.
14420 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14421 (org-back-to-heading invisible-OK)
14422 (let ((first t)
14423 (level (funcall outline-level)))
14424 (while (and (not (eobp))
14425 (or first (> (funcall outline-level) level)))
14426 (setq first nil)
14427 (outline-next-heading))
14428 (unless to-heading
14429 (if (memq (preceding-char) '(?\n ?\^M))
14430 (progn
14431 ;; Go to end of line before heading
14432 (forward-char -1)
14433 (if (memq (preceding-char) '(?\n ?\^M))
14434 ;; leave blank line before heading
14435 (forward-char -1))))))
14436 (point))
14438 (defun org-show-subtree ()
14439 "Show everything after this heading at deeper levels."
14440 (outline-flag-region
14441 (point)
14442 (save-excursion
14443 (outline-end-of-subtree) (outline-next-heading) (point))
14444 nil))
14446 (defun org-show-entry ()
14447 "Show the body directly following this heading.
14448 Show the heading too, if it is currently invisible."
14449 (interactive)
14450 (save-excursion
14451 (condition-case nil
14452 (progn
14453 (org-back-to-heading t)
14454 (outline-flag-region
14455 (max (point-min) (1- (point)))
14456 (save-excursion
14457 (re-search-forward
14458 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14459 (or (match-beginning 1) (point-max)))
14460 nil))
14461 (error nil))))
14463 (defun org-make-options-regexp (kwds)
14464 "Make a regular expression for keyword lines."
14465 (concat
14467 "#?[ \t]*\\+\\("
14468 (mapconcat 'regexp-quote kwds "\\|")
14469 "\\):[ \t]*"
14470 "\\(.+\\)"))
14472 ;; Make isearch reveal the necessary context
14473 (defun org-isearch-end ()
14474 "Reveal context after isearch exits."
14475 (when isearch-success ; only if search was successful
14476 (if (featurep 'xemacs)
14477 ;; Under XEmacs, the hook is run in the correct place,
14478 ;; we directly show the context.
14479 (org-show-context 'isearch)
14480 ;; In Emacs the hook runs *before* restoring the overlays.
14481 ;; So we have to use a one-time post-command-hook to do this.
14482 ;; (Emacs 22 has a special variable, see function `org-mode')
14483 (unless (and (boundp 'isearch-mode-end-hook-quit)
14484 isearch-mode-end-hook-quit)
14485 ;; Only when the isearch was not quitted.
14486 (org-add-hook 'post-command-hook 'org-isearch-post-command
14487 'append 'local)))))
14489 (defun org-isearch-post-command ()
14490 "Remove self from hook, and show context."
14491 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14492 (org-show-context 'isearch))
14495 ;;;; Integration with and fixes for other packages
14497 ;;; Imenu support
14499 (defvar org-imenu-markers nil
14500 "All markers currently used by Imenu.")
14501 (make-variable-buffer-local 'org-imenu-markers)
14503 (defun org-imenu-new-marker (&optional pos)
14504 "Return a new marker for use by Imenu, and remember the marker."
14505 (let ((m (make-marker)))
14506 (move-marker m (or pos (point)))
14507 (push m org-imenu-markers)
14510 (defun org-imenu-get-tree ()
14511 "Produce the index for Imenu."
14512 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14513 (setq org-imenu-markers nil)
14514 (let* ((n org-imenu-depth)
14515 (re (concat "^" outline-regexp))
14516 (subs (make-vector (1+ n) nil))
14517 (last-level 0)
14518 m tree level head)
14519 (save-excursion
14520 (save-restriction
14521 (widen)
14522 (goto-char (point-max))
14523 (while (re-search-backward re nil t)
14524 (setq level (org-reduced-level (funcall outline-level)))
14525 (when (<= level n)
14526 (looking-at org-complex-heading-regexp)
14527 (setq head (org-link-display-format
14528 (org-match-string-no-properties 4))
14529 m (org-imenu-new-marker))
14530 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14531 (if (>= level last-level)
14532 (push (cons head m) (aref subs level))
14533 (push (cons head (aref subs (1+ level))) (aref subs level))
14534 (loop for i from (1+ level) to n do (aset subs i nil)))
14535 (setq last-level level)))))
14536 (aref subs 1)))
14538 (eval-after-load "imenu"
14539 '(progn
14540 (add-hook 'imenu-after-jump-hook
14541 (lambda ()
14542 (if (eq major-mode 'org-mode)
14543 (org-show-context 'org-goto))))))
14545 (defun org-link-display-format (link)
14546 "Replace a link with either the description, or the link target
14547 if no description is present"
14548 (save-match-data
14549 (if (string-match org-bracket-link-analytic-regexp link)
14550 (replace-match (or (match-string 5 link)
14551 (concat (match-string 1 link)
14552 (match-string 3 link)))
14553 nil nil link)
14554 link)))
14556 ;; Speedbar support
14558 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14559 "Overlay marking the agenda restriction line in speedbar.")
14560 (org-overlay-put org-speedbar-restriction-lock-overlay
14561 'face 'org-agenda-restriction-lock)
14562 (org-overlay-put org-speedbar-restriction-lock-overlay
14563 'help-echo "Agendas are currently limited to this item.")
14564 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14566 (defun org-speedbar-set-agenda-restriction ()
14567 "Restrict future agenda commands to the location at point in speedbar.
14568 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14569 (interactive)
14570 (require 'org-agenda)
14571 (let (p m tp np dir txt w)
14572 (cond
14573 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14574 'org-imenu t))
14575 (setq m (get-text-property p 'org-imenu-marker))
14576 (save-excursion
14577 (save-restriction
14578 (set-buffer (marker-buffer m))
14579 (goto-char m)
14580 (org-agenda-set-restriction-lock 'subtree))))
14581 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14582 'speedbar-function 'speedbar-find-file))
14583 (setq tp (previous-single-property-change
14584 (1+ p) 'speedbar-function)
14585 np (next-single-property-change
14586 tp 'speedbar-function)
14587 dir (speedbar-line-directory)
14588 txt (buffer-substring-no-properties (or tp (point-min))
14589 (or np (point-max))))
14590 (save-excursion
14591 (save-restriction
14592 (set-buffer (find-file-noselect
14593 (let ((default-directory dir))
14594 (expand-file-name txt))))
14595 (unless (org-mode-p)
14596 (error "Cannot restrict to non-Org-mode file"))
14597 (org-agenda-set-restriction-lock 'file))))
14598 (t (error "Don't know how to restrict Org-mode's agenda")))
14599 (org-move-overlay org-speedbar-restriction-lock-overlay
14600 (point-at-bol) (point-at-eol))
14601 (setq current-prefix-arg nil)
14602 (org-agenda-maybe-redo)))
14604 (eval-after-load "speedbar"
14605 '(progn
14606 (speedbar-add-supported-extension ".org")
14607 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14608 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14609 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14610 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14611 (add-hook 'speedbar-visiting-tag-hook
14612 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14615 ;;; Fixes and Hacks for problems with other packages
14617 ;; Make flyspell not check words in links, to not mess up our keymap
14618 (defun org-mode-flyspell-verify ()
14619 "Don't let flyspell put overlays at active buttons."
14620 (not (get-text-property (point) 'keymap)))
14622 ;; Make `bookmark-jump' show the jump location if it was hidden.
14623 (eval-after-load "bookmark"
14624 '(if (boundp 'bookmark-after-jump-hook)
14625 ;; We can use the hook
14626 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14627 ;; Hook not available, use advice
14628 (defadvice bookmark-jump (after org-make-visible activate)
14629 "Make the position visible."
14630 (org-bookmark-jump-unhide))))
14632 ;; Make sure saveplace show the location if it was hidden
14633 (eval-after-load "saveplace"
14634 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14635 "Make the position visible."
14636 (org-bookmark-jump-unhide)))
14638 (defun org-bookmark-jump-unhide ()
14639 "Unhide the current position, to show the bookmark location."
14640 (and (org-mode-p)
14641 (or (org-invisible-p)
14642 (save-excursion (goto-char (max (point-min) (1- (point))))
14643 (org-invisible-p)))
14644 (org-show-context 'bookmark-jump)))
14646 ;; Make session.el ignore our circular variable
14647 (eval-after-load "session"
14648 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14650 ;;;; Experimental code
14652 (defun org-closed-in-range ()
14653 "Sparse tree of items closed in a certain time range.
14654 Still experimental, may disappear in the future."
14655 (interactive)
14656 ;; Get the time interval from the user.
14657 (let* ((time1 (time-to-seconds
14658 (org-read-date nil 'to-time nil "Starting date: ")))
14659 (time2 (time-to-seconds
14660 (org-read-date nil 'to-time nil "End date:")))
14661 ;; callback function
14662 (callback (lambda ()
14663 (let ((time
14664 (time-to-seconds
14665 (apply 'encode-time
14666 (org-parse-time-string
14667 (match-string 1))))))
14668 ;; check if time in interval
14669 (and (>= time time1) (<= time time2))))))
14670 ;; make tree, check each match with the callback
14671 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14674 ;;;; Finish up
14676 (provide 'org)
14678 (run-hooks 'org-load-hook)
14680 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14682 ;;; org.el ends here