Fix publishing of component files.
[org-mode.git] / lisp / org.el
blob340737be9396b14badb6a3dab01f5878e6ad03c7
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.13a
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.13a"
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-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 " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
184 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
185 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
186 (const :tag "C id: Global id's for identifying entries" org-id)
187 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
188 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
189 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
190 (const :tag "C mtags: Support for muse-like tags" org-mtags)
191 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
192 (const :tag "C registry: A registry for Org links" org-registry)
193 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
194 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
195 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
196 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
197 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
200 (defgroup org-startup nil
201 "Options concerning startup of Org-mode."
202 :tag "Org Startup"
203 :group 'org)
205 (defcustom org-startup-folded t
206 "Non-nil means, entering Org-mode will switch to OVERVIEW.
207 This can also be configured on a per-file basis by adding one of
208 the following lines anywhere in the buffer:
210 #+STARTUP: fold
211 #+STARTUP: nofold
212 #+STARTUP: content"
213 :group 'org-startup
214 :type '(choice
215 (const :tag "nofold: show all" nil)
216 (const :tag "fold: overview" t)
217 (const :tag "content: all headlines" content)))
219 (defcustom org-startup-truncated t
220 "Non-nil means, entering Org-mode will set `truncate-lines'.
221 This is useful since some lines containing links can be very long and
222 uninteresting. Also tables look terrible when wrapped."
223 :group 'org-startup
224 :type 'boolean)
226 (defcustom org-startup-align-all-tables nil
227 "Non-nil means, align all tables when visiting a file.
228 This is useful when the column width in tables is forced with <N> cookies
229 in table fields. Such tables will look correct only after the first re-align.
230 This can also be configured on a per-file basis by adding one of
231 the following lines anywhere in the buffer:
232 #+STARTUP: align
233 #+STARTUP: noalign"
234 :group 'org-startup
235 :type 'boolean)
237 (defcustom org-insert-mode-line-in-empty-file nil
238 "Non-nil means insert the first line setting Org-mode in empty files.
239 When the function `org-mode' is called interactively in an empty file, this
240 normally means that the file name does not automatically trigger Org-mode.
241 To ensure that the file will always be in Org-mode in the future, a
242 line enforcing Org-mode will be inserted into the buffer, if this option
243 has been set."
244 :group 'org-startup
245 :type 'boolean)
247 (defcustom org-replace-disputed-keys nil
248 "Non-nil means use alternative key bindings for some keys.
249 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
250 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
251 If you want to use Org-mode together with one of these other modes,
252 or more generally if you would like to move some Org-mode commands to
253 other keys, set this variable and configure the keys with the variable
254 `org-disputed-keys'.
256 This option is only relevant at load-time of Org-mode, and must be set
257 *before* org.el is loaded. Changing it requires a restart of Emacs to
258 become effective."
259 :group 'org-startup
260 :type 'boolean)
262 (defcustom org-use-extra-keys nil
263 "Non-nil means use extra key sequence definitions for certain
264 commands. This happens automatically if you run XEmacs or if
265 window-system is nil. This variable lets you do the same
266 manually. You must set it before loading org.
268 Example: on Carbon Emacs 22 running graphically, with an external
269 keyboard on a Powerbook, the default way of setting M-left might
270 not work for either Alt or ESC. Setting this variable will make
271 it work for ESC."
272 :group 'org-startup
273 :type 'boolean)
275 (if (fboundp 'defvaralias)
276 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
278 (defcustom org-disputed-keys
279 '(([(shift up)] . [(meta p)])
280 ([(shift down)] . [(meta n)])
281 ([(shift left)] . [(meta -)])
282 ([(shift right)] . [(meta +)])
283 ([(control shift right)] . [(meta shift +)])
284 ([(control shift left)] . [(meta shift -)]))
285 "Keys for which Org-mode and other modes compete.
286 This is an alist, cars are the default keys, second element specifies
287 the alternative to use when `org-replace-disputed-keys' is t.
289 Keys can be specified in any syntax supported by `define-key'.
290 The value of this option takes effect only at Org-mode's startup,
291 therefore you'll have to restart Emacs to apply it after changing."
292 :group 'org-startup
293 :type 'alist)
295 (defun org-key (key)
296 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
297 Or return the original if not disputed."
298 (if org-replace-disputed-keys
299 (let* ((nkey (key-description key))
300 (x (org-find-if (lambda (x)
301 (equal (key-description (car x)) nkey))
302 org-disputed-keys)))
303 (if x (cdr x) key))
304 key))
306 (defun org-find-if (predicate seq)
307 (catch 'exit
308 (while seq
309 (if (funcall predicate (car seq))
310 (throw 'exit (car seq))
311 (pop seq)))))
313 (defun org-defkey (keymap key def)
314 "Define a key, possibly translated, as returned by `org-key'."
315 (define-key keymap (org-key key) def))
317 (defcustom org-ellipsis nil
318 "The ellipsis to use in the Org-mode outline.
319 When nil, just use the standard three dots. When a string, use that instead,
320 When a face, use the standart 3 dots, but with the specified face.
321 The change affects only Org-mode (which will then use its own display table).
322 Changing this requires executing `M-x org-mode' in a buffer to become
323 effective."
324 :group 'org-startup
325 :type '(choice (const :tag "Default" nil)
326 (face :tag "Face" :value org-warning)
327 (string :tag "String" :value "...#")))
329 (defvar org-display-table nil
330 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
332 (defgroup org-keywords nil
333 "Keywords in Org-mode."
334 :tag "Org Keywords"
335 :group 'org)
337 (defcustom org-deadline-string "DEADLINE:"
338 "String to mark deadline entries.
339 A deadline is this string, followed by a time stamp. Should be a word,
340 terminated by a colon. You can insert a schedule keyword and
341 a timestamp with \\[org-deadline].
342 Changes become only effective after restarting Emacs."
343 :group 'org-keywords
344 :type 'string)
346 (defcustom org-scheduled-string "SCHEDULED:"
347 "String to mark scheduled TODO entries.
348 A schedule is this string, followed by a time stamp. Should be a word,
349 terminated by a colon. You can insert a schedule keyword and
350 a timestamp with \\[org-schedule].
351 Changes become only effective after restarting Emacs."
352 :group 'org-keywords
353 :type 'string)
355 (defcustom org-closed-string "CLOSED:"
356 "String used as the prefix for timestamps logging closing a TODO entry."
357 :group 'org-keywords
358 :type 'string)
360 (defcustom org-clock-string "CLOCK:"
361 "String used as prefix for timestamps clocking work hours on an item."
362 :group 'org-keywords
363 :type 'string)
365 (defcustom org-comment-string "COMMENT"
366 "Entries starting with this keyword will never be exported.
367 An entry can be toggled between COMMENT and normal with
368 \\[org-toggle-comment].
369 Changes become only effective after restarting Emacs."
370 :group 'org-keywords
371 :type 'string)
373 (defcustom org-quote-string "QUOTE"
374 "Entries starting with this keyword will be exported in fixed-width font.
375 Quoting applies only to the text in the entry following the headline, and does
376 not extend beyond the next headline, even if that is lower level.
377 An entry can be toggled between QUOTE and normal with
378 \\[org-toggle-fixed-width-section]."
379 :group 'org-keywords
380 :type 'string)
382 (defconst org-repeat-re
383 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
384 "Regular expression for specifying repeated events.
385 After a match, group 1 contains the repeat expression.")
387 (defgroup org-structure nil
388 "Options concerning the general structure of Org-mode files."
389 :tag "Org Structure"
390 :group 'org)
392 (defgroup org-reveal-location nil
393 "Options about how to make context of a location visible."
394 :tag "Org Reveal Location"
395 :group 'org-structure)
397 (defconst org-context-choice
398 '(choice
399 (const :tag "Always" t)
400 (const :tag "Never" nil)
401 (repeat :greedy t :tag "Individual contexts"
402 (cons
403 (choice :tag "Context"
404 (const agenda)
405 (const org-goto)
406 (const occur-tree)
407 (const tags-tree)
408 (const link-search)
409 (const mark-goto)
410 (const bookmark-jump)
411 (const isearch)
412 (const default))
413 (boolean))))
414 "Contexts for the reveal options.")
416 (defcustom org-show-hierarchy-above '((default . t))
417 "Non-nil means, show full hierarchy when revealing a location.
418 Org-mode often shows locations in an org-mode file which might have
419 been invisible before. When this is set, the hierarchy of headings
420 above the exposed location is shown.
421 Turning this off for example for sparse trees makes them very compact.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. Valid contexts are
424 agenda when exposing an entry from the agenda
425 org-goto when using the command `org-goto' on key C-c C-j
426 occur-tree when using the command `org-occur' on key C-c /
427 tags-tree when constructing a sparse tree based on tags matches
428 link-search when exposing search matches associated with a link
429 mark-goto when exposing the jump goal of a mark
430 bookmark-jump when exposing a bookmark location
431 isearch when exiting from an incremental search
432 default default for all contexts not set explicitly"
433 :group 'org-reveal-location
434 :type org-context-choice)
436 (defcustom org-show-following-heading '((default . nil))
437 "Non-nil means, show following heading when revealing a location.
438 Org-mode often shows locations in an org-mode file which might have
439 been invisible before. When this is set, the heading following the
440 match is shown.
441 Turning this off for example for sparse trees makes them very compact,
442 but makes it harder to edit the location of the match. In such a case,
443 use the command \\[org-reveal] to show more context.
444 Instead of t, this can also be an alist specifying this option for different
445 contexts. See `org-show-hierarchy-above' for valid contexts."
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-siblings '((default . nil) (isearch t))
450 "Non-nil means, show all sibling heading when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the sibling of the current entry
453 heading are all made visible. If `org-show-hierarchy-above' is t,
454 the same happens on each level of the hierarchy above the current entry.
456 By default this is on for the isearch context, off for all other contexts.
457 Turning this off for example for sparse trees makes them very compact,
458 but makes it harder to edit the location of the match. In such a case,
459 use the command \\[org-reveal] to show more context.
460 Instead of t, this can also be an alist specifying this option for different
461 contexts. See `org-show-hierarchy-above' for valid contexts."
462 :group 'org-reveal-location
463 :type org-context-choice)
465 (defcustom org-show-entry-below '((default . nil))
466 "Non-nil means, show the entry below a headline when revealing a location.
467 Org-mode often shows locations in an org-mode file which might have
468 been invisible before. When this is set, the text below the headline that is
469 exposed is also shown.
471 By default this is off for all contexts.
472 Instead of t, this can also be an alist specifying this option for different
473 contexts. See `org-show-hierarchy-above' for valid contexts."
474 :group 'org-reveal-location
475 :type org-context-choice)
477 (defcustom org-indirect-buffer-display 'other-window
478 "How should indirect tree buffers be displayed?
479 This applies to indirect buffers created with the commands
480 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
481 Valid values are:
482 current-window Display in the current window
483 other-window Just display in another window.
484 dedicated-frame Create one new frame, and re-use it each time.
485 new-frame Make a new frame each time. Note that in this case
486 previously-made indirect buffers are kept, and you need to
487 kill these buffers yourself."
488 :group 'org-structure
489 :group 'org-agenda-windows
490 :type '(choice
491 (const :tag "In current window" current-window)
492 (const :tag "In current frame, other window" other-window)
493 (const :tag "Each time a new frame" new-frame)
494 (const :tag "One dedicated frame" dedicated-frame)))
496 (defgroup org-cycle nil
497 "Options concerning visibility cycling in Org-mode."
498 :tag "Org Cycle"
499 :group 'org-structure)
501 (defcustom org-drawers '("PROPERTIES" "CLOCK")
502 "Names of drawers. Drawers are not opened by cycling on the headline above.
503 Drawers only open with a TAB on the drawer line itself. A drawer looks like
504 this:
505 :DRAWERNAME:
506 .....
507 :END:
508 The drawer \"PROPERTIES\" is special for capturing properties through
509 the property API.
511 Drawers can be defined on the per-file basis with a line like:
513 #+DRAWERS: HIDDEN STATE PROPERTIES"
514 :group 'org-structure
515 :type '(repeat (string :tag "Drawer Name")))
517 (defcustom org-cycle-global-at-bob nil
518 "Cycle globally if cursor is at beginning of buffer and not at a headline.
519 This makes it possible to do global cycling without having to use S-TAB or
520 C-u TAB. For this special case to work, the first line of the buffer
521 must not be a headline - it may be empty ot some other text. When used in
522 this way, `org-cycle-hook' is disables temporarily, to make sure the
523 cursor stays at the beginning of the buffer.
524 When this option is nil, don't do anything special at the beginning
525 of the buffer."
526 :group 'org-cycle
527 :type 'boolean)
529 (defcustom org-cycle-emulate-tab t
530 "Where should `org-cycle' emulate TAB.
531 nil Never
532 white Only in completely white lines
533 whitestart Only at the beginning of lines, before the first non-white char
534 t Everywhere except in headlines
535 exc-hl-bol Everywhere except at the start of a headline
536 If TAB is used in a place where it does not emulate TAB, the current subtree
537 visibility is cycled."
538 :group 'org-cycle
539 :type '(choice (const :tag "Never" nil)
540 (const :tag "Only in completely white lines" white)
541 (const :tag "Before first char in a line" whitestart)
542 (const :tag "Everywhere except in headlines" t)
543 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
546 (defcustom org-cycle-separator-lines 2
547 "Number of empty lines needed to keep an empty line between collapsed trees.
548 If you leave an empty line between the end of a subtree and the following
549 headline, this empty line is hidden when the subtree is folded.
550 Org-mode will leave (exactly) one empty line visible if the number of
551 empty lines is equal or larger to the number given in this variable.
552 So the default 2 means, at least 2 empty lines after the end of a subtree
553 are needed to produce free space between a collapsed subtree and the
554 following headline.
556 Special case: when 0, never leave empty lines in collapsed view."
557 :group 'org-cycle
558 :type 'integer)
559 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
561 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
562 org-cycle-hide-drawers
563 org-cycle-show-empty-lines
564 org-optimize-window-after-visibility-change)
565 "Hook that is run after `org-cycle' has changed the buffer visibility.
566 The function(s) in this hook must accept a single argument which indicates
567 the new state that was set by the most recent `org-cycle' command. The
568 argument is a symbol. After a global state change, it can have the values
569 `overview', `content', or `all'. After a local state change, it can have
570 the values `folded', `children', or `subtree'."
571 :group 'org-cycle
572 :type 'hook)
574 (defgroup org-edit-structure nil
575 "Options concerning structure editing in Org-mode."
576 :tag "Org Edit Structure"
577 :group 'org-structure)
579 (defcustom org-odd-levels-only nil
580 "Non-nil means, skip even levels and only use odd levels for the outline.
581 This has the effect that two stars are being added/taken away in
582 promotion/demotion commands. It also influences how levels are
583 handled by the exporters.
584 Changing it requires restart of `font-lock-mode' to become effective
585 for fontification also in regions already fontified.
586 You may also set this on a per-file basis by adding one of the following
587 lines to the buffer:
589 #+STARTUP: odd
590 #+STARTUP: oddeven"
591 :group 'org-edit-structure
592 :group 'org-font-lock
593 :type 'boolean)
595 (defcustom org-adapt-indentation t
596 "Non-nil means, adapt indentation when promoting and demoting.
597 When this is set and the *entire* text in an entry is indented, the
598 indentation is increased by one space in a demotion command, and
599 decreased by one in a promotion command. If any line in the entry
600 body starts at column 0, indentation is not changed at all."
601 :group 'org-edit-structure
602 :type 'boolean)
604 (defcustom org-special-ctrl-a/e nil
605 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
606 When t, `C-a' will bring back the cursor to the beginning of the
607 headline text, i.e. after the stars and after a possible TODO keyword.
608 In an item, this will be the position after the bullet.
609 When the cursor is already at that position, another `C-a' will bring
610 it to the beginning of the line.
611 `C-e' will jump to the end of the headline, ignoring the presence of tags
612 in the headline. A second `C-e' will then jump to the true end of the
613 line, after any tags.
614 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
615 and only a directly following, identical keypress will bring the cursor
616 to the special positions."
617 :group 'org-edit-structure
618 :type '(choice
619 (const :tag "off" nil)
620 (const :tag "after bullet first" t)
621 (const :tag "border first" reversed)))
623 (if (fboundp 'defvaralias)
624 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
626 (defcustom org-special-ctrl-k nil
627 "Non-nil means `C-k' will behave specially in headlines.
628 When nil, `C-k' will call the default `kill-line' command.
629 When t, the following will happen while the cursor is in the headline:
631 - When the cursor is at the beginning of a headline, kill the entire
632 line and possible the folded subtree below the line.
633 - When in the middle of the headline text, kill the headline up to the tags.
634 - When after the headline text, kill the tags."
635 :group 'org-edit-structure
636 :type 'boolean)
638 (defcustom org-yank-folded-subtrees t
639 "Non-nil means, when yanking subtrees, fold them.
640 If the kill is a single subtree, or a sequence of subtrees, i.e. if
641 it starts with a heading and all other headings in it are either children
642 or siblings, then fold all the subtrees. However, do this only if no
643 text after the yank would be swallowed into a folded tree by this action."
644 :group 'org-edit-structure
645 :type 'boolean)
647 (defcustom org-yank-adjusted-subtrees t
648 "Non-nil means, when yanking subtrees, adjust the level.
649 With this setting, `org-paste-subtree' is used to insert the subtree, see
650 this function for details."
651 :group 'org-edit-structure
652 :type 'boolean)
654 (defcustom org-M-RET-may-split-line '((default . t))
655 "Non-nil means, M-RET will split the line at the cursor position.
656 When nil, it will go to the end of the line before making a
657 new line.
658 You may also set this option in a different way for different
659 contexts. Valid contexts are:
661 headline when creating a new headline
662 item when creating a new item
663 table in a table field
664 default the value to be used for all contexts not explicitly
665 customized"
666 :group 'org-structure
667 :group 'org-table
668 :type '(choice
669 (const :tag "Always" t)
670 (const :tag "Never" nil)
671 (repeat :greedy t :tag "Individual contexts"
672 (cons
673 (choice :tag "Context"
674 (const headline)
675 (const item)
676 (const table)
677 (const default))
678 (boolean)))))
681 (defcustom org-insert-heading-respect-content nil
682 "Non-nil means, insert new headings after the current subtree.
683 When nil, the new heading is created directly after the current line.
684 The commands \\[org-insert-heading-respect-content] and
685 \\[org-insert-todo-heading-respect-content] turn this variable on
686 for the duration of the command."
687 :group 'org-structure
688 :type 'boolean)
690 (defcustom org-blank-before-new-entry '((heading . nil)
691 (plain-list-item . nil))
692 "Should `org-insert-heading' leave a blank line before new heading/item?
693 The value is an alist, with `heading' and `plain-list-item' as car,
694 and a boolean flag as cdr."
695 :group 'org-edit-structure
696 :type '(list
697 (cons (const heading) (boolean))
698 (cons (const plain-list-item) (boolean))))
700 (defcustom org-insert-heading-hook nil
701 "Hook being run after inserting a new heading."
702 :group 'org-edit-structure
703 :type 'hook)
705 (defcustom org-enable-fixed-width-editor t
706 "Non-nil means, lines starting with \":\" are treated as fixed-width.
707 This currently only means, they are never auto-wrapped.
708 When nil, such lines will be treated like ordinary lines.
709 See also the QUOTE keyword."
710 :group 'org-edit-structure
711 :type 'boolean)
713 (defcustom org-edit-src-region-extra nil
714 "Additional regexps to identify regions for editing with `org-edit-src-code'.
715 For examples see the function `org-edit-src-find-region-and-lang'.
716 The regular expression identifying the begin marker should end with a newline,
717 and the regexp marking the end line should start with a newline, to make sure
718 there are kept outside the narrowed region."
719 :group 'org-edit-structure
720 :type '(repeat
721 (list
722 (regexp :tag "begin regexp")
723 (regexp :tag "end regexp")
724 (choice :tag "language"
725 (string :tag "specify")
726 (integer :tag "from match group")
727 (const :tag "from `lang' element")
728 (const :tag "from `style' element")))))
730 (defcustom org-edit-fixed-width-region-mode 'artist-mode
731 "The mode that should be used to edit fixed-width regions.
732 These are the regions where each line starts with a colon."
733 :group 'org-edit-structure
734 :type '(choice
735 (const artist-mode)
736 (const picture-mode)
737 (const fundamental-mode)
738 (function :tag "Other (specify)")))
740 (defcustom org-goto-auto-isearch t
741 "Non-nil means, typing characters in org-goto starts incremental search."
742 :group 'org-edit-structure
743 :type 'boolean)
745 (defgroup org-sparse-trees nil
746 "Options concerning sparse trees in Org-mode."
747 :tag "Org Sparse Trees"
748 :group 'org-structure)
750 (defcustom org-highlight-sparse-tree-matches t
751 "Non-nil means, highlight all matches that define a sparse tree.
752 The highlights will automatically disappear the next time the buffer is
753 changed by an edit command."
754 :group 'org-sparse-trees
755 :type 'boolean)
757 (defcustom org-remove-highlights-with-change t
758 "Non-nil means, any change to the buffer will remove temporary highlights.
759 Such highlights are created by `org-occur' and `org-clock-display'.
760 When nil, `C-c C-c needs to be used to get rid of the highlights.
761 The highlights created by `org-preview-latex-fragment' always need
762 `C-c C-c' to be removed."
763 :group 'org-sparse-trees
764 :group 'org-time
765 :type 'boolean)
768 (defcustom org-occur-hook '(org-first-headline-recenter)
769 "Hook that is run after `org-occur' has constructed a sparse tree.
770 This can be used to recenter the window to show as much of the structure
771 as possible."
772 :group 'org-sparse-trees
773 :type 'hook)
775 (defgroup org-imenu-and-speedbar nil
776 "Options concerning imenu and speedbar in Org-mode."
777 :tag "Org Imenu and Speedbar"
778 :group 'org-structure)
780 (defcustom org-imenu-depth 2
781 "The maximum level for Imenu access to Org-mode headlines.
782 This also applied for speedbar access."
783 :group 'org-imenu-and-speedbar
784 :type 'number)
786 (defgroup org-table nil
787 "Options concerning tables in Org-mode."
788 :tag "Org Table"
789 :group 'org)
791 (defcustom org-enable-table-editor 'optimized
792 "Non-nil means, lines starting with \"|\" are handled by the table editor.
793 When nil, such lines will be treated like ordinary lines.
795 When equal to the symbol `optimized', the table editor will be optimized to
796 do the following:
797 - Automatic overwrite mode in front of whitespace in table fields.
798 This makes the structure of the table stay in tact as long as the edited
799 field does not exceed the column width.
800 - Minimize the number of realigns. Normally, the table is aligned each time
801 TAB or RET are pressed to move to another field. With optimization this
802 happens only if changes to a field might have changed the column width.
803 Optimization requires replacing the functions `self-insert-command',
804 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
805 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
806 very good at guessing when a re-align will be necessary, but you can always
807 force one with \\[org-ctrl-c-ctrl-c].
809 If you would like to use the optimized version in Org-mode, but the
810 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
812 This variable can be used to turn on and off the table editor during a session,
813 but in order to toggle optimization, a restart is required.
815 See also the variable `org-table-auto-blank-field'."
816 :group 'org-table
817 :type '(choice
818 (const :tag "off" nil)
819 (const :tag "on" t)
820 (const :tag "on, optimized" optimized)))
822 (defcustom org-table-tab-recognizes-table.el t
823 "Non-nil means, TAB will automatically notice a table.el table.
824 When it sees such a table, it moves point into it and - if necessary -
825 calls `table-recognize-table'."
826 :group 'org-table-editing
827 :type 'boolean)
829 (defgroup org-link nil
830 "Options concerning links in Org-mode."
831 :tag "Org Link"
832 :group 'org)
834 (defvar org-link-abbrev-alist-local nil
835 "Buffer-local version of `org-link-abbrev-alist', which see.
836 The value of this is taken from the #+LINK lines.")
837 (make-variable-buffer-local 'org-link-abbrev-alist-local)
839 (defcustom org-link-abbrev-alist nil
840 "Alist of link abbreviations.
841 The car of each element is a string, to be replaced at the start of a link.
842 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
843 links in Org-mode buffers can have an optional tag after a double colon, e.g.
845 [[linkkey:tag][description]]
847 If REPLACE is a string, the tag will simply be appended to create the link.
848 If the string contains \"%s\", the tag will be inserted there. Alternatively,
849 the placeholder \"%h\" will cause a url-encoded version of the tag to
850 be inserted at that point (see the function `url-hexify-string').
852 REPLACE may also be a function that will be called with the tag as the
853 only argument to create the link, which should be returned as a string.
855 See the manual for examples."
856 :group 'org-link
857 :type '(repeat
858 (cons
859 (string :tag "Protocol")
860 (choice
861 (string :tag "Format")
862 (function)))))
864 (defcustom org-descriptive-links t
865 "Non-nil means, hide link part and only show description of bracket links.
866 Bracket links are like [[link][descritpion]]. This variable sets the initial
867 state in new org-mode buffers. The setting can then be toggled on a
868 per-buffer basis from the Org->Hyperlinks menu."
869 :group 'org-link
870 :type 'boolean)
872 (defcustom org-link-file-path-type 'adaptive
873 "How the path name in file links should be stored.
874 Valid values are:
876 relative Relative to the current directory, i.e. the directory of the file
877 into which the link is being inserted.
878 absolute Absolute path, if possible with ~ for home directory.
879 noabbrev Absolute path, no abbreviation of home directory.
880 adaptive Use relative path for files in the current directory and sub-
881 directories of it. For other files, use an absolute path."
882 :group 'org-link
883 :type '(choice
884 (const relative)
885 (const absolute)
886 (const noabbrev)
887 (const adaptive)))
889 (defcustom org-activate-links '(bracket angle plain radio tag date)
890 "Types of links that should be activated in Org-mode files.
891 This is a list of symbols, each leading to the activation of a certain link
892 type. In principle, it does not hurt to turn on most link types - there may
893 be a small gain when turning off unused link types. The types are:
895 bracket The recommended [[link][description]] or [[link]] links with hiding.
896 angular Links in angular brackes that may contain whitespace like
897 <bbdb:Carsten Dominik>.
898 plain Plain links in normal text, no whitespace, like http://google.com.
899 radio Text that is matched by a radio target, see manual for details.
900 tag Tag settings in a headline (link to tag search).
901 date Time stamps (link to calendar).
903 Changing this variable requires a restart of Emacs to become effective."
904 :group 'org-link
905 :type '(set (const :tag "Double bracket links (new style)" bracket)
906 (const :tag "Angular bracket links (old style)" angular)
907 (const :tag "Plain text links" plain)
908 (const :tag "Radio target matches" radio)
909 (const :tag "Tags" tag)
910 (const :tag "Timestamps" date)))
912 (defcustom org-make-link-description-function nil
913 "Function to use to generate link descriptions from links. If
914 nil the link location will be used. This function must take two
915 parameters; the first is the link and the second the description
916 org-insert-link has generated, and should return the description
917 to use."
918 :group 'org-link
919 :type 'function)
921 (defgroup org-link-store nil
922 "Options concerning storing links in Org-mode."
923 :tag "Org Store Link"
924 :group 'org-link)
926 (defcustom org-email-link-description-format "Email %c: %.30s"
927 "Format of the description part of a link to an email or usenet message.
928 The following %-excapes will be replaced by corresponding information:
930 %F full \"From\" field
931 %f name, taken from \"From\" field, address if no name
932 %T full \"To\" field
933 %t first name in \"To\" field, address if no name
934 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
935 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
936 %s subject
937 %m message-id.
939 You may use normal field width specification between the % and the letter.
940 This is for example useful to limit the length of the subject.
942 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
943 :group 'org-link-store
944 :type 'string)
946 (defcustom org-from-is-user-regexp
947 (let (r1 r2)
948 (when (and user-mail-address (not (string= user-mail-address "")))
949 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
950 (when (and user-full-name (not (string= user-full-name "")))
951 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
952 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
953 "Regexp mached against the \"From:\" header of an email or usenet message.
954 It should match if the message is from the user him/herself."
955 :group 'org-link-store
956 :type 'regexp)
958 (defcustom org-context-in-file-links t
959 "Non-nil means, file links from `org-store-link' contain context.
960 A search string will be added to the file name with :: as separator and
961 used to find the context when the link is activated by the command
962 `org-open-at-point'.
963 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
964 negates this setting for the duration of the command."
965 :group 'org-link-store
966 :type 'boolean)
968 (defcustom org-keep-stored-link-after-insertion nil
969 "Non-nil means, keep link in list for entire session.
971 The command `org-store-link' adds a link pointing to the current
972 location to an internal list. These links accumulate during a session.
973 The command `org-insert-link' can be used to insert links into any
974 Org-mode file (offering completion for all stored links). When this
975 option is nil, every link which has been inserted once using \\[org-insert-link]
976 will be removed from the list, to make completing the unused links
977 more efficient."
978 :group 'org-link-store
979 :type 'boolean)
981 (defgroup org-link-follow nil
982 "Options concerning following links in Org-mode."
983 :tag "Org Follow Link"
984 :group 'org-link)
986 (defcustom org-link-translation-function nil
987 "Function to translate links with different syntax to Org syntax.
988 This can be used to translate links created for example by the Planner
989 or emacs-wiki packages to Org syntax.
990 The function must accept two parameters, a TYPE containing the link
991 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
992 which is everything after the link protocol. It should return a cons
993 with possibly modifed values of type and path.
994 Org contains a function for this, so if you set this variable to
995 `org-translate-link-from-planner', you should be able follow many
996 links created by planner."
997 :group 'org-link-follow
998 :type 'function)
1000 (defcustom org-follow-link-hook nil
1001 "Hook that is run after a link has been followed."
1002 :group 'org-link-follow
1003 :type 'hook)
1005 (defcustom org-tab-follows-link nil
1006 "Non-nil means, on links TAB will follow the link.
1007 Needs to be set before org.el is loaded."
1008 :group 'org-link-follow
1009 :type 'boolean)
1011 (defcustom org-return-follows-link nil
1012 "Non-nil means, on links RET will follow the link.
1013 Needs to be set before org.el is loaded."
1014 :group 'org-link-follow
1015 :type 'boolean)
1017 (defcustom org-mouse-1-follows-link
1018 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1019 "Non-nil means, mouse-1 on a link will follow the link.
1020 A longer mouse click will still set point. Does not work on XEmacs.
1021 Needs to be set before org.el is loaded."
1022 :group 'org-link-follow
1023 :type 'boolean)
1025 (defcustom org-mark-ring-length 4
1026 "Number of different positions to be recorded in the ring
1027 Changing this requires a restart of Emacs to work correctly."
1028 :group 'org-link-follow
1029 :type 'interger)
1031 (defcustom org-link-frame-setup
1032 '((vm . vm-visit-folder-other-frame)
1033 (gnus . gnus-other-frame)
1034 (file . find-file-other-window))
1035 "Setup the frame configuration for following links.
1036 When following a link with Emacs, it may often be useful to display
1037 this link in another window or frame. This variable can be used to
1038 set this up for the different types of links.
1039 For VM, use any of
1040 `vm-visit-folder'
1041 `vm-visit-folder-other-frame'
1042 For Gnus, use any of
1043 `gnus'
1044 `gnus-other-frame'
1045 `org-gnus-no-new-news'
1046 For FILE, use any of
1047 `find-file'
1048 `find-file-other-window'
1049 `find-file-other-frame'
1050 For the calendar, use the variable `calendar-setup'.
1051 For BBDB, it is currently only possible to display the matches in
1052 another window."
1053 :group 'org-link-follow
1054 :type '(list
1055 (cons (const vm)
1056 (choice
1057 (const vm-visit-folder)
1058 (const vm-visit-folder-other-window)
1059 (const vm-visit-folder-other-frame)))
1060 (cons (const gnus)
1061 (choice
1062 (const gnus)
1063 (const gnus-other-frame)
1064 (const org-gnus-no-new-news)))
1065 (cons (const file)
1066 (choice
1067 (const find-file)
1068 (const find-file-other-window)
1069 (const find-file-other-frame)))))
1071 (defcustom org-display-internal-link-with-indirect-buffer nil
1072 "Non-nil means, use indirect buffer to display infile links.
1073 Activating internal links (from one location in a file to another location
1074 in the same file) normally just jumps to the location. When the link is
1075 activated with a C-u prefix (or with mouse-3), the link is displayed in
1076 another window. When this option is set, the other window actually displays
1077 an indirect buffer clone of the current buffer, to avoid any visibility
1078 changes to the current buffer."
1079 :group 'org-link-follow
1080 :type 'boolean)
1082 (defcustom org-open-non-existing-files nil
1083 "Non-nil means, `org-open-file' will open non-existing files.
1084 When nil, an error will be generated."
1085 :group 'org-link-follow
1086 :type 'boolean)
1088 (defcustom org-open-directory-means-index-dot-org nil
1089 "Non-nil means, a link to a directory really means to index.org.
1090 When nil, following a directory link will run dired or open a finder/explorer
1091 window on that directory."
1092 :group 'org-link-follow
1093 :type 'boolean)
1095 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1096 "Function and arguments to call for following mailto links.
1097 This is a list with the first element being a lisp function, and the
1098 remaining elements being arguments to the function. In string arguments,
1099 %a will be replaced by the address, and %s will be replaced by the subject
1100 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1101 :group 'org-link-follow
1102 :type '(choice
1103 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1104 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1105 (const :tag "message-mail" (message-mail "%a" "%s"))
1106 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1108 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1109 "Non-nil means, ask for confirmation before executing shell links.
1110 Shell links can be dangerous: just think about a link
1112 [[shell:rm -rf ~/*][Google Search]]
1114 This link would show up in your Org-mode document as \"Google Search\",
1115 but really it would remove your entire home directory.
1116 Therefore we advise against setting this variable to nil.
1117 Just change it to `y-or-n-p' of you want to confirm with a
1118 single keystroke rather than having to type \"yes\"."
1119 :group 'org-link-follow
1120 :type '(choice
1121 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1122 (const :tag "with y-or-n (faster)" y-or-n-p)
1123 (const :tag "no confirmation (dangerous)" nil)))
1125 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1126 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1127 Elisp links can be dangerous: just think about a link
1129 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1131 This link would show up in your Org-mode document as \"Google Search\",
1132 but really it would remove your entire home directory.
1133 Therefore we advise against setting this variable to nil.
1134 Just change it to `y-or-n-p' of you want to confirm with a
1135 single keystroke rather than having to type \"yes\"."
1136 :group 'org-link-follow
1137 :type '(choice
1138 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1139 (const :tag "with y-or-n (faster)" y-or-n-p)
1140 (const :tag "no confirmation (dangerous)" nil)))
1142 (defconst org-file-apps-defaults-gnu
1143 '((remote . emacs)
1144 (system . mailcap)
1145 (t . mailcap))
1146 "Default file applications on a UNIX or GNU/Linux system.
1147 See `org-file-apps'.")
1149 (defconst org-file-apps-defaults-macosx
1150 '((remote . emacs)
1151 (t . "open %s")
1152 (system . "open %s")
1153 ("ps.gz" . "gv %s")
1154 ("eps.gz" . "gv %s")
1155 ("dvi" . "xdvi %s")
1156 ("fig" . "xfig %s"))
1157 "Default file applications on a MacOS X system.
1158 The system \"open\" is known as a default, but we use X11 applications
1159 for some files for which the OS does not have a good default.
1160 See `org-file-apps'.")
1162 (defconst org-file-apps-defaults-windowsnt
1163 (list
1164 '(remote . emacs)
1165 (cons t
1166 (list (if (featurep 'xemacs)
1167 'mswindows-shell-execute
1168 'w32-shell-execute)
1169 "open" 'file))
1170 (cons 'system
1171 (list (if (featurep 'xemacs)
1172 'mswindows-shell-execute
1173 'w32-shell-execute)
1174 "open" 'file)))
1175 "Default file applications on a Windows NT system.
1176 The system \"open\" is used for most files.
1177 See `org-file-apps'.")
1179 (defcustom org-file-apps
1181 (auto-mode . emacs)
1182 ("\\.x?html?\\'" . default)
1183 ("\\.pdf\\'" . default)
1185 "External applications for opening `file:path' items in a document.
1186 Org-mode uses system defaults for different file types, but
1187 you can use this variable to set the application for a given file
1188 extension. The entries in this list are cons cells where the car identifies
1189 files and the cdr the corresponding command. Possible values for the
1190 file identifier are
1191 \"regex\" Regular expression matched against the file name. For backward
1192 compatibility, this can also be a string with only alphanumeric
1193 characters, which is then interpreted as an extension.
1194 `directory' Matches a directory
1195 `remote' Matches a remote file, accessible through tramp or efs.
1196 Remote files most likely should be visited through Emacs
1197 because external applications cannot handle such paths.
1198 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1199 so all files Emacs knows how to handle. Using this with
1200 command `emacs' will open most files in Emacs. Beware that this
1201 will also open html files insite Emacs, unless you add
1202 (\"html\" . default) to the list as well.
1203 t Default for files not matched by any of the other options.
1204 `system' The system command to open files, like `open' on Windows
1205 and Mac OS X, and mailcap under GNU/Linux. This is the command
1206 that will be selected if you call `C-c C-o' with a double
1207 `C-u C-u' prefix.
1209 Possible values for the command are:
1210 `emacs' The file will be visited by the current Emacs process.
1211 `default' Use the default application for this file type, which is the
1212 association for t in the list, most likely in the system-specific
1213 part.
1214 This can be used to overrule an unwanted seting in the
1215 system-specific variable.
1216 `system' Use the system command for opening files, like \"open\".
1217 This command is specified by the entry whose car is `system'.
1218 Most likely, the system-specific version of this variable
1219 does define this command, but you can overrule/replace it
1220 here.
1221 string A command to be executed by a shell; %s will be replaced
1222 by the path to the file.
1223 sexp A Lisp form which will be evaluated. The file path will
1224 be available in the Lisp variable `file'.
1225 For more examples, see the system specific constants
1226 `org-file-apps-defaults-macosx'
1227 `org-file-apps-defaults-windowsnt'
1228 `org-file-apps-defaults-gnu'."
1229 :group 'org-link-follow
1230 :type '(repeat
1231 (cons (choice :value ""
1232 (string :tag "Extension")
1233 (const :tag "System command to open files" system)
1234 (const :tag "Default for unrecognized files" t)
1235 (const :tag "Remote file" remote)
1236 (const :tag "Links to a directory" directory)
1237 (const :tag "Any files that have Emacs modes"
1238 auto-mode))
1239 (choice :value ""
1240 (const :tag "Visit with Emacs" emacs)
1241 (const :tag "Use default" default)
1242 (const :tag "Use the system command" system)
1243 (string :tag "Command")
1244 (sexp :tag "Lisp form")))))
1246 (defgroup org-refile nil
1247 "Options concerning refiling entries in Org-mode."
1248 :tag "Org Refile"
1249 :group 'org)
1251 (defcustom org-directory "~/org"
1252 "Directory with org files.
1253 This directory will be used as default to prompt for org files.
1254 Used by the hooks for remember.el."
1255 :group 'org-refile
1256 :group 'org-remember
1257 :type 'directory)
1259 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1260 "Default target for storing notes.
1261 Used by the hooks for remember.el. This can be a string, or nil to mean
1262 the value of `remember-data-file'.
1263 You can set this on a per-template basis with the variable
1264 `org-remember-templates'."
1265 :group 'org-refile
1266 :group 'org-remember
1267 :type '(choice
1268 (const :tag "Default from remember-data-file" nil)
1269 file))
1271 (defcustom org-goto-interface 'outline
1272 "The default interface to be used for `org-goto'.
1273 Allowed vaues are:
1274 outline The interface shows an outline of the relevant file
1275 and the correct heading is found by moving through
1276 the outline or by searching with incremental search.
1277 outline-path-completion Headlines in the current buffer are offered via
1278 completion. This is the interface also used by
1279 the refile command."
1280 :group 'org-refile
1281 :type '(choice
1282 (const :tag "Outline" outline)
1283 (const :tag "Outline-path-completion" outline-path-completion)))
1285 (defcustom org-reverse-note-order nil
1286 "Non-nil means, store new notes at the beginning of a file or entry.
1287 When nil, new notes will be filed to the end of a file or entry.
1288 This can also be a list with cons cells of regular expressions that
1289 are matched against file names, and values."
1290 :group 'org-remember
1291 :group 'org-refile
1292 :type '(choice
1293 (const :tag "Reverse always" t)
1294 (const :tag "Reverse never" nil)
1295 (repeat :tag "By file name regexp"
1296 (cons regexp boolean))))
1298 (defcustom org-refile-targets nil
1299 "Targets for refiling entries with \\[org-refile].
1300 This is list of cons cells. Each cell contains:
1301 - a specification of the files to be considered, either a list of files,
1302 or a symbol whose function or variable value will be used to retrieve
1303 a file name or a list of file names. Nil means, refile to a different
1304 heading in the current buffer.
1305 - A specification of how to find candidate refile targets. This may be
1306 any of
1307 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1308 This tag has to be present in all target headlines, inheritance will
1309 not be considered.
1310 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1311 todo keyword.
1312 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1313 headlines that are refiling targets.
1314 - a cons cell (:level . N). Any headline of level N is considered a target.
1315 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1317 When this variable is nil, all top-level headlines in the current buffer
1318 are used, equivalent to the value `((nil . (:level . 1))'."
1319 :group 'org-refile
1320 :type '(repeat
1321 (cons
1322 (choice :value org-agenda-files
1323 (const :tag "All agenda files" org-agenda-files)
1324 (const :tag "Current buffer" nil)
1325 (function) (variable) (file))
1326 (choice :tag "Identify target headline by"
1327 (cons :tag "Specific tag" (const :value :tag) (string))
1328 (cons :tag "TODO keyword" (const :value :todo) (string))
1329 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1330 (cons :tag "Level number" (const :value :level) (integer))
1331 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1333 (defcustom org-refile-use-outline-path nil
1334 "Non-nil means, provide refile targets as paths.
1335 So a level 3 headline will be available as level1/level2/level3.
1336 When the value is `file', also include the file name (without directory)
1337 into the path. When `full-file-path', include the full file path."
1338 :group 'org-refile
1339 :type '(choice
1340 (const :tag "Not" nil)
1341 (const :tag "Yes" t)
1342 (const :tag "Start with file name" file)
1343 (const :tag "Start with full file path" full-file-path)))
1345 (defcustom org-outline-path-complete-in-steps t
1346 "Non-nil means, complete the outline path in hierarchical steps.
1347 When Org-mode uses the refile interface to select an outline path
1348 \(see variable `org-refile-use-outline-path'), the completion of
1349 the path can be done is a single go, or if can be done in steps down
1350 the headline hierarchy. Going in steps is probably the best if you
1351 do not use a special completion package like `ido' or `icicles'.
1352 However, when using these packages, going in one step can be very
1353 fast, while still showing the whole path to the entry."
1354 :group 'org-refile
1355 :type 'boolean)
1357 (defgroup org-todo nil
1358 "Options concerning TODO items in Org-mode."
1359 :tag "Org TODO"
1360 :group 'org)
1362 (defgroup org-progress nil
1363 "Options concerning Progress logging in Org-mode."
1364 :tag "Org Progress"
1365 :group 'org-time)
1367 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1368 "List of TODO entry keyword sequences and their interpretation.
1369 \\<org-mode-map>This is a list of sequences.
1371 Each sequence starts with a symbol, either `sequence' or `type',
1372 indicating if the keywords should be interpreted as a sequence of
1373 action steps, or as different types of TODO items. The first
1374 keywords are states requiring action - these states will select a headline
1375 for inclusion into the global TODO list Org-mode produces. If one of
1376 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1377 signify that no further action is necessary. If \"|\" is not found,
1378 the last keyword is treated as the only DONE state of the sequence.
1380 The command \\[org-todo] cycles an entry through these states, and one
1381 additional state where no keyword is present. For details about this
1382 cycling, see the manual.
1384 TODO keywords and interpretation can also be set on a per-file basis with
1385 the special #+SEQ_TODO and #+TYP_TODO lines.
1387 Each keyword can optionally specify a character for fast state selection
1388 \(in combination with the variable `org-use-fast-todo-selection')
1389 and specifiers for state change logging, using the same syntax
1390 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1391 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1392 indicates to record a time stamp each time this state is selected.
1394 Each keyword may also specify if a timestamp or a note should be
1395 recorded when entering or leaving the state, by adding additional
1396 characters in the parenthesis after the keyword. This looks like this:
1397 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1398 record only the time of the state change. With X and Y being either
1399 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1400 Y when leaving the state if and only if the *target* state does not
1401 define X. You may omit any of the fast-selection key or X or /Y,
1402 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1404 For backward compatibility, this variable may also be just a list
1405 of keywords - in this case the interptetation (sequence or type) will be
1406 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1407 :group 'org-todo
1408 :group 'org-keywords
1409 :type '(choice
1410 (repeat :tag "Old syntax, just keywords"
1411 (string :tag "Keyword"))
1412 (repeat :tag "New syntax"
1413 (cons
1414 (choice
1415 :tag "Interpretation"
1416 (const :tag "Sequence (cycling hits every state)" sequence)
1417 (const :tag "Type (cycling directly to DONE)" type))
1418 (repeat
1419 (string :tag "Keyword"))))))
1421 (defvar org-todo-keywords-1 nil
1422 "All TODO and DONE keywords active in a buffer.")
1423 (make-variable-buffer-local 'org-todo-keywords-1)
1424 (defvar org-todo-keywords-for-agenda nil)
1425 (defvar org-done-keywords-for-agenda nil)
1426 (defvar org-todo-keyword-alist-for-agenda nil)
1427 (defvar org-tag-alist-for-agenda nil)
1428 (defvar org-agenda-contributing-files nil)
1429 (defvar org-not-done-keywords nil)
1430 (make-variable-buffer-local 'org-not-done-keywords)
1431 (defvar org-done-keywords nil)
1432 (make-variable-buffer-local 'org-done-keywords)
1433 (defvar org-todo-heads nil)
1434 (make-variable-buffer-local 'org-todo-heads)
1435 (defvar org-todo-sets nil)
1436 (make-variable-buffer-local 'org-todo-sets)
1437 (defvar org-todo-log-states nil)
1438 (make-variable-buffer-local 'org-todo-log-states)
1439 (defvar org-todo-kwd-alist nil)
1440 (make-variable-buffer-local 'org-todo-kwd-alist)
1441 (defvar org-todo-key-alist nil)
1442 (make-variable-buffer-local 'org-todo-key-alist)
1443 (defvar org-todo-key-trigger nil)
1444 (make-variable-buffer-local 'org-todo-key-trigger)
1446 (defcustom org-todo-interpretation 'sequence
1447 "Controls how TODO keywords are interpreted.
1448 This variable is in principle obsolete and is only used for
1449 backward compatibility, if the interpretation of todo keywords is
1450 not given already in `org-todo-keywords'. See that variable for
1451 more information."
1452 :group 'org-todo
1453 :group 'org-keywords
1454 :type '(choice (const sequence)
1455 (const type)))
1457 (defcustom org-use-fast-todo-selection 'prefix
1458 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1459 This variable describes if and under what circumstances the cycling
1460 mechanism for TODO keywords will be replaced by a single-key, direct
1461 selection scheme.
1463 When nil, fast selection is never used.
1465 When the symbol `prefix', it will be used when `org-todo' is called with
1466 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1467 in an agenda buffer.
1469 When t, fast selection is used by default. In this case, the prefix
1470 argument forces cycling instead.
1472 In all cases, the special interface is only used if access keys have actually
1473 been assigned by the user, i.e. if keywords in the configuration are followed
1474 by a letter in parenthesis, like TODO(t)."
1475 :group 'org-todo
1476 :type '(choice
1477 (const :tag "Never" nil)
1478 (const :tag "By default" t)
1479 (const :tag "Only with C-u C-c C-t" prefix)))
1481 (defcustom org-provide-todo-statistics t
1482 "Non-nil means, update todo statistics after insert and toggle.
1483 When this is set, todo statistics is updated in the parent of the current
1484 entry each time a todo state is changed."
1485 :group 'org-todo
1486 :type 'boolean)
1488 (defcustom org-after-todo-state-change-hook nil
1489 "Hook which is run after the state of a TODO item was changed.
1490 The new state (a string with a TODO keyword, or nil) is available in the
1491 Lisp variable `state'."
1492 :group 'org-todo
1493 :type 'hook)
1495 (defcustom org-todo-state-tags-triggers nil
1496 "Tag changes that should be triggered by TODO state changes.
1497 This is a list. Each entry is
1499 (state-change (tag . flag) .......)
1501 State-change can be a string with a state, and empty string to indicate the
1502 state that has no TODO keyword, or it can be one of the symbols `todo'
1503 or `done', meaning any not-done or done state, respectively."
1504 :group 'org-todo
1505 :group 'org-tags
1506 :type '(repeat
1507 (cons (choice :tag "When changing to"
1508 (const :tag "Not-done state" todo)
1509 (const :tag "Done state" done)
1510 (string :tag "State"))
1511 (repeat
1512 (cons :tag "Tag action"
1513 (string :tag "Tag")
1514 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1516 (defcustom org-log-done nil
1517 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1518 When equal to the list (done), also prompt for a closing note.
1519 This can also be configured on a per-file basis by adding one of
1520 the following lines anywhere in the buffer:
1522 #+STARTUP: logdone
1523 #+STARTUP: lognotedone
1524 #+STARTUP: nologdone"
1525 :group 'org-todo
1526 :group 'org-progress
1527 :type '(choice
1528 (const :tag "No logging" nil)
1529 (const :tag "Record CLOSED timestamp" time)
1530 (const :tag "Record CLOSED timestamp with closing note." note)))
1532 ;; Normalize old uses of org-log-done.
1533 (cond
1534 ((eq org-log-done t) (setq org-log-done 'time))
1535 ((and (listp org-log-done) (memq 'done org-log-done))
1536 (setq org-log-done 'note)))
1538 (defcustom org-log-note-clock-out nil
1539 "Non-nil means, record a note when clocking out of an item.
1540 This can also be configured on a per-file basis by adding one of
1541 the following lines anywhere in the buffer:
1543 #+STARTUP: lognoteclock-out
1544 #+STARTUP: nolognoteclock-out"
1545 :group 'org-todo
1546 :group 'org-progress
1547 :type 'boolean)
1549 (defcustom org-log-done-with-time t
1550 "Non-nil means, the CLOSED time stamp will contain date and time.
1551 When nil, only the date will be recorded."
1552 :group 'org-progress
1553 :type 'boolean)
1555 (defcustom org-log-note-headings
1556 '((done . "CLOSING NOTE %t")
1557 (state . "State %-12s %t")
1558 (note . "Note taken on %t")
1559 (clock-out . ""))
1560 "Headings for notes added to entries.
1561 The value is an alist, with the car being a symbol indicating the note
1562 context, and the cdr is the heading to be used. The heading may also be the
1563 empty string.
1564 %t in the heading will be replaced by a time stamp.
1565 %s will be replaced by the new TODO state, in double quotes.
1566 %u will be replaced by the user name.
1567 %U will be replaced by the full user name."
1568 :group 'org-todo
1569 :group 'org-progress
1570 :type '(list :greedy t
1571 (cons (const :tag "Heading when closing an item" done) string)
1572 (cons (const :tag
1573 "Heading when changing todo state (todo sequence only)"
1574 state) string)
1575 (cons (const :tag "Heading when just taking a note" note) string)
1576 (cons (const :tag "Heading when clocking out" clock-out) string)))
1578 (unless (assq 'note org-log-note-headings)
1579 (push '(note . "%t") org-log-note-headings))
1581 (defcustom org-log-state-notes-insert-after-drawers nil
1582 "Non-nil means, insert state change notes after any drawers in entry.
1583 Only the drawers that *immediately* follow the headline and the
1584 deadline/scheduled line are skipped.
1585 When nil, insert notes right after the heading and perhaps the line
1586 with deadline/scheduling if present."
1587 :group 'org-todo
1588 :group 'org-progress
1589 :type 'boolean)
1591 (defcustom org-log-states-order-reversed t
1592 "Non-nil means, the latest state change note will be directly after heading.
1593 When nil, the notes will be orderer according to time."
1594 :group 'org-todo
1595 :group 'org-progress
1596 :type 'boolean)
1598 (defcustom org-log-repeat 'time
1599 "Non-nil means, record moving through the DONE state when triggering repeat.
1600 An auto-repeating tasks is immediately switched back to TODO when marked
1601 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1602 the TODO keyword definition, or recording a closing note by setting
1603 `org-log-done', there will be no record of the task moving through DONE.
1604 This variable forces taking a note anyway. Possible values are:
1606 nil Don't force a record
1607 time Record a time stamp
1608 note Record a note
1610 This option can also be set with on a per-file-basis with
1612 #+STARTUP: logrepeat
1613 #+STARTUP: lognoterepeat
1614 #+STARTUP: nologrepeat
1616 You can have local logging settings for a subtree by setting the LOGGING
1617 property to one or more of these keywords."
1618 :group 'org-todo
1619 :group 'org-progress
1620 :type '(choice
1621 (const :tag "Don't force a record" nil)
1622 (const :tag "Force recording the DONE state" time)
1623 (const :tag "Force recording a note with the DONE state" note)))
1626 (defgroup org-priorities nil
1627 "Priorities in Org-mode."
1628 :tag "Org Priorities"
1629 :group 'org-todo)
1631 (defcustom org-highest-priority ?A
1632 "The highest priority of TODO items. A character like ?A, ?B etc.
1633 Must have a smaller ASCII number than `org-lowest-priority'."
1634 :group 'org-priorities
1635 :type 'character)
1637 (defcustom org-lowest-priority ?C
1638 "The lowest priority of TODO items. A character like ?A, ?B etc.
1639 Must have a larger ASCII number than `org-highest-priority'."
1640 :group 'org-priorities
1641 :type 'character)
1643 (defcustom org-default-priority ?B
1644 "The default priority of TODO items.
1645 This is the priority an item get if no explicit priority is given."
1646 :group 'org-priorities
1647 :type 'character)
1649 (defcustom org-priority-start-cycle-with-default t
1650 "Non-nil means, start with default priority when starting to cycle.
1651 When this is nil, the first step in the cycle will be (depending on the
1652 command used) one higher or lower that the default priority."
1653 :group 'org-priorities
1654 :type 'boolean)
1656 (defgroup org-time nil
1657 "Options concerning time stamps and deadlines in Org-mode."
1658 :tag "Org Time"
1659 :group 'org)
1661 (defcustom org-insert-labeled-timestamps-at-point nil
1662 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1663 When nil, these labeled time stamps are forces into the second line of an
1664 entry, just after the headline. When scheduling from the global TODO list,
1665 the time stamp will always be forced into the second line."
1666 :group 'org-time
1667 :type 'boolean)
1669 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1670 "Formats for `format-time-string' which are used for time stamps.
1671 It is not recommended to change this constant.")
1673 (defcustom org-time-stamp-rounding-minutes '(0 5)
1674 "Number of minutes to round time stamps to.
1675 These are two values, the first applies when first creating a time stamp.
1676 The second applies when changing it with the commands `S-up' and `S-down'.
1677 When changing the time stamp, this means that it will change in steps
1678 of N minutes, as given by the second value.
1680 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1681 numbers should be factors of 60, so for example 5, 10, 15.
1683 When this is larger than 1, you can still force an exact time-stamp by using
1684 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1685 and by using a prefix arg to `S-up/down' to specify the exact number
1686 of minutes to shift."
1687 :group 'org-time
1688 :get '(lambda (var) ; Make sure all entries have 5 elements
1689 (if (integerp (default-value var))
1690 (list (default-value var) 5)
1691 (default-value var)))
1692 :type '(list
1693 (integer :tag "when inserting times")
1694 (integer :tag "when modifying times")))
1696 ;; Normalize old customizations of this variable.
1697 (when (integerp org-time-stamp-rounding-minutes)
1698 (setq org-time-stamp-rounding-minutes
1699 (list org-time-stamp-rounding-minutes
1700 org-time-stamp-rounding-minutes)))
1702 (defcustom org-display-custom-times nil
1703 "Non-nil means, overlay custom formats over all time stamps.
1704 The formats are defined through the variable `org-time-stamp-custom-formats'.
1705 To turn this on on a per-file basis, insert anywhere in the file:
1706 #+STARTUP: customtime"
1707 :group 'org-time
1708 :set 'set-default
1709 :type 'sexp)
1710 (make-variable-buffer-local 'org-display-custom-times)
1712 (defcustom org-time-stamp-custom-formats
1713 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1714 "Custom formats for time stamps. See `format-time-string' for the syntax.
1715 These are overlayed over the default ISO format if the variable
1716 `org-display-custom-times' is set. Time like %H:%M should be at the
1717 end of the second format."
1718 :group 'org-time
1719 :type 'sexp)
1721 (defun org-time-stamp-format (&optional long inactive)
1722 "Get the right format for a time string."
1723 (let ((f (if long (cdr org-time-stamp-formats)
1724 (car org-time-stamp-formats))))
1725 (if inactive
1726 (concat "[" (substring f 1 -1) "]")
1727 f)))
1729 (defcustom org-time-clocksum-format "%d:%02d"
1730 "The format string used when creating CLOCKSUM lines, or when
1731 org-mode generates a time duration."
1732 :group 'org-time
1733 :type 'string)
1735 (defcustom org-deadline-warning-days 14
1736 "No. of days before expiration during which a deadline becomes active.
1737 This variable governs the display in sparse trees and in the agenda.
1738 When 0 or negative, it means use this number (the absolute value of it)
1739 even if a deadline has a different individual lead time specified."
1740 :group 'org-time
1741 :group 'org-agenda-daily/weekly
1742 :type 'number)
1744 (defcustom org-read-date-prefer-future t
1745 "Non-nil means, assume future for incomplete date input from user.
1746 This affects the following situations:
1747 1. The user gives a day, but no month.
1748 For example, if today is the 15th, and you enter \"3\", Org-mode will
1749 read this as the third of *next* month. However, if you enter \"17\",
1750 it will be considered as *this* month.
1751 2. The user gives a month but not a year.
1752 For example, if it is april and you enter \"feb 2\", this will be read
1753 as feb 2, *next* year. \"May 5\", however, will be this year.
1755 Currently this does not work for ISO week specifications.
1757 When this option is nil, the current month and year will always be used
1758 as defaults."
1759 :group 'org-time
1760 :type 'boolean)
1762 (defcustom org-read-date-display-live t
1763 "Non-nil means, display current interpretation of date prompt live.
1764 This display will be in an overlay, in the minibuffer."
1765 :group 'org-time
1766 :type 'boolean)
1768 (defcustom org-read-date-popup-calendar t
1769 "Non-nil means, pop up a calendar when prompting for a date.
1770 In the calendar, the date can be selected with mouse-1. However, the
1771 minibuffer will also be active, and you can simply enter the date as well.
1772 When nil, only the minibuffer will be available."
1773 :group 'org-time
1774 :type 'boolean)
1775 (if (fboundp 'defvaralias)
1776 (defvaralias 'org-popup-calendar-for-date-prompt
1777 'org-read-date-popup-calendar))
1779 (defcustom org-extend-today-until 0
1780 "The hour when your day really ends. Must be an integer.
1781 This has influence for the following applications:
1782 - When switching the agenda to \"today\". It it is still earlier than
1783 the time given here, the day recognized as TODAY is actually yesterday.
1784 - When a date is read from the user and it is still before the time given
1785 here, the current date and time will be assumed to be yesterday, 23:59.
1786 Also, timestamps inserted in remember templates follow this rule.
1788 IMPORTANT: This is a feature whose implementation is and likely will
1789 remain incomplete. Really, it is only here because past midnight seems to
1790 be the favorite working time of John Wiegley :-)"
1791 :group 'org-time
1792 :type 'number)
1794 (defcustom org-edit-timestamp-down-means-later nil
1795 "Non-nil means, S-down will increase the time in a time stamp.
1796 When nil, S-up will increase."
1797 :group 'org-time
1798 :type 'boolean)
1800 (defcustom org-calendar-follow-timestamp-change t
1801 "Non-nil means, make the calendar window follow timestamp changes.
1802 When a timestamp is modified and the calendar window is visible, it will be
1803 moved to the new date."
1804 :group 'org-time
1805 :type 'boolean)
1807 (defgroup org-tags nil
1808 "Options concerning tags in Org-mode."
1809 :tag "Org Tags"
1810 :group 'org)
1812 (defcustom org-tag-alist nil
1813 "List of tags allowed in Org-mode files.
1814 When this list is nil, Org-mode will base TAG input on what is already in the
1815 buffer.
1816 The value of this variable is an alist, the car of each entry must be a
1817 keyword as a string, the cdr may be a character that is used to select
1818 that tag through the fast-tag-selection interface.
1819 See the manual for details."
1820 :group 'org-tags
1821 :type '(repeat
1822 (choice
1823 (cons (string :tag "Tag name")
1824 (character :tag "Access char"))
1825 (const :tag "Start radio group" (:startgroup))
1826 (const :tag "End radio group" (:endgroup)))))
1828 (defvar org-file-tags nil
1829 "List of tags that can be inherited by all entries in the file.
1830 The tags will be inherited if the variable `org-use-tag-inheritance'
1831 says they should be.
1832 This variable is populated from #+TAG lines.")
1834 (defcustom org-use-fast-tag-selection 'auto
1835 "Non-nil means, use fast tag selection scheme.
1836 This is a special interface to select and deselect tags with single keys.
1837 When nil, fast selection is never used.
1838 When the symbol `auto', fast selection is used if and only if selection
1839 characters for tags have been configured, either through the variable
1840 `org-tag-alist' or through a #+TAGS line in the buffer.
1841 When t, fast selection is always used and selection keys are assigned
1842 automatically if necessary."
1843 :group 'org-tags
1844 :type '(choice
1845 (const :tag "Always" t)
1846 (const :tag "Never" nil)
1847 (const :tag "When selection characters are configured" 'auto)))
1849 (defcustom org-fast-tag-selection-single-key nil
1850 "Non-nil means, fast tag selection exits after first change.
1851 When nil, you have to press RET to exit it.
1852 During fast tag selection, you can toggle this flag with `C-c'.
1853 This variable can also have the value `expert'. In this case, the window
1854 displaying the tags menu is not even shown, until you press C-c again."
1855 :group 'org-tags
1856 :type '(choice
1857 (const :tag "No" nil)
1858 (const :tag "Yes" t)
1859 (const :tag "Expert" expert)))
1861 (defvar org-fast-tag-selection-include-todo nil
1862 "Non-nil means, fast tags selection interface will also offer TODO states.
1863 This is an undocumented feature, you should not rely on it.")
1865 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1866 "The column to which tags should be indented in a headline.
1867 If this number is positive, it specifies the column. If it is negative,
1868 it means that the tags should be flushright to that column. For example,
1869 -80 works well for a normal 80 character screen."
1870 :group 'org-tags
1871 :type 'integer)
1873 (defcustom org-auto-align-tags t
1874 "Non-nil means, realign tags after pro/demotion of TODO state change.
1875 These operations change the length of a headline and therefore shift
1876 the tags around. With this options turned on, after each such operation
1877 the tags are again aligned to `org-tags-column'."
1878 :group 'org-tags
1879 :type 'boolean)
1881 (defcustom org-use-tag-inheritance t
1882 "Non-nil means, tags in levels apply also for sublevels.
1883 When nil, only the tags directly given in a specific line apply there.
1884 If this option is t, a match early-on in a tree can lead to a large
1885 number of matches in the subtree. If you only want to see the first
1886 match in a tree during a search, check out the variable
1887 `org-tags-match-list-sublevels'.
1889 This may also be a list of tags that should be inherited, or a regexp that
1890 matches tags that should be inherited."
1891 :group 'org-tags
1892 :type '(choice
1893 (const :tag "Not" nil)
1894 (const :tag "Always" t)
1895 (repeat :tag "Specific tags" (string :tag "Tag"))
1896 (regexp :tag "Tags matched by regexp")))
1898 (defun org-tag-inherit-p (tag)
1899 "Check if TAG is one that should be inherited."
1900 (cond
1901 ((eq org-use-tag-inheritance t) t)
1902 ((not org-use-tag-inheritance) nil)
1903 ((stringp org-use-tag-inheritance)
1904 (string-match org-use-tag-inheritance tag))
1905 ((listp org-use-tag-inheritance)
1906 (member tag org-use-tag-inheritance))
1907 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1909 (defcustom org-tags-match-list-sublevels t
1910 "Non-nil means list also sublevels of headlines matching tag search.
1911 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1912 the sublevels of a headline matching a tag search often also match
1913 the same search. Listing all of them can create very long lists.
1914 Setting this variable to nil causes subtrees of a match to be skipped.
1915 This option is off by default, because inheritance in on. If you turn
1916 inheritance off, you very likely want to turn this option on.
1918 As a special case, if the tag search is restricted to TODO items, the
1919 value of this variable is ignored and sublevels are always checked, to
1920 make sure all corresponding TODO items find their way into the list."
1921 :group 'org-tags
1922 :type 'boolean)
1924 (defvar org-tags-history nil
1925 "History of minibuffer reads for tags.")
1926 (defvar org-last-tags-completion-table nil
1927 "The last used completion table for tags.")
1928 (defvar org-after-tags-change-hook nil
1929 "Hook that is run after the tags in a line have changed.")
1931 (defgroup org-properties nil
1932 "Options concerning properties in Org-mode."
1933 :tag "Org Properties"
1934 :group 'org)
1936 (defcustom org-property-format "%-10s %s"
1937 "How property key/value pairs should be formatted by `indent-line'.
1938 When `indent-line' hits a property definition, it will format the line
1939 according to this format, mainly to make sure that the values are
1940 lined-up with respect to each other."
1941 :group 'org-properties
1942 :type 'string)
1944 (defcustom org-use-property-inheritance nil
1945 "Non-nil means, properties apply also for sublevels.
1947 This setting is chiefly used during property searches. Turning it on can
1948 cause significant overhead when doing a search, which is why it is not
1949 on by default.
1951 When nil, only the properties directly given in the current entry count.
1952 When t, every property is inherited. The value may also be a list of
1953 properties that should have inheritance, or a regular expression matching
1954 properties that should be inherited.
1956 However, note that some special properties use inheritance under special
1957 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1958 and the properties ending in \"_ALL\" when they are used as descriptor
1959 for valid values of a property.
1961 Note for programmers:
1962 When querying an entry with `org-entry-get', you can control if inheritance
1963 should be used. By default, `org-entry-get' looks only at the local
1964 properties. You can request inheritance by setting the inherit argument
1965 to t (to force inheritance) or to `selective' (to respect the setting
1966 in this variable)."
1967 :group 'org-properties
1968 :type '(choice
1969 (const :tag "Not" nil)
1970 (const :tag "Always" t)
1971 (repeat :tag "Specific properties" (string :tag "Property"))
1972 (regexp :tag "Properties matched by regexp")))
1974 (defun org-property-inherit-p (property)
1975 "Check if PROPERTY is one that should be inherited."
1976 (cond
1977 ((eq org-use-property-inheritance t) t)
1978 ((not org-use-property-inheritance) nil)
1979 ((stringp org-use-property-inheritance)
1980 (string-match org-use-property-inheritance property))
1981 ((listp org-use-property-inheritance)
1982 (member property org-use-property-inheritance))
1983 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1985 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1986 "The default column format, if no other format has been defined.
1987 This variable can be set on the per-file basis by inserting a line
1989 #+COLUMNS: %25ITEM ....."
1990 :group 'org-properties
1991 :type 'string)
1993 (defcustom org-columns-ellipses ".."
1994 "The ellipses to be used when a field in column view is truncated.
1995 When this is the empty string, as many characters as possible are shown,
1996 but then there will be no visual indication that the field has been truncated.
1997 When this is a string of length N, the last N characters of a truncated
1998 field are replaced by this string. If the column is narrower than the
1999 ellipses string, only part of the ellipses string will be shown."
2000 :group 'org-properties
2001 :type 'string)
2003 (defcustom org-columns-modify-value-for-display-function nil
2004 "Function that modifies values for display in column view.
2005 For example, it can be used to cut out a certain part from a time stamp.
2006 The function must take 2 arguments:
2008 column-title The tite of the column (*not* the property name)
2009 value The value that should be modified.
2011 The function should return the value that should be displayed,
2012 or nil if the normal value should be used."
2013 :group 'org-properties
2014 :type 'function)
2016 (defcustom org-effort-property "Effort"
2017 "The property that is being used to keep track of effort estimates.
2018 Effort estimates given in this property need to have the format H:MM."
2019 :group 'org-properties
2020 :group 'org-progress
2021 :type '(string :tag "Property"))
2023 (defconst org-global-properties-fixed
2024 '(("VISIBILITY_ALL" . "folded children content all"))
2025 "List of property/value pairs that can be inherited by any entry.
2026 These are fixed values, for the preset properties.")
2029 (defcustom org-global-properties nil
2030 "List of property/value pairs that can be inherited by any entry.
2031 You can set buffer-local values for the same purpose in the variable
2032 `org-file-properties' this by adding lines like
2034 #+PROPERTY: NAME VALUE"
2035 :group 'org-properties
2036 :type '(repeat
2037 (cons (string :tag "Property")
2038 (string :tag "Value"))))
2040 (defvar org-file-properties nil
2041 "List of property/value pairs that can be inherited by any entry.
2042 Valid for the current buffer.
2043 This variable is populated from #+PROPERTY lines.")
2044 (make-variable-buffer-local 'org-file-properties)
2046 (defgroup org-agenda nil
2047 "Options concerning agenda views in Org-mode."
2048 :tag "Org Agenda"
2049 :group 'org)
2051 (defvar org-category nil
2052 "Variable used by org files to set a category for agenda display.
2053 Such files should use a file variable to set it, for example
2055 # -*- mode: org; org-category: \"ELisp\"
2057 or contain a special line
2059 #+CATEGORY: ELisp
2061 If the file does not specify a category, then file's base name
2062 is used instead.")
2063 (make-variable-buffer-local 'org-category)
2064 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2066 (defcustom org-agenda-files nil
2067 "The files to be used for agenda display.
2068 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2069 \\[org-remove-file]. You can also use customize to edit the list.
2071 If an entry is a directory, all files in that directory that are matched by
2072 `org-agenda-file-regexp' will be part of the file list.
2074 If the value of the variable is not a list but a single file name, then
2075 the list of agenda files is actually stored and maintained in that file, one
2076 agenda file per line."
2077 :group 'org-agenda
2078 :type '(choice
2079 (repeat :tag "List of files and directories" file)
2080 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2082 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2083 "Regular expression to match files for `org-agenda-files'.
2084 If any element in the list in that variable contains a directory instead
2085 of a normal file, all files in that directory that are matched by this
2086 regular expression will be included."
2087 :group 'org-agenda
2088 :type 'regexp)
2090 (defcustom org-agenda-text-search-extra-files nil
2091 "List of extra files to be searched by text search commands.
2092 These files will be search in addition to the agenda files by the
2093 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2094 Note that these files will only be searched for text search commands,
2095 not for the other agenda views like todo lists, tag searches or the weekly
2096 agenda. This variable is intended to list notes and possibly archive files
2097 that should also be searched by these two commands.
2098 In fact, if the first element in the list is the symbol `agenda-archives',
2099 than all archive files of all agenda files will be added to the search
2100 scope."
2101 :group 'org-agenda
2102 :type '(set :greedy t
2103 (const :tag "Agenda Archives" agenda-archives)
2104 (repeat :inline t (file))))
2106 (if (fboundp 'defvaralias)
2107 (defvaralias 'org-agenda-multi-occur-extra-files
2108 'org-agenda-text-search-extra-files))
2110 (defcustom org-agenda-skip-unavailable-files nil
2111 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2112 A nil value means to remove them, after a query, from the list."
2113 :group 'org-agenda
2114 :type 'boolean)
2116 (defcustom org-calendar-to-agenda-key [?c]
2117 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2118 The command `org-calendar-goto-agenda' will be bound to this key. The
2119 default is the character `c' because then `c' can be used to switch back and
2120 forth between agenda and calendar."
2121 :group 'org-agenda
2122 :type 'sexp)
2124 (defcustom org-calendar-agenda-action-key [?k]
2125 "The key to be installed in `calendar-mode-map' for agenda-action.
2126 The command `org-agenda-action' will be bound to this key. The
2127 default is the character `k' because we use the same key in the agenda."
2128 :group 'org-agenda
2129 :type 'sexp)
2131 (eval-after-load "calendar"
2132 '(progn
2133 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2134 'org-calendar-goto-agenda)
2135 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2136 'org-agenda-action)))
2138 (defgroup org-latex nil
2139 "Options for embedding LaTeX code into Org-mode."
2140 :tag "Org LaTeX"
2141 :group 'org)
2143 (defcustom org-format-latex-options
2144 '(:foreground default :background default :scale 1.0
2145 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2146 :matchers ("begin" "$" "$$" "\\(" "\\["))
2147 "Options for creating images from LaTeX fragments.
2148 This is a property list with the following properties:
2149 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2150 `default' means use the foreground of the default face.
2151 :background the background color, or \"Transparent\".
2152 `default' means use the background of the default face.
2153 :scale a scaling factor for the size of the images.
2154 :html-foreground, :html-background, :html-scale
2155 the same numbers for HTML export.
2156 :matchers a list indicating which matchers should be used to
2157 find LaTeX fragments. Valid members of this list are:
2158 \"begin\" find environments
2159 \"$\" find math expressions surrounded by $...$
2160 \"$$\" find math expressions surrounded by $$....$$
2161 \"\\(\" find math expressions surrounded by \\(...\\)
2162 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2163 :group 'org-latex
2164 :type 'plist)
2166 (defcustom org-format-latex-header "\\documentclass{article}
2167 \\usepackage{fullpage} % do not remove
2168 \\usepackage{amssymb}
2169 \\usepackage[usenames]{color}
2170 \\usepackage{amsmath}
2171 \\usepackage{latexsym}
2172 \\usepackage[mathscr]{eucal}
2173 \\pagestyle{empty} % do not remove"
2174 "The document header used for processing LaTeX fragments."
2175 :group 'org-latex
2176 :type 'string)
2179 (defgroup org-font-lock nil
2180 "Font-lock settings for highlighting in Org-mode."
2181 :tag "Org Font Lock"
2182 :group 'org)
2184 (defcustom org-level-color-stars-only nil
2185 "Non-nil means fontify only the stars in each headline.
2186 When nil, the entire headline is fontified.
2187 Changing it requires restart of `font-lock-mode' to become effective
2188 also in regions already fontified."
2189 :group 'org-font-lock
2190 :type 'boolean)
2192 (defcustom org-hide-leading-stars nil
2193 "Non-nil means, hide the first N-1 stars in a headline.
2194 This works by using the face `org-hide' for these stars. This
2195 face is white for a light background, and black for a dark
2196 background. You may have to customize the face `org-hide' to
2197 make this work.
2198 Changing it requires restart of `font-lock-mode' to become effective
2199 also in regions already fontified.
2200 You may also set this on a per-file basis by adding one of the following
2201 lines to the buffer:
2203 #+STARTUP: hidestars
2204 #+STARTUP: showstars"
2205 :group 'org-font-lock
2206 :type 'boolean)
2208 (defcustom org-fontify-done-headline nil
2209 "Non-nil means, change the face of a headline if it is marked DONE.
2210 Normally, only the TODO/DONE keyword indicates the state of a headline.
2211 When this is non-nil, the headline after the keyword is set to the
2212 `org-headline-done' as an additional indication."
2213 :group 'org-font-lock
2214 :type 'boolean)
2216 (defcustom org-fontify-emphasized-text t
2217 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2218 Changing this variable requires a restart of Emacs to take effect."
2219 :group 'org-font-lock
2220 :type 'boolean)
2222 (defcustom org-highlight-latex-fragments-and-specials nil
2223 "Non-nil means, fontify what is treated specially by the exporters."
2224 :group 'org-font-lock
2225 :type 'boolean)
2227 (defcustom org-hide-emphasis-markers nil
2228 "Non-nil mean font-lock should hide the emphasis marker characters."
2229 :group 'org-font-lock
2230 :type 'boolean)
2232 (defvar org-emph-re nil
2233 "Regular expression for matching emphasis.")
2234 (defvar org-verbatim-re nil
2235 "Regular expression for matching verbatim text.")
2236 (defvar org-emphasis-regexp-components) ; defined just below
2237 (defvar org-emphasis-alist) ; defined just below
2238 (defun org-set-emph-re (var val)
2239 "Set variable and compute the emphasis regular expression."
2240 (set var val)
2241 (when (and (boundp 'org-emphasis-alist)
2242 (boundp 'org-emphasis-regexp-components)
2243 org-emphasis-alist org-emphasis-regexp-components)
2244 (let* ((e org-emphasis-regexp-components)
2245 (pre (car e))
2246 (post (nth 1 e))
2247 (border (nth 2 e))
2248 (body (nth 3 e))
2249 (nl (nth 4 e))
2250 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2251 (body1 (concat body "*?"))
2252 (markers (mapconcat 'car org-emphasis-alist ""))
2253 (vmarkers (mapconcat
2254 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2255 org-emphasis-alist "")))
2256 ;; make sure special characters appear at the right position in the class
2257 (if (string-match "\\^" markers)
2258 (setq markers (concat (replace-match "" t t markers) "^")))
2259 (if (string-match "-" markers)
2260 (setq markers (concat (replace-match "" t t markers) "-")))
2261 (if (string-match "\\^" vmarkers)
2262 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2263 (if (string-match "-" vmarkers)
2264 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2265 (if (> nl 0)
2266 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2267 (int-to-string nl) "\\}")))
2268 ;; Make the regexp
2269 (setq org-emph-re
2270 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2271 "\\("
2272 "\\([" markers "]\\)"
2273 "\\("
2274 "[^" border "]\\|"
2275 "[^" border (if (and nil stacked) markers) "]"
2276 body1
2277 "[^" border (if (and nil stacked) markers) "]"
2278 "\\)"
2279 "\\3\\)"
2280 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2281 (setq org-verbatim-re
2282 (concat "\\([" pre "]\\|^\\)"
2283 "\\("
2284 "\\([" vmarkers "]\\)"
2285 "\\("
2286 "[^" border "]\\|"
2287 "[^" border "]"
2288 body1
2289 "[^" border "]"
2290 "\\)"
2291 "\\3\\)"
2292 "\\([" post "]\\|$\\)")))))
2294 (defcustom org-emphasis-regexp-components
2295 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2296 "Components used to build the regular expression for emphasis.
2297 This is a list with 6 entries. Terminology: In an emphasis string
2298 like \" *strong word* \", we call the initial space PREMATCH, the final
2299 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2300 and \"trong wor\" is the body. The different components in this variable
2301 specify what is allowed/forbidden in each part:
2303 pre Chars allowed as prematch. Beginning of line will be allowed too.
2304 post Chars allowed as postmatch. End of line will be allowed too.
2305 border The chars *forbidden* as border characters.
2306 body-regexp A regexp like \".\" to match a body character. Don't use
2307 non-shy groups here, and don't allow newline here.
2308 newline The maximum number of newlines allowed in an emphasis exp.
2310 Use customize to modify this, or restart Emacs after changing it."
2311 :group 'org-font-lock
2312 :set 'org-set-emph-re
2313 :type '(list
2314 (sexp :tag "Allowed chars in pre ")
2315 (sexp :tag "Allowed chars in post ")
2316 (sexp :tag "Forbidden chars in border ")
2317 (sexp :tag "Regexp for body ")
2318 (integer :tag "number of newlines allowed")
2319 (option (boolean :tag "Please ignore this button"))))
2321 (defcustom org-emphasis-alist
2322 `(("*" bold "<b>" "</b>")
2323 ("/" italic "<i>" "</i>")
2324 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2325 ("=" org-code "<code>" "</code>" verbatim)
2326 ("~" org-verbatim "<code>" "</code>" verbatim)
2327 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2328 "<del>" "</del>")
2330 "Special syntax for emphasized text.
2331 Text starting and ending with a special character will be emphasized, for
2332 example *bold*, _underlined_ and /italic/. This variable sets the marker
2333 characters, the face to be used by font-lock for highlighting in Org-mode
2334 Emacs buffers, and the HTML tags to be used for this.
2335 Use customize to modify this, or restart Emacs after changing it."
2336 :group 'org-font-lock
2337 :set 'org-set-emph-re
2338 :type '(repeat
2339 (list
2340 (string :tag "Marker character")
2341 (choice
2342 (face :tag "Font-lock-face")
2343 (plist :tag "Face property list"))
2344 (string :tag "HTML start tag")
2345 (string :tag "HTML end tag")
2346 (option (const verbatim)))))
2348 ;;; Miscellaneous options
2350 (defgroup org-completion nil
2351 "Completion in Org-mode."
2352 :tag "Org Completion"
2353 :group 'org)
2355 (defcustom org-completion-use-ido nil
2356 "Non-ni means, use ido completion wherever possible."
2357 :group 'org-completion
2358 :type 'boolean)
2360 (defcustom org-completion-fallback-command 'hippie-expand
2361 "The expansion command called by \\[org-complete] in normal context.
2362 Normal means, no org-mode-specific context."
2363 :group 'org-completion
2364 :type 'function)
2366 ;;; Functions and variables from ther packages
2367 ;; Declared here to avoid compiler warnings
2369 ;; XEmacs only
2370 (defvar outline-mode-menu-heading)
2371 (defvar outline-mode-menu-show)
2372 (defvar outline-mode-menu-hide)
2373 (defvar zmacs-regions) ; XEmacs regions
2375 ;; Emacs only
2376 (defvar mark-active)
2378 ;; Various packages
2379 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2380 (declare-function calendar-forward-day "cal-move" (arg))
2381 (declare-function calendar-goto-date "cal-move" (date))
2382 (declare-function calendar-goto-today "cal-move" ())
2383 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2384 (defvar calc-embedded-close-formula)
2385 (defvar calc-embedded-open-formula)
2386 (declare-function cdlatex-tab "ext:cdlatex" ())
2387 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2388 (defvar font-lock-unfontify-region-function)
2389 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2390 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2391 (defvar iswitchb-temp-buflist)
2392 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2393 (declare-function org-agenda-skip "org-agenda" ())
2394 (declare-function org-format-agenda-item "org-agenda"
2395 (extra txt &optional category tags dotime noprefix remove-re))
2396 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2397 (declare-function org-agenda-change-all-lines "org-agenda"
2398 (newhead hdmarker &optional fixface just-this))
2399 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2400 (declare-function org-agenda-maybe-redo "org-agenda" ())
2401 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2402 (beg end))
2403 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2404 (declare-function parse-time-string "parse-time" (string))
2405 (declare-function remember "remember" (&optional initial))
2406 (declare-function remember-buffer-desc "remember" ())
2407 (declare-function remember-finalize "remember" ())
2408 (defvar remember-save-after-remembering)
2409 (defvar remember-data-file)
2410 (defvar remember-register)
2411 (defvar remember-buffer)
2412 (defvar remember-handler-functions)
2413 (defvar remember-annotation-functions)
2414 (defvar texmathp-why)
2415 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2416 (declare-function table--at-cell-p "table" (position &optional object at-column))
2418 (defvar w3m-current-url)
2419 (defvar w3m-current-title)
2421 (defvar org-latex-regexps)
2423 ;;; Autoload and prepare some org modules
2425 ;; Some table stuff that needs to be defined here, because it is used
2426 ;; by the functions setting up org-mode or checking for table context.
2428 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2429 "Detects an org-type or table-type table.")
2430 (defconst org-table-line-regexp "^[ \t]*|"
2431 "Detects an org-type table line.")
2432 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2433 "Detects an org-type table line.")
2434 (defconst org-table-hline-regexp "^[ \t]*|-"
2435 "Detects an org-type table hline.")
2436 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2437 "Detects a table-type table hline.")
2438 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2439 "Searching from within a table (any type) this finds the first line
2440 outside the table.")
2442 ;; Autoload the functions in org-table.el that are needed by functions here.
2444 (eval-and-compile
2445 (org-autoload "org-table"
2446 '(org-table-align org-table-begin org-table-blank-field
2447 org-table-convert org-table-convert-region org-table-copy-down
2448 org-table-copy-region org-table-create
2449 org-table-create-or-convert-from-region
2450 org-table-create-with-table.el org-table-current-dline
2451 org-table-cut-region org-table-delete-column org-table-edit-field
2452 org-table-edit-formulas org-table-end org-table-eval-formula
2453 org-table-export org-table-field-info
2454 org-table-get-stored-formulas org-table-goto-column
2455 org-table-hline-and-move org-table-import org-table-insert-column
2456 org-table-insert-hline org-table-insert-row org-table-iterate
2457 org-table-justify-field-maybe org-table-kill-row
2458 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2459 org-table-move-column org-table-move-column-left
2460 org-table-move-column-right org-table-move-row
2461 org-table-move-row-down org-table-move-row-up
2462 org-table-next-field org-table-next-row org-table-paste-rectangle
2463 org-table-previous-field org-table-recalculate
2464 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2465 org-table-toggle-coordinate-overlays
2466 org-table-toggle-formula-debugger org-table-wrap-region
2467 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2469 (defun org-at-table-p (&optional table-type)
2470 "Return t if the cursor is inside an org-type table.
2471 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2472 (if org-enable-table-editor
2473 (save-excursion
2474 (beginning-of-line 1)
2475 (looking-at (if table-type org-table-any-line-regexp
2476 org-table-line-regexp)))
2477 nil))
2478 (defsubst org-table-p () (org-at-table-p))
2480 (defun org-at-table.el-p ()
2481 "Return t if and only if we are at a table.el table."
2482 (and (org-at-table-p 'any)
2483 (save-excursion
2484 (goto-char (org-table-begin 'any))
2485 (looking-at org-table1-hline-regexp))))
2486 (defun org-table-recognize-table.el ()
2487 "If there is a table.el table nearby, recognize it and move into it."
2488 (if org-table-tab-recognizes-table.el
2489 (if (org-at-table.el-p)
2490 (progn
2491 (beginning-of-line 1)
2492 (if (looking-at org-table-dataline-regexp)
2494 (if (looking-at org-table1-hline-regexp)
2495 (progn
2496 (beginning-of-line 2)
2497 (if (looking-at org-table-any-border-regexp)
2498 (beginning-of-line -1)))))
2499 (if (re-search-forward "|" (org-table-end t) t)
2500 (progn
2501 (require 'table)
2502 (if (table--at-cell-p (point))
2504 (message "recognizing table.el table...")
2505 (table-recognize-table)
2506 (message "recognizing table.el table...done")))
2507 (error "This should not happen..."))
2509 nil)
2510 nil))
2512 (defun org-at-table-hline-p ()
2513 "Return t if the cursor is inside a hline in a table."
2514 (if org-enable-table-editor
2515 (save-excursion
2516 (beginning-of-line 1)
2517 (looking-at org-table-hline-regexp))
2518 nil))
2520 (defvar org-table-clean-did-remove-column nil)
2522 (defun org-table-map-tables (function)
2523 "Apply FUNCTION to the start of all tables in the buffer."
2524 (save-excursion
2525 (save-restriction
2526 (widen)
2527 (goto-char (point-min))
2528 (while (re-search-forward org-table-any-line-regexp nil t)
2529 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2530 (beginning-of-line 1)
2531 (if (looking-at org-table-line-regexp)
2532 (save-excursion (funcall function)))
2533 (re-search-forward org-table-any-border-regexp nil 1))))
2534 (message "Mapping tables: done"))
2536 ;; Declare and autoload functions from org-exp.el
2538 (declare-function org-default-export-plist "org-exp")
2539 (declare-function org-infile-export-plist "org-exp")
2540 (declare-function org-get-current-options "org-exp")
2541 (eval-and-compile
2542 (org-autoload "org-exp"
2543 '(org-export org-export-as-ascii org-export-visible
2544 org-insert-export-options-template org-export-as-html-and-open
2545 org-export-as-html-batch org-export-as-html-to-buffer
2546 org-replace-region-by-html org-export-region-as-html
2547 org-export-as-html org-export-icalendar-this-file
2548 org-export-icalendar-all-agenda-files
2549 org-table-clean-before-export
2550 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2552 ;; Declare and autoload functions from org-agenda.el
2554 (eval-and-compile
2555 (org-autoload "org-agenda"
2556 '(org-agenda org-agenda-list org-search-view
2557 org-todo-list org-tags-view org-agenda-list-stuck-projects
2558 org-diary org-agenda-to-appt)))
2560 ;; Autoload org-remember
2562 (eval-and-compile
2563 (org-autoload "org-remember"
2564 '(org-remember-insinuate org-remember-annotation
2565 org-remember-apply-template org-remember org-remember-handler)))
2567 ;; Autoload org-clock.el
2570 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2571 (beg end))
2572 (declare-function org-update-mode-line "org-clock" ())
2573 (defvar org-clock-start-time)
2574 (defvar org-clock-marker (make-marker)
2575 "Marker recording the last clock-in.")
2577 (eval-and-compile
2578 (org-autoload
2579 "org-clock"
2580 '(org-clock-in org-clock-out org-clock-cancel
2581 org-clock-goto org-clock-sum org-clock-display
2582 org-remove-clock-overlays org-clock-report
2583 org-clocktable-shift org-dblock-write:clocktable
2584 org-get-clocktable)))
2586 (defun org-clock-update-time-maybe ()
2587 "If this is a CLOCK line, update it and return t.
2588 Otherwise, return nil."
2589 (interactive)
2590 (save-excursion
2591 (beginning-of-line 1)
2592 (skip-chars-forward " \t")
2593 (when (looking-at org-clock-string)
2594 (let ((re (concat "[ \t]*" org-clock-string
2595 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2596 "\\([ \t]*=>.*\\)?\\)?"))
2597 ts te h m s neg)
2598 (cond
2599 ((not (looking-at re))
2600 nil)
2601 ((not (match-end 2))
2602 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2603 (> org-clock-marker (point))
2604 (<= org-clock-marker (point-at-eol)))
2605 ;; The clock is running here
2606 (setq org-clock-start-time
2607 (apply 'encode-time
2608 (org-parse-time-string (match-string 1))))
2609 (org-update-mode-line)))
2611 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2612 (end-of-line 1)
2613 (setq ts (match-string 1)
2614 te (match-string 3))
2615 (setq s (- (time-to-seconds
2616 (apply 'encode-time (org-parse-time-string te)))
2617 (time-to-seconds
2618 (apply 'encode-time (org-parse-time-string ts))))
2619 neg (< s 0)
2620 s (abs s)
2621 h (floor (/ s 3600))
2622 s (- s (* 3600 h))
2623 m (floor (/ s 60))
2624 s (- s (* 60 s)))
2625 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2626 t))))))
2628 (defun org-check-running-clock ()
2629 "Check if the current buffer contains the running clock.
2630 If yes, offer to stop it and to save the buffer with the changes."
2631 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2632 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2633 (buffer-name))))
2634 (org-clock-out)
2635 (when (y-or-n-p "Save changed buffer?")
2636 (save-buffer))))
2638 (defun org-clocktable-try-shift (dir n)
2639 "Check if this line starts a clock table, if yes, shift the time block."
2640 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2641 (org-clocktable-shift dir n)))
2643 ;; Autoload archiving code
2644 ;; The stuff that is needed for cycling and tags has to be defined here.
2646 (defgroup org-archive nil
2647 "Options concerning archiving in Org-mode."
2648 :tag "Org Archive"
2649 :group 'org-structure)
2651 (defcustom org-archive-location "%s_archive::"
2652 "The location where subtrees should be archived.
2654 The value of this variable is a string, consisting of two parts,
2655 separated by a double-colon. The first part is a filename and
2656 the second part is a headline.
2658 When the filename is omitted, archiving happens in the same file.
2659 %s in the filename will be replaced by the current file
2660 name (without the directory part). Archiving to a different file
2661 is useful to keep archived entries from contributing to the
2662 Org-mode Agenda.
2664 The archived entries will be filed as subtrees of the specified
2665 headline. When the headline is omitted, the subtrees are simply
2666 filed away at the end of the file, as top-level entries.
2668 Here are a few examples:
2669 \"%s_archive::\"
2670 If the current file is Projects.org, archive in file
2671 Projects.org_archive, as top-level trees. This is the default.
2673 \"::* Archived Tasks\"
2674 Archive in the current file, under the top-level headline
2675 \"* Archived Tasks\".
2677 \"~/org/archive.org::\"
2678 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2680 \"basement::** Finished Tasks\"
2681 Archive in file ./basement (relative path), as level 3 trees
2682 below the level 2 heading \"** Finished Tasks\".
2684 You may set this option on a per-file basis by adding to the buffer a
2685 line like
2687 #+ARCHIVE: basement::** Finished Tasks
2689 You may also define it locally for a subtree by setting an ARCHIVE property
2690 in the entry. If such a property is found in an entry, or anywhere up
2691 the hierarchy, it will be used."
2692 :group 'org-archive
2693 :type 'string)
2695 (defcustom org-archive-tag "ARCHIVE"
2696 "The tag that marks a subtree as archived.
2697 An archived subtree does not open during visibility cycling, and does
2698 not contribute to the agenda listings.
2699 After changing this, font-lock must be restarted in the relevant buffers to
2700 get the proper fontification."
2701 :group 'org-archive
2702 :group 'org-keywords
2703 :type 'string)
2705 (defcustom org-agenda-skip-archived-trees t
2706 "Non-nil means, the agenda will skip any items located in archived trees.
2707 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2708 variable is no longer recommended, you should leave it at the value t.
2709 Instead, use the key `v' to cycle the archives-mode in the agenda."
2710 :group 'org-archive
2711 :group 'org-agenda-skip
2712 :type 'boolean)
2714 (defcustom org-cycle-open-archived-trees nil
2715 "Non-nil means, `org-cycle' will open archived trees.
2716 An archived tree is a tree marked with the tag ARCHIVE.
2717 When nil, archived trees will stay folded. You can still open them with
2718 normal outline commands like `show-all', but not with the cycling commands."
2719 :group 'org-archive
2720 :group 'org-cycle
2721 :type 'boolean)
2723 (defcustom org-sparse-tree-open-archived-trees nil
2724 "Non-nil means sparse tree construction shows matches in archived trees.
2725 When nil, matches in these trees are highlighted, but the trees are kept in
2726 collapsed state."
2727 :group 'org-archive
2728 :group 'org-sparse-trees
2729 :type 'boolean)
2731 (defun org-cycle-hide-archived-subtrees (state)
2732 "Re-hide all archived subtrees after a visibility state change."
2733 (when (and (not org-cycle-open-archived-trees)
2734 (not (memq state '(overview folded))))
2735 (save-excursion
2736 (let* ((globalp (memq state '(contents all)))
2737 (beg (if globalp (point-min) (point)))
2738 (end (if globalp (point-max) (org-end-of-subtree t))))
2739 (org-hide-archived-subtrees beg end)
2740 (goto-char beg)
2741 (if (looking-at (concat ".*:" org-archive-tag ":"))
2742 (message "%s" (substitute-command-keys
2743 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2745 (defun org-force-cycle-archived ()
2746 "Cycle subtree even if it is archived."
2747 (interactive)
2748 (setq this-command 'org-cycle)
2749 (let ((org-cycle-open-archived-trees t))
2750 (call-interactively 'org-cycle)))
2752 (defun org-hide-archived-subtrees (beg end)
2753 "Re-hide all archived subtrees after a visibility state change."
2754 (save-excursion
2755 (let* ((re (concat ":" org-archive-tag ":")))
2756 (goto-char beg)
2757 (while (re-search-forward re end t)
2758 (and (org-on-heading-p) (hide-subtree))
2759 (org-end-of-subtree t)))))
2761 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2763 (eval-and-compile
2764 (org-autoload "org-archive"
2765 '(org-add-archive-files org-archive-subtree
2766 org-archive-to-archive-sibling org-toggle-archive-tag)))
2768 ;; Autoload Column View Code
2770 (declare-function org-columns-number-to-string "org-colview")
2771 (declare-function org-columns-get-format-and-top-level "org-colview")
2772 (declare-function org-columns-compute "org-colview")
2774 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2775 '(org-columns-number-to-string org-columns-get-format-and-top-level
2776 org-columns-compute org-agenda-columns org-columns-remove-overlays
2777 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2779 ;; Autoload ID code
2781 (org-autoload "org-id"
2782 '(org-id-get-create org-id-new org-id-copy org-id-get
2783 org-id-get-with-outline-path-completion
2784 org-id-get-with-outline-drilling
2785 org-id-goto org-id-find))
2787 ;;; Variables for pre-computed regular expressions, all buffer local
2789 (defvar org-drawer-regexp nil
2790 "Matches first line of a hidden block.")
2791 (make-variable-buffer-local 'org-drawer-regexp)
2792 (defvar org-todo-regexp nil
2793 "Matches any of the TODO state keywords.")
2794 (make-variable-buffer-local 'org-todo-regexp)
2795 (defvar org-not-done-regexp nil
2796 "Matches any of the TODO state keywords except the last one.")
2797 (make-variable-buffer-local 'org-not-done-regexp)
2798 (defvar org-todo-line-regexp nil
2799 "Matches a headline and puts TODO state into group 2 if present.")
2800 (make-variable-buffer-local 'org-todo-line-regexp)
2801 (defvar org-complex-heading-regexp nil
2802 "Matches a headline and puts everything into groups:
2803 group 1: the stars
2804 group 2: The todo keyword, maybe
2805 group 3: Priority cookie
2806 group 4: True headline
2807 group 5: Tags")
2808 (make-variable-buffer-local 'org-complex-heading-regexp)
2809 (defvar org-todo-line-tags-regexp nil
2810 "Matches a headline and puts TODO state into group 2 if present.
2811 Also put tags into group 4 if tags are present.")
2812 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2813 (defvar org-nl-done-regexp nil
2814 "Matches newline followed by a headline with the DONE keyword.")
2815 (make-variable-buffer-local 'org-nl-done-regexp)
2816 (defvar org-looking-at-done-regexp nil
2817 "Matches the DONE keyword a point.")
2818 (make-variable-buffer-local 'org-looking-at-done-regexp)
2819 (defvar org-ds-keyword-length 12
2820 "Maximum length of the Deadline and SCHEDULED keywords.")
2821 (make-variable-buffer-local 'org-ds-keyword-length)
2822 (defvar org-deadline-regexp nil
2823 "Matches the DEADLINE keyword.")
2824 (make-variable-buffer-local 'org-deadline-regexp)
2825 (defvar org-deadline-time-regexp nil
2826 "Matches the DEADLINE keyword together with a time stamp.")
2827 (make-variable-buffer-local 'org-deadline-time-regexp)
2828 (defvar org-deadline-line-regexp nil
2829 "Matches the DEADLINE keyword and the rest of the line.")
2830 (make-variable-buffer-local 'org-deadline-line-regexp)
2831 (defvar org-scheduled-regexp nil
2832 "Matches the SCHEDULED keyword.")
2833 (make-variable-buffer-local 'org-scheduled-regexp)
2834 (defvar org-scheduled-time-regexp nil
2835 "Matches the SCHEDULED keyword together with a time stamp.")
2836 (make-variable-buffer-local 'org-scheduled-time-regexp)
2837 (defvar org-closed-time-regexp nil
2838 "Matches the CLOSED keyword together with a time stamp.")
2839 (make-variable-buffer-local 'org-closed-time-regexp)
2841 (defvar org-keyword-time-regexp nil
2842 "Matches any of the 4 keywords, together with the time stamp.")
2843 (make-variable-buffer-local 'org-keyword-time-regexp)
2844 (defvar org-keyword-time-not-clock-regexp nil
2845 "Matches any of the 3 keywords, together with the time stamp.")
2846 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2847 (defvar org-maybe-keyword-time-regexp nil
2848 "Matches a timestamp, possibly preceeded by a keyword.")
2849 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2850 (defvar org-planning-or-clock-line-re nil
2851 "Matches a line with planning or clock info.")
2852 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2854 (defconst org-plain-time-of-day-regexp
2855 (concat
2856 "\\(\\<[012]?[0-9]"
2857 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2858 "\\(--?"
2859 "\\(\\<[012]?[0-9]"
2860 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2861 "\\)?")
2862 "Regular expression to match a plain time or time range.
2863 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2864 groups carry important information:
2865 0 the full match
2866 1 the first time, range or not
2867 8 the second time, if it is a range.")
2869 (defconst org-plain-time-extension-regexp
2870 (concat
2871 "\\(\\<[012]?[0-9]"
2872 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2873 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2874 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2875 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2876 groups carry important information:
2877 0 the full match
2878 7 hours of duration
2879 9 minutes of duration")
2881 (defconst org-stamp-time-of-day-regexp
2882 (concat
2883 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2884 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2885 "\\(--?"
2886 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2887 "Regular expression to match a timestamp time or time range.
2888 After a match, the following groups carry important information:
2889 0 the full match
2890 1 date plus weekday, for backreferencing to make sure both times on same day
2891 2 the first time, range or not
2892 4 the second time, if it is a range.")
2894 (defconst org-startup-options
2895 '(("fold" org-startup-folded t)
2896 ("overview" org-startup-folded t)
2897 ("nofold" org-startup-folded nil)
2898 ("showall" org-startup-folded nil)
2899 ("content" org-startup-folded content)
2900 ("hidestars" org-hide-leading-stars t)
2901 ("showstars" org-hide-leading-stars nil)
2902 ("odd" org-odd-levels-only t)
2903 ("oddeven" org-odd-levels-only nil)
2904 ("align" org-startup-align-all-tables t)
2905 ("noalign" org-startup-align-all-tables nil)
2906 ("customtime" org-display-custom-times t)
2907 ("logdone" org-log-done time)
2908 ("lognotedone" org-log-done note)
2909 ("nologdone" org-log-done nil)
2910 ("lognoteclock-out" org-log-note-clock-out t)
2911 ("nolognoteclock-out" org-log-note-clock-out nil)
2912 ("logrepeat" org-log-repeat state)
2913 ("lognoterepeat" org-log-repeat note)
2914 ("nologrepeat" org-log-repeat nil)
2915 ("constcgs" constants-unit-system cgs)
2916 ("constSI" constants-unit-system SI))
2917 "Variable associated with STARTUP options for org-mode.
2918 Each element is a list of three items: The startup options as written
2919 in the #+STARTUP line, the corresponding variable, and the value to
2920 set this variable to if the option is found. An optional forth element PUSH
2921 means to push this value onto the list in the variable.")
2923 (defun org-set-regexps-and-options ()
2924 "Precompute regular expressions for current buffer."
2925 (when (org-mode-p)
2926 (org-set-local 'org-todo-kwd-alist nil)
2927 (org-set-local 'org-todo-key-alist nil)
2928 (org-set-local 'org-todo-key-trigger nil)
2929 (org-set-local 'org-todo-keywords-1 nil)
2930 (org-set-local 'org-done-keywords nil)
2931 (org-set-local 'org-todo-heads nil)
2932 (org-set-local 'org-todo-sets nil)
2933 (org-set-local 'org-todo-log-states nil)
2934 (org-set-local 'org-file-properties nil)
2935 (org-set-local 'org-file-tags nil)
2936 (let ((re (org-make-options-regexp
2937 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2938 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2939 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2940 (splitre "[ \t]+")
2941 kwds kws0 kwsa key log value cat arch tags const links hw dws
2942 tail sep kws1 prio props ftags drawers
2943 ext-setup-or-nil setup-contents (start 0))
2944 (save-excursion
2945 (save-restriction
2946 (widen)
2947 (goto-char (point-min))
2948 (while (or (and ext-setup-or-nil
2949 (string-match re ext-setup-or-nil start)
2950 (setq start (match-end 0)))
2951 (and (setq ext-setup-or-nil nil start 0)
2952 (re-search-forward re nil t)))
2953 (setq key (upcase (match-string 1 ext-setup-or-nil))
2954 value (org-match-string-no-properties 2 ext-setup-or-nil))
2955 (cond
2956 ((equal key "CATEGORY")
2957 (if (string-match "[ \t]+$" value)
2958 (setq value (replace-match "" t t value)))
2959 (setq cat value))
2960 ((member key '("SEQ_TODO" "TODO"))
2961 (push (cons 'sequence (org-split-string value splitre)) kwds))
2962 ((equal key "TYP_TODO")
2963 (push (cons 'type (org-split-string value splitre)) kwds))
2964 ((equal key "TAGS")
2965 (setq tags (append tags (org-split-string value splitre))))
2966 ((equal key "COLUMNS")
2967 (org-set-local 'org-columns-default-format value))
2968 ((equal key "LINK")
2969 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2970 (push (cons (match-string 1 value)
2971 (org-trim (match-string 2 value)))
2972 links)))
2973 ((equal key "PRIORITIES")
2974 (setq prio (org-split-string value " +")))
2975 ((equal key "PROPERTY")
2976 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2977 (push (cons (match-string 1 value) (match-string 2 value))
2978 props)))
2979 ((equal key "FILETAGS")
2980 (when (string-match "\\S-" value)
2981 (setq ftags
2982 (append
2983 ftags
2984 (apply 'append
2985 (mapcar (lambda (x) (org-split-string x ":"))
2986 (org-split-string value)))))))
2987 ((equal key "DRAWERS")
2988 (setq drawers (org-split-string value splitre)))
2989 ((equal key "CONSTANTS")
2990 (setq const (append const (org-split-string value splitre))))
2991 ((equal key "STARTUP")
2992 (let ((opts (org-split-string value splitre))
2993 l var val)
2994 (while (setq l (pop opts))
2995 (when (setq l (assoc l org-startup-options))
2996 (setq var (nth 1 l) val (nth 2 l))
2997 (if (not (nth 3 l))
2998 (set (make-local-variable var) val)
2999 (if (not (listp (symbol-value var)))
3000 (set (make-local-variable var) nil))
3001 (set (make-local-variable var) (symbol-value var))
3002 (add-to-list var val))))))
3003 ((equal key "ARCHIVE")
3004 (string-match " *$" value)
3005 (setq arch (replace-match "" t t value))
3006 (remove-text-properties 0 (length arch)
3007 '(face t fontified t) arch))
3008 ((equal key "SETUPFILE")
3009 (setq setup-contents (org-file-contents
3010 (expand-file-name
3011 (org-remove-double-quotes value))
3012 'noerror))
3013 (if (not ext-setup-or-nil)
3014 (setq ext-setup-or-nil setup-contents start 0)
3015 (setq ext-setup-or-nil
3016 (concat (substring ext-setup-or-nil 0 start)
3017 "\n" setup-contents "\n"
3018 (substring ext-setup-or-nil start)))))
3019 ))))
3020 (when cat
3021 (org-set-local 'org-category (intern cat))
3022 (push (cons "CATEGORY" cat) props))
3023 (when prio
3024 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3025 (setq prio (mapcar 'string-to-char prio))
3026 (org-set-local 'org-highest-priority (nth 0 prio))
3027 (org-set-local 'org-lowest-priority (nth 1 prio))
3028 (org-set-local 'org-default-priority (nth 2 prio)))
3029 (and props (org-set-local 'org-file-properties (nreverse props)))
3030 (and ftags (org-set-local 'org-file-tags ftags))
3031 (and drawers (org-set-local 'org-drawers drawers))
3032 (and arch (org-set-local 'org-archive-location arch))
3033 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3034 ;; Process the TODO keywords
3035 (unless kwds
3036 ;; Use the global values as if they had been given locally.
3037 (setq kwds (default-value 'org-todo-keywords))
3038 (if (stringp (car kwds))
3039 (setq kwds (list (cons org-todo-interpretation
3040 (default-value 'org-todo-keywords)))))
3041 (setq kwds (reverse kwds)))
3042 (setq kwds (nreverse kwds))
3043 (let (inter kws kw)
3044 (while (setq kws (pop kwds))
3045 (setq inter (pop kws) sep (member "|" kws)
3046 kws0 (delete "|" (copy-sequence kws))
3047 kwsa nil
3048 kws1 (mapcar
3049 (lambda (x)
3050 ;; 1 2
3051 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3052 (progn
3053 (setq kw (match-string 1 x)
3054 key (and (match-end 2) (match-string 2 x))
3055 log (org-extract-log-state-settings x))
3056 (push (cons kw (and key (string-to-char key))) kwsa)
3057 (and log (push log org-todo-log-states))
3059 (error "Invalid TODO keyword %s" x)))
3060 kws0)
3061 kwsa (if kwsa (append '((:startgroup))
3062 (nreverse kwsa)
3063 '((:endgroup))))
3064 hw (car kws1)
3065 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3066 tail (list inter hw (car dws) (org-last dws)))
3067 (add-to-list 'org-todo-heads hw 'append)
3068 (push kws1 org-todo-sets)
3069 (setq org-done-keywords (append org-done-keywords dws nil))
3070 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3071 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3072 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3073 (setq org-todo-sets (nreverse org-todo-sets)
3074 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3075 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3076 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3077 ;; Process the constants
3078 (when const
3079 (let (e cst)
3080 (while (setq e (pop const))
3081 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3082 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3083 (setq org-table-formula-constants-local cst)))
3085 ;; Process the tags.
3086 (when tags
3087 (let (e tgs)
3088 (while (setq e (pop tags))
3089 (cond
3090 ((equal e "{") (push '(:startgroup) tgs))
3091 ((equal e "}") (push '(:endgroup) tgs))
3092 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3093 (push (cons (match-string 1 e)
3094 (string-to-char (match-string 2 e)))
3095 tgs))
3096 (t (push (list e) tgs))))
3097 (org-set-local 'org-tag-alist nil)
3098 (while (setq e (pop tgs))
3099 (or (and (stringp (car e))
3100 (assoc (car e) org-tag-alist))
3101 (push e org-tag-alist)))))
3103 ;; Compute the regular expressions and other local variables
3104 (if (not org-done-keywords)
3105 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3106 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3107 (length org-scheduled-string)
3108 (length org-clock-string)
3109 (length org-closed-string)))
3110 org-drawer-regexp
3111 (concat "^[ \t]*:\\("
3112 (mapconcat 'regexp-quote org-drawers "\\|")
3113 "\\):[ \t]*$")
3114 org-not-done-keywords
3115 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3116 org-todo-regexp
3117 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3118 "\\|") "\\)\\>")
3119 org-not-done-regexp
3120 (concat "\\<\\("
3121 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3122 "\\)\\>")
3123 org-todo-line-regexp
3124 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3125 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3126 "\\)\\>\\)?[ \t]*\\(.*\\)")
3127 org-complex-heading-regexp
3128 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3129 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3130 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3131 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3132 org-nl-done-regexp
3133 (concat "\n\\*+[ \t]+"
3134 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3135 "\\)" "\\>")
3136 org-todo-line-tags-regexp
3137 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3138 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3139 (org-re
3140 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3141 org-looking-at-done-regexp
3142 (concat "^" "\\(?:"
3143 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3144 "\\>")
3145 org-deadline-regexp (concat "\\<" org-deadline-string)
3146 org-deadline-time-regexp
3147 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3148 org-deadline-line-regexp
3149 (concat "\\<\\(" org-deadline-string "\\).*")
3150 org-scheduled-regexp
3151 (concat "\\<" org-scheduled-string)
3152 org-scheduled-time-regexp
3153 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3154 org-closed-time-regexp
3155 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3156 org-keyword-time-regexp
3157 (concat "\\<\\(" org-scheduled-string
3158 "\\|" org-deadline-string
3159 "\\|" org-closed-string
3160 "\\|" org-clock-string "\\)"
3161 " *[[<]\\([^]>]+\\)[]>]")
3162 org-keyword-time-not-clock-regexp
3163 (concat "\\<\\(" org-scheduled-string
3164 "\\|" org-deadline-string
3165 "\\|" org-closed-string
3166 "\\)"
3167 " *[[<]\\([^]>]+\\)[]>]")
3168 org-maybe-keyword-time-regexp
3169 (concat "\\(\\<\\(" org-scheduled-string
3170 "\\|" org-deadline-string
3171 "\\|" org-closed-string
3172 "\\|" org-clock-string "\\)\\)?"
3173 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3174 org-planning-or-clock-line-re
3175 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3176 "\\|" org-deadline-string
3177 "\\|" org-closed-string "\\|" org-clock-string
3178 "\\)\\>\\)")
3180 (org-compute-latex-and-specials-regexp)
3181 (org-set-font-lock-defaults))))
3183 (defun org-file-contents (file &optional noerror)
3184 "Return the contents of FILE, as a string."
3185 (if (or (not file)
3186 (not (file-readable-p file)))
3187 (if noerror
3188 (progn
3189 (message "Cannot read file %s" file)
3190 (ding) (sit-for 2)
3192 (error "Cannot read file %s" file))
3193 (with-temp-buffer
3194 (insert-file-contents file)
3195 (buffer-string))))
3197 (defun org-extract-log-state-settings (x)
3198 "Extract the log state setting from a TODO keyword string.
3199 This will extract info from a string like \"WAIT(w@/!)\"."
3200 (let (kw key log1 log2)
3201 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3202 (setq kw (match-string 1 x)
3203 key (and (match-end 2) (match-string 2 x))
3204 log1 (and (match-end 3) (match-string 3 x))
3205 log2 (and (match-end 4) (match-string 4 x)))
3206 (and (or log1 log2)
3207 (list kw
3208 (and log1 (if (equal log1 "!") 'time 'note))
3209 (and log2 (if (equal log2 "!") 'time 'note)))))))
3211 (defun org-remove-keyword-keys (list)
3212 "Remove a pair of parenthesis at the end of each string in LIST."
3213 (mapcar (lambda (x)
3214 (if (string-match "(.*)$" x)
3215 (substring x 0 (match-beginning 0))
3217 list))
3219 ;; FIXME: this could be done much better, using second characters etc.
3220 (defun org-assign-fast-keys (alist)
3221 "Assign fast keys to a keyword-key alist.
3222 Respect keys that are already there."
3223 (let (new e k c c1 c2 (char ?a))
3224 (while (setq e (pop alist))
3225 (cond
3226 ((equal e '(:startgroup)) (push e new))
3227 ((equal e '(:endgroup)) (push e new))
3229 (setq k (car e) c2 nil)
3230 (if (cdr e)
3231 (setq c (cdr e))
3232 ;; automatically assign a character.
3233 (setq c1 (string-to-char
3234 (downcase (substring
3235 k (if (= (string-to-char k) ?@) 1 0)))))
3236 (if (or (rassoc c1 new) (rassoc c1 alist))
3237 (while (or (rassoc char new) (rassoc char alist))
3238 (setq char (1+ char)))
3239 (setq c2 c1))
3240 (setq c (or c2 char)))
3241 (push (cons k c) new))))
3242 (nreverse new)))
3244 ;;; Some variables used in various places
3246 (defvar org-window-configuration nil
3247 "Used in various places to store a window configuration.")
3248 (defvar org-finish-function nil
3249 "Function to be called when `C-c C-c' is used.
3250 This is for getting out of special buffers like remember.")
3253 ;; FIXME: Occasionally check by commenting these, to make sure
3254 ;; no other functions uses these, forgetting to let-bind them.
3255 (defvar entry)
3256 (defvar state)
3257 (defvar last-state)
3258 (defvar date)
3259 (defvar description)
3261 ;; Defined somewhere in this file, but used before definition.
3262 (defvar org-html-entities)
3263 (defvar org-struct-menu)
3264 (defvar org-org-menu)
3265 (defvar org-tbl-menu)
3266 (defvar org-agenda-keymap)
3268 ;;;; Define the Org-mode
3270 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3271 (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."))
3274 ;; We use a before-change function to check if a table might need
3275 ;; an update.
3276 (defvar org-table-may-need-update t
3277 "Indicates that a table might need an update.
3278 This variable is set by `org-before-change-function'.
3279 `org-table-align' sets it back to nil.")
3280 (defun org-before-change-function (beg end)
3281 "Every change indicates that a table might need an update."
3282 (setq org-table-may-need-update t))
3283 (defvar org-mode-map)
3284 (defvar org-mode-hook nil)
3285 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3286 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3287 (defvar org-table-buffer-is-an nil)
3288 (defconst org-outline-regexp "\\*+ ")
3290 ;;;###autoload
3291 (define-derived-mode org-mode outline-mode "Org"
3292 "Outline-based notes management and organizer, alias
3293 \"Carsten's outline-mode for keeping track of everything.\"
3295 Org-mode develops organizational tasks around a NOTES file which
3296 contains information about projects as plain text. Org-mode is
3297 implemented on top of outline-mode, which is ideal to keep the content
3298 of large files well structured. It supports ToDo items, deadlines and
3299 time stamps, which magically appear in the diary listing of the Emacs
3300 calendar. Tables are easily created with a built-in table editor.
3301 Plain text URL-like links connect to websites, emails (VM), Usenet
3302 messages (Gnus), BBDB entries, and any files related to the project.
3303 For printing and sharing of notes, an Org-mode file (or a part of it)
3304 can be exported as a structured ASCII or HTML file.
3306 The following commands are available:
3308 \\{org-mode-map}"
3310 ;; Get rid of Outline menus, they are not needed
3311 ;; Need to do this here because define-derived-mode sets up
3312 ;; the keymap so late. Still, it is a waste to call this each time
3313 ;; we switch another buffer into org-mode.
3314 (if (featurep 'xemacs)
3315 (when (boundp 'outline-mode-menu-heading)
3316 ;; Assume this is Greg's port, it used easymenu
3317 (easy-menu-remove outline-mode-menu-heading)
3318 (easy-menu-remove outline-mode-menu-show)
3319 (easy-menu-remove outline-mode-menu-hide))
3320 (define-key org-mode-map [menu-bar headings] 'undefined)
3321 (define-key org-mode-map [menu-bar hide] 'undefined)
3322 (define-key org-mode-map [menu-bar show] 'undefined))
3324 (org-load-modules-maybe)
3325 (easy-menu-add org-org-menu)
3326 (easy-menu-add org-tbl-menu)
3327 (org-install-agenda-files-menu)
3328 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3329 (org-add-to-invisibility-spec '(org-cwidth))
3330 (when (featurep 'xemacs)
3331 (org-set-local 'line-move-ignore-invisible t))
3332 (org-set-local 'outline-regexp org-outline-regexp)
3333 (org-set-local 'outline-level 'org-outline-level)
3334 (when (and org-ellipsis
3335 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3336 (fboundp 'make-glyph-code))
3337 (unless org-display-table
3338 (setq org-display-table (make-display-table)))
3339 (set-display-table-slot
3340 org-display-table 4
3341 (vconcat (mapcar
3342 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3343 org-ellipsis)))
3344 (if (stringp org-ellipsis) org-ellipsis "..."))))
3345 (setq buffer-display-table org-display-table))
3346 (org-set-regexps-and-options)
3347 ;; Calc embedded
3348 (org-set-local 'calc-embedded-open-mode "# ")
3349 (modify-syntax-entry ?# "<")
3350 (modify-syntax-entry ?@ "w")
3351 (if org-startup-truncated (setq truncate-lines t))
3352 (org-set-local 'font-lock-unfontify-region-function
3353 'org-unfontify-region)
3354 ;; Activate before-change-function
3355 (org-set-local 'org-table-may-need-update t)
3356 (org-add-hook 'before-change-functions 'org-before-change-function nil
3357 'local)
3358 ;; Check for running clock before killing a buffer
3359 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3360 ;; Paragraphs and auto-filling
3361 (org-set-autofill-regexps)
3362 (setq indent-line-function 'org-indent-line-function)
3363 (org-update-radio-target-regexp)
3365 ;; Comment characters
3366 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3367 (org-set-local 'comment-padding " ")
3369 ;; Align options lines
3370 (org-set-local
3371 'align-mode-rules-list
3372 '((org-in-buffer-settings
3373 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3374 (modes . '(org-mode)))))
3376 ;; Imenu
3377 (org-set-local 'imenu-create-index-function
3378 'org-imenu-get-tree)
3380 ;; Make isearch reveal context
3381 (if (or (featurep 'xemacs)
3382 (not (boundp 'outline-isearch-open-invisible-function)))
3383 ;; Emacs 21 and XEmacs make use of the hook
3384 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3385 ;; Emacs 22 deals with this through a special variable
3386 (org-set-local 'outline-isearch-open-invisible-function
3387 (lambda (&rest ignore) (org-show-context 'isearch))))
3389 ;; If empty file that did not turn on org-mode automatically, make it to.
3390 (if (and org-insert-mode-line-in-empty-file
3391 (interactive-p)
3392 (= (point-min) (point-max)))
3393 (insert "# -*- mode: org -*-\n\n"))
3395 (unless org-inhibit-startup
3396 (when org-startup-align-all-tables
3397 (let ((bmp (buffer-modified-p)))
3398 (org-table-map-tables 'org-table-align)
3399 (set-buffer-modified-p bmp)))
3400 (org-set-startup-visibility)))
3402 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3404 (defun org-current-time ()
3405 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3406 (if (> (car org-time-stamp-rounding-minutes) 1)
3407 (let ((r (car org-time-stamp-rounding-minutes))
3408 (time (decode-time)))
3409 (apply 'encode-time
3410 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3411 (nthcdr 2 time))))
3412 (current-time)))
3414 ;;;; Font-Lock stuff, including the activators
3416 (defvar org-mouse-map (make-sparse-keymap))
3417 (org-defkey org-mouse-map
3418 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3419 (org-defkey org-mouse-map
3420 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3421 (when org-mouse-1-follows-link
3422 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3423 (when org-tab-follows-link
3424 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3425 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3426 (when org-return-follows-link
3427 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3428 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3430 (require 'font-lock)
3432 (defconst org-non-link-chars "]\t\n\r<>")
3433 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3434 "shell" "elisp"))
3435 (defvar org-link-types-re nil
3436 "Matches a link that has a url-like prefix like \"http:\"")
3437 (defvar org-link-re-with-space nil
3438 "Matches a link with spaces, optional angular brackets around it.")
3439 (defvar org-link-re-with-space2 nil
3440 "Matches a link with spaces, optional angular brackets around it.")
3441 (defvar org-link-re-with-space3 nil
3442 "Matches a link with spaces, only for internal part in bracket links.")
3443 (defvar org-angle-link-re nil
3444 "Matches link with angular brackets, spaces are allowed.")
3445 (defvar org-plain-link-re nil
3446 "Matches plain link, without spaces.")
3447 (defvar org-bracket-link-regexp nil
3448 "Matches a link in double brackets.")
3449 (defvar org-bracket-link-analytic-regexp nil
3450 "Regular expression used to analyze links.
3451 Here is what the match groups contain after a match:
3452 1: http:
3453 2: http
3454 3: path
3455 4: [desc]
3456 5: desc")
3457 (defvar org-any-link-re nil
3458 "Regular expression matching any link.")
3460 (defun org-make-link-regexps ()
3461 "Update the link regular expressions.
3462 This should be called after the variable `org-link-types' has changed."
3463 (setq org-link-types-re
3464 (concat
3465 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3466 org-link-re-with-space
3467 (concat
3468 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3469 "\\([^" org-non-link-chars " ]"
3470 "[^" org-non-link-chars "]*"
3471 "[^" org-non-link-chars " ]\\)>?")
3472 org-link-re-with-space2
3473 (concat
3474 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3475 "\\([^" org-non-link-chars " ]"
3476 "[^\t\n\r]*"
3477 "[^" org-non-link-chars " ]\\)>?")
3478 org-link-re-with-space3
3479 (concat
3480 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3481 "\\([^" org-non-link-chars " ]"
3482 "[^\t\n\r]*\\)")
3483 org-angle-link-re
3484 (concat
3485 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3486 "\\([^" org-non-link-chars " ]"
3487 "[^" org-non-link-chars "]*"
3488 "\\)>")
3489 org-plain-link-re
3490 (concat
3491 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3492 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3493 org-bracket-link-regexp
3494 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3495 org-bracket-link-analytic-regexp
3496 (concat
3497 "\\[\\["
3498 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3499 "\\([^]]+\\)"
3500 "\\]"
3501 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3502 "\\]")
3503 org-any-link-re
3504 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3505 org-angle-link-re "\\)\\|\\("
3506 org-plain-link-re "\\)")))
3508 (org-make-link-regexps)
3510 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3511 "Regular expression for fast time stamp matching.")
3512 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3513 "Regular expression for fast time stamp matching.")
3514 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3515 "Regular expression matching time strings for analysis.
3516 This one does not require the space after the date, so it can be used
3517 on a string that terminates immediately after the date.")
3518 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3519 "Regular expression matching time strings for analysis.")
3520 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3521 "Regular expression matching time stamps, with groups.")
3522 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3523 "Regular expression matching time stamps (also [..]), with groups.")
3524 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3525 "Regular expression matching a time stamp range.")
3526 (defconst org-tr-regexp-both
3527 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3528 "Regular expression matching a time stamp range.")
3529 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3530 org-ts-regexp "\\)?")
3531 "Regular expression matching a time stamp or time stamp range.")
3532 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3533 org-ts-regexp-both "\\)?")
3534 "Regular expression matching a time stamp or time stamp range.
3535 The time stamps may be either active or inactive.")
3537 (defvar org-emph-face nil)
3539 (defun org-do-emphasis-faces (limit)
3540 "Run through the buffer and add overlays to links."
3541 (let (rtn)
3542 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3543 (if (not (= (char-after (match-beginning 3))
3544 (char-after (match-beginning 4))))
3545 (progn
3546 (setq rtn t)
3547 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3548 'face
3549 (nth 1 (assoc (match-string 3)
3550 org-emphasis-alist)))
3551 (add-text-properties (match-beginning 2) (match-end 2)
3552 '(font-lock-multiline t))
3553 (when org-hide-emphasis-markers
3554 (add-text-properties (match-end 4) (match-beginning 5)
3555 '(invisible org-link))
3556 (add-text-properties (match-beginning 3) (match-end 3)
3557 '(invisible org-link)))))
3558 (backward-char 1))
3559 rtn))
3561 (defun org-emphasize (&optional char)
3562 "Insert or change an emphasis, i.e. a font like bold or italic.
3563 If there is an active region, change that region to a new emphasis.
3564 If there is no region, just insert the marker characters and position
3565 the cursor between them.
3566 CHAR should be either the marker character, or the first character of the
3567 HTML tag associated with that emphasis. If CHAR is a space, the means
3568 to remove the emphasis of the selected region.
3569 If char is not given (for example in an interactive call) it
3570 will be prompted for."
3571 (interactive)
3572 (let ((eal org-emphasis-alist) e det
3573 (erc org-emphasis-regexp-components)
3574 (prompt "")
3575 (string "") beg end move tag c s)
3576 (if (org-region-active-p)
3577 (setq beg (region-beginning) end (region-end)
3578 string (buffer-substring beg end))
3579 (setq move t))
3581 (while (setq e (pop eal))
3582 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3583 c (aref tag 0))
3584 (push (cons c (string-to-char (car e))) det)
3585 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3586 (substring tag 1)))))
3587 (setq det (nreverse det))
3588 (unless char
3589 (message "%s" (concat "Emphasis marker or tag:" prompt))
3590 (setq char (read-char-exclusive)))
3591 (setq char (or (cdr (assoc char det)) char))
3592 (if (equal char ?\ )
3593 (setq s "" move nil)
3594 (unless (assoc (char-to-string char) org-emphasis-alist)
3595 (error "No such emphasis marker: \"%c\"" char))
3596 (setq s (char-to-string char)))
3597 (while (and (> (length string) 1)
3598 (equal (substring string 0 1) (substring string -1))
3599 (assoc (substring string 0 1) org-emphasis-alist))
3600 (setq string (substring string 1 -1)))
3601 (setq string (concat s string s))
3602 (if beg (delete-region beg end))
3603 (unless (or (bolp)
3604 (string-match (concat "[" (nth 0 erc) "\n]")
3605 (char-to-string (char-before (point)))))
3606 (insert " "))
3607 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3608 (char-to-string (char-after (point))))
3609 (insert " ") (backward-char 1))
3610 (insert string)
3611 (and move (backward-char 1))))
3613 (defconst org-nonsticky-props
3614 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3617 (defun org-activate-plain-links (limit)
3618 "Run through the buffer and add overlays to links."
3619 (catch 'exit
3620 (let (f)
3621 (while (re-search-forward org-plain-link-re limit t)
3622 (setq f (get-text-property (match-beginning 0) 'face))
3623 (if (or (eq f 'org-tag)
3624 (and (listp f) (memq 'org-tag f)))
3626 (add-text-properties (match-beginning 0) (match-end 0)
3627 (list 'mouse-face 'highlight
3628 'rear-nonsticky org-nonsticky-props
3629 'keymap org-mouse-map
3631 (throw 'exit t))))))
3633 (defun org-activate-code (limit)
3634 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3635 (progn
3636 (remove-text-properties (match-beginning 0) (match-end 0)
3637 '(display t invisible t intangible t))
3638 t)))
3640 (defun org-activate-angle-links (limit)
3641 "Run through the buffer and add overlays to links."
3642 (if (re-search-forward org-angle-link-re limit t)
3643 (progn
3644 (add-text-properties (match-beginning 0) (match-end 0)
3645 (list 'mouse-face 'highlight
3646 'rear-nonsticky org-nonsticky-props
3647 'keymap org-mouse-map
3649 t)))
3651 (defun org-activate-bracket-links (limit)
3652 "Run through the buffer and add overlays to bracketed links."
3653 (if (re-search-forward org-bracket-link-regexp limit t)
3654 (let* ((help (concat "LINK: "
3655 (org-match-string-no-properties 1)))
3656 ;; FIXME: above we should remove the escapes.
3657 ;; but that requires another match, protecting match data,
3658 ;; a lot of overhead for font-lock.
3659 (ip (org-maybe-intangible
3660 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3661 'keymap org-mouse-map 'mouse-face 'highlight
3662 'font-lock-multiline t 'help-echo help)))
3663 (vp (list 'rear-nonsticky org-nonsticky-props
3664 'keymap org-mouse-map 'mouse-face 'highlight
3665 ' font-lock-multiline t 'help-echo help)))
3666 ;; We need to remove the invisible property here. Table narrowing
3667 ;; may have made some of this invisible.
3668 (remove-text-properties (match-beginning 0) (match-end 0)
3669 '(invisible nil))
3670 (if (match-end 3)
3671 (progn
3672 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3673 (add-text-properties (match-beginning 3) (match-end 3) vp)
3674 (add-text-properties (match-end 3) (match-end 0) ip))
3675 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3676 (add-text-properties (match-beginning 1) (match-end 1) vp)
3677 (add-text-properties (match-end 1) (match-end 0) ip))
3678 t)))
3680 (defun org-activate-dates (limit)
3681 "Run through the buffer and add overlays to dates."
3682 (if (re-search-forward org-tsr-regexp-both limit t)
3683 (progn
3684 (add-text-properties (match-beginning 0) (match-end 0)
3685 (list 'mouse-face 'highlight
3686 'rear-nonsticky org-nonsticky-props
3687 'keymap org-mouse-map))
3688 (when org-display-custom-times
3689 (if (match-end 3)
3690 (org-display-custom-time (match-beginning 3) (match-end 3)))
3691 (org-display-custom-time (match-beginning 1) (match-end 1)))
3692 t)))
3694 (defvar org-target-link-regexp nil
3695 "Regular expression matching radio targets in plain text.")
3696 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3697 "Regular expression matching a link target.")
3698 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3699 "Regular expression matching a radio target.")
3700 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3701 "Regular expression matching any target.")
3703 (defun org-activate-target-links (limit)
3704 "Run through the buffer and add overlays to target matches."
3705 (when org-target-link-regexp
3706 (let ((case-fold-search t))
3707 (if (re-search-forward org-target-link-regexp limit t)
3708 (progn
3709 (add-text-properties (match-beginning 0) (match-end 0)
3710 (list 'mouse-face 'highlight
3711 'rear-nonsticky org-nonsticky-props
3712 'keymap org-mouse-map
3713 'help-echo "Radio target link"
3714 'org-linked-text t))
3715 t)))))
3717 (defun org-update-radio-target-regexp ()
3718 "Find all radio targets in this file and update the regular expression."
3719 (interactive)
3720 (when (memq 'radio org-activate-links)
3721 (setq org-target-link-regexp
3722 (org-make-target-link-regexp (org-all-targets 'radio)))
3723 (org-restart-font-lock)))
3725 (defun org-hide-wide-columns (limit)
3726 (let (s e)
3727 (setq s (text-property-any (point) (or limit (point-max))
3728 'org-cwidth t))
3729 (when s
3730 (setq e (next-single-property-change s 'org-cwidth))
3731 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3732 (goto-char e)
3733 t)))
3735 (defvar org-latex-and-specials-regexp nil
3736 "Regular expression for highlighting export special stuff.")
3737 (defvar org-match-substring-regexp)
3738 (defvar org-match-substring-with-braces-regexp)
3739 (defvar org-export-html-special-string-regexps)
3741 (defun org-compute-latex-and-specials-regexp ()
3742 "Compute regular expression for stuff treated specially by exporters."
3743 (if (not org-highlight-latex-fragments-and-specials)
3744 (org-set-local 'org-latex-and-specials-regexp nil)
3745 (require 'org-exp)
3746 (let*
3747 ((matchers (plist-get org-format-latex-options :matchers))
3748 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3749 org-latex-regexps)))
3750 (options (org-combine-plists (org-default-export-plist)
3751 (org-infile-export-plist)))
3752 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3753 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3754 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3755 (org-export-html-expand (plist-get options :expand-quoted-html))
3756 (org-export-with-special-strings (plist-get options :special-strings))
3757 (re-sub
3758 (cond
3759 ((equal org-export-with-sub-superscripts '{})
3760 (list org-match-substring-with-braces-regexp))
3761 (org-export-with-sub-superscripts
3762 (list org-match-substring-regexp))
3763 (t nil)))
3764 (re-latex
3765 (if org-export-with-LaTeX-fragments
3766 (mapcar (lambda (x) (nth 1 x)) latexs)))
3767 (re-macros
3768 (if org-export-with-TeX-macros
3769 (list (concat "\\\\"
3770 (regexp-opt
3771 (append (mapcar 'car org-html-entities)
3772 (if (boundp 'org-latex-entities)
3773 org-latex-entities nil))
3774 'words))) ; FIXME
3776 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3777 (re-special (if org-export-with-special-strings
3778 (mapcar (lambda (x) (car x))
3779 org-export-html-special-string-regexps)))
3780 (re-rest
3781 (delq nil
3782 (list
3783 (if org-export-html-expand "@<[^>\n]+>")
3784 ))))
3785 (org-set-local
3786 'org-latex-and-specials-regexp
3787 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3788 re-rest) "\\|")))))
3790 (defun org-do-latex-and-special-faces (limit)
3791 "Run through the buffer and add overlays to links."
3792 (when org-latex-and-specials-regexp
3793 (let (rtn d)
3794 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3795 limit t))
3796 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3797 'face))
3798 '(org-code org-verbatim underline)))
3799 (progn
3800 (setq rtn t
3801 d (cond ((member (char-after (1+ (match-beginning 0)))
3802 '(?_ ?^)) 1)
3803 (t 0)))
3804 (font-lock-prepend-text-property
3805 (+ d (match-beginning 0)) (match-end 0)
3806 'face 'org-latex-and-export-specials)
3807 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3808 '(font-lock-multiline t)))))
3809 rtn)))
3811 (defun org-restart-font-lock ()
3812 "Restart font-lock-mode, to force refontification."
3813 (when (and (boundp 'font-lock-mode) font-lock-mode)
3814 (font-lock-mode -1)
3815 (font-lock-mode 1)))
3817 (defun org-all-targets (&optional radio)
3818 "Return a list of all targets in this file.
3819 With optional argument RADIO, only find radio targets."
3820 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3821 rtn)
3822 (save-excursion
3823 (goto-char (point-min))
3824 (while (re-search-forward re nil t)
3825 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3826 rtn)))
3828 (defun org-make-target-link-regexp (targets)
3829 "Make regular expression matching all strings in TARGETS.
3830 The regular expression finds the targets also if there is a line break
3831 between words."
3832 (and targets
3833 (concat
3834 "\\<\\("
3835 (mapconcat
3836 (lambda (x)
3837 (while (string-match " +" x)
3838 (setq x (replace-match "\\s-+" t t x)))
3840 targets
3841 "\\|")
3842 "\\)\\>")))
3844 (defun org-activate-tags (limit)
3845 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3846 (progn
3847 (add-text-properties (match-beginning 1) (match-end 1)
3848 (list 'mouse-face 'highlight
3849 'rear-nonsticky org-nonsticky-props
3850 'keymap org-mouse-map))
3851 t)))
3853 (defun org-outline-level ()
3854 (save-excursion
3855 (looking-at outline-regexp)
3856 (if (match-beginning 1)
3857 (+ (org-get-string-indentation (match-string 1)) 1000)
3858 (1- (- (match-end 0) (match-beginning 0))))))
3860 (defvar org-font-lock-keywords nil)
3862 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3863 "Regular expression matching a property line.")
3865 (defvar org-font-lock-hook nil
3866 "Functions to be called for special font lock stuff.")
3868 (defun org-font-lock-hook (limit)
3869 (run-hook-with-args 'org-font-lock-hook limit))
3871 (defun org-set-font-lock-defaults ()
3872 (let* ((em org-fontify-emphasized-text)
3873 (lk org-activate-links)
3874 (org-font-lock-extra-keywords
3875 (list
3876 ;; Call the hook
3877 '(org-font-lock-hook)
3878 ;; Headlines
3879 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3880 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3881 ;; Table lines
3882 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3883 (1 'org-table t))
3884 ;; Table internals
3885 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3886 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3887 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3888 ;; Drawers
3889 (list org-drawer-regexp '(0 'org-special-keyword t))
3890 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3891 ;; Properties
3892 (list org-property-re
3893 '(1 'org-special-keyword t)
3894 '(3 'org-property-value t))
3895 (if org-format-transports-properties-p
3896 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3897 ;; Links
3898 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3899 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3900 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3901 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3902 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3903 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3904 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3905 '(org-hide-wide-columns (0 nil append))
3906 ;; TODO lines
3907 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3908 '(1 (org-get-todo-face 1) t))
3909 ;; DONE
3910 (if org-fontify-done-headline
3911 (list (concat "^[*]+ +\\<\\("
3912 (mapconcat 'regexp-quote org-done-keywords "\\|")
3913 "\\)\\(.*\\)")
3914 '(2 'org-headline-done t))
3915 nil)
3916 ;; Priorities
3917 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3918 ;; Special keywords
3919 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3920 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3921 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3922 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3923 ;; Emphasis
3924 (if em
3925 (if (featurep 'xemacs)
3926 '(org-do-emphasis-faces (0 nil append))
3927 '(org-do-emphasis-faces)))
3928 ;; Checkboxes
3929 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3930 2 'bold prepend)
3931 (if org-provide-checkbox-statistics
3932 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3933 (0 (org-get-checkbox-statistics-face) t)))
3934 ;; Description list items
3935 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3936 2 'bold prepend)
3937 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3938 '(1 'org-archived prepend))
3939 ;; Specials
3940 '(org-do-latex-and-special-faces)
3941 ;; Code
3942 '(org-activate-code (1 'org-code t))
3943 ;; COMMENT
3944 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3945 "\\|" org-quote-string "\\)\\>")
3946 '(1 'org-special-keyword t))
3947 '("^#.*" (0 'font-lock-comment-face t))
3949 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3950 ;; Now set the full font-lock-keywords
3951 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3952 (org-set-local 'font-lock-defaults
3953 '(org-font-lock-keywords t nil nil backward-paragraph))
3954 (kill-local-variable 'font-lock-keywords) nil))
3956 (defvar org-m nil)
3957 (defvar org-l nil)
3958 (defvar org-f nil)
3959 (defun org-get-level-face (n)
3960 "Get the right face for match N in font-lock matching of healdines."
3961 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3962 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3963 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3964 (cond
3965 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3966 ((eq n 2) org-f)
3967 (t (if org-level-color-stars-only nil org-f))))
3969 (defun org-get-todo-face (kwd)
3970 "Get the right face for a TODO keyword KWD.
3971 If KWD is a number, get the corresponding match group."
3972 (if (numberp kwd) (setq kwd (match-string kwd)))
3973 (or (cdr (assoc kwd org-todo-keyword-faces))
3974 (and (member kwd org-done-keywords) 'org-done)
3975 'org-todo))
3977 (defun org-unfontify-region (beg end &optional maybe_loudly)
3978 "Remove fontification and activation overlays from links."
3979 (font-lock-default-unfontify-region beg end)
3980 (let* ((buffer-undo-list t)
3981 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3982 (inhibit-modification-hooks t)
3983 deactivate-mark buffer-file-name buffer-file-truename)
3984 (remove-text-properties beg end
3985 '(mouse-face t keymap t org-linked-text t
3986 invisible t intangible t))))
3988 ;;;; Visibility cycling, including org-goto and indirect buffer
3990 ;;; Cycling
3992 (defvar org-cycle-global-status nil)
3993 (make-variable-buffer-local 'org-cycle-global-status)
3994 (defvar org-cycle-subtree-status nil)
3995 (make-variable-buffer-local 'org-cycle-subtree-status)
3997 ;;;###autoload
3998 (defun org-cycle (&optional arg)
3999 "Visibility cycling for Org-mode.
4001 - When this function is called with a prefix argument, rotate the entire
4002 buffer through 3 states (global cycling)
4003 1. OVERVIEW: Show only top-level headlines.
4004 2. CONTENTS: Show all headlines of all levels, but no body text.
4005 3. SHOW ALL: Show everything.
4006 When called with two C-u C-u prefixes, switch to the startup visibility,
4007 determined by the variable `org-startup-folded', and by any VISIBILITY
4008 properties in the buffer.
4009 When called with three C-u C-u C-u prefixed, show the entire buffer,
4010 including drawers.
4012 - When point is at the beginning of a headline, rotate the subtree started
4013 by this line through 3 different states (local cycling)
4014 1. FOLDED: Only the main headline is shown.
4015 2. CHILDREN: The main headline and the direct children are shown.
4016 From this state, you can move to one of the children
4017 and zoom in further.
4018 3. SUBTREE: Show the entire subtree, including body text.
4020 - When there is a numeric prefix, go up to a heading with level ARG, do
4021 a `show-subtree' and return to the previous cursor position. If ARG
4022 is negative, go up that many levels.
4024 - When point is not at the beginning of a headline, execute the global
4025 binding for TAB, which is re-indenting the line. See the option
4026 `org-cycle-emulate-tab' for details.
4028 - Special case: if point is at the beginning of the buffer and there is
4029 no headline in line 1, this function will act as if called with prefix arg.
4030 But only if also the variable `org-cycle-global-at-bob' is t."
4031 (interactive "P")
4032 (org-load-modules-maybe)
4033 (let* ((outline-regexp
4034 (if (and (org-mode-p) org-cycle-include-plain-lists)
4035 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4036 outline-regexp))
4037 (bob-special (and org-cycle-global-at-bob (bobp)
4038 (not (looking-at outline-regexp))))
4039 (org-cycle-hook
4040 (if bob-special
4041 (delq 'org-optimize-window-after-visibility-change
4042 (copy-sequence org-cycle-hook))
4043 org-cycle-hook))
4044 (pos (point)))
4046 (if (or bob-special (equal arg '(4)))
4047 ;; special case: use global cycling
4048 (setq arg t))
4050 (cond
4052 ((equal arg '(16))
4053 (org-set-startup-visibility)
4054 (message "Startup visibility, plus VISIBILITY properties"))
4056 ((equal arg '(64))
4057 (show-all)
4058 (message "Entire buffer visible, including drawers"))
4060 ((org-at-table-p 'any)
4061 ;; Enter the table or move to the next field in the table
4062 (or (org-table-recognize-table.el)
4063 (progn
4064 (if arg (org-table-edit-field t)
4065 (org-table-justify-field-maybe)
4066 (call-interactively 'org-table-next-field)))))
4068 ((eq arg t) ;; Global cycling
4070 (cond
4071 ((and (eq last-command this-command)
4072 (eq org-cycle-global-status 'overview))
4073 ;; We just created the overview - now do table of contents
4074 ;; This can be slow in very large buffers, so indicate action
4075 (message "CONTENTS...")
4076 (org-content)
4077 (message "CONTENTS...done")
4078 (setq org-cycle-global-status 'contents)
4079 (run-hook-with-args 'org-cycle-hook 'contents))
4081 ((and (eq last-command this-command)
4082 (eq org-cycle-global-status 'contents))
4083 ;; We just showed the table of contents - now show everything
4084 (show-all)
4085 (message "SHOW ALL")
4086 (setq org-cycle-global-status 'all)
4087 (run-hook-with-args 'org-cycle-hook 'all))
4090 ;; Default action: go to overview
4091 (org-overview)
4092 (message "OVERVIEW")
4093 (setq org-cycle-global-status 'overview)
4094 (run-hook-with-args 'org-cycle-hook 'overview))))
4096 ((and org-drawers org-drawer-regexp
4097 (save-excursion
4098 (beginning-of-line 1)
4099 (looking-at org-drawer-regexp)))
4100 ;; Toggle block visibility
4101 (org-flag-drawer
4102 (not (get-char-property (match-end 0) 'invisible))))
4104 ((integerp arg)
4105 ;; Show-subtree, ARG levels up from here.
4106 (save-excursion
4107 (org-back-to-heading)
4108 (outline-up-heading (if (< arg 0) (- arg)
4109 (- (funcall outline-level) arg)))
4110 (org-show-subtree)))
4112 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4113 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4114 ;; At a heading: rotate between three different views
4115 (org-back-to-heading)
4116 (let ((goal-column 0) eoh eol eos)
4117 ;; First, some boundaries
4118 (save-excursion
4119 (org-back-to-heading)
4120 (save-excursion
4121 (beginning-of-line 2)
4122 (while (and (not (eobp)) ;; this is like `next-line'
4123 (get-char-property (1- (point)) 'invisible))
4124 (beginning-of-line 2)) (setq eol (point)))
4125 (outline-end-of-heading) (setq eoh (point))
4126 (org-end-of-subtree t)
4127 (unless (eobp)
4128 (skip-chars-forward " \t\n")
4129 (beginning-of-line 1) ; in case this is an item
4131 (setq eos (1- (point))))
4132 ;; Find out what to do next and set `this-command'
4133 (cond
4134 ((= eos eoh)
4135 ;; Nothing is hidden behind this heading
4136 (message "EMPTY ENTRY")
4137 (setq org-cycle-subtree-status nil)
4138 (save-excursion
4139 (goto-char eos)
4140 (outline-next-heading)
4141 (if (org-invisible-p) (org-flag-heading nil))))
4142 ((or (>= eol eos)
4143 (not (string-match "\\S-" (buffer-substring eol eos))))
4144 ;; Entire subtree is hidden in one line: open it
4145 (org-show-entry)
4146 (show-children)
4147 (message "CHILDREN")
4148 (save-excursion
4149 (goto-char eos)
4150 (outline-next-heading)
4151 (if (org-invisible-p) (org-flag-heading nil)))
4152 (setq org-cycle-subtree-status 'children)
4153 (run-hook-with-args 'org-cycle-hook 'children))
4154 ((and (eq last-command this-command)
4155 (eq org-cycle-subtree-status 'children))
4156 ;; We just showed the children, now show everything.
4157 (org-show-subtree)
4158 (message "SUBTREE")
4159 (setq org-cycle-subtree-status 'subtree)
4160 (run-hook-with-args 'org-cycle-hook 'subtree))
4162 ;; Default action: hide the subtree.
4163 (hide-subtree)
4164 (message "FOLDED")
4165 (setq org-cycle-subtree-status 'folded)
4166 (run-hook-with-args 'org-cycle-hook 'folded)))))
4168 ;; TAB emulation and template completion
4169 (buffer-read-only (org-back-to-heading))
4171 ((org-try-structure-completion))
4173 ((org-try-cdlatex-tab))
4175 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4176 (or (not (bolp))
4177 (not (looking-at outline-regexp))))
4178 (call-interactively (global-key-binding "\t")))
4180 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4181 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4182 (or (and (eq org-cycle-emulate-tab 'white)
4183 (= (match-end 0) (point-at-eol)))
4184 (and (eq org-cycle-emulate-tab 'whitestart)
4185 (>= (match-end 0) pos))))
4187 (eq org-cycle-emulate-tab t))
4188 (call-interactively (global-key-binding "\t")))
4190 (t (save-excursion
4191 (org-back-to-heading)
4192 (org-cycle))))))
4194 ;;;###autoload
4195 (defun org-global-cycle (&optional arg)
4196 "Cycle the global visibility. For details see `org-cycle'.
4197 With C-u prefix arg, switch to startup visibility.
4198 With a numeric prefix, show all headlines up to that level."
4199 (interactive "P")
4200 (let ((org-cycle-include-plain-lists
4201 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4202 (cond
4203 ((integerp arg)
4204 (show-all)
4205 (hide-sublevels arg)
4206 (setq org-cycle-global-status 'contents))
4207 ((equal arg '(4))
4208 (org-set-startup-visibility)
4209 (message "Startup visibility, plus VISIBILITY properties."))
4211 (org-cycle '(4))))))
4213 (defun org-set-startup-visibility ()
4214 "Set the visibility required by startup options and properties."
4215 (cond
4216 ((eq org-startup-folded t)
4217 (org-cycle '(4)))
4218 ((eq org-startup-folded 'content)
4219 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4220 (org-cycle '(4)) (org-cycle '(4)))))
4221 (org-set-visibility-according-to-property 'no-cleanup)
4222 (org-cycle-hide-archived-subtrees 'all)
4223 (org-cycle-hide-drawers 'all)
4224 (org-cycle-show-empty-lines 'all))
4226 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4227 "Switch subtree visibilities according to :VISIBILITY: property."
4228 (interactive)
4229 (let (state)
4230 (save-excursion
4231 (goto-char (point-min))
4232 (while (re-search-forward
4233 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4234 nil t)
4235 (setq state (match-string 1))
4236 (save-excursion
4237 (org-back-to-heading t)
4238 (hide-subtree)
4239 (org-reveal)
4240 (cond
4241 ((equal state '("fold" "folded"))
4242 (hide-subtree))
4243 ((equal state "children")
4244 (org-show-hidden-entry)
4245 (show-children))
4246 ((equal state "content")
4247 (save-excursion
4248 (save-restriction
4249 (org-narrow-to-subtree)
4250 (org-content))))
4251 ((member state '("all" "showall"))
4252 (show-subtree)))))
4253 (unless no-cleanup
4254 (org-cycle-hide-archived-subtrees 'all)
4255 (org-cycle-hide-drawers 'all)
4256 (org-cycle-show-empty-lines 'all)))))
4258 (defun org-overview ()
4259 "Switch to overview mode, shoing only top-level headlines.
4260 Really, this shows all headlines with level equal or greater than the level
4261 of the first headline in the buffer. This is important, because if the
4262 first headline is not level one, then (hide-sublevels 1) gives confusing
4263 results."
4264 (interactive)
4265 (let ((level (save-excursion
4266 (goto-char (point-min))
4267 (if (re-search-forward (concat "^" outline-regexp) nil t)
4268 (progn
4269 (goto-char (match-beginning 0))
4270 (funcall outline-level))))))
4271 (and level (hide-sublevels level))))
4273 (defun org-content (&optional arg)
4274 "Show all headlines in the buffer, like a table of contents.
4275 With numerical argument N, show content up to level N."
4276 (interactive "P")
4277 (save-excursion
4278 ;; Visit all headings and show their offspring
4279 (and (integerp arg) (org-overview))
4280 (goto-char (point-max))
4281 (catch 'exit
4282 (while (and (progn (condition-case nil
4283 (outline-previous-visible-heading 1)
4284 (error (goto-char (point-min))))
4286 (looking-at outline-regexp))
4287 (if (integerp arg)
4288 (show-children (1- arg))
4289 (show-branches))
4290 (if (bobp) (throw 'exit nil))))))
4293 (defun org-optimize-window-after-visibility-change (state)
4294 "Adjust the window after a change in outline visibility.
4295 This function is the default value of the hook `org-cycle-hook'."
4296 (when (get-buffer-window (current-buffer))
4297 (cond
4298 ; ((eq state 'overview) (org-first-headline-recenter 1))
4299 ; ((eq state 'overview) (org-beginning-of-line))
4300 ((eq state 'content) nil)
4301 ((eq state 'all) nil)
4302 ((eq state 'folded) nil)
4303 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4304 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4306 (defun org-compact-display-after-subtree-move ()
4307 (let (beg end)
4308 (save-excursion
4309 (if (org-up-heading-safe)
4310 (progn
4311 (hide-subtree)
4312 (show-entry)
4313 (show-children)
4314 (org-cycle-show-empty-lines 'children)
4315 (org-cycle-hide-drawers 'children))
4316 (org-overview)))))
4318 (defun org-cycle-show-empty-lines (state)
4319 "Show empty lines above all visible headlines.
4320 The region to be covered depends on STATE when called through
4321 `org-cycle-hook'. Lisp program can use t for STATE to get the
4322 entire buffer covered. Note that an empty line is only shown if there
4323 are at least `org-cycle-separator-lines' empty lines before the headeline."
4324 (when (> org-cycle-separator-lines 0)
4325 (save-excursion
4326 (let* ((n org-cycle-separator-lines)
4327 (re (cond
4328 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4329 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4330 (t (let ((ns (number-to-string (- n 2))))
4331 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4332 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4333 beg end)
4334 (cond
4335 ((memq state '(overview contents t))
4336 (setq beg (point-min) end (point-max)))
4337 ((memq state '(children folded))
4338 (setq beg (point) end (progn (org-end-of-subtree t t)
4339 (beginning-of-line 2)
4340 (point)))))
4341 (when beg
4342 (goto-char beg)
4343 (while (re-search-forward re end t)
4344 (if (not (get-char-property (match-end 1) 'invisible))
4345 (outline-flag-region
4346 (match-beginning 1) (match-end 1) nil)))))))
4347 ;; Never hide empty lines at the end of the file.
4348 (save-excursion
4349 (goto-char (point-max))
4350 (outline-previous-heading)
4351 (outline-end-of-heading)
4352 (if (and (looking-at "[ \t\n]+")
4353 (= (match-end 0) (point-max)))
4354 (outline-flag-region (point) (match-end 0) nil))))
4356 (defun org-show-empty-lines-in-parent ()
4357 "Move to the parent and re-show empty lines before visible headlines."
4358 (save-excursion
4359 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4360 (org-cycle-show-empty-lines context))))
4362 (defun org-cycle-hide-drawers (state)
4363 "Re-hide all drawers after a visibility state change."
4364 (when (and (org-mode-p)
4365 (not (memq state '(overview folded))))
4366 (save-excursion
4367 (let* ((globalp (memq state '(contents all)))
4368 (beg (if globalp (point-min) (point)))
4369 (end (if globalp (point-max) (org-end-of-subtree t))))
4370 (goto-char beg)
4371 (while (re-search-forward org-drawer-regexp end t)
4372 (org-flag-drawer t))))))
4374 (defun org-flag-drawer (flag)
4375 (save-excursion
4376 (beginning-of-line 1)
4377 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4378 (let ((b (match-end 0))
4379 (outline-regexp org-outline-regexp))
4380 (if (re-search-forward
4381 "^[ \t]*:END:"
4382 (save-excursion (outline-next-heading) (point)) t)
4383 (outline-flag-region b (point-at-eol) flag)
4384 (error ":END: line missing"))))))
4386 (defun org-subtree-end-visible-p ()
4387 "Is the end of the current subtree visible?"
4388 (pos-visible-in-window-p
4389 (save-excursion (org-end-of-subtree t) (point))))
4391 (defun org-first-headline-recenter (&optional N)
4392 "Move cursor to the first headline and recenter the headline.
4393 Optional argument N means, put the headline into the Nth line of the window."
4394 (goto-char (point-min))
4395 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4396 (beginning-of-line)
4397 (recenter (prefix-numeric-value N))))
4399 ;;; Org-goto
4401 (defvar org-goto-window-configuration nil)
4402 (defvar org-goto-marker nil)
4403 (defvar org-goto-map
4404 (let ((map (make-sparse-keymap)))
4405 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4406 (while (setq cmd (pop cmds))
4407 (substitute-key-definition cmd cmd map global-map)))
4408 (suppress-keymap map)
4409 (org-defkey map "\C-m" 'org-goto-ret)
4410 (org-defkey map [(return)] 'org-goto-ret)
4411 (org-defkey map [(left)] 'org-goto-left)
4412 (org-defkey map [(right)] 'org-goto-right)
4413 (org-defkey map [(control ?g)] 'org-goto-quit)
4414 (org-defkey map "\C-i" 'org-cycle)
4415 (org-defkey map [(tab)] 'org-cycle)
4416 (org-defkey map [(down)] 'outline-next-visible-heading)
4417 (org-defkey map [(up)] 'outline-previous-visible-heading)
4418 (if org-goto-auto-isearch
4419 (if (fboundp 'define-key-after)
4420 (define-key-after map [t] 'org-goto-local-auto-isearch)
4421 nil)
4422 (org-defkey map "q" 'org-goto-quit)
4423 (org-defkey map "n" 'outline-next-visible-heading)
4424 (org-defkey map "p" 'outline-previous-visible-heading)
4425 (org-defkey map "f" 'outline-forward-same-level)
4426 (org-defkey map "b" 'outline-backward-same-level)
4427 (org-defkey map "u" 'outline-up-heading))
4428 (org-defkey map "/" 'org-occur)
4429 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4430 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4431 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4432 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4433 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4434 map))
4436 (defconst org-goto-help
4437 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4438 RET=jump to location [Q]uit and return to previous location
4439 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4441 (defvar org-goto-start-pos) ; dynamically scoped parameter
4443 ;; FIXME: Docstring doe not mention both interfaces
4444 (defun org-goto (&optional alternative-interface)
4445 "Look up a different location in the current file, keeping current visibility.
4447 When you want look-up or go to a different location in a document, the
4448 fastest way is often to fold the entire buffer and then dive into the tree.
4449 This method has the disadvantage, that the previous location will be folded,
4450 which may not be what you want.
4452 This command works around this by showing a copy of the current buffer
4453 in an indirect buffer, in overview mode. You can dive into the tree in
4454 that copy, use org-occur and incremental search to find a location.
4455 When pressing RET or `Q', the command returns to the original buffer in
4456 which the visibility is still unchanged. After RET is will also jump to
4457 the location selected in the indirect buffer and expose the
4458 the headline hierarchy above."
4459 (interactive "P")
4460 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4461 (org-refile-use-outline-path t)
4462 (interface
4463 (if (not alternative-interface)
4464 org-goto-interface
4465 (if (eq org-goto-interface 'outline)
4466 'outline-path-completion
4467 'outline)))
4468 (org-goto-start-pos (point))
4469 (selected-point
4470 (if (eq interface 'outline)
4471 (car (org-get-location (current-buffer) org-goto-help))
4472 (nth 3 (org-refile-get-location "Goto: ")))))
4473 (if selected-point
4474 (progn
4475 (org-mark-ring-push org-goto-start-pos)
4476 (goto-char selected-point)
4477 (if (or (org-invisible-p) (org-invisible-p2))
4478 (org-show-context 'org-goto)))
4479 (message "Quit"))))
4481 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4482 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4483 (defvar org-goto-local-auto-isearch-map) ; defined below
4485 (defun org-get-location (buf help)
4486 "Let the user select a location in the Org-mode buffer BUF.
4487 This function uses a recursive edit. It returns the selected position
4488 or nil."
4489 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4490 (isearch-hide-immediately nil)
4491 (isearch-search-fun-function
4492 (lambda () 'org-goto-local-search-headings))
4493 (org-goto-selected-point org-goto-exit-command))
4494 (save-excursion
4495 (save-window-excursion
4496 (delete-other-windows)
4497 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4498 (switch-to-buffer
4499 (condition-case nil
4500 (make-indirect-buffer (current-buffer) "*org-goto*")
4501 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4502 (with-output-to-temp-buffer "*Help*"
4503 (princ help))
4504 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4505 (setq buffer-read-only nil)
4506 (let ((org-startup-truncated t)
4507 (org-startup-folded nil)
4508 (org-startup-align-all-tables nil))
4509 (org-mode)
4510 (org-overview))
4511 (setq buffer-read-only t)
4512 (if (and (boundp 'org-goto-start-pos)
4513 (integer-or-marker-p org-goto-start-pos))
4514 (let ((org-show-hierarchy-above t)
4515 (org-show-siblings t)
4516 (org-show-following-heading t))
4517 (goto-char org-goto-start-pos)
4518 (and (org-invisible-p) (org-show-context)))
4519 (goto-char (point-min)))
4520 (org-beginning-of-line)
4521 (message "Select location and press RET")
4522 (use-local-map org-goto-map)
4523 (recursive-edit)
4525 (kill-buffer "*org-goto*")
4526 (cons org-goto-selected-point org-goto-exit-command)))
4528 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4529 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4530 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4531 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4533 (defun org-goto-local-search-headings (string bound noerror)
4534 "Search and make sure that any matches are in headlines."
4535 (catch 'return
4536 (while (if isearch-forward
4537 (search-forward string bound noerror)
4538 (search-backward string bound noerror))
4539 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4540 (and (member :headline context)
4541 (not (member :tags context))))
4542 (throw 'return (point))))))
4544 (defun org-goto-local-auto-isearch ()
4545 "Start isearch."
4546 (interactive)
4547 (goto-char (point-min))
4548 (let ((keys (this-command-keys)))
4549 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4550 (isearch-mode t)
4551 (isearch-process-search-char (string-to-char keys)))))
4553 (defun org-goto-ret (&optional arg)
4554 "Finish `org-goto' by going to the new location."
4555 (interactive "P")
4556 (setq org-goto-selected-point (point)
4557 org-goto-exit-command 'return)
4558 (throw 'exit nil))
4560 (defun org-goto-left ()
4561 "Finish `org-goto' by going to the new location."
4562 (interactive)
4563 (if (org-on-heading-p)
4564 (progn
4565 (beginning-of-line 1)
4566 (setq org-goto-selected-point (point)
4567 org-goto-exit-command 'left)
4568 (throw 'exit nil))
4569 (error "Not on a heading")))
4571 (defun org-goto-right ()
4572 "Finish `org-goto' by going to the new location."
4573 (interactive)
4574 (if (org-on-heading-p)
4575 (progn
4576 (setq org-goto-selected-point (point)
4577 org-goto-exit-command 'right)
4578 (throw 'exit nil))
4579 (error "Not on a heading")))
4581 (defun org-goto-quit ()
4582 "Finish `org-goto' without cursor motion."
4583 (interactive)
4584 (setq org-goto-selected-point nil)
4585 (setq org-goto-exit-command 'quit)
4586 (throw 'exit nil))
4588 ;;; Indirect buffer display of subtrees
4590 (defvar org-indirect-dedicated-frame nil
4591 "This is the frame being used for indirect tree display.")
4592 (defvar org-last-indirect-buffer nil)
4594 (defun org-tree-to-indirect-buffer (&optional arg)
4595 "Create indirect buffer and narrow it to current subtree.
4596 With numerical prefix ARG, go up to this level and then take that tree.
4597 If ARG is negative, go up that many levels.
4598 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4599 indirect buffer previously made with this command, to avoid proliferation of
4600 indirect buffers. However, when you call the command with a `C-u' prefix, or
4601 when `org-indirect-buffer-display' is `new-frame', the last buffer
4602 is kept so that you can work with several indirect buffers at the same time.
4603 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4604 requests that a new frame be made for the new buffer, so that the dedicated
4605 frame is not changed."
4606 (interactive "P")
4607 (let ((cbuf (current-buffer))
4608 (cwin (selected-window))
4609 (pos (point))
4610 beg end level heading ibuf)
4611 (save-excursion
4612 (org-back-to-heading t)
4613 (when (numberp arg)
4614 (setq level (org-outline-level))
4615 (if (< arg 0) (setq arg (+ level arg)))
4616 (while (> (setq level (org-outline-level)) arg)
4617 (outline-up-heading 1 t)))
4618 (setq beg (point)
4619 heading (org-get-heading))
4620 (org-end-of-subtree t) (setq end (point)))
4621 (if (and (buffer-live-p org-last-indirect-buffer)
4622 (not (eq org-indirect-buffer-display 'new-frame))
4623 (not arg))
4624 (kill-buffer org-last-indirect-buffer))
4625 (setq ibuf (org-get-indirect-buffer cbuf)
4626 org-last-indirect-buffer ibuf)
4627 (cond
4628 ((or (eq org-indirect-buffer-display 'new-frame)
4629 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4630 (select-frame (make-frame))
4631 (delete-other-windows)
4632 (switch-to-buffer ibuf)
4633 (org-set-frame-title heading))
4634 ((eq org-indirect-buffer-display 'dedicated-frame)
4635 (raise-frame
4636 (select-frame (or (and org-indirect-dedicated-frame
4637 (frame-live-p org-indirect-dedicated-frame)
4638 org-indirect-dedicated-frame)
4639 (setq org-indirect-dedicated-frame (make-frame)))))
4640 (delete-other-windows)
4641 (switch-to-buffer ibuf)
4642 (org-set-frame-title (concat "Indirect: " heading)))
4643 ((eq org-indirect-buffer-display 'current-window)
4644 (switch-to-buffer ibuf))
4645 ((eq org-indirect-buffer-display 'other-window)
4646 (pop-to-buffer ibuf))
4647 (t (error "Invalid value.")))
4648 (if (featurep 'xemacs)
4649 (save-excursion (org-mode) (turn-on-font-lock)))
4650 (narrow-to-region beg end)
4651 (show-all)
4652 (goto-char pos)
4653 (and (window-live-p cwin) (select-window cwin))))
4655 (defun org-get-indirect-buffer (&optional buffer)
4656 (setq buffer (or buffer (current-buffer)))
4657 (let ((n 1) (base (buffer-name buffer)) bname)
4658 (while (buffer-live-p
4659 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4660 (setq n (1+ n)))
4661 (condition-case nil
4662 (make-indirect-buffer buffer bname 'clone)
4663 (error (make-indirect-buffer buffer bname)))))
4665 (defun org-set-frame-title (title)
4666 "Set the title of the current frame to the string TITLE."
4667 ;; FIXME: how to name a single frame in XEmacs???
4668 (unless (featurep 'xemacs)
4669 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4671 ;;;; Structure editing
4673 ;;; Inserting headlines
4675 (defun org-insert-heading (&optional force-heading)
4676 "Insert a new heading or item with same depth at point.
4677 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4678 If point is at the beginning of a headline, insert a sibling before the
4679 current headline. If point is not at the beginning, do not split the line,
4680 but create the new headline after the current line."
4681 (interactive "P")
4682 (if (= (buffer-size) 0)
4683 (insert "\n* ")
4684 (when (or force-heading (not (org-insert-item)))
4685 (let* ((head (save-excursion
4686 (condition-case nil
4687 (progn
4688 (org-back-to-heading)
4689 (match-string 0))
4690 (error "*"))))
4691 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4692 pos hide-previous previous-pos)
4693 (cond
4694 ((and (org-on-heading-p) (bolp)
4695 (or (bobp)
4696 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4697 ;; insert before the current line
4698 (open-line (if blank 2 1)))
4699 ((and (bolp)
4700 (or (bobp)
4701 (save-excursion
4702 (backward-char 1) (not (org-invisible-p)))))
4703 ;; insert right here
4704 nil)
4706 ;; somewhere in the line
4707 (save-excursion
4708 (setq previous-pos (point-at-bol))
4709 (end-of-line)
4710 (setq hide-previous (org-invisible-p)))
4711 (and org-insert-heading-respect-content (org-show-subtree))
4712 (let ((split
4713 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4714 (save-excursion
4715 (let ((p (point)))
4716 (goto-char (point-at-bol))
4717 (and (looking-at org-complex-heading-regexp)
4718 (> p (match-beginning 4)))))))
4719 tags pos)
4720 (cond
4721 (org-insert-heading-respect-content
4722 (org-end-of-subtree nil t)
4723 (or (bolp) (newline))
4724 (open-line 1))
4725 ((org-on-heading-p)
4726 (when hide-previous
4727 (show-children)
4728 (org-show-entry))
4729 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4730 (setq tags (and (match-end 2) (match-string 2)))
4731 (and (match-end 1)
4732 (delete-region (match-beginning 1) (match-end 1)))
4733 (setq pos (point-at-bol))
4734 (or split (end-of-line 1))
4735 (delete-horizontal-space)
4736 (newline (if blank 2 1))
4737 (when tags
4738 (save-excursion
4739 (goto-char pos)
4740 (end-of-line 1)
4741 (insert " " tags)
4742 (org-set-tags nil 'align))))
4744 (or split (end-of-line 1))
4745 (newline (if blank 2 1)))))))
4746 (insert head) (just-one-space)
4747 (setq pos (point))
4748 (end-of-line 1)
4749 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4750 (when (and org-insert-heading-respect-content hide-previous)
4751 (save-excursion
4752 (goto-char previous-pos)
4753 (hide-subtree)))
4754 (run-hooks 'org-insert-heading-hook)))))
4756 (defun org-get-heading (&optional no-tags)
4757 "Return the heading of the current entry, without the stars."
4758 (save-excursion
4759 (org-back-to-heading t)
4760 (if (looking-at
4761 (if no-tags
4762 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4763 "\\*+[ \t]+\\([^\r\n]*\\)"))
4764 (match-string 1) "")))
4766 (defun org-insert-heading-after-current ()
4767 "Insert a new heading with same level as current, after current subtree."
4768 (interactive)
4769 (org-back-to-heading)
4770 (org-insert-heading)
4771 (org-move-subtree-down)
4772 (end-of-line 1))
4774 (defun org-insert-heading-respect-content ()
4775 (interactive)
4776 (let ((org-insert-heading-respect-content t))
4777 (org-insert-heading t)))
4779 (defun org-insert-todo-heading-respect-content (&optional force-state)
4780 (interactive "P")
4781 (let ((org-insert-heading-respect-content t))
4782 (org-insert-todo-heading force-state t)))
4784 (defun org-insert-todo-heading (arg &optional force-heading)
4785 "Insert a new heading with the same level and TODO state as current heading.
4786 If the heading has no TODO state, or if the state is DONE, use the first
4787 state (TODO by default). Also with prefix arg, force first state."
4788 (interactive "P")
4789 (when (or force-heading (not (org-insert-item 'checkbox)))
4790 (org-insert-heading force-heading)
4791 (save-excursion
4792 (org-back-to-heading)
4793 (outline-previous-heading)
4794 (looking-at org-todo-line-regexp))
4795 (if (or arg
4796 (not (match-beginning 2))
4797 (member (match-string 2) org-done-keywords))
4798 (insert (car org-todo-keywords-1) " ")
4799 (insert (match-string 2) " "))
4800 (when org-provide-todo-statistics
4801 (org-update-parent-todo-statistics))))
4803 (defun org-insert-subheading (arg)
4804 "Insert a new subheading and demote it.
4805 Works for outline headings and for plain lists alike."
4806 (interactive "P")
4807 (org-insert-heading arg)
4808 (cond
4809 ((org-on-heading-p) (org-do-demote))
4810 ((org-at-item-p) (org-indent-item 1))))
4812 (defun org-insert-todo-subheading (arg)
4813 "Insert a new subheading with TODO keyword or checkbox and demote it.
4814 Works for outline headings and for plain lists alike."
4815 (interactive "P")
4816 (org-insert-todo-heading arg)
4817 (cond
4818 ((org-on-heading-p) (org-do-demote))
4819 ((org-at-item-p) (org-indent-item 1))))
4821 ;;; Promotion and Demotion
4823 (defun org-promote-subtree ()
4824 "Promote the entire subtree.
4825 See also `org-promote'."
4826 (interactive)
4827 (save-excursion
4828 (org-map-tree 'org-promote))
4829 (org-fix-position-after-promote))
4831 (defun org-demote-subtree ()
4832 "Demote the entire subtree. See `org-demote'.
4833 See also `org-promote'."
4834 (interactive)
4835 (save-excursion
4836 (org-map-tree 'org-demote))
4837 (org-fix-position-after-promote))
4840 (defun org-do-promote ()
4841 "Promote the current heading higher up the tree.
4842 If the region is active in `transient-mark-mode', promote all headings
4843 in the region."
4844 (interactive)
4845 (save-excursion
4846 (if (org-region-active-p)
4847 (org-map-region 'org-promote (region-beginning) (region-end))
4848 (org-promote)))
4849 (org-fix-position-after-promote))
4851 (defun org-do-demote ()
4852 "Demote the current heading lower down the tree.
4853 If the region is active in `transient-mark-mode', demote all headings
4854 in the region."
4855 (interactive)
4856 (save-excursion
4857 (if (org-region-active-p)
4858 (org-map-region 'org-demote (region-beginning) (region-end))
4859 (org-demote)))
4860 (org-fix-position-after-promote))
4862 (defun org-fix-position-after-promote ()
4863 "Make sure that after pro/demotion cursor position is right."
4864 (let ((pos (point)))
4865 (when (save-excursion
4866 (beginning-of-line 1)
4867 (looking-at org-todo-line-regexp)
4868 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4869 (cond ((eobp) (insert " "))
4870 ((eolp) (insert " "))
4871 ((equal (char-after) ?\ ) (forward-char 1))))))
4873 (defun org-reduced-level (l)
4874 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4876 (defun org-get-valid-level (level &optional change)
4877 "Rectify a level change under the influence of `org-odd-levels-only'
4878 LEVEL is a current level, CHANGE is by how much the level should be
4879 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4880 even level numbers will become the next higher odd number."
4881 (if org-odd-levels-only
4882 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4883 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4884 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4885 (max 1 (+ level change))))
4887 (if (boundp 'define-obsolete-function-alias)
4888 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4889 (define-obsolete-function-alias 'org-get-legal-level
4890 'org-get-valid-level)
4891 (define-obsolete-function-alias 'org-get-legal-level
4892 'org-get-valid-level "23.1")))
4894 (defun org-promote ()
4895 "Promote the current heading higher up the tree.
4896 If the region is active in `transient-mark-mode', promote all headings
4897 in the region."
4898 (org-back-to-heading t)
4899 (let* ((level (save-match-data (funcall outline-level)))
4900 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4901 (diff (abs (- level (length up-head) -1))))
4902 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4903 (replace-match up-head nil t)
4904 ;; Fixup tag positioning
4905 (and org-auto-align-tags (org-set-tags nil t))
4906 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4908 (defun org-demote ()
4909 "Demote the current heading lower down the tree.
4910 If the region is active in `transient-mark-mode', demote all headings
4911 in the region."
4912 (org-back-to-heading t)
4913 (let* ((level (save-match-data (funcall outline-level)))
4914 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4915 (diff (abs (- level (length down-head) -1))))
4916 (replace-match down-head nil t)
4917 ;; Fixup tag positioning
4918 (and org-auto-align-tags (org-set-tags nil t))
4919 (if org-adapt-indentation (org-fixup-indentation diff))))
4921 (defun org-map-tree (fun)
4922 "Call FUN for every heading underneath the current one."
4923 (org-back-to-heading)
4924 (let ((level (funcall outline-level)))
4925 (save-excursion
4926 (funcall fun)
4927 (while (and (progn
4928 (outline-next-heading)
4929 (> (funcall outline-level) level))
4930 (not (eobp)))
4931 (funcall fun)))))
4933 (defun org-map-region (fun beg end)
4934 "Call FUN for every heading between BEG and END."
4935 (let ((org-ignore-region t))
4936 (save-excursion
4937 (setq end (copy-marker end))
4938 (goto-char beg)
4939 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4940 (< (point) end))
4941 (funcall fun))
4942 (while (and (progn
4943 (outline-next-heading)
4944 (< (point) end))
4945 (not (eobp)))
4946 (funcall fun)))))
4948 (defun org-fixup-indentation (diff)
4949 "Change the indentation in the current entry by DIFF
4950 However, if any line in the current entry has no indentation, or if it
4951 would end up with no indentation after the change, nothing at all is done."
4952 (save-excursion
4953 (let ((end (save-excursion (outline-next-heading)
4954 (point-marker)))
4955 (prohibit (if (> diff 0)
4956 "^\\S-"
4957 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4958 col)
4959 (unless (save-excursion (end-of-line 1)
4960 (re-search-forward prohibit end t))
4961 (while (and (< (point) end)
4962 (re-search-forward "^[ \t]+" end t))
4963 (goto-char (match-end 0))
4964 (setq col (current-column))
4965 (if (< diff 0) (replace-match ""))
4966 (org-indent-to-column (+ diff col))))
4967 (move-marker end nil))))
4969 (defun org-convert-to-odd-levels ()
4970 "Convert an org-mode file with all levels allowed to one with odd levels.
4971 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4972 level 5 etc."
4973 (interactive)
4974 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4975 (let ((org-odd-levels-only nil) n)
4976 (save-excursion
4977 (goto-char (point-min))
4978 (while (re-search-forward "^\\*\\*+ " nil t)
4979 (setq n (- (length (match-string 0)) 2))
4980 (while (>= (setq n (1- n)) 0)
4981 (org-demote))
4982 (end-of-line 1))))))
4985 (defun org-convert-to-oddeven-levels ()
4986 "Convert an org-mode file with only odd levels to one with odd and even levels.
4987 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4988 section with an even level, conversion would destroy the structure of the file. An error
4989 is signaled in this case."
4990 (interactive)
4991 (goto-char (point-min))
4992 ;; First check if there are no even levels
4993 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4994 (org-show-context t)
4995 (error "Not all levels are odd in this file. Conversion not possible."))
4996 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4997 (let ((org-odd-levels-only nil) n)
4998 (save-excursion
4999 (goto-char (point-min))
5000 (while (re-search-forward "^\\*\\*+ " nil t)
5001 (setq n (/ (1- (length (match-string 0))) 2))
5002 (while (>= (setq n (1- n)) 0)
5003 (org-promote))
5004 (end-of-line 1))))))
5006 (defun org-tr-level (n)
5007 "Make N odd if required."
5008 (if org-odd-levels-only (1+ (/ n 2)) n))
5010 ;;; Vertical tree motion, cutting and pasting of subtrees
5012 (defun org-move-subtree-up (&optional arg)
5013 "Move the current subtree up past ARG headlines of the same level."
5014 (interactive "p")
5015 (org-move-subtree-down (- (prefix-numeric-value arg))))
5017 (defun org-move-subtree-down (&optional arg)
5018 "Move the current subtree down past ARG headlines of the same level."
5019 (interactive "p")
5020 (setq arg (prefix-numeric-value arg))
5021 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5022 'outline-get-last-sibling))
5023 (ins-point (make-marker))
5024 (cnt (abs arg))
5025 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5026 ;; Select the tree
5027 (org-back-to-heading)
5028 (setq beg0 (point))
5029 (save-excursion
5030 (setq ne-beg (org-back-over-empty-lines))
5031 (setq beg (point)))
5032 (save-match-data
5033 (save-excursion (outline-end-of-heading)
5034 (setq folded (org-invisible-p)))
5035 (outline-end-of-subtree))
5036 (outline-next-heading)
5037 (setq ne-end (org-back-over-empty-lines))
5038 (setq end (point))
5039 (goto-char beg0)
5040 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5041 ;; include less whitespace
5042 (save-excursion
5043 (goto-char beg)
5044 (forward-line (- ne-beg ne-end))
5045 (setq beg (point))))
5046 ;; Find insertion point, with error handling
5047 (while (> cnt 0)
5048 (or (and (funcall movfunc) (looking-at outline-regexp))
5049 (progn (goto-char beg0)
5050 (error "Cannot move past superior level or buffer limit")))
5051 (setq cnt (1- cnt)))
5052 (if (> arg 0)
5053 ;; Moving forward - still need to move over subtree
5054 (progn (org-end-of-subtree t t)
5055 (save-excursion
5056 (org-back-over-empty-lines)
5057 (or (bolp) (newline)))))
5058 (setq ne-ins (org-back-over-empty-lines))
5059 (move-marker ins-point (point))
5060 (setq txt (buffer-substring beg end))
5061 (org-save-markers-in-region beg end)
5062 (delete-region beg end)
5063 (outline-flag-region (1- beg) beg nil)
5064 (outline-flag-region (1- (point)) (point) nil)
5065 (let ((bbb (point)))
5066 (insert-before-markers txt)
5067 (org-reinstall-markers-in-region bbb)
5068 (move-marker ins-point bbb))
5069 (or (bolp) (insert "\n"))
5070 (setq ins-end (point))
5071 (goto-char ins-point)
5072 (org-skip-whitespace)
5073 (when (and (< arg 0)
5074 (org-first-sibling-p)
5075 (> ne-ins ne-beg))
5076 ;; Move whitespace back to beginning
5077 (save-excursion
5078 (goto-char ins-end)
5079 (let ((kill-whole-line t))
5080 (kill-line (- ne-ins ne-beg)) (point)))
5081 (insert (make-string (- ne-ins ne-beg) ?\n)))
5082 (move-marker ins-point nil)
5083 (org-compact-display-after-subtree-move)
5084 (org-show-empty-lines-in-parent)
5085 (unless folded
5086 (org-show-entry)
5087 (show-children)
5088 (org-cycle-hide-drawers 'children))))
5090 (defvar org-subtree-clip ""
5091 "Clipboard for cut and paste of subtrees.
5092 This is actually only a copy of the kill, because we use the normal kill
5093 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5095 (defvar org-subtree-clip-folded nil
5096 "Was the last copied subtree folded?
5097 This is used to fold the tree back after pasting.")
5099 (defun org-cut-subtree (&optional n)
5100 "Cut the current subtree into the clipboard.
5101 With prefix arg N, cut this many sequential subtrees.
5102 This is a short-hand for marking the subtree and then cutting it."
5103 (interactive "p")
5104 (org-copy-subtree n 'cut))
5106 (defun org-copy-subtree (&optional n cut force-store-markers)
5107 "Cut the current subtree into the clipboard.
5108 With prefix arg N, cut this many sequential subtrees.
5109 This is a short-hand for marking the subtree and then copying it.
5110 If CUT is non-nil, actually cut the subtree.
5111 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5112 of some markers in the region, even if CUT is non-nil. This is
5113 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5114 (interactive "p")
5115 (let (beg end folded (beg0 (point)))
5116 (if (interactive-p)
5117 (org-back-to-heading nil) ; take what looks like a subtree
5118 (org-back-to-heading t)) ; take what is really there
5119 (org-back-over-empty-lines)
5120 (setq beg (point))
5121 (skip-chars-forward " \t\r\n")
5122 (save-match-data
5123 (save-excursion (outline-end-of-heading)
5124 (setq folded (org-invisible-p)))
5125 (condition-case nil
5126 (outline-forward-same-level (1- n))
5127 (error nil))
5128 (org-end-of-subtree t t))
5129 (org-back-over-empty-lines)
5130 (setq end (point))
5131 (goto-char beg0)
5132 (when (> end beg)
5133 (setq org-subtree-clip-folded folded)
5134 (when (or cut force-store-markers)
5135 (org-save-markers-in-region beg end))
5136 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5137 (setq org-subtree-clip (current-kill 0))
5138 (message "%s: Subtree(s) with %d characters"
5139 (if cut "Cut" "Copied")
5140 (length org-subtree-clip)))))
5142 (defun org-paste-subtree (&optional level tree for-yank)
5143 "Paste the clipboard as a subtree, with modification of headline level.
5144 The entire subtree is promoted or demoted in order to match a new headline
5145 level.
5147 If the cursor is at the beginning of a headline, the same level as
5148 that headline is used to paste the tree
5150 If not, the new level is derived from the *visible* headings
5151 before and after the insertion point, and taken to be the inferior headline
5152 level of the two. So if the previous visible heading is level 3 and the
5153 next is level 4 (or vice versa), level 4 will be used for insertion.
5154 This makes sure that the subtree remains an independent subtree and does
5155 not swallow low level entries.
5157 You can also force a different level, either by using a numeric prefix
5158 argument, or by inserting the heading marker by hand. For example, if the
5159 cursor is after \"*****\", then the tree will be shifted to level 5.
5161 If optional TREE is given, use this text instead of the kill ring.
5163 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5164 move back over whitespace before inserting, and move point to the end of
5165 the inserted text when done."
5166 (interactive "P")
5167 (unless (org-kill-is-subtree-p tree)
5168 (error "%s"
5169 (substitute-command-keys
5170 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5171 (let* ((visp (not (org-invisible-p)))
5172 (txt (or tree (and kill-ring (current-kill 0))))
5173 (^re (concat "^\\(" outline-regexp "\\)"))
5174 (re (concat "\\(" outline-regexp "\\)"))
5175 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5177 (old-level (if (string-match ^re txt)
5178 (- (match-end 0) (match-beginning 0) 1)
5179 -1))
5180 (force-level (cond (level (prefix-numeric-value level))
5181 ((and (looking-at "[ \t]*$")
5182 (string-match
5183 ^re_ (buffer-substring
5184 (point-at-bol) (point))))
5185 (- (match-end 1) (match-beginning 1)))
5186 ((and (bolp)
5187 (looking-at org-outline-regexp))
5188 (- (match-end 0) (point) 1))
5189 (t nil)))
5190 (previous-level (save-excursion
5191 (condition-case nil
5192 (progn
5193 (outline-previous-visible-heading 1)
5194 (if (looking-at re)
5195 (- (match-end 0) (match-beginning 0) 1)
5197 (error 1))))
5198 (next-level (save-excursion
5199 (condition-case nil
5200 (progn
5201 (or (looking-at outline-regexp)
5202 (outline-next-visible-heading 1))
5203 (if (looking-at re)
5204 (- (match-end 0) (match-beginning 0) 1)
5206 (error 1))))
5207 (new-level (or force-level (max previous-level next-level)))
5208 (shift (if (or (= old-level -1)
5209 (= new-level -1)
5210 (= old-level new-level))
5212 (- new-level old-level)))
5213 (delta (if (> shift 0) -1 1))
5214 (func (if (> shift 0) 'org-demote 'org-promote))
5215 (org-odd-levels-only nil)
5216 beg end newend)
5217 ;; Remove the forced level indicator
5218 (if force-level
5219 (delete-region (point-at-bol) (point)))
5220 ;; Paste
5221 (beginning-of-line 1)
5222 (unless for-yank (org-back-over-empty-lines))
5223 (setq beg (point))
5224 (insert-before-markers txt)
5225 (unless (string-match "\n\\'" txt) (insert "\n"))
5226 (setq newend (point))
5227 (org-reinstall-markers-in-region beg)
5228 (setq end (point))
5229 (goto-char beg)
5230 (skip-chars-forward " \t\n\r")
5231 (setq beg (point))
5232 (if (and (org-invisible-p) visp)
5233 (save-excursion (outline-show-heading)))
5234 ;; Shift if necessary
5235 (unless (= shift 0)
5236 (save-restriction
5237 (narrow-to-region beg end)
5238 (while (not (= shift 0))
5239 (org-map-region func (point-min) (point-max))
5240 (setq shift (+ delta shift)))
5241 (goto-char (point-min))
5242 (setq newend (point-max))))
5243 (when (or (interactive-p) for-yank)
5244 (message "Clipboard pasted as level %d subtree" new-level))
5245 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5246 kill-ring
5247 (eq org-subtree-clip (current-kill 0))
5248 org-subtree-clip-folded)
5249 ;; The tree was folded before it was killed/copied
5250 (hide-subtree))
5251 (and for-yank (goto-char newend))))
5253 (defun org-kill-is-subtree-p (&optional txt)
5254 "Check if the current kill is an outline subtree, or a set of trees.
5255 Returns nil if kill does not start with a headline, or if the first
5256 headline level is not the largest headline level in the tree.
5257 So this will actually accept several entries of equal levels as well,
5258 which is OK for `org-paste-subtree'.
5259 If optional TXT is given, check this string instead of the current kill."
5260 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5261 (start-level (and kill
5262 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5263 org-outline-regexp "\\)")
5264 kill)
5265 (- (match-end 2) (match-beginning 2) 1)))
5266 (re (concat "^" org-outline-regexp))
5267 (start (1+ (or (match-beginning 2) -1))))
5268 (if (not start-level)
5269 (progn
5270 nil) ;; does not even start with a heading
5271 (catch 'exit
5272 (while (setq start (string-match re kill (1+ start)))
5273 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5274 (throw 'exit nil)))
5275 t))))
5277 (defvar org-markers-to-move nil
5278 "Markers that should be moved with a cut-and-paste operation.
5279 Those markers are stored together with their positions relative to
5280 the start of the region.")
5282 (defun org-save-markers-in-region (beg end)
5283 "Check markers in region.
5284 If these markers are between BEG and END, record their position relative
5285 to BEG, so that after moving the block of text, we can put the markers back
5286 into place.
5287 This function gets called just before an entry or tree gets cut from the
5288 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5289 called immediately, to move the markers with the entries."
5290 (setq org-markers-to-move nil)
5291 (when (featurep 'org-clock)
5292 (org-clock-save-markers-for-cut-and-paste beg end))
5293 (when (featurep 'org-agenda)
5294 (org-agenda-save-markers-for-cut-and-paste beg end)))
5296 (defun org-check-and-save-marker (marker beg end)
5297 "Check if MARKER is between BEG and END.
5298 If yes, remember the marker and the distance to BEG."
5299 (when (and (marker-buffer marker)
5300 (equal (marker-buffer marker) (current-buffer)))
5301 (if (and (>= marker beg) (< marker end))
5302 (push (cons marker (- marker beg)) org-markers-to-move))))
5304 (defun org-reinstall-markers-in-region (beg)
5305 "Move all remembered markers to their position relative to BEG."
5306 (mapc (lambda (x)
5307 (move-marker (car x) (+ beg (cdr x))))
5308 org-markers-to-move)
5309 (setq org-markers-to-move nil))
5311 (defun org-narrow-to-subtree ()
5312 "Narrow buffer to the current subtree."
5313 (interactive)
5314 (save-excursion
5315 (save-match-data
5316 (narrow-to-region
5317 (progn (org-back-to-heading) (point))
5318 (progn (org-end-of-subtree t) (point))))))
5321 ;;; Outline Sorting
5323 (defun org-sort (with-case)
5324 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5325 Optional argument WITH-CASE means sort case-sensitively."
5326 (interactive "P")
5327 (if (org-at-table-p)
5328 (org-call-with-arg 'org-table-sort-lines with-case)
5329 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5331 (defun org-sort-remove-invisible (s)
5332 (remove-text-properties 0 (length s) org-rm-props s)
5333 (while (string-match org-bracket-link-regexp s)
5334 (setq s (replace-match (if (match-end 2)
5335 (match-string 3 s)
5336 (match-string 1 s)) t t s)))
5339 (defvar org-priority-regexp) ; defined later in the file
5341 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5342 "Sort entries on a certain level of an outline tree.
5343 If there is an active region, the entries in the region are sorted.
5344 Else, if the cursor is before the first entry, sort the top-level items.
5345 Else, the children of the entry at point are sorted.
5347 Sorting can be alphabetically, numerically, and by date/time as given by
5348 the first time stamp in the entry. The command prompts for the sorting
5349 type unless it has been given to the function through the SORTING-TYPE
5350 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5351 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5352 called with point at the beginning of the record. It must return either
5353 a string or a number that should serve as the sorting key for that record.
5355 Comparing entries ignores case by default. However, with an optional argument
5356 WITH-CASE, the sorting considers case as well."
5357 (interactive "P")
5358 (let ((case-func (if with-case 'identity 'downcase))
5359 start beg end stars re re2
5360 txt what tmp plain-list-p)
5361 ;; Find beginning and end of region to sort
5362 (cond
5363 ((org-region-active-p)
5364 ;; we will sort the region
5365 (setq end (region-end)
5366 what "region")
5367 (goto-char (region-beginning))
5368 (if (not (org-on-heading-p)) (outline-next-heading))
5369 (setq start (point)))
5370 ((org-at-item-p)
5371 ;; we will sort this plain list
5372 (org-beginning-of-item-list) (setq start (point))
5373 (org-end-of-item-list) (setq end (point))
5374 (goto-char start)
5375 (setq plain-list-p t
5376 what "plain list"))
5377 ((or (org-on-heading-p)
5378 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5379 ;; we will sort the children of the current headline
5380 (org-back-to-heading)
5381 (setq start (point)
5382 end (progn (org-end-of-subtree t t)
5383 (org-back-over-empty-lines)
5384 (point))
5385 what "children")
5386 (goto-char start)
5387 (show-subtree)
5388 (outline-next-heading))
5390 ;; we will sort the top-level entries in this file
5391 (goto-char (point-min))
5392 (or (org-on-heading-p) (outline-next-heading))
5393 (setq start (point) end (point-max) what "top-level")
5394 (goto-char start)
5395 (show-all)))
5397 (setq beg (point))
5398 (if (>= beg end) (error "Nothing to sort"))
5400 (unless plain-list-p
5401 (looking-at "\\(\\*+\\)")
5402 (setq stars (match-string 1)
5403 re (concat "^" (regexp-quote stars) " +")
5404 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5405 txt (buffer-substring beg end))
5406 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5407 (if (and (not (equal stars "*")) (string-match re2 txt))
5408 (error "Region to sort contains a level above the first entry")))
5410 (unless sorting-type
5411 (message
5412 (if plain-list-p
5413 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5414 "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:")
5415 what)
5416 (setq sorting-type (read-char-exclusive))
5418 (and (= (downcase sorting-type) ?f)
5419 (setq getkey-func
5420 (org-ido-completing-read "Sort using function: "
5421 obarray 'fboundp t nil nil))
5422 (setq getkey-func (intern getkey-func)))
5424 (and (= (downcase sorting-type) ?r)
5425 (setq property
5426 (org-ido-completing-read "Property: "
5427 (mapcar 'list (org-buffer-property-keys t))
5428 nil t))))
5430 (message "Sorting entries...")
5432 (save-restriction
5433 (narrow-to-region start end)
5435 (let ((dcst (downcase sorting-type))
5436 (now (current-time)))
5437 (sort-subr
5438 (/= dcst sorting-type)
5439 ;; This function moves to the beginning character of the "record" to
5440 ;; be sorted.
5441 (if plain-list-p
5442 (lambda nil
5443 (if (org-at-item-p) t (goto-char (point-max))))
5444 (lambda nil
5445 (if (re-search-forward re nil t)
5446 (goto-char (match-beginning 0))
5447 (goto-char (point-max)))))
5448 ;; This function moves to the last character of the "record" being
5449 ;; sorted.
5450 (if plain-list-p
5451 'org-end-of-item
5452 (lambda nil
5453 (save-match-data
5454 (condition-case nil
5455 (outline-forward-same-level 1)
5456 (error
5457 (goto-char (point-max)))))))
5459 ;; This function returns the value that gets sorted against.
5460 (if plain-list-p
5461 (lambda nil
5462 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5463 (cond
5464 ((= dcst ?n)
5465 (string-to-number (buffer-substring (match-end 0)
5466 (point-at-eol))))
5467 ((= dcst ?a)
5468 (buffer-substring (match-end 0) (point-at-eol)))
5469 ((= dcst ?t)
5470 (if (re-search-forward org-ts-regexp
5471 (point-at-eol) t)
5472 (org-time-string-to-time (match-string 0))
5473 now))
5474 ((= dcst ?f)
5475 (if getkey-func
5476 (progn
5477 (setq tmp (funcall getkey-func))
5478 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5479 tmp)
5480 (error "Invalid key function `%s'" getkey-func)))
5481 (t (error "Invalid sorting type `%c'" sorting-type)))))
5482 (lambda nil
5483 (cond
5484 ((= dcst ?n)
5485 (if (looking-at org-complex-heading-regexp)
5486 (string-to-number (match-string 4))
5487 nil))
5488 ((= dcst ?a)
5489 (if (looking-at org-complex-heading-regexp)
5490 (funcall case-func (match-string 4))
5491 nil))
5492 ((= dcst ?t)
5493 (if (re-search-forward org-ts-regexp
5494 (save-excursion
5495 (forward-line 2)
5496 (point)) t)
5497 (org-time-string-to-time (match-string 0))
5498 now))
5499 ((= dcst ?p)
5500 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5501 (string-to-char (match-string 2))
5502 org-default-priority))
5503 ((= dcst ?r)
5504 (or (org-entry-get nil property) ""))
5505 ((= dcst ?o)
5506 (if (looking-at org-complex-heading-regexp)
5507 (- 9999 (length (member (match-string 2)
5508 org-todo-keywords-1)))))
5509 ((= dcst ?f)
5510 (if getkey-func
5511 (progn
5512 (setq tmp (funcall getkey-func))
5513 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5514 tmp)
5515 (error "Invalid key function `%s'" getkey-func)))
5516 (t (error "Invalid sorting type `%c'" sorting-type)))))
5518 (cond
5519 ((= dcst ?a) 'string<)
5520 ((= dcst ?t) 'time-less-p)
5521 (t nil)))))
5522 (message "Sorting entries...done")))
5524 (defun org-do-sort (table what &optional with-case sorting-type)
5525 "Sort TABLE of WHAT according to SORTING-TYPE.
5526 The user will be prompted for the SORTING-TYPE if the call to this
5527 function does not specify it. WHAT is only for the prompt, to indicate
5528 what is being sorted. The sorting key will be extracted from
5529 the car of the elements of the table.
5530 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5531 (unless sorting-type
5532 (message
5533 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5534 what)
5535 (setq sorting-type (read-char-exclusive)))
5536 (let ((dcst (downcase sorting-type))
5537 extractfun comparefun)
5538 ;; Define the appropriate functions
5539 (cond
5540 ((= dcst ?n)
5541 (setq extractfun 'string-to-number
5542 comparefun (if (= dcst sorting-type) '< '>)))
5543 ((= dcst ?a)
5544 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5545 (lambda(x) (downcase (org-sort-remove-invisible x))))
5546 comparefun (if (= dcst sorting-type)
5547 'string<
5548 (lambda (a b) (and (not (string< a b))
5549 (not (string= a b)))))))
5550 ((= dcst ?t)
5551 (setq extractfun
5552 (lambda (x)
5553 (if (string-match org-ts-regexp x)
5554 (time-to-seconds
5555 (org-time-string-to-time (match-string 0 x)))
5557 comparefun (if (= dcst sorting-type) '< '>)))
5558 (t (error "Invalid sorting type `%c'" sorting-type)))
5560 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5561 table)
5562 (lambda (a b) (funcall comparefun (car a) (car b))))))
5564 ;;; Editing source examples
5566 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5567 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5568 (defvar org-edit-src-force-single-line nil)
5569 (defvar org-edit-src-from-org-mode nil)
5570 (defvar org-edit-src-picture nil)
5572 (define-minor-mode org-exit-edit-mode
5573 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5575 (defun org-edit-src-code ()
5576 "Edit the source code example at point.
5577 An indirect buffer is created, and that buffer is then narrowed to the
5578 example at point and switched to the correct language mode. When done,
5579 exit by killing the buffer with \\[org-edit-src-exit]."
5580 (interactive)
5581 (let ((line (org-current-line))
5582 (case-fold-search t)
5583 (msg (substitute-command-keys
5584 "Edit, then exit with C-c ' (C-c and single quote)"))
5585 (info (org-edit-src-find-region-and-lang))
5586 (org-mode-p (eq major-mode 'org-mode))
5587 beg end lang lang-f single)
5588 (if (not info)
5590 (setq beg (nth 0 info)
5591 end (nth 1 info)
5592 lang (nth 2 info)
5593 single (nth 3 info)
5594 lang-f (intern (concat lang "-mode")))
5595 (unless (functionp lang-f)
5596 (error "No such language mode: %s" lang-f))
5597 (goto-line line)
5598 (if (get-buffer "*Org Edit Src Example*")
5599 (kill-buffer "*Org Edit Src Example*"))
5600 (switch-to-buffer (make-indirect-buffer (current-buffer)
5601 "*Org Edit Src Example*"))
5602 (narrow-to-region beg end)
5603 (remove-text-properties beg end '(display nil invisible nil
5604 intangible nil))
5605 (let ((org-inhibit-startup t))
5606 (funcall lang-f))
5607 (set (make-local-variable 'org-edit-src-force-single-line) single)
5608 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5609 (when org-mode-p
5610 (goto-char (point-min))
5611 (while (re-search-forward "^," nil t)
5612 (replace-match "")))
5613 (goto-line line)
5614 (org-exit-edit-mode)
5615 (org-set-local 'header-line-format msg)
5616 (message "%s" msg)
5617 t)))
5619 (defun org-edit-fixed-width-region ()
5620 "Edit the fixed-width ascii drawing at point.
5621 This must be a region where each line starts with ca colon followed by
5622 a space character.
5623 An indirect buffer is created, and that buffer is then narrowed to the
5624 example at point and switched to artist-mode. When done,
5625 exit by killing the buffer with \\[org-edit-src-exit]."
5626 (interactive)
5627 (let ((line (org-current-line))
5628 (case-fold-search t)
5629 (msg (substitute-command-keys
5630 "Edit, then exit with C-c ' (C-c and single quote)"))
5631 (org-mode-p (eq major-mode 'org-mode))
5632 beg end lang lang-f)
5633 (beginning-of-line 1)
5634 (if (looking-at "[ \t]*[^:\n \t]")
5636 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5637 (setq beg (point) end beg)
5638 (save-excursion
5639 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5640 (setq beg (point-at-bol 2))
5641 (setq beg (point))))
5642 (save-excursion
5643 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5644 (setq end (1- (match-beginning 0)))
5645 (setq end (point))))
5646 (goto-line line))
5647 (if (get-buffer "*Org Edit Picture*")
5648 (kill-buffer "*Org Edit Picture*"))
5649 (switch-to-buffer (make-indirect-buffer (current-buffer)
5650 "*Org Edit Picture*"))
5651 (narrow-to-region beg end)
5652 (remove-text-properties beg end '(display nil invisible nil
5653 intangible nil))
5654 (when (fboundp 'font-lock-unfontify-region)
5655 (font-lock-unfontify-region (point-min) (point-max)))
5656 (cond
5657 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5658 (fundamental-mode)
5659 (artist-mode 1))
5660 (t (funcall org-edit-fixed-width-region-mode)))
5661 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5662 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5663 (set (make-local-variable 'org-edit-src-picture) t)
5664 (goto-char (point-min))
5665 (while (re-search-forward "^[ \t]*: ?" nil t)
5666 (replace-match ""))
5667 (goto-line line)
5668 (org-exit-edit-mode)
5669 (org-set-local 'header-line-format msg)
5670 (message "%s" msg)
5671 t)))
5674 (defun org-edit-src-find-region-and-lang ()
5675 "Find the region and language for a local edit.
5676 Return a list with beginning and end of the region, a string representing
5677 the language, a switch telling of the content should be in a single line."
5678 (let ((re-list
5679 (append
5680 org-edit-src-region-extra
5682 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5683 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5684 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5685 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5686 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5687 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5688 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5689 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5690 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5691 ("^#\\+html:" "\n" "html" single-line)
5692 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5693 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5694 ("^#\\+latex:" "\n" "latex" single-line)
5695 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5696 ("^#\\+ascii:" "\n" "ascii" single-line)
5698 (pos (point))
5699 re re1 re2 single beg end lang)
5700 (catch 'exit
5701 (while (setq entry (pop re-list))
5702 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5703 single (nth 3 entry))
5704 (save-excursion
5705 (if (or (looking-at re1)
5706 (re-search-backward re1 nil t))
5707 (progn
5708 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5709 (if (and (re-search-forward re2 nil t)
5710 (>= (match-end 0) pos))
5711 (throw 'exit (list beg (match-beginning 0) lang single))))
5712 (if (or (looking-at re2)
5713 (re-search-forward re2 nil t))
5714 (progn
5715 (setq end (match-beginning 0))
5716 (if (and (re-search-backward re1 nil t)
5717 (<= (match-beginning 0) pos))
5718 (throw 'exit
5719 (list (match-end 0) end
5720 (org-edit-src-get-lang lang) single)))))))))))
5722 (defun org-edit-src-get-lang (lang)
5723 "Extract the src language."
5724 (let ((m (match-string 0)))
5725 (cond
5726 ((stringp lang) lang)
5727 ((integerp lang) (match-string lang))
5728 ((and (eq lang 'lang)
5729 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5730 (match-string 1 m))
5731 ((and (eq lang 'style)
5732 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5733 (match-string 1 m))
5734 (t "fundamental"))))
5736 (defun org-edit-src-exit ()
5737 "Exit special edit and protect problematic lines."
5738 (interactive)
5739 (unless (buffer-base-buffer (current-buffer))
5740 (error "This is not an indirect buffer, something is wrong..."))
5741 (unless (> (point-min) 1)
5742 (error "This buffer is not narrowed, something is wrong..."))
5743 (goto-char (point-min))
5744 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5745 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5746 (when (org-bound-and-true-p org-edit-src-force-single-line)
5747 (goto-char (point-min))
5748 (while (re-search-forward "\n" nil t)
5749 (replace-match " "))
5750 (goto-char (point-min))
5751 (if (looking-at "\\s-*") (replace-match " "))
5752 (if (re-search-forward "\\s-+\\'" nil t)
5753 (replace-match "")))
5754 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5755 (goto-char (point-min))
5756 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5757 (replace-match ",\\1"))
5758 (when font-lock-mode
5759 (font-lock-unfontify-region (point-min) (point-max)))
5760 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5761 (when (org-bound-and-true-p org-edit-src-picture)
5762 (untabify (point-min) (point-max))
5763 (goto-char (point-min))
5764 (while (re-search-forward "^" nil t)
5765 (replace-match ": "))
5766 (when font-lock-mode
5767 (font-lock-unfontify-region (point-min) (point-max)))
5768 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5769 (kill-buffer (current-buffer))
5770 (and (org-mode-p) (org-restart-font-lock)))
5773 ;;; The orgstruct minor mode
5775 ;; Define a minor mode which can be used in other modes in order to
5776 ;; integrate the org-mode structure editing commands.
5778 ;; This is really a hack, because the org-mode structure commands use
5779 ;; keys which normally belong to the major mode. Here is how it
5780 ;; works: The minor mode defines all the keys necessary to operate the
5781 ;; structure commands, but wraps the commands into a function which
5782 ;; tests if the cursor is currently at a headline or a plain list
5783 ;; item. If that is the case, the structure command is used,
5784 ;; temporarily setting many Org-mode variables like regular
5785 ;; expressions for filling etc. However, when any of those keys is
5786 ;; used at a different location, function uses `key-binding' to look
5787 ;; up if the key has an associated command in another currently active
5788 ;; keymap (minor modes, major mode, global), and executes that
5789 ;; command. There might be problems if any of the keys is otherwise
5790 ;; used as a prefix key.
5792 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5793 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5794 ;; addresses this by checking explicitly for both bindings.
5796 (defvar orgstruct-mode-map (make-sparse-keymap)
5797 "Keymap for the minor `orgstruct-mode'.")
5799 (defvar org-local-vars nil
5800 "List of local variables, for use by `orgstruct-mode'")
5802 ;;;###autoload
5803 (define-minor-mode orgstruct-mode
5804 "Toggle the minor more `orgstruct-mode'.
5805 This mode is for using Org-mode structure commands in other modes.
5806 The following key behave as if Org-mode was active, if the cursor
5807 is on a headline, or on a plain list item (both in the definition
5808 of Org-mode).
5810 M-up Move entry/item up
5811 M-down Move entry/item down
5812 M-left Promote
5813 M-right Demote
5814 M-S-up Move entry/item up
5815 M-S-down Move entry/item down
5816 M-S-left Promote subtree
5817 M-S-right Demote subtree
5818 M-q Fill paragraph and items like in Org-mode
5819 C-c ^ Sort entries
5820 C-c - Cycle list bullet
5821 TAB Cycle item visibility
5822 M-RET Insert new heading/item
5823 S-M-RET Insert new TODO heading / Chekbox item
5824 C-c C-c Set tags / toggle checkbox"
5825 nil " OrgStruct" nil
5826 (org-load-modules-maybe)
5827 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5829 ;;;###autoload
5830 (defun turn-on-orgstruct ()
5831 "Unconditionally turn on `orgstruct-mode'."
5832 (orgstruct-mode 1))
5834 ;;;###autoload
5835 (defun turn-on-orgstruct++ ()
5836 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5837 In addition to setting orgstruct-mode, this also exports all indentation and
5838 autofilling variables from org-mode into the buffer. Note that turning
5839 off orgstruct-mode will *not* remove these additional settings."
5840 (orgstruct-mode 1)
5841 (let (var val)
5842 (mapc
5843 (lambda (x)
5844 (when (string-match
5845 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5846 (symbol-name (car x)))
5847 (setq var (car x) val (nth 1 x))
5848 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5849 org-local-vars)))
5851 (defun orgstruct-error ()
5852 "Error when there is no default binding for a structure key."
5853 (interactive)
5854 (error "This key has no function outside structure elements"))
5856 (defun orgstruct-setup ()
5857 "Setup orgstruct keymaps."
5858 (let ((nfunc 0)
5859 (bindings
5860 (list
5861 '([(meta up)] org-metaup)
5862 '([(meta down)] org-metadown)
5863 '([(meta left)] org-metaleft)
5864 '([(meta right)] org-metaright)
5865 '([(meta shift up)] org-shiftmetaup)
5866 '([(meta shift down)] org-shiftmetadown)
5867 '([(meta shift left)] org-shiftmetaleft)
5868 '([(meta shift right)] org-shiftmetaright)
5869 '([(shift up)] org-shiftup)
5870 '([(shift down)] org-shiftdown)
5871 '([(shift left)] org-shiftleft)
5872 '([(shift right)] org-shiftright)
5873 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5874 '("\M-q" fill-paragraph)
5875 '("\C-c^" org-sort)
5876 '("\C-c-" org-cycle-list-bullet)))
5877 elt key fun cmd)
5878 (while (setq elt (pop bindings))
5879 (setq nfunc (1+ nfunc))
5880 (setq key (org-key (car elt))
5881 fun (nth 1 elt)
5882 cmd (orgstruct-make-binding fun nfunc key))
5883 (org-defkey orgstruct-mode-map key cmd))
5885 ;; Special treatment needed for TAB and RET
5886 (org-defkey orgstruct-mode-map [(tab)]
5887 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5888 (org-defkey orgstruct-mode-map "\C-i"
5889 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5891 (org-defkey orgstruct-mode-map "\M-\C-m"
5892 (orgstruct-make-binding 'org-insert-heading 105
5893 "\M-\C-m" [(meta return)]))
5894 (org-defkey orgstruct-mode-map [(meta return)]
5895 (orgstruct-make-binding 'org-insert-heading 106
5896 [(meta return)] "\M-\C-m"))
5898 (org-defkey orgstruct-mode-map [(shift meta return)]
5899 (orgstruct-make-binding 'org-insert-todo-heading 107
5900 [(meta return)] "\M-\C-m"))
5902 (unless org-local-vars
5903 (setq org-local-vars (org-get-local-variables)))
5907 (defun orgstruct-make-binding (fun n &rest keys)
5908 "Create a function for binding in the structure minor mode.
5909 FUN is the command to call inside a table. N is used to create a unique
5910 command name. KEYS are keys that should be checked in for a command
5911 to execute outside of tables."
5912 (eval
5913 (list 'defun
5914 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5915 '(arg)
5916 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5917 "Outside of structure, run the binding of `"
5918 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5919 "'.")
5920 '(interactive "p")
5921 (list 'if
5922 '(org-context-p 'headline 'item)
5923 (list 'org-run-like-in-org-mode (list 'quote fun))
5924 (list 'let '(orgstruct-mode)
5925 (list 'call-interactively
5926 (append '(or)
5927 (mapcar (lambda (k)
5928 (list 'key-binding k))
5929 keys)
5930 '('orgstruct-error))))))))
5932 (defun org-context-p (&rest contexts)
5933 "Check if local context is any of CONTEXTS.
5934 Possible values in the list of contexts are `table', `headline', and `item'."
5935 (let ((pos (point)))
5936 (goto-char (point-at-bol))
5937 (prog1 (or (and (memq 'table contexts)
5938 (looking-at "[ \t]*|"))
5939 (and (memq 'headline contexts)
5940 ;;????????? (looking-at "\\*+"))
5941 (looking-at outline-regexp))
5942 (and (memq 'item contexts)
5943 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5944 (goto-char pos))))
5946 (defun org-get-local-variables ()
5947 "Return a list of all local variables in an org-mode buffer."
5948 (let (varlist)
5949 (with-current-buffer (get-buffer-create "*Org tmp*")
5950 (erase-buffer)
5951 (org-mode)
5952 (setq varlist (buffer-local-variables)))
5953 (kill-buffer "*Org tmp*")
5954 (delq nil
5955 (mapcar
5956 (lambda (x)
5957 (setq x
5958 (if (symbolp x)
5959 (list x)
5960 (list (car x) (list 'quote (cdr x)))))
5961 (if (string-match
5962 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5963 (symbol-name (car x)))
5964 x nil))
5965 varlist))))
5967 ;;;###autoload
5968 (defun org-run-like-in-org-mode (cmd)
5969 (org-load-modules-maybe)
5970 (unless org-local-vars
5971 (setq org-local-vars (org-get-local-variables)))
5972 (eval (list 'let org-local-vars
5973 (list 'call-interactively (list 'quote cmd)))))
5975 ;;;; Archiving
5977 (defun org-get-category (&optional pos)
5978 "Get the category applying to position POS."
5979 (get-text-property (or pos (point)) 'org-category))
5981 (defun org-refresh-category-properties ()
5982 "Refresh category text properties in the buffer."
5983 (let ((def-cat (cond
5984 ((null org-category)
5985 (if buffer-file-name
5986 (file-name-sans-extension
5987 (file-name-nondirectory buffer-file-name))
5988 "???"))
5989 ((symbolp org-category) (symbol-name org-category))
5990 (t org-category)))
5991 beg end cat pos optionp)
5992 (org-unmodified
5993 (save-excursion
5994 (save-restriction
5995 (widen)
5996 (goto-char (point-min))
5997 (put-text-property (point) (point-max) 'org-category def-cat)
5998 (while (re-search-forward
5999 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6000 (setq pos (match-end 0)
6001 optionp (equal (char-after (match-beginning 0)) ?#)
6002 cat (org-trim (match-string 2)))
6003 (if optionp
6004 (setq beg (point-at-bol) end (point-max))
6005 (org-back-to-heading t)
6006 (setq beg (point) end (org-end-of-subtree t t)))
6007 (put-text-property beg end 'org-category cat)
6008 (goto-char pos)))))))
6011 ;;;; Link Stuff
6013 ;;; Link abbreviations
6015 (defun org-link-expand-abbrev (link)
6016 "Apply replacements as defined in `org-link-abbrev-alist."
6017 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6018 (let* ((key (match-string 1 link))
6019 (as (or (assoc key org-link-abbrev-alist-local)
6020 (assoc key org-link-abbrev-alist)))
6021 (tag (and (match-end 2) (match-string 3 link)))
6022 rpl)
6023 (if (not as)
6024 link
6025 (setq rpl (cdr as))
6026 (cond
6027 ((symbolp rpl) (funcall rpl tag))
6028 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6029 ((string-match "%h" rpl)
6030 (replace-match (url-hexify-string (or tag "")) t t rpl))
6031 (t (concat rpl tag)))))
6032 link))
6034 ;;; Storing and inserting links
6036 (defvar org-insert-link-history nil
6037 "Minibuffer history for links inserted with `org-insert-link'.")
6039 (defvar org-stored-links nil
6040 "Contains the links stored with `org-store-link'.")
6042 (defvar org-store-link-plist nil
6043 "Plist with info about the most recently link created with `org-store-link'.")
6045 (defvar org-link-protocols nil
6046 "Link protocols added to Org-mode using `org-add-link-type'.")
6048 (defvar org-store-link-functions nil
6049 "List of functions that are called to create and store a link.
6050 Each function will be called in turn until one returns a non-nil
6051 value. Each function should check if it is responsible for creating
6052 this link (for example by looking at the major mode).
6053 If not, it must exit and return nil.
6054 If yes, it should return a non-nil value after a calling
6055 `org-store-link-props' with a list of properties and values.
6056 Special properties are:
6058 :type The link prefix. like \"http\". This must be given.
6059 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6060 This is obligatory as well.
6061 :description Optional default description for the second pair
6062 of brackets in an Org-mode link. The user can still change
6063 this when inserting this link into an Org-mode buffer.
6065 In addition to these, any additional properties can be specified
6066 and then used in remember templates.")
6068 (defun org-add-link-type (type &optional follow export)
6069 "Add TYPE to the list of `org-link-types'.
6070 Re-compute all regular expressions depending on `org-link-types'
6072 FOLLOW and EXPORT are two functions.
6074 FOLLOW should take the link path as the single argument and do whatever
6075 is necessary to follow the link, for example find a file or display
6076 a mail message.
6078 EXPORT should format the link path for export to one of the export formats.
6079 It should be a function accepting three arguments:
6081 path the path of the link, the text after the prefix (like \"http:\")
6082 desc the description of the link, if any, nil if there was no descripton
6083 format the export format, a symbol like `html' or `latex'.
6085 The function may use the FORMAT information to return different values
6086 depending on the format. The return value will be put literally into
6087 the exported file.
6088 Org-mode has a built-in default for exporting links. If you are happy with
6089 this default, there is no need to define an export function for the link
6090 type. For a simple example of an export function, see `org-bbdb.el'."
6091 (add-to-list 'org-link-types type t)
6092 (org-make-link-regexps)
6093 (if (assoc type org-link-protocols)
6094 (setcdr (assoc type org-link-protocols) (list follow export))
6095 (push (list type follow export) org-link-protocols)))
6098 ;;;###autoload
6099 (defun org-store-link (arg)
6100 "\\<org-mode-map>Store an org-link to the current location.
6101 This link is added to `org-stored-links' and can later be inserted
6102 into an org-buffer with \\[org-insert-link].
6104 For some link types, a prefix arg is interpreted:
6105 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6106 For file links, arg negates `org-context-in-file-links'."
6107 (interactive "P")
6108 (org-load-modules-maybe)
6109 (setq org-store-link-plist nil) ; reset
6110 (let (link cpltxt desc description search txt)
6111 (cond
6113 ((run-hook-with-args-until-success 'org-store-link-functions)
6114 (setq link (plist-get org-store-link-plist :link)
6115 desc (or (plist-get org-store-link-plist :description) link)))
6117 ((eq major-mode 'calendar-mode)
6118 (let ((cd (calendar-cursor-to-date)))
6119 (setq link
6120 (format-time-string
6121 (car org-time-stamp-formats)
6122 (apply 'encode-time
6123 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6124 nil nil nil))))
6125 (org-store-link-props :type "calendar" :date cd)))
6127 ((eq major-mode 'w3-mode)
6128 (setq cpltxt (url-view-url t)
6129 link (org-make-link cpltxt))
6130 (org-store-link-props :type "w3" :url (url-view-url t)))
6132 ((eq major-mode 'w3m-mode)
6133 (setq cpltxt (or w3m-current-title w3m-current-url)
6134 link (org-make-link w3m-current-url))
6135 (org-store-link-props :type "w3m" :url (url-view-url t)))
6137 ((setq search (run-hook-with-args-until-success
6138 'org-create-file-search-functions))
6139 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6140 "::" search))
6141 (setq cpltxt (or description link)))
6143 ((eq major-mode 'image-mode)
6144 (setq cpltxt (concat "file:"
6145 (abbreviate-file-name buffer-file-name))
6146 link (org-make-link cpltxt))
6147 (org-store-link-props :type "image" :file buffer-file-name))
6149 ((eq major-mode 'dired-mode)
6150 ;; link to the file in the current line
6151 (setq cpltxt (concat "file:"
6152 (abbreviate-file-name
6153 (expand-file-name
6154 (dired-get-filename nil t))))
6155 link (org-make-link cpltxt)))
6157 ((and buffer-file-name (org-mode-p))
6158 ;; Just link to current headline
6159 (setq cpltxt (concat "file:"
6160 (abbreviate-file-name buffer-file-name)))
6161 ;; Add a context search string
6162 (when (org-xor org-context-in-file-links arg)
6163 ;; Check if we are on a target
6164 (if (org-in-regexp "<<\\(.*?\\)>>")
6165 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6166 (setq txt (cond
6167 ((org-on-heading-p) nil)
6168 ((org-region-active-p)
6169 (buffer-substring (region-beginning) (region-end)))
6170 (t nil)))
6171 (when (or (null txt) (string-match "\\S-" txt))
6172 (setq cpltxt
6173 (concat cpltxt "::"
6174 (condition-case nil
6175 (org-make-org-heading-search-string txt)
6176 (error "")))
6177 desc "NONE"))))
6178 (if (string-match "::\\'" cpltxt)
6179 (setq cpltxt (substring cpltxt 0 -2)))
6180 (setq link (org-make-link cpltxt)))
6182 ((buffer-file-name (buffer-base-buffer))
6183 ;; Just link to this file here.
6184 (setq cpltxt (concat "file:"
6185 (abbreviate-file-name
6186 (buffer-file-name (buffer-base-buffer)))))
6187 ;; Add a context string
6188 (when (org-xor org-context-in-file-links arg)
6189 (setq txt (if (org-region-active-p)
6190 (buffer-substring (region-beginning) (region-end))
6191 (buffer-substring (point-at-bol) (point-at-eol))))
6192 ;; Only use search option if there is some text.
6193 (when (string-match "\\S-" txt)
6194 (setq cpltxt
6195 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6196 desc "NONE")))
6197 (setq link (org-make-link cpltxt)))
6199 ((interactive-p)
6200 (error "Cannot link to a buffer which is not visiting a file"))
6202 (t (setq link nil)))
6204 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6205 (setq link (or link cpltxt)
6206 desc (or desc cpltxt))
6207 (if (equal desc "NONE") (setq desc nil))
6209 (if (and (interactive-p) link)
6210 (progn
6211 (setq org-stored-links
6212 (cons (list link desc) org-stored-links))
6213 (message "Stored: %s" (or desc link)))
6214 (and link (org-make-link-string link desc)))))
6216 (defun org-store-link-props (&rest plist)
6217 "Store link properties, extract names and addresses."
6218 (let (x adr)
6219 (when (setq x (plist-get plist :from))
6220 (setq adr (mail-extract-address-components x))
6221 (setq plist (plist-put plist :fromname (car adr)))
6222 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6223 (when (setq x (plist-get plist :to))
6224 (setq adr (mail-extract-address-components x))
6225 (setq plist (plist-put plist :toname (car adr)))
6226 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6227 (let ((from (plist-get plist :from))
6228 (to (plist-get plist :to)))
6229 (when (and from to org-from-is-user-regexp)
6230 (setq plist
6231 (plist-put plist :fromto
6232 (if (string-match org-from-is-user-regexp from)
6233 (concat "to %t")
6234 (concat "from %f"))))))
6235 (setq org-store-link-plist plist))
6237 (defun org-add-link-props (&rest plist)
6238 "Add these properties to the link property list."
6239 (let (key value)
6240 (while plist
6241 (setq key (pop plist) value (pop plist))
6242 (setq org-store-link-plist
6243 (plist-put org-store-link-plist key value)))))
6245 (defun org-email-link-description (&optional fmt)
6246 "Return the description part of an email link.
6247 This takes information from `org-store-link-plist' and formats it
6248 according to FMT (default from `org-email-link-description-format')."
6249 (setq fmt (or fmt org-email-link-description-format))
6250 (let* ((p org-store-link-plist)
6251 (to (plist-get p :toaddress))
6252 (from (plist-get p :fromaddress))
6253 (table
6254 (list
6255 (cons "%c" (plist-get p :fromto))
6256 (cons "%F" (plist-get p :from))
6257 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6258 (cons "%T" (plist-get p :to))
6259 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6260 (cons "%s" (plist-get p :subject))
6261 (cons "%m" (plist-get p :message-id)))))
6262 (when (string-match "%c" fmt)
6263 ;; Check if the user wrote this message
6264 (if (and org-from-is-user-regexp from to
6265 (save-match-data (string-match org-from-is-user-regexp from)))
6266 (setq fmt (replace-match "to %t" t t fmt))
6267 (setq fmt (replace-match "from %f" t t fmt))))
6268 (org-replace-escapes fmt table)))
6270 (defun org-make-org-heading-search-string (&optional string heading)
6271 "Make search string for STRING or current headline."
6272 (interactive)
6273 (let ((s (or string (org-get-heading))))
6274 (unless (and string (not heading))
6275 ;; We are using a headline, clean up garbage in there.
6276 (if (string-match org-todo-regexp s)
6277 (setq s (replace-match "" t t s)))
6278 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6279 (setq s (replace-match "" t t s)))
6280 (setq s (org-trim s))
6281 (if (string-match (concat "^\\(" org-quote-string "\\|"
6282 org-comment-string "\\)") s)
6283 (setq s (replace-match "" t t s)))
6284 (while (string-match org-ts-regexp s)
6285 (setq s (replace-match "" t t s))))
6286 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6287 (setq s (replace-match " " t t s)))
6288 (or string (setq s (concat "*" s))) ; Add * for headlines
6289 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6291 (defun org-make-link (&rest strings)
6292 "Concatenate STRINGS."
6293 (apply 'concat strings))
6295 (defun org-make-link-string (link &optional description)
6296 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6297 (unless (string-match "\\S-" link)
6298 (error "Empty link"))
6299 (when (stringp description)
6300 ;; Remove brackets from the description, they are fatal.
6301 (while (string-match "\\[" description)
6302 (setq description (replace-match "{" t t description)))
6303 (while (string-match "\\]" description)
6304 (setq description (replace-match "}" t t description))))
6305 (when (equal (org-link-escape link) description)
6306 ;; No description needed, it is identical
6307 (setq description nil))
6308 (when (and (not description)
6309 (not (equal link (org-link-escape link))))
6310 (setq description (org-extract-attributes link)))
6311 (concat "[[" (org-link-escape link) "]"
6312 (if description (concat "[" description "]") "")
6313 "]"))
6315 (defconst org-link-escape-chars
6316 '((?\ . "%20")
6317 (?\[ . "%5B")
6318 (?\] . "%5D")
6319 (?\340 . "%E0") ; `a
6320 (?\342 . "%E2") ; ^a
6321 (?\347 . "%E7") ; ,c
6322 (?\350 . "%E8") ; `e
6323 (?\351 . "%E9") ; 'e
6324 (?\352 . "%EA") ; ^e
6325 (?\356 . "%EE") ; ^i
6326 (?\364 . "%F4") ; ^o
6327 (?\371 . "%F9") ; `u
6328 (?\373 . "%FB") ; ^u
6329 (?\; . "%3B")
6330 (?? . "%3F")
6331 (?= . "%3D")
6332 (?+ . "%2B")
6334 "Association list of escapes for some characters problematic in links.
6335 This is the list that is used for internal purposes.")
6337 (defconst org-link-escape-chars-browser
6338 '((?\ . "%20")) ; 32 for the SPC char
6339 "Association list of escapes for some characters problematic in links.
6340 This is the list that is used before handing over to the browser.")
6342 (defun org-link-escape (text &optional table)
6343 "Escape characters in TEXT that are problematic for links."
6344 (setq table (or table org-link-escape-chars))
6345 (when text
6346 (let ((re (mapconcat (lambda (x) (regexp-quote
6347 (char-to-string (car x))))
6348 table "\\|")))
6349 (while (string-match re text)
6350 (setq text
6351 (replace-match
6352 (cdr (assoc (string-to-char (match-string 0 text))
6353 table))
6354 t t text)))
6355 text)))
6357 (defun org-link-unescape (text &optional table)
6358 "Reverse the action of `org-link-escape'."
6359 (setq table (or table org-link-escape-chars))
6360 (when text
6361 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6362 table "\\|")))
6363 (while (string-match re text)
6364 (setq text
6365 (replace-match
6366 (char-to-string (car (rassoc (match-string 0 text) table)))
6367 t t text)))
6368 text)))
6370 (defun org-xor (a b)
6371 "Exclusive or."
6372 (if a (not b) b))
6374 (defun org-get-header (header)
6375 "Find a header field in the current buffer."
6376 (save-excursion
6377 (goto-char (point-min))
6378 (let ((case-fold-search t) s)
6379 (cond
6380 ((eq header 'from)
6381 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6382 (setq s (match-string 1)))
6383 (while (string-match "\"" s)
6384 (setq s (replace-match "" t t s)))
6385 (if (string-match "[<(].*" s)
6386 (setq s (replace-match "" t t s))))
6387 ((eq header 'message-id)
6388 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6389 (setq s (match-string 1))))
6390 ((eq header 'subject)
6391 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6392 (setq s (match-string 1)))))
6393 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6394 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6395 s)))
6398 (defun org-fixup-message-id-for-http (s)
6399 "Replace special characters in a message id, so it can be used in an http query."
6400 (while (string-match "<" s)
6401 (setq s (replace-match "%3C" t t s)))
6402 (while (string-match ">" s)
6403 (setq s (replace-match "%3E" t t s)))
6404 (while (string-match "@" s)
6405 (setq s (replace-match "%40" t t s)))
6408 ;;;###autoload
6409 (defun org-insert-link-global ()
6410 "Insert a link like Org-mode does.
6411 This command can be called in any mode to insert a link in Org-mode syntax."
6412 (interactive)
6413 (org-load-modules-maybe)
6414 (org-run-like-in-org-mode 'org-insert-link))
6416 (defun org-insert-link (&optional complete-file link-location)
6417 "Insert a link. At the prompt, enter the link.
6419 Completion can be used to insert any of the link protocol prefixes like
6420 http or ftp in use.
6422 The history can be used to select a link previously stored with
6423 `org-store-link'. When the empty string is entered (i.e. if you just
6424 press RET at the prompt), the link defaults to the most recently
6425 stored link. As SPC triggers completion in the minibuffer, you need to
6426 use M-SPC or C-q SPC to force the insertion of a space character.
6428 You will also be prompted for a description, and if one is given, it will
6429 be displayed in the buffer instead of the link.
6431 If there is already a link at point, this command will allow you to edit link
6432 and description parts.
6434 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6435 be selected using completion. The path to the file will be relative to the
6436 current directory if the file is in the current directory or a subdirectory.
6437 Otherwise, the link will be the absolute path as completed in the minibuffer
6438 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6439 option `org-link-file-path-type'.
6441 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6442 the current directory or below.
6444 With three \\[universal-argument] prefixes, negate the meaning of
6445 `org-keep-stored-link-after-insertion'.
6447 If `org-make-link-description-function' is non-nil, this function will be
6448 called with the link target, and the result will be the default
6449 link description.
6451 If the LINK-LOCATION parameter is non-nil, this value will be
6452 used as the link location instead of reading one interactively."
6453 (interactive "P")
6454 (let* ((wcf (current-window-configuration))
6455 (region (if (org-region-active-p)
6456 (buffer-substring (region-beginning) (region-end))))
6457 (remove (and region (list (region-beginning) (region-end))))
6458 (desc region)
6459 tmphist ; byte-compile incorrectly complains about this
6460 (link link-location)
6461 entry file)
6462 (cond
6463 (link-location) ; specified by arg, just use it.
6464 ((org-in-regexp org-bracket-link-regexp 1)
6465 ;; We do have a link at point, and we are going to edit it.
6466 (setq remove (list (match-beginning 0) (match-end 0)))
6467 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6468 (setq link (read-string "Link: "
6469 (org-link-unescape
6470 (org-match-string-no-properties 1)))))
6471 ((or (org-in-regexp org-angle-link-re)
6472 (org-in-regexp org-plain-link-re))
6473 ;; Convert to bracket link
6474 (setq remove (list (match-beginning 0) (match-end 0))
6475 link (read-string "Link: "
6476 (org-remove-angle-brackets (match-string 0)))))
6477 ((member complete-file '((4) (16)))
6478 ;; Completing read for file names.
6479 (setq file (read-file-name "File: "))
6480 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6481 (pwd1 (file-name-as-directory (abbreviate-file-name
6482 (expand-file-name ".")))))
6483 (cond
6484 ((equal complete-file '(16))
6485 (setq link (org-make-link
6486 "file:"
6487 (abbreviate-file-name (expand-file-name file)))))
6488 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6489 (setq link (org-make-link "file:" (match-string 1 file))))
6490 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6491 (expand-file-name file))
6492 (setq link (org-make-link
6493 "file:" (match-string 1 (expand-file-name file)))))
6494 (t (setq link (org-make-link "file:" file))))))
6496 ;; Read link, with completion for stored links.
6497 (with-output-to-temp-buffer "*Org Links*"
6498 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6499 (when org-stored-links
6500 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6501 (princ (mapconcat
6502 (lambda (x)
6503 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6504 (reverse org-stored-links) "\n"))))
6505 (let ((cw (selected-window)))
6506 (select-window (get-buffer-window "*Org Links*"))
6507 (org-fit-window-to-buffer)
6508 (setq truncate-lines t)
6509 (select-window cw))
6510 ;; Fake a link history, containing the stored links.
6511 (setq tmphist (append (mapcar 'car org-stored-links)
6512 org-insert-link-history))
6513 (unwind-protect
6514 (setq link (org-completing-read
6515 "Link: "
6516 (append
6517 (mapcar (lambda (x) (list (concat (car x) ":")))
6518 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6519 (mapcar (lambda (x) (list (concat x ":")))
6520 org-link-types))
6521 nil nil nil
6522 'tmphist
6523 (or (car (car org-stored-links)))))
6524 (set-window-configuration wcf)
6525 (kill-buffer "*Org Links*"))
6526 (setq entry (assoc link org-stored-links))
6527 (or entry (push link org-insert-link-history))
6528 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6529 (not org-keep-stored-link-after-insertion))
6530 (setq org-stored-links (delq (assoc link org-stored-links)
6531 org-stored-links)))
6532 (setq desc (or desc (nth 1 entry)))))
6534 (if (string-match org-plain-link-re link)
6535 ;; URL-like link, normalize the use of angular brackets.
6536 (setq link (org-make-link (org-remove-angle-brackets link))))
6538 ;; Check if we are linking to the current file with a search option
6539 ;; If yes, simplify the link by using only the search option.
6540 (when (and buffer-file-name
6541 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6542 (let* ((path (match-string 1 link))
6543 (case-fold-search nil)
6544 (search (match-string 2 link)))
6545 (save-match-data
6546 (if (equal (file-truename buffer-file-name) (file-truename path))
6547 ;; We are linking to this same file, with a search option
6548 (setq link search)))))
6550 ;; Check if we can/should use a relative path. If yes, simplify the link
6551 (when (string-match "^file:\\(.*\\)" link)
6552 (let* ((path (match-string 1 link))
6553 (origpath path)
6554 (case-fold-search nil))
6555 (cond
6556 ((or (eq org-link-file-path-type 'absolute)
6557 (equal complete-file '(16)))
6558 (setq path (abbreviate-file-name (expand-file-name path))))
6559 ((eq org-link-file-path-type 'noabbrev)
6560 (setq path (expand-file-name path)))
6561 ((eq org-link-file-path-type 'relative)
6562 (setq path (file-relative-name path)))
6564 (save-match-data
6565 (if (string-match (concat "^" (regexp-quote
6566 (file-name-as-directory
6567 (expand-file-name "."))))
6568 (expand-file-name path))
6569 ;; We are linking a file with relative path name.
6570 (setq path (substring (expand-file-name path)
6571 (match-end 0)))
6572 (setq path (abbreviate-file-name (expand-file-name path)))))))
6573 (setq link (concat "file:" path))
6574 (if (equal desc origpath)
6575 (setq desc path))))
6577 (if org-make-link-description-function
6578 (setq desc (funcall org-make-link-description-function link desc)))
6580 (setq desc (read-string "Description: " desc))
6581 (unless (string-match "\\S-" desc) (setq desc nil))
6582 (if remove (apply 'delete-region remove))
6583 (insert (org-make-link-string link desc))))
6585 (defun org-completing-read (&rest args)
6586 "Completing-read with SPACE being a normal character."
6587 (let ((minibuffer-local-completion-map
6588 (copy-keymap minibuffer-local-completion-map)))
6589 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6590 (apply 'org-ido-completing-read args)))
6592 (defun org-ido-completing-read (&rest args)
6593 "Completing-read using `ido-mode' speedups if available"
6594 (if (and org-completion-use-ido
6595 (fboundp 'ido-completing-read)
6596 (boundp 'ido-mode) ido-mode
6597 (listp (second args)))
6598 (apply 'ido-completing-read (concat (car args)) (cdr args))
6599 (apply 'completing-read args)))
6601 (defun org-extract-attributes (s)
6602 "Extract the attributes cookie from a string and set as text property."
6603 (let (a attr (start 0) key value)
6604 (save-match-data
6605 (when (string-match "{{\\([^}]+\\)}}$" s)
6606 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6607 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6608 (setq key (match-string 1 a) value (match-string 2 a)
6609 start (match-end 0)
6610 attr (plist-put attr (intern key) value))))
6611 (org-add-props s nil 'org-attributes attr))
6614 (defun org-attributes-to-string (plist)
6615 "Format a property list into an HTML attribute list."
6616 (let ((s "") key value)
6617 (while plist
6618 (setq key (pop plist) value (pop plist))
6619 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6622 ;;; Opening/following a link
6624 (defvar org-link-search-failed nil)
6626 (defun org-next-link ()
6627 "Move forward to the next link.
6628 If the link is in hidden text, expose it."
6629 (interactive)
6630 (when (and org-link-search-failed (eq this-command last-command))
6631 (goto-char (point-min))
6632 (message "Link search wrapped back to beginning of buffer"))
6633 (setq org-link-search-failed nil)
6634 (let* ((pos (point))
6635 (ct (org-context))
6636 (a (assoc :link ct)))
6637 (if a (goto-char (nth 2 a)))
6638 (if (re-search-forward org-any-link-re nil t)
6639 (progn
6640 (goto-char (match-beginning 0))
6641 (if (org-invisible-p) (org-show-context)))
6642 (goto-char pos)
6643 (setq org-link-search-failed t)
6644 (error "No further link found"))))
6646 (defun org-previous-link ()
6647 "Move backward to the previous link.
6648 If the link is in hidden text, expose it."
6649 (interactive)
6650 (when (and org-link-search-failed (eq this-command last-command))
6651 (goto-char (point-max))
6652 (message "Link search wrapped back to end of buffer"))
6653 (setq org-link-search-failed nil)
6654 (let* ((pos (point))
6655 (ct (org-context))
6656 (a (assoc :link ct)))
6657 (if a (goto-char (nth 1 a)))
6658 (if (re-search-backward org-any-link-re nil t)
6659 (progn
6660 (goto-char (match-beginning 0))
6661 (if (org-invisible-p) (org-show-context)))
6662 (goto-char pos)
6663 (setq org-link-search-failed t)
6664 (error "No further link found"))))
6666 (defun org-translate-link (s)
6667 "Translate a link string if a translation function has been defined."
6668 (if (and org-link-translation-function
6669 (fboundp org-link-translation-function)
6670 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6671 (progn
6672 (setq s (funcall org-link-translation-function
6673 (match-string 1) (match-string 2)))
6674 (concat (car s) ":" (cdr s)))
6677 (defun org-translate-link-from-planner (type path)
6678 "Translate a link from Emacs Planner syntax so that Org can follow it.
6679 This is still an experimental function, your mileage may vary."
6680 (cond
6681 ((member type '("http" "https" "news" "ftp"))
6682 ;; standard Internet links are the same.
6683 nil)
6684 ((and (equal type "irc") (string-match "^//" path))
6685 ;; Planner has two / at the beginning of an irc link, we have 1.
6686 ;; We should have zero, actually....
6687 (setq path (substring path 1)))
6688 ((and (equal type "lisp") (string-match "^/" path))
6689 ;; Planner has a slash, we do not.
6690 (setq type "elisp" path (substring path 1)))
6691 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6692 ;; A typical message link. Planner has the id after the fina slash,
6693 ;; we separate it with a hash mark
6694 (setq path (concat (match-string 1 path) "#"
6695 (org-remove-angle-brackets (match-string 2 path)))))
6697 (cons type path))
6699 (defun org-find-file-at-mouse (ev)
6700 "Open file link or URL at mouse."
6701 (interactive "e")
6702 (mouse-set-point ev)
6703 (org-open-at-point 'in-emacs))
6705 (defun org-open-at-mouse (ev)
6706 "Open file link or URL at mouse."
6707 (interactive "e")
6708 (mouse-set-point ev)
6709 (if (eq major-mode 'org-agenda-mode)
6710 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6711 (org-open-at-point))
6713 (defvar org-window-config-before-follow-link nil
6714 "The window configuration before following a link.
6715 This is saved in case the need arises to restore it.")
6717 (defvar org-open-link-marker (make-marker)
6718 "Marker pointing to the location where `org-open-at-point; was called.")
6720 ;;;###autoload
6721 (defun org-open-at-point-global ()
6722 "Follow a link like Org-mode does.
6723 This command can be called in any mode to follow a link that has
6724 Org-mode syntax."
6725 (interactive)
6726 (org-run-like-in-org-mode 'org-open-at-point))
6728 ;;;###autoload
6729 (defun org-open-link-from-string (s &optional arg)
6730 "Open a link in the string S, as if it was in Org-mode."
6731 (interactive "sLink: \nP")
6732 (with-temp-buffer
6733 (let ((org-inhibit-startup t))
6734 (org-mode)
6735 (insert s)
6736 (goto-char (point-min))
6737 (org-open-at-point arg))))
6739 (defun org-open-at-point (&optional in-emacs)
6740 "Open link at or after point.
6741 If there is no link at point, this function will search forward up to
6742 the end of the current subtree.
6743 Normally, files will be opened by an appropriate application. If the
6744 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6745 With a double prefix argument, try to open outside of Emacs, in the
6746 application the system uses for this file type."
6747 (interactive "P")
6748 (org-load-modules-maybe)
6749 (move-marker org-open-link-marker (point))
6750 (setq org-window-config-before-follow-link (current-window-configuration))
6751 (org-remove-occur-highlights nil nil t)
6752 (if (org-at-timestamp-p t)
6753 (org-follow-timestamp-link)
6754 (let (type path link line search (pos (point)))
6755 (catch 'match
6756 (save-excursion
6757 (skip-chars-forward "^]\n\r")
6758 (when (org-in-regexp org-bracket-link-regexp)
6759 (setq link (org-extract-attributes
6760 (org-link-unescape (org-match-string-no-properties 1))))
6761 (while (string-match " *\n *" link)
6762 (setq link (replace-match " " t t link)))
6763 (setq link (org-link-expand-abbrev link))
6764 (cond
6765 ((or (file-name-absolute-p link)
6766 (string-match "^\\.\\.?/" link))
6767 (setq type "file" path link))
6768 ((string-match org-link-re-with-space3 link)
6769 (setq type (match-string 1 link) path (match-string 2 link)))
6770 (t (setq type "thisfile" path link)))
6771 (throw 'match t)))
6773 (when (get-text-property (point) 'org-linked-text)
6774 (setq type "thisfile"
6775 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6776 (1+ (point)) (point))
6777 path (buffer-substring
6778 (previous-single-property-change pos 'org-linked-text)
6779 (next-single-property-change pos 'org-linked-text)))
6780 (throw 'match t))
6782 (save-excursion
6783 (when (or (org-in-regexp org-angle-link-re)
6784 (org-in-regexp org-plain-link-re))
6785 (setq type (match-string 1) path (match-string 2))
6786 (throw 'match t)))
6787 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6788 (setq type "tree-match"
6789 path (match-string 1))
6790 (throw 'match t))
6791 (save-excursion
6792 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6793 (setq type "tags"
6794 path (match-string 1))
6795 (while (string-match ":" path)
6796 (setq path (replace-match "+" t t path)))
6797 (throw 'match t))))
6798 (unless path
6799 (error "No link found"))
6800 ;; Remove any trailing spaces in path
6801 (if (string-match " +\\'" path)
6802 (setq path (replace-match "" t t path)))
6803 (if (and org-link-translation-function
6804 (fboundp org-link-translation-function))
6805 ;; Check if we need to translate the link
6806 (let ((tmp (funcall org-link-translation-function type path)))
6807 (setq type (car tmp) path (cdr tmp))))
6809 (cond
6811 ((assoc type org-link-protocols)
6812 (funcall (nth 1 (assoc type org-link-protocols)) path))
6814 ((equal type "mailto")
6815 (let ((cmd (car org-link-mailto-program))
6816 (args (cdr org-link-mailto-program)) args1
6817 (address path) (subject "") a)
6818 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6819 (setq address (match-string 1 path)
6820 subject (org-link-escape (match-string 2 path))))
6821 (while args
6822 (cond
6823 ((not (stringp (car args))) (push (pop args) args1))
6824 (t (setq a (pop args))
6825 (if (string-match "%a" a)
6826 (setq a (replace-match address t t a)))
6827 (if (string-match "%s" a)
6828 (setq a (replace-match subject t t a)))
6829 (push a args1))))
6830 (apply cmd (nreverse args1))))
6832 ((member type '("http" "https" "ftp" "news"))
6833 (browse-url (concat type ":" (org-link-escape
6834 path org-link-escape-chars-browser))))
6836 ((member type '("message"))
6837 (browse-url (concat type ":" path)))
6839 ((string= type "tags")
6840 (org-tags-view in-emacs path))
6841 ((string= type "thisfile")
6842 (if in-emacs
6843 (switch-to-buffer-other-window
6844 (org-get-buffer-for-internal-link (current-buffer)))
6845 (org-mark-ring-push))
6846 (let ((cmd `(org-link-search
6847 ,path
6848 ,(cond ((equal in-emacs '(4)) 'occur)
6849 ((equal in-emacs '(16)) 'org-occur)
6850 (t nil))
6851 ,pos)))
6852 (condition-case nil (eval cmd)
6853 (error (progn (widen) (eval cmd))))))
6855 ((string= type "tree-match")
6856 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6858 ((string= type "file")
6859 (if (string-match "::\\([0-9]+\\)\\'" path)
6860 (setq line (string-to-number (match-string 1 path))
6861 path (substring path 0 (match-beginning 0)))
6862 (if (string-match "::\\(.+\\)\\'" path)
6863 (setq search (match-string 1 path)
6864 path (substring path 0 (match-beginning 0)))))
6865 (if (string-match "[*?{]" (file-name-nondirectory path))
6866 (dired path)
6867 (org-open-file path in-emacs line search)))
6869 ((string= type "news")
6870 (require 'org-gnus)
6871 (org-gnus-follow-link path))
6873 ((string= type "shell")
6874 (let ((cmd path))
6875 (if (or (not org-confirm-shell-link-function)
6876 (funcall org-confirm-shell-link-function
6877 (format "Execute \"%s\" in shell? "
6878 (org-add-props cmd nil
6879 'face 'org-warning))))
6880 (progn
6881 (message "Executing %s" cmd)
6882 (shell-command cmd))
6883 (error "Abort"))))
6885 ((string= type "elisp")
6886 (let ((cmd path))
6887 (if (or (not org-confirm-elisp-link-function)
6888 (funcall org-confirm-elisp-link-function
6889 (format "Execute \"%s\" as elisp? "
6890 (org-add-props cmd nil
6891 'face 'org-warning))))
6892 (message "%s => %s" cmd
6893 (if (equal (string-to-char cmd) ?\()
6894 (eval (read cmd))
6895 (call-interactively (read cmd))))
6896 (error "Abort"))))
6899 (browse-url-at-point)))))
6900 (move-marker org-open-link-marker nil)
6901 (run-hook-with-args 'org-follow-link-hook))
6903 ;;;; Time estimates
6905 (defun org-get-effort (&optional pom)
6906 "Get the effort estimate for the current entry."
6907 (org-entry-get pom org-effort-property))
6909 ;;; File search
6911 (defvar org-create-file-search-functions nil
6912 "List of functions to construct the right search string for a file link.
6913 These functions are called in turn with point at the location to
6914 which the link should point.
6916 A function in the hook should first test if it would like to
6917 handle this file type, for example by checking the major-mode or
6918 the file extension. If it decides not to handle this file, it
6919 should just return nil to give other functions a chance. If it
6920 does handle the file, it must return the search string to be used
6921 when following the link. The search string will be part of the
6922 file link, given after a double colon, and `org-open-at-point'
6923 will automatically search for it. If special measures must be
6924 taken to make the search successful, another function should be
6925 added to the companion hook `org-execute-file-search-functions',
6926 which see.
6928 A function in this hook may also use `setq' to set the variable
6929 `description' to provide a suggestion for the descriptive text to
6930 be used for this link when it gets inserted into an Org-mode
6931 buffer with \\[org-insert-link].")
6933 (defvar org-execute-file-search-functions nil
6934 "List of functions to execute a file search triggered by a link.
6936 Functions added to this hook must accept a single argument, the
6937 search string that was part of the file link, the part after the
6938 double colon. The function must first check if it would like to
6939 handle this search, for example by checking the major-mode or the
6940 file extension. If it decides not to handle this search, it
6941 should just return nil to give other functions a chance. If it
6942 does handle the search, it must return a non-nil value to keep
6943 other functions from trying.
6945 Each function can access the current prefix argument through the
6946 variable `current-prefix-argument'. Note that a single prefix is
6947 used to force opening a link in Emacs, so it may be good to only
6948 use a numeric or double prefix to guide the search function.
6950 In case this is needed, a function in this hook can also restore
6951 the window configuration before `org-open-at-point' was called using:
6953 (set-window-configuration org-window-config-before-follow-link)")
6955 (defun org-link-search (s &optional type avoid-pos)
6956 "Search for a link search option.
6957 If S is surrounded by forward slashes, it is interpreted as a
6958 regular expression. In org-mode files, this will create an `org-occur'
6959 sparse tree. In ordinary files, `occur' will be used to list matches.
6960 If the current buffer is in `dired-mode', grep will be used to search
6961 in all files. If AVOID-POS is given, ignore matches near that position."
6962 (let ((case-fold-search t)
6963 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6964 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6965 (append '(("") (" ") ("\t") ("\n"))
6966 org-emphasis-alist)
6967 "\\|") "\\)"))
6968 (pos (point))
6969 (pre nil) (post nil)
6970 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6971 (cond
6972 ;; First check if there are any special
6973 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6974 ;; Now try the builtin stuff
6975 ((save-excursion
6976 (goto-char (point-min))
6977 (and
6978 (re-search-forward
6979 (concat "<<" (regexp-quote s0) ">>") nil t)
6980 (setq type 'dedicated
6981 pos (match-beginning 0))))
6982 ;; There is an exact target for this
6983 (goto-char pos))
6984 ((string-match "^/\\(.*\\)/$" s)
6985 ;; A regular expression
6986 (cond
6987 ((org-mode-p)
6988 (org-occur (match-string 1 s)))
6989 ;;((eq major-mode 'dired-mode)
6990 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6991 (t (org-do-occur (match-string 1 s)))))
6993 ;; A normal search strings
6994 (when (equal (string-to-char s) ?*)
6995 ;; Anchor on headlines, post may include tags.
6996 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6997 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6998 s (substring s 1)))
6999 (remove-text-properties
7000 0 (length s)
7001 '(face nil mouse-face nil keymap nil fontified nil) s)
7002 ;; Make a series of regular expressions to find a match
7003 (setq words (org-split-string s "[ \n\r\t]+")
7005 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7006 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7007 "\\)" markers)
7008 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7009 re2a (concat "[ \t\r\n]" re2a_)
7010 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7011 re4 (concat "[^a-zA-Z_]" re4_)
7013 re1 (concat pre re2 post)
7014 re3 (concat pre (if pre re4_ re4) post)
7015 re5 (concat pre ".*" re4)
7016 re2 (concat pre re2)
7017 re2a (concat pre (if pre re2a_ re2a))
7018 re4 (concat pre (if pre re4_ re4))
7019 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7020 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7021 re5 "\\)"
7023 (cond
7024 ((eq type 'org-occur) (org-occur reall))
7025 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7026 (t (goto-char (point-min))
7027 (setq type 'fuzzy)
7028 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7029 (org-search-not-self 1 re1 nil t)
7030 (org-search-not-self 1 re2 nil t)
7031 (org-search-not-self 1 re2a nil t)
7032 (org-search-not-self 1 re3 nil t)
7033 (org-search-not-self 1 re4 nil t)
7034 (org-search-not-self 1 re5 nil t)
7036 (goto-char (match-beginning 1))
7037 (goto-char pos)
7038 (error "No match")))))
7040 ;; Normal string-search
7041 (goto-char (point-min))
7042 (if (search-forward s nil t)
7043 (goto-char (match-beginning 0))
7044 (error "No match"))))
7045 (and (org-mode-p) (org-show-context 'link-search))
7046 type))
7048 (defun org-search-not-self (group &rest args)
7049 "Execute `re-search-forward', but only accept matches that do not
7050 enclose the position of `org-open-link-marker'."
7051 (let ((m org-open-link-marker))
7052 (catch 'exit
7053 (while (apply 're-search-forward args)
7054 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7055 (goto-char (match-end group))
7056 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7057 (> (match-beginning 0) (marker-position m))
7058 (< (match-end 0) (marker-position m)))
7059 (save-match-data
7060 (or (not (org-in-regexp
7061 org-bracket-link-analytic-regexp 1))
7062 (not (match-end 4)) ; no description
7063 (and (<= (match-beginning 4) (point))
7064 (>= (match-end 4) (point))))))
7065 (throw 'exit (point))))))))
7067 (defun org-get-buffer-for-internal-link (buffer)
7068 "Return a buffer to be used for displaying the link target of internal links."
7069 (cond
7070 ((not org-display-internal-link-with-indirect-buffer)
7071 buffer)
7072 ((string-match "(Clone)$" (buffer-name buffer))
7073 (message "Buffer is already a clone, not making another one")
7074 ;; we also do not modify visibility in this case
7075 buffer)
7076 (t ; make a new indirect buffer for displaying the link
7077 (let* ((bn (buffer-name buffer))
7078 (ibn (concat bn "(Clone)"))
7079 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7080 (with-current-buffer ib (org-overview))
7081 ib))))
7083 (defun org-do-occur (regexp &optional cleanup)
7084 "Call the Emacs command `occur'.
7085 If CLEANUP is non-nil, remove the printout of the regular expression
7086 in the *Occur* buffer. This is useful if the regex is long and not useful
7087 to read."
7088 (occur regexp)
7089 (when cleanup
7090 (let ((cwin (selected-window)) win beg end)
7091 (when (setq win (get-buffer-window "*Occur*"))
7092 (select-window win))
7093 (goto-char (point-min))
7094 (when (re-search-forward "match[a-z]+" nil t)
7095 (setq beg (match-end 0))
7096 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7097 (setq end (1- (match-beginning 0)))))
7098 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7099 (goto-char (point-min))
7100 (select-window cwin))))
7102 ;;; The mark ring for links jumps
7104 (defvar org-mark-ring nil
7105 "Mark ring for positions before jumps in Org-mode.")
7106 (defvar org-mark-ring-last-goto nil
7107 "Last position in the mark ring used to go back.")
7108 ;; Fill and close the ring
7109 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7110 (loop for i from 1 to org-mark-ring-length do
7111 (push (make-marker) org-mark-ring))
7112 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7113 org-mark-ring)
7115 (defun org-mark-ring-push (&optional pos buffer)
7116 "Put the current position or POS into the mark ring and rotate it."
7117 (interactive)
7118 (setq pos (or pos (point)))
7119 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7120 (move-marker (car org-mark-ring)
7121 (or pos (point))
7122 (or buffer (current-buffer)))
7123 (message "%s"
7124 (substitute-command-keys
7125 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7127 (defun org-mark-ring-goto (&optional n)
7128 "Jump to the previous position in the mark ring.
7129 With prefix arg N, jump back that many stored positions. When
7130 called several times in succession, walk through the entire ring.
7131 Org-mode commands jumping to a different position in the current file,
7132 or to another Org-mode file, automatically push the old position
7133 onto the ring."
7134 (interactive "p")
7135 (let (p m)
7136 (if (eq last-command this-command)
7137 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7138 (setq p org-mark-ring))
7139 (setq org-mark-ring-last-goto p)
7140 (setq m (car p))
7141 (switch-to-buffer (marker-buffer m))
7142 (goto-char m)
7143 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7145 (defun org-remove-angle-brackets (s)
7146 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7147 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7149 (defun org-add-angle-brackets (s)
7150 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7151 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7153 (defun org-remove-double-quotes (s)
7154 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7155 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7158 ;;; Following specific links
7160 (defun org-follow-timestamp-link ()
7161 (cond
7162 ((org-at-date-range-p t)
7163 (let ((org-agenda-start-on-weekday)
7164 (t1 (match-string 1))
7165 (t2 (match-string 2)))
7166 (setq t1 (time-to-days (org-time-string-to-time t1))
7167 t2 (time-to-days (org-time-string-to-time t2)))
7168 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7169 ((org-at-timestamp-p t)
7170 (org-agenda-list nil (time-to-days (org-time-string-to-time
7171 (substring (match-string 1) 0 10)))
7173 (t (error "This should not happen"))))
7176 ;;; Following file links
7177 (defvar org-wait nil)
7178 (defun org-open-file (path &optional in-emacs line search)
7179 "Open the file at PATH.
7180 First, this expands any special file name abbreviations. Then the
7181 configuration variable `org-file-apps' is checked if it contains an
7182 entry for this file type, and if yes, the corresponding command is launched.
7184 If no application is found, Emacs simply visits the file.
7186 With optional prefix argument IN-EMACS, Emacs will visit the file.
7187 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7188 and o use an external application to visit the file.
7190 Optional LINE specifies a line to go to, optional SEARCH a string to
7191 search for. If LINE or SEARCH is given, the file will always be
7192 opened in Emacs.
7193 If the file does not exist, an error is thrown."
7194 (setq in-emacs (or in-emacs line search))
7195 (let* ((file (if (equal path "")
7196 buffer-file-name
7197 (substitute-in-file-name (expand-file-name path))))
7198 (apps (append org-file-apps (org-default-apps)))
7199 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7200 (dirp (if remp nil (file-directory-p file)))
7201 (file (if (and dirp org-open-directory-means-index-dot-org)
7202 (concat (file-name-as-directory file) "index.org")
7203 file))
7204 (a-m-a-p (assq 'auto-mode apps))
7205 (dfile (downcase file))
7206 (old-buffer (current-buffer))
7207 (old-pos (point))
7208 (old-mode major-mode)
7209 ext cmd)
7210 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7211 (setq ext (match-string 1 dfile))
7212 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7213 (setq ext (match-string 1 dfile))))
7214 (cond
7215 ((equal in-emacs '(16))
7216 (setq cmd (cdr (assoc 'system apps))))
7217 (in-emacs (setq cmd 'emacs))
7219 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7220 (and dirp (cdr (assoc 'directory apps)))
7221 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7222 'string-match)
7223 (cdr (assoc ext apps))
7224 (cdr (assoc t apps))))))
7225 (when (eq cmd 'system)
7226 (setq cmd (cdr (assoc 'system apps))))
7227 (when (eq cmd 'default)
7228 (setq cmd (cdr (assoc t apps))))
7229 (when (eq cmd 'mailcap)
7230 (require 'mailcap)
7231 (mailcap-parse-mailcaps)
7232 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7233 (command (mailcap-mime-info mime-type)))
7234 (if (stringp command)
7235 (setq cmd command)
7236 (setq cmd 'emacs))))
7237 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7238 (not (file-exists-p file))
7239 (not org-open-non-existing-files))
7240 (error "No such file: %s" file))
7241 (cond
7242 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7243 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7244 (while (string-match "['\"]%s['\"]" cmd)
7245 (setq cmd (replace-match "%s" t t cmd)))
7246 (while (string-match "%s" cmd)
7247 (setq cmd (replace-match
7248 (save-match-data
7249 (shell-quote-argument
7250 (convert-standard-filename file)))
7251 t t cmd)))
7252 (save-window-excursion
7253 (start-process-shell-command cmd nil cmd)
7254 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7256 ((or (stringp cmd)
7257 (eq cmd 'emacs))
7258 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7259 (widen)
7260 (if line (goto-line line)
7261 (if search (org-link-search search))))
7262 ((consp cmd)
7263 (let ((file (convert-standard-filename file)))
7264 (eval cmd)))
7265 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7266 (and (org-mode-p) (eq old-mode 'org-mode)
7267 (or (not (equal old-buffer (current-buffer)))
7268 (not (equal old-pos (point))))
7269 (org-mark-ring-push old-pos old-buffer))))
7271 (defun org-default-apps ()
7272 "Return the default applications for this operating system."
7273 (cond
7274 ((eq system-type 'darwin)
7275 org-file-apps-defaults-macosx)
7276 ((eq system-type 'windows-nt)
7277 org-file-apps-defaults-windowsnt)
7278 (t org-file-apps-defaults-gnu)))
7280 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7281 "Convert extensions to regular expressions in the cars of LIST.
7282 Also, weed out any non-string entries, because the return value is used
7283 only for regexp matching.
7284 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7285 point to the symbol `emacs', indicating that the file should
7286 be opened in Emacs."
7287 (append
7288 (delq nil
7289 (mapcar (lambda (x)
7290 (if (not (stringp (car x)))
7292 (if (string-match "\\W" (car x))
7294 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7295 list))
7296 (if add-auto-mode
7297 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7299 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7300 (defun org-file-remote-p (file)
7301 "Test whether FILE specifies a location on a remote system.
7302 Return non-nil if the location is indeed remote.
7304 For example, the filename \"/user@host:/foo\" specifies a location
7305 on the system \"/user@host:\"."
7306 (cond ((fboundp 'file-remote-p)
7307 (file-remote-p file))
7308 ((fboundp 'tramp-handle-file-remote-p)
7309 (tramp-handle-file-remote-p file))
7310 ((and (boundp 'ange-ftp-name-format)
7311 (string-match (car ange-ftp-name-format) file))
7313 (t nil)))
7316 ;;;; Refiling
7318 (defun org-get-org-file ()
7319 "Read a filename, with default directory `org-directory'."
7320 (let ((default (or org-default-notes-file remember-data-file)))
7321 (read-file-name (format "File name [%s]: " default)
7322 (file-name-as-directory org-directory)
7323 default)))
7325 (defun org-notes-order-reversed-p ()
7326 "Check if the current file should receive notes in reversed order."
7327 (cond
7328 ((not org-reverse-note-order) nil)
7329 ((eq t org-reverse-note-order) t)
7330 ((not (listp org-reverse-note-order)) nil)
7331 (t (catch 'exit
7332 (let ((all org-reverse-note-order)
7333 entry)
7334 (while (setq entry (pop all))
7335 (if (string-match (car entry) buffer-file-name)
7336 (throw 'exit (cdr entry))))
7337 nil)))))
7339 (defvar org-refile-target-table nil
7340 "The list of refile targets, created by `org-refile'.")
7342 (defvar org-agenda-new-buffers nil
7343 "Buffers created to visit agenda files.")
7345 (defun org-get-refile-targets (&optional default-buffer)
7346 "Produce a table with refile targets."
7347 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7348 targets txt re files f desc descre)
7349 (with-current-buffer (or default-buffer (current-buffer))
7350 (while (setq entry (pop entries))
7351 (setq files (car entry) desc (cdr entry))
7352 (cond
7353 ((null files) (setq files (list (current-buffer))))
7354 ((eq files 'org-agenda-files)
7355 (setq files (org-agenda-files 'unrestricted)))
7356 ((and (symbolp files) (fboundp files))
7357 (setq files (funcall files)))
7358 ((and (symbolp files) (boundp files))
7359 (setq files (symbol-value files))))
7360 (if (stringp files) (setq files (list files)))
7361 (cond
7362 ((eq (car desc) :tag)
7363 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7364 ((eq (car desc) :todo)
7365 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7366 ((eq (car desc) :regexp)
7367 (setq descre (cdr desc)))
7368 ((eq (car desc) :level)
7369 (setq descre (concat "^\\*\\{" (number-to-string
7370 (if org-odd-levels-only
7371 (1- (* 2 (cdr desc)))
7372 (cdr desc)))
7373 "\\}[ \t]")))
7374 ((eq (car desc) :maxlevel)
7375 (setq descre (concat "^\\*\\{1," (number-to-string
7376 (if org-odd-levels-only
7377 (1- (* 2 (cdr desc)))
7378 (cdr desc)))
7379 "\\}[ \t]")))
7380 (t (error "Bad refiling target description %s" desc)))
7381 (while (setq f (pop files))
7382 (save-excursion
7383 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7384 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7385 (save-excursion
7386 (save-restriction
7387 (widen)
7388 (goto-char (point-min))
7389 (while (re-search-forward descre nil t)
7390 (goto-char (point-at-bol))
7391 (when (looking-at org-complex-heading-regexp)
7392 (setq txt (org-link-display-format (match-string 4))
7393 re (concat "^" (regexp-quote
7394 (buffer-substring (match-beginning 1)
7395 (match-end 4)))))
7396 (if (match-end 5) (setq re (concat re "[ \t]+"
7397 (regexp-quote
7398 (match-string 5)))))
7399 (setq re (concat re "[ \t]*$"))
7400 (when org-refile-use-outline-path
7401 (setq txt (mapconcat 'org-protect-slash
7402 (append
7403 (if (eq org-refile-use-outline-path 'file)
7404 (list (file-name-nondirectory
7405 (buffer-file-name (buffer-base-buffer))))
7406 (if (eq org-refile-use-outline-path 'full-file-path)
7407 (list (buffer-file-name (buffer-base-buffer)))))
7408 (org-get-outline-path)
7409 (list txt))
7410 "/")))
7411 (push (list txt f re (point)) targets))
7412 (goto-char (point-at-eol))))))))
7413 (nreverse targets))))
7415 (defun org-protect-slash (s)
7416 (while (string-match "/" s)
7417 (setq s (replace-match "\\" t t s)))
7420 (defun org-get-outline-path ()
7421 "Return the outline path to the current entry, as a list."
7422 (let (rtn)
7423 (save-excursion
7424 (while (org-up-heading-safe)
7425 (when (looking-at org-complex-heading-regexp)
7426 (push (org-match-string-no-properties 4) rtn)))
7427 rtn)))
7429 (defvar org-refile-history nil
7430 "History for refiling operations.")
7432 (defun org-refile (&optional goto default-buffer)
7433 "Move the entry at point to another heading.
7434 The list of target headings is compiled using the information in
7435 `org-refile-targets', which see. This list is created before each use
7436 and will therefore always be up-to-date.
7438 At the target location, the entry is filed as a subitem of the target heading.
7439 Depending on `org-reverse-note-order', the new subitem will either be the
7440 first or the last subitem.
7442 If there is an active region, all entries in that region will be moved.
7443 However, the region must fulfil the requirement that the first heading
7444 is the first one sets the top-level of the moved text - at most siblings
7445 below it are allowed.
7447 With prefix arg GOTO, the command will only visit the target location,
7448 not actually move anything.
7449 With a double prefix `C-u C-u', go to the location where the last refiling
7450 operation has put the subtree."
7451 (interactive "P")
7452 (let* ((cbuf (current-buffer))
7453 (regionp (org-region-active-p))
7454 (region-start (and regionp (region-beginning)))
7455 (region-end (and regionp (region-end)))
7456 (region-length (and regionp (- region-end region-start)))
7457 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7458 pos it nbuf file re level reversed)
7459 (when regionp (goto-char region-start)
7460 (unless (org-kill-is-subtree-p
7461 (buffer-substring region-start region-end))
7462 (error "The region is not a (sequence of) subtree(s)")))
7463 (if (equal goto '(16))
7464 (org-refile-goto-last-stored)
7465 (when (setq it (org-refile-get-location
7466 (if goto "Goto: " "Refile to: ") default-buffer))
7467 (setq file (nth 1 it)
7468 re (nth 2 it)
7469 pos (nth 3 it))
7470 (setq nbuf (or (find-buffer-visiting file)
7471 (find-file-noselect file)))
7472 (if goto
7473 (progn
7474 (switch-to-buffer nbuf)
7475 (goto-char pos)
7476 (org-show-context 'org-goto))
7477 (if regionp
7478 (progn
7479 (kill-new (buffer-substring region-start region-end))
7480 (org-save-markers-in-region region-start region-end))
7481 (org-copy-subtree 1 nil t))
7482 (save-excursion
7483 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7484 (find-file-noselect file))))
7485 (setq reversed (org-notes-order-reversed-p))
7486 (save-excursion
7487 (save-restriction
7488 (widen)
7489 (goto-char pos)
7490 (looking-at outline-regexp)
7491 (setq level (org-get-valid-level (funcall outline-level) 1))
7492 (goto-char
7493 (if reversed
7494 (or (outline-next-heading) (point-max))
7495 (or (save-excursion (outline-get-next-sibling))
7496 (org-end-of-subtree t t)
7497 (point-max))))
7498 (if (not (bolp)) (newline))
7499 (bookmark-set "org-refile-last-stored")
7500 (org-paste-subtree level))))
7501 (if regionp
7502 (delete-region (point) (+ (point) region-length))
7503 (org-cut-subtree))
7504 (setq org-markers-to-move nil)
7505 (message "Refiled to \"%s\"" (car it)))))))
7507 (defun org-refile-goto-last-stored ()
7508 "Go to the location where the last refile was stored."
7509 (interactive)
7510 (bookmark-jump "org-refile-last-stored")
7511 (message "This is the location of the last refile"))
7513 (defun org-refile-get-location (&optional prompt default-buffer)
7514 "Prompt the user for a refile location, using PROMPT."
7515 (let ((org-refile-targets org-refile-targets)
7516 (org-refile-use-outline-path org-refile-use-outline-path))
7517 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7518 (unless org-refile-target-table
7519 (error "No refile targets"))
7520 (let* ((cbuf (current-buffer))
7521 (cfunc (if (and org-refile-use-outline-path
7522 org-outline-path-complete-in-steps)
7523 'org-olpath-completing-read
7524 'org-ido-completing-read))
7525 (extra (if org-refile-use-outline-path "/" ""))
7526 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7527 (fname (and filename (file-truename filename)))
7528 (tbl (mapcar
7529 (lambda (x)
7530 (if (not (equal fname (file-truename (nth 1 x))))
7531 (cons (concat (car x) extra " ("
7532 (file-name-nondirectory (nth 1 x)) ")")
7533 (cdr x))
7534 (cons (concat (car x) extra) (cdr x))))
7535 org-refile-target-table))
7536 (completion-ignore-case t))
7537 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7538 tbl)))
7540 (defun org-olpath-completing-read (prompt collection &rest args)
7541 "Read an outline path like a file name."
7542 (let ((thetable collection))
7543 (apply
7544 'org-ido-completing-read prompt
7545 (lambda (string predicate &optional flag)
7546 (let (rtn r s f (l (length string)))
7547 (cond
7548 ((eq flag nil)
7549 ;; try completion
7550 (try-completion string thetable))
7551 ((eq flag t)
7552 ;; all-completions
7553 (setq rtn (all-completions string thetable predicate))
7554 (mapcar
7555 (lambda (x)
7556 (setq r (substring x l))
7557 (if (string-match " ([^)]*)$" x)
7558 (setq f (match-string 0 x))
7559 (setq f ""))
7560 (if (string-match "/" r)
7561 (concat string (substring r 0 (match-end 0)) f)
7563 rtn))
7564 ((eq flag 'lambda)
7565 ;; exact match?
7566 (assoc string thetable)))
7568 args)))
7570 ;;;; Dynamic blocks
7572 (defun org-find-dblock (name)
7573 "Find the first dynamic block with name NAME in the buffer.
7574 If not found, stay at current position and return nil."
7575 (let (pos)
7576 (save-excursion
7577 (goto-char (point-min))
7578 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7579 nil t)
7580 (match-beginning 0))))
7581 (if pos (goto-char pos))
7582 pos))
7584 (defconst org-dblock-start-re
7585 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7586 "Matches the startline of a dynamic block, with parameters.")
7588 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7589 "Matches the end of a dyhamic block.")
7591 (defun org-create-dblock (plist)
7592 "Create a dynamic block section, with parameters taken from PLIST.
7593 PLIST must containe a :name entry which is used as name of the block."
7594 (unless (bolp) (newline))
7595 (let ((name (plist-get plist :name)))
7596 (insert "#+BEGIN: " name)
7597 (while plist
7598 (if (eq (car plist) :name)
7599 (setq plist (cddr plist))
7600 (insert " " (prin1-to-string (pop plist)))))
7601 (insert "\n\n#+END:\n")
7602 (beginning-of-line -2)))
7604 (defun org-prepare-dblock ()
7605 "Prepare dynamic block for refresh.
7606 This empties the block, puts the cursor at the insert position and returns
7607 the property list including an extra property :name with the block name."
7608 (unless (looking-at org-dblock-start-re)
7609 (error "Not at a dynamic block"))
7610 (let* ((begdel (1+ (match-end 0)))
7611 (name (org-no-properties (match-string 1)))
7612 (params (append (list :name name)
7613 (read (concat "(" (match-string 3) ")")))))
7614 (unless (re-search-forward org-dblock-end-re nil t)
7615 (error "Dynamic block not terminated"))
7616 (setq params
7617 (append params
7618 (list :content (buffer-substring
7619 begdel (match-beginning 0)))))
7620 (delete-region begdel (match-beginning 0))
7621 (goto-char begdel)
7622 (open-line 1)
7623 params))
7625 (defun org-map-dblocks (&optional command)
7626 "Apply COMMAND to all dynamic blocks in the current buffer.
7627 If COMMAND is not given, use `org-update-dblock'."
7628 (let ((cmd (or command 'org-update-dblock))
7629 pos)
7630 (save-excursion
7631 (goto-char (point-min))
7632 (while (re-search-forward org-dblock-start-re nil t)
7633 (goto-char (setq pos (match-beginning 0)))
7634 (condition-case nil
7635 (funcall cmd)
7636 (error (message "Error during update of dynamic block")))
7637 (goto-char pos)
7638 (unless (re-search-forward org-dblock-end-re nil t)
7639 (error "Dynamic block not terminated"))))))
7641 (defun org-dblock-update (&optional arg)
7642 "User command for updating dynamic blocks.
7643 Update the dynamic block at point. With prefix ARG, update all dynamic
7644 blocks in the buffer."
7645 (interactive "P")
7646 (if arg
7647 (org-update-all-dblocks)
7648 (or (looking-at org-dblock-start-re)
7649 (org-beginning-of-dblock))
7650 (org-update-dblock)))
7652 (defun org-update-dblock ()
7653 "Update the dynamic block at point
7654 This means to empty the block, parse for parameters and then call
7655 the correct writing function."
7656 (save-window-excursion
7657 (let* ((pos (point))
7658 (line (org-current-line))
7659 (params (org-prepare-dblock))
7660 (name (plist-get params :name))
7661 (cmd (intern (concat "org-dblock-write:" name))))
7662 (message "Updating dynamic block `%s' at line %d..." name line)
7663 (funcall cmd params)
7664 (message "Updating dynamic block `%s' at line %d...done" name line)
7665 (goto-char pos))))
7667 (defun org-beginning-of-dblock ()
7668 "Find the beginning of the dynamic block at point.
7669 Error if there is no scuh block at point."
7670 (let ((pos (point))
7671 beg)
7672 (end-of-line 1)
7673 (if (and (re-search-backward org-dblock-start-re nil t)
7674 (setq beg (match-beginning 0))
7675 (re-search-forward org-dblock-end-re nil t)
7676 (> (match-end 0) pos))
7677 (goto-char beg)
7678 (goto-char pos)
7679 (error "Not in a dynamic block"))))
7681 (defun org-update-all-dblocks ()
7682 "Update all dynamic blocks in the buffer.
7683 This function can be used in a hook."
7684 (when (org-mode-p)
7685 (org-map-dblocks 'org-update-dblock)))
7688 ;;;; Completion
7690 (defconst org-additional-option-like-keywords
7691 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7692 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7693 "BEGIN_EXAMPLE" "END_EXAMPLE"
7694 "BEGIN_QUOTE" "END_QUOTE"
7695 "BEGIN_VERSE" "END_VERSE"
7696 "BEGIN_SRC" "END_SRC"))
7698 (defcustom org-structure-template-alist
7700 ("s" "#+begin_src ?\n\n#+end_src"
7701 "<src lang=\"?\">\n\n</src>")
7702 ("e" "#+begin_example\n?\n#+end_example"
7703 "<example>\n?\n</example>")
7704 ("q" "#+begin_quote\n?\n#+end_quote"
7705 "<quote>\n?\n</quote>")
7706 ("v" "#+begin_verse\n?\n#+end_verse"
7707 "<verse>\n?\n/verse>")
7708 ("l" "#+begin_latex\n?\n#+end_latex"
7709 "<literal style=\"latex\">\n?\n</literal>")
7710 ("L" "#+latex: "
7711 "<literal style=\"latex\">?</literal>")
7712 ("h" "#+begin_html\n?\n#+end_html"
7713 "<literal style=\"html\">\n?\n</literal>")
7714 ("H" "#+html: "
7715 "<literal style=\"html\">?</literal>")
7716 ("a" "#+begin_ascii\n?\n#+end_ascii")
7717 ("A" "#+ascii: ")
7718 ("i" "#+include %file ?"
7719 "<include file=%file markup=\"?\">")
7721 "Structure completion elements.
7722 This is a list of abbreviation keys and values. The value gets inserted
7723 it you type @samp{.} followed by the key and then the completion key,
7724 usually `M-TAB'. %file will be replaced by a file name after prompting
7725 for the file uning completion.
7726 There are two templates for each key, the first uses the original Org syntax,
7727 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7728 the default when the /org-mtags.el/ module has been loaded. See also the
7729 variable `org-mtags-prefer-muse-templates'.
7730 This is an experimental feature, it is undecided if it is going to stay in."
7731 :group 'org-completion
7732 :type '(repeat
7733 (string :tag "Key")
7734 (string :tag "Template")
7735 (string :tag "Muse Template")))
7737 (defun org-try-structure-completion ()
7738 "Try to complete a structure template before point.
7739 This looks for strings like \"<e\" on an otherwise empty line and
7740 expands them."
7741 (let ((l (buffer-substring (point-at-bol) (point)))
7743 (when (and (looking-at "[ \t]*$")
7744 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7745 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7746 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7747 (match-beginning 1)) a)
7748 t)))
7750 (defun org-complete-expand-structure-template (start cell)
7751 "Expand a structure template."
7752 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7753 (rpl (nth (if musep 2 1) cell)))
7754 (delete-region start (point))
7755 (when (string-match "\\`#\\+" rpl)
7756 (cond
7757 ((bolp))
7758 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7759 (delete-region (point-at-bol) (point)))
7760 (t (newline))))
7761 (setq start (point))
7762 (if (string-match "%file" rpl)
7763 (setq rpl (replace-match
7764 (concat
7765 "\""
7766 (save-match-data
7767 (abbreviate-file-name (read-file-name "Include file: ")))
7768 "\"")
7769 t t rpl)))
7770 (insert rpl)
7771 (if (re-search-backward "\\?" start t) (delete-char 1))))
7774 (defun org-complete (&optional arg)
7775 "Perform completion on word at point.
7776 At the beginning of a headline, this completes TODO keywords as given in
7777 `org-todo-keywords'.
7778 If the current word is preceded by a backslash, completes the TeX symbols
7779 that are supported for HTML support.
7780 If the current word is preceded by \"#+\", completes special words for
7781 setting file options.
7782 In the line after \"#+STARTUP:, complete valid keywords.\"
7783 At all other locations, this simply calls the value of
7784 `org-completion-fallback-command'."
7785 (interactive "P")
7786 (org-without-partial-completion
7787 (catch 'exit
7788 (let* ((a nil)
7789 (end (point))
7790 (beg1 (save-excursion
7791 (skip-chars-backward (org-re "[:alnum:]_@"))
7792 (point)))
7793 (beg (save-excursion
7794 (skip-chars-backward "a-zA-Z0-9_:$")
7795 (point)))
7796 (confirm (lambda (x) (stringp (car x))))
7797 (searchhead (equal (char-before beg) ?*))
7798 (struct
7799 (when (and (member (char-before beg1) '(?. ?<))
7800 (setq a (assoc (buffer-substring beg1 (point))
7801 org-structure-template-alist)))
7802 (org-complete-expand-structure-template (1- beg1) a)
7803 (throw 'exit t)))
7804 (tag (and (equal (char-before beg1) ?:)
7805 (equal (char-after (point-at-bol)) ?*)))
7806 (prop (and (equal (char-before beg1) ?:)
7807 (not (equal (char-after (point-at-bol)) ?*))))
7808 (texp (equal (char-before beg) ?\\))
7809 (link (equal (char-before beg) ?\[))
7810 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7811 beg)
7812 "#+"))
7813 (startup (string-match "^#\\+STARTUP:.*"
7814 (buffer-substring (point-at-bol) (point))))
7815 (completion-ignore-case opt)
7816 (type nil)
7817 (tbl nil)
7818 (table (cond
7819 (opt
7820 (setq type :opt)
7821 (require 'org-exp)
7822 (append
7823 (mapcar
7824 (lambda (x)
7825 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7826 (cons (match-string 2 x) (match-string 1 x)))
7827 (org-split-string (org-get-current-options) "\n"))
7828 (mapcar 'list org-additional-option-like-keywords)))
7829 (startup
7830 (setq type :startup)
7831 org-startup-options)
7832 (link (append org-link-abbrev-alist-local
7833 org-link-abbrev-alist))
7834 (texp
7835 (setq type :tex)
7836 org-html-entities)
7837 ((string-match "\\`\\*+[ \t]+\\'"
7838 (buffer-substring (point-at-bol) beg))
7839 (setq type :todo)
7840 (mapcar 'list org-todo-keywords-1))
7841 (searchhead
7842 (setq type :searchhead)
7843 (save-excursion
7844 (goto-char (point-min))
7845 (while (re-search-forward org-todo-line-regexp nil t)
7846 (push (list
7847 (org-make-org-heading-search-string
7848 (match-string 3) t))
7849 tbl)))
7850 tbl)
7851 (tag (setq type :tag beg beg1)
7852 (or org-tag-alist (org-get-buffer-tags)))
7853 (prop (setq type :prop beg beg1)
7854 (mapcar 'list (org-buffer-property-keys nil t t)))
7855 (t (progn
7856 (call-interactively org-completion-fallback-command)
7857 (throw 'exit nil)))))
7858 (pattern (buffer-substring-no-properties beg end))
7859 (completion (try-completion pattern table confirm)))
7860 (cond ((eq completion t)
7861 (if (not (assoc (upcase pattern) table))
7862 (message "Already complete")
7863 (if (and (equal type :opt)
7864 (not (member (car (assoc (upcase pattern) table))
7865 org-additional-option-like-keywords)))
7866 (insert (substring (cdr (assoc (upcase pattern) table))
7867 (length pattern)))
7868 (if (memq type '(:tag :prop)) (insert ":")))))
7869 ((null completion)
7870 (message "Can't find completion for \"%s\"" pattern)
7871 (ding))
7872 ((not (string= pattern completion))
7873 (delete-region beg end)
7874 (if (string-match " +$" completion)
7875 (setq completion (replace-match "" t t completion)))
7876 (insert completion)
7877 (if (get-buffer-window "*Completions*")
7878 (delete-window (get-buffer-window "*Completions*")))
7879 (if (assoc completion table)
7880 (if (eq type :todo) (insert " ")
7881 (if (memq type '(:tag :prop)) (insert ":"))))
7882 (if (and (equal type :opt) (assoc completion table))
7883 (message "%s" (substitute-command-keys
7884 "Press \\[org-complete] again to insert example settings"))))
7886 (message "Making completion list...")
7887 (let ((list (sort (all-completions pattern table confirm)
7888 'string<)))
7889 (with-output-to-temp-buffer "*Completions*"
7890 (condition-case nil
7891 ;; Protection needed for XEmacs and emacs 21
7892 (display-completion-list list pattern)
7893 (error (display-completion-list list)))))
7894 (message "Making completion list...%s" "done")))))))
7896 ;;;; TODO, DEADLINE, Comments
7898 (defun org-toggle-comment ()
7899 "Change the COMMENT state of an entry."
7900 (interactive)
7901 (save-excursion
7902 (org-back-to-heading)
7903 (let (case-fold-search)
7904 (if (looking-at (concat outline-regexp
7905 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7906 (replace-match "" t t nil 1)
7907 (if (looking-at outline-regexp)
7908 (progn
7909 (goto-char (match-end 0))
7910 (insert org-comment-string " ")))))))
7912 (defvar org-last-todo-state-is-todo nil
7913 "This is non-nil when the last TODO state change led to a TODO state.
7914 If the last change removed the TODO tag or switched to DONE, then
7915 this is nil.")
7917 (defvar org-setting-tags nil) ; dynamically skiped
7919 (defun org-parse-local-options (string var)
7920 "Parse STRING for startup setting relevant for variable VAR."
7921 (let ((rtn (symbol-value var))
7922 e opts)
7923 (save-match-data
7924 (if (or (not string) (not (string-match "\\S-" string)))
7926 (setq opts (delq nil (mapcar (lambda (x)
7927 (setq e (assoc x org-startup-options))
7928 (if (eq (nth 1 e) var) e nil))
7929 (org-split-string string "[ \t]+"))))
7930 (if (not opts)
7932 (setq rtn nil)
7933 (while (setq e (pop opts))
7934 (if (not (nth 3 e))
7935 (setq rtn (nth 2 e))
7936 (if (not (listp rtn)) (setq rtn nil))
7937 (push (nth 2 e) rtn)))
7938 rtn)))))
7940 (defvar org-blocker-hook nil
7941 "Hook for functions that are allowed to block a state change.
7943 Each function gets as its single argument a property list, see
7944 `org-trigger-hook' for more information about this list.
7946 If any of the functions in this hook returns nil, the state change
7947 is blocked.")
7949 (defvar org-trigger-hook nil
7950 "Hook for functions that are triggered by a state change.
7952 Each function gets as its single argument a property list with at least
7953 the following elements:
7955 (:type type-of-change :position pos-at-entry-start
7956 :from old-state :to new-state)
7958 Depending on the type, more properties may be present.
7960 This mechanism is currently implemented for:
7962 TODO state changes
7963 ------------------
7964 :type todo-state-change
7965 :from previous state (keyword as a string), or nil
7966 :to new state (keyword as a string), or nil")
7968 (defvar org-agenda-headline-snapshot-before-repeat)
7969 (defun org-todo (&optional arg)
7970 "Change the TODO state of an item.
7971 The state of an item is given by a keyword at the start of the heading,
7972 like
7973 *** TODO Write paper
7974 *** DONE Call mom
7976 The different keywords are specified in the variable `org-todo-keywords'.
7977 By default the available states are \"TODO\" and \"DONE\".
7978 So for this example: when the item starts with TODO, it is changed to DONE.
7979 When it starts with DONE, the DONE is removed. And when neither TODO nor
7980 DONE are present, add TODO at the beginning of the heading.
7982 With C-u prefix arg, use completion to determine the new state.
7983 With numeric prefix arg, switch to that state.
7985 For calling through lisp, arg is also interpreted in the following way:
7986 'none -> empty state
7987 \"\"(empty string) -> switch to empty state
7988 'done -> switch to DONE
7989 'nextset -> switch to the next set of keywords
7990 'previousset -> switch to the previous set of keywords
7991 \"WAITING\" -> switch to the specified keyword, but only if it
7992 really is a member of `org-todo-keywords'."
7993 (interactive "P")
7994 (save-excursion
7995 (catch 'exit
7996 (org-back-to-heading)
7997 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7998 (or (looking-at (concat " +" org-todo-regexp " *"))
7999 (looking-at " *"))
8000 (let* ((match-data (match-data))
8001 (startpos (point-at-bol))
8002 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8003 (org-log-done org-log-done)
8004 (org-log-repeat org-log-repeat)
8005 (org-todo-log-states org-todo-log-states)
8006 (this (match-string 1))
8007 (hl-pos (match-beginning 0))
8008 (head (org-get-todo-sequence-head this))
8009 (ass (assoc head org-todo-kwd-alist))
8010 (interpret (nth 1 ass))
8011 (done-word (nth 3 ass))
8012 (final-done-word (nth 4 ass))
8013 (last-state (or this ""))
8014 (completion-ignore-case t)
8015 (member (member this org-todo-keywords-1))
8016 (tail (cdr member))
8017 (state (cond
8018 ((and org-todo-key-trigger
8019 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8020 (and (not arg) org-use-fast-todo-selection
8021 (not (eq org-use-fast-todo-selection 'prefix)))))
8022 ;; Use fast selection
8023 (org-fast-todo-selection))
8024 ((and (equal arg '(4))
8025 (or (not org-use-fast-todo-selection)
8026 (not org-todo-key-trigger)))
8027 ;; Read a state with completion
8028 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8029 org-todo-keywords-1)
8030 nil t))
8031 ((eq arg 'right)
8032 (if this
8033 (if tail (car tail) nil)
8034 (car org-todo-keywords-1)))
8035 ((eq arg 'left)
8036 (if (equal member org-todo-keywords-1)
8038 (if this
8039 (nth (- (length org-todo-keywords-1) (length tail) 2)
8040 org-todo-keywords-1)
8041 (org-last org-todo-keywords-1))))
8042 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8043 (setq arg nil))) ; hack to fall back to cycling
8044 (arg
8045 ;; user or caller requests a specific state
8046 (cond
8047 ((equal arg "") nil)
8048 ((eq arg 'none) nil)
8049 ((eq arg 'done) (or done-word (car org-done-keywords)))
8050 ((eq arg 'nextset)
8051 (or (car (cdr (member head org-todo-heads)))
8052 (car org-todo-heads)))
8053 ((eq arg 'previousset)
8054 (let ((org-todo-heads (reverse org-todo-heads)))
8055 (or (car (cdr (member head org-todo-heads)))
8056 (car org-todo-heads))))
8057 ((car (member arg org-todo-keywords-1)))
8058 ((nth (1- (prefix-numeric-value arg))
8059 org-todo-keywords-1))))
8060 ((null member) (or head (car org-todo-keywords-1)))
8061 ((equal this final-done-word) nil) ;; -> make empty
8062 ((null tail) nil) ;; -> first entry
8063 ((eq interpret 'sequence)
8064 (car tail))
8065 ((memq interpret '(type priority))
8066 (if (eq this-command last-command)
8067 (car tail)
8068 (if (> (length tail) 0)
8069 (or done-word (car org-done-keywords))
8070 nil)))
8071 (t nil)))
8072 (next (if state (concat " " state " ") " "))
8073 (change-plist (list :type 'todo-state-change :from this :to state
8074 :position startpos))
8075 dolog now-done-p)
8076 (when org-blocker-hook
8077 (unless (save-excursion
8078 (save-match-data
8079 (run-hook-with-args-until-failure
8080 'org-blocker-hook change-plist)))
8081 (if (interactive-p)
8082 (error "TODO state change from %s to %s blocked" this state)
8083 ;; fail silently
8084 (message "TODO state change from %s to %s blocked" this state)
8085 (throw 'exit nil))))
8086 (store-match-data match-data)
8087 (replace-match next t t)
8088 (unless (pos-visible-in-window-p hl-pos)
8089 (message "TODO state changed to %s" (org-trim next)))
8090 (unless head
8091 (setq head (org-get-todo-sequence-head state)
8092 ass (assoc head org-todo-kwd-alist)
8093 interpret (nth 1 ass)
8094 done-word (nth 3 ass)
8095 final-done-word (nth 4 ass)))
8096 (when (memq arg '(nextset previousset))
8097 (message "Keyword-Set %d/%d: %s"
8098 (- (length org-todo-sets) -1
8099 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8100 (length org-todo-sets)
8101 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8102 (setq org-last-todo-state-is-todo
8103 (not (member state org-done-keywords)))
8104 (setq now-done-p (and (member state org-done-keywords)
8105 (not (member this org-done-keywords))))
8106 (and logging (org-local-logging logging))
8107 (when (and (or org-todo-log-states org-log-done)
8108 (not (memq arg '(nextset previousset))))
8109 ;; we need to look at recording a time and note
8110 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8111 (nth 2 (assoc this org-todo-log-states))))
8112 (when (and state
8113 (member state org-not-done-keywords)
8114 (not (member this org-not-done-keywords)))
8115 ;; This is now a todo state and was not one before
8116 ;; If there was a CLOSED time stamp, get rid of it.
8117 (org-add-planning-info nil nil 'closed))
8118 (when (and now-done-p org-log-done)
8119 ;; It is now done, and it was not done before
8120 (org-add-planning-info 'closed (org-current-time))
8121 (if (and (not dolog) (eq 'note org-log-done))
8122 (org-add-log-setup 'done state 'findpos 'note)))
8123 (when (and state dolog)
8124 ;; This is a non-nil state, and we need to log it
8125 (org-add-log-setup 'state state 'findpos dolog)))
8126 ;; Fixup tag positioning
8127 (org-todo-trigger-tag-changes state)
8128 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8129 (when org-provide-todo-statistics
8130 (org-update-parent-todo-statistics))
8131 (run-hooks 'org-after-todo-state-change-hook)
8132 (if (and arg (not (member state org-done-keywords)))
8133 (setq head (org-get-todo-sequence-head state)))
8134 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8135 ;; Do we need to trigger a repeat?
8136 (when now-done-p
8137 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8138 ;; This is for the agenda, take a snapshot of the headline.
8139 (save-match-data
8140 (setq org-agenda-headline-snapshot-before-repeat
8141 (org-get-heading))))
8142 (org-auto-repeat-maybe state))
8143 ;; Fixup cursor location if close to the keyword
8144 (if (and (outline-on-heading-p)
8145 (not (bolp))
8146 (save-excursion (beginning-of-line 1)
8147 (looking-at org-todo-line-regexp))
8148 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8149 (progn
8150 (goto-char (or (match-end 2) (match-end 1)))
8151 (just-one-space)))
8152 (when org-trigger-hook
8153 (save-excursion
8154 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8156 (defun org-update-parent-todo-statistics ()
8157 "Update any statistics cookie in the parent of the current headline."
8158 (interactive)
8159 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8160 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8161 (catch 'exit
8162 (save-excursion
8163 (setq level (org-up-heading-safe))
8164 (unless (and level
8165 (re-search-forward box-re (point-at-eol) t))
8166 (throw 'exit nil))
8167 (setq is-percent (match-end 2))
8168 (save-match-data
8169 (unless (outline-next-heading) (throw 'exit nil))
8170 (while (looking-at org-todo-line-regexp)
8171 (setq kwd (match-string 2))
8172 (and kwd (setq cnt-all (1+ cnt-all)))
8173 (and (member kwd org-done-keywords)
8174 (setq cnt-done (1+ cnt-done)))
8175 (condition-case nil
8176 (org-forward-same-level 1)
8177 (error (end-of-line 1)))))
8178 (replace-match
8179 (if is-percent
8180 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8181 (format "[%d/%d]" cnt-done cnt-all)))
8182 (run-hook-with-args 'org-after-todo-statistics-hook
8183 cnt-done (- cnt-all cnt-done))))))
8185 (defvar org-after-todo-statistics-hook nil
8186 "Hook that is called after a TODO statistics cookie has been updated.
8187 Each function is called with two arguments: the number of not-done entries
8188 and the number of done entries.
8190 For example, the following function, when added to this hook, will switch
8191 an entry to DONE when all children are done, and back to TODO when new
8192 entries are set to a TODO status. Note that this hook is only called
8193 when there is a statistics cookie in the headline!
8195 (defun org-summary-todo (n-done n-not-done)
8196 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8197 (let (org-log-done org-log-states) ; turn off logging
8198 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8201 (defun org-todo-trigger-tag-changes (state)
8202 "Apply the changes defined in `org-todo-state-tags-triggers'."
8203 (let ((l org-todo-state-tags-triggers)
8204 changes)
8205 (when (or (not state) (equal state ""))
8206 (setq changes (append changes (cdr (assoc "" l)))))
8207 (when (and (stringp state) (> (length state) 0))
8208 (setq changes (append changes (cdr (assoc state l)))))
8209 (when (member state org-not-done-keywords)
8210 (setq changes (append changes (cdr (assoc 'todo l)))))
8211 (when (member state org-done-keywords)
8212 (setq changes (append changes (cdr (assoc 'done l)))))
8213 (dolist (c changes)
8214 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8216 (defun org-local-logging (value)
8217 "Get logging settings from a property VALUE."
8218 (let* (words w a)
8219 ;; directly set the variables, they are already local.
8220 (setq org-log-done nil
8221 org-log-repeat nil
8222 org-todo-log-states nil)
8223 (setq words (org-split-string value))
8224 (while (setq w (pop words))
8225 (cond
8226 ((setq a (assoc w org-startup-options))
8227 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8228 (set (nth 1 a) (nth 2 a))))
8229 ((setq a (org-extract-log-state-settings w))
8230 (and (member (car a) org-todo-keywords-1)
8231 (push a org-todo-log-states)))))))
8233 (defun org-get-todo-sequence-head (kwd)
8234 "Return the head of the TODO sequence to which KWD belongs.
8235 If KWD is not set, check if there is a text property remembering the
8236 right sequence."
8237 (let (p)
8238 (cond
8239 ((not kwd)
8240 (or (get-text-property (point-at-bol) 'org-todo-head)
8241 (progn
8242 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8243 nil (point-at-eol)))
8244 (get-text-property p 'org-todo-head))))
8245 ((not (member kwd org-todo-keywords-1))
8246 (car org-todo-keywords-1))
8247 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8249 (defun org-fast-todo-selection ()
8250 "Fast TODO keyword selection with single keys.
8251 Returns the new TODO keyword, or nil if no state change should occur."
8252 (let* ((fulltable org-todo-key-alist)
8253 (done-keywords org-done-keywords) ;; needed for the faces.
8254 (maxlen (apply 'max (mapcar
8255 (lambda (x)
8256 (if (stringp (car x)) (string-width (car x)) 0))
8257 fulltable)))
8258 (expert nil)
8259 (fwidth (+ maxlen 3 1 3))
8260 (ncol (/ (- (window-width) 4) fwidth))
8261 tg cnt e c tbl
8262 groups ingroup)
8263 (save-window-excursion
8264 (if expert
8265 (set-buffer (get-buffer-create " *Org todo*"))
8266 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8267 (erase-buffer)
8268 (org-set-local 'org-done-keywords done-keywords)
8269 (setq tbl fulltable cnt 0)
8270 (while (setq e (pop tbl))
8271 (cond
8272 ((equal e '(:startgroup))
8273 (push '() groups) (setq ingroup t)
8274 (when (not (= cnt 0))
8275 (setq cnt 0)
8276 (insert "\n"))
8277 (insert "{ "))
8278 ((equal e '(:endgroup))
8279 (setq ingroup nil cnt 0)
8280 (insert "}\n"))
8282 (setq tg (car e) c (cdr e))
8283 (if ingroup (push tg (car groups)))
8284 (setq tg (org-add-props tg nil 'face
8285 (org-get-todo-face tg)))
8286 (if (and (= cnt 0) (not ingroup)) (insert " "))
8287 (insert "[" c "] " tg (make-string
8288 (- fwidth 4 (length tg)) ?\ ))
8289 (when (= (setq cnt (1+ cnt)) ncol)
8290 (insert "\n")
8291 (if ingroup (insert " "))
8292 (setq cnt 0)))))
8293 (insert "\n")
8294 (goto-char (point-min))
8295 (if (not expert) (org-fit-window-to-buffer))
8296 (message "[a-z..]:Set [SPC]:clear")
8297 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8298 (cond
8299 ((or (= c ?\C-g)
8300 (and (= c ?q) (not (rassoc c fulltable))))
8301 (setq quit-flag t))
8302 ((= c ?\ ) nil)
8303 ((setq e (rassoc c fulltable) tg (car e))
8305 (t (setq quit-flag t))))))
8307 (defun org-entry-is-todo-p ()
8308 (member (org-get-todo-state) org-not-done-keywords))
8310 (defun org-entry-is-done-p ()
8311 (member (org-get-todo-state) org-done-keywords))
8313 (defun org-get-todo-state ()
8314 (save-excursion
8315 (org-back-to-heading t)
8316 (and (looking-at org-todo-line-regexp)
8317 (match-end 2)
8318 (match-string 2))))
8320 (defun org-at-date-range-p (&optional inactive-ok)
8321 "Is the cursor inside a date range?"
8322 (interactive)
8323 (save-excursion
8324 (catch 'exit
8325 (let ((pos (point)))
8326 (skip-chars-backward "^[<\r\n")
8327 (skip-chars-backward "<[")
8328 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8329 (>= (match-end 0) pos)
8330 (throw 'exit t))
8331 (skip-chars-backward "^<[\r\n")
8332 (skip-chars-backward "<[")
8333 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8334 (>= (match-end 0) pos)
8335 (throw 'exit t)))
8336 nil)))
8338 (defun org-get-repeat ()
8339 "Check if there is a deadline/schedule with repeater in this entry."
8340 (save-match-data
8341 (save-excursion
8342 (org-back-to-heading t)
8343 (if (re-search-forward
8344 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8345 (match-string 1)))))
8347 (defvar org-last-changed-timestamp)
8348 (defvar org-last-inserted-timestamp)
8349 (defvar org-log-post-message)
8350 (defvar org-log-note-purpose)
8351 (defvar org-log-note-how)
8352 (defvar org-log-note-extra)
8353 (defun org-auto-repeat-maybe (done-word)
8354 "Check if the current headline contains a repeated deadline/schedule.
8355 If yes, set TODO state back to what it was and change the base date
8356 of repeating deadline/scheduled time stamps to new date.
8357 This function is run automatically after each state change to a DONE state."
8358 ;; last-state is dynamically scoped into this function
8359 (let* ((repeat (org-get-repeat))
8360 (aa (assoc last-state org-todo-kwd-alist))
8361 (interpret (nth 1 aa))
8362 (head (nth 2 aa))
8363 (whata '(("d" . day) ("m" . month) ("y" . year)))
8364 (msg "Entry repeats: ")
8365 (org-log-done nil)
8366 (org-todo-log-states nil)
8367 (nshiftmax 10) (nshift 0)
8368 re type n what ts mb0 time)
8369 (when repeat
8370 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8371 (org-todo (if (eq interpret 'type) last-state head))
8372 (when org-log-repeat
8373 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8374 (memq 'org-add-log-note post-command-hook))
8375 ;; OK, we are already setup for some record
8376 (if (eq org-log-repeat 'note)
8377 ;; make sure we take a note, not only a time stamp
8378 (setq org-log-note-how 'note))
8379 ;; Set up for taking a record
8380 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8381 'findpos org-log-repeat)))
8382 (org-back-to-heading t)
8383 (org-add-planning-info nil nil 'closed)
8384 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8385 org-deadline-time-regexp "\\)\\|\\("
8386 org-ts-regexp "\\)"))
8387 (while (re-search-forward
8388 re (save-excursion (outline-next-heading) (point)) t)
8389 (setq type (if (match-end 1) org-scheduled-string
8390 (if (match-end 3) org-deadline-string "Plain:"))
8391 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8392 mb0 (match-beginning 0))
8393 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8394 (setq n (string-to-number (match-string 2 ts))
8395 what (match-string 3 ts))
8396 (if (equal what "w") (setq n (* n 7) what "d"))
8397 ;; Preparation, see if we need to modify the start date for the change
8398 (when (match-end 1)
8399 (setq time (save-match-data (org-time-string-to-time ts)))
8400 (cond
8401 ((equal (match-string 1 ts) ".")
8402 ;; Shift starting date to today
8403 (org-timestamp-change
8404 (- (time-to-days (current-time)) (time-to-days time))
8405 'day))
8406 ((equal (match-string 1 ts) "+")
8407 (while (or (= nshift 0)
8408 (<= (time-to-days time) (time-to-days (current-time))))
8409 (when (= (incf nshift) nshiftmax)
8410 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8411 (error "Abort")))
8412 (org-timestamp-change n (cdr (assoc what whata)))
8413 (org-at-timestamp-p t)
8414 (setq ts (match-string 1))
8415 (setq time (save-match-data (org-time-string-to-time ts))))
8416 (org-timestamp-change (- n) (cdr (assoc what whata)))
8417 ;; rematch, so that we have everything in place for the real shift
8418 (org-at-timestamp-p t)
8419 (setq ts (match-string 1))
8420 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8421 (org-timestamp-change n (cdr (assoc what whata)))
8422 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8423 (setq org-log-post-message msg)
8424 (message "%s" msg))))
8426 (defun org-show-todo-tree (arg)
8427 "Make a compact tree which shows all headlines marked with TODO.
8428 The tree will show the lines where the regexp matches, and all higher
8429 headlines above the match.
8430 With a \\[universal-argument] prefix, also show the DONE entries.
8431 With a numeric prefix N, construct a sparse tree for the Nth element
8432 of `org-todo-keywords-1'."
8433 (interactive "P")
8434 (let ((case-fold-search nil)
8435 (kwd-re
8436 (cond ((null arg) org-not-done-regexp)
8437 ((equal arg '(4))
8438 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8439 (mapcar 'list org-todo-keywords-1))))
8440 (concat "\\("
8441 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8442 "\\)\\>")))
8443 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8444 (regexp-quote (nth (1- (prefix-numeric-value arg))
8445 org-todo-keywords-1)))
8446 (t (error "Invalid prefix argument: %s" arg)))))
8447 (message "%d TODO entries found"
8448 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8450 (defun org-deadline (&optional remove time)
8451 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8452 With argument REMOVE, remove any deadline from the item.
8453 When TIME is set, it should be an internal time specification, and the
8454 scheduling will use the corresponding date."
8455 (interactive "P")
8456 (if remove
8457 (progn
8458 (org-remove-timestamp-with-keyword org-deadline-string)
8459 (message "Item no longer has a deadline."))
8460 (if (org-get-repeat)
8461 (error "Cannot change deadline on task with repeater, please do that by hand")
8462 (org-add-planning-info 'deadline time 'closed)
8463 (message "Deadline on %s" org-last-inserted-timestamp))))
8465 (defun org-schedule (&optional remove time)
8466 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8467 With argument REMOVE, remove any scheduling date from the item.
8468 When TIME is set, it should be an internal time specification, and the
8469 scheduling will use the corresponding date."
8470 (interactive "P")
8471 (if remove
8472 (progn
8473 (org-remove-timestamp-with-keyword org-scheduled-string)
8474 (message "Item is no longer scheduled."))
8475 (if (org-get-repeat)
8476 (error "Cannot reschedule task with repeater, please do that by hand")
8477 (org-add-planning-info 'scheduled time 'closed)
8478 (message "Scheduled to %s" org-last-inserted-timestamp))))
8480 (defun org-remove-timestamp-with-keyword (keyword)
8481 "Remove all time stamps with KEYWORD in the current entry."
8482 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8483 beg)
8484 (save-excursion
8485 (org-back-to-heading t)
8486 (setq beg (point))
8487 (org-end-of-subtree t t)
8488 (while (re-search-backward re beg t)
8489 (replace-match "")
8490 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8491 (equal (char-before) ?\ ))
8492 (backward-delete-char 1)
8493 (if (string-match "^[ \t]*$" (buffer-substring
8494 (point-at-bol) (point-at-eol)))
8495 (delete-region (point-at-bol)
8496 (min (point-max) (1+ (point-at-eol))))))))))
8498 (defun org-add-planning-info (what &optional time &rest remove)
8499 "Insert new timestamp with keyword in the line directly after the headline.
8500 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8501 If non is given, the user is prompted for a date.
8502 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8503 be removed."
8504 (interactive)
8505 (let (org-time-was-given org-end-time-was-given ts
8506 end default-time default-input)
8508 (when (and (not time) (memq what '(scheduled deadline)))
8509 ;; Try to get a default date/time from existing timestamp
8510 (save-excursion
8511 (org-back-to-heading t)
8512 (setq end (save-excursion (outline-next-heading) (point)))
8513 (when (re-search-forward (if (eq what 'scheduled)
8514 org-scheduled-time-regexp
8515 org-deadline-time-regexp)
8516 end t)
8517 (setq ts (match-string 1)
8518 default-time
8519 (apply 'encode-time (org-parse-time-string ts))
8520 default-input (and ts (org-get-compact-tod ts))))))
8521 (when what
8522 ;; If necessary, get the time from the user
8523 (setq time (or time (org-read-date nil 'to-time nil nil
8524 default-time default-input))))
8526 (when (and org-insert-labeled-timestamps-at-point
8527 (member what '(scheduled deadline)))
8528 (insert
8529 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8530 (org-insert-time-stamp time org-time-was-given
8531 nil nil nil (list org-end-time-was-given))
8532 (setq what nil))
8533 (save-excursion
8534 (save-restriction
8535 (let (col list elt ts buffer-invisibility-spec)
8536 (org-back-to-heading t)
8537 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8538 (goto-char (match-end 1))
8539 (setq col (current-column))
8540 (goto-char (match-end 0))
8541 (if (eobp) (insert "\n") (forward-char 1))
8542 (if (and (not (looking-at outline-regexp))
8543 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8544 "[^\r\n]*"))
8545 (not (equal (match-string 1) org-clock-string)))
8546 (narrow-to-region (match-beginning 0) (match-end 0))
8547 (insert-before-markers "\n")
8548 (backward-char 1)
8549 (narrow-to-region (point) (point))
8550 (and org-adapt-indentation (org-indent-to-column col)))
8551 ;; Check if we have to remove something.
8552 (setq list (cons what remove))
8553 (while list
8554 (setq elt (pop list))
8555 (goto-char (point-min))
8556 (when (or (and (eq elt 'scheduled)
8557 (re-search-forward org-scheduled-time-regexp nil t))
8558 (and (eq elt 'deadline)
8559 (re-search-forward org-deadline-time-regexp nil t))
8560 (and (eq elt 'closed)
8561 (re-search-forward org-closed-time-regexp nil t)))
8562 (replace-match "")
8563 (if (looking-at "--+<[^>]+>") (replace-match ""))
8564 (if (looking-at " +") (replace-match ""))))
8565 (goto-char (point-max))
8566 (when what
8567 (insert
8568 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8569 (cond ((eq what 'scheduled) org-scheduled-string)
8570 ((eq what 'deadline) org-deadline-string)
8571 ((eq what 'closed) org-closed-string))
8572 " ")
8573 (setq ts (org-insert-time-stamp
8574 time
8575 (or org-time-was-given
8576 (and (eq what 'closed) org-log-done-with-time))
8577 (eq what 'closed)
8578 nil nil (list org-end-time-was-given)))
8579 (end-of-line 1))
8580 (goto-char (point-min))
8581 (widen)
8582 (if (and (looking-at "[ \t]+\n")
8583 (equal (char-before) ?\n))
8584 (delete-region (1- (point)) (point-at-eol)))
8585 ts)))))
8587 (defvar org-log-note-marker (make-marker))
8588 (defvar org-log-note-purpose nil)
8589 (defvar org-log-note-state nil)
8590 (defvar org-log-note-how nil)
8591 (defvar org-log-note-extra nil)
8592 (defvar org-log-note-window-configuration nil)
8593 (defvar org-log-note-return-to (make-marker))
8594 (defvar org-log-post-message nil
8595 "Message to be displayed after a log note has been stored.
8596 The auto-repeater uses this.")
8598 (defun org-add-note ()
8599 "Add a note to the current entry.
8600 This is done in the same way as adding a state change note."
8601 (interactive)
8602 (org-add-log-setup 'note nil 'findpos nil))
8604 (defvar org-property-end-re)
8605 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8606 "Set up the post command hook to take a note.
8607 If this is about to TODO state change, the new state is expected in STATE.
8608 When FINDPOS is non-nil, find the correct position for the note in
8609 the current entry. If not, assume that it can be inserted at point.
8610 HOW is an indicator what kind of note should be created.
8611 EXTRA is additional text that will be inserted into the notes buffer."
8612 (save-restriction
8613 (save-excursion
8614 (when findpos
8615 (org-back-to-heading t)
8616 (narrow-to-region (point) (save-excursion
8617 (outline-next-heading) (point)))
8618 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8619 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8620 "[^\r\n]*\\)?"))
8621 (goto-char (match-end 0))
8622 (when (and org-log-state-notes-insert-after-drawers
8623 (save-excursion
8624 (forward-line) (looking-at org-drawer-regexp)))
8625 (progn (forward-line)
8626 (while (looking-at org-drawer-regexp)
8627 (goto-char (match-end 0))
8628 (re-search-forward org-property-end-re (point-max) t)
8629 (forward-line))
8630 (forward-line -1)))
8631 (unless org-log-states-order-reversed
8632 (and (= (char-after) ?\n) (forward-char 1))
8633 (org-skip-over-state-notes)
8634 (skip-chars-backward " \t\n\r")))
8635 (move-marker org-log-note-marker (point))
8636 (setq org-log-note-purpose purpose
8637 org-log-note-state state
8638 org-log-note-how how
8639 org-log-note-extra extra)
8640 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8642 (defun org-skip-over-state-notes ()
8643 "Skip past the list of State notes in an entry."
8644 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8645 (while (looking-at "[ \t]*- State")
8646 (condition-case nil
8647 (org-next-item)
8648 (error (org-end-of-item)))))
8650 (defun org-add-log-note (&optional purpose)
8651 "Pop up a window for taking a note, and add this note later at point."
8652 (remove-hook 'post-command-hook 'org-add-log-note)
8653 (setq org-log-note-window-configuration (current-window-configuration))
8654 (delete-other-windows)
8655 (move-marker org-log-note-return-to (point))
8656 (switch-to-buffer (marker-buffer org-log-note-marker))
8657 (goto-char org-log-note-marker)
8658 (org-switch-to-buffer-other-window "*Org Note*")
8659 (erase-buffer)
8660 (if (memq org-log-note-how '(time state))
8661 (let (current-prefix-arg) (org-store-log-note))
8662 (let ((org-inhibit-startup t)) (org-mode))
8663 (insert (format "# Insert note for %s.
8664 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8665 (cond
8666 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8667 ((eq org-log-note-purpose 'done) "closed todo item")
8668 ((eq org-log-note-purpose 'state)
8669 (format "state change to \"%s\"" org-log-note-state))
8670 ((eq org-log-note-purpose 'note)
8671 "this entry")
8672 (t (error "This should not happen")))))
8673 (if org-log-note-extra (insert org-log-note-extra))
8674 (org-set-local 'org-finish-function 'org-store-log-note)))
8676 (defvar org-note-abort nil) ; dynamically scoped
8677 (defun org-store-log-note ()
8678 "Finish taking a log note, and insert it to where it belongs."
8679 (let ((txt (buffer-string))
8680 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8681 lines ind)
8682 (kill-buffer (current-buffer))
8683 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8684 (setq txt (replace-match "" t t txt)))
8685 (if (string-match "\\s-+\\'" txt)
8686 (setq txt (replace-match "" t t txt)))
8687 (setq lines (org-split-string txt "\n"))
8688 (when (and note (string-match "\\S-" note))
8689 (setq note
8690 (org-replace-escapes
8691 note
8692 (list (cons "%u" (user-login-name))
8693 (cons "%U" user-full-name)
8694 (cons "%t" (format-time-string
8695 (org-time-stamp-format 'long 'inactive)
8696 (current-time)))
8697 (cons "%s" (if org-log-note-state
8698 (concat "\"" org-log-note-state "\"")
8699 "")))))
8700 (if lines (setq note (concat note " \\\\")))
8701 (push note lines))
8702 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8703 (when lines
8704 (save-excursion
8705 (set-buffer (marker-buffer org-log-note-marker))
8706 (save-excursion
8707 (goto-char org-log-note-marker)
8708 (move-marker org-log-note-marker nil)
8709 (end-of-line 1)
8710 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8711 (indent-relative nil)
8712 (insert "- " (pop lines))
8713 (org-indent-line-function)
8714 (beginning-of-line 1)
8715 (looking-at "[ \t]*")
8716 (setq ind (concat (match-string 0) " "))
8717 (end-of-line 1)
8718 (while lines (insert "\n" ind (pop lines)))))))
8719 (set-window-configuration org-log-note-window-configuration)
8720 (with-current-buffer (marker-buffer org-log-note-return-to)
8721 (goto-char org-log-note-return-to))
8722 (move-marker org-log-note-return-to nil)
8723 (and org-log-post-message (message "%s" org-log-post-message)))
8725 (defun org-sparse-tree (&optional arg)
8726 "Create a sparse tree, prompt for the details.
8727 This command can create sparse trees. You first need to select the type
8728 of match used to create the tree:
8730 t Show entries with a specific TODO keyword.
8731 T Show entries selected by a tags match.
8732 p Enter a property name and its value (both with completion on existing
8733 names/values) and show entries with that property.
8734 r Show entries matching a regular expression
8735 d Show deadlines due within `org-deadline-warning-days'."
8736 (interactive "P")
8737 (let (ans kwd value)
8738 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8739 (setq ans (read-char-exclusive))
8740 (cond
8741 ((equal ans ?d)
8742 (call-interactively 'org-check-deadlines))
8743 ((equal ans ?b)
8744 (call-interactively 'org-check-before-date))
8745 ((equal ans ?t)
8746 (org-show-todo-tree '(4)))
8747 ((equal ans ?T)
8748 (call-interactively 'org-tags-sparse-tree))
8749 ((member ans '(?p ?P))
8750 (setq kwd (org-ido-completing-read "Property: "
8751 (mapcar 'list (org-buffer-property-keys))))
8752 (setq value (org-ido-completing-read "Value: "
8753 (mapcar 'list (org-property-values kwd))))
8754 (unless (string-match "\\`{.*}\\'" value)
8755 (setq value (concat "\"" value "\"")))
8756 (org-tags-sparse-tree arg (concat kwd "=" value)))
8757 ((member ans '(?r ?R ?/))
8758 (call-interactively 'org-occur))
8759 (t (error "No such sparse tree command \"%c\"" ans)))))
8761 (defvar org-occur-highlights nil
8762 "List of overlays used for occur matches.")
8763 (make-variable-buffer-local 'org-occur-highlights)
8764 (defvar org-occur-parameters nil
8765 "Parameters of the active org-occur calls.
8766 This is a list, each call to org-occur pushes as cons cell,
8767 containing the regular expression and the callback, onto the list.
8768 The list can contain several entries if `org-occur' has been called
8769 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8770 will only contain one set of parameters. When the highlights are
8771 removed (for example with `C-c C-c', or with the next edit (depending
8772 on `org-remove-highlights-with-change'), this variable is emptied
8773 as well.")
8774 (make-variable-buffer-local 'org-occur-parameters)
8776 (defun org-occur (regexp &optional keep-previous callback)
8777 "Make a compact tree which shows all matches of REGEXP.
8778 The tree will show the lines where the regexp matches, and all higher
8779 headlines above the match. It will also show the heading after the match,
8780 to make sure editing the matching entry is easy.
8781 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8782 call to `org-occur' will be kept, to allow stacking of calls to this
8783 command.
8784 If CALLBACK is non-nil, it is a function which is called to confirm
8785 that the match should indeed be shown."
8786 (interactive "sRegexp: \nP")
8787 (unless keep-previous
8788 (org-remove-occur-highlights nil nil t))
8789 (push (cons regexp callback) org-occur-parameters)
8790 (let ((cnt 0))
8791 (save-excursion
8792 (goto-char (point-min))
8793 (if (or (not keep-previous) ; do not want to keep
8794 (not org-occur-highlights)) ; no previous matches
8795 ;; hide everything
8796 (org-overview))
8797 (while (re-search-forward regexp nil t)
8798 (when (or (not callback)
8799 (save-match-data (funcall callback)))
8800 (setq cnt (1+ cnt))
8801 (when org-highlight-sparse-tree-matches
8802 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8803 (org-show-context 'occur-tree))))
8804 (when org-remove-highlights-with-change
8805 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8806 nil 'local))
8807 (unless org-sparse-tree-open-archived-trees
8808 (org-hide-archived-subtrees (point-min) (point-max)))
8809 (run-hooks 'org-occur-hook)
8810 (if (interactive-p)
8811 (message "%d match(es) for regexp %s" cnt regexp))
8812 cnt))
8814 (defun org-show-context (&optional key)
8815 "Make sure point and context and visible.
8816 How much context is shown depends upon the variables
8817 `org-show-hierarchy-above', `org-show-following-heading'. and
8818 `org-show-siblings'."
8819 (let ((heading-p (org-on-heading-p t))
8820 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8821 (following-p (org-get-alist-option org-show-following-heading key))
8822 (entry-p (org-get-alist-option org-show-entry-below key))
8823 (siblings-p (org-get-alist-option org-show-siblings key)))
8824 (catch 'exit
8825 ;; Show heading or entry text
8826 (if (and heading-p (not entry-p))
8827 (org-flag-heading nil) ; only show the heading
8828 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8829 (org-show-hidden-entry))) ; show entire entry
8830 (when following-p
8831 ;; Show next sibling, or heading below text
8832 (save-excursion
8833 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8834 (org-flag-heading nil))))
8835 (when siblings-p (org-show-siblings))
8836 (when hierarchy-p
8837 ;; show all higher headings, possibly with siblings
8838 (save-excursion
8839 (while (and (condition-case nil
8840 (progn (org-up-heading-all 1) t)
8841 (error nil))
8842 (not (bobp)))
8843 (org-flag-heading nil)
8844 (when siblings-p (org-show-siblings))))))))
8846 (defun org-reveal (&optional siblings)
8847 "Show current entry, hierarchy above it, and the following headline.
8848 This can be used to show a consistent set of context around locations
8849 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8850 not t for the search context.
8852 With optional argument SIBLINGS, on each level of the hierarchy all
8853 siblings are shown. This repairs the tree structure to what it would
8854 look like when opened with hierarchical calls to `org-cycle'."
8855 (interactive "P")
8856 (let ((org-show-hierarchy-above t)
8857 (org-show-following-heading t)
8858 (org-show-siblings (if siblings t org-show-siblings)))
8859 (org-show-context nil)))
8861 (defun org-highlight-new-match (beg end)
8862 "Highlight from BEG to END and mark the highlight is an occur headline."
8863 (let ((ov (org-make-overlay beg end)))
8864 (org-overlay-put ov 'face 'secondary-selection)
8865 (push ov org-occur-highlights)))
8867 (defun org-remove-occur-highlights (&optional beg end noremove)
8868 "Remove the occur highlights from the buffer.
8869 BEG and END are ignored. If NOREMOVE is nil, remove this function
8870 from the `before-change-functions' in the current buffer."
8871 (interactive)
8872 (unless org-inhibit-highlight-removal
8873 (mapc 'org-delete-overlay org-occur-highlights)
8874 (setq org-occur-highlights nil)
8875 (setq org-occur-parameters nil)
8876 (unless noremove
8877 (remove-hook 'before-change-functions
8878 'org-remove-occur-highlights 'local))))
8880 ;;;; Priorities
8882 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8883 "Regular expression matching the priority indicator.")
8885 (defvar org-remove-priority-next-time nil)
8887 (defun org-priority-up ()
8888 "Increase the priority of the current item."
8889 (interactive)
8890 (org-priority 'up))
8892 (defun org-priority-down ()
8893 "Decrease the priority of the current item."
8894 (interactive)
8895 (org-priority 'down))
8897 (defun org-priority (&optional action)
8898 "Change the priority of an item by ARG.
8899 ACTION can be `set', `up', `down', or a character."
8900 (interactive)
8901 (setq action (or action 'set))
8902 (let (current new news have remove)
8903 (save-excursion
8904 (org-back-to-heading)
8905 (if (looking-at org-priority-regexp)
8906 (setq current (string-to-char (match-string 2))
8907 have t)
8908 (setq current org-default-priority))
8909 (cond
8910 ((or (eq action 'set)
8911 (if (featurep 'xemacs) (characterp action) (integerp action)))
8912 (if (not (eq action 'set))
8913 (setq new action)
8914 (message "Priority %c-%c, SPC to remove: "
8915 org-highest-priority org-lowest-priority)
8916 (setq new (read-char-exclusive)))
8917 (if (and (= (upcase org-highest-priority) org-highest-priority)
8918 (= (upcase org-lowest-priority) org-lowest-priority))
8919 (setq new (upcase new)))
8920 (cond ((equal new ?\ ) (setq remove t))
8921 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8922 (error "Priority must be between `%c' and `%c'"
8923 org-highest-priority org-lowest-priority))))
8924 ((eq action 'up)
8925 (if (and (not have) (eq last-command this-command))
8926 (setq new org-lowest-priority)
8927 (setq new (if (and org-priority-start-cycle-with-default (not have))
8928 org-default-priority (1- current)))))
8929 ((eq action 'down)
8930 (if (and (not have) (eq last-command this-command))
8931 (setq new org-highest-priority)
8932 (setq new (if (and org-priority-start-cycle-with-default (not have))
8933 org-default-priority (1+ current)))))
8934 (t (error "Invalid action")))
8935 (if (or (< (upcase new) org-highest-priority)
8936 (> (upcase new) org-lowest-priority))
8937 (setq remove t))
8938 (setq news (format "%c" new))
8939 (if have
8940 (if remove
8941 (replace-match "" t t nil 1)
8942 (replace-match news t t nil 2))
8943 (if remove
8944 (error "No priority cookie found in line")
8945 (looking-at org-todo-line-regexp)
8946 (if (match-end 2)
8947 (progn
8948 (goto-char (match-end 2))
8949 (insert " [#" news "]"))
8950 (goto-char (match-beginning 3))
8951 (insert "[#" news "] ")))))
8952 (org-preserve-lc (org-set-tags nil 'align))
8953 (if remove
8954 (message "Priority removed")
8955 (message "Priority of current item set to %s" news))))
8958 (defun org-get-priority (s)
8959 "Find priority cookie and return priority."
8960 (save-match-data
8961 (if (not (string-match org-priority-regexp s))
8962 (* 1000 (- org-lowest-priority org-default-priority))
8963 (* 1000 (- org-lowest-priority
8964 (string-to-char (match-string 2 s)))))))
8966 ;;;; Tags
8968 (defvar org-agenda-archives-mode)
8969 (defun org-scan-tags (action matcher &optional todo-only)
8970 "Scan headline tags with inheritance and produce output ACTION.
8972 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8973 or `agenda' to produce an entry list for an agenda view. It can also be
8974 a Lisp form or a function that should be called at each matched headline, in
8975 this case the return value is a list of all return values from these calls.
8977 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8978 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8979 only lines with a TODO keyword are included in the output."
8980 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8981 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8982 (org-re
8983 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8984 (props (list 'face 'default
8985 'done-face 'org-done
8986 'undone-face 'default
8987 'mouse-face 'highlight
8988 'org-not-done-regexp org-not-done-regexp
8989 'org-todo-regexp org-todo-regexp
8990 'keymap org-agenda-keymap
8991 'help-echo
8992 (format "mouse-2 or RET jump to org file %s"
8993 (abbreviate-file-name
8994 (or (buffer-file-name (buffer-base-buffer))
8995 (buffer-name (buffer-base-buffer)))))))
8996 (case-fold-search nil)
8997 lspos tags tags-list
8998 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8999 (llast 0) rtn rtn1 level category i txt
9000 todo marker entry priority)
9001 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9002 (setq action (list 'lambda nil action)))
9003 (save-excursion
9004 (goto-char (point-min))
9005 (when (eq action 'sparse-tree)
9006 (org-overview)
9007 (org-remove-occur-highlights))
9008 (while (re-search-forward re nil t)
9009 (catch :skip
9010 (setq todo (if (match-end 1) (match-string 2))
9011 tags (if (match-end 4) (match-string 4)))
9012 (goto-char (setq lspos (1+ (match-beginning 0))))
9013 (setq level (org-reduced-level (funcall outline-level))
9014 category (org-get-category))
9015 (setq i llast llast level)
9016 ;; remove tag lists from same and sublevels
9017 (while (>= i level)
9018 (when (setq entry (assoc i tags-alist))
9019 (setq tags-alist (delete entry tags-alist)))
9020 (setq i (1- i)))
9021 ;; add the next tags
9022 (when tags
9023 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9024 tags-alist
9025 (cons (cons level tags) tags-alist)))
9026 ;; compile tags for current headline
9027 (setq tags-list
9028 (if org-use-tag-inheritance
9029 (apply 'append (mapcar 'cdr tags-alist))
9030 tags))
9031 (when (and tags org-use-tag-inheritance
9032 (not (eq t org-use-tag-inheritance)))
9033 ;; selective inheritance, remove uninherited ones
9034 (setcdr (car tags-alist)
9035 (org-remove-uniherited-tags (cdar tags-alist))))
9036 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9037 (let ((case-fold-search t)) (eval matcher))
9039 (not (member org-archive-tag tags-list))
9040 ;; we have an archive tag, should we use this anyway?
9041 (or (not org-agenda-skip-archived-trees)
9042 (and (eq action 'agenda) org-agenda-archives-mode))))
9043 (unless (eq action 'sparse-tree) (org-agenda-skip))
9045 ;; select this headline
9047 (cond
9048 ((eq action 'sparse-tree)
9049 (and org-highlight-sparse-tree-matches
9050 (org-get-heading) (match-end 0)
9051 (org-highlight-new-match
9052 (match-beginning 0) (match-beginning 1)))
9053 (org-show-context 'tags-tree))
9054 ((eq action 'agenda)
9055 (setq txt (org-format-agenda-item
9057 (concat
9058 (if org-tags-match-list-sublevels
9059 (make-string (1- level) ?.) "")
9060 (org-get-heading))
9061 category tags-list)
9062 priority (org-get-priority txt))
9063 (goto-char lspos)
9064 (setq marker (org-agenda-new-marker))
9065 (org-add-props txt props
9066 'org-marker marker 'org-hd-marker marker 'org-category category
9067 'priority priority 'type "tagsmatch")
9068 (push txt rtn))
9069 ((functionp action)
9070 (save-excursion
9071 (setq rtn1 (funcall action))
9072 (push rtn1 rtn))
9073 (goto-char (point-at-eol)))
9074 (t (error "Invalid action")))
9076 ;; if we are to skip sublevels, jump to end of subtree
9077 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9078 (when (and (eq action 'sparse-tree)
9079 (not org-sparse-tree-open-archived-trees))
9080 (org-hide-archived-subtrees (point-min) (point-max)))
9081 (nreverse rtn)))
9083 (defun org-remove-uniherited-tags (tags)
9084 "Remove all tags that are not inherited from the list TAGS."
9085 (cond
9086 ((eq org-use-tag-inheritance t) tags)
9087 ((not org-use-tag-inheritance) nil)
9088 ((stringp org-use-tag-inheritance)
9089 (delq nil (mapcar
9090 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9091 tags)))
9092 ((listp org-use-tag-inheritance)
9093 (delq nil (mapcar
9094 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
9095 tags)))))
9097 (defvar todo-only) ;; dynamically scoped
9099 (defun org-tags-sparse-tree (&optional todo-only match)
9100 "Create a sparse tree according to tags string MATCH.
9101 MATCH can contain positive and negative selection of tags, like
9102 \"+WORK+URGENT-WITHBOSS\".
9103 If optional argument TODO-ONLY is non-nil, only select lines that are
9104 also TODO lines."
9105 (interactive "P")
9106 (org-prepare-agenda-buffers (list (current-buffer)))
9107 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9109 (defvar org-cached-props nil)
9110 (defun org-cached-entry-get (pom property)
9111 (if (or (eq t org-use-property-inheritance)
9112 (and (stringp org-use-property-inheritance)
9113 (string-match org-use-property-inheritance property))
9114 (and (listp org-use-property-inheritance)
9115 (member property org-use-property-inheritance)))
9116 ;; Caching is not possible, check it directly
9117 (org-entry-get pom property 'inherit)
9118 ;; Get all properties, so that we can do complicated checks easily
9119 (cdr (assoc property (or org-cached-props
9120 (setq org-cached-props
9121 (org-entry-properties pom)))))))
9123 (defun org-global-tags-completion-table (&optional files)
9124 "Return the list of all tags in all agenda buffer/files."
9125 (save-excursion
9126 (org-uniquify
9127 (delq nil
9128 (apply 'append
9129 (mapcar
9130 (lambda (file)
9131 (set-buffer (find-file-noselect file))
9132 (append (org-get-buffer-tags)
9133 (mapcar (lambda (x) (if (stringp (car-safe x))
9134 (list (car-safe x)) nil))
9135 org-tag-alist)))
9136 (if (and files (car files))
9137 files
9138 (org-agenda-files))))))))
9140 (defun org-make-tags-matcher (match)
9141 "Create the TAGS//TODO matcher form for the selection string MATCH."
9142 ;; todo-only is scoped dynamically into this function, and the function
9143 ;; may change it it the matcher asksk for it.
9144 (unless match
9145 ;; Get a new match request, with completion
9146 (let ((org-last-tags-completion-table
9147 (org-global-tags-completion-table)))
9148 (setq match (org-ido-completing-read
9149 "Match: " 'org-tags-completion-function nil nil nil
9150 'org-tags-history))))
9152 ;; Parse the string and create a lisp form
9153 (let ((match0 match)
9154 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9155 minus tag mm
9156 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9157 orterms term orlist re-p str-p level-p level-op time-p
9158 prop-p pn pv po cat-p gv rest)
9159 (if (string-match "/+" match)
9160 ;; match contains also a todo-matching request
9161 (progn
9162 (setq tagsmatch (substring match 0 (match-beginning 0))
9163 todomatch (substring match (match-end 0)))
9164 (if (string-match "^!" todomatch)
9165 (setq todo-only t todomatch (substring todomatch 1)))
9166 (if (string-match "^\\s-*$" todomatch)
9167 (setq todomatch nil)))
9168 ;; only matching tags
9169 (setq tagsmatch match todomatch nil))
9171 ;; Make the tags matcher
9172 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9173 (setq tagsmatcher t)
9174 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9175 (while (setq term (pop orterms))
9176 (while (and (equal (substring term -1) "\\") orterms)
9177 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9178 (while (string-match re term)
9179 (setq rest (substring term (match-end 0))
9180 minus (and (match-end 1)
9181 (equal (match-string 1 term) "-"))
9182 tag (match-string 2 term)
9183 re-p (equal (string-to-char tag) ?{)
9184 level-p (match-end 4)
9185 prop-p (match-end 5)
9186 mm (cond
9187 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9188 (level-p
9189 (setq level-op (org-op-to-function (match-string 3 term)))
9190 `(,level-op level ,(string-to-number
9191 (match-string 4 term))))
9192 (prop-p
9193 (setq pn (match-string 5 term)
9194 po (match-string 6 term)
9195 pv (match-string 7 term)
9196 cat-p (equal pn "CATEGORY")
9197 re-p (equal (string-to-char pv) ?{)
9198 str-p (equal (string-to-char pv) ?\")
9199 time-p (save-match-data
9200 (string-match "^\"[[<].*[]>]\"$" pv))
9201 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9202 (if time-p (setq pv (org-matcher-time pv)))
9203 (setq po (org-op-to-function po (if time-p 'time str-p)))
9204 (cond
9205 ((equal pn "CATEGORY")
9206 (setq gv '(get-text-property (point) 'org-category)))
9207 ((equal pn "TODO")
9208 (setq gv 'todo))
9210 (setq gv `(org-cached-entry-get nil ,pn))))
9211 (if re-p
9212 (if (eq po 'org<>)
9213 `(not (string-match ,pv (or ,gv "")))
9214 `(string-match ,pv (or ,gv "")))
9215 (if str-p
9216 `(,po (or ,gv "") ,pv)
9217 `(,po (string-to-number (or ,gv ""))
9218 ,(string-to-number pv) ))))
9219 (t `(member ,(downcase tag) tags-list)))
9220 mm (if minus (list 'not mm) mm)
9221 term rest)
9222 (push mm tagsmatcher))
9223 (push (if (> (length tagsmatcher) 1)
9224 (cons 'and tagsmatcher)
9225 (car tagsmatcher))
9226 orlist)
9227 (setq tagsmatcher nil))
9228 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9229 (setq tagsmatcher
9230 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9231 ;; Make the todo matcher
9232 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9233 (setq todomatcher t)
9234 (setq orterms (org-split-string todomatch "|") orlist nil)
9235 (while (setq term (pop orterms))
9236 (while (string-match re term)
9237 (setq minus (and (match-end 1)
9238 (equal (match-string 1 term) "-"))
9239 kwd (match-string 2 term)
9240 re-p (equal (string-to-char kwd) ?{)
9241 term (substring term (match-end 0))
9242 mm (if re-p
9243 `(string-match ,(substring kwd 1 -1) todo)
9244 (list 'equal 'todo kwd))
9245 mm (if minus (list 'not mm) mm))
9246 (push mm todomatcher))
9247 (push (if (> (length todomatcher) 1)
9248 (cons 'and todomatcher)
9249 (car todomatcher))
9250 orlist)
9251 (setq todomatcher nil))
9252 (setq todomatcher (if (> (length orlist) 1)
9253 (cons 'or orlist) (car orlist))))
9255 ;; Return the string and lisp forms of the matcher
9256 (setq matcher (if todomatcher
9257 (list 'and tagsmatcher todomatcher)
9258 tagsmatcher))
9259 (cons match0 matcher)))
9261 (defun org-op-to-function (op &optional stringp)
9262 "Turn an operator into the appropriate function."
9263 (setq op
9264 (cond
9265 ((equal op "<" ) '(< string< org-time<))
9266 ((equal op ">" ) '(> org-string> org-time>))
9267 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9268 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9269 ((member op '("=" "==")) '(= string= org-time=))
9270 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9271 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9273 (defun org<> (a b) (not (= a b)))
9274 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9275 (defun org-string>= (a b) (not (string< a b)))
9276 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9277 (defun org-string<> (a b) (not (string= a b)))
9278 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9279 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9280 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9281 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9282 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9283 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9284 (defun org-2ft (s)
9285 "Convert S to a floating point time.
9286 If S is already a number, just return it. If it is a string, parse
9287 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9288 (cond
9289 ((numberp s) s)
9290 ((stringp s)
9291 (condition-case nil
9292 (float-time (apply 'encode-time (org-parse-time-string s)))
9293 (error 0.)))
9294 (t 0.)))
9296 (defun org-time-today ()
9297 "Time in seconds today at 0:00.
9298 Returns the float number of seconds since the beginning of the
9299 epoch to the beginning of today (00:00)."
9300 (float-time (apply 'encode-time
9301 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9303 (defun org-matcher-time (s)
9304 (cond
9305 ((string= s "<now>") (float-time))
9306 ((string= s "<today>") (org-time-today))
9307 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9308 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9309 (t (org-2ft s))))
9311 (defun org-match-any-p (re list)
9312 "Does re match any element of list?"
9313 (setq list (mapcar (lambda (x) (string-match re x)) list))
9314 (delq nil list))
9316 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9317 (defvar org-tags-overlay (org-make-overlay 1 1))
9318 (org-detach-overlay org-tags-overlay)
9320 (defun org-get-local-tags-at (&optional pos)
9321 "Get a list of tags defined in the current headline."
9322 (org-get-tags-at pos 'local))
9324 (defun org-get-local-tags ()
9325 "Get a list of tags defined in the current headline."
9326 (org-get-tags-at nil 'local))
9328 (defun org-get-tags-at (&optional pos local)
9329 "Get a list of all headline tags applicable at POS.
9330 POS defaults to point. If tags are inherited, the list contains
9331 the targets in the same sequence as the headlines appear, i.e.
9332 the tags of the current headline come last.
9333 When LOCAL is non-nil, only return tags from the current headline,
9334 ignore inherited ones."
9335 (interactive)
9336 (let (tags ltags lastpos parent)
9337 (save-excursion
9338 (save-restriction
9339 (widen)
9340 (goto-char (or pos (point)))
9341 (save-match-data
9342 (catch 'done
9343 (condition-case nil
9344 (progn
9345 (org-back-to-heading t)
9346 (while (not (equal lastpos (point)))
9347 (setq lastpos (point))
9348 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9349 (setq ltags (org-split-string
9350 (org-match-string-no-properties 1) ":"))
9351 (setq tags (append
9352 (if parent
9353 (org-remove-uniherited-tags ltags)
9354 ltags)
9355 tags)))
9356 (or org-use-tag-inheritance (throw 'done t))
9357 (if local (throw 'done t))
9358 (org-up-heading-all 1)
9359 (setq parent t)))
9360 (error nil)))))
9361 (append (org-remove-uniherited-tags org-file-tags) tags))))
9363 (defun org-toggle-tag (tag &optional onoff)
9364 "Toggle the tag TAG for the current line.
9365 If ONOFF is `on' or `off', don't toggle but set to this state."
9366 (unless (org-on-heading-p t) (error "Not on headling"))
9367 (let (res current)
9368 (save-excursion
9369 (beginning-of-line)
9370 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9371 (point-at-eol) t)
9372 (progn
9373 (setq current (match-string 1))
9374 (replace-match ""))
9375 (setq current ""))
9376 (setq current (nreverse (org-split-string current ":")))
9377 (cond
9378 ((eq onoff 'on)
9379 (setq res t)
9380 (or (member tag current) (push tag current)))
9381 ((eq onoff 'off)
9382 (or (not (member tag current)) (setq current (delete tag current))))
9383 (t (if (member tag current)
9384 (setq current (delete tag current))
9385 (setq res t)
9386 (push tag current))))
9387 (end-of-line 1)
9388 (if current
9389 (progn
9390 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9391 (org-set-tags nil t))
9392 (delete-horizontal-space))
9393 (run-hooks 'org-after-tags-change-hook))
9394 res))
9396 (defun org-align-tags-here (to-col)
9397 ;; Assumes that this is a headline
9398 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9399 (beginning-of-line 1)
9400 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9401 (< pos (match-beginning 2)))
9402 (progn
9403 (setq tags-l (- (match-end 2) (match-beginning 2)))
9404 (goto-char (match-beginning 1))
9405 (insert " ")
9406 (delete-region (point) (1+ (match-beginning 2)))
9407 (setq ncol (max (1+ (current-column))
9408 (1+ col)
9409 (if (> to-col 0)
9410 to-col
9411 (- (abs to-col) tags-l))))
9412 (setq p (point))
9413 (insert (make-string (- ncol (current-column)) ?\ ))
9414 (setq ncol (current-column))
9415 (when indent-tabs-mode (tabify p (point-at-eol)))
9416 (org-move-to-column (min ncol col) t))
9417 (goto-char pos))))
9419 (defun org-set-tags-command (&optional arg just-align)
9420 "Call the set-tags command for the current entry."
9421 (interactive "P")
9422 (if (org-on-heading-p)
9423 (org-set-tags arg just-align)
9424 (save-excursion
9425 (org-back-to-heading t)
9426 (org-set-tags arg just-align))))
9428 (defun org-set-tags (&optional arg just-align)
9429 "Set the tags for the current headline.
9430 With prefix ARG, realign all tags in headings in the current buffer."
9431 (interactive "P")
9432 (let* ((re (concat "^" outline-regexp))
9433 (current (org-get-tags-string))
9434 (col (current-column))
9435 (org-setting-tags t)
9436 table current-tags inherited-tags ; computed below when needed
9437 tags p0 c0 c1 rpl)
9438 (if arg
9439 (save-excursion
9440 (goto-char (point-min))
9441 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9442 (while (re-search-forward re nil t)
9443 (org-set-tags nil t)
9444 (end-of-line 1)))
9445 (message "All tags realigned to column %d" org-tags-column))
9446 (if just-align
9447 (setq tags current)
9448 ;; Get a new set of tags from the user
9449 (save-excursion
9450 (setq table (or org-tag-alist (org-get-buffer-tags))
9451 org-last-tags-completion-table table
9452 current-tags (org-split-string current ":")
9453 inherited-tags (nreverse
9454 (nthcdr (length current-tags)
9455 (nreverse (org-get-tags-at))))
9456 tags
9457 (if (or (eq t org-use-fast-tag-selection)
9458 (and org-use-fast-tag-selection
9459 (delq nil (mapcar 'cdr table))))
9460 (org-fast-tag-selection
9461 current-tags inherited-tags table
9462 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9463 (let ((org-add-colon-after-tag-completion t))
9464 (org-trim
9465 (org-without-partial-completion
9466 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9467 nil nil current 'org-tags-history)))))))
9468 (while (string-match "[-+&]+" tags)
9469 ;; No boolean logic, just a list
9470 (setq tags (replace-match ":" t t tags))))
9472 (if (string-match "\\`[\t ]*\\'" tags)
9473 (setq tags "")
9474 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9475 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9477 ;; Insert new tags at the correct column
9478 (beginning-of-line 1)
9479 (cond
9480 ((and (equal current "") (equal tags "")))
9481 ((re-search-forward
9482 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9483 (point-at-eol) t)
9484 (if (equal tags "")
9485 (setq rpl "")
9486 (goto-char (match-beginning 0))
9487 (setq c0 (current-column) p0 (point)
9488 c1 (max (1+ c0) (if (> org-tags-column 0)
9489 org-tags-column
9490 (- (- org-tags-column) (length tags))))
9491 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9492 (replace-match rpl t t)
9493 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9494 tags)
9495 (t (error "Tags alignment failed")))
9496 (org-move-to-column col)
9497 (unless just-align
9498 (run-hooks 'org-after-tags-change-hook)))))
9500 (defun org-change-tag-in-region (beg end tag off)
9501 "Add or remove TAG for each entry in the region.
9502 This works in the agenda, and also in an org-mode buffer."
9503 (interactive
9504 (list (region-beginning) (region-end)
9505 (let ((org-last-tags-completion-table
9506 (if (org-mode-p)
9507 (org-get-buffer-tags)
9508 (org-global-tags-completion-table))))
9509 (org-ido-completing-read
9510 "Tag: " 'org-tags-completion-function nil nil nil
9511 'org-tags-history))
9512 (progn
9513 (message "[s]et or [r]emove? ")
9514 (equal (read-char-exclusive) ?r))))
9515 (if (fboundp 'deactivate-mark) (deactivate-mark))
9516 (let ((agendap (equal major-mode 'org-agenda-mode))
9517 l1 l2 m buf pos newhead (cnt 0))
9518 (goto-char end)
9519 (setq l2 (1- (org-current-line)))
9520 (goto-char beg)
9521 (setq l1 (org-current-line))
9522 (loop for l from l1 to l2 do
9523 (goto-line l)
9524 (setq m (get-text-property (point) 'org-hd-marker))
9525 (when (or (and (org-mode-p) (org-on-heading-p))
9526 (and agendap m))
9527 (setq buf (if agendap (marker-buffer m) (current-buffer))
9528 pos (if agendap m (point)))
9529 (with-current-buffer buf
9530 (save-excursion
9531 (save-restriction
9532 (goto-char pos)
9533 (setq cnt (1+ cnt))
9534 (org-toggle-tag tag (if off 'off 'on))
9535 (setq newhead (org-get-heading)))))
9536 (and agendap (org-agenda-change-all-lines newhead m))))
9537 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9539 (defun org-tags-completion-function (string predicate &optional flag)
9540 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9541 (confirm (lambda (x) (stringp (car x)))))
9542 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9543 (setq s1 (match-string 1 string)
9544 s2 (match-string 2 string))
9545 (setq s1 "" s2 string))
9546 (cond
9547 ((eq flag nil)
9548 ;; try completion
9549 (setq rtn (try-completion s2 ctable confirm))
9550 (if (stringp rtn)
9551 (setq rtn
9552 (concat s1 s2 (substring rtn (length s2))
9553 (if (and org-add-colon-after-tag-completion
9554 (assoc rtn ctable))
9555 ":" ""))))
9556 rtn)
9557 ((eq flag t)
9558 ;; all-completions
9559 (all-completions s2 ctable confirm)
9561 ((eq flag 'lambda)
9562 ;; exact match?
9563 (assoc s2 ctable)))
9566 (defun org-fast-tag-insert (kwd tags face &optional end)
9567 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9568 (insert (format "%-12s" (concat kwd ":"))
9569 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9570 (or end "")))
9572 (defun org-fast-tag-show-exit (flag)
9573 (save-excursion
9574 (goto-line 3)
9575 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9576 (replace-match ""))
9577 (when flag
9578 (end-of-line 1)
9579 (org-move-to-column (- (window-width) 19) t)
9580 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9582 (defun org-set-current-tags-overlay (current prefix)
9583 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9584 (if (featurep 'xemacs)
9585 (org-overlay-display org-tags-overlay (concat prefix s)
9586 'secondary-selection)
9587 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9588 (org-overlay-display org-tags-overlay (concat prefix s)))))
9590 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9591 "Fast tag selection with single keys.
9592 CURRENT is the current list of tags in the headline, INHERITED is the
9593 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9594 possibly with grouping information. TODO-TABLE is a similar table with
9595 TODO keywords, should these have keys assigned to them.
9596 If the keys are nil, a-z are automatically assigned.
9597 Returns the new tags string, or nil to not change the current settings."
9598 (let* ((fulltable (append table todo-table))
9599 (maxlen (apply 'max (mapcar
9600 (lambda (x)
9601 (if (stringp (car x)) (string-width (car x)) 0))
9602 fulltable)))
9603 (buf (current-buffer))
9604 (expert (eq org-fast-tag-selection-single-key 'expert))
9605 (buffer-tags nil)
9606 (fwidth (+ maxlen 3 1 3))
9607 (ncol (/ (- (window-width) 4) fwidth))
9608 (i-face 'org-done)
9609 (c-face 'org-todo)
9610 tg cnt e c char c1 c2 ntable tbl rtn
9611 ov-start ov-end ov-prefix
9612 (exit-after-next org-fast-tag-selection-single-key)
9613 (done-keywords org-done-keywords)
9614 groups ingroup)
9615 (save-excursion
9616 (beginning-of-line 1)
9617 (if (looking-at
9618 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9619 (setq ov-start (match-beginning 1)
9620 ov-end (match-end 1)
9621 ov-prefix "")
9622 (setq ov-start (1- (point-at-eol))
9623 ov-end (1+ ov-start))
9624 (skip-chars-forward "^\n\r")
9625 (setq ov-prefix
9626 (concat
9627 (buffer-substring (1- (point)) (point))
9628 (if (> (current-column) org-tags-column)
9630 (make-string (- org-tags-column (current-column)) ?\ ))))))
9631 (org-move-overlay org-tags-overlay ov-start ov-end)
9632 (save-window-excursion
9633 (if expert
9634 (set-buffer (get-buffer-create " *Org tags*"))
9635 (delete-other-windows)
9636 (split-window-vertically)
9637 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9638 (erase-buffer)
9639 (org-set-local 'org-done-keywords done-keywords)
9640 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9641 (org-fast-tag-insert "Current" current c-face "\n\n")
9642 (org-fast-tag-show-exit exit-after-next)
9643 (org-set-current-tags-overlay current ov-prefix)
9644 (setq tbl fulltable char ?a cnt 0)
9645 (while (setq e (pop tbl))
9646 (cond
9647 ((equal e '(:startgroup))
9648 (push '() groups) (setq ingroup t)
9649 (when (not (= cnt 0))
9650 (setq cnt 0)
9651 (insert "\n"))
9652 (insert "{ "))
9653 ((equal e '(:endgroup))
9654 (setq ingroup nil cnt 0)
9655 (insert "}\n"))
9657 (setq tg (car e) c2 nil)
9658 (if (cdr e)
9659 (setq c (cdr e))
9660 ;; automatically assign a character.
9661 (setq c1 (string-to-char
9662 (downcase (substring
9663 tg (if (= (string-to-char tg) ?@) 1 0)))))
9664 (if (or (rassoc c1 ntable) (rassoc c1 table))
9665 (while (or (rassoc char ntable) (rassoc char table))
9666 (setq char (1+ char)))
9667 (setq c2 c1))
9668 (setq c (or c2 char)))
9669 (if ingroup (push tg (car groups)))
9670 (setq tg (org-add-props tg nil 'face
9671 (cond
9672 ((not (assoc tg table))
9673 (org-get-todo-face tg))
9674 ((member tg current) c-face)
9675 ((member tg inherited) i-face)
9676 (t nil))))
9677 (if (and (= cnt 0) (not ingroup)) (insert " "))
9678 (insert "[" c "] " tg (make-string
9679 (- fwidth 4 (length tg)) ?\ ))
9680 (push (cons tg c) ntable)
9681 (when (= (setq cnt (1+ cnt)) ncol)
9682 (insert "\n")
9683 (if ingroup (insert " "))
9684 (setq cnt 0)))))
9685 (setq ntable (nreverse ntable))
9686 (insert "\n")
9687 (goto-char (point-min))
9688 (if (not expert) (org-fit-window-to-buffer))
9689 (setq rtn
9690 (catch 'exit
9691 (while t
9692 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9693 (if groups " [!] no groups" " [!]groups")
9694 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9695 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9696 (cond
9697 ((= c ?\r) (throw 'exit t))
9698 ((= c ?!)
9699 (setq groups (not groups))
9700 (goto-char (point-min))
9701 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9702 ((= c ?\C-c)
9703 (if (not expert)
9704 (org-fast-tag-show-exit
9705 (setq exit-after-next (not exit-after-next)))
9706 (setq expert nil)
9707 (delete-other-windows)
9708 (split-window-vertically)
9709 (org-switch-to-buffer-other-window " *Org tags*")
9710 (org-fit-window-to-buffer)))
9711 ((or (= c ?\C-g)
9712 (and (= c ?q) (not (rassoc c ntable))))
9713 (org-detach-overlay org-tags-overlay)
9714 (setq quit-flag t))
9715 ((= c ?\ )
9716 (setq current nil)
9717 (if exit-after-next (setq exit-after-next 'now)))
9718 ((= c ?\t)
9719 (condition-case nil
9720 (setq tg (org-ido-completing-read
9721 "Tag: "
9722 (or buffer-tags
9723 (with-current-buffer buf
9724 (org-get-buffer-tags)))))
9725 (quit (setq tg "")))
9726 (when (string-match "\\S-" tg)
9727 (add-to-list 'buffer-tags (list tg))
9728 (if (member tg current)
9729 (setq current (delete tg current))
9730 (push tg current)))
9731 (if exit-after-next (setq exit-after-next 'now)))
9732 ((setq e (rassoc c todo-table) tg (car e))
9733 (with-current-buffer buf
9734 (save-excursion (org-todo tg)))
9735 (if exit-after-next (setq exit-after-next 'now)))
9736 ((setq e (rassoc c ntable) tg (car e))
9737 (if (member tg current)
9738 (setq current (delete tg current))
9739 (loop for g in groups do
9740 (if (member tg g)
9741 (mapc (lambda (x)
9742 (setq current (delete x current)))
9743 g)))
9744 (push tg current))
9745 (if exit-after-next (setq exit-after-next 'now))))
9747 ;; Create a sorted list
9748 (setq current
9749 (sort current
9750 (lambda (a b)
9751 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9752 (if (eq exit-after-next 'now) (throw 'exit t))
9753 (goto-char (point-min))
9754 (beginning-of-line 2)
9755 (delete-region (point) (point-at-eol))
9756 (org-fast-tag-insert "Current" current c-face)
9757 (org-set-current-tags-overlay current ov-prefix)
9758 (while (re-search-forward
9759 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9760 (setq tg (match-string 1))
9761 (add-text-properties
9762 (match-beginning 1) (match-end 1)
9763 (list 'face
9764 (cond
9765 ((member tg current) c-face)
9766 ((member tg inherited) i-face)
9767 (t (get-text-property (match-beginning 1) 'face))))))
9768 (goto-char (point-min)))))
9769 (org-detach-overlay org-tags-overlay)
9770 (if rtn
9771 (mapconcat 'identity current ":")
9772 nil))))
9774 (defun org-get-tags-string ()
9775 "Get the TAGS string in the current headline."
9776 (unless (org-on-heading-p t)
9777 (error "Not on a heading"))
9778 (save-excursion
9779 (beginning-of-line 1)
9780 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9781 (org-match-string-no-properties 1)
9782 "")))
9784 (defun org-get-tags ()
9785 "Get the list of tags specified in the current headline."
9786 (org-split-string (org-get-tags-string) ":"))
9788 (defun org-get-buffer-tags ()
9789 "Get a table of all tags used in the buffer, for completion."
9790 (let (tags)
9791 (save-excursion
9792 (goto-char (point-min))
9793 (while (re-search-forward
9794 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9795 (when (equal (char-after (point-at-bol 0)) ?*)
9796 (mapc (lambda (x) (add-to-list 'tags x))
9797 (org-split-string (org-match-string-no-properties 1) ":")))))
9798 (mapcar 'list tags)))
9800 ;;;; The mapping API
9802 ;;;###autoload
9803 (defun org-map-entries (func &optional match scope &rest skip)
9804 "Call FUNC at each headline selected by MATCH in SCOPE.
9806 FUNC is a function or a lisp form. The function will be called without
9807 arguments, with the cursor positioned at the beginning of the headline.
9808 The return values of all calls to the function will be collected and
9809 returned as a list.
9811 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9812 Only headlines that are matched by this query will be considered during
9813 the iteration. When MATCH is nil or t, all headlines will be
9814 visited by the iteration.
9816 SCOPE determines the scope of this command. It can be any of:
9818 nil The current buffer, respecting the restriction if any
9819 tree The subtree started with the entry at point
9820 file The current buffer, without restriction
9821 file-with-archives
9822 The current buffer, and any archives associated with it
9823 agenda All agenda files
9824 agenda-with-archives
9825 All agenda files with any archive files associated with them
9826 \(file1 file2 ...)
9827 If this is a list, all files in the list will be scanned
9829 The remaining args are treated as settings for the skipping facilities of
9830 the scanner. The following items can be given here:
9832 archive skip trees with the archive tag.
9833 comment skip trees with the COMMENT keyword
9834 function or Emacs Lisp form:
9835 will be used as value for `org-agenda-skip-function', so whenever
9836 the the function returns t, FUNC will not be called for that
9837 entry and search will continue from the point where the
9838 function leaves it."
9839 (let* ((org-agenda-archives-mode nil) ; just to make sure
9840 (org-agenda-skip-archived-trees (memq 'archive skip))
9841 (org-agenda-skip-comment-trees (memq 'comment skip))
9842 (org-agenda-skip-function
9843 (car (org-delete-all '(comment archive) skip)))
9844 (org-tags-match-list-sublevels t)
9845 matcher pos file
9846 org-todo-keywords-for-agenda
9847 org-done-keywords-for-agenda
9848 org-todo-keyword-alist-for-agenda
9849 org-tag-alist-for-agenda)
9851 (cond
9852 ((eq match t) (setq matcher t))
9853 ((eq match nil) (setq matcher t))
9854 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9856 (when (eq scope 'tree)
9857 (org-back-to-heading t)
9858 (org-narrow-to-subtree)
9859 (setq scope nil))
9861 (if (not scope)
9862 (progn
9863 (org-prepare-agenda-buffers
9864 (list (buffer-file-name (current-buffer))))
9865 (org-scan-tags func matcher))
9866 ;; Get the right scope
9867 (setq pos (point))
9868 (cond
9869 ((and scope (listp scope) (symbolp (car scope)))
9870 (setq scope (eval scope)))
9871 ((eq scope 'agenda)
9872 (setq scope (org-agenda-files t)))
9873 ((eq scope 'agenda-with-archives)
9874 (setq scope (org-agenda-files t))
9875 (setq scope (org-add-archive-files scope)))
9876 ((eq scope 'file)
9877 (setq scope (list (buffer-file-name))))
9878 ((eq scope 'file-with-archives)
9879 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9880 (org-prepare-agenda-buffers scope)
9881 (while (setq file (pop scope))
9882 (with-current-buffer (org-find-base-buffer-visiting file)
9883 (save-excursion
9884 (save-restriction
9885 (widen)
9886 (goto-char (point-min))
9887 (org-scan-tags func matcher))))))))
9889 ;;;; Properties
9891 ;;; Setting and retrieving properties
9893 (defconst org-special-properties
9894 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9895 "TIMESTAMP" "TIMESTAMP_IA")
9896 "The special properties valid in Org-mode.
9898 These are properties that are not defined in the property drawer,
9899 but in some other way.")
9901 (defconst org-default-properties
9902 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9903 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9904 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9905 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9906 "Some properties that are used by Org-mode for various purposes.
9907 Being in this list makes sure that they are offered for completion.")
9909 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9910 "Regular expression matching the first line of a property drawer.")
9912 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9913 "Regular expression matching the first line of a property drawer.")
9915 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9916 "Regular expression matching the first line of a property drawer.")
9918 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9919 "Regular expression matching the first line of a property drawer.")
9921 (defconst org-property-drawer-re
9922 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9923 org-property-end-re "\\)\n?")
9924 "Matches an entire property drawer.")
9926 (defconst org-clock-drawer-re
9927 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9928 org-property-end-re "\\)\n?")
9929 "Matches an entire clock drawer.")
9931 (defun org-property-action ()
9932 "Do an action on properties."
9933 (interactive)
9934 (let (c)
9935 (org-at-property-p)
9936 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9937 (setq c (read-char-exclusive))
9938 (cond
9939 ((equal c ?s)
9940 (call-interactively 'org-set-property))
9941 ((equal c ?d)
9942 (call-interactively 'org-delete-property))
9943 ((equal c ?D)
9944 (call-interactively 'org-delete-property-globally))
9945 ((equal c ?c)
9946 (call-interactively 'org-compute-property-at-point))
9947 (t (error "No such property action %c" c)))))
9949 (defun org-at-property-p ()
9950 "Is the cursor in a property line?"
9951 ;; FIXME: Does not check if we are actually in the drawer.
9952 ;; FIXME: also returns true on any drawers.....
9953 ;; This is used by C-c C-c for property action.
9954 (save-excursion
9955 (beginning-of-line 1)
9956 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9958 (defun org-get-property-block (&optional beg end force)
9959 "Return the (beg . end) range of the body of the property drawer.
9960 BEG and END can be beginning and end of subtree, if not given
9961 they will be found.
9962 If the drawer does not exist and FORCE is non-nil, create the drawer."
9963 (catch 'exit
9964 (save-excursion
9965 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9966 (end (or end (progn (outline-next-heading) (point)))))
9967 (goto-char beg)
9968 (if (re-search-forward org-property-start-re end t)
9969 (setq beg (1+ (match-end 0)))
9970 (if force
9971 (save-excursion
9972 (org-insert-property-drawer)
9973 (setq end (progn (outline-next-heading) (point))))
9974 (throw 'exit nil))
9975 (goto-char beg)
9976 (if (re-search-forward org-property-start-re end t)
9977 (setq beg (1+ (match-end 0)))))
9978 (if (re-search-forward org-property-end-re end t)
9979 (setq end (match-beginning 0))
9980 (or force (throw 'exit nil))
9981 (goto-char beg)
9982 (setq end beg)
9983 (org-indent-line-function)
9984 (insert ":END:\n"))
9985 (cons beg end)))))
9987 (defun org-entry-properties (&optional pom which)
9988 "Get all properties of the entry at point-or-marker POM.
9989 This includes the TODO keyword, the tags, time strings for deadline,
9990 scheduled, and clocking, and any additional properties defined in the
9991 entry. The return value is an alist, keys may occur multiple times
9992 if the property key was used several times.
9993 POM may also be nil, in which case the current entry is used.
9994 If WHICH is nil or `all', get all properties. If WHICH is
9995 `special' or `standard', only get that subclass."
9996 (setq which (or which 'all))
9997 (org-with-point-at pom
9998 (let ((clockstr (substring org-clock-string 0 -1))
9999 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10000 beg end range props sum-props key value string clocksum)
10001 (save-excursion
10002 (when (condition-case nil (org-back-to-heading t) (error nil))
10003 (setq beg (point))
10004 (setq sum-props (get-text-property (point) 'org-summaries))
10005 (setq clocksum (get-text-property (point) :org-clock-minutes))
10006 (outline-next-heading)
10007 (setq end (point))
10008 (when (memq which '(all special))
10009 ;; Get the special properties, like TODO and tags
10010 (goto-char beg)
10011 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10012 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10013 (when (looking-at org-priority-regexp)
10014 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10015 (when (and (setq value (org-get-tags-string))
10016 (string-match "\\S-" value))
10017 (push (cons "TAGS" value) props))
10018 (when (setq value (org-get-tags-at))
10019 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10020 props))
10021 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10022 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10023 string (if (equal key clockstr)
10024 (org-no-properties
10025 (org-trim
10026 (buffer-substring
10027 (match-beginning 3) (goto-char (point-at-eol)))))
10028 (substring (org-match-string-no-properties 3) 1 -1)))
10029 (unless key
10030 (if (= (char-after (match-beginning 3)) ?\[)
10031 (setq key "TIMESTAMP_IA")
10032 (setq key "TIMESTAMP")))
10033 (when (or (equal key clockstr) (not (assoc key props)))
10034 (push (cons key string) props)))
10038 (when (memq which '(all standard))
10039 ;; Get the standard properties, like :PORP: ...
10040 (setq range (org-get-property-block beg end))
10041 (when range
10042 (goto-char (car range))
10043 (while (re-search-forward
10044 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10045 (cdr range) t)
10046 (setq key (org-match-string-no-properties 1)
10047 value (org-trim (or (org-match-string-no-properties 2) "")))
10048 (unless (member key excluded)
10049 (push (cons key (or value "")) props)))))
10050 (if clocksum
10051 (push (cons "CLOCKSUM"
10052 (org-columns-number-to-string (/ (float clocksum) 60.)
10053 'add_times))
10054 props))
10055 (unless (assoc "CATEGORY" props)
10056 (setq value (or (org-get-category)
10057 (progn (org-refresh-category-properties)
10058 (org-get-category))))
10059 (push (cons "CATEGORY" value) props))
10060 (append sum-props (nreverse props)))))))
10062 (defun org-entry-get (pom property &optional inherit)
10063 "Get value of PROPERTY for entry at point-or-marker POM.
10064 If INHERIT is non-nil and the entry does not have the property,
10065 then also check higher levels of the hierarchy.
10066 If INHERIT is the symbol `selective', use inheritance only if the setting
10067 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10068 If the property is present but empty, the return value is the empty string.
10069 If the property is not present at all, nil is returned."
10070 (org-with-point-at pom
10071 (if (and inherit (if (eq inherit 'selective)
10072 (org-property-inherit-p property)
10074 (org-entry-get-with-inheritance property)
10075 (if (member property org-special-properties)
10076 ;; We need a special property. Use brute force, get all properties.
10077 (cdr (assoc property (org-entry-properties nil 'special)))
10078 (let ((range (org-get-property-block)))
10079 (if (and range
10080 (goto-char (car range))
10081 (re-search-forward
10082 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10083 (cdr range) t))
10084 ;; Found the property, return it.
10085 (if (match-end 1)
10086 (org-match-string-no-properties 1)
10087 "")))))))
10089 (defun org-property-or-variable-value (var &optional inherit)
10090 "Check if there is a property fixing the value of VAR.
10091 If yes, return this value. If not, return the current value of the variable."
10092 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10093 (if (and prop (stringp prop) (string-match "\\S-" prop))
10094 (read prop)
10095 (symbol-value var))))
10097 (defun org-entry-delete (pom property)
10098 "Delete the property PROPERTY from entry at point-or-marker POM."
10099 (org-with-point-at pom
10100 (if (member property org-special-properties)
10101 nil ; cannot delete these properties.
10102 (let ((range (org-get-property-block)))
10103 (if (and range
10104 (goto-char (car range))
10105 (re-search-forward
10106 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10107 (cdr range) t))
10108 (progn
10109 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10111 nil)))))
10113 ;; Multi-values properties are properties that contain multiple values
10114 ;; These values are assumed to be single words, separated by whitespace.
10115 (defun org-entry-add-to-multivalued-property (pom property value)
10116 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10117 (let* ((old (org-entry-get pom property))
10118 (values (and old (org-split-string old "[ \t]"))))
10119 (setq value (org-entry-protect-space value))
10120 (unless (member value values)
10121 (setq values (cons value values))
10122 (org-entry-put pom property
10123 (mapconcat 'identity values " ")))))
10125 (defun org-entry-remove-from-multivalued-property (pom property value)
10126 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10127 (let* ((old (org-entry-get pom property))
10128 (values (and old (org-split-string old "[ \t]"))))
10129 (setq value (org-entry-protect-space value))
10130 (when (member value values)
10131 (setq values (delete value values))
10132 (org-entry-put pom property
10133 (mapconcat 'identity values " ")))))
10135 (defun org-entry-member-in-multivalued-property (pom property value)
10136 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10137 (let* ((old (org-entry-get pom property))
10138 (values (and old (org-split-string old "[ \t]"))))
10139 (setq value (org-entry-protect-space value))
10140 (member value values)))
10142 (defun org-entry-get-multivalued-property (pom property)
10143 "Return a list of values in a multivalued property."
10144 (let* ((value (org-entry-get pom property))
10145 (values (and value (org-split-string value "[ \t]"))))
10146 (mapcar 'org-entry-restore-space values)))
10148 (defun org-entry-put-multivalued-property (pom property &rest values)
10149 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10150 VALUES should be a list of strings. Spaces will be protected."
10151 (org-entry-put pom property
10152 (mapconcat 'org-entry-protect-space values " "))
10153 (let* ((value (org-entry-get pom property))
10154 (values (and value (org-split-string value "[ \t]"))))
10155 (mapcar 'org-entry-restore-space values)))
10157 (defun org-entry-protect-space (s)
10158 "Protect spaces and newline in string S."
10159 (while (string-match " " s)
10160 (setq s (replace-match "%20" t t s)))
10161 (while (string-match "\n" s)
10162 (setq s (replace-match "%0A" t t s)))
10165 (defun org-entry-restore-space (s)
10166 "Restore spaces and newline in string S."
10167 (while (string-match "%20" s)
10168 (setq s (replace-match " " t t s)))
10169 (while (string-match "%0A" s)
10170 (setq s (replace-match "\n" t t s)))
10173 (defvar org-entry-property-inherited-from (make-marker)
10174 "Marker pointing to the entry from where a proerty was inherited.
10175 Each call to `org-entry-get-with-inheritance' will set this marker to the
10176 location of the entry where the inheriance search matched. If there was
10177 no match, the marker will point nowhere.
10178 Note that also `org-entry-get' calls this function, if the INHERIT flag
10179 is set.")
10181 (defun org-entry-get-with-inheritance (property)
10182 "Get entry property, and search higher levels if not present."
10183 (move-marker org-entry-property-inherited-from nil)
10184 (let (tmp)
10185 (save-excursion
10186 (save-restriction
10187 (widen)
10188 (catch 'ex
10189 (while t
10190 (when (setq tmp (org-entry-get nil property))
10191 (org-back-to-heading t)
10192 (move-marker org-entry-property-inherited-from (point))
10193 (throw 'ex tmp))
10194 (or (org-up-heading-safe) (throw 'ex nil)))))
10195 (or tmp
10196 (cdr (assoc property org-file-properties))
10197 (cdr (assoc property org-global-properties))
10198 (cdr (assoc property org-global-properties-fixed))))))
10200 (defun org-entry-put (pom property value)
10201 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10202 (org-with-point-at pom
10203 (org-back-to-heading t)
10204 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10205 range)
10206 (cond
10207 ((equal property "TODO")
10208 (when (and (stringp value) (string-match "\\S-" value)
10209 (not (member value org-todo-keywords-1)))
10210 (error "\"%s\" is not a valid TODO state" value))
10211 (if (or (not value)
10212 (not (string-match "\\S-" value)))
10213 (setq value 'none))
10214 (org-todo value)
10215 (org-set-tags nil 'align))
10216 ((equal property "PRIORITY")
10217 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10218 (string-to-char value) ?\ ))
10219 (org-set-tags nil 'align))
10220 ((equal property "SCHEDULED")
10221 (if (re-search-forward org-scheduled-time-regexp end t)
10222 (cond
10223 ((eq value 'earlier) (org-timestamp-change -1 'day))
10224 ((eq value 'later) (org-timestamp-change 1 'day))
10225 (t (call-interactively 'org-schedule)))
10226 (call-interactively 'org-schedule)))
10227 ((equal property "DEADLINE")
10228 (if (re-search-forward org-deadline-time-regexp end t)
10229 (cond
10230 ((eq value 'earlier) (org-timestamp-change -1 'day))
10231 ((eq value 'later) (org-timestamp-change 1 'day))
10232 (t (call-interactively 'org-deadline)))
10233 (call-interactively 'org-deadline)))
10234 ((member property org-special-properties)
10235 (error "The %s property can not yet be set with `org-entry-put'"
10236 property))
10237 (t ; a non-special property
10238 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10239 (setq range (org-get-property-block beg end 'force))
10240 (goto-char (car range))
10241 (if (re-search-forward
10242 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10243 (progn
10244 (delete-region (match-beginning 1) (match-end 1))
10245 (goto-char (match-beginning 1)))
10246 (goto-char (cdr range))
10247 (insert "\n")
10248 (backward-char 1)
10249 (org-indent-line-function)
10250 (insert ":" property ":"))
10251 (and value (insert " " value))
10252 (org-indent-line-function)))))))
10254 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10255 "Get all property keys in the current buffer.
10256 With INCLUDE-SPECIALS, also list the special properties that relect things
10257 like tags and TODO state.
10258 With INCLUDE-DEFAULTS, also include properties that has special meaning
10259 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10260 With INCLUDE-COLUMNS, also include property names given in COLUMN
10261 formats in the current buffer."
10262 (let (rtn range cfmt cols s p)
10263 (save-excursion
10264 (save-restriction
10265 (widen)
10266 (goto-char (point-min))
10267 (while (re-search-forward org-property-start-re nil t)
10268 (setq range (org-get-property-block))
10269 (goto-char (car range))
10270 (while (re-search-forward
10271 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10272 (cdr range) t)
10273 (add-to-list 'rtn (org-match-string-no-properties 1)))
10274 (outline-next-heading))))
10276 (when include-specials
10277 (setq rtn (append org-special-properties rtn)))
10279 (when include-defaults
10280 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10282 (when include-columns
10283 (save-excursion
10284 (save-restriction
10285 (widen)
10286 (goto-char (point-min))
10287 (while (re-search-forward
10288 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10289 nil t)
10290 (setq cfmt (match-string 2) s 0)
10291 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10292 cfmt s)
10293 (setq s (match-end 0)
10294 p (match-string 1 cfmt))
10295 (unless (or (equal p "ITEM")
10296 (member p org-special-properties))
10297 (add-to-list 'rtn (match-string 1 cfmt))))))))
10299 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10301 (defun org-property-values (key)
10302 "Return a list of all values of property KEY."
10303 (save-excursion
10304 (save-restriction
10305 (widen)
10306 (goto-char (point-min))
10307 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10308 values)
10309 (while (re-search-forward re nil t)
10310 (add-to-list 'values (org-trim (match-string 1))))
10311 (delete "" values)))))
10313 (defun org-insert-property-drawer ()
10314 "Insert a property drawer into the current entry."
10315 (interactive)
10316 (org-back-to-heading t)
10317 (looking-at outline-regexp)
10318 (let ((indent (- (match-end 0)(match-beginning 0)))
10319 (beg (point))
10320 (re (concat "^[ \t]*" org-keyword-time-regexp))
10321 end hiddenp)
10322 (outline-next-heading)
10323 (setq end (point))
10324 (goto-char beg)
10325 (while (re-search-forward re end t))
10326 (setq hiddenp (org-invisible-p))
10327 (end-of-line 1)
10328 (and (equal (char-after) ?\n) (forward-char 1))
10329 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10330 (beginning-of-line 2))
10331 (org-skip-over-state-notes)
10332 (skip-chars-backward " \t\n\r")
10333 (if (eq (char-before) ?*) (forward-char 1))
10334 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10335 (beginning-of-line 0)
10336 (org-indent-to-column indent)
10337 (beginning-of-line 2)
10338 (org-indent-to-column indent)
10339 (beginning-of-line 0)
10340 (if hiddenp
10341 (save-excursion
10342 (org-back-to-heading t)
10343 (hide-entry))
10344 (org-flag-drawer t))))
10346 (defun org-set-property (property value)
10347 "In the current entry, set PROPERTY to VALUE.
10348 When called interactively, this will prompt for a property name, offering
10349 completion on existing and default properties. And then it will prompt
10350 for a value, offering competion either on allowed values (via an inherited
10351 xxx_ALL property) or on existing values in other instances of this property
10352 in the current file."
10353 (interactive
10354 (let* ((completion-ignore-case t)
10355 (keys (org-buffer-property-keys nil t t))
10356 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10357 (prop (if (member prop0 keys)
10358 prop0
10359 (or (cdr (assoc (downcase prop0)
10360 (mapcar (lambda (x) (cons (downcase x) x))
10361 keys)))
10362 prop0)))
10363 (cur (org-entry-get nil prop))
10364 (allowed (org-property-get-allowed-values nil prop 'table))
10365 (existing (mapcar 'list (org-property-values prop)))
10366 (val (if allowed
10367 (org-completing-read "Value: " allowed nil 'req-match)
10368 (org-completing-read
10369 (concat "Value" (if (and cur (string-match "\\S-" cur))
10370 (concat "[" cur "]") "")
10371 ": ")
10372 existing nil nil "" nil cur))))
10373 (list prop (if (equal val "") cur val))))
10374 (unless (equal (org-entry-get nil property) value)
10375 (org-entry-put nil property value)))
10377 (defun org-delete-property (property)
10378 "In the current entry, delete PROPERTY."
10379 (interactive
10380 (let* ((completion-ignore-case t)
10381 (prop (org-ido-completing-read
10382 "Property: " (org-entry-properties nil 'standard))))
10383 (list prop)))
10384 (message "Property %s %s" property
10385 (if (org-entry-delete nil property)
10386 "deleted"
10387 "was not present in the entry")))
10389 (defun org-delete-property-globally (property)
10390 "Remove PROPERTY globally, from all entries."
10391 (interactive
10392 (let* ((completion-ignore-case t)
10393 (prop (org-ido-completing-read
10394 "Globally remove property: "
10395 (mapcar 'list (org-buffer-property-keys)))))
10396 (list prop)))
10397 (save-excursion
10398 (save-restriction
10399 (widen)
10400 (goto-char (point-min))
10401 (let ((cnt 0))
10402 (while (re-search-forward
10403 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10404 nil t)
10405 (setq cnt (1+ cnt))
10406 (replace-match ""))
10407 (message "Property \"%s\" removed from %d entries" property cnt)))))
10409 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10411 (defun org-compute-property-at-point ()
10412 "Compute the property at point.
10413 This looks for an enclosing column format, extracts the operator and
10414 then applies it to the proerty in the column format's scope."
10415 (interactive)
10416 (unless (org-at-property-p)
10417 (error "Not at a property"))
10418 (let ((prop (org-match-string-no-properties 2)))
10419 (org-columns-get-format-and-top-level)
10420 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10421 (error "No operator defined for property %s" prop))
10422 (org-columns-compute prop)))
10424 (defun org-property-get-allowed-values (pom property &optional table)
10425 "Get allowed values for the property PROPERTY.
10426 When TABLE is non-nil, return an alist that can directly be used for
10427 completion."
10428 (let (vals)
10429 (cond
10430 ((equal property "TODO")
10431 (setq vals (org-with-point-at pom
10432 (append org-todo-keywords-1 '("")))))
10433 ((equal property "PRIORITY")
10434 (let ((n org-lowest-priority))
10435 (while (>= n org-highest-priority)
10436 (push (char-to-string n) vals)
10437 (setq n (1- n)))))
10438 ((member property org-special-properties))
10440 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10442 (when (and vals (string-match "\\S-" vals))
10443 (setq vals (car (read-from-string (concat "(" vals ")"))))
10444 (setq vals (mapcar (lambda (x)
10445 (cond ((stringp x) x)
10446 ((numberp x) (number-to-string x))
10447 ((symbolp x) (symbol-name x))
10448 (t "???")))
10449 vals)))))
10450 (if table (mapcar 'list vals) vals)))
10452 (defun org-property-previous-allowed-value (&optional previous)
10453 "Switch to the next allowed value for this property."
10454 (interactive)
10455 (org-property-next-allowed-value t))
10457 (defun org-property-next-allowed-value (&optional previous)
10458 "Switch to the next allowed value for this property."
10459 (interactive)
10460 (unless (org-at-property-p)
10461 (error "Not at a property"))
10462 (let* ((key (match-string 2))
10463 (value (match-string 3))
10464 (allowed (or (org-property-get-allowed-values (point) key)
10465 (and (member value '("[ ]" "[-]" "[X]"))
10466 '("[ ]" "[X]"))))
10467 nval)
10468 (unless allowed
10469 (error "Allowed values for this property have not been defined"))
10470 (if previous (setq allowed (reverse allowed)))
10471 (if (member value allowed)
10472 (setq nval (car (cdr (member value allowed)))))
10473 (setq nval (or nval (car allowed)))
10474 (if (equal nval value)
10475 (error "Only one allowed value for this property"))
10476 (org-at-property-p)
10477 (replace-match (concat " :" key ": " nval) t t)
10478 (org-indent-line-function)
10479 (beginning-of-line 1)
10480 (skip-chars-forward " \t")))
10482 (defun org-find-entry-with-id (ident)
10483 "Locate the entry that contains the ID property with exact value IDENT.
10484 IDENT can be a string, a symbol or a number, this function will search for
10485 the string representation of it.
10486 Return the position where this entry starts, or nil if there is no such entry."
10487 (let ((id (cond
10488 ((stringp ident) ident)
10489 ((symbol-name ident) (symbol-name ident))
10490 ((numberp ident) (number-to-string ident))
10491 (t (error "IDENT %s must be a string, symbol or number" ident))))
10492 (case-fold-search nil))
10493 (save-excursion
10494 (save-restriction
10495 (widen)
10496 (goto-char (point-min))
10497 (when (re-search-forward
10498 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10499 nil t)
10500 (org-back-to-heading)
10501 (point))))))
10503 ;;;; Timestamps
10505 (defvar org-last-changed-timestamp nil)
10506 (defvar org-last-inserted-timestamp nil
10507 "The last time stamp inserted with `org-insert-time-stamp'.")
10508 (defvar org-time-was-given) ; dynamically scoped parameter
10509 (defvar org-end-time-was-given) ; dynamically scoped parameter
10510 (defvar org-ts-what) ; dynamically scoped parameter
10512 (defun org-time-stamp (arg &optional inactive)
10513 "Prompt for a date/time and insert a time stamp.
10514 If the user specifies a time like HH:MM, or if this command is called
10515 with a prefix argument, the time stamp will contain date and time.
10516 Otherwise, only the date will be included. All parts of a date not
10517 specified by the user will be filled in from the current date/time.
10518 So if you press just return without typing anything, the time stamp
10519 will represent the current date/time. If there is already a timestamp
10520 at the cursor, it will be modified."
10521 (interactive "P")
10522 (let* ((ts nil)
10523 (default-time
10524 ;; Default time is either today, or, when entering a range,
10525 ;; the range start.
10526 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10527 (save-excursion
10528 (re-search-backward
10529 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10530 (- (point) 20) t)))
10531 (apply 'encode-time (org-parse-time-string (match-string 1)))
10532 (current-time)))
10533 (default-input (and ts (org-get-compact-tod ts)))
10534 org-time-was-given org-end-time-was-given time)
10535 (cond
10536 ((and (org-at-timestamp-p t)
10537 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10538 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10539 (insert "--")
10540 (setq time (let ((this-command this-command))
10541 (org-read-date arg 'totime nil nil
10542 default-time default-input)))
10543 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10544 ((org-at-timestamp-p t)
10545 (setq time (let ((this-command this-command))
10546 (org-read-date arg 'totime nil nil default-time default-input)))
10547 (when (org-at-timestamp-p t) ; just to get the match data
10548 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10549 (replace-match "")
10550 (setq org-last-changed-timestamp
10551 (org-insert-time-stamp
10552 time (or org-time-was-given arg)
10553 inactive nil nil (list org-end-time-was-given))))
10554 (message "Timestamp updated"))
10556 (setq time (let ((this-command this-command))
10557 (org-read-date arg 'totime nil nil default-time default-input)))
10558 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10559 nil nil (list org-end-time-was-given))))))
10561 ;; FIXME: can we use this for something else, like computing time differences?
10562 (defun org-get-compact-tod (s)
10563 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10564 (let* ((t1 (match-string 1 s))
10565 (h1 (string-to-number (match-string 2 s)))
10566 (m1 (string-to-number (match-string 3 s)))
10567 (t2 (and (match-end 4) (match-string 5 s)))
10568 (h2 (and t2 (string-to-number (match-string 6 s))))
10569 (m2 (and t2 (string-to-number (match-string 7 s))))
10570 dh dm)
10571 (if (not t2)
10573 (setq dh (- h2 h1) dm (- m2 m1))
10574 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10575 (concat t1 "+" (number-to-string dh)
10576 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10578 (defun org-time-stamp-inactive (&optional arg)
10579 "Insert an inactive time stamp.
10580 An inactive time stamp is enclosed in square brackets instead of angle
10581 brackets. It is inactive in the sense that it does not trigger agenda entries,
10582 does not link to the calendar and cannot be changed with the S-cursor keys.
10583 So these are more for recording a certain time/date."
10584 (interactive "P")
10585 (org-time-stamp arg 'inactive))
10587 (defvar org-date-ovl (org-make-overlay 1 1))
10588 (org-overlay-put org-date-ovl 'face 'org-warning)
10589 (org-detach-overlay org-date-ovl)
10591 (defvar org-ans1) ; dynamically scoped parameter
10592 (defvar org-ans2) ; dynamically scoped parameter
10594 (defvar org-plain-time-of-day-regexp) ; defined below
10596 (defvar org-overriding-default-time nil) ; dynamically scoped
10597 (defvar org-read-date-overlay nil)
10598 (defvar org-dcst nil) ; dynamically scoped
10600 (defun org-read-date (&optional with-time to-time from-string prompt
10601 default-time default-input)
10602 "Read a date, possibly a time, and make things smooth for the user.
10603 The prompt will suggest to enter an ISO date, but you can also enter anything
10604 which will at least partially be understood by `parse-time-string'.
10605 Unrecognized parts of the date will default to the current day, month, year,
10606 hour and minute. If this command is called to replace a timestamp at point,
10607 of to enter the second timestamp of a range, the default time is taken from the
10608 existing stamp. For example,
10609 3-2-5 --> 2003-02-05
10610 feb 15 --> currentyear-02-15
10611 sep 12 9 --> 2009-09-12
10612 12:45 --> today 12:45
10613 22 sept 0:34 --> currentyear-09-22 0:34
10614 12 --> currentyear-currentmonth-12
10615 Fri --> nearest Friday (today or later)
10616 etc.
10618 Furthermore you can specify a relative date by giving, as the *first* thing
10619 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10620 change in days weeks, months, years.
10621 With a single plus or minus, the date is relative to today. With a double
10622 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10623 +4d --> four days from today
10624 +4 --> same as above
10625 +2w --> two weeks from today
10626 ++5 --> five days from default date
10628 The function understands only English month and weekday abbreviations,
10629 but this can be configured with the variables `parse-time-months' and
10630 `parse-time-weekdays'.
10632 While prompting, a calendar is popped up - you can also select the
10633 date with the mouse (button 1). The calendar shows a period of three
10634 months. To scroll it to other months, use the keys `>' and `<'.
10635 If you don't like the calendar, turn it off with
10636 \(setq org-read-date-popup-calendar nil)
10638 With optional argument TO-TIME, the date will immediately be converted
10639 to an internal time.
10640 With an optional argument WITH-TIME, the prompt will suggest to also
10641 insert a time. Note that when WITH-TIME is not set, you can still
10642 enter a time, and this function will inform the calling routine about
10643 this change. The calling routine may then choose to change the format
10644 used to insert the time stamp into the buffer to include the time.
10645 With optional argument FROM-STRING, read from this string instead from
10646 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10647 the time/date that is used for everything that is not specified by the
10648 user."
10649 (require 'parse-time)
10650 (let* ((org-time-stamp-rounding-minutes
10651 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10652 (org-dcst org-display-custom-times)
10653 (ct (org-current-time))
10654 (def (or org-overriding-default-time default-time ct))
10655 (defdecode (decode-time def))
10656 (dummy (progn
10657 (when (< (nth 2 defdecode) org-extend-today-until)
10658 (setcar (nthcdr 2 defdecode) -1)
10659 (setcar (nthcdr 1 defdecode) 59)
10660 (setq def (apply 'encode-time defdecode)
10661 defdecode (decode-time def)))))
10662 (calendar-move-hook nil)
10663 (calendar-view-diary-initially-flag nil)
10664 (view-diary-entries-initially nil)
10665 (calendar-view-holidays-initially-flag nil)
10666 (view-calendar-holidays-initially nil)
10667 (timestr (format-time-string
10668 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10669 (prompt (concat (if prompt (concat prompt " ") "")
10670 (format "Date+time [%s]: " timestr)))
10671 ans (org-ans0 "") org-ans1 org-ans2 final)
10673 (cond
10674 (from-string (setq ans from-string))
10675 (org-read-date-popup-calendar
10676 (save-excursion
10677 (save-window-excursion
10678 (calendar)
10679 (calendar-forward-day (- (time-to-days def)
10680 (calendar-absolute-from-gregorian
10681 (calendar-current-date))))
10682 (org-eval-in-calendar nil t)
10683 (let* ((old-map (current-local-map))
10684 (map (copy-keymap calendar-mode-map))
10685 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10686 (org-defkey map (kbd "RET") 'org-calendar-select)
10687 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10688 'org-calendar-select-mouse)
10689 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10690 'org-calendar-select-mouse)
10691 (org-defkey minibuffer-local-map [(meta shift left)]
10692 (lambda () (interactive)
10693 (org-eval-in-calendar '(calendar-backward-month 1))))
10694 (org-defkey minibuffer-local-map [(meta shift right)]
10695 (lambda () (interactive)
10696 (org-eval-in-calendar '(calendar-forward-month 1))))
10697 (org-defkey minibuffer-local-map [(meta shift up)]
10698 (lambda () (interactive)
10699 (org-eval-in-calendar '(calendar-backward-year 1))))
10700 (org-defkey minibuffer-local-map [(meta shift down)]
10701 (lambda () (interactive)
10702 (org-eval-in-calendar '(calendar-forward-year 1))))
10703 (org-defkey minibuffer-local-map [(shift up)]
10704 (lambda () (interactive)
10705 (org-eval-in-calendar '(calendar-backward-week 1))))
10706 (org-defkey minibuffer-local-map [(shift down)]
10707 (lambda () (interactive)
10708 (org-eval-in-calendar '(calendar-forward-week 1))))
10709 (org-defkey minibuffer-local-map [(shift left)]
10710 (lambda () (interactive)
10711 (org-eval-in-calendar '(calendar-backward-day 1))))
10712 (org-defkey minibuffer-local-map [(shift right)]
10713 (lambda () (interactive)
10714 (org-eval-in-calendar '(calendar-forward-day 1))))
10715 (org-defkey minibuffer-local-map ">"
10716 (lambda () (interactive)
10717 (org-eval-in-calendar '(scroll-calendar-left 1))))
10718 (org-defkey minibuffer-local-map "<"
10719 (lambda () (interactive)
10720 (org-eval-in-calendar '(scroll-calendar-right 1))))
10721 (unwind-protect
10722 (progn
10723 (use-local-map map)
10724 (add-hook 'post-command-hook 'org-read-date-display)
10725 (setq org-ans0 (read-string prompt default-input nil nil))
10726 ;; org-ans0: from prompt
10727 ;; org-ans1: from mouse click
10728 ;; org-ans2: from calendar motion
10729 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10730 (remove-hook 'post-command-hook 'org-read-date-display)
10731 (use-local-map old-map)
10732 (when org-read-date-overlay
10733 (org-delete-overlay org-read-date-overlay)
10734 (setq org-read-date-overlay nil)))))))
10736 (t ; Naked prompt only
10737 (unwind-protect
10738 (setq ans (read-string prompt default-input nil timestr))
10739 (when org-read-date-overlay
10740 (org-delete-overlay org-read-date-overlay)
10741 (setq org-read-date-overlay nil)))))
10743 (setq final (org-read-date-analyze ans def defdecode))
10745 (if to-time
10746 (apply 'encode-time final)
10747 (if (and (boundp 'org-time-was-given) org-time-was-given)
10748 (format "%04d-%02d-%02d %02d:%02d"
10749 (nth 5 final) (nth 4 final) (nth 3 final)
10750 (nth 2 final) (nth 1 final))
10751 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10752 (defvar def)
10753 (defvar defdecode)
10754 (defvar with-time)
10755 (defun org-read-date-display ()
10756 "Display the currrent date prompt interpretation in the minibuffer."
10757 (when org-read-date-display-live
10758 (when org-read-date-overlay
10759 (org-delete-overlay org-read-date-overlay))
10760 (let ((p (point)))
10761 (end-of-line 1)
10762 (while (not (equal (buffer-substring
10763 (max (point-min) (- (point) 4)) (point))
10764 " "))
10765 (insert " "))
10766 (goto-char p))
10767 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10768 " " (or org-ans1 org-ans2)))
10769 (org-end-time-was-given nil)
10770 (f (org-read-date-analyze ans def defdecode))
10771 (fmts (if org-dcst
10772 org-time-stamp-custom-formats
10773 org-time-stamp-formats))
10774 (fmt (if (or with-time
10775 (and (boundp 'org-time-was-given) org-time-was-given))
10776 (cdr fmts)
10777 (car fmts)))
10778 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10779 (when (and org-end-time-was-given
10780 (string-match org-plain-time-of-day-regexp txt))
10781 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10782 org-end-time-was-given
10783 (substring txt (match-end 0)))))
10784 (setq org-read-date-overlay
10785 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10786 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10788 (defun org-read-date-analyze (ans def defdecode)
10789 "Analyze the combined answer of the date prompt."
10790 ;; FIXME: cleanup and comment
10791 (let (delta deltan deltaw deltadef year month day
10792 hour minute second wday pm h2 m2 tl wday1
10793 iso-year iso-weekday iso-week iso-year iso-date)
10795 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10796 (setq ans "+0"))
10798 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10799 (setq ans (replace-match "" t t ans)
10800 deltan (car delta)
10801 deltaw (nth 1 delta)
10802 deltadef (nth 2 delta)))
10804 ;; Check if there is an iso week date in there
10805 ;; If yes, sore the info and ostpone interpreting it until the rest
10806 ;; of the parsing is done
10807 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10808 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10809 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10810 iso-week (string-to-number (match-string 2 ans)))
10811 (setq ans (replace-match "" t t ans)))
10813 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10814 (when (string-match
10815 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10816 (setq year (if (match-end 2)
10817 (string-to-number (match-string 2 ans))
10818 (string-to-number (format-time-string "%Y")))
10819 month (string-to-number (match-string 3 ans))
10820 day (string-to-number (match-string 4 ans)))
10821 (if (< year 100) (setq year (+ 2000 year)))
10822 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10823 t nil ans)))
10824 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10825 ;; If there is a time with am/pm, and *no* time without it, we convert
10826 ;; so that matching will be successful.
10827 (loop for i from 1 to 2 do ; twice, for end time as well
10828 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10829 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10830 (setq hour (string-to-number (match-string 1 ans))
10831 minute (if (match-end 3)
10832 (string-to-number (match-string 3 ans))
10834 pm (equal ?p
10835 (string-to-char (downcase (match-string 4 ans)))))
10836 (if (and (= hour 12) (not pm))
10837 (setq hour 0)
10838 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10839 (setq ans (replace-match (format "%02d:%02d" hour minute)
10840 t t ans))))
10842 ;; Check if a time range is given as a duration
10843 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10844 (setq hour (string-to-number (match-string 1 ans))
10845 h2 (+ hour (string-to-number (match-string 3 ans)))
10846 minute (string-to-number (match-string 2 ans))
10847 m2 (+ minute (if (match-end 5) (string-to-number
10848 (match-string 5 ans))0)))
10849 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10850 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10851 t t ans)))
10853 ;; Check if there is a time range
10854 (when (boundp 'org-end-time-was-given)
10855 (setq org-time-was-given nil)
10856 (when (and (string-match org-plain-time-of-day-regexp ans)
10857 (match-end 8))
10858 (setq org-end-time-was-given (match-string 8 ans))
10859 (setq ans (concat (substring ans 0 (match-beginning 7))
10860 (substring ans (match-end 7))))))
10862 (setq tl (parse-time-string ans)
10863 day (or (nth 3 tl) (nth 3 defdecode))
10864 month (or (nth 4 tl)
10865 (if (and org-read-date-prefer-future
10866 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10867 (1+ (nth 4 defdecode))
10868 (nth 4 defdecode)))
10869 year (or (nth 5 tl)
10870 (if (and org-read-date-prefer-future
10871 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10872 (1+ (nth 5 defdecode))
10873 (nth 5 defdecode)))
10874 hour (or (nth 2 tl) (nth 2 defdecode))
10875 minute (or (nth 1 tl) (nth 1 defdecode))
10876 second (or (nth 0 tl) 0)
10877 wday (nth 6 tl))
10879 ;; Special date definitions below
10880 (cond
10881 (iso-week
10882 ;; There was an iso week
10883 (setq year (or iso-year year)
10884 day (or iso-weekday wday 1)
10885 wday nil ; to make sure that the trigger below does not match
10886 iso-date (calendar-gregorian-from-absolute
10887 (calendar-absolute-from-iso
10888 (list iso-week day year))))
10889 ; FIXME: Should we also push ISO weeks into the future?
10890 ; (when (and org-read-date-prefer-future
10891 ; (not iso-year)
10892 ; (< (calendar-absolute-from-gregorian iso-date)
10893 ; (time-to-days (current-time))))
10894 ; (setq year (1+ year)
10895 ; iso-date (calendar-gregorian-from-absolute
10896 ; (calendar-absolute-from-iso
10897 ; (list iso-week day year)))))
10898 (setq month (car iso-date)
10899 year (nth 2 iso-date)
10900 day (nth 1 iso-date)))
10901 (deltan
10902 (unless deltadef
10903 (let ((now (decode-time (current-time))))
10904 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10905 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10906 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10907 ((equal deltaw "m") (setq month (+ month deltan)))
10908 ((equal deltaw "y") (setq year (+ year deltan)))))
10909 ((and wday (not (nth 3 tl)))
10910 ;; Weekday was given, but no day, so pick that day in the week
10911 ;; on or after the derived date.
10912 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10913 (unless (equal wday wday1)
10914 (setq day (+ day (% (- wday wday1 -7) 7))))))
10915 (if (and (boundp 'org-time-was-given)
10916 (nth 2 tl))
10917 (setq org-time-was-given t))
10918 (if (< year 100) (setq year (+ 2000 year)))
10919 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10920 (list second minute hour day month year)))
10922 (defvar parse-time-weekdays)
10924 (defun org-read-date-get-relative (s today default)
10925 "Check string S for special relative date string.
10926 TODAY and DEFAULT are internal times, for today and for a default.
10927 Return shift list (N what def-flag)
10928 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10929 N is the number of WHATs to shift.
10930 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10931 the DEFAULT date rather than TODAY."
10932 (when (and
10933 (string-match
10934 (concat
10935 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10936 "\\([0-9]+\\)?"
10937 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10938 "\\([ \t]\\|$\\)") s)
10939 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10940 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10941 (string-to-char (substring (match-string 1 s) -1))
10942 ?+))
10943 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10944 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10945 (what (if (match-end 3) (match-string 3 s) "d"))
10946 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10947 (date (if rel default today))
10948 (wday (nth 6 (decode-time date)))
10949 delta)
10950 (if wday1
10951 (progn
10952 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10953 (if (= dir ?-) (setq delta (- delta 7)))
10954 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10955 (list delta "d" rel))
10956 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10958 (defun org-eval-in-calendar (form &optional keepdate)
10959 "Eval FORM in the calendar window and return to current window.
10960 Also, store the cursor date in variable org-ans2."
10961 (let ((sw (selected-window)))
10962 (select-window (get-buffer-window "*Calendar*"))
10963 (eval form)
10964 (when (and (not keepdate) (calendar-cursor-to-date))
10965 (let* ((date (calendar-cursor-to-date))
10966 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10967 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10968 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10969 (select-window sw)))
10971 (defun org-calendar-select ()
10972 "Return to `org-read-date' with the date currently selected.
10973 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10974 (interactive)
10975 (when (calendar-cursor-to-date)
10976 (let* ((date (calendar-cursor-to-date))
10977 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10978 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10979 (if (active-minibuffer-window) (exit-minibuffer))))
10981 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10982 "Insert a date stamp for the date given by the internal TIME.
10983 WITH-HM means, use the stamp format that includes the time of the day.
10984 INACTIVE means use square brackets instead of angular ones, so that the
10985 stamp will not contribute to the agenda.
10986 PRE and POST are optional strings to be inserted before and after the
10987 stamp.
10988 The command returns the inserted time stamp."
10989 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10990 stamp)
10991 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10992 (insert-before-markers (or pre ""))
10993 (insert-before-markers (setq stamp (format-time-string fmt time)))
10994 (when (listp extra)
10995 (setq extra (car extra))
10996 (if (and (stringp extra)
10997 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10998 (setq extra (format "-%02d:%02d"
10999 (string-to-number (match-string 1 extra))
11000 (string-to-number (match-string 2 extra))))
11001 (setq extra nil)))
11002 (when extra
11003 (backward-char 1)
11004 (insert-before-markers extra)
11005 (forward-char 1))
11006 (insert-before-markers (or post ""))
11007 (setq org-last-inserted-timestamp stamp)))
11009 (defun org-toggle-time-stamp-overlays ()
11010 "Toggle the use of custom time stamp formats."
11011 (interactive)
11012 (setq org-display-custom-times (not org-display-custom-times))
11013 (unless org-display-custom-times
11014 (let ((p (point-min)) (bmp (buffer-modified-p)))
11015 (while (setq p (next-single-property-change p 'display))
11016 (if (and (get-text-property p 'display)
11017 (eq (get-text-property p 'face) 'org-date))
11018 (remove-text-properties
11019 p (setq p (next-single-property-change p 'display))
11020 '(display t))))
11021 (set-buffer-modified-p bmp)))
11022 (if (featurep 'xemacs)
11023 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11024 (org-restart-font-lock)
11025 (setq org-table-may-need-update t)
11026 (if org-display-custom-times
11027 (message "Time stamps are overlayed with custom format")
11028 (message "Time stamp overlays removed")))
11030 (defun org-display-custom-time (beg end)
11031 "Overlay modified time stamp format over timestamp between BEG and END."
11032 (let* ((ts (buffer-substring beg end))
11033 t1 w1 with-hm tf time str w2 (off 0))
11034 (save-match-data
11035 (setq t1 (org-parse-time-string ts t))
11036 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11037 (setq off (- (match-end 0) (match-beginning 0)))))
11038 (setq end (- end off))
11039 (setq w1 (- end beg)
11040 with-hm (and (nth 1 t1) (nth 2 t1))
11041 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11042 time (org-fix-decoded-time t1)
11043 str (org-add-props
11044 (format-time-string
11045 (substring tf 1 -1) (apply 'encode-time time))
11046 nil 'mouse-face 'highlight)
11047 w2 (length str))
11048 (if (not (= w2 w1))
11049 (add-text-properties (1+ beg) (+ 2 beg)
11050 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11051 (if (featurep 'xemacs)
11052 (progn
11053 (put-text-property beg end 'invisible t)
11054 (put-text-property beg end 'end-glyph (make-glyph str)))
11055 (put-text-property beg end 'display str))))
11057 (defun org-translate-time (string)
11058 "Translate all timestamps in STRING to custom format.
11059 But do this only if the variable `org-display-custom-times' is set."
11060 (when org-display-custom-times
11061 (save-match-data
11062 (let* ((start 0)
11063 (re org-ts-regexp-both)
11064 t1 with-hm inactive tf time str beg end)
11065 (while (setq start (string-match re string start))
11066 (setq beg (match-beginning 0)
11067 end (match-end 0)
11068 t1 (save-match-data
11069 (org-parse-time-string (substring string beg end) t))
11070 with-hm (and (nth 1 t1) (nth 2 t1))
11071 inactive (equal (substring string beg (1+ beg)) "[")
11072 tf (funcall (if with-hm 'cdr 'car)
11073 org-time-stamp-custom-formats)
11074 time (org-fix-decoded-time t1)
11075 str (format-time-string
11076 (concat
11077 (if inactive "[" "<") (substring tf 1 -1)
11078 (if inactive "]" ">"))
11079 (apply 'encode-time time))
11080 string (replace-match str t t string)
11081 start (+ start (length str)))))))
11082 string)
11084 (defun org-fix-decoded-time (time)
11085 "Set 0 instead of nil for the first 6 elements of time.
11086 Don't touch the rest."
11087 (let ((n 0))
11088 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11090 (defun org-days-to-time (timestamp-string)
11091 "Difference between TIMESTAMP-STRING and now in days."
11092 (- (time-to-days (org-time-string-to-time timestamp-string))
11093 (time-to-days (current-time))))
11095 (defun org-deadline-close (timestamp-string &optional ndays)
11096 "Is the time in TIMESTAMP-STRING close to the current date?"
11097 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11098 (and (< (org-days-to-time timestamp-string) ndays)
11099 (not (org-entry-is-done-p))))
11101 (defun org-get-wdays (ts)
11102 "Get the deadline lead time appropriate for timestring TS."
11103 (cond
11104 ((<= org-deadline-warning-days 0)
11105 ;; 0 or negative, enforce this value no matter what
11106 (- org-deadline-warning-days))
11107 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11108 ;; lead time is specified.
11109 (floor (* (string-to-number (match-string 1 ts))
11110 (cdr (assoc (match-string 2 ts)
11111 '(("d" . 1) ("w" . 7)
11112 ("m" . 30.4) ("y" . 365.25)))))))
11113 ;; go for the default.
11114 (t org-deadline-warning-days)))
11116 (defun org-calendar-select-mouse (ev)
11117 "Return to `org-read-date' with the date currently selected.
11118 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11119 (interactive "e")
11120 (mouse-set-point ev)
11121 (when (calendar-cursor-to-date)
11122 (let* ((date (calendar-cursor-to-date))
11123 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11124 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11125 (if (active-minibuffer-window) (exit-minibuffer))))
11127 (defun org-check-deadlines (ndays)
11128 "Check if there are any deadlines due or past due.
11129 A deadline is considered due if it happens within `org-deadline-warning-days'
11130 days from today's date. If the deadline appears in an entry marked DONE,
11131 it is not shown. The prefix arg NDAYS can be used to test that many
11132 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11133 (interactive "P")
11134 (let* ((org-warn-days
11135 (cond
11136 ((equal ndays '(4)) 100000)
11137 (ndays (prefix-numeric-value ndays))
11138 (t (abs org-deadline-warning-days))))
11139 (case-fold-search nil)
11140 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11141 (callback
11142 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11144 (message "%d deadlines past-due or due within %d days"
11145 (org-occur regexp nil callback)
11146 org-warn-days)))
11148 (defun org-check-before-date (date)
11149 "Check if there are deadlines or scheduled entries before DATE."
11150 (interactive (list (org-read-date)))
11151 (let ((case-fold-search nil)
11152 (regexp (concat "\\<\\(" org-deadline-string
11153 "\\|" org-scheduled-string
11154 "\\) *<\\([^>]+\\)>"))
11155 (callback
11156 (lambda () (time-less-p
11157 (org-time-string-to-time (match-string 2))
11158 (org-time-string-to-time date)))))
11159 (message "%d entries before %s"
11160 (org-occur regexp nil callback) date)))
11162 (defun org-evaluate-time-range (&optional to-buffer)
11163 "Evaluate a time range by computing the difference between start and end.
11164 Normally the result is just printed in the echo area, but with prefix arg
11165 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11166 If the time range is actually in a table, the result is inserted into the
11167 next column.
11168 For time difference computation, a year is assumed to be exactly 365
11169 days in order to avoid rounding problems."
11170 (interactive "P")
11172 (org-clock-update-time-maybe)
11173 (save-excursion
11174 (unless (org-at-date-range-p t)
11175 (goto-char (point-at-bol))
11176 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11177 (if (not (org-at-date-range-p t))
11178 (error "Not at a time-stamp range, and none found in current line")))
11179 (let* ((ts1 (match-string 1))
11180 (ts2 (match-string 2))
11181 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11182 (match-end (match-end 0))
11183 (time1 (org-time-string-to-time ts1))
11184 (time2 (org-time-string-to-time ts2))
11185 (t1 (time-to-seconds time1))
11186 (t2 (time-to-seconds time2))
11187 (diff (abs (- t2 t1)))
11188 (negative (< (- t2 t1) 0))
11189 ;; (ys (floor (* 365 24 60 60)))
11190 (ds (* 24 60 60))
11191 (hs (* 60 60))
11192 (fy "%dy %dd %02d:%02d")
11193 (fy1 "%dy %dd")
11194 (fd "%dd %02d:%02d")
11195 (fd1 "%dd")
11196 (fh "%02d:%02d")
11197 y d h m align)
11198 (if havetime
11199 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11201 d (floor (/ diff ds)) diff (mod diff ds)
11202 h (floor (/ diff hs)) diff (mod diff hs)
11203 m (floor (/ diff 60)))
11204 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11206 d (floor (+ (/ diff ds) 0.5))
11207 h 0 m 0))
11208 (if (not to-buffer)
11209 (message "%s" (org-make-tdiff-string y d h m))
11210 (if (org-at-table-p)
11211 (progn
11212 (goto-char match-end)
11213 (setq align t)
11214 (and (looking-at " *|") (goto-char (match-end 0))))
11215 (goto-char match-end))
11216 (if (looking-at
11217 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11218 (replace-match ""))
11219 (if negative (insert " -"))
11220 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11221 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11222 (insert " " (format fh h m))))
11223 (if align (org-table-align))
11224 (message "Time difference inserted")))))
11226 (defun org-make-tdiff-string (y d h m)
11227 (let ((fmt "")
11228 (l nil))
11229 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11230 l (push y l)))
11231 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11232 l (push d l)))
11233 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11234 l (push h l)))
11235 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11236 l (push m l)))
11237 (apply 'format fmt (nreverse l))))
11239 (defun org-time-string-to-time (s)
11240 (apply 'encode-time (org-parse-time-string s)))
11242 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11243 "Convert a time stamp to an absolute day number.
11244 If there is a specifyer for a cyclic time stamp, get the closest date to
11245 DAYNR.
11246 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11247 (cond
11248 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11249 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11250 daynr
11251 (+ daynr 1000)))
11252 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11253 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11254 (time-to-days (current-time))) (match-string 0 s)
11255 prefer show-all))
11256 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11258 (defun org-days-to-iso-week (days)
11259 "Return the iso week number."
11260 (require 'cal-iso)
11261 (car (calendar-iso-from-absolute days)))
11263 (defun org-small-year-to-year (year)
11264 "Convert 2-digit years into 4-digit years.
11265 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11266 The year 2000 cannot be abbreviated. Any year larger than 99
11267 is returned unchanged."
11268 (if (< year 38)
11269 (setq year (+ 2000 year))
11270 (if (< year 100)
11271 (setq year (+ 1900 year))))
11272 year)
11274 (defun org-time-from-absolute (d)
11275 "Return the time corresponding to date D.
11276 D may be an absolute day number, or a calendar-type list (month day year)."
11277 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11278 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11280 (defun org-calendar-holiday ()
11281 "List of holidays, for Diary display in Org-mode."
11282 (require 'holidays)
11283 (let ((hl (funcall
11284 (if (fboundp 'calendar-check-holidays)
11285 'calendar-check-holidays 'check-calendar-holidays) date)))
11286 (if hl (mapconcat 'identity hl "; "))))
11288 (defun org-diary-sexp-entry (sexp entry date)
11289 "Process a SEXP diary ENTRY for DATE."
11290 (require 'diary-lib)
11291 (let ((result (if calendar-debug-sexp
11292 (let ((stack-trace-on-error t))
11293 (eval (car (read-from-string sexp))))
11294 (condition-case nil
11295 (eval (car (read-from-string sexp)))
11296 (error
11297 (beep)
11298 (message "Bad sexp at line %d in %s: %s"
11299 (org-current-line)
11300 (buffer-file-name) sexp)
11301 (sleep-for 2))))))
11302 (cond ((stringp result) result)
11303 ((and (consp result)
11304 (stringp (cdr result))) (cdr result))
11305 (result entry)
11306 (t nil))))
11308 (defun org-diary-to-ical-string (frombuf)
11309 "Get iCalendar entries from diary entries in buffer FROMBUF.
11310 This uses the icalendar.el library."
11311 (let* ((tmpdir (if (featurep 'xemacs)
11312 (temp-directory)
11313 temporary-file-directory))
11314 (tmpfile (make-temp-name
11315 (expand-file-name "orgics" tmpdir)))
11316 buf rtn b e)
11317 (save-excursion
11318 (set-buffer frombuf)
11319 (icalendar-export-region (point-min) (point-max) tmpfile)
11320 (setq buf (find-buffer-visiting tmpfile))
11321 (set-buffer buf)
11322 (goto-char (point-min))
11323 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11324 (setq b (match-beginning 0)))
11325 (goto-char (point-max))
11326 (if (re-search-backward "^END:VEVENT" nil t)
11327 (setq e (match-end 0)))
11328 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11329 (kill-buffer buf)
11330 (delete-file tmpfile)
11331 rtn))
11333 (defun org-closest-date (start current change prefer show-all)
11334 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11335 When PREFER is `past' return a date that is either CURRENT or past.
11336 When PREFER is `future', return a date that is either CURRENT or future.
11337 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11338 ;; Make the proper lists from the dates
11339 (catch 'exit
11340 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11341 dn dw sday cday n1 n2
11342 d m y y1 y2 date1 date2 nmonths nm ny m2)
11344 (setq start (org-date-to-gregorian start)
11345 current (org-date-to-gregorian
11346 (if show-all
11347 current
11348 (time-to-days (current-time))))
11349 sday (calendar-absolute-from-gregorian start)
11350 cday (calendar-absolute-from-gregorian current))
11352 (if (<= cday sday) (throw 'exit sday))
11354 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11355 (setq dn (string-to-number (match-string 1 change))
11356 dw (cdr (assoc (match-string 2 change) a1)))
11357 (error "Invalid change specifyer: %s" change))
11358 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11359 (cond
11360 ((eq dw 'day)
11361 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11362 n2 (+ n1 dn)))
11363 ((eq dw 'year)
11364 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11365 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11366 (setq date1 (list m d y1)
11367 n1 (calendar-absolute-from-gregorian date1)
11368 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11369 n2 (calendar-absolute-from-gregorian date2)))
11370 ((eq dw 'month)
11371 ;; approx number of month between the two dates
11372 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11373 ;; How often does dn fit in there?
11374 (setq d (nth 1 start) m (car start) y (nth 2 start)
11375 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11376 m (+ m nm)
11377 ny (floor (/ m 12))
11378 y (+ y ny)
11379 m (- m (* ny 12)))
11380 (while (> m 12) (setq m (- m 12) y (1+ y)))
11381 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11382 (setq m2 (+ m dn) y2 y)
11383 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11384 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11385 (while (<= n2 cday)
11386 (setq n1 n2 m m2 y y2)
11387 (setq m2 (+ m dn) y2 y)
11388 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11389 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11390 (if show-all
11391 (cond
11392 ((eq prefer 'past) n1)
11393 ((eq prefer 'future) (if (= cday n1) n1 n2))
11394 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11395 (cond
11396 ((eq prefer 'past) n1)
11397 ((eq prefer 'future) (if (= cday n1) n1 n2))
11398 (t (if (= cday n1) n1 n2)))))))
11400 (defun org-date-to-gregorian (date)
11401 "Turn any specification of DATE into a gregorian date for the calendar."
11402 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11403 ((and (listp date) (= (length date) 3)) date)
11404 ((stringp date)
11405 (setq date (org-parse-time-string date))
11406 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11407 ((listp date)
11408 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11410 (defun org-parse-time-string (s &optional nodefault)
11411 "Parse the standard Org-mode time string.
11412 This should be a lot faster than the normal `parse-time-string'.
11413 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11414 hour and minute fields will be nil if not given."
11415 (if (string-match org-ts-regexp0 s)
11416 (list 0
11417 (if (or (match-beginning 8) (not nodefault))
11418 (string-to-number (or (match-string 8 s) "0")))
11419 (if (or (match-beginning 7) (not nodefault))
11420 (string-to-number (or (match-string 7 s) "0")))
11421 (string-to-number (match-string 4 s))
11422 (string-to-number (match-string 3 s))
11423 (string-to-number (match-string 2 s))
11424 nil nil nil)
11425 (make-list 9 0)))
11427 (defun org-timestamp-up (&optional arg)
11428 "Increase the date item at the cursor by one.
11429 If the cursor is on the year, change the year. If it is on the month or
11430 the day, change that.
11431 With prefix ARG, change by that many units."
11432 (interactive "p")
11433 (org-timestamp-change (prefix-numeric-value arg)))
11435 (defun org-timestamp-down (&optional arg)
11436 "Decrease the date item at the cursor by one.
11437 If the cursor is on the year, change the year. If it is on the month or
11438 the day, change that.
11439 With prefix ARG, change by that many units."
11440 (interactive "p")
11441 (org-timestamp-change (- (prefix-numeric-value arg))))
11443 (defun org-timestamp-up-day (&optional arg)
11444 "Increase the date in the time stamp by one day.
11445 With prefix ARG, change that many days."
11446 (interactive "p")
11447 (if (and (not (org-at-timestamp-p t))
11448 (org-on-heading-p))
11449 (org-todo 'up)
11450 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11452 (defun org-timestamp-down-day (&optional arg)
11453 "Decrease the date in the time stamp by one day.
11454 With prefix ARG, change that many days."
11455 (interactive "p")
11456 (if (and (not (org-at-timestamp-p t))
11457 (org-on-heading-p))
11458 (org-todo 'down)
11459 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11461 (defun org-at-timestamp-p (&optional inactive-ok)
11462 "Determine if the cursor is in or at a timestamp."
11463 (interactive)
11464 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11465 (pos (point))
11466 (ans (or (looking-at tsr)
11467 (save-excursion
11468 (skip-chars-backward "^[<\n\r\t")
11469 (if (> (point) (point-min)) (backward-char 1))
11470 (and (looking-at tsr)
11471 (> (- (match-end 0) pos) -1))))))
11472 (and ans
11473 (boundp 'org-ts-what)
11474 (setq org-ts-what
11475 (cond
11476 ((= pos (match-beginning 0)) 'bracket)
11477 ((= pos (1- (match-end 0))) 'bracket)
11478 ((org-pos-in-match-range pos 2) 'year)
11479 ((org-pos-in-match-range pos 3) 'month)
11480 ((org-pos-in-match-range pos 7) 'hour)
11481 ((org-pos-in-match-range pos 8) 'minute)
11482 ((or (org-pos-in-match-range pos 4)
11483 (org-pos-in-match-range pos 5)) 'day)
11484 ((and (> pos (or (match-end 8) (match-end 5)))
11485 (< pos (match-end 0)))
11486 (- pos (or (match-end 8) (match-end 5))))
11487 (t 'day))))
11488 ans))
11490 (defun org-toggle-timestamp-type ()
11491 "Toggle the type (<active> or [inactive]) of a time stamp."
11492 (interactive)
11493 (when (org-at-timestamp-p t)
11494 (let ((beg (match-beginning 0)) (end (match-end 0))
11495 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11496 (save-excursion
11497 (goto-char beg)
11498 (while (re-search-forward "[][<>]" end t)
11499 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11500 t t)))
11501 (message "Timestamp is now %sactive"
11502 (if (equal (char-after beg) ?<) "" "in")))))
11504 (defun org-timestamp-change (n &optional what)
11505 "Change the date in the time stamp at point.
11506 The date will be changed by N times WHAT. WHAT can be `day', `month',
11507 `year', `minute', `second'. If WHAT is not given, the cursor position
11508 in the timestamp determines what will be changed."
11509 (let ((pos (point))
11510 with-hm inactive
11511 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11512 org-ts-what
11513 extra rem
11514 ts time time0)
11515 (if (not (org-at-timestamp-p t))
11516 (error "Not at a timestamp"))
11517 (if (and (not what) (eq org-ts-what 'bracket))
11518 (org-toggle-timestamp-type)
11519 (if (and (not what) (not (eq org-ts-what 'day))
11520 org-display-custom-times
11521 (get-text-property (point) 'display)
11522 (not (get-text-property (1- (point)) 'display)))
11523 (setq org-ts-what 'day))
11524 (setq org-ts-what (or what org-ts-what)
11525 inactive (= (char-after (match-beginning 0)) ?\[)
11526 ts (match-string 0))
11527 (replace-match "")
11528 (if (string-match
11529 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11531 (setq extra (match-string 1 ts)))
11532 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11533 (setq with-hm t))
11534 (setq time0 (org-parse-time-string ts))
11535 (when (and (eq org-ts-what 'minute)
11536 (eq current-prefix-arg nil))
11537 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11538 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11539 (setcar (cdr time0) (+ (nth 1 time0)
11540 (if (> n 0) (- rem) (- dm rem))))))
11541 (setq time
11542 (encode-time (or (car time0) 0)
11543 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11544 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11545 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11546 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11547 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11548 (nthcdr 6 time0)))
11549 (when (integerp org-ts-what)
11550 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11551 (if (eq what 'calendar)
11552 (let ((cal-date (org-get-date-from-calendar)))
11553 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11554 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11555 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11556 (setcar time0 (or (car time0) 0))
11557 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11558 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11559 (setq time (apply 'encode-time time0))))
11560 (setq org-last-changed-timestamp
11561 (org-insert-time-stamp time with-hm inactive nil nil extra))
11562 (org-clock-update-time-maybe)
11563 (goto-char pos)
11564 ;; Try to recenter the calendar window, if any
11565 (if (and org-calendar-follow-timestamp-change
11566 (get-buffer-window "*Calendar*" t)
11567 (memq org-ts-what '(day month year)))
11568 (org-recenter-calendar (time-to-days time))))))
11570 (defun org-modify-ts-extra (s pos n dm)
11571 "Change the different parts of the lead-time and repeat fields in timestamp."
11572 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11573 ng h m new rem)
11574 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11575 (cond
11576 ((or (org-pos-in-match-range pos 2)
11577 (org-pos-in-match-range pos 3))
11578 (setq m (string-to-number (match-string 3 s))
11579 h (string-to-number (match-string 2 s)))
11580 (if (org-pos-in-match-range pos 2)
11581 (setq h (+ h n))
11582 (setq n (* dm (org-no-warnings (signum n))))
11583 (when (not (= 0 (setq rem (% m dm))))
11584 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11585 (setq m (+ m n)))
11586 (if (< m 0) (setq m (+ m 60) h (1- h)))
11587 (if (> m 59) (setq m (- m 60) h (1+ h)))
11588 (setq h (min 24 (max 0 h)))
11589 (setq ng 1 new (format "-%02d:%02d" h m)))
11590 ((org-pos-in-match-range pos 6)
11591 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11592 ((org-pos-in-match-range pos 5)
11593 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11595 ((org-pos-in-match-range pos 9)
11596 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11597 ((org-pos-in-match-range pos 8)
11598 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11600 (when ng
11601 (setq s (concat
11602 (substring s 0 (match-beginning ng))
11604 (substring s (match-end ng))))))
11607 (defun org-recenter-calendar (date)
11608 "If the calendar is visible, recenter it to DATE."
11609 (let* ((win (selected-window))
11610 (cwin (get-buffer-window "*Calendar*" t))
11611 (calendar-move-hook nil))
11612 (when cwin
11613 (select-window cwin)
11614 (calendar-goto-date (if (listp date) date
11615 (calendar-gregorian-from-absolute date)))
11616 (select-window win))))
11618 (defun org-goto-calendar (&optional arg)
11619 "Go to the Emacs calendar at the current date.
11620 If there is a time stamp in the current line, go to that date.
11621 A prefix ARG can be used to force the current date."
11622 (interactive "P")
11623 (let ((tsr org-ts-regexp) diff
11624 (calendar-move-hook nil)
11625 (calendar-view-holidays-initially-flag nil)
11626 (view-calendar-holidays-initially nil)
11627 (calendar-view-diary-initially-flag nil)
11628 (view-diary-entries-initially nil))
11629 (if (or (org-at-timestamp-p)
11630 (save-excursion
11631 (beginning-of-line 1)
11632 (looking-at (concat ".*" tsr))))
11633 (let ((d1 (time-to-days (current-time)))
11634 (d2 (time-to-days
11635 (org-time-string-to-time (match-string 1)))))
11636 (setq diff (- d2 d1))))
11637 (calendar)
11638 (calendar-goto-today)
11639 (if (and diff (not arg)) (calendar-forward-day diff))))
11641 (defun org-get-date-from-calendar ()
11642 "Return a list (month day year) of date at point in calendar."
11643 (with-current-buffer "*Calendar*"
11644 (save-match-data
11645 (calendar-cursor-to-date))))
11647 (defun org-date-from-calendar ()
11648 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11649 If there is already a time stamp at the cursor position, update it."
11650 (interactive)
11651 (if (org-at-timestamp-p t)
11652 (org-timestamp-change 0 'calendar)
11653 (let ((cal-date (org-get-date-from-calendar)))
11654 (org-insert-time-stamp
11655 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11657 (defun org-minutes-to-hh:mm-string (m)
11658 "Compute H:MM from a number of minutes."
11659 (let ((h (/ m 60)))
11660 (setq m (- m (* 60 h)))
11661 (format org-time-clocksum-format h m)))
11663 (defun org-hh:mm-string-to-minutes (s)
11664 "Convert a string H:MM to a number of minutes."
11665 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11666 (+ (* (string-to-number (match-string 1 s)) 60)
11667 (string-to-number (match-string 2 s)))
11670 ;;;; Agenda files
11672 ;;;###autoload
11673 (defun org-iswitchb (&optional arg)
11674 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11675 With a prefix argument, restrict available to files.
11676 With two prefix arguments, restrict available buffers to agenda files.
11678 Due to some yet unresolved reason, the global function
11679 `iswitchb-mode' needs to be active for this function to work."
11680 (interactive "P")
11681 (require 'iswitchb)
11682 (let ((enabled iswitchb-mode) blist)
11683 (or enabled (iswitchb-mode 1))
11684 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11685 ((equal arg '(16)) (org-buffer-list 'agenda))
11686 (t (org-buffer-list))))
11687 (unwind-protect
11688 (let ((iswitchb-make-buflist-hook
11689 (lambda ()
11690 (setq iswitchb-temp-buflist
11691 (mapcar 'buffer-name blist)))))
11692 (switch-to-buffer
11693 (iswitchb-read-buffer
11694 "Switch-to: " nil t))
11695 (or enabled (iswitchb-mode -1))))))
11697 (defun org-buffer-list (&optional predicate exclude-tmp)
11698 "Return a list of Org buffers.
11699 PREDICATE can be `export', `files' or `agenda'.
11701 export restrict the list to Export buffers.
11702 files restrict the list to buffers visiting Org files.
11703 agenda restrict the list to buffers visiting agenda files.
11705 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11706 (let* ((bfn nil)
11707 (agenda-files (and (eq predicate 'agenda)
11708 (mapcar 'file-truename (org-agenda-files t))))
11709 (filter
11710 (cond
11711 ((eq predicate 'files)
11712 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11713 ((eq predicate 'export)
11714 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11715 ((eq predicate 'agenda)
11716 (lambda (b)
11717 (with-current-buffer b
11718 (and (eq major-mode 'org-mode)
11719 (setq bfn (buffer-file-name b))
11720 (member (file-truename bfn) agenda-files)))))
11721 (t (lambda (b) (with-current-buffer b
11722 (or (eq major-mode 'org-mode)
11723 (string-match "\*Org .*Export"
11724 (buffer-name b)))))))))
11725 (delq nil
11726 (mapcar
11727 (lambda(b)
11728 (if (and (funcall filter b)
11729 (or (not exclude-tmp)
11730 (not (string-match "tmp" (buffer-name b)))))
11732 nil))
11733 (buffer-list)))))
11735 (defun org-agenda-files (&optional unrestricted archives)
11736 "Get the list of agenda files.
11737 Optional UNRESTRICTED means return the full list even if a restriction
11738 is currently in place.
11739 When ARCHIVES is t, include all archive files hat are really being
11740 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11741 `org-agenda-archives-mode' is t."
11742 (let ((files
11743 (cond
11744 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11745 ((stringp org-agenda-files) (org-read-agenda-file-list))
11746 ((listp org-agenda-files) org-agenda-files)
11747 (t (error "Invalid value of `org-agenda-files'")))))
11748 (setq files (apply 'append
11749 (mapcar (lambda (f)
11750 (if (file-directory-p f)
11751 (directory-files
11752 f t org-agenda-file-regexp)
11753 (list f)))
11754 files)))
11755 (when org-agenda-skip-unavailable-files
11756 (setq files (delq nil
11757 (mapcar (function
11758 (lambda (file)
11759 (and (file-readable-p file) file)))
11760 files))))
11761 (when (or (eq archives t)
11762 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11763 (setq files (org-add-archive-files files)))
11764 files))
11766 (defun org-edit-agenda-file-list ()
11767 "Edit the list of agenda files.
11768 Depending on setup, this either uses customize to edit the variable
11769 `org-agenda-files', or it visits the file that is holding the list. In the
11770 latter case, the buffer is set up in a way that saving it automatically kills
11771 the buffer and restores the previous window configuration."
11772 (interactive)
11773 (if (stringp org-agenda-files)
11774 (let ((cw (current-window-configuration)))
11775 (find-file org-agenda-files)
11776 (org-set-local 'org-window-configuration cw)
11777 (org-add-hook 'after-save-hook
11778 (lambda ()
11779 (set-window-configuration
11780 (prog1 org-window-configuration
11781 (kill-buffer (current-buffer))))
11782 (org-install-agenda-files-menu)
11783 (message "New agenda file list installed"))
11784 nil 'local)
11785 (message "%s" (substitute-command-keys
11786 "Edit list and finish with \\[save-buffer]")))
11787 (customize-variable 'org-agenda-files)))
11789 (defun org-store-new-agenda-file-list (list)
11790 "Set new value for the agenda file list and save it correcly."
11791 (if (stringp org-agenda-files)
11792 (let ((f org-agenda-files) b)
11793 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11794 (with-temp-file f
11795 (insert (mapconcat 'identity list "\n") "\n")))
11796 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11797 (setq org-agenda-files list)
11798 (customize-save-variable 'org-agenda-files org-agenda-files))))
11800 (defun org-read-agenda-file-list ()
11801 "Read the list of agenda files from a file."
11802 (when (file-directory-p org-agenda-files)
11803 (error "`org-agenda-files' cannot be a single directory"))
11804 (when (stringp org-agenda-files)
11805 (with-temp-buffer
11806 (insert-file-contents org-agenda-files)
11807 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11810 ;;;###autoload
11811 (defun org-cycle-agenda-files ()
11812 "Cycle through the files in `org-agenda-files'.
11813 If the current buffer visits an agenda file, find the next one in the list.
11814 If the current buffer does not, find the first agenda file."
11815 (interactive)
11816 (let* ((fs (org-agenda-files t))
11817 (files (append fs (list (car fs))))
11818 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11819 file)
11820 (unless files (error "No agenda files"))
11821 (catch 'exit
11822 (while (setq file (pop files))
11823 (if (equal (file-truename file) tcf)
11824 (when (car files)
11825 (find-file (car files))
11826 (throw 'exit t))))
11827 (find-file (car fs)))
11828 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11830 (defun org-agenda-file-to-front (&optional to-end)
11831 "Move/add the current file to the top of the agenda file list.
11832 If the file is not present in the list, it is added to the front. If it is
11833 present, it is moved there. With optional argument TO-END, add/move to the
11834 end of the list."
11835 (interactive "P")
11836 (let ((org-agenda-skip-unavailable-files nil)
11837 (file-alist (mapcar (lambda (x)
11838 (cons (file-truename x) x))
11839 (org-agenda-files t)))
11840 (ctf (file-truename buffer-file-name))
11841 x had)
11842 (setq x (assoc ctf file-alist) had x)
11844 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11845 (if to-end
11846 (setq file-alist (append (delq x file-alist) (list x)))
11847 (setq file-alist (cons x (delq x file-alist))))
11848 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11849 (org-install-agenda-files-menu)
11850 (message "File %s to %s of agenda file list"
11851 (if had "moved" "added") (if to-end "end" "front"))))
11853 (defun org-remove-file (&optional file)
11854 "Remove current file from the list of files in variable `org-agenda-files'.
11855 These are the files which are being checked for agenda entries.
11856 Optional argument FILE means, use this file instead of the current."
11857 (interactive)
11858 (let* ((org-agenda-skip-unavailable-files nil)
11859 (file (or file buffer-file-name))
11860 (true-file (file-truename file))
11861 (afile (abbreviate-file-name file))
11862 (files (delq nil (mapcar
11863 (lambda (x)
11864 (if (equal true-file
11865 (file-truename x))
11866 nil x))
11867 (org-agenda-files t)))))
11868 (if (not (= (length files) (length (org-agenda-files t))))
11869 (progn
11870 (org-store-new-agenda-file-list files)
11871 (org-install-agenda-files-menu)
11872 (message "Removed file: %s" afile))
11873 (message "File was not in list: %s (not removed)" afile))))
11875 (defun org-file-menu-entry (file)
11876 (vector file (list 'find-file file) t))
11878 (defun org-check-agenda-file (file)
11879 "Make sure FILE exists. If not, ask user what to do."
11880 (when (not (file-exists-p file))
11881 (message "non-existent file %s. [R]emove from list or [A]bort?"
11882 (abbreviate-file-name file))
11883 (let ((r (downcase (read-char-exclusive))))
11884 (cond
11885 ((equal r ?r)
11886 (org-remove-file file)
11887 (throw 'nextfile t))
11888 (t (error "Abort"))))))
11890 (defun org-get-agenda-file-buffer (file)
11891 "Get a buffer visiting FILE. If the buffer needs to be created, add
11892 it to the list of buffers which might be released later."
11893 (let ((buf (org-find-base-buffer-visiting file)))
11894 (if buf
11895 buf ; just return it
11896 ;; Make a new buffer and remember it
11897 (setq buf (find-file-noselect file))
11898 (if buf (push buf org-agenda-new-buffers))
11899 buf)))
11901 (defun org-release-buffers (blist)
11902 "Release all buffers in list, asking the user for confirmation when needed.
11903 When a buffer is unmodified, it is just killed. When modified, it is saved
11904 \(if the user agrees) and then killed."
11905 (let (buf file)
11906 (while (setq buf (pop blist))
11907 (setq file (buffer-file-name buf))
11908 (when (and (buffer-modified-p buf)
11909 file
11910 (y-or-n-p (format "Save file %s? " file)))
11911 (with-current-buffer buf (save-buffer)))
11912 (kill-buffer buf))))
11914 (defun org-prepare-agenda-buffers (files)
11915 "Create buffers for all agenda files, protect archived trees and comments."
11916 (interactive)
11917 (let ((pa '(:org-archived t))
11918 (pc '(:org-comment t))
11919 (pall '(:org-archived t :org-comment t))
11920 (inhibit-read-only t)
11921 (rea (concat ":" org-archive-tag ":"))
11922 bmp file re)
11923 (save-excursion
11924 (save-restriction
11925 (while (setq file (pop files))
11926 (if (bufferp file)
11927 (set-buffer file)
11928 (org-check-agenda-file file)
11929 (set-buffer (org-get-agenda-file-buffer file)))
11930 (widen)
11931 (setq bmp (buffer-modified-p))
11932 (org-refresh-category-properties)
11933 (setq org-todo-keywords-for-agenda
11934 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11935 (setq org-done-keywords-for-agenda
11936 (append org-done-keywords-for-agenda org-done-keywords))
11937 (setq org-todo-keyword-alist-for-agenda
11938 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11939 (setq org-tag-alist-for-agenda
11940 (append org-tag-alist-for-agenda org-tag-alist))
11942 (save-excursion
11943 (remove-text-properties (point-min) (point-max) pall)
11944 (when org-agenda-skip-archived-trees
11945 (goto-char (point-min))
11946 (while (re-search-forward rea nil t)
11947 (if (org-on-heading-p t)
11948 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11949 (goto-char (point-min))
11950 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11951 (while (re-search-forward re nil t)
11952 (add-text-properties
11953 (match-beginning 0) (org-end-of-subtree t) pc)))
11954 (set-buffer-modified-p bmp))))
11955 (setq org-todo-keyword-alist-for-agenda
11956 (org-uniquify org-todo-keyword-alist-for-agenda)
11957 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11959 ;;;; Embedded LaTeX
11961 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11962 "Keymap for the minor `org-cdlatex-mode'.")
11964 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11965 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11966 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11967 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11968 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11970 (defvar org-cdlatex-texmathp-advice-is-done nil
11971 "Flag remembering if we have applied the advice to texmathp already.")
11973 (define-minor-mode org-cdlatex-mode
11974 "Toggle the minor `org-cdlatex-mode'.
11975 This mode supports entering LaTeX environment and math in LaTeX fragments
11976 in Org-mode.
11977 \\{org-cdlatex-mode-map}"
11978 nil " OCDL" nil
11979 (when org-cdlatex-mode (require 'cdlatex))
11980 (unless org-cdlatex-texmathp-advice-is-done
11981 (setq org-cdlatex-texmathp-advice-is-done t)
11982 (defadvice texmathp (around org-math-always-on activate)
11983 "Always return t in org-mode buffers.
11984 This is because we want to insert math symbols without dollars even outside
11985 the LaTeX math segments. If Orgmode thinks that point is actually inside
11986 en embedded LaTeX fragement, let texmathp do its job.
11987 \\[org-cdlatex-mode-map]"
11988 (interactive)
11989 (let (p)
11990 (cond
11991 ((not (org-mode-p)) ad-do-it)
11992 ((eq this-command 'cdlatex-math-symbol)
11993 (setq ad-return-value t
11994 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11996 (let ((p (org-inside-LaTeX-fragment-p)))
11997 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11998 (setq ad-return-value t
11999 texmathp-why '("Org-mode embedded math" . 0))
12000 (if p ad-do-it)))))))))
12002 (defun turn-on-org-cdlatex ()
12003 "Unconditionally turn on `org-cdlatex-mode'."
12004 (org-cdlatex-mode 1))
12006 (defun org-inside-LaTeX-fragment-p ()
12007 "Test if point is inside a LaTeX fragment.
12008 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12009 sequence appearing also before point.
12010 Even though the matchers for math are configurable, this function assumes
12011 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12012 delimiters are skipped when they have been removed by customization.
12013 The return value is nil, or a cons cell with the delimiter and
12014 and the position of this delimiter.
12016 This function does a reasonably good job, but can locally be fooled by
12017 for example currency specifications. For example it will assume being in
12018 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12019 fragments that are properly closed, but during editing, we have to live
12020 with the uncertainty caused by missing closing delimiters. This function
12021 looks only before point, not after."
12022 (catch 'exit
12023 (let ((pos (point))
12024 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12025 (lim (progn
12026 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12027 (point)))
12028 dd-on str (start 0) m re)
12029 (goto-char pos)
12030 (when dodollar
12031 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12032 re (nth 1 (assoc "$" org-latex-regexps)))
12033 (while (string-match re str start)
12034 (cond
12035 ((= (match-end 0) (length str))
12036 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12037 ((= (match-end 0) (- (length str) 5))
12038 (throw 'exit nil))
12039 (t (setq start (match-end 0))))))
12040 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12041 (goto-char pos)
12042 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12043 (and (match-beginning 2) (throw 'exit nil))
12044 ;; count $$
12045 (while (re-search-backward "\\$\\$" lim t)
12046 (setq dd-on (not dd-on)))
12047 (goto-char pos)
12048 (if dd-on (cons "$$" m))))))
12051 (defun org-try-cdlatex-tab ()
12052 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12053 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12054 - inside a LaTeX fragment, or
12055 - after the first word in a line, where an abbreviation expansion could
12056 insert a LaTeX environment."
12057 (when org-cdlatex-mode
12058 (cond
12059 ((save-excursion
12060 (skip-chars-backward "a-zA-Z0-9*")
12061 (skip-chars-backward " \t")
12062 (bolp))
12063 (cdlatex-tab) t)
12064 ((org-inside-LaTeX-fragment-p)
12065 (cdlatex-tab) t)
12066 (t nil))))
12068 (defun org-cdlatex-underscore-caret (&optional arg)
12069 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12070 Revert to the normal definition outside of these fragments."
12071 (interactive "P")
12072 (if (org-inside-LaTeX-fragment-p)
12073 (call-interactively 'cdlatex-sub-superscript)
12074 (let (org-cdlatex-mode)
12075 (call-interactively (key-binding (vector last-input-event))))))
12077 (defun org-cdlatex-math-modify (&optional arg)
12078 "Execute `cdlatex-math-modify' in LaTeX fragments.
12079 Revert to the normal definition outside of these fragments."
12080 (interactive "P")
12081 (if (org-inside-LaTeX-fragment-p)
12082 (call-interactively 'cdlatex-math-modify)
12083 (let (org-cdlatex-mode)
12084 (call-interactively (key-binding (vector last-input-event))))))
12086 (defvar org-latex-fragment-image-overlays nil
12087 "List of overlays carrying the images of latex fragments.")
12088 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12090 (defun org-remove-latex-fragment-image-overlays ()
12091 "Remove all overlays with LaTeX fragment images in current buffer."
12092 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12093 (setq org-latex-fragment-image-overlays nil))
12095 (defun org-preview-latex-fragment (&optional subtree)
12096 "Preview the LaTeX fragment at point, or all locally or globally.
12097 If the cursor is in a LaTeX fragment, create the image and overlay
12098 it over the source code. If there is no fragment at point, display
12099 all fragments in the current text, from one headline to the next. With
12100 prefix SUBTREE, display all fragments in the current subtree. With a
12101 double prefix `C-u C-u', or when the cursor is before the first headline,
12102 display all fragments in the buffer.
12103 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12104 (interactive "P")
12105 (org-remove-latex-fragment-image-overlays)
12106 (save-excursion
12107 (save-restriction
12108 (let (beg end at msg)
12109 (cond
12110 ((or (equal subtree '(16))
12111 (not (save-excursion
12112 (re-search-backward (concat "^" outline-regexp) nil t))))
12113 (setq beg (point-min) end (point-max)
12114 msg "Creating images for buffer...%s"))
12115 ((equal subtree '(4))
12116 (org-back-to-heading)
12117 (setq beg (point) end (org-end-of-subtree t)
12118 msg "Creating images for subtree...%s"))
12120 (if (setq at (org-inside-LaTeX-fragment-p))
12121 (goto-char (max (point-min) (- (cdr at) 2)))
12122 (org-back-to-heading))
12123 (setq beg (point) end (progn (outline-next-heading) (point))
12124 msg (if at "Creating image...%s"
12125 "Creating images for entry...%s"))))
12126 (message msg "")
12127 (narrow-to-region beg end)
12128 (goto-char beg)
12129 (org-format-latex
12130 (concat "ltxpng/" (file-name-sans-extension
12131 (file-name-nondirectory
12132 buffer-file-name)))
12133 default-directory 'overlays msg at 'forbuffer)
12134 (message msg "done. Use `C-c C-c' to remove images.")))))
12136 (defvar org-latex-regexps
12137 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12138 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12139 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12140 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12141 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12142 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12143 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12144 "Regular expressions for matching embedded LaTeX.")
12146 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12147 "Replace LaTeX fragments with links to an image, and produce images."
12148 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12149 (let* ((prefixnodir (file-name-nondirectory prefix))
12150 (absprefix (expand-file-name prefix dir))
12151 (todir (file-name-directory absprefix))
12152 (opt org-format-latex-options)
12153 (matchers (plist-get opt :matchers))
12154 (re-list org-latex-regexps)
12155 (cnt 0) txt link beg end re e checkdir
12156 m n block linkfile movefile ov)
12157 ;; Check if there are old images files with this prefix, and remove them
12158 (when (file-directory-p todir)
12159 (mapc 'delete-file
12160 (directory-files
12161 todir 'full
12162 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12163 ;; Check the different regular expressions
12164 (while (setq e (pop re-list))
12165 (setq m (car e) re (nth 1 e) n (nth 2 e)
12166 block (if (nth 3 e) "\n\n" ""))
12167 (when (member m matchers)
12168 (goto-char (point-min))
12169 (while (re-search-forward re nil t)
12170 (when (or (not at) (equal (cdr at) (match-beginning n)))
12171 (setq txt (match-string n)
12172 beg (match-beginning n) end (match-end n)
12173 cnt (1+ cnt)
12174 linkfile (format "%s_%04d.png" prefix cnt)
12175 movefile (format "%s_%04d.png" absprefix cnt)
12176 link (concat block "[[file:" linkfile "]]" block))
12177 (if msg (message msg cnt))
12178 (goto-char beg)
12179 (unless checkdir ; make sure the directory exists
12180 (setq checkdir t)
12181 (or (file-directory-p todir) (make-directory todir)))
12182 (org-create-formula-image
12183 txt movefile opt forbuffer)
12184 (if overlays
12185 (progn
12186 (setq ov (org-make-overlay beg end))
12187 (if (featurep 'xemacs)
12188 (progn
12189 (org-overlay-put ov 'invisible t)
12190 (org-overlay-put
12191 ov 'end-glyph
12192 (make-glyph (vector 'png :file movefile))))
12193 (org-overlay-put
12194 ov 'display
12195 (list 'image :type 'png :file movefile :ascent 'center)))
12196 (push ov org-latex-fragment-image-overlays)
12197 (goto-char end))
12198 (delete-region beg end)
12199 (insert link))))))))
12201 ;; This function borrows from Ganesh Swami's latex2png.el
12202 (defun org-create-formula-image (string tofile options buffer)
12203 (let* ((tmpdir (if (featurep 'xemacs)
12204 (temp-directory)
12205 temporary-file-directory))
12206 (texfilebase (make-temp-name
12207 (expand-file-name "orgtex" tmpdir)))
12208 (texfile (concat texfilebase ".tex"))
12209 (dvifile (concat texfilebase ".dvi"))
12210 (pngfile (concat texfilebase ".png"))
12211 (fnh (if (featurep 'xemacs)
12212 (font-height (get-face-font 'default))
12213 (face-attribute 'default :height nil)))
12214 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12215 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12216 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12217 "Black"))
12218 (bg (or (plist-get options (if buffer :background :html-background))
12219 "Transparent")))
12220 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12221 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12222 (with-temp-file texfile
12223 (insert org-format-latex-header
12224 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12225 (let ((dir default-directory))
12226 (condition-case nil
12227 (progn
12228 (cd tmpdir)
12229 (call-process "latex" nil nil nil texfile))
12230 (error nil))
12231 (cd dir))
12232 (if (not (file-exists-p dvifile))
12233 (progn (message "Failed to create dvi file from %s" texfile) nil)
12234 (condition-case nil
12235 (call-process "dvipng" nil nil nil
12236 "-E" "-fg" fg "-bg" bg
12237 "-D" dpi
12238 ;;"-x" scale "-y" scale
12239 "-T" "tight"
12240 "-o" pngfile
12241 dvifile)
12242 (error nil))
12243 (if (not (file-exists-p pngfile))
12244 (progn (message "Failed to create png file from %s" texfile) nil)
12245 ;; Use the requested file name and clean up
12246 (copy-file pngfile tofile 'replace)
12247 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12248 (delete-file (concat texfilebase e)))
12249 pngfile))))
12251 (defun org-dvipng-color (attr)
12252 "Return an rgb color specification for dvipng."
12253 (apply 'format "rgb %s %s %s"
12254 (mapcar 'org-normalize-color
12255 (color-values (face-attribute 'default attr nil)))))
12257 (defun org-normalize-color (value)
12258 "Return string to be used as color value for an RGB component."
12259 (format "%g" (/ value 65535.0)))
12262 ;;;; Key bindings
12264 ;; Make `C-c C-x' a prefix key
12265 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12267 ;; TAB key with modifiers
12268 (org-defkey org-mode-map "\C-i" 'org-cycle)
12269 (org-defkey org-mode-map [(tab)] 'org-cycle)
12270 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12271 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12272 (org-defkey org-mode-map "\M-\t" 'org-complete)
12273 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12274 ;; The following line is necessary under Suse GNU/Linux
12275 (unless (featurep 'xemacs)
12276 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12277 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12278 (define-key org-mode-map [backtab] 'org-shifttab)
12280 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12281 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12282 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12284 ;; Cursor keys with modifiers
12285 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12286 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12287 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12288 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12290 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12291 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12292 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12293 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12295 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12296 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12297 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12298 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12300 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12301 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12303 ;;; Extra keys for tty access.
12304 ;; We only set them when really needed because otherwise the
12305 ;; menus don't show the simple keys
12307 (when (or org-use-extra-keys
12308 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12309 (not window-system))
12310 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12311 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12312 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12313 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12314 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12315 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12316 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12317 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12318 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12319 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12320 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12321 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12322 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12323 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12324 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12325 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12326 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12327 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12328 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12329 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12330 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12331 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12333 ;; All the other keys
12335 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12336 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12337 (if (boundp 'narrow-map)
12338 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12339 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12340 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12341 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12342 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12343 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12344 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12345 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12346 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12347 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12348 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12349 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12350 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12351 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12352 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12353 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12354 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12355 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12356 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12357 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12358 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12359 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12360 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12361 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12362 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12363 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12364 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12365 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12366 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12367 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12368 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12369 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12370 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12371 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12372 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12373 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12374 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12375 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12376 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12377 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12378 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12379 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12380 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12381 (org-defkey org-mode-map "\C-c^" 'org-sort)
12382 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12383 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12384 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12385 (org-defkey org-mode-map "\C-m" 'org-return)
12386 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12387 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12388 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12389 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12390 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12391 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12392 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12393 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12394 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12395 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12396 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12397 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12398 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12399 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12400 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12401 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12403 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12404 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12405 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12406 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12408 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12409 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12410 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12411 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12412 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12413 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12414 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12415 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12416 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12417 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12418 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12419 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12421 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12423 (when (featurep 'xemacs)
12424 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12426 (defvar org-table-auto-blank-field) ; defined in org-table.el
12427 (defun org-self-insert-command (N)
12428 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12429 If the cursor is in a table looking at whitespace, the whitespace is
12430 overwritten, and the table is not marked as requiring realignment."
12431 (interactive "p")
12432 (if (and (org-table-p)
12433 (progn
12434 ;; check if we blank the field, and if that triggers align
12435 (and (featurep 'org-table) org-table-auto-blank-field
12436 (member last-command
12437 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12438 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12439 ;; got extra space, this field does not determine column width
12440 (let (org-table-may-need-update) (org-table-blank-field))
12441 ;; no extra space, this field may determine column width
12442 (org-table-blank-field)))
12444 (eq N 1)
12445 (looking-at "[^|\n]* |"))
12446 (let (org-table-may-need-update)
12447 (goto-char (1- (match-end 0)))
12448 (delete-backward-char 1)
12449 (goto-char (match-beginning 0))
12450 (self-insert-command N))
12451 (setq org-table-may-need-update t)
12452 (self-insert-command N)
12453 (org-fix-tags-on-the-fly)))
12455 (defun org-fix-tags-on-the-fly ()
12456 (when (and (equal (char-after (point-at-bol)) ?*)
12457 (org-on-heading-p))
12458 (org-align-tags-here org-tags-column)))
12460 (defun org-delete-backward-char (N)
12461 "Like `delete-backward-char', insert whitespace at field end in tables.
12462 When deleting backwards, in tables this function will insert whitespace in
12463 front of the next \"|\" separator, to keep the table aligned. The table will
12464 still be marked for re-alignment if the field did fill the entire column,
12465 because, in this case the deletion might narrow the column."
12466 (interactive "p")
12467 (if (and (org-table-p)
12468 (eq N 1)
12469 (string-match "|" (buffer-substring (point-at-bol) (point)))
12470 (looking-at ".*?|"))
12471 (let ((pos (point))
12472 (noalign (looking-at "[^|\n\r]* |"))
12473 (c org-table-may-need-update))
12474 (backward-delete-char N)
12475 (skip-chars-forward "^|")
12476 (insert " ")
12477 (goto-char (1- pos))
12478 ;; noalign: if there were two spaces at the end, this field
12479 ;; does not determine the width of the column.
12480 (if noalign (setq org-table-may-need-update c)))
12481 (backward-delete-char N)
12482 (org-fix-tags-on-the-fly)))
12484 (defun org-delete-char (N)
12485 "Like `delete-char', but insert whitespace at field end in tables.
12486 When deleting characters, in tables this function will insert whitespace in
12487 front of the next \"|\" separator, to keep the table aligned. The table will
12488 still be marked for re-alignment if the field did fill the entire column,
12489 because, in this case the deletion might narrow the column."
12490 (interactive "p")
12491 (if (and (org-table-p)
12492 (not (bolp))
12493 (not (= (char-after) ?|))
12494 (eq N 1))
12495 (if (looking-at ".*?|")
12496 (let ((pos (point))
12497 (noalign (looking-at "[^|\n\r]* |"))
12498 (c org-table-may-need-update))
12499 (replace-match (concat
12500 (substring (match-string 0) 1 -1)
12501 " |"))
12502 (goto-char pos)
12503 ;; noalign: if there were two spaces at the end, this field
12504 ;; does not determine the width of the column.
12505 (if noalign (setq org-table-may-need-update c)))
12506 (delete-char N))
12507 (delete-char N)
12508 (org-fix-tags-on-the-fly)))
12510 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12511 (put 'org-self-insert-command 'delete-selection t)
12512 (put 'orgtbl-self-insert-command 'delete-selection t)
12513 (put 'org-delete-char 'delete-selection 'supersede)
12514 (put 'org-delete-backward-char 'delete-selection 'supersede)
12516 ;; Make `flyspell-mode' delay after some commands
12517 (put 'org-self-insert-command 'flyspell-delayed t)
12518 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12519 (put 'org-delete-char 'flyspell-delayed t)
12520 (put 'org-delete-backward-char 'flyspell-delayed t)
12522 ;; Make pabbrev-mode expand after org-mode commands
12523 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12524 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12526 ;; How to do this: Measure non-white length of current string
12527 ;; If equal to column width, we should realign.
12529 (defun org-remap (map &rest commands)
12530 "In MAP, remap the functions given in COMMANDS.
12531 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12532 (let (new old)
12533 (while commands
12534 (setq old (pop commands) new (pop commands))
12535 (if (fboundp 'command-remapping)
12536 (org-defkey map (vector 'remap old) new)
12537 (substitute-key-definition old new map global-map)))))
12539 (when (eq org-enable-table-editor 'optimized)
12540 ;; If the user wants maximum table support, we need to hijack
12541 ;; some standard editing functions
12542 (org-remap org-mode-map
12543 'self-insert-command 'org-self-insert-command
12544 'delete-char 'org-delete-char
12545 'delete-backward-char 'org-delete-backward-char)
12546 (org-defkey org-mode-map "|" 'org-force-self-insert))
12548 (defun org-shiftcursor-error ()
12549 "Throw an error because Shift-Cursor command was applied in wrong context."
12550 (error "This command is active in special context like tables, headlines or timestamps"))
12552 (defun org-shifttab (&optional arg)
12553 "Global visibility cycling or move to previous table field.
12554 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12555 on context.
12556 See the individual commands for more information."
12557 (interactive "P")
12558 (cond
12559 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12560 ((integerp arg)
12561 (message "Content view to level: %d" arg)
12562 (org-content (prefix-numeric-value arg))
12563 (setq org-cycle-global-status 'overview))
12564 (t (call-interactively 'org-global-cycle))))
12566 (defun org-shiftmetaleft ()
12567 "Promote subtree or delete table column.
12568 Calls `org-promote-subtree', `org-outdent-item',
12569 or `org-table-delete-column', depending on context.
12570 See the individual commands for more information."
12571 (interactive)
12572 (cond
12573 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12574 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12575 ((org-at-item-p) (call-interactively 'org-outdent-item))
12576 (t (org-shiftcursor-error))))
12578 (defun org-shiftmetaright ()
12579 "Demote subtree or insert table column.
12580 Calls `org-demote-subtree', `org-indent-item',
12581 or `org-table-insert-column', depending on context.
12582 See the individual commands for more information."
12583 (interactive)
12584 (cond
12585 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12586 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12587 ((org-at-item-p) (call-interactively 'org-indent-item))
12588 (t (org-shiftcursor-error))))
12590 (defun org-shiftmetaup (&optional arg)
12591 "Move subtree up or kill table row.
12592 Calls `org-move-subtree-up' or `org-table-kill-row' or
12593 `org-move-item-up' depending on context. See the individual commands
12594 for more information."
12595 (interactive "P")
12596 (cond
12597 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12598 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12599 ((org-at-item-p) (call-interactively 'org-move-item-up))
12600 (t (org-shiftcursor-error))))
12601 (defun org-shiftmetadown (&optional arg)
12602 "Move subtree down or insert table row.
12603 Calls `org-move-subtree-down' or `org-table-insert-row' or
12604 `org-move-item-down', depending on context. See the individual
12605 commands for more information."
12606 (interactive "P")
12607 (cond
12608 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12609 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12610 ((org-at-item-p) (call-interactively 'org-move-item-down))
12611 (t (org-shiftcursor-error))))
12613 (defun org-metaleft (&optional arg)
12614 "Promote heading or move table column to left.
12615 Calls `org-do-promote' or `org-table-move-column', depending on context.
12616 With no specific context, calls the Emacs default `backward-word'.
12617 See the individual commands for more information."
12618 (interactive "P")
12619 (cond
12620 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12621 ((or (org-on-heading-p) (org-region-active-p))
12622 (call-interactively 'org-do-promote))
12623 ((org-at-item-p) (call-interactively 'org-outdent-item))
12624 (t (call-interactively 'backward-word))))
12626 (defun org-metaright (&optional arg)
12627 "Demote subtree or move table column to right.
12628 Calls `org-do-demote' or `org-table-move-column', depending on context.
12629 With no specific context, calls the Emacs default `forward-word'.
12630 See the individual commands for more information."
12631 (interactive "P")
12632 (cond
12633 ((org-at-table-p) (call-interactively 'org-table-move-column))
12634 ((or (org-on-heading-p) (org-region-active-p))
12635 (call-interactively 'org-do-demote))
12636 ((org-at-item-p) (call-interactively 'org-indent-item))
12637 (t (call-interactively 'forward-word))))
12639 (defun org-metaup (&optional arg)
12640 "Move subtree up or move table row up.
12641 Calls `org-move-subtree-up' or `org-table-move-row' or
12642 `org-move-item-up', depending on context. See the individual commands
12643 for more information."
12644 (interactive "P")
12645 (cond
12646 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12647 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12648 ((org-at-item-p) (call-interactively 'org-move-item-up))
12649 (t (transpose-lines 1) (beginning-of-line -1))))
12651 (defun org-metadown (&optional arg)
12652 "Move subtree down or move table row down.
12653 Calls `org-move-subtree-down' or `org-table-move-row' or
12654 `org-move-item-down', depending on context. See the individual
12655 commands for more information."
12656 (interactive "P")
12657 (cond
12658 ((org-at-table-p) (call-interactively 'org-table-move-row))
12659 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12660 ((org-at-item-p) (call-interactively 'org-move-item-down))
12661 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12663 (defun org-shiftup (&optional arg)
12664 "Increase item in timestamp or increase priority of current headline.
12665 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12666 depending on context. See the individual commands for more information."
12667 (interactive "P")
12668 (cond
12669 ((org-at-timestamp-p t)
12670 (call-interactively (if org-edit-timestamp-down-means-later
12671 'org-timestamp-down 'org-timestamp-up)))
12672 ((org-on-heading-p) (call-interactively 'org-priority-up))
12673 ((org-at-item-p) (call-interactively 'org-previous-item))
12674 ((org-clocktable-try-shift 'up arg))
12675 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12677 (defun org-shiftdown (&optional arg)
12678 "Decrease item in timestamp or decrease priority of current headline.
12679 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12680 depending on context. See the individual commands for more information."
12681 (interactive "P")
12682 (cond
12683 ((org-at-timestamp-p t)
12684 (call-interactively (if org-edit-timestamp-down-means-later
12685 'org-timestamp-up 'org-timestamp-down)))
12686 ((org-on-heading-p) (call-interactively 'org-priority-down))
12687 ((org-clocktable-try-shift 'down arg))
12688 (t (call-interactively 'org-next-item))))
12690 (defun org-shiftright (&optional arg)
12691 "Cycle the thing at point or in the current line, depending on context.
12692 Depending on context, this does one of the following:
12694 - switch a timestamp at point one day into the future
12695 - on a headline, switch to the next TODO keyword.
12696 - on an item, switch entire list to the next bullet type
12697 - on a property line, switch to the next allowed value
12698 - on a clocktable definition line, move time block into the future"
12699 (interactive "P")
12700 (cond
12701 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12702 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12703 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12704 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12705 ((org-clocktable-try-shift 'right arg))
12706 (t (org-shiftcursor-error))))
12708 (defun org-shiftleft (&optional arg)
12709 "Cycle the thing at point or in the current line, depending on context.
12710 Depending on context, this does one of the following:
12712 - switch a timestamp at point one day into the past
12713 - on a headline, switch to the previous TODO keyword.
12714 - on an item, switch entire list to the previous bullet type
12715 - on a property line, switch to the previous allowed value
12716 - on a clocktable definition line, move time block into the past"
12717 (interactive "P")
12718 (cond
12719 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12720 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12721 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12722 ((org-at-property-p)
12723 (call-interactively 'org-property-previous-allowed-value))
12724 ((org-clocktable-try-shift 'left arg))
12725 (t (org-shiftcursor-error))))
12727 (defun org-shiftcontrolright ()
12728 "Switch to next TODO set."
12729 (interactive)
12730 (cond
12731 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12732 (t (org-shiftcursor-error))))
12734 (defun org-shiftcontrolleft ()
12735 "Switch to previous TODO set."
12736 (interactive)
12737 (cond
12738 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12739 (t (org-shiftcursor-error))))
12741 (defun org-ctrl-c-ret ()
12742 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12743 (interactive)
12744 (cond
12745 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12746 (t (call-interactively 'org-insert-heading))))
12748 (defun org-copy-special ()
12749 "Copy region in table or copy current subtree.
12750 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12751 See the individual commands for more information."
12752 (interactive)
12753 (call-interactively
12754 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12756 (defun org-cut-special ()
12757 "Cut region in table or cut current subtree.
12758 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12759 See the individual commands for more information."
12760 (interactive)
12761 (call-interactively
12762 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12764 (defun org-paste-special (arg)
12765 "Paste rectangular region into table, or past subtree relative to level.
12766 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12767 See the individual commands for more information."
12768 (interactive "P")
12769 (if (org-at-table-p)
12770 (org-table-paste-rectangle)
12771 (org-paste-subtree arg)))
12773 (defun org-edit-special ()
12774 "Call a special editor for the stuff at point.
12775 When at a table, call the formula editor with `org-table-edit-formulas'.
12776 When at the first line of an src example, call `org-edit-src-code'.
12777 When in an #+include line, visit the include file. Otherwise call
12778 `ffap' to visit the file at point."
12779 (interactive)
12780 (cond
12781 ((org-at-table-p)
12782 (call-interactively 'org-table-edit-formulas))
12783 ((save-excursion
12784 (beginning-of-line 1)
12785 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12786 (find-file (org-trim (match-string 1))))
12787 ((org-edit-src-code))
12788 ((org-edit-fixed-width-region))
12789 (t (call-interactively 'ffap))))
12791 (defun org-ctrl-c-ctrl-c (&optional arg)
12792 "Set tags in headline, or update according to changed information at point.
12794 This command does many different things, depending on context:
12796 - If the cursor is in a headline, prompt for tags and insert them
12797 into the current line, aligned to `org-tags-column'. When called
12798 with prefix arg, realign all tags in the current buffer.
12800 - If the cursor is in one of the special #+KEYWORD lines, this
12801 triggers scanning the buffer for these lines and updating the
12802 information.
12804 - If the cursor is inside a table, realign the table. This command
12805 works even if the automatic table editor has been turned off.
12807 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12808 the entire table.
12810 - If the cursor is a the beginning of a dynamic block, update it.
12812 - If the cursor is inside a table created by the table.el package,
12813 activate that table.
12815 - If the current buffer is a remember buffer, close note and file
12816 it. A prefix argument of 1 files to the default location
12817 without further interaction. A prefix argument of 2 files to
12818 the currently clocking task.
12820 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12821 links in this buffer.
12823 - If the cursor is on a numbered item in a plain list, renumber the
12824 ordered list.
12826 - If the cursor is on a checkbox, toggle it."
12827 (interactive "P")
12828 (let ((org-enable-table-editor t))
12829 (cond
12830 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12831 org-occur-highlights
12832 org-latex-fragment-image-overlays)
12833 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12834 (org-remove-occur-highlights)
12835 (org-remove-latex-fragment-image-overlays)
12836 (message "Temporary highlights/overlays removed from current buffer"))
12837 ((and (local-variable-p 'org-finish-function (current-buffer))
12838 (fboundp org-finish-function))
12839 (funcall org-finish-function))
12840 ((org-at-property-p)
12841 (call-interactively 'org-property-action))
12842 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12843 ((org-on-heading-p) (call-interactively 'org-set-tags))
12844 ((org-at-table.el-p)
12845 (require 'table)
12846 (beginning-of-line 1)
12847 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12848 (call-interactively 'table-recognize-table))
12849 ((org-at-table-p)
12850 (org-table-maybe-eval-formula)
12851 (if arg
12852 (call-interactively 'org-table-recalculate)
12853 (org-table-maybe-recalculate-line))
12854 (call-interactively 'org-table-align))
12855 ((org-at-item-checkbox-p)
12856 (call-interactively 'org-toggle-checkbox))
12857 ((org-at-item-p)
12858 (call-interactively 'org-maybe-renumber-ordered-list))
12859 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12860 ;; Dynamic block
12861 (beginning-of-line 1)
12862 (save-excursion (org-update-dblock)))
12863 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12864 (cond
12865 ((equal (match-string 1) "TBLFM")
12866 ;; Recalculate the table before this line
12867 (save-excursion
12868 (beginning-of-line 1)
12869 (skip-chars-backward " \r\n\t")
12870 (if (org-at-table-p)
12871 (org-call-with-arg 'org-table-recalculate t))))
12873 ; (org-set-regexps-and-options)
12874 ; (org-restart-font-lock)
12875 (let ((org-inhibit-startup t)) (org-mode-restart))
12876 (message "Local setup has been refreshed"))))
12877 (t (error "C-c C-c can do nothing useful at this location.")))))
12879 (defun org-mode-restart ()
12880 "Restart Org-mode, to scan again for special lines.
12881 Also updates the keyword regular expressions."
12882 (interactive)
12883 (org-mode)
12884 (message "Org-mode restarted"))
12886 (defun org-kill-note-or-show-branches ()
12887 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12888 (interactive)
12889 (if (not org-finish-function)
12890 (call-interactively 'show-branches)
12891 (let ((org-note-abort t))
12892 (funcall org-finish-function))))
12894 (defun org-return (&optional indent)
12895 "Goto next table row or insert a newline.
12896 Calls `org-table-next-row' or `newline', depending on context.
12897 See the individual commands for more information."
12898 (interactive)
12899 (cond
12900 ((bobp) (if indent (newline-and-indent) (newline)))
12901 ((and (org-at-heading-p)
12902 (looking-at
12903 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12904 (org-show-entry)
12905 (end-of-line 1)
12906 (newline))
12907 ((org-at-table-p)
12908 (org-table-justify-field-maybe)
12909 (call-interactively 'org-table-next-row))
12910 (t (if indent (newline-and-indent) (newline)))))
12912 (defun org-return-indent ()
12913 "Goto next table row or insert a newline and indent.
12914 Calls `org-table-next-row' or `newline-and-indent', depending on
12915 context. See the individual commands for more information."
12916 (interactive)
12917 (org-return t))
12919 (defun org-ctrl-c-star ()
12920 "Compute table, or change heading status of lines.
12921 Calls `org-table-recalculate' or `org-toggle-region-headings',
12922 depending on context. This will also turn a plain list item or a normal
12923 line into a subheading."
12924 (interactive)
12925 (cond
12926 ((org-at-table-p)
12927 (call-interactively 'org-table-recalculate))
12928 ((org-region-active-p)
12929 ;; Convert all lines in region to list items
12930 (call-interactively 'org-toggle-region-headings))
12931 ((org-on-heading-p)
12932 (org-toggle-region-headings (point-at-bol)
12933 (min (1+ (point-at-eol)) (point-max))))
12934 ((org-at-item-p)
12935 ;; Convert to heading
12936 (let ((level (save-match-data
12937 (save-excursion
12938 (condition-case nil
12939 (progn
12940 (org-back-to-heading t)
12941 (funcall outline-level))
12942 (error 0))))))
12943 (replace-match
12944 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12945 (t (org-toggle-region-headings (point-at-bol)
12946 (min (1+ (point-at-eol)) (point-max))))))
12948 (defun org-ctrl-c-minus ()
12949 "Insert separator line in table or modify bullet status of line.
12950 Also turns a plain line or a region of lines into list items.
12951 Calls `org-table-insert-hline', `org-toggle-region-items', or
12952 `org-cycle-list-bullet', depending on context."
12953 (interactive)
12954 (cond
12955 ((org-at-table-p)
12956 (call-interactively 'org-table-insert-hline))
12957 ((org-on-heading-p)
12958 ;; Convert to item
12959 (save-excursion
12960 (beginning-of-line 1)
12961 (if (looking-at "\\*+ ")
12962 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12963 ((org-region-active-p)
12964 ;; Convert all lines in region to list items
12965 (call-interactively 'org-toggle-region-items))
12966 ((org-in-item-p)
12967 (call-interactively 'org-cycle-list-bullet))
12968 (t (org-toggle-region-items (point-at-bol)
12969 (min (1+ (point-at-eol)) (point-max))))))
12971 (defun org-toggle-region-items (beg end)
12972 "Convert all lines in region to list items.
12973 If the first line is already an item, convert all list items in the region
12974 to normal lines."
12975 (interactive "r")
12976 (let (l2 l)
12977 (save-excursion
12978 (goto-char end)
12979 (setq l2 (org-current-line))
12980 (goto-char beg)
12981 (beginning-of-line 1)
12982 (setq l (1- (org-current-line)))
12983 (if (org-at-item-p)
12984 ;; We already have items, de-itemize
12985 (while (< (setq l (1+ l)) l2)
12986 (when (org-at-item-p)
12987 (goto-char (match-beginning 2))
12988 (delete-region (match-beginning 2) (match-end 2))
12989 (and (looking-at "[ \t]+") (replace-match "")))
12990 (beginning-of-line 2))
12991 (while (< (setq l (1+ l)) l2)
12992 (unless (org-at-item-p)
12993 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12994 (replace-match "\\1- \\2")))
12995 (beginning-of-line 2))))))
12997 (defun org-toggle-region-headings (beg end)
12998 "Convert all lines in region to list items.
12999 If the first line is already an item, convert all list items in the region
13000 to normal lines."
13001 (interactive "r")
13002 (let (l2 l)
13003 (save-excursion
13004 (goto-char end)
13005 (setq l2 (org-current-line))
13006 (goto-char beg)
13007 (beginning-of-line 1)
13008 (setq l (1- (org-current-line)))
13009 (if (org-on-heading-p)
13010 ;; We already have headlines, de-star them
13011 (while (< (setq l (1+ l)) l2)
13012 (when (org-on-heading-p t)
13013 (and (looking-at outline-regexp) (replace-match "")))
13014 (beginning-of-line 2))
13015 (let* ((stars (save-excursion
13016 (re-search-backward org-complex-heading-regexp nil t)
13017 (or (match-string 1) "*")))
13018 (add-stars (if org-odd-levels-only "**" "*"))
13019 (rpl (concat stars add-stars " \\2")))
13020 (while (< (setq l (1+ l)) l2)
13021 (unless (org-on-heading-p)
13022 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13023 (replace-match rpl)))
13024 (beginning-of-line 2)))))))
13026 (defun org-meta-return (&optional arg)
13027 "Insert a new heading or wrap a region in a table.
13028 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13029 See the individual commands for more information."
13030 (interactive "P")
13031 (cond
13032 ((org-at-table-p)
13033 (call-interactively 'org-table-wrap-region))
13034 (t (call-interactively 'org-insert-heading))))
13036 ;;; Menu entries
13038 ;; Define the Org-mode menus
13039 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13040 '("Tbl"
13041 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13042 ["Next Field" org-cycle (org-at-table-p)]
13043 ["Previous Field" org-shifttab (org-at-table-p)]
13044 ["Next Row" org-return (org-at-table-p)]
13045 "--"
13046 ["Blank Field" org-table-blank-field (org-at-table-p)]
13047 ["Edit Field" org-table-edit-field (org-at-table-p)]
13048 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13049 "--"
13050 ("Column"
13051 ["Move Column Left" org-metaleft (org-at-table-p)]
13052 ["Move Column Right" org-metaright (org-at-table-p)]
13053 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13054 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13055 ("Row"
13056 ["Move Row Up" org-metaup (org-at-table-p)]
13057 ["Move Row Down" org-metadown (org-at-table-p)]
13058 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13059 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13060 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13061 "--"
13062 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13063 ("Rectangle"
13064 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13065 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13066 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13067 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13068 "--"
13069 ("Calculate"
13070 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13071 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13072 ["Edit Formulas" org-edit-special (org-at-table-p)]
13073 "--"
13074 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13075 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13076 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13077 "--"
13078 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13079 "--"
13080 ["Sum Column/Rectangle" org-table-sum
13081 (or (org-at-table-p) (org-region-active-p))]
13082 ["Which Column?" org-table-current-column (org-at-table-p)])
13083 ["Debug Formulas"
13084 org-table-toggle-formula-debugger
13085 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13086 ["Show Col/Row Numbers"
13087 org-table-toggle-coordinate-overlays
13088 :style toggle
13089 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13090 "--"
13091 ["Create" org-table-create (and (not (org-at-table-p))
13092 org-enable-table-editor)]
13093 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13094 ["Import from File" org-table-import (not (org-at-table-p))]
13095 ["Export to File" org-table-export (org-at-table-p)]
13096 "--"
13097 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13099 (easy-menu-define org-org-menu org-mode-map "Org menu"
13100 '("Org"
13101 ("Show/Hide"
13102 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13103 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13104 ["Sparse Tree..." org-sparse-tree t]
13105 ["Reveal Context" org-reveal t]
13106 ["Show All" show-all t]
13107 "--"
13108 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13109 "--"
13110 ["New Heading" org-insert-heading t]
13111 ("Navigate Headings"
13112 ["Up" outline-up-heading t]
13113 ["Next" outline-next-visible-heading t]
13114 ["Previous" outline-previous-visible-heading t]
13115 ["Next Same Level" outline-forward-same-level t]
13116 ["Previous Same Level" outline-backward-same-level t]
13117 "--"
13118 ["Jump" org-goto t])
13119 ("Edit Structure"
13120 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13121 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13122 "--"
13123 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13124 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13125 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13126 "--"
13127 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13128 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13129 ["Demote Heading" org-metaright (not (org-at-table-p))]
13130 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13131 "--"
13132 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13133 "--"
13134 ["Convert to odd levels" org-convert-to-odd-levels t]
13135 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13136 ("Editing"
13137 ["Emphasis..." org-emphasize t]
13138 ["Edit Source Example" org-edit-special t])
13139 ("Archive"
13140 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13141 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13142 ; :active t :keys "C-u C-c C-x C-a"]
13143 ["Sparse trees open ARCHIVE trees"
13144 (setq org-sparse-tree-open-archived-trees
13145 (not org-sparse-tree-open-archived-trees))
13146 :style toggle :selected org-sparse-tree-open-archived-trees]
13147 ["Cycling opens ARCHIVE trees"
13148 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13149 :style toggle :selected org-cycle-open-archived-trees]
13150 "--"
13151 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13152 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13153 ; ["Check and Move Children" (org-archive-subtree '(4))
13154 ; :active t :keys "C-u C-c C-x C-s"]
13156 "--"
13157 ("TODO Lists"
13158 ["TODO/DONE/-" org-todo t]
13159 ("Select keyword"
13160 ["Next keyword" org-shiftright (org-on-heading-p)]
13161 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13162 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13163 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13164 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13165 ["Show TODO Tree" org-show-todo-tree t]
13166 ["Global TODO list" org-todo-list t]
13167 "--"
13168 ["Set Priority" org-priority t]
13169 ["Priority Up" org-shiftup t]
13170 ["Priority Down" org-shiftdown t])
13171 ("TAGS and Properties"
13172 ["Set Tags" 'org-set-tags-command t]
13173 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13174 "--"
13175 ["Set property" 'org-set-property t]
13176 ["Column view of properties" org-columns t]
13177 ["Insert Column View DBlock" org-insert-columns-dblock t])
13178 ("Dates and Scheduling"
13179 ["Timestamp" org-time-stamp t]
13180 ["Timestamp (inactive)" org-time-stamp-inactive t]
13181 ("Change Date"
13182 ["1 Day Later" org-shiftright t]
13183 ["1 Day Earlier" org-shiftleft t]
13184 ["1 ... Later" org-shiftup t]
13185 ["1 ... Earlier" org-shiftdown t])
13186 ["Compute Time Range" org-evaluate-time-range t]
13187 ["Schedule Item" org-schedule t]
13188 ["Deadline" org-deadline t]
13189 "--"
13190 ["Custom time format" org-toggle-time-stamp-overlays
13191 :style radio :selected org-display-custom-times]
13192 "--"
13193 ["Goto Calendar" org-goto-calendar t]
13194 ["Date from Calendar" org-date-from-calendar t])
13195 ("Logging work"
13196 ["Clock in" org-clock-in t]
13197 ["Clock out" org-clock-out t]
13198 ["Clock cancel" org-clock-cancel t]
13199 ["Goto running clock" org-clock-goto t]
13200 ["Display times" org-clock-display t]
13201 ["Create clock table" org-clock-report t]
13202 "--"
13203 ["Record DONE time"
13204 (progn (setq org-log-done (not org-log-done))
13205 (message "Switching to %s will %s record a timestamp"
13206 (car org-done-keywords)
13207 (if org-log-done "automatically" "not")))
13208 :style toggle :selected org-log-done])
13209 "--"
13210 ["Agenda Command..." org-agenda t]
13211 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13212 ("File List for Agenda")
13213 ("Special views current file"
13214 ["TODO Tree" org-show-todo-tree t]
13215 ["Check Deadlines" org-check-deadlines t]
13216 ["Timeline" org-timeline t]
13217 ["Tags Tree" org-tags-sparse-tree t])
13218 "--"
13219 ("Hyperlinks"
13220 ["Store Link (Global)" org-store-link t]
13221 ["Insert Link" org-insert-link t]
13222 ["Follow Link" org-open-at-point t]
13223 "--"
13224 ["Next link" org-next-link t]
13225 ["Previous link" org-previous-link t]
13226 "--"
13227 ["Descriptive Links"
13228 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13229 :style radio
13230 :selected (member '(org-link) buffer-invisibility-spec)]
13231 ["Literal Links"
13232 (progn
13233 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13234 :style radio
13235 :selected (not (member '(org-link) buffer-invisibility-spec))])
13236 "--"
13237 ["Export/Publish..." org-export t]
13238 ("LaTeX"
13239 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13240 :selected org-cdlatex-mode]
13241 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13242 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13243 ["Modify math symbol" org-cdlatex-math-modify
13244 (org-inside-LaTeX-fragment-p)]
13245 ["Export LaTeX fragments as images"
13246 (if (featurep 'org-exp)
13247 (setq org-export-with-LaTeX-fragments
13248 (not org-export-with-LaTeX-fragments))
13249 (require 'org-exp))
13250 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13251 org-export-with-LaTeX-fragments)])
13252 "--"
13253 ("Documentation"
13254 ["Show Version" org-version t]
13255 ["Info Documentation" org-info t])
13256 ("Customize"
13257 ["Browse Org Group" org-customize t]
13258 "--"
13259 ["Expand This Menu" org-create-customize-menu
13260 (fboundp 'customize-menu-create)])
13261 "--"
13262 ["Refresh setup" org-mode-restart t]
13265 (defun org-info (&optional node)
13266 "Read documentation for Org-mode in the info system.
13267 With optional NODE, go directly to that node."
13268 (interactive)
13269 (info (format "(org)%s" (or node ""))))
13271 (defun org-install-agenda-files-menu ()
13272 (let ((bl (buffer-list)))
13273 (save-excursion
13274 (while bl
13275 (set-buffer (pop bl))
13276 (if (org-mode-p) (setq bl nil)))
13277 (when (org-mode-p)
13278 (easy-menu-change
13279 '("Org") "File List for Agenda"
13280 (append
13281 (list
13282 ["Edit File List" (org-edit-agenda-file-list) t]
13283 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13284 ["Remove Current File from List" org-remove-file t]
13285 ["Cycle through agenda files" org-cycle-agenda-files t]
13286 ["Occur in all agenda files" org-occur-in-agenda-files t]
13287 "--")
13288 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13290 ;;;; Documentation
13292 ;;;###autoload
13293 (defun org-require-autoloaded-modules ()
13294 (interactive)
13295 (mapc 'require
13296 '(org-agenda org-archive org-clock org-colview
13297 org-exp org-id org-export-latex org-publish
13298 org-remember org-table)))
13300 ;;;###autoload
13301 (defun org-customize ()
13302 "Call the customize function with org as argument."
13303 (interactive)
13304 (org-load-modules-maybe)
13305 (org-require-autoloaded-modules)
13306 (customize-browse 'org))
13308 (defun org-create-customize-menu ()
13309 "Create a full customization menu for Org-mode, insert it into the menu."
13310 (interactive)
13311 (org-load-modules-maybe)
13312 (org-require-autoloaded-modules)
13313 (if (fboundp 'customize-menu-create)
13314 (progn
13315 (easy-menu-change
13316 '("Org") "Customize"
13317 `(["Browse Org group" org-customize t]
13318 "--"
13319 ,(customize-menu-create 'org)
13320 ["Set" Custom-set t]
13321 ["Save" Custom-save t]
13322 ["Reset to Current" Custom-reset-current t]
13323 ["Reset to Saved" Custom-reset-saved t]
13324 ["Reset to Standard Settings" Custom-reset-standard t]))
13325 (message "\"Org\"-menu now contains full customization menu"))
13326 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13328 ;;;; Miscellaneous stuff
13330 ;;; Generally useful functions
13332 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13333 "Display the given MESSAGE as a warning."
13334 (if (fboundp 'display-warning)
13335 (display-warning 'org message
13336 (if (featurep 'xemacs)
13337 'warning
13338 :warning))
13339 (let ((buf (get-buffer-create "*Org warnings*")))
13340 (with-current-buffer buf
13341 (goto-char (point-max))
13342 (insert "Warning (Org): " message)
13343 (unless (bolp)
13344 (newline)))
13345 (display-buffer buf)
13346 (sit-for 0))))
13348 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13349 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13350 (if (and marker (marker-buffer marker)
13351 (buffer-live-p (marker-buffer marker)))
13352 (progn
13353 (switch-to-buffer (marker-buffer marker))
13354 (if (or (> marker (point-max)) (< marker (point-min)))
13355 (widen))
13356 (goto-char marker))
13357 (if bookmark
13358 (bookmark-jump bookmark)
13359 (error "Cannot find location"))))
13361 (defun org-quote-csv-field (s)
13362 "Quote field for inclusion in CSV material."
13363 (if (string-match "[\",]" s)
13364 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13367 (defun org-plist-delete (plist property)
13368 "Delete PROPERTY from PLIST.
13369 This is in contrast to merely setting it to 0."
13370 (let (p)
13371 (while plist
13372 (if (not (eq property (car plist)))
13373 (setq p (plist-put p (car plist) (nth 1 plist))))
13374 (setq plist (cddr plist)))
13377 (defun org-force-self-insert (N)
13378 "Needed to enforce self-insert under remapping."
13379 (interactive "p")
13380 (self-insert-command N))
13382 (defun org-string-width (s)
13383 "Compute width of string, ignoring invisible characters.
13384 This ignores character with invisibility property `org-link', and also
13385 characters with property `org-cwidth', because these will become invisible
13386 upon the next fontification round."
13387 (let (b l)
13388 (when (or (eq t buffer-invisibility-spec)
13389 (assq 'org-link buffer-invisibility-spec))
13390 (while (setq b (text-property-any 0 (length s)
13391 'invisible 'org-link s))
13392 (setq s (concat (substring s 0 b)
13393 (substring s (or (next-single-property-change
13394 b 'invisible s) (length s)))))))
13395 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13396 (setq s (concat (substring s 0 b)
13397 (substring s (or (next-single-property-change
13398 b 'org-cwidth s) (length s))))))
13399 (setq l (string-width s) b -1)
13400 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13401 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13404 (defun org-get-indentation (&optional line)
13405 "Get the indentation of the current line, interpreting tabs.
13406 When LINE is given, assume it represents a line and compute its indentation."
13407 (if line
13408 (if (string-match "^ *" (org-remove-tabs line))
13409 (match-end 0))
13410 (save-excursion
13411 (beginning-of-line 1)
13412 (skip-chars-forward " \t")
13413 (current-column))))
13415 (defun org-remove-tabs (s &optional width)
13416 "Replace tabulators in S with spaces.
13417 Assumes that s is a single line, starting in column 0."
13418 (setq width (or width tab-width))
13419 (while (string-match "\t" s)
13420 (setq s (replace-match
13421 (make-string
13422 (- (* width (/ (+ (match-beginning 0) width) width))
13423 (match-beginning 0)) ?\ )
13424 t t s)))
13427 (defun org-fix-indentation (line ind)
13428 "Fix indentation in LINE.
13429 IND is a cons cell with target and minimum indentation.
13430 If the current indenation in LINE is smaller than the minimum,
13431 leave it alone. If it is larger than ind, set it to the target."
13432 (let* ((l (org-remove-tabs line))
13433 (i (org-get-indentation l))
13434 (i1 (car ind)) (i2 (cdr ind)))
13435 (if (>= i i2) (setq l (substring line i2)))
13436 (if (> i1 0)
13437 (concat (make-string i1 ?\ ) l)
13438 l)))
13440 (defun org-base-buffer (buffer)
13441 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13442 (if (not buffer)
13443 buffer
13444 (or (buffer-base-buffer buffer)
13445 buffer)))
13447 (defun org-trim (s)
13448 "Remove whitespace at beginning and end of string."
13449 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13450 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13453 (defun org-wrap (string &optional width lines)
13454 "Wrap string to either a number of lines, or a width in characters.
13455 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13456 that costs. If there is a word longer than WIDTH, the text is actually
13457 wrapped to the length of that word.
13458 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13459 many lines, whatever width that takes.
13460 The return value is a list of lines, without newlines at the end."
13461 (let* ((words (org-split-string string "[ \t\n]+"))
13462 (maxword (apply 'max (mapcar 'org-string-width words)))
13463 w ll)
13464 (cond (width
13465 (org-do-wrap words (max maxword width)))
13466 (lines
13467 (setq w maxword)
13468 (setq ll (org-do-wrap words maxword))
13469 (if (<= (length ll) lines)
13471 (setq ll words)
13472 (while (> (length ll) lines)
13473 (setq w (1+ w))
13474 (setq ll (org-do-wrap words w)))
13475 ll))
13476 (t (error "Cannot wrap this")))))
13478 (defun org-do-wrap (words width)
13479 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13480 (let (lines line)
13481 (while words
13482 (setq line (pop words))
13483 (while (and words (< (+ (length line) (length (car words))) width))
13484 (setq line (concat line " " (pop words))))
13485 (setq lines (push line lines)))
13486 (nreverse lines)))
13488 (defun org-split-string (string &optional separators)
13489 "Splits STRING into substrings at SEPARATORS.
13490 No empty strings are returned if there are matches at the beginning
13491 and end of string."
13492 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13493 (start 0)
13494 notfirst
13495 (list nil))
13496 (while (and (string-match rexp string
13497 (if (and notfirst
13498 (= start (match-beginning 0))
13499 (< start (length string)))
13500 (1+ start) start))
13501 (< (match-beginning 0) (length string)))
13502 (setq notfirst t)
13503 (or (eq (match-beginning 0) 0)
13504 (and (eq (match-beginning 0) (match-end 0))
13505 (eq (match-beginning 0) start))
13506 (setq list
13507 (cons (substring string start (match-beginning 0))
13508 list)))
13509 (setq start (match-end 0)))
13510 (or (eq start (length string))
13511 (setq list
13512 (cons (substring string start)
13513 list)))
13514 (nreverse list)))
13516 (defun org-context ()
13517 "Return a list of contexts of the current cursor position.
13518 If several contexts apply, all are returned.
13519 Each context entry is a list with a symbol naming the context, and
13520 two positions indicating start and end of the context. Possible
13521 contexts are:
13523 :headline anywhere in a headline
13524 :headline-stars on the leading stars in a headline
13525 :todo-keyword on a TODO keyword (including DONE) in a headline
13526 :tags on the TAGS in a headline
13527 :priority on the priority cookie in a headline
13528 :item on the first line of a plain list item
13529 :item-bullet on the bullet/number of a plain list item
13530 :checkbox on the checkbox in a plain list item
13531 :table in an org-mode table
13532 :table-special on a special filed in a table
13533 :table-table in a table.el table
13534 :link on a hyperlink
13535 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13536 :target on a <<target>>
13537 :radio-target on a <<<radio-target>>>
13538 :latex-fragment on a LaTeX fragment
13539 :latex-preview on a LaTeX fragment with overlayed preview image
13541 This function expects the position to be visible because it uses font-lock
13542 faces as a help to recognize the following contexts: :table-special, :link,
13543 and :keyword."
13544 (let* ((f (get-text-property (point) 'face))
13545 (faces (if (listp f) f (list f)))
13546 (p (point)) clist o)
13547 ;; First the large context
13548 (cond
13549 ((org-on-heading-p t)
13550 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13551 (when (progn
13552 (beginning-of-line 1)
13553 (looking-at org-todo-line-tags-regexp))
13554 (push (org-point-in-group p 1 :headline-stars) clist)
13555 (push (org-point-in-group p 2 :todo-keyword) clist)
13556 (push (org-point-in-group p 4 :tags) clist))
13557 (goto-char p)
13558 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13559 (if (looking-at "\\[#[A-Z0-9]\\]")
13560 (push (org-point-in-group p 0 :priority) clist)))
13562 ((org-at-item-p)
13563 (push (org-point-in-group p 2 :item-bullet) clist)
13564 (push (list :item (point-at-bol)
13565 (save-excursion (org-end-of-item) (point)))
13566 clist)
13567 (and (org-at-item-checkbox-p)
13568 (push (org-point-in-group p 0 :checkbox) clist)))
13570 ((org-at-table-p)
13571 (push (list :table (org-table-begin) (org-table-end)) clist)
13572 (if (memq 'org-formula faces)
13573 (push (list :table-special
13574 (previous-single-property-change p 'face)
13575 (next-single-property-change p 'face)) clist)))
13576 ((org-at-table-p 'any)
13577 (push (list :table-table) clist)))
13578 (goto-char p)
13580 ;; Now the small context
13581 (cond
13582 ((org-at-timestamp-p)
13583 (push (org-point-in-group p 0 :timestamp) clist))
13584 ((memq 'org-link faces)
13585 (push (list :link
13586 (previous-single-property-change p 'face)
13587 (next-single-property-change p 'face)) clist))
13588 ((memq 'org-special-keyword faces)
13589 (push (list :keyword
13590 (previous-single-property-change p 'face)
13591 (next-single-property-change p 'face)) clist))
13592 ((org-on-target-p)
13593 (push (org-point-in-group p 0 :target) clist)
13594 (goto-char (1- (match-beginning 0)))
13595 (if (looking-at org-radio-target-regexp)
13596 (push (org-point-in-group p 0 :radio-target) clist))
13597 (goto-char p))
13598 ((setq o (car (delq nil
13599 (mapcar
13600 (lambda (x)
13601 (if (memq x org-latex-fragment-image-overlays) x))
13602 (org-overlays-at (point))))))
13603 (push (list :latex-fragment
13604 (org-overlay-start o) (org-overlay-end o)) clist)
13605 (push (list :latex-preview
13606 (org-overlay-start o) (org-overlay-end o)) clist))
13607 ((org-inside-LaTeX-fragment-p)
13608 ;; FIXME: positions wrong.
13609 (push (list :latex-fragment (point) (point)) clist)))
13611 (setq clist (nreverse (delq nil clist)))
13612 clist))
13614 ;; FIXME: Compare with at-regexp-p Do we need both?
13615 (defun org-in-regexp (re &optional nlines visually)
13616 "Check if point is inside a match of regexp.
13617 Normally only the current line is checked, but you can include NLINES extra
13618 lines both before and after point into the search.
13619 If VISUALLY is set, require that the cursor is not after the match but
13620 really on, so that the block visually is on the match."
13621 (catch 'exit
13622 (let ((pos (point))
13623 (eol (point-at-eol (+ 1 (or nlines 0))))
13624 (inc (if visually 1 0)))
13625 (save-excursion
13626 (beginning-of-line (- 1 (or nlines 0)))
13627 (while (re-search-forward re eol t)
13628 (if (and (<= (match-beginning 0) pos)
13629 (>= (+ inc (match-end 0)) pos))
13630 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13632 (defun org-at-regexp-p (regexp)
13633 "Is point inside a match of REGEXP in the current line?"
13634 (catch 'exit
13635 (save-excursion
13636 (let ((pos (point)) (end (point-at-eol)))
13637 (beginning-of-line 1)
13638 (while (re-search-forward regexp end t)
13639 (if (and (<= (match-beginning 0) pos)
13640 (>= (match-end 0) pos))
13641 (throw 'exit t)))
13642 nil))))
13644 (defun org-occur-in-agenda-files (regexp &optional nlines)
13645 "Call `multi-occur' with buffers for all agenda files."
13646 (interactive "sOrg-files matching: \np")
13647 (let* ((files (org-agenda-files))
13648 (tnames (mapcar 'file-truename files))
13649 (extra org-agenda-text-search-extra-files)
13651 (when (eq (car extra) 'agenda-archives)
13652 (setq extra (cdr extra))
13653 (setq files (org-add-archive-files files)))
13654 (while (setq f (pop extra))
13655 (unless (member (file-truename f) tnames)
13656 (add-to-list 'files f 'append)
13657 (add-to-list 'tnames (file-truename f) 'append)))
13658 (multi-occur
13659 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13660 regexp)))
13662 (if (boundp 'occur-mode-find-occurrence-hook)
13663 ;; Emacs 23
13664 (add-hook 'occur-mode-find-occurrence-hook
13665 (lambda ()
13666 (when (org-mode-p)
13667 (org-reveal))))
13668 ;; Emacs 22
13669 (defadvice occur-mode-goto-occurrence
13670 (after org-occur-reveal activate)
13671 (and (org-mode-p) (org-reveal)))
13672 (defadvice occur-mode-goto-occurrence-other-window
13673 (after org-occur-reveal activate)
13674 (and (org-mode-p) (org-reveal)))
13675 (defadvice occur-mode-display-occurrence
13676 (after org-occur-reveal activate)
13677 (when (org-mode-p)
13678 (let ((pos (occur-mode-find-occurrence)))
13679 (with-current-buffer (marker-buffer pos)
13680 (save-excursion
13681 (goto-char pos)
13682 (org-reveal)))))))
13684 (defun org-uniquify (list)
13685 "Remove duplicate elements from LIST."
13686 (let (res)
13687 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13688 res))
13690 (defun org-delete-all (elts list)
13691 "Remove all elements in ELTS from LIST."
13692 (while elts
13693 (setq list (delete (pop elts) list)))
13694 list)
13696 (defun org-back-over-empty-lines ()
13697 "Move backwards over witespace, to the beginning of the first empty line.
13698 Returns the number of empty lines passed."
13699 (let ((pos (point)))
13700 (skip-chars-backward " \t\n\r")
13701 (beginning-of-line 2)
13702 (goto-char (min (point) pos))
13703 (count-lines (point) pos)))
13705 (defun org-skip-whitespace ()
13706 (skip-chars-forward " \t\n\r"))
13708 (defun org-point-in-group (point group &optional context)
13709 "Check if POINT is in match-group GROUP.
13710 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13711 match. If the match group does ot exist or point is not inside it,
13712 return nil."
13713 (and (match-beginning group)
13714 (>= point (match-beginning group))
13715 (<= point (match-end group))
13716 (if context
13717 (list context (match-beginning group) (match-end group))
13718 t)))
13720 (defun org-switch-to-buffer-other-window (&rest args)
13721 "Switch to buffer in a second window on the current frame.
13722 In particular, do not allow pop-up frames."
13723 (let (pop-up-frames special-display-buffer-names special-display-regexps
13724 special-display-function)
13725 (apply 'switch-to-buffer-other-window args)))
13727 (defun org-combine-plists (&rest plists)
13728 "Create a single property list from all plists in PLISTS.
13729 The process starts by copying the first list, and then setting properties
13730 from the other lists. Settings in the last list are the most significant
13731 ones and overrule settings in the other lists."
13732 (let ((rtn (copy-sequence (pop plists)))
13733 p v ls)
13734 (while plists
13735 (setq ls (pop plists))
13736 (while ls
13737 (setq p (pop ls) v (pop ls))
13738 (setq rtn (plist-put rtn p v))))
13739 rtn))
13741 (defun org-move-line-down (arg)
13742 "Move the current line down. With prefix argument, move it past ARG lines."
13743 (interactive "p")
13744 (let ((col (current-column))
13745 beg end pos)
13746 (beginning-of-line 1) (setq beg (point))
13747 (beginning-of-line 2) (setq end (point))
13748 (beginning-of-line (+ 1 arg))
13749 (setq pos (move-marker (make-marker) (point)))
13750 (insert (delete-and-extract-region beg end))
13751 (goto-char pos)
13752 (org-move-to-column col)))
13754 (defun org-move-line-up (arg)
13755 "Move the current line up. With prefix argument, move it past ARG lines."
13756 (interactive "p")
13757 (let ((col (current-column))
13758 beg end pos)
13759 (beginning-of-line 1) (setq beg (point))
13760 (beginning-of-line 2) (setq end (point))
13761 (beginning-of-line (- arg))
13762 (setq pos (move-marker (make-marker) (point)))
13763 (insert (delete-and-extract-region beg end))
13764 (goto-char pos)
13765 (org-move-to-column col)))
13767 (defun org-replace-escapes (string table)
13768 "Replace %-escapes in STRING with values in TABLE.
13769 TABLE is an association list with keys like \"%a\" and string values.
13770 The sequences in STRING may contain normal field width and padding information,
13771 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13772 so values can contain further %-escapes if they are define later in TABLE."
13773 (let ((case-fold-search nil)
13774 e re rpl)
13775 (while (setq e (pop table))
13776 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13777 (while (string-match re string)
13778 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13779 (cdr e)))
13780 (setq string (replace-match rpl t t string))))
13781 string))
13784 (defun org-sublist (list start end)
13785 "Return a section of LIST, from START to END.
13786 Counting starts at 1."
13787 (let (rtn (c start))
13788 (setq list (nthcdr (1- start) list))
13789 (while (and list (<= c end))
13790 (push (pop list) rtn)
13791 (setq c (1+ c)))
13792 (nreverse rtn)))
13794 (defun org-find-base-buffer-visiting (file)
13795 "Like `find-buffer-visiting' but alway return the base buffer and
13796 not an indirect buffer."
13797 (let ((buf (find-buffer-visiting file)))
13798 (if buf
13799 (or (buffer-base-buffer buf) buf)
13800 nil)))
13802 (defun org-image-file-name-regexp ()
13803 "Return regexp matching the file names of images."
13804 (if (fboundp 'image-file-name-regexp)
13805 (image-file-name-regexp)
13806 (let ((image-file-name-extensions
13807 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13808 "xbm" "xpm" "pbm" "pgm" "ppm")))
13809 (concat "\\."
13810 (regexp-opt (nconc (mapcar 'upcase
13811 image-file-name-extensions)
13812 image-file-name-extensions)
13814 "\\'"))))
13816 (defun org-file-image-p (file)
13817 "Return non-nil if FILE is an image."
13818 (save-match-data
13819 (string-match (org-image-file-name-regexp) file)))
13821 (defun org-get-cursor-date ()
13822 "Return the date at cursor in as a time.
13823 This works in the calendar and in the agenda, anywhere else it just
13824 returns the current time."
13825 (let (date day defd)
13826 (cond
13827 ((eq major-mode 'calendar-mode)
13828 (setq date (calendar-cursor-to-date)
13829 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13830 ((eq major-mode 'org-agenda-mode)
13831 (setq day (get-text-property (point) 'day))
13832 (if day
13833 (setq date (calendar-gregorian-from-absolute day)
13834 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13835 (nth 2 date))))))
13836 (or defd (current-time))))
13838 (defvar org-agenda-action-marker (make-marker)
13839 "Marker pointing to the entry for the next agenda action.")
13841 (defun org-mark-entry-for-agenda-action ()
13842 "Mark the current entry as target of an agenda action.
13843 Agenda actions are actions executed from the agenda with the key `k',
13844 which make use of the date at the cursor."
13845 (interactive)
13846 (move-marker org-agenda-action-marker
13847 (save-excursion (org-back-to-heading t) (point))
13848 (current-buffer))
13849 (message
13850 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13852 ;;; Paragraph filling stuff.
13853 ;; We want this to be just right, so use the full arsenal.
13855 (defun org-indent-line-function ()
13856 "Indent line like previous, but further if previous was headline or item."
13857 (interactive)
13858 (let* ((pos (point))
13859 (itemp (org-at-item-p))
13860 column bpos bcol tpos tcol bullet btype bullet-type)
13861 ;; Find the previous relevant line
13862 (beginning-of-line 1)
13863 (cond
13864 ((looking-at "#") (setq column 0))
13865 ((looking-at "\\*+ ") (setq column 0))
13867 (beginning-of-line 0)
13868 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13869 (beginning-of-line 0))
13870 (cond
13871 ((looking-at "\\*+[ \t]+")
13872 (if (not org-adapt-indentation)
13873 (setq column 0)
13874 (goto-char (match-end 0))
13875 (setq column (current-column))))
13876 ((org-in-item-p)
13877 (org-beginning-of-item)
13878 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13879 (setq bpos (match-beginning 1) tpos (match-end 0)
13880 bcol (progn (goto-char bpos) (current-column))
13881 tcol (progn (goto-char tpos) (current-column))
13882 bullet (match-string 1)
13883 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13884 (if (> tcol (+ bcol org-description-max-indent))
13885 (setq tcol (+ bcol 5)))
13886 (if (not itemp)
13887 (setq column tcol)
13888 (goto-char pos)
13889 (beginning-of-line 1)
13890 (if (looking-at "\\S-")
13891 (progn
13892 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13893 (setq bullet (match-string 1)
13894 btype (if (string-match "[0-9]" bullet) "n" bullet))
13895 (setq column (if (equal btype bullet-type) bcol tcol)))
13896 (setq column (org-get-indentation)))))
13897 (t (setq column (org-get-indentation))))))
13898 (goto-char pos)
13899 (if (<= (current-column) (current-indentation))
13900 (org-indent-line-to column)
13901 (save-excursion (org-indent-line-to column)))
13902 (setq column (current-column))
13903 (beginning-of-line 1)
13904 (if (looking-at
13905 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13906 (replace-match (concat "\\1" (format org-property-format
13907 (match-string 2) (match-string 3)))
13908 t nil))
13909 (org-move-to-column column)))
13911 (defun org-set-autofill-regexps ()
13912 (interactive)
13913 ;; In the paragraph separator we include headlines, because filling
13914 ;; text in a line directly attached to a headline would otherwise
13915 ;; fill the headline as well.
13916 (org-set-local 'comment-start-skip "^#+[ \t]*")
13917 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13918 ;; The paragraph starter includes hand-formatted lists.
13919 (org-set-local 'paragraph-start
13920 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13921 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13922 ;; But only if the user has not turned off tables or fixed-width regions
13923 (org-set-local
13924 'auto-fill-inhibit-regexp
13925 (concat "\\*+ \\|#\\+"
13926 "\\|[ \t]*" org-keyword-time-regexp
13927 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13928 (concat
13929 "\\|[ \t]*["
13930 (if org-enable-table-editor "|" "")
13931 (if org-enable-fixed-width-editor ":" "")
13932 "]"))))
13933 ;; We use our own fill-paragraph function, to make sure that tables
13934 ;; and fixed-width regions are not wrapped. That function will pass
13935 ;; through to `fill-paragraph' when appropriate.
13936 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13937 ; Adaptive filling: To get full control, first make sure that
13938 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13939 (org-set-local 'adaptive-fill-regexp "\000")
13940 (org-set-local 'adaptive-fill-function
13941 'org-adaptive-fill-function)
13942 (org-set-local
13943 'align-mode-rules-list
13944 '((org-in-buffer-settings
13945 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13946 (modes . '(org-mode))))))
13948 (defun org-fill-paragraph (&optional justify)
13949 "Re-align a table, pass through to fill-paragraph if no table."
13950 (let ((table-p (org-at-table-p))
13951 (table.el-p (org-at-table.el-p)))
13952 (cond ((and (equal (char-after (point-at-bol)) ?*)
13953 (save-excursion (goto-char (point-at-bol))
13954 (looking-at outline-regexp)))
13955 t) ; skip headlines
13956 (table.el-p t) ; skip table.el tables
13957 (table-p (org-table-align) t) ; align org-mode tables
13958 (t nil)))) ; call paragraph-fill
13960 ;; For reference, this is the default value of adaptive-fill-regexp
13961 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13963 (defun org-adaptive-fill-function ()
13964 "Return a fill prefix for org-mode files.
13965 In particular, this makes sure hanging paragraphs for hand-formatted lists
13966 work correctly."
13967 (cond ((looking-at "#[ \t]+")
13968 (match-string 0))
13969 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13970 (save-excursion
13971 (if (> (match-end 1) (+ (match-beginning 1)
13972 org-description-max-indent))
13973 (goto-char (+ (match-beginning 1) 5))
13974 (goto-char (match-end 0)))
13975 (make-string (current-column) ?\ )))
13976 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
13977 (save-excursion
13978 (goto-char (match-end 0))
13979 (make-string (current-column) ?\ )))
13980 (t nil)))
13982 ;;; Other stuff.
13984 (defun org-toggle-fixed-width-section (arg)
13985 "Toggle the fixed-width export.
13986 If there is no active region, the QUOTE keyword at the current headline is
13987 inserted or removed. When present, it causes the text between this headline
13988 and the next to be exported as fixed-width text, and unmodified.
13989 If there is an active region, this command adds or removes a colon as the
13990 first character of this line. If the first character of a line is a colon,
13991 this line is also exported in fixed-width font."
13992 (interactive "P")
13993 (let* ((cc 0)
13994 (regionp (org-region-active-p))
13995 (beg (if regionp (region-beginning) (point)))
13996 (end (if regionp (region-end)))
13997 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13998 (case-fold-search nil)
13999 (re "[ \t]*\\(:\\)")
14000 off)
14001 (if regionp
14002 (save-excursion
14003 (goto-char beg)
14004 (setq cc (current-column))
14005 (beginning-of-line 1)
14006 (setq off (looking-at re))
14007 (while (> nlines 0)
14008 (setq nlines (1- nlines))
14009 (beginning-of-line 1)
14010 (cond
14011 (arg
14012 (org-move-to-column cc t)
14013 (insert ":\n")
14014 (forward-line -1))
14015 ((and off (looking-at re))
14016 (replace-match "" t t nil 1))
14017 ((not off) (org-move-to-column cc t) (insert ":")))
14018 (forward-line 1)))
14019 (save-excursion
14020 (org-back-to-heading)
14021 (if (looking-at (concat outline-regexp
14022 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14023 (replace-match "" t t nil 1)
14024 (if (looking-at outline-regexp)
14025 (progn
14026 (goto-char (match-end 0))
14027 (insert org-quote-string " "))))))))
14029 ;;;; Functions extending outline functionality
14031 (defun org-beginning-of-line (&optional arg)
14032 "Go to the beginning of the current line. If that is invisible, continue
14033 to a visible line beginning. This makes the function of C-a more intuitive.
14034 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14035 first attempt, and only move to after the tags when the cursor is already
14036 beyond the end of the headline."
14037 (interactive "P")
14038 (let ((pos (point)) refpos)
14039 (beginning-of-line 1)
14040 (if (bobp)
14042 (backward-char 1)
14043 (if (org-invisible-p)
14044 (while (and (not (bobp)) (org-invisible-p))
14045 (backward-char 1)
14046 (beginning-of-line 1))
14047 (forward-char 1)))
14048 (when org-special-ctrl-a/e
14049 (cond
14050 ((and (looking-at org-complex-heading-regexp)
14051 (= (char-after (match-end 1)) ?\ ))
14052 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14053 (point-at-eol)))
14054 (goto-char
14055 (if (eq org-special-ctrl-a/e t)
14056 (cond ((> pos refpos) refpos)
14057 ((= pos (point)) refpos)
14058 (t (point)))
14059 (cond ((> pos (point)) (point))
14060 ((not (eq last-command this-command)) (point))
14061 (t refpos)))))
14062 ((org-at-item-p)
14063 (goto-char
14064 (if (eq org-special-ctrl-a/e t)
14065 (cond ((> pos (match-end 4)) (match-end 4))
14066 ((= pos (point)) (match-end 4))
14067 (t (point)))
14068 (cond ((> pos (point)) (point))
14069 ((not (eq last-command this-command)) (point))
14070 (t (match-end 4))))))))
14071 (org-no-warnings
14072 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14074 (defun org-end-of-line (&optional arg)
14075 "Go to the end of the line.
14076 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14077 first attempt, and only move to after the tags when the cursor is already
14078 beyond the end of the headline."
14079 (interactive "P")
14080 (if (or (not org-special-ctrl-a/e)
14081 (not (org-on-heading-p)))
14082 (end-of-line arg)
14083 (let ((pos (point)))
14084 (beginning-of-line 1)
14085 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14086 (if (eq org-special-ctrl-a/e t)
14087 (if (or (< pos (match-beginning 1))
14088 (= pos (match-end 0)))
14089 (goto-char (match-beginning 1))
14090 (goto-char (match-end 0)))
14091 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14092 (goto-char (match-end 0))
14093 (goto-char (match-beginning 1))))
14094 (end-of-line arg))))
14095 (org-no-warnings
14096 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14099 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14100 (define-key org-mode-map "\C-e" 'org-end-of-line)
14102 (defun org-kill-line (&optional arg)
14103 "Kill line, to tags or end of line."
14104 (interactive "P")
14105 (cond
14106 ((or (not org-special-ctrl-k)
14107 (bolp)
14108 (not (org-on-heading-p)))
14109 (call-interactively 'kill-line))
14110 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14111 (kill-region (point) (match-beginning 1))
14112 (org-set-tags nil t))
14113 (t (kill-region (point) (point-at-eol)))))
14115 (define-key org-mode-map "\C-k" 'org-kill-line)
14117 (defun org-yank (&optional arg)
14118 "Yank. If the kill is a subtree, treat it specially.
14119 This command will look at the current kill and check if is a single
14120 subtree, or a series of subtrees[1]. If it passes the test, and if the
14121 cursor is at the beginning of a line or after the stars of a currently
14122 empty headline, then the yank is handeled specially. How exactly depends
14123 on the value of the following variables, both set by default.
14125 org-yank-folded-subtrees
14126 When set, the subree(s) will be folded after insertion, but only
14127 if doing so would now swallow text after the yanked text.
14129 org-yank-adjusted-subtrees
14130 When set, the subtree will be promoted or demoted in order to
14131 fit into the local outline tree structure, which means that the level
14132 will be adjusted so that it becomes the smaller one of the two
14133 *visible* surrounding headings.
14135 Any prefix to this command will cause `yank' to be called directly with
14136 no special treatment. In particular, a simple `C-u' prefix will just
14137 plainly yank the text as it is.
14139 \[1] Basically, the test checks if the first non-white line is a heading
14140 and if there are no other headings with fewer stars."
14141 (interactive "P")
14142 (setq this-command 'yank)
14143 (if arg
14144 (call-interactively 'yank)
14145 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14146 (and (org-kill-is-subtree-p)
14147 (or (bolp)
14148 (and (looking-at "[ \t]*$")
14149 (string-match
14150 "\\`\\*+\\'"
14151 (buffer-substring (point-at-bol) (point)))))))
14152 swallowp)
14153 (cond
14154 ((and subtreep org-yank-folded-subtrees)
14155 (let ((beg (point))
14156 end)
14157 (if (and subtreep org-yank-adjusted-subtrees)
14158 (org-paste-subtree nil nil 'for-yank)
14159 (call-interactively 'yank))
14160 (setq end (point))
14161 (goto-char beg)
14162 (when (and (bolp) subtreep
14163 (not (setq swallowp
14164 (org-yank-folding-would-swallow-text beg end))))
14165 (or (looking-at outline-regexp)
14166 (re-search-forward (concat "^" outline-regexp) end t))
14167 (while (and (< (point) end) (looking-at outline-regexp))
14168 (hide-subtree)
14169 (org-cycle-show-empty-lines 'folded)
14170 (condition-case nil
14171 (outline-forward-same-level 1)
14172 (error (goto-char end)))))
14173 (when swallowp
14174 (message
14175 "Yanked text not folded because that would swallow text"))
14176 (goto-char end)
14177 (skip-chars-forward " \t\n\r")
14178 (beginning-of-line 1)
14179 (push-mark beg 'nomsg)))
14180 ((and subtreep org-yank-adjusted-subtrees)
14181 (let ((beg (point-at-bol)))
14182 (org-paste-subtree nil nil 'for-yank)
14183 (push-mark beg 'nomsg)))
14185 (call-interactively 'yank))))))
14187 (defun org-yank-folding-would-swallow-text (beg end)
14188 "Would hide-subtree at BEG swallow any text after END?"
14189 (let (level)
14190 (save-excursion
14191 (goto-char beg)
14192 (when (or (looking-at outline-regexp)
14193 (re-search-forward (concat "^" outline-regexp) end t))
14194 (setq level (org-outline-level)))
14195 (goto-char end)
14196 (skip-chars-forward " \t\r\n\v\f")
14197 (if (or (eobp)
14198 (and (bolp) (looking-at org-outline-regexp)
14199 (<= (org-outline-level) level)))
14200 nil ; Nothing would be swallowed
14201 t)))) ; something would swallow
14203 (define-key org-mode-map "\C-y" 'org-yank)
14205 (defun org-invisible-p ()
14206 "Check if point is at a character currently not visible."
14207 ;; Early versions of noutline don't have `outline-invisible-p'.
14208 (if (fboundp 'outline-invisible-p)
14209 (outline-invisible-p)
14210 (get-char-property (point) 'invisible)))
14212 (defun org-invisible-p2 ()
14213 "Check if point is at a character currently not visible."
14214 (save-excursion
14215 (if (and (eolp) (not (bobp))) (backward-char 1))
14216 ;; Early versions of noutline don't have `outline-invisible-p'.
14217 (if (fboundp 'outline-invisible-p)
14218 (outline-invisible-p)
14219 (get-char-property (point) 'invisible))))
14221 (defun org-back-to-heading (&optional invisible-ok)
14222 "Call `outline-back-to-heading', but provide a better error message."
14223 (condition-case nil
14224 (outline-back-to-heading invisible-ok)
14225 (error (error "Before first headline at position %d in buffer %s"
14226 (point) (current-buffer)))))
14228 (defalias 'org-on-heading-p 'outline-on-heading-p)
14229 (defalias 'org-at-heading-p 'outline-on-heading-p)
14230 (defun org-at-heading-or-item-p ()
14231 (or (org-on-heading-p) (org-at-item-p)))
14233 (defun org-on-target-p ()
14234 (or (org-in-regexp org-radio-target-regexp)
14235 (org-in-regexp org-target-regexp)))
14237 (defun org-up-heading-all (arg)
14238 "Move to the heading line of which the present line is a subheading.
14239 This function considers both visible and invisible heading lines.
14240 With argument, move up ARG levels."
14241 (if (fboundp 'outline-up-heading-all)
14242 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14243 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14245 (defun org-up-heading-safe ()
14246 "Move to the heading line of which the present line is a subheading.
14247 This version will not throw an error. It will return the level of the
14248 headline found, or nil if no higher level is found."
14249 (let ((pos (point)) start-level level
14250 (re (concat "^" outline-regexp)))
14251 (catch 'exit
14252 (org-back-to-heading t)
14253 (setq start-level (funcall outline-level))
14254 (if (equal start-level 1) (throw 'exit nil))
14255 (while (re-search-backward re nil t)
14256 (setq level (funcall outline-level))
14257 (if (< level start-level) (throw 'exit level)))
14258 nil)))
14260 (defun org-first-sibling-p ()
14261 "Is this heading the first child of its parents?"
14262 (interactive)
14263 (let ((re (concat "^" outline-regexp))
14264 level l)
14265 (unless (org-at-heading-p t)
14266 (error "Not at a heading"))
14267 (setq level (funcall outline-level))
14268 (save-excursion
14269 (if (not (re-search-backward re nil t))
14271 (setq l (funcall outline-level))
14272 (< l level)))))
14274 (defun org-goto-sibling (&optional previous)
14275 "Goto the next sibling, even if it is invisible.
14276 When PREVIOUS is set, go to the previous sibling instead. Returns t
14277 when a sibling was found. When none is found, return nil and don't
14278 move point."
14279 (let ((fun (if previous 're-search-backward 're-search-forward))
14280 (pos (point))
14281 (re (concat "^" outline-regexp))
14282 level l)
14283 (when (condition-case nil (org-back-to-heading t) (error nil))
14284 (setq level (funcall outline-level))
14285 (catch 'exit
14286 (or previous (forward-char 1))
14287 (while (funcall fun re nil t)
14288 (setq l (funcall outline-level))
14289 (when (< l level) (goto-char pos) (throw 'exit nil))
14290 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14291 (goto-char pos)
14292 nil))))
14294 (defun org-show-siblings ()
14295 "Show all siblings of the current headline."
14296 (save-excursion
14297 (while (org-goto-sibling) (org-flag-heading nil)))
14298 (save-excursion
14299 (while (org-goto-sibling 'previous)
14300 (org-flag-heading nil))))
14302 (defun org-show-hidden-entry ()
14303 "Show an entry where even the heading is hidden."
14304 (save-excursion
14305 (org-show-entry)))
14307 (defun org-flag-heading (flag &optional entry)
14308 "Flag the current heading. FLAG non-nil means make invisible.
14309 When ENTRY is non-nil, show the entire entry."
14310 (save-excursion
14311 (org-back-to-heading t)
14312 ;; Check if we should show the entire entry
14313 (if entry
14314 (progn
14315 (org-show-entry)
14316 (save-excursion
14317 (and (outline-next-heading)
14318 (org-flag-heading nil))))
14319 (outline-flag-region (max (point-min) (1- (point)))
14320 (save-excursion (outline-end-of-heading) (point))
14321 flag))))
14323 (defun org-forward-same-level (arg)
14324 "Move forward to the ARG'th subheading at same level as this one.
14325 Stop at the first and last subheadings of a superior heading.
14326 This is like outline-forward-same-level, but invisible headings are ok."
14327 (interactive "p")
14328 (org-back-to-heading t)
14329 (while (> arg 0)
14330 (let ((point-to-move-to (save-excursion
14331 (org-get-next-sibling))))
14332 (if point-to-move-to
14333 (progn
14334 (goto-char point-to-move-to)
14335 (setq arg (1- arg)))
14336 (progn
14337 (setq arg 0)
14338 (error "No following same-level heading"))))))
14340 (defun org-get-next-sibling ()
14341 "Move to next heading of the same level, and return point.
14342 If there is no such heading, return nil.
14343 This is like outline-next-sibling, but invisible headings are ok."
14344 (let ((level (funcall outline-level)))
14345 (outline-next-heading)
14346 (while (and (not (eobp)) (> (funcall outline-level) level))
14347 (outline-next-heading))
14348 (if (or (eobp) (< (funcall outline-level) level))
14350 (point))))
14352 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14353 ;; This is an exact copy of the original function, but it uses
14354 ;; `org-back-to-heading', to make it work also in invisible
14355 ;; trees. And is uses an invisible-OK argument.
14356 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14357 (org-back-to-heading invisible-OK)
14358 (let ((first t)
14359 (level (funcall outline-level)))
14360 (while (and (not (eobp))
14361 (or first (> (funcall outline-level) level)))
14362 (setq first nil)
14363 (outline-next-heading))
14364 (unless to-heading
14365 (if (memq (preceding-char) '(?\n ?\^M))
14366 (progn
14367 ;; Go to end of line before heading
14368 (forward-char -1)
14369 (if (memq (preceding-char) '(?\n ?\^M))
14370 ;; leave blank line before heading
14371 (forward-char -1))))))
14372 (point))
14374 (defun org-show-subtree ()
14375 "Show everything after this heading at deeper levels."
14376 (outline-flag-region
14377 (point)
14378 (save-excursion
14379 (outline-end-of-subtree) (outline-next-heading) (point))
14380 nil))
14382 (defun org-show-entry ()
14383 "Show the body directly following this heading.
14384 Show the heading too, if it is currently invisible."
14385 (interactive)
14386 (save-excursion
14387 (condition-case nil
14388 (progn
14389 (org-back-to-heading t)
14390 (outline-flag-region
14391 (max (point-min) (1- (point)))
14392 (save-excursion
14393 (re-search-forward
14394 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14395 (or (match-beginning 1) (point-max)))
14396 nil))
14397 (error nil))))
14399 (defun org-make-options-regexp (kwds)
14400 "Make a regular expression for keyword lines."
14401 (concat
14403 "#?[ \t]*\\+\\("
14404 (mapconcat 'regexp-quote kwds "\\|")
14405 "\\):[ \t]*"
14406 "\\(.+\\)"))
14408 ;; Make isearch reveal the necessary context
14409 (defun org-isearch-end ()
14410 "Reveal context after isearch exits."
14411 (when isearch-success ; only if search was successful
14412 (if (featurep 'xemacs)
14413 ;; Under XEmacs, the hook is run in the correct place,
14414 ;; we directly show the context.
14415 (org-show-context 'isearch)
14416 ;; In Emacs the hook runs *before* restoring the overlays.
14417 ;; So we have to use a one-time post-command-hook to do this.
14418 ;; (Emacs 22 has a special variable, see function `org-mode')
14419 (unless (and (boundp 'isearch-mode-end-hook-quit)
14420 isearch-mode-end-hook-quit)
14421 ;; Only when the isearch was not quitted.
14422 (org-add-hook 'post-command-hook 'org-isearch-post-command
14423 'append 'local)))))
14425 (defun org-isearch-post-command ()
14426 "Remove self from hook, and show context."
14427 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14428 (org-show-context 'isearch))
14431 ;;;; Integration with and fixes for other packages
14433 ;;; Imenu support
14435 (defvar org-imenu-markers nil
14436 "All markers currently used by Imenu.")
14437 (make-variable-buffer-local 'org-imenu-markers)
14439 (defun org-imenu-new-marker (&optional pos)
14440 "Return a new marker for use by Imenu, and remember the marker."
14441 (let ((m (make-marker)))
14442 (move-marker m (or pos (point)))
14443 (push m org-imenu-markers)
14446 (defun org-imenu-get-tree ()
14447 "Produce the index for Imenu."
14448 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14449 (setq org-imenu-markers nil)
14450 (let* ((n org-imenu-depth)
14451 (re (concat "^" outline-regexp))
14452 (subs (make-vector (1+ n) nil))
14453 (last-level 0)
14454 m tree level head)
14455 (save-excursion
14456 (save-restriction
14457 (widen)
14458 (goto-char (point-max))
14459 (while (re-search-backward re nil t)
14460 (setq level (org-reduced-level (funcall outline-level)))
14461 (when (<= level n)
14462 (looking-at org-complex-heading-regexp)
14463 (setq head (org-link-display-format
14464 (org-match-string-no-properties 4))
14465 m (org-imenu-new-marker))
14466 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14467 (if (>= level last-level)
14468 (push (cons head m) (aref subs level))
14469 (push (cons head (aref subs (1+ level))) (aref subs level))
14470 (loop for i from (1+ level) to n do (aset subs i nil)))
14471 (setq last-level level)))))
14472 (aref subs 1)))
14474 (eval-after-load "imenu"
14475 '(progn
14476 (add-hook 'imenu-after-jump-hook
14477 (lambda ()
14478 (if (eq major-mode 'org-mode)
14479 (org-show-context 'org-goto))))))
14481 (defun org-link-display-format (link)
14482 "Replace a link with either the description, or the link target
14483 if no description is present"
14484 (save-match-data
14485 (if (string-match org-bracket-link-analytic-regexp link)
14486 (replace-match (or (match-string 5 link)
14487 (concat (match-string 1 link)
14488 (match-string 3 link)))
14489 nil nil link)
14490 link)))
14492 ;; Speedbar support
14494 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14495 "Overlay marking the agenda restriction line in speedbar.")
14496 (org-overlay-put org-speedbar-restriction-lock-overlay
14497 'face 'org-agenda-restriction-lock)
14498 (org-overlay-put org-speedbar-restriction-lock-overlay
14499 'help-echo "Agendas are currently limited to this item.")
14500 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14502 (defun org-speedbar-set-agenda-restriction ()
14503 "Restrict future agenda commands to the location at point in speedbar.
14504 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14505 (interactive)
14506 (require 'org-agenda)
14507 (let (p m tp np dir txt w)
14508 (cond
14509 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14510 'org-imenu t))
14511 (setq m (get-text-property p 'org-imenu-marker))
14512 (save-excursion
14513 (save-restriction
14514 (set-buffer (marker-buffer m))
14515 (goto-char m)
14516 (org-agenda-set-restriction-lock 'subtree))))
14517 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14518 'speedbar-function 'speedbar-find-file))
14519 (setq tp (previous-single-property-change
14520 (1+ p) 'speedbar-function)
14521 np (next-single-property-change
14522 tp 'speedbar-function)
14523 dir (speedbar-line-directory)
14524 txt (buffer-substring-no-properties (or tp (point-min))
14525 (or np (point-max))))
14526 (save-excursion
14527 (save-restriction
14528 (set-buffer (find-file-noselect
14529 (let ((default-directory dir))
14530 (expand-file-name txt))))
14531 (unless (org-mode-p)
14532 (error "Cannot restrict to non-Org-mode file"))
14533 (org-agenda-set-restriction-lock 'file))))
14534 (t (error "Don't know how to restrict Org-mode's agenda")))
14535 (org-move-overlay org-speedbar-restriction-lock-overlay
14536 (point-at-bol) (point-at-eol))
14537 (setq current-prefix-arg nil)
14538 (org-agenda-maybe-redo)))
14540 (eval-after-load "speedbar"
14541 '(progn
14542 (speedbar-add-supported-extension ".org")
14543 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14544 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14545 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14546 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14547 (add-hook 'speedbar-visiting-tag-hook
14548 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14551 ;;; Fixes and Hacks for problems with other packages
14553 ;; Make flyspell not check words in links, to not mess up our keymap
14554 (defun org-mode-flyspell-verify ()
14555 "Don't let flyspell put overlays at active buttons."
14556 (not (get-text-property (point) 'keymap)))
14558 ;; Make `bookmark-jump' show the jump location if it was hidden.
14559 (eval-after-load "bookmark"
14560 '(if (boundp 'bookmark-after-jump-hook)
14561 ;; We can use the hook
14562 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14563 ;; Hook not available, use advice
14564 (defadvice bookmark-jump (after org-make-visible activate)
14565 "Make the position visible."
14566 (org-bookmark-jump-unhide))))
14568 ;; Make sure saveplace show the location if it was hidden
14569 (eval-after-load "saveplace"
14570 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14571 "Make the position visible."
14572 (org-bookmark-jump-unhide)))
14574 (defun org-bookmark-jump-unhide ()
14575 "Unhide the current position, to show the bookmark location."
14576 (and (org-mode-p)
14577 (or (org-invisible-p)
14578 (save-excursion (goto-char (max (point-min) (1- (point))))
14579 (org-invisible-p)))
14580 (org-show-context 'bookmark-jump)))
14582 ;; Make session.el ignore our circular variable
14583 (eval-after-load "session"
14584 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14586 ;;;; Experimental code
14588 (defun org-closed-in-range ()
14589 "Sparse tree of items closed in a certain time range.
14590 Still experimental, may disappear in the future."
14591 (interactive)
14592 ;; Get the time interval from the user.
14593 (let* ((time1 (time-to-seconds
14594 (org-read-date nil 'to-time nil "Starting date: ")))
14595 (time2 (time-to-seconds
14596 (org-read-date nil 'to-time nil "End date:")))
14597 ;; callback function
14598 (callback (lambda ()
14599 (let ((time
14600 (time-to-seconds
14601 (apply 'encode-time
14602 (org-parse-time-string
14603 (match-string 1))))))
14604 ;; check if time in interval
14605 (and (>= time time1) (<= time time2))))))
14606 ;; make tree, check each match with the callback
14607 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14610 ;;;; Finish up
14612 (provide 'org)
14614 (run-hooks 'org-load-hook)
14616 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14618 ;;; org.el ends here