Improve the description for org-eval-light.el.
[org-mode.git] / lisp / org.el
blobfa3be124af89973eacc2a8f34cf5fef5a7091f20
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.12trans
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.12trans"
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 Remember"
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."
1279 :group 'org-refile
1280 :type '(choice
1281 (const :tag "Outline" outline)
1282 (const :tag "Outline-path-completion" outline-path-completion)))
1284 (defcustom org-reverse-note-order nil
1285 "Non-nil means, store new notes at the beginning of a file or entry.
1286 When nil, new notes will be filed to the end of a file or entry.
1287 This can also be a list with cons cells of regular expressions that
1288 are matched against file names, and values."
1289 :group 'org-remember
1290 :type '(choice
1291 (const :tag "Reverse always" t)
1292 (const :tag "Reverse never" nil)
1293 (repeat :tag "By file name regexp"
1294 (cons regexp boolean))))
1296 (defcustom org-refile-targets nil
1297 "Targets for refiling entries with \\[org-refile].
1298 This is list of cons cells. Each cell contains:
1299 - a specification of the files to be considered, either a list of files,
1300 or a symbol whose function or variable value will be used to retrieve
1301 a file name or a list of file names. Nil means, refile to a different
1302 heading in the current buffer.
1303 - A specification of how to find candidate refile targets. This may be
1304 any of
1305 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1306 This tag has to be present in all target headlines, inheritance will
1307 not be considered.
1308 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1309 todo keyword.
1310 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1311 headlines that are refiling targets.
1312 - a cons cell (:level . N). Any headline of level N is considered a target.
1313 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1315 When this variable is nil, all top-level headlines in the current buffer
1316 are used, equivalent to the value `((nil . (:level . 1))'."
1317 :group 'org-remember
1318 :type '(repeat
1319 (cons
1320 (choice :value org-agenda-files
1321 (const :tag "All agenda files" org-agenda-files)
1322 (const :tag "Current buffer" nil)
1323 (function) (variable) (file))
1324 (choice :tag "Identify target headline by"
1325 (cons :tag "Specific tag" (const :tag) (string))
1326 (cons :tag "TODO keyword" (const :todo) (string))
1327 (cons :tag "Regular expression" (const :regexp) (regexp))
1328 (cons :tag "Level number" (const :level) (integer))
1329 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1331 (defcustom org-refile-use-outline-path nil
1332 "Non-nil means, provide refile targets as paths.
1333 So a level 3 headline will be available as level1/level2/level3.
1334 When the value is `file', also include the file name (without directory)
1335 into the path. When `full-file-path', include the full file path."
1336 :group 'org-remember
1337 :type '(choice
1338 (const :tag "Not" nil)
1339 (const :tag "Yes" t)
1340 (const :tag "Start with file name" file)
1341 (const :tag "Start with full file path" full-file-path)))
1343 (defgroup org-todo nil
1344 "Options concerning TODO items in Org-mode."
1345 :tag "Org TODO"
1346 :group 'org)
1348 (defgroup org-progress nil
1349 "Options concerning Progress logging in Org-mode."
1350 :tag "Org Progress"
1351 :group 'org-time)
1353 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1354 "List of TODO entry keyword sequences and their interpretation.
1355 \\<org-mode-map>This is a list of sequences.
1357 Each sequence starts with a symbol, either `sequence' or `type',
1358 indicating if the keywords should be interpreted as a sequence of
1359 action steps, or as different types of TODO items. The first
1360 keywords are states requiring action - these states will select a headline
1361 for inclusion into the global TODO list Org-mode produces. If one of
1362 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1363 signify that no further action is necessary. If \"|\" is not found,
1364 the last keyword is treated as the only DONE state of the sequence.
1366 The command \\[org-todo] cycles an entry through these states, and one
1367 additional state where no keyword is present. For details about this
1368 cycling, see the manual.
1370 TODO keywords and interpretation can also be set on a per-file basis with
1371 the special #+SEQ_TODO and #+TYP_TODO lines.
1373 Each keyword can optionally specify a character for fast state selection
1374 \(in combination with the variable `org-use-fast-todo-selection')
1375 and specifiers for state change logging, using the same syntax
1376 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1377 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1378 indicates to record a time stamp each time this state is selected.
1380 Each keyword may also specify if a timestamp or a note should be
1381 recorded when entering or leaving the state, by adding additional
1382 characters in the parenthesis after the keyword. This looks like this:
1383 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1384 record only the time of the state change. With X and Y being either
1385 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1386 Y when leaving the state if and only if the *target* state does not
1387 define X. You may omit any of the fast-selection key or X or /Y,
1388 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1390 For backward compatibility, this variable may also be just a list
1391 of keywords - in this case the interptetation (sequence or type) will be
1392 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1393 :group 'org-todo
1394 :group 'org-keywords
1395 :type '(choice
1396 (repeat :tag "Old syntax, just keywords"
1397 (string :tag "Keyword"))
1398 (repeat :tag "New syntax"
1399 (cons
1400 (choice
1401 :tag "Interpretation"
1402 (const :tag "Sequence (cycling hits every state)" sequence)
1403 (const :tag "Type (cycling directly to DONE)" type))
1404 (repeat
1405 (string :tag "Keyword"))))))
1407 (defvar org-todo-keywords-1 nil
1408 "All TODO and DONE keywords active in a buffer.")
1409 (make-variable-buffer-local 'org-todo-keywords-1)
1410 (defvar org-todo-keywords-for-agenda nil)
1411 (defvar org-done-keywords-for-agenda nil)
1412 (defvar org-todo-keyword-alist-for-agenda nil)
1413 (defvar org-tag-alist-for-agenda nil)
1414 (defvar org-agenda-contributing-files nil)
1415 (defvar org-not-done-keywords nil)
1416 (make-variable-buffer-local 'org-not-done-keywords)
1417 (defvar org-done-keywords nil)
1418 (make-variable-buffer-local 'org-done-keywords)
1419 (defvar org-todo-heads nil)
1420 (make-variable-buffer-local 'org-todo-heads)
1421 (defvar org-todo-sets nil)
1422 (make-variable-buffer-local 'org-todo-sets)
1423 (defvar org-todo-log-states nil)
1424 (make-variable-buffer-local 'org-todo-log-states)
1425 (defvar org-todo-kwd-alist nil)
1426 (make-variable-buffer-local 'org-todo-kwd-alist)
1427 (defvar org-todo-key-alist nil)
1428 (make-variable-buffer-local 'org-todo-key-alist)
1429 (defvar org-todo-key-trigger nil)
1430 (make-variable-buffer-local 'org-todo-key-trigger)
1432 (defcustom org-todo-interpretation 'sequence
1433 "Controls how TODO keywords are interpreted.
1434 This variable is in principle obsolete and is only used for
1435 backward compatibility, if the interpretation of todo keywords is
1436 not given already in `org-todo-keywords'. See that variable for
1437 more information."
1438 :group 'org-todo
1439 :group 'org-keywords
1440 :type '(choice (const sequence)
1441 (const type)))
1443 (defcustom org-use-fast-todo-selection 'prefix
1444 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1445 This variable describes if and under what circumstances the cycling
1446 mechanism for TODO keywords will be replaced by a single-key, direct
1447 selection scheme.
1449 When nil, fast selection is never used.
1451 When the symbol `prefix', it will be used when `org-todo' is called with
1452 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1453 in an agenda buffer.
1455 When t, fast selection is used by default. In this case, the prefix
1456 argument forces cycling instead.
1458 In all cases, the special interface is only used if access keys have actually
1459 been assigned by the user, i.e. if keywords in the configuration are followed
1460 by a letter in parenthesis, like TODO(t)."
1461 :group 'org-todo
1462 :type '(choice
1463 (const :tag "Never" nil)
1464 (const :tag "By default" t)
1465 (const :tag "Only with C-u C-c C-t" prefix)))
1467 (defcustom org-provide-todo-statistics t
1468 "Non-nil means, update todo statistics after insert and toggle.
1469 When this is set, todo statistics is updated in the parent of the current
1470 entry each time a todo state is changed."
1471 :group 'org-todo
1472 :type 'boolean)
1474 (defcustom org-after-todo-state-change-hook nil
1475 "Hook which is run after the state of a TODO item was changed.
1476 The new state (a string with a TODO keyword, or nil) is available in the
1477 Lisp variable `state'."
1478 :group 'org-todo
1479 :type 'hook)
1481 (defcustom org-todo-state-tags-triggers nil
1482 "Tag changes that should be triggered by TODO state changes.
1483 This is a list. Each entry is
1485 (state-change (tag . flag) .......)
1487 State-change can be a string with a state, and empty string to indicate the
1488 state that has no TODO keyword, or it can be one of the symbols `todo'
1489 or `done', meaning any not-done or done state, respectively."
1490 :group 'org-todo
1491 :group 'org-tags
1492 :type '(repeat
1493 (cons (choice :tag "When changing to"
1494 (const :tag "Not-done state" todo)
1495 (const :tag "Done state" done)
1496 (string :tag "State"))
1497 (repeat
1498 (cons :tag "Tag action"
1499 (string :tag "Tag")
1500 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1502 (defcustom org-log-done nil
1503 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1504 When equal to the list (done), also prompt for a closing note.
1505 This can also be configured on a per-file basis by adding one of
1506 the following lines anywhere in the buffer:
1508 #+STARTUP: logdone
1509 #+STARTUP: lognotedone
1510 #+STARTUP: nologdone"
1511 :group 'org-todo
1512 :group 'org-progress
1513 :type '(choice
1514 (const :tag "No logging" nil)
1515 (const :tag "Record CLOSED timestamp" time)
1516 (const :tag "Record CLOSED timestamp with closing note." note)))
1518 ;; Normalize old uses of org-log-done.
1519 (cond
1520 ((eq org-log-done t) (setq org-log-done 'time))
1521 ((and (listp org-log-done) (memq 'done org-log-done))
1522 (setq org-log-done 'note)))
1524 (defcustom org-log-note-clock-out nil
1525 "Non-nil means, record a note when clocking out of an item.
1526 This can also be configured on a per-file basis by adding one of
1527 the following lines anywhere in the buffer:
1529 #+STARTUP: lognoteclock-out
1530 #+STARTUP: nolognoteclock-out"
1531 :group 'org-todo
1532 :group 'org-progress
1533 :type 'boolean)
1535 (defcustom org-log-done-with-time t
1536 "Non-nil means, the CLOSED time stamp will contain date and time.
1537 When nil, only the date will be recorded."
1538 :group 'org-progress
1539 :type 'boolean)
1541 (defcustom org-log-note-headings
1542 '((done . "CLOSING NOTE %t")
1543 (state . "State %-12s %t")
1544 (note . "Note taken on %t")
1545 (clock-out . ""))
1546 "Headings for notes added to entries.
1547 The value is an alist, with the car being a symbol indicating the note
1548 context, and the cdr is the heading to be used. The heading may also be the
1549 empty string.
1550 %t in the heading will be replaced by a time stamp.
1551 %s will be replaced by the new TODO state, in double quotes.
1552 %u will be replaced by the user name.
1553 %U will be replaced by the full user name."
1554 :group 'org-todo
1555 :group 'org-progress
1556 :type '(list :greedy t
1557 (cons (const :tag "Heading when closing an item" done) string)
1558 (cons (const :tag
1559 "Heading when changing todo state (todo sequence only)"
1560 state) string)
1561 (cons (const :tag "Heading when just taking a note" note) string)
1562 (cons (const :tag "Heading when clocking out" clock-out) string)))
1564 (unless (assq 'note org-log-note-headings)
1565 (push '(note . "%t") org-log-note-headings))
1567 (defcustom org-log-state-notes-insert-after-drawers nil
1568 "Non-nil means, insert state change notes after any drawers in entry.
1569 Only the drawers that *immediately* follow the headline and the
1570 deadline/scheduled line are skipped.
1571 When nil, insert notes right after the heading and perhaps the line
1572 with deadline/scheduling if present."
1573 :group 'org-todo
1574 :group 'org-progress
1575 :type 'boolean)
1577 (defcustom org-log-states-order-reversed t
1578 "Non-nil means, the latest state change note will be directly after heading.
1579 When nil, the notes will be orderer according to time."
1580 :group 'org-todo
1581 :group 'org-progress
1582 :type 'boolean)
1584 (defcustom org-log-repeat 'time
1585 "Non-nil means, record moving through the DONE state when triggering repeat.
1586 An auto-repeating tasks is immediately switched back to TODO when marked
1587 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1588 the TODO keyword definition, or recording a closing note by setting
1589 `org-log-done', there will be no record of the task moving through DONE.
1590 This variable forces taking a note anyway. Possible values are:
1592 nil Don't force a record
1593 time Record a time stamp
1594 note Record a note
1596 This option can also be set with on a per-file-basis with
1598 #+STARTUP: logrepeat
1599 #+STARTUP: lognoterepeat
1600 #+STARTUP: nologrepeat
1602 You can have local logging settings for a subtree by setting the LOGGING
1603 property to one or more of these keywords."
1604 :group 'org-todo
1605 :group 'org-progress
1606 :type '(choice
1607 (const :tag "Don't force a record" nil)
1608 (const :tag "Force recording the DONE state" time)
1609 (const :tag "Force recording a note with the DONE state" note)))
1612 (defgroup org-priorities nil
1613 "Priorities in Org-mode."
1614 :tag "Org Priorities"
1615 :group 'org-todo)
1617 (defcustom org-highest-priority ?A
1618 "The highest priority of TODO items. A character like ?A, ?B etc.
1619 Must have a smaller ASCII number than `org-lowest-priority'."
1620 :group 'org-priorities
1621 :type 'character)
1623 (defcustom org-lowest-priority ?C
1624 "The lowest priority of TODO items. A character like ?A, ?B etc.
1625 Must have a larger ASCII number than `org-highest-priority'."
1626 :group 'org-priorities
1627 :type 'character)
1629 (defcustom org-default-priority ?B
1630 "The default priority of TODO items.
1631 This is the priority an item get if no explicit priority is given."
1632 :group 'org-priorities
1633 :type 'character)
1635 (defcustom org-priority-start-cycle-with-default t
1636 "Non-nil means, start with default priority when starting to cycle.
1637 When this is nil, the first step in the cycle will be (depending on the
1638 command used) one higher or lower that the default priority."
1639 :group 'org-priorities
1640 :type 'boolean)
1642 (defgroup org-time nil
1643 "Options concerning time stamps and deadlines in Org-mode."
1644 :tag "Org Time"
1645 :group 'org)
1647 (defcustom org-insert-labeled-timestamps-at-point nil
1648 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1649 When nil, these labeled time stamps are forces into the second line of an
1650 entry, just after the headline. When scheduling from the global TODO list,
1651 the time stamp will always be forced into the second line."
1652 :group 'org-time
1653 :type 'boolean)
1655 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1656 "Formats for `format-time-string' which are used for time stamps.
1657 It is not recommended to change this constant.")
1659 (defcustom org-time-stamp-rounding-minutes '(0 5)
1660 "Number of minutes to round time stamps to.
1661 These are two values, the first applies when first creating a time stamp.
1662 The second applies when changing it with the commands `S-up' and `S-down'.
1663 When changing the time stamp, this means that it will change in steps
1664 of N minutes, as given by the second value.
1666 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1667 numbers should be factors of 60, so for example 5, 10, 15.
1669 When this is larger than 1, you can still force an exact time-stamp by using
1670 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1671 and by using a prefix arg to `S-up/down' to specify the exact number
1672 of minutes to shift."
1673 :group 'org-time
1674 :get '(lambda (var) ; Make sure all entries have 5 elements
1675 (if (integerp (default-value var))
1676 (list (default-value var) 5)
1677 (default-value var)))
1678 :type '(list
1679 (integer :tag "when inserting times")
1680 (integer :tag "when modifying times")))
1682 ;; Normalize old customizations of this variable.
1683 (when (integerp org-time-stamp-rounding-minutes)
1684 (setq org-time-stamp-rounding-minutes
1685 (list org-time-stamp-rounding-minutes
1686 org-time-stamp-rounding-minutes)))
1688 (defcustom org-display-custom-times nil
1689 "Non-nil means, overlay custom formats over all time stamps.
1690 The formats are defined through the variable `org-time-stamp-custom-formats'.
1691 To turn this on on a per-file basis, insert anywhere in the file:
1692 #+STARTUP: customtime"
1693 :group 'org-time
1694 :set 'set-default
1695 :type 'sexp)
1696 (make-variable-buffer-local 'org-display-custom-times)
1698 (defcustom org-time-stamp-custom-formats
1699 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1700 "Custom formats for time stamps. See `format-time-string' for the syntax.
1701 These are overlayed over the default ISO format if the variable
1702 `org-display-custom-times' is set. Time like %H:%M should be at the
1703 end of the second format."
1704 :group 'org-time
1705 :type 'sexp)
1707 (defun org-time-stamp-format (&optional long inactive)
1708 "Get the right format for a time string."
1709 (let ((f (if long (cdr org-time-stamp-formats)
1710 (car org-time-stamp-formats))))
1711 (if inactive
1712 (concat "[" (substring f 1 -1) "]")
1713 f)))
1715 (defcustom org-time-clocksum-format "%d:%02d"
1716 "The format string used when creating CLOCKSUM lines, or when
1717 org-mode generates a time duration."
1718 :group 'org-time
1719 :type 'string)
1721 (defcustom org-deadline-warning-days 14
1722 "No. of days before expiration during which a deadline becomes active.
1723 This variable governs the display in sparse trees and in the agenda.
1724 When 0 or negative, it means use this number (the absolute value of it)
1725 even if a deadline has a different individual lead time specified."
1726 :group 'org-time
1727 :group 'org-agenda-daily/weekly
1728 :type 'number)
1730 (defcustom org-read-date-prefer-future t
1731 "Non-nil means, assume future for incomplete date input from user.
1732 This affects the following situations:
1733 1. The user gives a day, but no month.
1734 For example, if today is the 15th, and you enter \"3\", Org-mode will
1735 read this as the third of *next* month. However, if you enter \"17\",
1736 it will be considered as *this* month.
1737 2. The user gives a month but not a year.
1738 For example, if it is april and you enter \"feb 2\", this will be read
1739 as feb 2, *next* year. \"May 5\", however, will be this year.
1741 Currently this does not work for ISO week specifications.
1743 When this option is nil, the current month and year will always be used
1744 as defaults."
1745 :group 'org-time
1746 :type 'boolean)
1748 (defcustom org-read-date-display-live t
1749 "Non-nil means, display current interpretation of date prompt live.
1750 This display will be in an overlay, in the minibuffer."
1751 :group 'org-time
1752 :type 'boolean)
1754 (defcustom org-read-date-popup-calendar t
1755 "Non-nil means, pop up a calendar when prompting for a date.
1756 In the calendar, the date can be selected with mouse-1. However, the
1757 minibuffer will also be active, and you can simply enter the date as well.
1758 When nil, only the minibuffer will be available."
1759 :group 'org-time
1760 :type 'boolean)
1761 (if (fboundp 'defvaralias)
1762 (defvaralias 'org-popup-calendar-for-date-prompt
1763 'org-read-date-popup-calendar))
1765 (defcustom org-extend-today-until 0
1766 "The hour when your day really ends. Must be an integer.
1767 This has influence for the following applications:
1768 - When switching the agenda to \"today\". It it is still earlier than
1769 the time given here, the day recognized as TODAY is actually yesterday.
1770 - When a date is read from the user and it is still before the time given
1771 here, the current date and time will be assumed to be yesterday, 23:59.
1772 Also, timestamps inserted in remember templates follow this rule.
1774 IMPORTANT: This is a feature whose implementation is and likely will
1775 remain incomplete. Really, it is only here because past midnight seems to
1776 be the favorite working time of John Wiegley :-)"
1777 :group 'org-time
1778 :type 'number)
1780 (defcustom org-edit-timestamp-down-means-later nil
1781 "Non-nil means, S-down will increase the time in a time stamp.
1782 When nil, S-up will increase."
1783 :group 'org-time
1784 :type 'boolean)
1786 (defcustom org-calendar-follow-timestamp-change t
1787 "Non-nil means, make the calendar window follow timestamp changes.
1788 When a timestamp is modified and the calendar window is visible, it will be
1789 moved to the new date."
1790 :group 'org-time
1791 :type 'boolean)
1793 (defgroup org-tags nil
1794 "Options concerning tags in Org-mode."
1795 :tag "Org Tags"
1796 :group 'org)
1798 (defcustom org-tag-alist nil
1799 "List of tags allowed in Org-mode files.
1800 When this list is nil, Org-mode will base TAG input on what is already in the
1801 buffer.
1802 The value of this variable is an alist, the car of each entry must be a
1803 keyword as a string, the cdr may be a character that is used to select
1804 that tag through the fast-tag-selection interface.
1805 See the manual for details."
1806 :group 'org-tags
1807 :type '(repeat
1808 (choice
1809 (cons (string :tag "Tag name")
1810 (character :tag "Access char"))
1811 (const :tag "Start radio group" (:startgroup))
1812 (const :tag "End radio group" (:endgroup)))))
1814 (defvar org-file-tags nil
1815 "List of tags that can be inherited by all entries in the file.
1816 The tags will be inherited if the variable `org-use-tag-inheritance'
1817 says they should be.
1818 This variable is populated from #+TAG lines.")
1820 (defcustom org-use-fast-tag-selection 'auto
1821 "Non-nil means, use fast tag selection scheme.
1822 This is a special interface to select and deselect tags with single keys.
1823 When nil, fast selection is never used.
1824 When the symbol `auto', fast selection is used if and only if selection
1825 characters for tags have been configured, either through the variable
1826 `org-tag-alist' or through a #+TAGS line in the buffer.
1827 When t, fast selection is always used and selection keys are assigned
1828 automatically if necessary."
1829 :group 'org-tags
1830 :type '(choice
1831 (const :tag "Always" t)
1832 (const :tag "Never" nil)
1833 (const :tag "When selection characters are configured" 'auto)))
1835 (defcustom org-fast-tag-selection-single-key nil
1836 "Non-nil means, fast tag selection exits after first change.
1837 When nil, you have to press RET to exit it.
1838 During fast tag selection, you can toggle this flag with `C-c'.
1839 This variable can also have the value `expert'. In this case, the window
1840 displaying the tags menu is not even shown, until you press C-c again."
1841 :group 'org-tags
1842 :type '(choice
1843 (const :tag "No" nil)
1844 (const :tag "Yes" t)
1845 (const :tag "Expert" expert)))
1847 (defvar org-fast-tag-selection-include-todo nil
1848 "Non-nil means, fast tags selection interface will also offer TODO states.
1849 This is an undocumented feature, you should not rely on it.")
1851 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1852 "The column to which tags should be indented in a headline.
1853 If this number is positive, it specifies the column. If it is negative,
1854 it means that the tags should be flushright to that column. For example,
1855 -80 works well for a normal 80 character screen."
1856 :group 'org-tags
1857 :type 'integer)
1859 (defcustom org-auto-align-tags t
1860 "Non-nil means, realign tags after pro/demotion of TODO state change.
1861 These operations change the length of a headline and therefore shift
1862 the tags around. With this options turned on, after each such operation
1863 the tags are again aligned to `org-tags-column'."
1864 :group 'org-tags
1865 :type 'boolean)
1867 (defcustom org-use-tag-inheritance t
1868 "Non-nil means, tags in levels apply also for sublevels.
1869 When nil, only the tags directly given in a specific line apply there.
1870 If this option is t, a match early-on in a tree can lead to a large
1871 number of matches in the subtree. If you only want to see the first
1872 match in a tree during a search, check out the variable
1873 `org-tags-match-list-sublevels'.
1875 This may also be a list of tags that should be inherited, or a regexp that
1876 matches tags that should be inherited."
1877 :group 'org-tags
1878 :type '(choice
1879 (const :tag "Not" nil)
1880 (const :tag "Always" t)
1881 (repeat :tag "Specific tags" (string :tag "Tag"))
1882 (regexp :tag "Tags matched by regexp")))
1884 (defun org-tag-inherit-p (tag)
1885 "Check if TAG is one that should be inherited."
1886 (cond
1887 ((eq org-use-tag-inheritance t) t)
1888 ((not org-use-tag-inheritance) nil)
1889 ((stringp org-use-tag-inheritance)
1890 (string-match org-use-tag-inheritance tag))
1891 ((listp org-use-tag-inheritance)
1892 (member tag org-use-tag-inheritance))
1893 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1895 (defcustom org-tags-match-list-sublevels t
1896 "Non-nil means list also sublevels of headlines matching tag search.
1897 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1898 the sublevels of a headline matching a tag search often also match
1899 the same search. Listing all of them can create very long lists.
1900 Setting this variable to nil causes subtrees of a match to be skipped.
1901 This option is off by default, because inheritance in on. If you turn
1902 inheritance off, you very likely want to turn this option on.
1904 As a special case, if the tag search is restricted to TODO items, the
1905 value of this variable is ignored and sublevels are always checked, to
1906 make sure all corresponding TODO items find their way into the list."
1907 :group 'org-tags
1908 :type 'boolean)
1910 (defvar org-tags-history nil
1911 "History of minibuffer reads for tags.")
1912 (defvar org-last-tags-completion-table nil
1913 "The last used completion table for tags.")
1914 (defvar org-after-tags-change-hook nil
1915 "Hook that is run after the tags in a line have changed.")
1917 (defgroup org-properties nil
1918 "Options concerning properties in Org-mode."
1919 :tag "Org Properties"
1920 :group 'org)
1922 (defcustom org-property-format "%-10s %s"
1923 "How property key/value pairs should be formatted by `indent-line'.
1924 When `indent-line' hits a property definition, it will format the line
1925 according to this format, mainly to make sure that the values are
1926 lined-up with respect to each other."
1927 :group 'org-properties
1928 :type 'string)
1930 (defcustom org-use-property-inheritance nil
1931 "Non-nil means, properties apply also for sublevels.
1933 This setting is chiefly used during property searches. Turning it on can
1934 cause significant overhead when doing a search, which is why it is not
1935 on by default.
1937 When nil, only the properties directly given in the current entry count.
1938 When t, every property is inherited. The value may also be a list of
1939 properties that should have inheritance, or a regular expression matching
1940 properties that should be inherited.
1942 However, note that some special properties use inheritance under special
1943 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1944 and the properties ending in \"_ALL\" when they are used as descriptor
1945 for valid values of a property.
1947 Note for programmers:
1948 When querying an entry with `org-entry-get', you can control if inheritance
1949 should be used. By default, `org-entry-get' looks only at the local
1950 properties. You can request inheritance by setting the inherit argument
1951 to t (to force inheritance) or to `selective' (to respect the setting
1952 in this variable)."
1953 :group 'org-properties
1954 :type '(choice
1955 (const :tag "Not" nil)
1956 (const :tag "Always" t)
1957 (repeat :tag "Specific properties" (string :tag "Property"))
1958 (regexp :tag "Properties matched by regexp")))
1960 (defun org-property-inherit-p (property)
1961 "Check if PROPERTY is one that should be inherited."
1962 (cond
1963 ((eq org-use-property-inheritance t) t)
1964 ((not org-use-property-inheritance) nil)
1965 ((stringp org-use-property-inheritance)
1966 (string-match org-use-property-inheritance property))
1967 ((listp org-use-property-inheritance)
1968 (member property org-use-property-inheritance))
1969 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1971 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1972 "The default column format, if no other format has been defined.
1973 This variable can be set on the per-file basis by inserting a line
1975 #+COLUMNS: %25ITEM ....."
1976 :group 'org-properties
1977 :type 'string)
1979 (defcustom org-columns-ellipses ".."
1980 "The ellipses to be used when a field in column view is truncated.
1981 When this is the empty string, as many characters as possible are shown,
1982 but then there will be no visual indication that the field has been truncated.
1983 When this is a string of length N, the last N characters of a truncated
1984 field are replaced by this string. If the column is narrower than the
1985 ellipses string, only part of the ellipses string will be shown."
1986 :group 'org-properties
1987 :type 'string)
1989 (defcustom org-columns-modify-value-for-display-function nil
1990 "Function that modifies values for display in column view.
1991 For example, it can be used to cut out a certain part from a time stamp.
1992 The function must take 2 arguments:
1994 column-title The tite of the column (*not* the property name)
1995 value The value that should be modified.
1997 The function should return the value that should be displayed,
1998 or nil if the normal value should be used."
1999 :group 'org-properties
2000 :type 'function)
2002 (defcustom org-effort-property "Effort"
2003 "The property that is being used to keep track of effort estimates.
2004 Effort estimates given in this property need to have the format H:MM."
2005 :group 'org-properties
2006 :group 'org-progress
2007 :type '(string :tag "Property"))
2009 (defconst org-global-properties-fixed
2010 '(("VISIBILITY_ALL" . "folded children content all"))
2011 "List of property/value pairs that can be inherited by any entry.
2012 These are fixed values, for the preset properties.")
2015 (defcustom org-global-properties nil
2016 "List of property/value pairs that can be inherited by any entry.
2017 You can set buffer-local values for the same purpose in the variable
2018 `org-file-properties' this by adding lines like
2020 #+PROPERTY: NAME VALUE"
2021 :group 'org-properties
2022 :type '(repeat
2023 (cons (string :tag "Property")
2024 (string :tag "Value"))))
2026 (defvar org-file-properties nil
2027 "List of property/value pairs that can be inherited by any entry.
2028 Valid for the current buffer.
2029 This variable is populated from #+PROPERTY lines.")
2030 (make-variable-buffer-local 'org-file-properties)
2032 (defgroup org-agenda nil
2033 "Options concerning agenda views in Org-mode."
2034 :tag "Org Agenda"
2035 :group 'org)
2037 (defvar org-category nil
2038 "Variable used by org files to set a category for agenda display.
2039 Such files should use a file variable to set it, for example
2041 # -*- mode: org; org-category: \"ELisp\"
2043 or contain a special line
2045 #+CATEGORY: ELisp
2047 If the file does not specify a category, then file's base name
2048 is used instead.")
2049 (make-variable-buffer-local 'org-category)
2050 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2052 (defcustom org-agenda-files nil
2053 "The files to be used for agenda display.
2054 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2055 \\[org-remove-file]. You can also use customize to edit the list.
2057 If an entry is a directory, all files in that directory that are matched by
2058 `org-agenda-file-regexp' will be part of the file list.
2060 If the value of the variable is not a list but a single file name, then
2061 the list of agenda files is actually stored and maintained in that file, one
2062 agenda file per line."
2063 :group 'org-agenda
2064 :type '(choice
2065 (repeat :tag "List of files and directories" file)
2066 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2068 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2069 "Regular expression to match files for `org-agenda-files'.
2070 If any element in the list in that variable contains a directory instead
2071 of a normal file, all files in that directory that are matched by this
2072 regular expression will be included."
2073 :group 'org-agenda
2074 :type 'regexp)
2076 (defcustom org-agenda-text-search-extra-files nil
2077 "List of extra files to be searched by text search commands.
2078 These files will be search in addition to the agenda files by the
2079 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2080 Note that these files will only be searched for text search commands,
2081 not for the other agenda views like todo lists, tag searches or the weekly
2082 agenda. This variable is intended to list notes and possibly archive files
2083 that should also be searched by these two commands.
2084 In fact, if the first element in the list is the symbol `agenda-archives',
2085 than all archive files of all agenda files will be added to the search
2086 scope."
2087 :group 'org-agenda
2088 :type '(set :greedy t
2089 (const :tag "Agenda Archives" agenda-archives)
2090 (repeat :inline t (file))))
2092 (if (fboundp 'defvaralias)
2093 (defvaralias 'org-agenda-multi-occur-extra-files
2094 'org-agenda-text-search-extra-files))
2096 (defcustom org-agenda-skip-unavailable-files nil
2097 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2098 A nil value means to remove them, after a query, from the list."
2099 :group 'org-agenda
2100 :type 'boolean)
2102 (defcustom org-calendar-to-agenda-key [?c]
2103 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2104 The command `org-calendar-goto-agenda' will be bound to this key. The
2105 default is the character `c' because then `c' can be used to switch back and
2106 forth between agenda and calendar."
2107 :group 'org-agenda
2108 :type 'sexp)
2110 (defcustom org-calendar-agenda-action-key [?k]
2111 "The key to be installed in `calendar-mode-map' for agenda-action.
2112 The command `org-agenda-action' will be bound to this key. The
2113 default is the character `k' because we use the same key in the agenda."
2114 :group 'org-agenda
2115 :type 'sexp)
2117 (eval-after-load "calendar"
2118 '(progn
2119 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2120 'org-calendar-goto-agenda)
2121 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2122 'org-agenda-action)))
2124 (defgroup org-latex nil
2125 "Options for embedding LaTeX code into Org-mode."
2126 :tag "Org LaTeX"
2127 :group 'org)
2129 (defcustom org-format-latex-options
2130 '(:foreground default :background default :scale 1.0
2131 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2132 :matchers ("begin" "$" "$$" "\\(" "\\["))
2133 "Options for creating images from LaTeX fragments.
2134 This is a property list with the following properties:
2135 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2136 `default' means use the foreground of the default face.
2137 :background the background color, or \"Transparent\".
2138 `default' means use the background of the default face.
2139 :scale a scaling factor for the size of the images.
2140 :html-foreground, :html-background, :html-scale
2141 the same numbers for HTML export.
2142 :matchers a list indicating which matchers should be used to
2143 find LaTeX fragments. Valid members of this list are:
2144 \"begin\" find environments
2145 \"$\" find math expressions surrounded by $...$
2146 \"$$\" find math expressions surrounded by $$....$$
2147 \"\\(\" find math expressions surrounded by \\(...\\)
2148 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2149 :group 'org-latex
2150 :type 'plist)
2152 (defcustom org-format-latex-header "\\documentclass{article}
2153 \\usepackage{fullpage} % do not remove
2154 \\usepackage{amssymb}
2155 \\usepackage[usenames]{color}
2156 \\usepackage{amsmath}
2157 \\usepackage{latexsym}
2158 \\usepackage[mathscr]{eucal}
2159 \\pagestyle{empty} % do not remove"
2160 "The document header used for processing LaTeX fragments."
2161 :group 'org-latex
2162 :type 'string)
2165 (defgroup org-font-lock nil
2166 "Font-lock settings for highlighting in Org-mode."
2167 :tag "Org Font Lock"
2168 :group 'org)
2170 (defcustom org-level-color-stars-only nil
2171 "Non-nil means fontify only the stars in each headline.
2172 When nil, the entire headline is fontified.
2173 Changing it requires restart of `font-lock-mode' to become effective
2174 also in regions already fontified."
2175 :group 'org-font-lock
2176 :type 'boolean)
2178 (defcustom org-hide-leading-stars nil
2179 "Non-nil means, hide the first N-1 stars in a headline.
2180 This works by using the face `org-hide' for these stars. This
2181 face is white for a light background, and black for a dark
2182 background. You may have to customize the face `org-hide' to
2183 make this work.
2184 Changing it requires restart of `font-lock-mode' to become effective
2185 also in regions already fontified.
2186 You may also set this on a per-file basis by adding one of the following
2187 lines to the buffer:
2189 #+STARTUP: hidestars
2190 #+STARTUP: showstars"
2191 :group 'org-font-lock
2192 :type 'boolean)
2194 (defcustom org-fontify-done-headline nil
2195 "Non-nil means, change the face of a headline if it is marked DONE.
2196 Normally, only the TODO/DONE keyword indicates the state of a headline.
2197 When this is non-nil, the headline after the keyword is set to the
2198 `org-headline-done' as an additional indication."
2199 :group 'org-font-lock
2200 :type 'boolean)
2202 (defcustom org-fontify-emphasized-text t
2203 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2204 Changing this variable requires a restart of Emacs to take effect."
2205 :group 'org-font-lock
2206 :type 'boolean)
2208 (defcustom org-highlight-latex-fragments-and-specials nil
2209 "Non-nil means, fontify what is treated specially by the exporters."
2210 :group 'org-font-lock
2211 :type 'boolean)
2213 (defcustom org-hide-emphasis-markers nil
2214 "Non-nil mean font-lock should hide the emphasis marker characters."
2215 :group 'org-font-lock
2216 :type 'boolean)
2218 (defvar org-emph-re nil
2219 "Regular expression for matching emphasis.")
2220 (defvar org-verbatim-re nil
2221 "Regular expression for matching verbatim text.")
2222 (defvar org-emphasis-regexp-components) ; defined just below
2223 (defvar org-emphasis-alist) ; defined just below
2224 (defun org-set-emph-re (var val)
2225 "Set variable and compute the emphasis regular expression."
2226 (set var val)
2227 (when (and (boundp 'org-emphasis-alist)
2228 (boundp 'org-emphasis-regexp-components)
2229 org-emphasis-alist org-emphasis-regexp-components)
2230 (let* ((e org-emphasis-regexp-components)
2231 (pre (car e))
2232 (post (nth 1 e))
2233 (border (nth 2 e))
2234 (body (nth 3 e))
2235 (nl (nth 4 e))
2236 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2237 (body1 (concat body "*?"))
2238 (markers (mapconcat 'car org-emphasis-alist ""))
2239 (vmarkers (mapconcat
2240 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2241 org-emphasis-alist "")))
2242 ;; make sure special characters appear at the right position in the class
2243 (if (string-match "\\^" markers)
2244 (setq markers (concat (replace-match "" t t markers) "^")))
2245 (if (string-match "-" markers)
2246 (setq markers (concat (replace-match "" t t markers) "-")))
2247 (if (string-match "\\^" vmarkers)
2248 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2249 (if (string-match "-" vmarkers)
2250 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2251 (if (> nl 0)
2252 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2253 (int-to-string nl) "\\}")))
2254 ;; Make the regexp
2255 (setq org-emph-re
2256 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2257 "\\("
2258 "\\([" markers "]\\)"
2259 "\\("
2260 "[^" border "]\\|"
2261 "[^" border (if (and nil stacked) markers) "]"
2262 body1
2263 "[^" border (if (and nil stacked) markers) "]"
2264 "\\)"
2265 "\\3\\)"
2266 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2267 (setq org-verbatim-re
2268 (concat "\\([" pre "]\\|^\\)"
2269 "\\("
2270 "\\([" vmarkers "]\\)"
2271 "\\("
2272 "[^" border "]\\|"
2273 "[^" border "]"
2274 body1
2275 "[^" border "]"
2276 "\\)"
2277 "\\3\\)"
2278 "\\([" post "]\\|$\\)")))))
2280 (defcustom org-emphasis-regexp-components
2281 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2282 "Components used to build the regular expression for emphasis.
2283 This is a list with 6 entries. Terminology: In an emphasis string
2284 like \" *strong word* \", we call the initial space PREMATCH, the final
2285 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2286 and \"trong wor\" is the body. The different components in this variable
2287 specify what is allowed/forbidden in each part:
2289 pre Chars allowed as prematch. Beginning of line will be allowed too.
2290 post Chars allowed as postmatch. End of line will be allowed too.
2291 border The chars *forbidden* as border characters.
2292 body-regexp A regexp like \".\" to match a body character. Don't use
2293 non-shy groups here, and don't allow newline here.
2294 newline The maximum number of newlines allowed in an emphasis exp.
2296 Use customize to modify this, or restart Emacs after changing it."
2297 :group 'org-font-lock
2298 :set 'org-set-emph-re
2299 :type '(list
2300 (sexp :tag "Allowed chars in pre ")
2301 (sexp :tag "Allowed chars in post ")
2302 (sexp :tag "Forbidden chars in border ")
2303 (sexp :tag "Regexp for body ")
2304 (integer :tag "number of newlines allowed")
2305 (option (boolean :tag "Please ignore this button"))))
2307 (defcustom org-emphasis-alist
2308 `(("*" bold "<b>" "</b>")
2309 ("/" italic "<i>" "</i>")
2310 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2311 ("=" org-code "<code>" "</code>" verbatim)
2312 ("~" org-verbatim "<code>" "</code>" verbatim)
2313 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2314 "<del>" "</del>")
2316 "Special syntax for emphasized text.
2317 Text starting and ending with a special character will be emphasized, for
2318 example *bold*, _underlined_ and /italic/. This variable sets the marker
2319 characters, the face to be used by font-lock for highlighting in Org-mode
2320 Emacs buffers, and the HTML tags to be used for this.
2321 Use customize to modify this, or restart Emacs after changing it."
2322 :group 'org-font-lock
2323 :set 'org-set-emph-re
2324 :type '(repeat
2325 (list
2326 (string :tag "Marker character")
2327 (choice
2328 (face :tag "Font-lock-face")
2329 (plist :tag "Face property list"))
2330 (string :tag "HTML start tag")
2331 (string :tag "HTML end tag")
2332 (option (const verbatim)))))
2334 ;;; Miscellaneous options
2336 (defgroup org-completion nil
2337 "Completion in Org-mode."
2338 :tag "Org Completion"
2339 :group 'org)
2341 (defcustom org-completion-use-ido nil
2342 "Non-ni means, use ido completion wherever possible."
2343 :group 'org
2344 :type 'boolean)
2346 (defcustom org-completion-fallback-command 'hippie-expand
2347 "The expansion command called by \\[org-complete] in normal context.
2348 Normal means, no org-mode-specific context."
2349 :group 'org-completion
2350 :type 'function)
2352 ;;; Functions and variables from ther packages
2353 ;; Declared here to avoid compiler warnings
2355 ;; XEmacs only
2356 (defvar outline-mode-menu-heading)
2357 (defvar outline-mode-menu-show)
2358 (defvar outline-mode-menu-hide)
2359 (defvar zmacs-regions) ; XEmacs regions
2361 ;; Emacs only
2362 (defvar mark-active)
2364 ;; Various packages
2365 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2366 (declare-function calendar-forward-day "cal-move" (arg))
2367 (declare-function calendar-goto-date "cal-move" (date))
2368 (declare-function calendar-goto-today "cal-move" ())
2369 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2370 (defvar calc-embedded-close-formula)
2371 (defvar calc-embedded-open-formula)
2372 (declare-function cdlatex-tab "ext:cdlatex" ())
2373 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2374 (defvar font-lock-unfontify-region-function)
2375 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2376 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2377 (defvar iswitchb-temp-buflist)
2378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2379 (declare-function org-agenda-skip "org-agenda" ())
2380 (declare-function org-format-agenda-item "org-agenda"
2381 (extra txt &optional category tags dotime noprefix remove-re))
2382 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2383 (declare-function org-agenda-change-all-lines "org-agenda"
2384 (newhead hdmarker &optional fixface))
2385 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2386 (declare-function org-agenda-maybe-redo "org-agenda" ())
2387 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2388 (beg end))
2389 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2390 (declare-function parse-time-string "parse-time" (string))
2391 (declare-function remember "remember" (&optional initial))
2392 (declare-function remember-buffer-desc "remember" ())
2393 (declare-function remember-finalize "remember" ())
2394 (defvar remember-save-after-remembering)
2395 (defvar remember-data-file)
2396 (defvar remember-register)
2397 (defvar remember-buffer)
2398 (defvar remember-handler-functions)
2399 (defvar remember-annotation-functions)
2400 (defvar texmathp-why)
2401 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2402 (declare-function table--at-cell-p "table" (position &optional object at-column))
2404 (defvar w3m-current-url)
2405 (defvar w3m-current-title)
2407 (defvar org-latex-regexps)
2409 ;;; Autoload and prepare some org modules
2411 ;; Some table stuff that needs to be defined here, because it is used
2412 ;; by the functions setting up org-mode or checking for table context.
2414 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2415 "Detects an org-type or table-type table.")
2416 (defconst org-table-line-regexp "^[ \t]*|"
2417 "Detects an org-type table line.")
2418 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2419 "Detects an org-type table line.")
2420 (defconst org-table-hline-regexp "^[ \t]*|-"
2421 "Detects an org-type table hline.")
2422 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2423 "Detects a table-type table hline.")
2424 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2425 "Searching from within a table (any type) this finds the first line
2426 outside the table.")
2428 ;; Autoload the functions in org-table.el that are needed by functions here.
2430 (eval-and-compile
2431 (org-autoload "org-table"
2432 '(org-table-align org-table-begin org-table-blank-field
2433 org-table-convert org-table-convert-region org-table-copy-down
2434 org-table-copy-region org-table-create
2435 org-table-create-or-convert-from-region
2436 org-table-create-with-table.el org-table-current-dline
2437 org-table-cut-region org-table-delete-column org-table-edit-field
2438 org-table-edit-formulas org-table-end org-table-eval-formula
2439 org-table-export org-table-field-info
2440 org-table-get-stored-formulas org-table-goto-column
2441 org-table-hline-and-move org-table-import org-table-insert-column
2442 org-table-insert-hline org-table-insert-row org-table-iterate
2443 org-table-justify-field-maybe org-table-kill-row
2444 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2445 org-table-move-column org-table-move-column-left
2446 org-table-move-column-right org-table-move-row
2447 org-table-move-row-down org-table-move-row-up
2448 org-table-next-field org-table-next-row org-table-paste-rectangle
2449 org-table-previous-field org-table-recalculate
2450 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2451 org-table-toggle-coordinate-overlays
2452 org-table-toggle-formula-debugger org-table-wrap-region
2453 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2455 (defun org-at-table-p (&optional table-type)
2456 "Return t if the cursor is inside an org-type table.
2457 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2458 (if org-enable-table-editor
2459 (save-excursion
2460 (beginning-of-line 1)
2461 (looking-at (if table-type org-table-any-line-regexp
2462 org-table-line-regexp)))
2463 nil))
2464 (defsubst org-table-p () (org-at-table-p))
2466 (defun org-at-table.el-p ()
2467 "Return t if and only if we are at a table.el table."
2468 (and (org-at-table-p 'any)
2469 (save-excursion
2470 (goto-char (org-table-begin 'any))
2471 (looking-at org-table1-hline-regexp))))
2472 (defun org-table-recognize-table.el ()
2473 "If there is a table.el table nearby, recognize it and move into it."
2474 (if org-table-tab-recognizes-table.el
2475 (if (org-at-table.el-p)
2476 (progn
2477 (beginning-of-line 1)
2478 (if (looking-at org-table-dataline-regexp)
2480 (if (looking-at org-table1-hline-regexp)
2481 (progn
2482 (beginning-of-line 2)
2483 (if (looking-at org-table-any-border-regexp)
2484 (beginning-of-line -1)))))
2485 (if (re-search-forward "|" (org-table-end t) t)
2486 (progn
2487 (require 'table)
2488 (if (table--at-cell-p (point))
2490 (message "recognizing table.el table...")
2491 (table-recognize-table)
2492 (message "recognizing table.el table...done")))
2493 (error "This should not happen..."))
2495 nil)
2496 nil))
2498 (defun org-at-table-hline-p ()
2499 "Return t if the cursor is inside a hline in a table."
2500 (if org-enable-table-editor
2501 (save-excursion
2502 (beginning-of-line 1)
2503 (looking-at org-table-hline-regexp))
2504 nil))
2506 (defvar org-table-clean-did-remove-column nil)
2508 (defun org-table-map-tables (function)
2509 "Apply FUNCTION to the start of all tables in the buffer."
2510 (save-excursion
2511 (save-restriction
2512 (widen)
2513 (goto-char (point-min))
2514 (while (re-search-forward org-table-any-line-regexp nil t)
2515 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2516 (beginning-of-line 1)
2517 (if (looking-at org-table-line-regexp)
2518 (save-excursion (funcall function)))
2519 (re-search-forward org-table-any-border-regexp nil 1))))
2520 (message "Mapping tables: done"))
2522 ;; Declare and autoload functions from org-exp.el
2524 (declare-function org-default-export-plist "org-exp")
2525 (declare-function org-infile-export-plist "org-exp")
2526 (declare-function org-get-current-options "org-exp")
2527 (eval-and-compile
2528 (org-autoload "org-exp"
2529 '(org-export org-export-as-ascii org-export-visible
2530 org-insert-export-options-template org-export-as-html-and-open
2531 org-export-as-html-batch org-export-as-html-to-buffer
2532 org-replace-region-by-html org-export-region-as-html
2533 org-export-as-html org-export-icalendar-this-file
2534 org-export-icalendar-all-agenda-files
2535 org-table-clean-before-export
2536 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2538 ;; Declare and autoload functions from org-agenda.el
2540 (eval-and-compile
2541 (org-autoload "org-agenda"
2542 '(org-agenda org-agenda-list org-search-view
2543 org-todo-list org-tags-view org-agenda-list-stuck-projects
2544 org-diary org-agenda-to-appt)))
2546 ;; Autoload org-remember
2548 (eval-and-compile
2549 (org-autoload "org-remember"
2550 '(org-remember-insinuate org-remember-annotation
2551 org-remember-apply-template org-remember org-remember-handler)))
2553 ;; Autoload org-clock.el
2556 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2557 (beg end))
2558 (declare-function org-update-mode-line "org-clock" ())
2559 (defvar org-clock-start-time)
2560 (defvar org-clock-marker (make-marker)
2561 "Marker recording the last clock-in.")
2563 (eval-and-compile
2564 (org-autoload
2565 "org-clock"
2566 '(org-clock-in org-clock-out org-clock-cancel
2567 org-clock-goto org-clock-sum org-clock-display
2568 org-remove-clock-overlays org-clock-report
2569 org-clocktable-shift org-dblock-write:clocktable
2570 org-get-clocktable)))
2572 (defun org-clock-update-time-maybe ()
2573 "If this is a CLOCK line, update it and return t.
2574 Otherwise, return nil."
2575 (interactive)
2576 (save-excursion
2577 (beginning-of-line 1)
2578 (skip-chars-forward " \t")
2579 (when (looking-at org-clock-string)
2580 (let ((re (concat "[ \t]*" org-clock-string
2581 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2582 "\\([ \t]*=>.*\\)?\\)?"))
2583 ts te h m s neg)
2584 (cond
2585 ((not (looking-at re))
2586 nil)
2587 ((not (match-end 2))
2588 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2589 (> org-clock-marker (point))
2590 (<= org-clock-marker (point-at-eol)))
2591 ;; The clock is running here
2592 (setq org-clock-start-time
2593 (apply 'encode-time
2594 (org-parse-time-string (match-string 1))))
2595 (org-update-mode-line)))
2597 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2598 (end-of-line 1)
2599 (setq ts (match-string 1)
2600 te (match-string 3))
2601 (setq s (- (time-to-seconds
2602 (apply 'encode-time (org-parse-time-string te)))
2603 (time-to-seconds
2604 (apply 'encode-time (org-parse-time-string ts))))
2605 neg (< s 0)
2606 s (abs s)
2607 h (floor (/ s 3600))
2608 s (- s (* 3600 h))
2609 m (floor (/ s 60))
2610 s (- s (* 60 s)))
2611 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2612 t))))))
2614 (defun org-check-running-clock ()
2615 "Check if the current buffer contains the running clock.
2616 If yes, offer to stop it and to save the buffer with the changes."
2617 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2618 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2619 (buffer-name))))
2620 (org-clock-out)
2621 (when (y-or-n-p "Save changed buffer?")
2622 (save-buffer))))
2624 (defun org-clocktable-try-shift (dir n)
2625 "Check if this line starts a clock table, if yes, shift the time block."
2626 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2627 (org-clocktable-shift dir n)))
2629 ;; Autoload archiving code
2630 ;; The stuff that is needed for cycling and tags has to be defined here.
2632 (defgroup org-archive nil
2633 "Options concerning archiving in Org-mode."
2634 :tag "Org Archive"
2635 :group 'org-structure)
2637 (defcustom org-archive-location "%s_archive::"
2638 "The location where subtrees should be archived.
2640 Otherwise, the value of this variable is a string, consisting of two
2641 parts, separated by a double-colon.
2643 The first part is a file name - when omitted, archiving happens in the same
2644 file. %s will be replaced by the current file name (without directory part).
2645 Archiving to a different file is useful to keep archived entries from
2646 contributing to the Org-mode Agenda.
2648 The part after the double colon is a headline. The archived entries will be
2649 filed under that headline. When omitted, the subtrees are simply filed away
2650 at the end of the file, as top-level entries.
2652 Here are a few examples:
2653 \"%s_archive::\"
2654 If the current file is Projects.org, archive in file
2655 Projects.org_archive, as top-level trees. This is the default.
2657 \"::* Archived Tasks\"
2658 Archive in the current file, under the top-level headline
2659 \"* Archived Tasks\".
2661 \"~/org/archive.org::\"
2662 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2664 \"basement::** Finished Tasks\"
2665 Archive in file ./basement (relative path), as level 3 trees
2666 below the level 2 heading \"** Finished Tasks\".
2668 You may set this option on a per-file basis by adding to the buffer a
2669 line like
2671 #+ARCHIVE: basement::** Finished Tasks
2673 You may also define it locally for a subtree by setting an ARCHIVE property
2674 in the entry. If such a property is found in an entry, or anywhere up
2675 the hierarchy, it will be used."
2676 :group 'org-archive
2677 :type 'string)
2679 (defcustom org-archive-tag "ARCHIVE"
2680 "The tag that marks a subtree as archived.
2681 An archived subtree does not open during visibility cycling, and does
2682 not contribute to the agenda listings.
2683 After changing this, font-lock must be restarted in the relevant buffers to
2684 get the proper fontification."
2685 :group 'org-archive
2686 :group 'org-keywords
2687 :type 'string)
2689 (defcustom org-agenda-skip-archived-trees t
2690 "Non-nil means, the agenda will skip any items located in archived trees.
2691 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2692 variable is no longer recommended, you should leave it at the value t.
2693 Instead, use the key `v' to cycle the archives-mode in the agenda."
2694 :group 'org-archive
2695 :group 'org-agenda-skip
2696 :type 'boolean)
2698 (defcustom org-cycle-open-archived-trees nil
2699 "Non-nil means, `org-cycle' will open archived trees.
2700 An archived tree is a tree marked with the tag ARCHIVE.
2701 When nil, archived trees will stay folded. You can still open them with
2702 normal outline commands like `show-all', but not with the cycling commands."
2703 :group 'org-archive
2704 :group 'org-cycle
2705 :type 'boolean)
2707 (defcustom org-sparse-tree-open-archived-trees nil
2708 "Non-nil means sparse tree construction shows matches in archived trees.
2709 When nil, matches in these trees are highlighted, but the trees are kept in
2710 collapsed state."
2711 :group 'org-archive
2712 :group 'org-sparse-trees
2713 :type 'boolean)
2715 (defun org-cycle-hide-archived-subtrees (state)
2716 "Re-hide all archived subtrees after a visibility state change."
2717 (when (and (not org-cycle-open-archived-trees)
2718 (not (memq state '(overview folded))))
2719 (save-excursion
2720 (let* ((globalp (memq state '(contents all)))
2721 (beg (if globalp (point-min) (point)))
2722 (end (if globalp (point-max) (org-end-of-subtree t))))
2723 (org-hide-archived-subtrees beg end)
2724 (goto-char beg)
2725 (if (looking-at (concat ".*:" org-archive-tag ":"))
2726 (message "%s" (substitute-command-keys
2727 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2729 (defun org-force-cycle-archived ()
2730 "Cycle subtree even if it is archived."
2731 (interactive)
2732 (setq this-command 'org-cycle)
2733 (let ((org-cycle-open-archived-trees t))
2734 (call-interactively 'org-cycle)))
2736 (defun org-hide-archived-subtrees (beg end)
2737 "Re-hide all archived subtrees after a visibility state change."
2738 (save-excursion
2739 (let* ((re (concat ":" org-archive-tag ":")))
2740 (goto-char beg)
2741 (while (re-search-forward re end t)
2742 (and (org-on-heading-p) (hide-subtree))
2743 (org-end-of-subtree t)))))
2745 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2747 (eval-and-compile
2748 (org-autoload "org-archive"
2749 '(org-add-archive-files org-archive-subtree
2750 org-archive-to-archive-sibling org-toggle-archive-tag)))
2752 ;; Autoload Column View Code
2754 (declare-function org-columns-number-to-string "org-colview")
2755 (declare-function org-columns-get-format-and-top-level "org-colview")
2756 (declare-function org-columns-compute "org-colview")
2758 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2759 '(org-columns-number-to-string org-columns-get-format-and-top-level
2760 org-columns-compute org-agenda-columns org-columns-remove-overlays
2761 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2763 ;; Autoload ID code
2765 (org-autoload "org-id"
2766 '(org-id-get-create org-id-new org-id-copy org-id-get
2767 org-id-get-with-outline-path-completion
2768 org-id-get-with-outline-drilling
2769 org-id-goto org-id-find))
2771 ;;; Variables for pre-computed regular expressions, all buffer local
2773 (defvar org-drawer-regexp nil
2774 "Matches first line of a hidden block.")
2775 (make-variable-buffer-local 'org-drawer-regexp)
2776 (defvar org-todo-regexp nil
2777 "Matches any of the TODO state keywords.")
2778 (make-variable-buffer-local 'org-todo-regexp)
2779 (defvar org-not-done-regexp nil
2780 "Matches any of the TODO state keywords except the last one.")
2781 (make-variable-buffer-local 'org-not-done-regexp)
2782 (defvar org-todo-line-regexp nil
2783 "Matches a headline and puts TODO state into group 2 if present.")
2784 (make-variable-buffer-local 'org-todo-line-regexp)
2785 (defvar org-complex-heading-regexp nil
2786 "Matches a headline and puts everything into groups:
2787 group 1: the stars
2788 group 2: The todo keyword, maybe
2789 group 3: Priority cookie
2790 group 4: True headline
2791 group 5: Tags")
2792 (make-variable-buffer-local 'org-complex-heading-regexp)
2793 (defvar org-todo-line-tags-regexp nil
2794 "Matches a headline and puts TODO state into group 2 if present.
2795 Also put tags into group 4 if tags are present.")
2796 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2797 (defvar org-nl-done-regexp nil
2798 "Matches newline followed by a headline with the DONE keyword.")
2799 (make-variable-buffer-local 'org-nl-done-regexp)
2800 (defvar org-looking-at-done-regexp nil
2801 "Matches the DONE keyword a point.")
2802 (make-variable-buffer-local 'org-looking-at-done-regexp)
2803 (defvar org-ds-keyword-length 12
2804 "Maximum length of the Deadline and SCHEDULED keywords.")
2805 (make-variable-buffer-local 'org-ds-keyword-length)
2806 (defvar org-deadline-regexp nil
2807 "Matches the DEADLINE keyword.")
2808 (make-variable-buffer-local 'org-deadline-regexp)
2809 (defvar org-deadline-time-regexp nil
2810 "Matches the DEADLINE keyword together with a time stamp.")
2811 (make-variable-buffer-local 'org-deadline-time-regexp)
2812 (defvar org-deadline-line-regexp nil
2813 "Matches the DEADLINE keyword and the rest of the line.")
2814 (make-variable-buffer-local 'org-deadline-line-regexp)
2815 (defvar org-scheduled-regexp nil
2816 "Matches the SCHEDULED keyword.")
2817 (make-variable-buffer-local 'org-scheduled-regexp)
2818 (defvar org-scheduled-time-regexp nil
2819 "Matches the SCHEDULED keyword together with a time stamp.")
2820 (make-variable-buffer-local 'org-scheduled-time-regexp)
2821 (defvar org-closed-time-regexp nil
2822 "Matches the CLOSED keyword together with a time stamp.")
2823 (make-variable-buffer-local 'org-closed-time-regexp)
2825 (defvar org-keyword-time-regexp nil
2826 "Matches any of the 4 keywords, together with the time stamp.")
2827 (make-variable-buffer-local 'org-keyword-time-regexp)
2828 (defvar org-keyword-time-not-clock-regexp nil
2829 "Matches any of the 3 keywords, together with the time stamp.")
2830 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2831 (defvar org-maybe-keyword-time-regexp nil
2832 "Matches a timestamp, possibly preceeded by a keyword.")
2833 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2834 (defvar org-planning-or-clock-line-re nil
2835 "Matches a line with planning or clock info.")
2836 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2838 (defconst org-plain-time-of-day-regexp
2839 (concat
2840 "\\(\\<[012]?[0-9]"
2841 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2842 "\\(--?"
2843 "\\(\\<[012]?[0-9]"
2844 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2845 "\\)?")
2846 "Regular expression to match a plain time or time range.
2847 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2848 groups carry important information:
2849 0 the full match
2850 1 the first time, range or not
2851 8 the second time, if it is a range.")
2853 (defconst org-plain-time-extension-regexp
2854 (concat
2855 "\\(\\<[012]?[0-9]"
2856 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2857 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2858 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2859 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2860 groups carry important information:
2861 0 the full match
2862 7 hours of duration
2863 9 minutes of duration")
2865 (defconst org-stamp-time-of-day-regexp
2866 (concat
2867 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2868 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2869 "\\(--?"
2870 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2871 "Regular expression to match a timestamp time or time range.
2872 After a match, the following groups carry important information:
2873 0 the full match
2874 1 date plus weekday, for backreferencing to make sure both times on same day
2875 2 the first time, range or not
2876 4 the second time, if it is a range.")
2878 (defconst org-startup-options
2879 '(("fold" org-startup-folded t)
2880 ("overview" org-startup-folded t)
2881 ("nofold" org-startup-folded nil)
2882 ("showall" org-startup-folded nil)
2883 ("content" org-startup-folded content)
2884 ("hidestars" org-hide-leading-stars t)
2885 ("showstars" org-hide-leading-stars nil)
2886 ("odd" org-odd-levels-only t)
2887 ("oddeven" org-odd-levels-only nil)
2888 ("align" org-startup-align-all-tables t)
2889 ("noalign" org-startup-align-all-tables nil)
2890 ("customtime" org-display-custom-times t)
2891 ("logdone" org-log-done time)
2892 ("lognotedone" org-log-done note)
2893 ("nologdone" org-log-done nil)
2894 ("lognoteclock-out" org-log-note-clock-out t)
2895 ("nolognoteclock-out" org-log-note-clock-out nil)
2896 ("logrepeat" org-log-repeat state)
2897 ("lognoterepeat" org-log-repeat note)
2898 ("nologrepeat" org-log-repeat nil)
2899 ("constcgs" constants-unit-system cgs)
2900 ("constSI" constants-unit-system SI))
2901 "Variable associated with STARTUP options for org-mode.
2902 Each element is a list of three items: The startup options as written
2903 in the #+STARTUP line, the corresponding variable, and the value to
2904 set this variable to if the option is found. An optional forth element PUSH
2905 means to push this value onto the list in the variable.")
2907 (defun org-set-regexps-and-options ()
2908 "Precompute regular expressions for current buffer."
2909 (when (org-mode-p)
2910 (org-set-local 'org-todo-kwd-alist nil)
2911 (org-set-local 'org-todo-key-alist nil)
2912 (org-set-local 'org-todo-key-trigger nil)
2913 (org-set-local 'org-todo-keywords-1 nil)
2914 (org-set-local 'org-done-keywords nil)
2915 (org-set-local 'org-todo-heads nil)
2916 (org-set-local 'org-todo-sets nil)
2917 (org-set-local 'org-todo-log-states nil)
2918 (org-set-local 'org-file-properties nil)
2919 (org-set-local 'org-file-tags nil)
2920 (let ((re (org-make-options-regexp
2921 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2922 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2923 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2924 (splitre "[ \t]+")
2925 kwds kws0 kwsa key log value cat arch tags const links hw dws
2926 tail sep kws1 prio props ftags drawers
2927 ext-setup-or-nil setup-contents (start 0))
2928 (save-excursion
2929 (save-restriction
2930 (widen)
2931 (goto-char (point-min))
2932 (while (or (and ext-setup-or-nil
2933 (string-match re ext-setup-or-nil start)
2934 (setq start (match-end 0)))
2935 (and (setq ext-setup-or-nil nil start 0)
2936 (re-search-forward re nil t)))
2937 (setq key (upcase (match-string 1 ext-setup-or-nil))
2938 value (org-match-string-no-properties 2 ext-setup-or-nil))
2939 (cond
2940 ((equal key "CATEGORY")
2941 (if (string-match "[ \t]+$" value)
2942 (setq value (replace-match "" t t value)))
2943 (setq cat value))
2944 ((member key '("SEQ_TODO" "TODO"))
2945 (push (cons 'sequence (org-split-string value splitre)) kwds))
2946 ((equal key "TYP_TODO")
2947 (push (cons 'type (org-split-string value splitre)) kwds))
2948 ((equal key "TAGS")
2949 (setq tags (append tags (org-split-string value splitre))))
2950 ((equal key "COLUMNS")
2951 (org-set-local 'org-columns-default-format value))
2952 ((equal key "LINK")
2953 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2954 (push (cons (match-string 1 value)
2955 (org-trim (match-string 2 value)))
2956 links)))
2957 ((equal key "PRIORITIES")
2958 (setq prio (org-split-string value " +")))
2959 ((equal key "PROPERTY")
2960 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2961 (push (cons (match-string 1 value) (match-string 2 value))
2962 props)))
2963 ((equal key "FILETAGS")
2964 (when (string-match "\\S-" value)
2965 (setq ftags
2966 (append
2967 ftags
2968 (apply 'append
2969 (mapcar (lambda (x) (org-split-string x ":"))
2970 (org-split-string value)))))))
2971 ((equal key "DRAWERS")
2972 (setq drawers (org-split-string value splitre)))
2973 ((equal key "CONSTANTS")
2974 (setq const (append const (org-split-string value splitre))))
2975 ((equal key "STARTUP")
2976 (let ((opts (org-split-string value splitre))
2977 l var val)
2978 (while (setq l (pop opts))
2979 (when (setq l (assoc l org-startup-options))
2980 (setq var (nth 1 l) val (nth 2 l))
2981 (if (not (nth 3 l))
2982 (set (make-local-variable var) val)
2983 (if (not (listp (symbol-value var)))
2984 (set (make-local-variable var) nil))
2985 (set (make-local-variable var) (symbol-value var))
2986 (add-to-list var val))))))
2987 ((equal key "ARCHIVE")
2988 (string-match " *$" value)
2989 (setq arch (replace-match "" t t value))
2990 (remove-text-properties 0 (length arch)
2991 '(face t fontified t) arch))
2992 ((equal key "SETUPFILE")
2993 (setq setup-contents (org-file-contents
2994 (expand-file-name
2995 (org-remove-double-quotes value))
2996 'noerror))
2997 (if (not ext-setup-or-nil)
2998 (setq ext-setup-or-nil setup-contents start 0)
2999 (setq ext-setup-or-nil
3000 (concat (substring ext-setup-or-nil 0 start)
3001 "\n" setup-contents "\n"
3002 (substring ext-setup-or-nil start)))))
3003 ))))
3004 (when cat
3005 (org-set-local 'org-category (intern cat))
3006 (push (cons "CATEGORY" cat) props))
3007 (when prio
3008 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3009 (setq prio (mapcar 'string-to-char prio))
3010 (org-set-local 'org-highest-priority (nth 0 prio))
3011 (org-set-local 'org-lowest-priority (nth 1 prio))
3012 (org-set-local 'org-default-priority (nth 2 prio)))
3013 (and props (org-set-local 'org-file-properties (nreverse props)))
3014 (and ftags (org-set-local 'org-file-tags ftags))
3015 (and drawers (org-set-local 'org-drawers drawers))
3016 (and arch (org-set-local 'org-archive-location arch))
3017 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3018 ;; Process the TODO keywords
3019 (unless kwds
3020 ;; Use the global values as if they had been given locally.
3021 (setq kwds (default-value 'org-todo-keywords))
3022 (if (stringp (car kwds))
3023 (setq kwds (list (cons org-todo-interpretation
3024 (default-value 'org-todo-keywords)))))
3025 (setq kwds (reverse kwds)))
3026 (setq kwds (nreverse kwds))
3027 (let (inter kws kw)
3028 (while (setq kws (pop kwds))
3029 (setq inter (pop kws) sep (member "|" kws)
3030 kws0 (delete "|" (copy-sequence kws))
3031 kwsa nil
3032 kws1 (mapcar
3033 (lambda (x)
3034 ;; 1 2
3035 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3036 (progn
3037 (setq kw (match-string 1 x)
3038 key (and (match-end 2) (match-string 2 x))
3039 log (org-extract-log-state-settings x))
3040 (push (cons kw (and key (string-to-char key))) kwsa)
3041 (and log (push log org-todo-log-states))
3043 (error "Invalid TODO keyword %s" x)))
3044 kws0)
3045 kwsa (if kwsa (append '((:startgroup))
3046 (nreverse kwsa)
3047 '((:endgroup))))
3048 hw (car kws1)
3049 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3050 tail (list inter hw (car dws) (org-last dws)))
3051 (add-to-list 'org-todo-heads hw 'append)
3052 (push kws1 org-todo-sets)
3053 (setq org-done-keywords (append org-done-keywords dws nil))
3054 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3055 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3056 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3057 (setq org-todo-sets (nreverse org-todo-sets)
3058 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3059 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3060 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3061 ;; Process the constants
3062 (when const
3063 (let (e cst)
3064 (while (setq e (pop const))
3065 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3066 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3067 (setq org-table-formula-constants-local cst)))
3069 ;; Process the tags.
3070 (when tags
3071 (let (e tgs)
3072 (while (setq e (pop tags))
3073 (cond
3074 ((equal e "{") (push '(:startgroup) tgs))
3075 ((equal e "}") (push '(:endgroup) tgs))
3076 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3077 (push (cons (match-string 1 e)
3078 (string-to-char (match-string 2 e)))
3079 tgs))
3080 (t (push (list e) tgs))))
3081 (org-set-local 'org-tag-alist nil)
3082 (while (setq e (pop tgs))
3083 (or (and (stringp (car e))
3084 (assoc (car e) org-tag-alist))
3085 (push e org-tag-alist)))))
3087 ;; Compute the regular expressions and other local variables
3088 (if (not org-done-keywords)
3089 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3090 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3091 (length org-scheduled-string)
3092 (length org-clock-string)
3093 (length org-closed-string)))
3094 org-drawer-regexp
3095 (concat "^[ \t]*:\\("
3096 (mapconcat 'regexp-quote org-drawers "\\|")
3097 "\\):[ \t]*$")
3098 org-not-done-keywords
3099 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3100 org-todo-regexp
3101 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3102 "\\|") "\\)\\>")
3103 org-not-done-regexp
3104 (concat "\\<\\("
3105 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3106 "\\)\\>")
3107 org-todo-line-regexp
3108 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3109 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3110 "\\)\\>\\)?[ \t]*\\(.*\\)")
3111 org-complex-heading-regexp
3112 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3113 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3114 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3115 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3116 org-nl-done-regexp
3117 (concat "\n\\*+[ \t]+"
3118 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3119 "\\)" "\\>")
3120 org-todo-line-tags-regexp
3121 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3122 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3123 (org-re
3124 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3125 org-looking-at-done-regexp
3126 (concat "^" "\\(?:"
3127 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3128 "\\>")
3129 org-deadline-regexp (concat "\\<" org-deadline-string)
3130 org-deadline-time-regexp
3131 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3132 org-deadline-line-regexp
3133 (concat "\\<\\(" org-deadline-string "\\).*")
3134 org-scheduled-regexp
3135 (concat "\\<" org-scheduled-string)
3136 org-scheduled-time-regexp
3137 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3138 org-closed-time-regexp
3139 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3140 org-keyword-time-regexp
3141 (concat "\\<\\(" org-scheduled-string
3142 "\\|" org-deadline-string
3143 "\\|" org-closed-string
3144 "\\|" org-clock-string "\\)"
3145 " *[[<]\\([^]>]+\\)[]>]")
3146 org-keyword-time-not-clock-regexp
3147 (concat "\\<\\(" org-scheduled-string
3148 "\\|" org-deadline-string
3149 "\\|" org-closed-string
3150 "\\)"
3151 " *[[<]\\([^]>]+\\)[]>]")
3152 org-maybe-keyword-time-regexp
3153 (concat "\\(\\<\\(" org-scheduled-string
3154 "\\|" org-deadline-string
3155 "\\|" org-closed-string
3156 "\\|" org-clock-string "\\)\\)?"
3157 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3158 org-planning-or-clock-line-re
3159 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3160 "\\|" org-deadline-string
3161 "\\|" org-closed-string "\\|" org-clock-string
3162 "\\)\\>\\)")
3164 (org-compute-latex-and-specials-regexp)
3165 (org-set-font-lock-defaults))))
3167 (defun org-file-contents (file &optional noerror)
3168 "Return the contents of FILE, as a string."
3169 (if (or (not file)
3170 (not (file-readable-p file)))
3171 (if noerror
3172 (progn
3173 (message "Cannot read file %s" file)
3174 (ding) (sit-for 2)
3176 (error "Cannot read file %s" file))
3177 (with-temp-buffer
3178 (insert-file-contents file)
3179 (buffer-string))))
3181 (defun org-extract-log-state-settings (x)
3182 "Extract the log state setting from a TODO keyword string.
3183 This will extract info from a string like \"WAIT(w@/!)\"."
3184 (let (kw key log1 log2)
3185 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3186 (setq kw (match-string 1 x)
3187 key (and (match-end 2) (match-string 2 x))
3188 log1 (and (match-end 3) (match-string 3 x))
3189 log2 (and (match-end 4) (match-string 4 x)))
3190 (and (or log1 log2)
3191 (list kw
3192 (and log1 (if (equal log1 "!") 'time 'note))
3193 (and log2 (if (equal log2 "!") 'time 'note)))))))
3195 (defun org-remove-keyword-keys (list)
3196 "Remove a pair of parenthesis at the end of each string in LIST."
3197 (mapcar (lambda (x)
3198 (if (string-match "(.*)$" x)
3199 (substring x 0 (match-beginning 0))
3201 list))
3203 ;; FIXME: this could be done much better, using second characters etc.
3204 (defun org-assign-fast-keys (alist)
3205 "Assign fast keys to a keyword-key alist.
3206 Respect keys that are already there."
3207 (let (new e k c c1 c2 (char ?a))
3208 (while (setq e (pop alist))
3209 (cond
3210 ((equal e '(:startgroup)) (push e new))
3211 ((equal e '(:endgroup)) (push e new))
3213 (setq k (car e) c2 nil)
3214 (if (cdr e)
3215 (setq c (cdr e))
3216 ;; automatically assign a character.
3217 (setq c1 (string-to-char
3218 (downcase (substring
3219 k (if (= (string-to-char k) ?@) 1 0)))))
3220 (if (or (rassoc c1 new) (rassoc c1 alist))
3221 (while (or (rassoc char new) (rassoc char alist))
3222 (setq char (1+ char)))
3223 (setq c2 c1))
3224 (setq c (or c2 char)))
3225 (push (cons k c) new))))
3226 (nreverse new)))
3228 ;;; Some variables used in various places
3230 (defvar org-window-configuration nil
3231 "Used in various places to store a window configuration.")
3232 (defvar org-finish-function nil
3233 "Function to be called when `C-c C-c' is used.
3234 This is for getting out of special buffers like remember.")
3237 ;; FIXME: Occasionally check by commenting these, to make sure
3238 ;; no other functions uses these, forgetting to let-bind them.
3239 (defvar entry)
3240 (defvar state)
3241 (defvar last-state)
3242 (defvar date)
3243 (defvar description)
3245 ;; Defined somewhere in this file, but used before definition.
3246 (defvar org-html-entities)
3247 (defvar org-struct-menu)
3248 (defvar org-org-menu)
3249 (defvar org-tbl-menu)
3250 (defvar org-agenda-keymap)
3252 ;;;; Define the Org-mode
3254 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3255 (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."))
3258 ;; We use a before-change function to check if a table might need
3259 ;; an update.
3260 (defvar org-table-may-need-update t
3261 "Indicates that a table might need an update.
3262 This variable is set by `org-before-change-function'.
3263 `org-table-align' sets it back to nil.")
3264 (defun org-before-change-function (beg end)
3265 "Every change indicates that a table might need an update."
3266 (setq org-table-may-need-update t))
3267 (defvar org-mode-map)
3268 (defvar org-mode-hook nil)
3269 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3270 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3271 (defvar org-table-buffer-is-an nil)
3272 (defconst org-outline-regexp "\\*+ ")
3274 ;;;###autoload
3275 (define-derived-mode org-mode outline-mode "Org"
3276 "Outline-based notes management and organizer, alias
3277 \"Carsten's outline-mode for keeping track of everything.\"
3279 Org-mode develops organizational tasks around a NOTES file which
3280 contains information about projects as plain text. Org-mode is
3281 implemented on top of outline-mode, which is ideal to keep the content
3282 of large files well structured. It supports ToDo items, deadlines and
3283 time stamps, which magically appear in the diary listing of the Emacs
3284 calendar. Tables are easily created with a built-in table editor.
3285 Plain text URL-like links connect to websites, emails (VM), Usenet
3286 messages (Gnus), BBDB entries, and any files related to the project.
3287 For printing and sharing of notes, an Org-mode file (or a part of it)
3288 can be exported as a structured ASCII or HTML file.
3290 The following commands are available:
3292 \\{org-mode-map}"
3294 ;; Get rid of Outline menus, they are not needed
3295 ;; Need to do this here because define-derived-mode sets up
3296 ;; the keymap so late. Still, it is a waste to call this each time
3297 ;; we switch another buffer into org-mode.
3298 (if (featurep 'xemacs)
3299 (when (boundp 'outline-mode-menu-heading)
3300 ;; Assume this is Greg's port, it used easymenu
3301 (easy-menu-remove outline-mode-menu-heading)
3302 (easy-menu-remove outline-mode-menu-show)
3303 (easy-menu-remove outline-mode-menu-hide))
3304 (define-key org-mode-map [menu-bar headings] 'undefined)
3305 (define-key org-mode-map [menu-bar hide] 'undefined)
3306 (define-key org-mode-map [menu-bar show] 'undefined))
3308 (org-load-modules-maybe)
3309 (easy-menu-add org-org-menu)
3310 (easy-menu-add org-tbl-menu)
3311 (org-install-agenda-files-menu)
3312 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3313 (org-add-to-invisibility-spec '(org-cwidth))
3314 (when (featurep 'xemacs)
3315 (org-set-local 'line-move-ignore-invisible t))
3316 (org-set-local 'outline-regexp org-outline-regexp)
3317 (org-set-local 'outline-level 'org-outline-level)
3318 (when (and org-ellipsis
3319 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3320 (fboundp 'make-glyph-code))
3321 (unless org-display-table
3322 (setq org-display-table (make-display-table)))
3323 (set-display-table-slot
3324 org-display-table 4
3325 (vconcat (mapcar
3326 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3327 org-ellipsis)))
3328 (if (stringp org-ellipsis) org-ellipsis "..."))))
3329 (setq buffer-display-table org-display-table))
3330 (org-set-regexps-and-options)
3331 ;; Calc embedded
3332 (org-set-local 'calc-embedded-open-mode "# ")
3333 (modify-syntax-entry ?# "<")
3334 (modify-syntax-entry ?@ "w")
3335 (if org-startup-truncated (setq truncate-lines t))
3336 (org-set-local 'font-lock-unfontify-region-function
3337 'org-unfontify-region)
3338 ;; Activate before-change-function
3339 (org-set-local 'org-table-may-need-update t)
3340 (org-add-hook 'before-change-functions 'org-before-change-function nil
3341 'local)
3342 ;; Check for running clock before killing a buffer
3343 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3344 ;; Paragraphs and auto-filling
3345 (org-set-autofill-regexps)
3346 (setq indent-line-function 'org-indent-line-function)
3347 (org-update-radio-target-regexp)
3349 ;; Comment characters
3350 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3351 (org-set-local 'comment-padding " ")
3353 ;; Align options lines
3354 (org-set-local
3355 'align-mode-rules-list
3356 '((org-in-buffer-settings
3357 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3358 (modes . '(org-mode)))))
3360 ;; Imenu
3361 (org-set-local 'imenu-create-index-function
3362 'org-imenu-get-tree)
3364 ;; Make isearch reveal context
3365 (if (or (featurep 'xemacs)
3366 (not (boundp 'outline-isearch-open-invisible-function)))
3367 ;; Emacs 21 and XEmacs make use of the hook
3368 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3369 ;; Emacs 22 deals with this through a special variable
3370 (org-set-local 'outline-isearch-open-invisible-function
3371 (lambda (&rest ignore) (org-show-context 'isearch))))
3373 ;; If empty file that did not turn on org-mode automatically, make it to.
3374 (if (and org-insert-mode-line-in-empty-file
3375 (interactive-p)
3376 (= (point-min) (point-max)))
3377 (insert "# -*- mode: org -*-\n\n"))
3379 (unless org-inhibit-startup
3380 (when org-startup-align-all-tables
3381 (let ((bmp (buffer-modified-p)))
3382 (org-table-map-tables 'org-table-align)
3383 (set-buffer-modified-p bmp)))
3384 (org-set-startup-visibility)))
3386 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3388 (defun org-current-time ()
3389 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3390 (if (> (car org-time-stamp-rounding-minutes) 1)
3391 (let ((r (car org-time-stamp-rounding-minutes))
3392 (time (decode-time)))
3393 (apply 'encode-time
3394 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3395 (nthcdr 2 time))))
3396 (current-time)))
3398 ;;;; Font-Lock stuff, including the activators
3400 (defvar org-mouse-map (make-sparse-keymap))
3401 (org-defkey org-mouse-map
3402 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3403 (org-defkey org-mouse-map
3404 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3405 (when org-mouse-1-follows-link
3406 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3407 (when org-tab-follows-link
3408 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3409 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3410 (when org-return-follows-link
3411 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3412 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3414 (require 'font-lock)
3416 (defconst org-non-link-chars "]\t\n\r<>")
3417 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3418 "shell" "elisp"))
3419 (defvar org-link-types-re nil
3420 "Matches a link that has a url-like prefix like \"http:\"")
3421 (defvar org-link-re-with-space nil
3422 "Matches a link with spaces, optional angular brackets around it.")
3423 (defvar org-link-re-with-space2 nil
3424 "Matches a link with spaces, optional angular brackets around it.")
3425 (defvar org-link-re-with-space3 nil
3426 "Matches a link with spaces, only for internal part in bracket links.")
3427 (defvar org-angle-link-re nil
3428 "Matches link with angular brackets, spaces are allowed.")
3429 (defvar org-plain-link-re nil
3430 "Matches plain link, without spaces.")
3431 (defvar org-bracket-link-regexp nil
3432 "Matches a link in double brackets.")
3433 (defvar org-bracket-link-analytic-regexp nil
3434 "Regular expression used to analyze links.
3435 Here is what the match groups contain after a match:
3436 1: http:
3437 2: http
3438 3: path
3439 4: [desc]
3440 5: desc")
3441 (defvar org-any-link-re nil
3442 "Regular expression matching any link.")
3444 (defun org-make-link-regexps ()
3445 "Update the link regular expressions.
3446 This should be called after the variable `org-link-types' has changed."
3447 (setq org-link-types-re
3448 (concat
3449 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3450 org-link-re-with-space
3451 (concat
3452 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3453 "\\([^" org-non-link-chars " ]"
3454 "[^" org-non-link-chars "]*"
3455 "[^" org-non-link-chars " ]\\)>?")
3456 org-link-re-with-space2
3457 (concat
3458 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3459 "\\([^" org-non-link-chars " ]"
3460 "[^\t\n\r]*"
3461 "[^" org-non-link-chars " ]\\)>?")
3462 org-link-re-with-space3
3463 (concat
3464 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3465 "\\([^" org-non-link-chars " ]"
3466 "[^\t\n\r]*\\)")
3467 org-angle-link-re
3468 (concat
3469 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3470 "\\([^" org-non-link-chars " ]"
3471 "[^" org-non-link-chars "]*"
3472 "\\)>")
3473 org-plain-link-re
3474 (concat
3475 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3476 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3477 org-bracket-link-regexp
3478 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3479 org-bracket-link-analytic-regexp
3480 (concat
3481 "\\[\\["
3482 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3483 "\\([^]]+\\)"
3484 "\\]"
3485 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3486 "\\]")
3487 org-any-link-re
3488 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3489 org-angle-link-re "\\)\\|\\("
3490 org-plain-link-re "\\)")))
3492 (org-make-link-regexps)
3494 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3495 "Regular expression for fast time stamp matching.")
3496 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3497 "Regular expression for fast time stamp matching.")
3498 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3499 "Regular expression matching time strings for analysis.
3500 This one does not require the space after the date, so it can be used
3501 on a string that terminates immediately after the date.")
3502 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3503 "Regular expression matching time strings for analysis.")
3504 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3505 "Regular expression matching time stamps, with groups.")
3506 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3507 "Regular expression matching time stamps (also [..]), with groups.")
3508 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3509 "Regular expression matching a time stamp range.")
3510 (defconst org-tr-regexp-both
3511 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3512 "Regular expression matching a time stamp range.")
3513 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3514 org-ts-regexp "\\)?")
3515 "Regular expression matching a time stamp or time stamp range.")
3516 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3517 org-ts-regexp-both "\\)?")
3518 "Regular expression matching a time stamp or time stamp range.
3519 The time stamps may be either active or inactive.")
3521 (defvar org-emph-face nil)
3523 (defun org-do-emphasis-faces (limit)
3524 "Run through the buffer and add overlays to links."
3525 (let (rtn)
3526 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3527 (if (not (= (char-after (match-beginning 3))
3528 (char-after (match-beginning 4))))
3529 (progn
3530 (setq rtn t)
3531 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3532 'face
3533 (nth 1 (assoc (match-string 3)
3534 org-emphasis-alist)))
3535 (add-text-properties (match-beginning 2) (match-end 2)
3536 '(font-lock-multiline t))
3537 (when org-hide-emphasis-markers
3538 (add-text-properties (match-end 4) (match-beginning 5)
3539 '(invisible org-link))
3540 (add-text-properties (match-beginning 3) (match-end 3)
3541 '(invisible org-link)))))
3542 (backward-char 1))
3543 rtn))
3545 (defun org-emphasize (&optional char)
3546 "Insert or change an emphasis, i.e. a font like bold or italic.
3547 If there is an active region, change that region to a new emphasis.
3548 If there is no region, just insert the marker characters and position
3549 the cursor between them.
3550 CHAR should be either the marker character, or the first character of the
3551 HTML tag associated with that emphasis. If CHAR is a space, the means
3552 to remove the emphasis of the selected region.
3553 If char is not given (for example in an interactive call) it
3554 will be prompted for."
3555 (interactive)
3556 (let ((eal org-emphasis-alist) e det
3557 (erc org-emphasis-regexp-components)
3558 (prompt "")
3559 (string "") beg end move tag c s)
3560 (if (org-region-active-p)
3561 (setq beg (region-beginning) end (region-end)
3562 string (buffer-substring beg end))
3563 (setq move t))
3565 (while (setq e (pop eal))
3566 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3567 c (aref tag 0))
3568 (push (cons c (string-to-char (car e))) det)
3569 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3570 (substring tag 1)))))
3571 (setq det (nreverse det))
3572 (unless char
3573 (message "%s" (concat "Emphasis marker or tag:" prompt))
3574 (setq char (read-char-exclusive)))
3575 (setq char (or (cdr (assoc char det)) char))
3576 (if (equal char ?\ )
3577 (setq s "" move nil)
3578 (unless (assoc (char-to-string char) org-emphasis-alist)
3579 (error "No such emphasis marker: \"%c\"" char))
3580 (setq s (char-to-string char)))
3581 (while (and (> (length string) 1)
3582 (equal (substring string 0 1) (substring string -1))
3583 (assoc (substring string 0 1) org-emphasis-alist))
3584 (setq string (substring string 1 -1)))
3585 (setq string (concat s string s))
3586 (if beg (delete-region beg end))
3587 (unless (or (bolp)
3588 (string-match (concat "[" (nth 0 erc) "\n]")
3589 (char-to-string (char-before (point)))))
3590 (insert " "))
3591 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3592 (char-to-string (char-after (point))))
3593 (insert " ") (backward-char 1))
3594 (insert string)
3595 (and move (backward-char 1))))
3597 (defconst org-nonsticky-props
3598 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3601 (defun org-activate-plain-links (limit)
3602 "Run through the buffer and add overlays to links."
3603 (catch 'exit
3604 (let (f)
3605 (while (re-search-forward org-plain-link-re limit t)
3606 (setq f (get-text-property (match-beginning 0) 'face))
3607 (if (or (eq f 'org-tag)
3608 (and (listp f) (memq 'org-tag f)))
3610 (add-text-properties (match-beginning 0) (match-end 0)
3611 (list 'mouse-face 'highlight
3612 'rear-nonsticky org-nonsticky-props
3613 'keymap org-mouse-map
3615 (throw 'exit t))))))
3617 (defun org-activate-code (limit)
3618 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3619 (progn
3620 (remove-text-properties (match-beginning 0) (match-end 0)
3621 '(display t invisible t intangible t))
3622 t)))
3624 (defun org-activate-angle-links (limit)
3625 "Run through the buffer and add overlays to links."
3626 (if (re-search-forward org-angle-link-re limit t)
3627 (progn
3628 (add-text-properties (match-beginning 0) (match-end 0)
3629 (list 'mouse-face 'highlight
3630 'rear-nonsticky org-nonsticky-props
3631 'keymap org-mouse-map
3633 t)))
3635 (defun org-activate-bracket-links (limit)
3636 "Run through the buffer and add overlays to bracketed links."
3637 (if (re-search-forward org-bracket-link-regexp limit t)
3638 (let* ((help (concat "LINK: "
3639 (org-match-string-no-properties 1)))
3640 ;; FIXME: above we should remove the escapes.
3641 ;; but that requires another match, protecting match data,
3642 ;; a lot of overhead for font-lock.
3643 (ip (org-maybe-intangible
3644 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3645 'keymap org-mouse-map 'mouse-face 'highlight
3646 'font-lock-multiline t 'help-echo help)))
3647 (vp (list 'rear-nonsticky org-nonsticky-props
3648 'keymap org-mouse-map 'mouse-face 'highlight
3649 ' font-lock-multiline t 'help-echo help)))
3650 ;; We need to remove the invisible property here. Table narrowing
3651 ;; may have made some of this invisible.
3652 (remove-text-properties (match-beginning 0) (match-end 0)
3653 '(invisible nil))
3654 (if (match-end 3)
3655 (progn
3656 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3657 (add-text-properties (match-beginning 3) (match-end 3) vp)
3658 (add-text-properties (match-end 3) (match-end 0) ip))
3659 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3660 (add-text-properties (match-beginning 1) (match-end 1) vp)
3661 (add-text-properties (match-end 1) (match-end 0) ip))
3662 t)))
3664 (defun org-activate-dates (limit)
3665 "Run through the buffer and add overlays to dates."
3666 (if (re-search-forward org-tsr-regexp-both limit t)
3667 (progn
3668 (add-text-properties (match-beginning 0) (match-end 0)
3669 (list 'mouse-face 'highlight
3670 'rear-nonsticky org-nonsticky-props
3671 'keymap org-mouse-map))
3672 (when org-display-custom-times
3673 (if (match-end 3)
3674 (org-display-custom-time (match-beginning 3) (match-end 3)))
3675 (org-display-custom-time (match-beginning 1) (match-end 1)))
3676 t)))
3678 (defvar org-target-link-regexp nil
3679 "Regular expression matching radio targets in plain text.")
3680 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3681 "Regular expression matching a link target.")
3682 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3683 "Regular expression matching a radio target.")
3684 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3685 "Regular expression matching any target.")
3687 (defun org-activate-target-links (limit)
3688 "Run through the buffer and add overlays to target matches."
3689 (when org-target-link-regexp
3690 (let ((case-fold-search t))
3691 (if (re-search-forward org-target-link-regexp limit t)
3692 (progn
3693 (add-text-properties (match-beginning 0) (match-end 0)
3694 (list 'mouse-face 'highlight
3695 'rear-nonsticky org-nonsticky-props
3696 'keymap org-mouse-map
3697 'help-echo "Radio target link"
3698 'org-linked-text t))
3699 t)))))
3701 (defun org-update-radio-target-regexp ()
3702 "Find all radio targets in this file and update the regular expression."
3703 (interactive)
3704 (when (memq 'radio org-activate-links)
3705 (setq org-target-link-regexp
3706 (org-make-target-link-regexp (org-all-targets 'radio)))
3707 (org-restart-font-lock)))
3709 (defun org-hide-wide-columns (limit)
3710 (let (s e)
3711 (setq s (text-property-any (point) (or limit (point-max))
3712 'org-cwidth t))
3713 (when s
3714 (setq e (next-single-property-change s 'org-cwidth))
3715 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3716 (goto-char e)
3717 t)))
3719 (defvar org-latex-and-specials-regexp nil
3720 "Regular expression for highlighting export special stuff.")
3721 (defvar org-match-substring-regexp)
3722 (defvar org-match-substring-with-braces-regexp)
3723 (defvar org-export-html-special-string-regexps)
3725 (defun org-compute-latex-and-specials-regexp ()
3726 "Compute regular expression for stuff treated specially by exporters."
3727 (if (not org-highlight-latex-fragments-and-specials)
3728 (org-set-local 'org-latex-and-specials-regexp nil)
3729 (require 'org-exp)
3730 (let*
3731 ((matchers (plist-get org-format-latex-options :matchers))
3732 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3733 org-latex-regexps)))
3734 (options (org-combine-plists (org-default-export-plist)
3735 (org-infile-export-plist)))
3736 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3737 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3738 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3739 (org-export-html-expand (plist-get options :expand-quoted-html))
3740 (org-export-with-special-strings (plist-get options :special-strings))
3741 (re-sub
3742 (cond
3743 ((equal org-export-with-sub-superscripts '{})
3744 (list org-match-substring-with-braces-regexp))
3745 (org-export-with-sub-superscripts
3746 (list org-match-substring-regexp))
3747 (t nil)))
3748 (re-latex
3749 (if org-export-with-LaTeX-fragments
3750 (mapcar (lambda (x) (nth 1 x)) latexs)))
3751 (re-macros
3752 (if org-export-with-TeX-macros
3753 (list (concat "\\\\"
3754 (regexp-opt
3755 (append (mapcar 'car org-html-entities)
3756 (if (boundp 'org-latex-entities)
3757 org-latex-entities nil))
3758 'words))) ; FIXME
3760 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3761 (re-special (if org-export-with-special-strings
3762 (mapcar (lambda (x) (car x))
3763 org-export-html-special-string-regexps)))
3764 (re-rest
3765 (delq nil
3766 (list
3767 (if org-export-html-expand "@<[^>\n]+>")
3768 ))))
3769 (org-set-local
3770 'org-latex-and-specials-regexp
3771 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3772 re-rest) "\\|")))))
3774 (defun org-do-latex-and-special-faces (limit)
3775 "Run through the buffer and add overlays to links."
3776 (when org-latex-and-specials-regexp
3777 (let (rtn d)
3778 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3779 limit t))
3780 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3781 'face))
3782 '(org-code org-verbatim underline)))
3783 (progn
3784 (setq rtn t
3785 d (cond ((member (char-after (1+ (match-beginning 0)))
3786 '(?_ ?^)) 1)
3787 (t 0)))
3788 (font-lock-prepend-text-property
3789 (+ d (match-beginning 0)) (match-end 0)
3790 'face 'org-latex-and-export-specials)
3791 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3792 '(font-lock-multiline t)))))
3793 rtn)))
3795 (defun org-restart-font-lock ()
3796 "Restart font-lock-mode, to force refontification."
3797 (when (and (boundp 'font-lock-mode) font-lock-mode)
3798 (font-lock-mode -1)
3799 (font-lock-mode 1)))
3801 (defun org-all-targets (&optional radio)
3802 "Return a list of all targets in this file.
3803 With optional argument RADIO, only find radio targets."
3804 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3805 rtn)
3806 (save-excursion
3807 (goto-char (point-min))
3808 (while (re-search-forward re nil t)
3809 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3810 rtn)))
3812 (defun org-make-target-link-regexp (targets)
3813 "Make regular expression matching all strings in TARGETS.
3814 The regular expression finds the targets also if there is a line break
3815 between words."
3816 (and targets
3817 (concat
3818 "\\<\\("
3819 (mapconcat
3820 (lambda (x)
3821 (while (string-match " +" x)
3822 (setq x (replace-match "\\s-+" t t x)))
3824 targets
3825 "\\|")
3826 "\\)\\>")))
3828 (defun org-activate-tags (limit)
3829 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3830 (progn
3831 (add-text-properties (match-beginning 1) (match-end 1)
3832 (list 'mouse-face 'highlight
3833 'rear-nonsticky org-nonsticky-props
3834 'keymap org-mouse-map))
3835 t)))
3837 (defun org-outline-level ()
3838 (save-excursion
3839 (looking-at outline-regexp)
3840 (if (match-beginning 1)
3841 (+ (org-get-string-indentation (match-string 1)) 1000)
3842 (1- (- (match-end 0) (match-beginning 0))))))
3844 (defvar org-font-lock-keywords nil)
3846 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3847 "Regular expression matching a property line.")
3849 (defvar org-font-lock-hook nil
3850 "Functions to be called for special font lock stuff.")
3852 (defun org-font-lock-hook (limit)
3853 (run-hook-with-args 'org-font-lock-hook limit))
3855 (defun org-set-font-lock-defaults ()
3856 (let* ((em org-fontify-emphasized-text)
3857 (lk org-activate-links)
3858 (org-font-lock-extra-keywords
3859 (list
3860 ;; Call the hook
3861 '(org-font-lock-hook)
3862 ;; Headlines
3863 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3864 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3865 ;; Table lines
3866 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3867 (1 'org-table t))
3868 ;; Table internals
3869 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3870 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3871 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3872 ;; Drawers
3873 (list org-drawer-regexp '(0 'org-special-keyword t))
3874 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3875 ;; Properties
3876 (list org-property-re
3877 '(1 'org-special-keyword t)
3878 '(3 'org-property-value t))
3879 (if org-format-transports-properties-p
3880 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3881 ;; Links
3882 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3883 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3884 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3885 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3886 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3887 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3888 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3889 '(org-hide-wide-columns (0 nil append))
3890 ;; TODO lines
3891 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3892 '(1 (org-get-todo-face 1) t))
3893 ;; DONE
3894 (if org-fontify-done-headline
3895 (list (concat "^[*]+ +\\<\\("
3896 (mapconcat 'regexp-quote org-done-keywords "\\|")
3897 "\\)\\(.*\\)")
3898 '(2 'org-headline-done t))
3899 nil)
3900 ;; Priorities
3901 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3902 ;; Special keywords
3903 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3904 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3905 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3906 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3907 ;; Emphasis
3908 (if em
3909 (if (featurep 'xemacs)
3910 '(org-do-emphasis-faces (0 nil append))
3911 '(org-do-emphasis-faces)))
3912 ;; Checkboxes
3913 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3914 2 'bold prepend)
3915 (if org-provide-checkbox-statistics
3916 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3917 (0 (org-get-checkbox-statistics-face) t)))
3918 ;; Description list items
3919 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3920 2 'bold prepend)
3921 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3922 '(1 'org-archived prepend))
3923 ;; Specials
3924 '(org-do-latex-and-special-faces)
3925 ;; Code
3926 '(org-activate-code (1 'org-code t))
3927 ;; COMMENT
3928 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3929 "\\|" org-quote-string "\\)\\>")
3930 '(1 'org-special-keyword t))
3931 '("^#.*" (0 'font-lock-comment-face t))
3933 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3934 ;; Now set the full font-lock-keywords
3935 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3936 (org-set-local 'font-lock-defaults
3937 '(org-font-lock-keywords t nil nil backward-paragraph))
3938 (kill-local-variable 'font-lock-keywords) nil))
3940 (defvar org-m nil)
3941 (defvar org-l nil)
3942 (defvar org-f nil)
3943 (defun org-get-level-face (n)
3944 "Get the right face for match N in font-lock matching of healdines."
3945 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3946 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3947 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3948 (cond
3949 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3950 ((eq n 2) org-f)
3951 (t (if org-level-color-stars-only nil org-f))))
3953 (defun org-get-todo-face (kwd)
3954 "Get the right face for a TODO keyword KWD.
3955 If KWD is a number, get the corresponding match group."
3956 (if (numberp kwd) (setq kwd (match-string kwd)))
3957 (or (cdr (assoc kwd org-todo-keyword-faces))
3958 (and (member kwd org-done-keywords) 'org-done)
3959 'org-todo))
3961 (defun org-unfontify-region (beg end &optional maybe_loudly)
3962 "Remove fontification and activation overlays from links."
3963 (font-lock-default-unfontify-region beg end)
3964 (let* ((buffer-undo-list t)
3965 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3966 (inhibit-modification-hooks t)
3967 deactivate-mark buffer-file-name buffer-file-truename)
3968 (remove-text-properties beg end
3969 '(mouse-face t keymap t org-linked-text t
3970 invisible t intangible t))))
3972 ;;;; Visibility cycling, including org-goto and indirect buffer
3974 ;;; Cycling
3976 (defvar org-cycle-global-status nil)
3977 (make-variable-buffer-local 'org-cycle-global-status)
3978 (defvar org-cycle-subtree-status nil)
3979 (make-variable-buffer-local 'org-cycle-subtree-status)
3981 ;;;###autoload
3982 (defun org-cycle (&optional arg)
3983 "Visibility cycling for Org-mode.
3985 - When this function is called with a prefix argument, rotate the entire
3986 buffer through 3 states (global cycling)
3987 1. OVERVIEW: Show only top-level headlines.
3988 2. CONTENTS: Show all headlines of all levels, but no body text.
3989 3. SHOW ALL: Show everything.
3990 When called with two C-u C-u prefixes, switch to the startup visibility,
3991 determined by the variable `org-startup-folded', and by any VISIBILITY
3992 properties in the buffer.
3993 When called with three C-u C-u C-u prefixed, show the entire buffer,
3994 including drawers.
3996 - When point is at the beginning of a headline, rotate the subtree started
3997 by this line through 3 different states (local cycling)
3998 1. FOLDED: Only the main headline is shown.
3999 2. CHILDREN: The main headline and the direct children are shown.
4000 From this state, you can move to one of the children
4001 and zoom in further.
4002 3. SUBTREE: Show the entire subtree, including body text.
4004 - When there is a numeric prefix, go up to a heading with level ARG, do
4005 a `show-subtree' and return to the previous cursor position. If ARG
4006 is negative, go up that many levels.
4008 - When point is not at the beginning of a headline, execute the global
4009 binding for TAB, which is re-indenting the line. See the option
4010 `org-cycle-emulate-tab' for details.
4012 - Special case: if point is at the beginning of the buffer and there is
4013 no headline in line 1, this function will act as if called with prefix arg.
4014 But only if also the variable `org-cycle-global-at-bob' is t."
4015 (interactive "P")
4016 (org-load-modules-maybe)
4017 (let* ((outline-regexp
4018 (if (and (org-mode-p) org-cycle-include-plain-lists)
4019 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4020 outline-regexp))
4021 (bob-special (and org-cycle-global-at-bob (bobp)
4022 (not (looking-at outline-regexp))))
4023 (org-cycle-hook
4024 (if bob-special
4025 (delq 'org-optimize-window-after-visibility-change
4026 (copy-sequence org-cycle-hook))
4027 org-cycle-hook))
4028 (pos (point)))
4030 (if (or bob-special (equal arg '(4)))
4031 ;; special case: use global cycling
4032 (setq arg t))
4034 (cond
4036 ((equal arg '(16))
4037 (org-set-startup-visibility)
4038 (message "Startup visibility, plus VISIBILITY properties"))
4040 ((equal arg '(64))
4041 (show-all)
4042 (message "Entire buffer visible, including drawers"))
4044 ((org-at-table-p 'any)
4045 ;; Enter the table or move to the next field in the table
4046 (or (org-table-recognize-table.el)
4047 (progn
4048 (if arg (org-table-edit-field t)
4049 (org-table-justify-field-maybe)
4050 (call-interactively 'org-table-next-field)))))
4052 ((eq arg t) ;; Global cycling
4054 (cond
4055 ((and (eq last-command this-command)
4056 (eq org-cycle-global-status 'overview))
4057 ;; We just created the overview - now do table of contents
4058 ;; This can be slow in very large buffers, so indicate action
4059 (message "CONTENTS...")
4060 (org-content)
4061 (message "CONTENTS...done")
4062 (setq org-cycle-global-status 'contents)
4063 (run-hook-with-args 'org-cycle-hook 'contents))
4065 ((and (eq last-command this-command)
4066 (eq org-cycle-global-status 'contents))
4067 ;; We just showed the table of contents - now show everything
4068 (show-all)
4069 (message "SHOW ALL")
4070 (setq org-cycle-global-status 'all)
4071 (run-hook-with-args 'org-cycle-hook 'all))
4074 ;; Default action: go to overview
4075 (org-overview)
4076 (message "OVERVIEW")
4077 (setq org-cycle-global-status 'overview)
4078 (run-hook-with-args 'org-cycle-hook 'overview))))
4080 ((and org-drawers org-drawer-regexp
4081 (save-excursion
4082 (beginning-of-line 1)
4083 (looking-at org-drawer-regexp)))
4084 ;; Toggle block visibility
4085 (org-flag-drawer
4086 (not (get-char-property (match-end 0) 'invisible))))
4088 ((integerp arg)
4089 ;; Show-subtree, ARG levels up from here.
4090 (save-excursion
4091 (org-back-to-heading)
4092 (outline-up-heading (if (< arg 0) (- arg)
4093 (- (funcall outline-level) arg)))
4094 (org-show-subtree)))
4096 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4097 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4098 ;; At a heading: rotate between three different views
4099 (org-back-to-heading)
4100 (let ((goal-column 0) eoh eol eos)
4101 ;; First, some boundaries
4102 (save-excursion
4103 (org-back-to-heading)
4104 (save-excursion
4105 (beginning-of-line 2)
4106 (while (and (not (eobp)) ;; this is like `next-line'
4107 (get-char-property (1- (point)) 'invisible))
4108 (beginning-of-line 2)) (setq eol (point)))
4109 (outline-end-of-heading) (setq eoh (point))
4110 (org-end-of-subtree t)
4111 (unless (eobp)
4112 (skip-chars-forward " \t\n")
4113 (beginning-of-line 1) ; in case this is an item
4115 (setq eos (1- (point))))
4116 ;; Find out what to do next and set `this-command'
4117 (cond
4118 ((= eos eoh)
4119 ;; Nothing is hidden behind this heading
4120 (message "EMPTY ENTRY")
4121 (setq org-cycle-subtree-status nil)
4122 (save-excursion
4123 (goto-char eos)
4124 (outline-next-heading)
4125 (if (org-invisible-p) (org-flag-heading nil))))
4126 ((or (>= eol eos)
4127 (not (string-match "\\S-" (buffer-substring eol eos))))
4128 ;; Entire subtree is hidden in one line: open it
4129 (org-show-entry)
4130 (show-children)
4131 (message "CHILDREN")
4132 (save-excursion
4133 (goto-char eos)
4134 (outline-next-heading)
4135 (if (org-invisible-p) (org-flag-heading nil)))
4136 (setq org-cycle-subtree-status 'children)
4137 (run-hook-with-args 'org-cycle-hook 'children))
4138 ((and (eq last-command this-command)
4139 (eq org-cycle-subtree-status 'children))
4140 ;; We just showed the children, now show everything.
4141 (org-show-subtree)
4142 (message "SUBTREE")
4143 (setq org-cycle-subtree-status 'subtree)
4144 (run-hook-with-args 'org-cycle-hook 'subtree))
4146 ;; Default action: hide the subtree.
4147 (hide-subtree)
4148 (message "FOLDED")
4149 (setq org-cycle-subtree-status 'folded)
4150 (run-hook-with-args 'org-cycle-hook 'folded)))))
4152 ;; TAB emulation and template completion
4153 (buffer-read-only (org-back-to-heading))
4155 ((org-try-structure-completion))
4157 ((org-try-cdlatex-tab))
4159 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4160 (or (not (bolp))
4161 (not (looking-at outline-regexp))))
4162 (call-interactively (global-key-binding "\t")))
4164 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4165 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4166 (or (and (eq org-cycle-emulate-tab 'white)
4167 (= (match-end 0) (point-at-eol)))
4168 (and (eq org-cycle-emulate-tab 'whitestart)
4169 (>= (match-end 0) pos))))
4171 (eq org-cycle-emulate-tab t))
4172 (call-interactively (global-key-binding "\t")))
4174 (t (save-excursion
4175 (org-back-to-heading)
4176 (org-cycle))))))
4178 ;;;###autoload
4179 (defun org-global-cycle (&optional arg)
4180 "Cycle the global visibility. For details see `org-cycle'.
4181 With C-u prefix arg, switch to startup visibility.
4182 With a numeric prefix, show all headlines up to that level."
4183 (interactive "P")
4184 (let ((org-cycle-include-plain-lists
4185 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4186 (cond
4187 ((integerp arg)
4188 (show-all)
4189 (hide-sublevels arg)
4190 (setq org-cycle-global-status 'contents))
4191 ((equal arg '(4))
4192 (org-set-startup-visibility)
4193 (message "Startup visibility, plus VISIBILITY properties."))
4195 (org-cycle '(4))))))
4197 (defun org-set-startup-visibility ()
4198 "Set the visibility required by startup options and properties."
4199 (cond
4200 ((eq org-startup-folded t)
4201 (org-cycle '(4)))
4202 ((eq org-startup-folded 'content)
4203 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4204 (org-cycle '(4)) (org-cycle '(4)))))
4205 (org-set-visibility-according-to-property 'no-cleanup)
4206 (org-cycle-hide-archived-subtrees 'all)
4207 (org-cycle-hide-drawers 'all)
4208 (org-cycle-show-empty-lines 'all))
4210 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4211 "Switch subtree visibilities according to :VISIBILITY: property."
4212 (interactive)
4213 (let (state)
4214 (save-excursion
4215 (goto-char (point-min))
4216 (while (re-search-forward
4217 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4218 nil t)
4219 (setq state (match-string 1))
4220 (save-excursion
4221 (org-back-to-heading t)
4222 (hide-subtree)
4223 (org-reveal)
4224 (cond
4225 ((equal state '("fold" "folded"))
4226 (hide-subtree))
4227 ((equal state "children")
4228 (org-show-hidden-entry)
4229 (show-children))
4230 ((equal state "content")
4231 (save-excursion
4232 (save-restriction
4233 (org-narrow-to-subtree)
4234 (org-content))))
4235 ((member state '("all" "showall"))
4236 (show-subtree)))))
4237 (unless no-cleanup
4238 (org-cycle-hide-archived-subtrees 'all)
4239 (org-cycle-hide-drawers 'all)
4240 (org-cycle-show-empty-lines 'all)))))
4242 (defun org-overview ()
4243 "Switch to overview mode, shoing only top-level headlines.
4244 Really, this shows all headlines with level equal or greater than the level
4245 of the first headline in the buffer. This is important, because if the
4246 first headline is not level one, then (hide-sublevels 1) gives confusing
4247 results."
4248 (interactive)
4249 (let ((level (save-excursion
4250 (goto-char (point-min))
4251 (if (re-search-forward (concat "^" outline-regexp) nil t)
4252 (progn
4253 (goto-char (match-beginning 0))
4254 (funcall outline-level))))))
4255 (and level (hide-sublevels level))))
4257 (defun org-content (&optional arg)
4258 "Show all headlines in the buffer, like a table of contents.
4259 With numerical argument N, show content up to level N."
4260 (interactive "P")
4261 (save-excursion
4262 ;; Visit all headings and show their offspring
4263 (and (integerp arg) (org-overview))
4264 (goto-char (point-max))
4265 (catch 'exit
4266 (while (and (progn (condition-case nil
4267 (outline-previous-visible-heading 1)
4268 (error (goto-char (point-min))))
4270 (looking-at outline-regexp))
4271 (if (integerp arg)
4272 (show-children (1- arg))
4273 (show-branches))
4274 (if (bobp) (throw 'exit nil))))))
4277 (defun org-optimize-window-after-visibility-change (state)
4278 "Adjust the window after a change in outline visibility.
4279 This function is the default value of the hook `org-cycle-hook'."
4280 (when (get-buffer-window (current-buffer))
4281 (cond
4282 ; ((eq state 'overview) (org-first-headline-recenter 1))
4283 ; ((eq state 'overview) (org-beginning-of-line))
4284 ((eq state 'content) nil)
4285 ((eq state 'all) nil)
4286 ((eq state 'folded) nil)
4287 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4288 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4290 (defun org-compact-display-after-subtree-move ()
4291 (let (beg end)
4292 (save-excursion
4293 (if (org-up-heading-safe)
4294 (progn
4295 (hide-subtree)
4296 (show-entry)
4297 (show-children)
4298 (org-cycle-show-empty-lines 'children)
4299 (org-cycle-hide-drawers 'children))
4300 (org-overview)))))
4302 (defun org-cycle-show-empty-lines (state)
4303 "Show empty lines above all visible headlines.
4304 The region to be covered depends on STATE when called through
4305 `org-cycle-hook'. Lisp program can use t for STATE to get the
4306 entire buffer covered. Note that an empty line is only shown if there
4307 are at least `org-cycle-separator-lines' empty lines before the headeline."
4308 (when (> org-cycle-separator-lines 0)
4309 (save-excursion
4310 (let* ((n org-cycle-separator-lines)
4311 (re (cond
4312 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4313 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4314 (t (let ((ns (number-to-string (- n 2))))
4315 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4316 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4317 beg end)
4318 (cond
4319 ((memq state '(overview contents t))
4320 (setq beg (point-min) end (point-max)))
4321 ((memq state '(children folded))
4322 (setq beg (point) end (progn (org-end-of-subtree t t)
4323 (beginning-of-line 2)
4324 (point)))))
4325 (when beg
4326 (goto-char beg)
4327 (while (re-search-forward re end t)
4328 (if (not (get-char-property (match-end 1) 'invisible))
4329 (outline-flag-region
4330 (match-beginning 1) (match-end 1) nil)))))))
4331 ;; Never hide empty lines at the end of the file.
4332 (save-excursion
4333 (goto-char (point-max))
4334 (outline-previous-heading)
4335 (outline-end-of-heading)
4336 (if (and (looking-at "[ \t\n]+")
4337 (= (match-end 0) (point-max)))
4338 (outline-flag-region (point) (match-end 0) nil))))
4340 (defun org-show-empty-lines-in-parent ()
4341 "Move to the parent and re-show empty lines before visible headlines."
4342 (save-excursion
4343 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4344 (org-cycle-show-empty-lines context))))
4346 (defun org-cycle-hide-drawers (state)
4347 "Re-hide all drawers after a visibility state change."
4348 (when (and (org-mode-p)
4349 (not (memq state '(overview folded))))
4350 (save-excursion
4351 (let* ((globalp (memq state '(contents all)))
4352 (beg (if globalp (point-min) (point)))
4353 (end (if globalp (point-max) (org-end-of-subtree t))))
4354 (goto-char beg)
4355 (while (re-search-forward org-drawer-regexp end t)
4356 (org-flag-drawer t))))))
4358 (defun org-flag-drawer (flag)
4359 (save-excursion
4360 (beginning-of-line 1)
4361 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4362 (let ((b (match-end 0))
4363 (outline-regexp org-outline-regexp))
4364 (if (re-search-forward
4365 "^[ \t]*:END:"
4366 (save-excursion (outline-next-heading) (point)) t)
4367 (outline-flag-region b (point-at-eol) flag)
4368 (error ":END: line missing"))))))
4370 (defun org-subtree-end-visible-p ()
4371 "Is the end of the current subtree visible?"
4372 (pos-visible-in-window-p
4373 (save-excursion (org-end-of-subtree t) (point))))
4375 (defun org-first-headline-recenter (&optional N)
4376 "Move cursor to the first headline and recenter the headline.
4377 Optional argument N means, put the headline into the Nth line of the window."
4378 (goto-char (point-min))
4379 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4380 (beginning-of-line)
4381 (recenter (prefix-numeric-value N))))
4383 ;;; Org-goto
4385 (defvar org-goto-window-configuration nil)
4386 (defvar org-goto-marker nil)
4387 (defvar org-goto-map
4388 (let ((map (make-sparse-keymap)))
4389 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4390 (while (setq cmd (pop cmds))
4391 (substitute-key-definition cmd cmd map global-map)))
4392 (suppress-keymap map)
4393 (org-defkey map "\C-m" 'org-goto-ret)
4394 (org-defkey map [(return)] 'org-goto-ret)
4395 (org-defkey map [(left)] 'org-goto-left)
4396 (org-defkey map [(right)] 'org-goto-right)
4397 (org-defkey map [(control ?g)] 'org-goto-quit)
4398 (org-defkey map "\C-i" 'org-cycle)
4399 (org-defkey map [(tab)] 'org-cycle)
4400 (org-defkey map [(down)] 'outline-next-visible-heading)
4401 (org-defkey map [(up)] 'outline-previous-visible-heading)
4402 (if org-goto-auto-isearch
4403 (if (fboundp 'define-key-after)
4404 (define-key-after map [t] 'org-goto-local-auto-isearch)
4405 nil)
4406 (org-defkey map "q" 'org-goto-quit)
4407 (org-defkey map "n" 'outline-next-visible-heading)
4408 (org-defkey map "p" 'outline-previous-visible-heading)
4409 (org-defkey map "f" 'outline-forward-same-level)
4410 (org-defkey map "b" 'outline-backward-same-level)
4411 (org-defkey map "u" 'outline-up-heading))
4412 (org-defkey map "/" 'org-occur)
4413 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4414 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4415 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4416 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4417 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4418 map))
4420 (defconst org-goto-help
4421 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4422 RET=jump to location [Q]uit and return to previous location
4423 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4425 (defvar org-goto-start-pos) ; dynamically scoped parameter
4427 ;; FIXME: Docstring doe not mention both interfaces
4428 (defun org-goto (&optional alternative-interface)
4429 "Look up a different location in the current file, keeping current visibility.
4431 When you want look-up or go to a different location in a document, the
4432 fastest way is often to fold the entire buffer and then dive into the tree.
4433 This method has the disadvantage, that the previous location will be folded,
4434 which may not be what you want.
4436 This command works around this by showing a copy of the current buffer
4437 in an indirect buffer, in overview mode. You can dive into the tree in
4438 that copy, use org-occur and incremental search to find a location.
4439 When pressing RET or `Q', the command returns to the original buffer in
4440 which the visibility is still unchanged. After RET is will also jump to
4441 the location selected in the indirect buffer and expose the
4442 the headline hierarchy above."
4443 (interactive "P")
4444 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4445 (org-refile-use-outline-path t)
4446 (interface
4447 (if (not alternative-interface)
4448 org-goto-interface
4449 (if (eq org-goto-interface 'outline)
4450 'outline-path-completion
4451 'outline)))
4452 (org-goto-start-pos (point))
4453 (selected-point
4454 (if (eq interface 'outline)
4455 (car (org-get-location (current-buffer) org-goto-help))
4456 (nth 3 (org-refile-get-location "Goto: ")))))
4457 (if selected-point
4458 (progn
4459 (org-mark-ring-push org-goto-start-pos)
4460 (goto-char selected-point)
4461 (if (or (org-invisible-p) (org-invisible-p2))
4462 (org-show-context 'org-goto)))
4463 (message "Quit"))))
4465 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4466 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4467 (defvar org-goto-local-auto-isearch-map) ; defined below
4469 (defun org-get-location (buf help)
4470 "Let the user select a location in the Org-mode buffer BUF.
4471 This function uses a recursive edit. It returns the selected position
4472 or nil."
4473 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4474 (isearch-hide-immediately nil)
4475 (isearch-search-fun-function
4476 (lambda () 'org-goto-local-search-headings))
4477 (org-goto-selected-point org-goto-exit-command))
4478 (save-excursion
4479 (save-window-excursion
4480 (delete-other-windows)
4481 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4482 (switch-to-buffer
4483 (condition-case nil
4484 (make-indirect-buffer (current-buffer) "*org-goto*")
4485 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4486 (with-output-to-temp-buffer "*Help*"
4487 (princ help))
4488 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4489 (setq buffer-read-only nil)
4490 (let ((org-startup-truncated t)
4491 (org-startup-folded nil)
4492 (org-startup-align-all-tables nil))
4493 (org-mode)
4494 (org-overview))
4495 (setq buffer-read-only t)
4496 (if (and (boundp 'org-goto-start-pos)
4497 (integer-or-marker-p org-goto-start-pos))
4498 (let ((org-show-hierarchy-above t)
4499 (org-show-siblings t)
4500 (org-show-following-heading t))
4501 (goto-char org-goto-start-pos)
4502 (and (org-invisible-p) (org-show-context)))
4503 (goto-char (point-min)))
4504 (org-beginning-of-line)
4505 (message "Select location and press RET")
4506 (use-local-map org-goto-map)
4507 (recursive-edit)
4509 (kill-buffer "*org-goto*")
4510 (cons org-goto-selected-point org-goto-exit-command)))
4512 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4513 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4514 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4515 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4517 (defun org-goto-local-search-headings (string bound noerror)
4518 "Search and make sure that any matches are in headlines."
4519 (catch 'return
4520 (while (if isearch-forward
4521 (search-forward string bound noerror)
4522 (search-backward string bound noerror))
4523 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4524 (and (member :headline context)
4525 (not (member :tags context))))
4526 (throw 'return (point))))))
4528 (defun org-goto-local-auto-isearch ()
4529 "Start isearch."
4530 (interactive)
4531 (goto-char (point-min))
4532 (let ((keys (this-command-keys)))
4533 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4534 (isearch-mode t)
4535 (isearch-process-search-char (string-to-char keys)))))
4537 (defun org-goto-ret (&optional arg)
4538 "Finish `org-goto' by going to the new location."
4539 (interactive "P")
4540 (setq org-goto-selected-point (point)
4541 org-goto-exit-command 'return)
4542 (throw 'exit nil))
4544 (defun org-goto-left ()
4545 "Finish `org-goto' by going to the new location."
4546 (interactive)
4547 (if (org-on-heading-p)
4548 (progn
4549 (beginning-of-line 1)
4550 (setq org-goto-selected-point (point)
4551 org-goto-exit-command 'left)
4552 (throw 'exit nil))
4553 (error "Not on a heading")))
4555 (defun org-goto-right ()
4556 "Finish `org-goto' by going to the new location."
4557 (interactive)
4558 (if (org-on-heading-p)
4559 (progn
4560 (setq org-goto-selected-point (point)
4561 org-goto-exit-command 'right)
4562 (throw 'exit nil))
4563 (error "Not on a heading")))
4565 (defun org-goto-quit ()
4566 "Finish `org-goto' without cursor motion."
4567 (interactive)
4568 (setq org-goto-selected-point nil)
4569 (setq org-goto-exit-command 'quit)
4570 (throw 'exit nil))
4572 ;;; Indirect buffer display of subtrees
4574 (defvar org-indirect-dedicated-frame nil
4575 "This is the frame being used for indirect tree display.")
4576 (defvar org-last-indirect-buffer nil)
4578 (defun org-tree-to-indirect-buffer (&optional arg)
4579 "Create indirect buffer and narrow it to current subtree.
4580 With numerical prefix ARG, go up to this level and then take that tree.
4581 If ARG is negative, go up that many levels.
4582 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4583 indirect buffer previously made with this command, to avoid proliferation of
4584 indirect buffers. However, when you call the command with a `C-u' prefix, or
4585 when `org-indirect-buffer-display' is `new-frame', the last buffer
4586 is kept so that you can work with several indirect buffers at the same time.
4587 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4588 requests that a new frame be made for the new buffer, so that the dedicated
4589 frame is not changed."
4590 (interactive "P")
4591 (let ((cbuf (current-buffer))
4592 (cwin (selected-window))
4593 (pos (point))
4594 beg end level heading ibuf)
4595 (save-excursion
4596 (org-back-to-heading t)
4597 (when (numberp arg)
4598 (setq level (org-outline-level))
4599 (if (< arg 0) (setq arg (+ level arg)))
4600 (while (> (setq level (org-outline-level)) arg)
4601 (outline-up-heading 1 t)))
4602 (setq beg (point)
4603 heading (org-get-heading))
4604 (org-end-of-subtree t) (setq end (point)))
4605 (if (and (buffer-live-p org-last-indirect-buffer)
4606 (not (eq org-indirect-buffer-display 'new-frame))
4607 (not arg))
4608 (kill-buffer org-last-indirect-buffer))
4609 (setq ibuf (org-get-indirect-buffer cbuf)
4610 org-last-indirect-buffer ibuf)
4611 (cond
4612 ((or (eq org-indirect-buffer-display 'new-frame)
4613 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4614 (select-frame (make-frame))
4615 (delete-other-windows)
4616 (switch-to-buffer ibuf)
4617 (org-set-frame-title heading))
4618 ((eq org-indirect-buffer-display 'dedicated-frame)
4619 (raise-frame
4620 (select-frame (or (and org-indirect-dedicated-frame
4621 (frame-live-p org-indirect-dedicated-frame)
4622 org-indirect-dedicated-frame)
4623 (setq org-indirect-dedicated-frame (make-frame)))))
4624 (delete-other-windows)
4625 (switch-to-buffer ibuf)
4626 (org-set-frame-title (concat "Indirect: " heading)))
4627 ((eq org-indirect-buffer-display 'current-window)
4628 (switch-to-buffer ibuf))
4629 ((eq org-indirect-buffer-display 'other-window)
4630 (pop-to-buffer ibuf))
4631 (t (error "Invalid value.")))
4632 (if (featurep 'xemacs)
4633 (save-excursion (org-mode) (turn-on-font-lock)))
4634 (narrow-to-region beg end)
4635 (show-all)
4636 (goto-char pos)
4637 (and (window-live-p cwin) (select-window cwin))))
4639 (defun org-get-indirect-buffer (&optional buffer)
4640 (setq buffer (or buffer (current-buffer)))
4641 (let ((n 1) (base (buffer-name buffer)) bname)
4642 (while (buffer-live-p
4643 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4644 (setq n (1+ n)))
4645 (condition-case nil
4646 (make-indirect-buffer buffer bname 'clone)
4647 (error (make-indirect-buffer buffer bname)))))
4649 (defun org-set-frame-title (title)
4650 "Set the title of the current frame to the string TITLE."
4651 ;; FIXME: how to name a single frame in XEmacs???
4652 (unless (featurep 'xemacs)
4653 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4655 ;;;; Structure editing
4657 ;;; Inserting headlines
4659 (defun org-insert-heading (&optional force-heading)
4660 "Insert a new heading or item with same depth at point.
4661 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4662 If point is at the beginning of a headline, insert a sibling before the
4663 current headline. If point is not at the beginning, do not split the line,
4664 but create the new headline after the current line."
4665 (interactive "P")
4666 (if (= (buffer-size) 0)
4667 (insert "\n* ")
4668 (when (or force-heading (not (org-insert-item)))
4669 (let* ((head (save-excursion
4670 (condition-case nil
4671 (progn
4672 (org-back-to-heading)
4673 (match-string 0))
4674 (error "*"))))
4675 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4676 pos hide-previous previous-pos)
4677 (cond
4678 ((and (org-on-heading-p) (bolp)
4679 (or (bobp)
4680 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4681 ;; insert before the current line
4682 (open-line (if blank 2 1)))
4683 ((and (bolp)
4684 (or (bobp)
4685 (save-excursion
4686 (backward-char 1) (not (org-invisible-p)))))
4687 ;; insert right here
4688 nil)
4690 ;; somewhere in the line
4691 (save-excursion
4692 (setq previous-pos (point-at-bol))
4693 (end-of-line)
4694 (setq hide-previous (org-invisible-p)))
4695 (and org-insert-heading-respect-content (org-show-subtree))
4696 (let ((split
4697 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4698 (save-excursion
4699 (let ((p (point)))
4700 (goto-char (point-at-bol))
4701 (and (looking-at org-complex-heading-regexp)
4702 (> p (match-beginning 4)))))))
4703 tags pos)
4704 (cond
4705 (org-insert-heading-respect-content
4706 (org-end-of-subtree nil t)
4707 (or (bolp) (newline))
4708 (open-line 1))
4709 ((org-on-heading-p)
4710 (when hide-previous
4711 (show-children)
4712 (org-show-entry))
4713 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4714 (setq tags (and (match-end 2) (match-string 2)))
4715 (and (match-end 1)
4716 (delete-region (match-beginning 1) (match-end 1)))
4717 (setq pos (point-at-bol))
4718 (or split (end-of-line 1))
4719 (delete-horizontal-space)
4720 (newline (if blank 2 1))
4721 (when tags
4722 (save-excursion
4723 (goto-char pos)
4724 (end-of-line 1)
4725 (insert " " tags)
4726 (org-set-tags nil 'align))))
4728 (or split (end-of-line 1))
4729 (newline (if blank 2 1)))))))
4730 (insert head) (just-one-space)
4731 (setq pos (point))
4732 (end-of-line 1)
4733 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4734 (when (and org-insert-heading-respect-content hide-previous)
4735 (save-excursion
4736 (goto-char previous-pos)
4737 (hide-subtree)))
4738 (run-hooks 'org-insert-heading-hook)))))
4740 (defun org-get-heading (&optional no-tags)
4741 "Return the heading of the current entry, without the stars."
4742 (save-excursion
4743 (org-back-to-heading t)
4744 (if (looking-at
4745 (if no-tags
4746 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4747 "\\*+[ \t]+\\([^\r\n]*\\)"))
4748 (match-string 1) "")))
4750 (defun org-insert-heading-after-current ()
4751 "Insert a new heading with same level as current, after current subtree."
4752 (interactive)
4753 (org-back-to-heading)
4754 (org-insert-heading)
4755 (org-move-subtree-down)
4756 (end-of-line 1))
4758 (defun org-insert-heading-respect-content ()
4759 (interactive)
4760 (let ((org-insert-heading-respect-content t))
4761 (org-insert-heading t)))
4763 (defun org-insert-todo-heading-respect-content (&optional force-state)
4764 (interactive "P")
4765 (let ((org-insert-heading-respect-content t))
4766 (org-insert-todo-heading force-state t)))
4768 (defun org-insert-todo-heading (arg &optional force-heading)
4769 "Insert a new heading with the same level and TODO state as current heading.
4770 If the heading has no TODO state, or if the state is DONE, use the first
4771 state (TODO by default). Also with prefix arg, force first state."
4772 (interactive "P")
4773 (when (or force-heading (not (org-insert-item 'checkbox)))
4774 (org-insert-heading force-heading)
4775 (save-excursion
4776 (org-back-to-heading)
4777 (outline-previous-heading)
4778 (looking-at org-todo-line-regexp))
4779 (if (or arg
4780 (not (match-beginning 2))
4781 (member (match-string 2) org-done-keywords))
4782 (insert (car org-todo-keywords-1) " ")
4783 (insert (match-string 2) " "))
4784 (when org-provide-todo-statistics
4785 (org-update-parent-todo-statistics))))
4787 (defun org-insert-subheading (arg)
4788 "Insert a new subheading and demote it.
4789 Works for outline headings and for plain lists alike."
4790 (interactive "P")
4791 (org-insert-heading arg)
4792 (cond
4793 ((org-on-heading-p) (org-do-demote))
4794 ((org-at-item-p) (org-indent-item 1))))
4796 (defun org-insert-todo-subheading (arg)
4797 "Insert a new subheading with TODO keyword or checkbox and demote it.
4798 Works for outline headings and for plain lists alike."
4799 (interactive "P")
4800 (org-insert-todo-heading arg)
4801 (cond
4802 ((org-on-heading-p) (org-do-demote))
4803 ((org-at-item-p) (org-indent-item 1))))
4805 ;;; Promotion and Demotion
4807 (defun org-promote-subtree ()
4808 "Promote the entire subtree.
4809 See also `org-promote'."
4810 (interactive)
4811 (save-excursion
4812 (org-map-tree 'org-promote))
4813 (org-fix-position-after-promote))
4815 (defun org-demote-subtree ()
4816 "Demote the entire subtree. See `org-demote'.
4817 See also `org-promote'."
4818 (interactive)
4819 (save-excursion
4820 (org-map-tree 'org-demote))
4821 (org-fix-position-after-promote))
4824 (defun org-do-promote ()
4825 "Promote the current heading higher up the tree.
4826 If the region is active in `transient-mark-mode', promote all headings
4827 in the region."
4828 (interactive)
4829 (save-excursion
4830 (if (org-region-active-p)
4831 (org-map-region 'org-promote (region-beginning) (region-end))
4832 (org-promote)))
4833 (org-fix-position-after-promote))
4835 (defun org-do-demote ()
4836 "Demote the current heading lower down the tree.
4837 If the region is active in `transient-mark-mode', demote all headings
4838 in the region."
4839 (interactive)
4840 (save-excursion
4841 (if (org-region-active-p)
4842 (org-map-region 'org-demote (region-beginning) (region-end))
4843 (org-demote)))
4844 (org-fix-position-after-promote))
4846 (defun org-fix-position-after-promote ()
4847 "Make sure that after pro/demotion cursor position is right."
4848 (let ((pos (point)))
4849 (when (save-excursion
4850 (beginning-of-line 1)
4851 (looking-at org-todo-line-regexp)
4852 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4853 (cond ((eobp) (insert " "))
4854 ((eolp) (insert " "))
4855 ((equal (char-after) ?\ ) (forward-char 1))))))
4857 (defun org-reduced-level (l)
4858 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4860 (defun org-get-valid-level (level &optional change)
4861 "Rectify a level change under the influence of `org-odd-levels-only'
4862 LEVEL is a current level, CHANGE is by how much the level should be
4863 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4864 even level numbers will become the next higher odd number."
4865 (if org-odd-levels-only
4866 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4867 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4868 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4869 (max 1 (+ level change))))
4871 (if (boundp 'define-obsolete-function-alias)
4872 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4873 (define-obsolete-function-alias 'org-get-legal-level
4874 'org-get-valid-level)
4875 (define-obsolete-function-alias 'org-get-legal-level
4876 'org-get-valid-level "23.1")))
4878 (defun org-promote ()
4879 "Promote the current heading higher up the tree.
4880 If the region is active in `transient-mark-mode', promote all headings
4881 in the region."
4882 (org-back-to-heading t)
4883 (let* ((level (save-match-data (funcall outline-level)))
4884 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4885 (diff (abs (- level (length up-head) -1))))
4886 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4887 (replace-match up-head nil t)
4888 ;; Fixup tag positioning
4889 (and org-auto-align-tags (org-set-tags nil t))
4890 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4892 (defun org-demote ()
4893 "Demote the current heading lower down the tree.
4894 If the region is active in `transient-mark-mode', demote all headings
4895 in the region."
4896 (org-back-to-heading t)
4897 (let* ((level (save-match-data (funcall outline-level)))
4898 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4899 (diff (abs (- level (length down-head) -1))))
4900 (replace-match down-head nil t)
4901 ;; Fixup tag positioning
4902 (and org-auto-align-tags (org-set-tags nil t))
4903 (if org-adapt-indentation (org-fixup-indentation diff))))
4905 (defun org-map-tree (fun)
4906 "Call FUN for every heading underneath the current one."
4907 (org-back-to-heading)
4908 (let ((level (funcall outline-level)))
4909 (save-excursion
4910 (funcall fun)
4911 (while (and (progn
4912 (outline-next-heading)
4913 (> (funcall outline-level) level))
4914 (not (eobp)))
4915 (funcall fun)))))
4917 (defun org-map-region (fun beg end)
4918 "Call FUN for every heading between BEG and END."
4919 (let ((org-ignore-region t))
4920 (save-excursion
4921 (setq end (copy-marker end))
4922 (goto-char beg)
4923 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4924 (< (point) end))
4925 (funcall fun))
4926 (while (and (progn
4927 (outline-next-heading)
4928 (< (point) end))
4929 (not (eobp)))
4930 (funcall fun)))))
4932 (defun org-fixup-indentation (diff)
4933 "Change the indentation in the current entry by DIFF
4934 However, if any line in the current entry has no indentation, or if it
4935 would end up with no indentation after the change, nothing at all is done."
4936 (save-excursion
4937 (let ((end (save-excursion (outline-next-heading)
4938 (point-marker)))
4939 (prohibit (if (> diff 0)
4940 "^\\S-"
4941 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4942 col)
4943 (unless (save-excursion (end-of-line 1)
4944 (re-search-forward prohibit end t))
4945 (while (and (< (point) end)
4946 (re-search-forward "^[ \t]+" end t))
4947 (goto-char (match-end 0))
4948 (setq col (current-column))
4949 (if (< diff 0) (replace-match ""))
4950 (indent-to (+ diff col))))
4951 (move-marker end nil))))
4953 (defun org-convert-to-odd-levels ()
4954 "Convert an org-mode file with all levels allowed to one with odd levels.
4955 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4956 level 5 etc."
4957 (interactive)
4958 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4959 (let ((org-odd-levels-only nil) n)
4960 (save-excursion
4961 (goto-char (point-min))
4962 (while (re-search-forward "^\\*\\*+ " nil t)
4963 (setq n (- (length (match-string 0)) 2))
4964 (while (>= (setq n (1- n)) 0)
4965 (org-demote))
4966 (end-of-line 1))))))
4969 (defun org-convert-to-oddeven-levels ()
4970 "Convert an org-mode file with only odd levels to one with odd and even levels.
4971 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4972 section with an even level, conversion would destroy the structure of the file. An error
4973 is signaled in this case."
4974 (interactive)
4975 (goto-char (point-min))
4976 ;; First check if there are no even levels
4977 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4978 (org-show-context t)
4979 (error "Not all levels are odd in this file. Conversion not possible."))
4980 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4981 (let ((org-odd-levels-only nil) n)
4982 (save-excursion
4983 (goto-char (point-min))
4984 (while (re-search-forward "^\\*\\*+ " nil t)
4985 (setq n (/ (1- (length (match-string 0))) 2))
4986 (while (>= (setq n (1- n)) 0)
4987 (org-promote))
4988 (end-of-line 1))))))
4990 (defun org-tr-level (n)
4991 "Make N odd if required."
4992 (if org-odd-levels-only (1+ (/ n 2)) n))
4994 ;;; Vertical tree motion, cutting and pasting of subtrees
4996 (defun org-move-subtree-up (&optional arg)
4997 "Move the current subtree up past ARG headlines of the same level."
4998 (interactive "p")
4999 (org-move-subtree-down (- (prefix-numeric-value arg))))
5001 (defun org-move-subtree-down (&optional arg)
5002 "Move the current subtree down past ARG headlines of the same level."
5003 (interactive "p")
5004 (setq arg (prefix-numeric-value arg))
5005 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5006 'outline-get-last-sibling))
5007 (ins-point (make-marker))
5008 (cnt (abs arg))
5009 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5010 ;; Select the tree
5011 (org-back-to-heading)
5012 (setq beg0 (point))
5013 (save-excursion
5014 (setq ne-beg (org-back-over-empty-lines))
5015 (setq beg (point)))
5016 (save-match-data
5017 (save-excursion (outline-end-of-heading)
5018 (setq folded (org-invisible-p)))
5019 (outline-end-of-subtree))
5020 (outline-next-heading)
5021 (setq ne-end (org-back-over-empty-lines))
5022 (setq end (point))
5023 (goto-char beg0)
5024 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5025 ;; include less whitespace
5026 (save-excursion
5027 (goto-char beg)
5028 (forward-line (- ne-beg ne-end))
5029 (setq beg (point))))
5030 ;; Find insertion point, with error handling
5031 (while (> cnt 0)
5032 (or (and (funcall movfunc) (looking-at outline-regexp))
5033 (progn (goto-char beg0)
5034 (error "Cannot move past superior level or buffer limit")))
5035 (setq cnt (1- cnt)))
5036 (if (> arg 0)
5037 ;; Moving forward - still need to move over subtree
5038 (progn (org-end-of-subtree t t)
5039 (save-excursion
5040 (org-back-over-empty-lines)
5041 (or (bolp) (newline)))))
5042 (setq ne-ins (org-back-over-empty-lines))
5043 (move-marker ins-point (point))
5044 (setq txt (buffer-substring beg end))
5045 (org-save-markers-in-region beg end)
5046 (delete-region beg end)
5047 (outline-flag-region (1- beg) beg nil)
5048 (outline-flag-region (1- (point)) (point) nil)
5049 (let ((bbb (point)))
5050 (insert-before-markers txt)
5051 (org-reinstall-markers-in-region bbb)
5052 (move-marker ins-point bbb))
5053 (or (bolp) (insert "\n"))
5054 (setq ins-end (point))
5055 (goto-char ins-point)
5056 (org-skip-whitespace)
5057 (when (and (< arg 0)
5058 (org-first-sibling-p)
5059 (> ne-ins ne-beg))
5060 ;; Move whitespace back to beginning
5061 (save-excursion
5062 (goto-char ins-end)
5063 (let ((kill-whole-line t))
5064 (kill-line (- ne-ins ne-beg)) (point)))
5065 (insert (make-string (- ne-ins ne-beg) ?\n)))
5066 (move-marker ins-point nil)
5067 (org-compact-display-after-subtree-move)
5068 (org-show-empty-lines-in-parent)
5069 (unless folded
5070 (org-show-entry)
5071 (show-children)
5072 (org-cycle-hide-drawers 'children))))
5074 (defvar org-subtree-clip ""
5075 "Clipboard for cut and paste of subtrees.
5076 This is actually only a copy of the kill, because we use the normal kill
5077 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5079 (defvar org-subtree-clip-folded nil
5080 "Was the last copied subtree folded?
5081 This is used to fold the tree back after pasting.")
5083 (defun org-cut-subtree (&optional n)
5084 "Cut the current subtree into the clipboard.
5085 With prefix arg N, cut this many sequential subtrees.
5086 This is a short-hand for marking the subtree and then cutting it."
5087 (interactive "p")
5088 (org-copy-subtree n 'cut))
5090 (defun org-copy-subtree (&optional n cut force-store-markers)
5091 "Cut the current subtree into the clipboard.
5092 With prefix arg N, cut this many sequential subtrees.
5093 This is a short-hand for marking the subtree and then copying it.
5094 If CUT is non-nil, actually cut the subtree.
5095 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5096 of some markers in the region, even if CUT is non-nil. This is
5097 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5098 (interactive "p")
5099 (let (beg end folded (beg0 (point)))
5100 (if (interactive-p)
5101 (org-back-to-heading nil) ; take what looks like a subtree
5102 (org-back-to-heading t)) ; take what is really there
5103 (org-back-over-empty-lines)
5104 (setq beg (point))
5105 (skip-chars-forward " \t\r\n")
5106 (save-match-data
5107 (save-excursion (outline-end-of-heading)
5108 (setq folded (org-invisible-p)))
5109 (condition-case nil
5110 (outline-forward-same-level (1- n))
5111 (error nil))
5112 (org-end-of-subtree t t))
5113 (org-back-over-empty-lines)
5114 (setq end (point))
5115 (goto-char beg0)
5116 (when (> end beg)
5117 (setq org-subtree-clip-folded folded)
5118 (when (or cut force-store-markers)
5119 (org-save-markers-in-region beg end))
5120 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5121 (setq org-subtree-clip (current-kill 0))
5122 (message "%s: Subtree(s) with %d characters"
5123 (if cut "Cut" "Copied")
5124 (length org-subtree-clip)))))
5126 (defun org-paste-subtree (&optional level tree for-yank)
5127 "Paste the clipboard as a subtree, with modification of headline level.
5128 The entire subtree is promoted or demoted in order to match a new headline
5129 level.
5131 If the cursor is at the beginning of a headline, the same level as
5132 that headline is used to paste the tree
5134 If not, the new level is derived from the *visible* headings
5135 before and after the insertion point, and taken to be the inferior headline
5136 level of the two. So if the previous visible heading is level 3 and the
5137 next is level 4 (or vice versa), level 4 will be used for insertion.
5138 This makes sure that the subtree remains an independent subtree and does
5139 not swallow low level entries.
5141 You can also force a different level, either by using a numeric prefix
5142 argument, or by inserting the heading marker by hand. For example, if the
5143 cursor is after \"*****\", then the tree will be shifted to level 5.
5145 If optional TREE is given, use this text instead of the kill ring.
5147 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5148 move back over whitespace before inserting, and move point to the end of
5149 the inserted text when done."
5150 (interactive "P")
5151 (unless (org-kill-is-subtree-p tree)
5152 (error "%s"
5153 (substitute-command-keys
5154 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5155 (let* ((visp (not (org-invisible-p)))
5156 (txt (or tree (and kill-ring (current-kill 0))))
5157 (^re (concat "^\\(" outline-regexp "\\)"))
5158 (re (concat "\\(" outline-regexp "\\)"))
5159 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5161 (old-level (if (string-match ^re txt)
5162 (- (match-end 0) (match-beginning 0) 1)
5163 -1))
5164 (force-level (cond (level (prefix-numeric-value level))
5165 ((and (looking-at "[ \t]*$")
5166 (string-match
5167 ^re_ (buffer-substring
5168 (point-at-bol) (point))))
5169 (- (match-end 1) (match-beginning 1)))
5170 ((and (bolp)
5171 (looking-at org-outline-regexp))
5172 (- (match-end 0) (point) 1))
5173 (t nil)))
5174 (previous-level (save-excursion
5175 (condition-case nil
5176 (progn
5177 (outline-previous-visible-heading 1)
5178 (if (looking-at re)
5179 (- (match-end 0) (match-beginning 0) 1)
5181 (error 1))))
5182 (next-level (save-excursion
5183 (condition-case nil
5184 (progn
5185 (or (looking-at outline-regexp)
5186 (outline-next-visible-heading 1))
5187 (if (looking-at re)
5188 (- (match-end 0) (match-beginning 0) 1)
5190 (error 1))))
5191 (new-level (or force-level (max previous-level next-level)))
5192 (shift (if (or (= old-level -1)
5193 (= new-level -1)
5194 (= old-level new-level))
5196 (- new-level old-level)))
5197 (delta (if (> shift 0) -1 1))
5198 (func (if (> shift 0) 'org-demote 'org-promote))
5199 (org-odd-levels-only nil)
5200 beg end newend)
5201 ;; Remove the forced level indicator
5202 (if force-level
5203 (delete-region (point-at-bol) (point)))
5204 ;; Paste
5205 (beginning-of-line 1)
5206 (unless for-yank (org-back-over-empty-lines))
5207 (setq beg (point))
5208 (insert-before-markers txt)
5209 (unless (string-match "\n\\'" txt) (insert "\n"))
5210 (setq newend (point))
5211 (org-reinstall-markers-in-region beg)
5212 (setq end (point))
5213 (goto-char beg)
5214 (skip-chars-forward " \t\n\r")
5215 (setq beg (point))
5216 (if (and (org-invisible-p) visp)
5217 (save-excursion (outline-show-heading)))
5218 ;; Shift if necessary
5219 (unless (= shift 0)
5220 (save-restriction
5221 (narrow-to-region beg end)
5222 (while (not (= shift 0))
5223 (org-map-region func (point-min) (point-max))
5224 (setq shift (+ delta shift)))
5225 (goto-char (point-min))
5226 (setq newend (point-max))))
5227 (when (or (interactive-p) for-yank)
5228 (message "Clipboard pasted as level %d subtree" new-level))
5229 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5230 kill-ring
5231 (eq org-subtree-clip (current-kill 0))
5232 org-subtree-clip-folded)
5233 ;; The tree was folded before it was killed/copied
5234 (hide-subtree))
5235 (and for-yank (goto-char newend))))
5237 (defun org-kill-is-subtree-p (&optional txt)
5238 "Check if the current kill is an outline subtree, or a set of trees.
5239 Returns nil if kill does not start with a headline, or if the first
5240 headline level is not the largest headline level in the tree.
5241 So this will actually accept several entries of equal levels as well,
5242 which is OK for `org-paste-subtree'.
5243 If optional TXT is given, check this string instead of the current kill."
5244 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5245 (start-level (and kill
5246 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5247 org-outline-regexp "\\)")
5248 kill)
5249 (- (match-end 2) (match-beginning 2) 1)))
5250 (re (concat "^" org-outline-regexp))
5251 (start (1+ (or (match-beginning 2) -1))))
5252 (if (not start-level)
5253 (progn
5254 nil) ;; does not even start with a heading
5255 (catch 'exit
5256 (while (setq start (string-match re kill (1+ start)))
5257 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5258 (throw 'exit nil)))
5259 t))))
5261 (defvar org-markers-to-move nil
5262 "Markers that should be moved with a cut-and-paste operation.
5263 Those markers are stored together with their positions relative to
5264 the start of the region.")
5266 (defun org-save-markers-in-region (beg end)
5267 "Check markers in region.
5268 If these markers are between BEG and END, record their position relative
5269 to BEG, so that after moving the block of text, we can put the markers back
5270 into place.
5271 This function gets called just before an entry or tree gets cut from the
5272 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5273 called immediately, to move the markers with the entries."
5274 (setq org-markers-to-move nil)
5275 (when (featurep 'org-clock)
5276 (org-clock-save-markers-for-cut-and-paste beg end))
5277 (when (featurep 'org-agenda)
5278 (org-agenda-save-markers-for-cut-and-paste beg end)))
5280 (defun org-check-and-save-marker (marker beg end)
5281 "Check if MARKER is between BEG and END.
5282 If yes, remember the marker and the distance to BEG."
5283 (when (and (marker-buffer marker)
5284 (equal (marker-buffer marker) (current-buffer)))
5285 (if (and (>= marker beg) (< marker end))
5286 (push (cons marker (- marker beg)) org-markers-to-move))))
5288 (defun org-reinstall-markers-in-region (beg)
5289 "Move all remembered markers to their position relative to BEG."
5290 (mapc (lambda (x)
5291 (move-marker (car x) (+ beg (cdr x))))
5292 org-markers-to-move)
5293 (setq org-markers-to-move nil))
5295 (defun org-narrow-to-subtree ()
5296 "Narrow buffer to the current subtree."
5297 (interactive)
5298 (save-excursion
5299 (save-match-data
5300 (narrow-to-region
5301 (progn (org-back-to-heading) (point))
5302 (progn (org-end-of-subtree t) (point))))))
5305 ;;; Outline Sorting
5307 (defun org-sort (with-case)
5308 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5309 Optional argument WITH-CASE means sort case-sensitively."
5310 (interactive "P")
5311 (if (org-at-table-p)
5312 (org-call-with-arg 'org-table-sort-lines with-case)
5313 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5315 (defun org-sort-remove-invisible (s)
5316 (remove-text-properties 0 (length s) org-rm-props s)
5317 (while (string-match org-bracket-link-regexp s)
5318 (setq s (replace-match (if (match-end 2)
5319 (match-string 3 s)
5320 (match-string 1 s)) t t s)))
5323 (defvar org-priority-regexp) ; defined later in the file
5325 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5326 "Sort entries on a certain level of an outline tree.
5327 If there is an active region, the entries in the region are sorted.
5328 Else, if the cursor is before the first entry, sort the top-level items.
5329 Else, the children of the entry at point are sorted.
5331 Sorting can be alphabetically, numerically, and by date/time as given by
5332 the first time stamp in the entry. The command prompts for the sorting
5333 type unless it has been given to the function through the SORTING-TYPE
5334 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5335 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5336 called with point at the beginning of the record. It must return either
5337 a string or a number that should serve as the sorting key for that record.
5339 Comparing entries ignores case by default. However, with an optional argument
5340 WITH-CASE, the sorting considers case as well."
5341 (interactive "P")
5342 (let ((case-func (if with-case 'identity 'downcase))
5343 start beg end stars re re2
5344 txt what tmp plain-list-p)
5345 ;; Find beginning and end of region to sort
5346 (cond
5347 ((org-region-active-p)
5348 ;; we will sort the region
5349 (setq end (region-end)
5350 what "region")
5351 (goto-char (region-beginning))
5352 (if (not (org-on-heading-p)) (outline-next-heading))
5353 (setq start (point)))
5354 ((org-at-item-p)
5355 ;; we will sort this plain list
5356 (org-beginning-of-item-list) (setq start (point))
5357 (org-end-of-item-list) (setq end (point))
5358 (goto-char start)
5359 (setq plain-list-p t
5360 what "plain list"))
5361 ((or (org-on-heading-p)
5362 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5363 ;; we will sort the children of the current headline
5364 (org-back-to-heading)
5365 (setq start (point)
5366 end (progn (org-end-of-subtree t t)
5367 (org-back-over-empty-lines)
5368 (point))
5369 what "children")
5370 (goto-char start)
5371 (show-subtree)
5372 (outline-next-heading))
5374 ;; we will sort the top-level entries in this file
5375 (goto-char (point-min))
5376 (or (org-on-heading-p) (outline-next-heading))
5377 (setq start (point) end (point-max) what "top-level")
5378 (goto-char start)
5379 (show-all)))
5381 (setq beg (point))
5382 (if (>= beg end) (error "Nothing to sort"))
5384 (unless plain-list-p
5385 (looking-at "\\(\\*+\\)")
5386 (setq stars (match-string 1)
5387 re (concat "^" (regexp-quote stars) " +")
5388 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5389 txt (buffer-substring beg end))
5390 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5391 (if (and (not (equal stars "*")) (string-match re2 txt))
5392 (error "Region to sort contains a level above the first entry")))
5394 (unless sorting-type
5395 (message
5396 (if plain-list-p
5397 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5398 "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:")
5399 what)
5400 (setq sorting-type (read-char-exclusive))
5402 (and (= (downcase sorting-type) ?f)
5403 (setq getkey-func
5404 (org-ido-completing-read "Sort using function: "
5405 obarray 'fboundp t nil nil))
5406 (setq getkey-func (intern getkey-func)))
5408 (and (= (downcase sorting-type) ?r)
5409 (setq property
5410 (org-ido-completing-read "Property: "
5411 (mapcar 'list (org-buffer-property-keys t))
5412 nil t))))
5414 (message "Sorting entries...")
5416 (save-restriction
5417 (narrow-to-region start end)
5419 (let ((dcst (downcase sorting-type))
5420 (now (current-time)))
5421 (sort-subr
5422 (/= dcst sorting-type)
5423 ;; This function moves to the beginning character of the "record" to
5424 ;; be sorted.
5425 (if plain-list-p
5426 (lambda nil
5427 (if (org-at-item-p) t (goto-char (point-max))))
5428 (lambda nil
5429 (if (re-search-forward re nil t)
5430 (goto-char (match-beginning 0))
5431 (goto-char (point-max)))))
5432 ;; This function moves to the last character of the "record" being
5433 ;; sorted.
5434 (if plain-list-p
5435 'org-end-of-item
5436 (lambda nil
5437 (save-match-data
5438 (condition-case nil
5439 (outline-forward-same-level 1)
5440 (error
5441 (goto-char (point-max)))))))
5443 ;; This function returns the value that gets sorted against.
5444 (if plain-list-p
5445 (lambda nil
5446 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5447 (cond
5448 ((= dcst ?n)
5449 (string-to-number (buffer-substring (match-end 0)
5450 (point-at-eol))))
5451 ((= dcst ?a)
5452 (buffer-substring (match-end 0) (point-at-eol)))
5453 ((= dcst ?t)
5454 (if (re-search-forward org-ts-regexp
5455 (point-at-eol) t)
5456 (org-time-string-to-time (match-string 0))
5457 now))
5458 ((= dcst ?f)
5459 (if getkey-func
5460 (progn
5461 (setq tmp (funcall getkey-func))
5462 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5463 tmp)
5464 (error "Invalid key function `%s'" getkey-func)))
5465 (t (error "Invalid sorting type `%c'" sorting-type)))))
5466 (lambda nil
5467 (cond
5468 ((= dcst ?n)
5469 (if (looking-at org-complex-heading-regexp)
5470 (string-to-number (match-string 4))
5471 nil))
5472 ((= dcst ?a)
5473 (if (looking-at org-complex-heading-regexp)
5474 (funcall case-func (match-string 4))
5475 nil))
5476 ((= dcst ?t)
5477 (if (re-search-forward org-ts-regexp
5478 (save-excursion
5479 (forward-line 2)
5480 (point)) t)
5481 (org-time-string-to-time (match-string 0))
5482 now))
5483 ((= dcst ?p)
5484 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5485 (string-to-char (match-string 2))
5486 org-default-priority))
5487 ((= dcst ?r)
5488 (or (org-entry-get nil property) ""))
5489 ((= dcst ?o)
5490 (if (looking-at org-complex-heading-regexp)
5491 (- 9999 (length (member (match-string 2)
5492 org-todo-keywords-1)))))
5493 ((= dcst ?f)
5494 (if getkey-func
5495 (progn
5496 (setq tmp (funcall getkey-func))
5497 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5498 tmp)
5499 (error "Invalid key function `%s'" getkey-func)))
5500 (t (error "Invalid sorting type `%c'" sorting-type)))))
5502 (cond
5503 ((= dcst ?a) 'string<)
5504 ((= dcst ?t) 'time-less-p)
5505 (t nil)))))
5506 (message "Sorting entries...done")))
5508 (defun org-do-sort (table what &optional with-case sorting-type)
5509 "Sort TABLE of WHAT according to SORTING-TYPE.
5510 The user will be prompted for the SORTING-TYPE if the call to this
5511 function does not specify it. WHAT is only for the prompt, to indicate
5512 what is being sorted. The sorting key will be extracted from
5513 the car of the elements of the table.
5514 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5515 (unless sorting-type
5516 (message
5517 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5518 what)
5519 (setq sorting-type (read-char-exclusive)))
5520 (let ((dcst (downcase sorting-type))
5521 extractfun comparefun)
5522 ;; Define the appropriate functions
5523 (cond
5524 ((= dcst ?n)
5525 (setq extractfun 'string-to-number
5526 comparefun (if (= dcst sorting-type) '< '>)))
5527 ((= dcst ?a)
5528 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5529 (lambda(x) (downcase (org-sort-remove-invisible x))))
5530 comparefun (if (= dcst sorting-type)
5531 'string<
5532 (lambda (a b) (and (not (string< a b))
5533 (not (string= a b)))))))
5534 ((= dcst ?t)
5535 (setq extractfun
5536 (lambda (x)
5537 (if (string-match org-ts-regexp x)
5538 (time-to-seconds
5539 (org-time-string-to-time (match-string 0 x)))
5541 comparefun (if (= dcst sorting-type) '< '>)))
5542 (t (error "Invalid sorting type `%c'" sorting-type)))
5544 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5545 table)
5546 (lambda (a b) (funcall comparefun (car a) (car b))))))
5548 ;;; Editing source examples
5550 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5551 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5552 (defvar org-edit-src-force-single-line nil)
5553 (defvar org-edit-src-from-org-mode nil)
5554 (defvar org-edit-src-picture nil)
5556 (define-minor-mode org-exit-edit-mode
5557 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5559 (defun org-edit-src-code ()
5560 "Edit the source code example at point.
5561 An indirect buffer is created, and that buffer is then narrowed to the
5562 example at point and switched to the correct language mode. When done,
5563 exit by killing the buffer with \\[org-edit-src-exit]."
5564 (interactive)
5565 (let ((line (org-current-line))
5566 (case-fold-search t)
5567 (msg (substitute-command-keys
5568 "Edit, then exit with C-c ' (C-c and single quote)"))
5569 (info (org-edit-src-find-region-and-lang))
5570 (org-mode-p (eq major-mode 'org-mode))
5571 beg end lang lang-f single)
5572 (if (not info)
5574 (setq beg (nth 0 info)
5575 end (nth 1 info)
5576 lang (nth 2 info)
5577 single (nth 3 info)
5578 lang-f (intern (concat lang "-mode")))
5579 (unless (functionp lang-f)
5580 (error "No such language mode: %s" lang-f))
5581 (goto-line line)
5582 (if (get-buffer "*Org Edit Src Example*")
5583 (kill-buffer "*Org Edit Src Example*"))
5584 (switch-to-buffer (make-indirect-buffer (current-buffer)
5585 "*Org Edit Src Example*"))
5586 (narrow-to-region beg end)
5587 (remove-text-properties beg end '(display nil invisible nil
5588 intangible nil))
5589 (let ((org-inhibit-startup t))
5590 (funcall lang-f))
5591 (set (make-local-variable 'org-edit-src-force-single-line) single)
5592 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5593 (when org-mode-p
5594 (goto-char (point-min))
5595 (while (re-search-forward "^," nil t)
5596 (replace-match "")))
5597 (goto-line line)
5598 (org-exit-edit-mode)
5599 (org-set-local 'header-line-format msg)
5600 (message "%s" msg)
5601 t)))
5603 (defun org-edit-fixed-width-region ()
5604 "Edit the fixed-width ascii drawing at point.
5605 This must be a region where each line starts with ca colon followed by
5606 a space character.
5607 An indirect buffer is created, and that buffer is then narrowed to the
5608 example at point and switched to artist-mode. When done,
5609 exit by killing the buffer with \\[org-edit-src-exit]."
5610 (interactive)
5611 (let ((line (org-current-line))
5612 (case-fold-search t)
5613 (msg (substitute-command-keys
5614 "Edit, then exit with C-c ' (C-c and single quote)"))
5615 (org-mode-p (eq major-mode 'org-mode))
5616 beg end lang lang-f)
5617 (beginning-of-line 1)
5618 (if (looking-at "[ \t]*[^:\n \t]")
5620 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5621 (setq beg (point) end beg)
5622 (save-excursion
5623 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5624 (setq beg (point-at-bol 2))
5625 (setq beg (point))))
5626 (save-excursion
5627 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5628 (setq end (1- (match-beginning 0)))
5629 (setq end (point))))
5630 (goto-line line))
5631 (if (get-buffer "*Org Edit Picture*")
5632 (kill-buffer "*Org Edit Picture*"))
5633 (switch-to-buffer (make-indirect-buffer (current-buffer)
5634 "*Org Edit Picture*"))
5635 (narrow-to-region beg end)
5636 (remove-text-properties beg end '(display nil invisible nil
5637 intangible nil))
5638 (when (fboundp 'font-lock-unfontify-region)
5639 (font-lock-unfontify-region (point-min) (point-max)))
5640 (cond
5641 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5642 (fundamental-mode)
5643 (artist-mode 1))
5644 (t (funcall org-edit-fixed-width-region-mode)))
5645 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5646 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5647 (set (make-local-variable 'org-edit-src-picture) t)
5648 (goto-char (point-min))
5649 (while (re-search-forward "^[ \t]*: ?" nil t)
5650 (replace-match ""))
5651 (goto-line line)
5652 (org-exit-edit-mode)
5653 (org-set-local 'header-line-format msg)
5654 (message "%s" msg)
5655 t)))
5658 (defun org-edit-src-find-region-and-lang ()
5659 "Find the region and language for a local edit.
5660 Return a list with beginning and end of the region, a string representing
5661 the language, a switch telling of the content should be in a single line."
5662 (let ((re-list
5663 (append
5664 org-edit-src-region-extra
5666 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5667 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5668 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5669 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5670 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5671 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5672 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5673 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5674 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5675 ("^#\\+html:" "\n" "html" single-line)
5676 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5677 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5678 ("^#\\+latex:" "\n" "latex" single-line)
5679 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5680 ("^#\\+ascii:" "\n" "ascii" single-line)
5682 (pos (point))
5683 re re1 re2 single beg end lang)
5684 (catch 'exit
5685 (while (setq entry (pop re-list))
5686 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5687 single (nth 3 entry))
5688 (save-excursion
5689 (if (or (looking-at re1)
5690 (re-search-backward re1 nil t))
5691 (progn
5692 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5693 (if (and (re-search-forward re2 nil t)
5694 (>= (match-end 0) pos))
5695 (throw 'exit (list beg (match-beginning 0) lang single))))
5696 (if (or (looking-at re2)
5697 (re-search-forward re2 nil t))
5698 (progn
5699 (setq end (match-beginning 0))
5700 (if (and (re-search-backward re1 nil t)
5701 (<= (match-beginning 0) pos))
5702 (throw 'exit
5703 (list (match-end 0) end
5704 (org-edit-src-get-lang lang) single)))))))))))
5706 (defun org-edit-src-get-lang (lang)
5707 "Extract the src language."
5708 (let ((m (match-string 0)))
5709 (cond
5710 ((stringp lang) lang)
5711 ((integerp lang) (match-string lang))
5712 ((and (eq lang 'lang)
5713 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5714 (match-string 1 m))
5715 ((and (eq lang 'style)
5716 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5717 (match-string 1 m))
5718 (t "fundamental"))))
5720 (defun org-edit-src-exit ()
5721 "Exit special edit and protect problematic lines."
5722 (interactive)
5723 (unless (buffer-base-buffer (current-buffer))
5724 (error "This is not an indirect buffer, something is wrong..."))
5725 (unless (> (point-min) 1)
5726 (error "This buffer is not narrowed, something is wrong..."))
5727 (goto-char (point-min))
5728 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5729 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5730 (when (org-bound-and-true-p org-edit-src-force-single-line)
5731 (goto-char (point-min))
5732 (while (re-search-forward "\n" nil t)
5733 (replace-match " "))
5734 (goto-char (point-min))
5735 (if (looking-at "\\s-*") (replace-match " "))
5736 (if (re-search-forward "\\s-+\\'" nil t)
5737 (replace-match "")))
5738 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5739 (goto-char (point-min))
5740 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5741 (replace-match ",\\1"))
5742 (when font-lock-mode
5743 (font-lock-unfontify-region (point-min) (point-max)))
5744 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5745 (when (org-bound-and-true-p org-edit-src-picture)
5746 (untabify (point-min) (point-max))
5747 (goto-char (point-min))
5748 (while (re-search-forward "^" nil t)
5749 (replace-match ": "))
5750 (when font-lock-mode
5751 (font-lock-unfontify-region (point-min) (point-max)))
5752 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5753 (kill-buffer (current-buffer))
5754 (and (org-mode-p) (org-restart-font-lock)))
5757 ;;; The orgstruct minor mode
5759 ;; Define a minor mode which can be used in other modes in order to
5760 ;; integrate the org-mode structure editing commands.
5762 ;; This is really a hack, because the org-mode structure commands use
5763 ;; keys which normally belong to the major mode. Here is how it
5764 ;; works: The minor mode defines all the keys necessary to operate the
5765 ;; structure commands, but wraps the commands into a function which
5766 ;; tests if the cursor is currently at a headline or a plain list
5767 ;; item. If that is the case, the structure command is used,
5768 ;; temporarily setting many Org-mode variables like regular
5769 ;; expressions for filling etc. However, when any of those keys is
5770 ;; used at a different location, function uses `key-binding' to look
5771 ;; up if the key has an associated command in another currently active
5772 ;; keymap (minor modes, major mode, global), and executes that
5773 ;; command. There might be problems if any of the keys is otherwise
5774 ;; used as a prefix key.
5776 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5777 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5778 ;; addresses this by checking explicitly for both bindings.
5780 (defvar orgstruct-mode-map (make-sparse-keymap)
5781 "Keymap for the minor `orgstruct-mode'.")
5783 (defvar org-local-vars nil
5784 "List of local variables, for use by `orgstruct-mode'")
5786 ;;;###autoload
5787 (define-minor-mode orgstruct-mode
5788 "Toggle the minor more `orgstruct-mode'.
5789 This mode is for using Org-mode structure commands in other modes.
5790 The following key behave as if Org-mode was active, if the cursor
5791 is on a headline, or on a plain list item (both in the definition
5792 of Org-mode).
5794 M-up Move entry/item up
5795 M-down Move entry/item down
5796 M-left Promote
5797 M-right Demote
5798 M-S-up Move entry/item up
5799 M-S-down Move entry/item down
5800 M-S-left Promote subtree
5801 M-S-right Demote subtree
5802 M-q Fill paragraph and items like in Org-mode
5803 C-c ^ Sort entries
5804 C-c - Cycle list bullet
5805 TAB Cycle item visibility
5806 M-RET Insert new heading/item
5807 S-M-RET Insert new TODO heading / Chekbox item
5808 C-c C-c Set tags / toggle checkbox"
5809 nil " OrgStruct" nil
5810 (org-load-modules-maybe)
5811 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5813 ;;;###autoload
5814 (defun turn-on-orgstruct ()
5815 "Unconditionally turn on `orgstruct-mode'."
5816 (orgstruct-mode 1))
5818 ;;;###autoload
5819 (defun turn-on-orgstruct++ ()
5820 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5821 In addition to setting orgstruct-mode, this also exports all indentation and
5822 autofilling variables from org-mode into the buffer. Note that turning
5823 off orgstruct-mode will *not* remove these additional settings."
5824 (orgstruct-mode 1)
5825 (let (var val)
5826 (mapc
5827 (lambda (x)
5828 (when (string-match
5829 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5830 (symbol-name (car x)))
5831 (setq var (car x) val (nth 1 x))
5832 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5833 org-local-vars)))
5835 (defun orgstruct-error ()
5836 "Error when there is no default binding for a structure key."
5837 (interactive)
5838 (error "This key has no function outside structure elements"))
5840 (defun orgstruct-setup ()
5841 "Setup orgstruct keymaps."
5842 (let ((nfunc 0)
5843 (bindings
5844 (list
5845 '([(meta up)] org-metaup)
5846 '([(meta down)] org-metadown)
5847 '([(meta left)] org-metaleft)
5848 '([(meta right)] org-metaright)
5849 '([(meta shift up)] org-shiftmetaup)
5850 '([(meta shift down)] org-shiftmetadown)
5851 '([(meta shift left)] org-shiftmetaleft)
5852 '([(meta shift right)] org-shiftmetaright)
5853 '([(shift up)] org-shiftup)
5854 '([(shift down)] org-shiftdown)
5855 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5856 '("\M-q" fill-paragraph)
5857 '("\C-c^" org-sort)
5858 '("\C-c-" org-cycle-list-bullet)))
5859 elt key fun cmd)
5860 (while (setq elt (pop bindings))
5861 (setq nfunc (1+ nfunc))
5862 (setq key (org-key (car elt))
5863 fun (nth 1 elt)
5864 cmd (orgstruct-make-binding fun nfunc key))
5865 (org-defkey orgstruct-mode-map key cmd))
5867 ;; Special treatment needed for TAB and RET
5868 (org-defkey orgstruct-mode-map [(tab)]
5869 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5870 (org-defkey orgstruct-mode-map "\C-i"
5871 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5873 (org-defkey orgstruct-mode-map "\M-\C-m"
5874 (orgstruct-make-binding 'org-insert-heading 105
5875 "\M-\C-m" [(meta return)]))
5876 (org-defkey orgstruct-mode-map [(meta return)]
5877 (orgstruct-make-binding 'org-insert-heading 106
5878 [(meta return)] "\M-\C-m"))
5880 (org-defkey orgstruct-mode-map [(shift meta return)]
5881 (orgstruct-make-binding 'org-insert-todo-heading 107
5882 [(meta return)] "\M-\C-m"))
5884 (unless org-local-vars
5885 (setq org-local-vars (org-get-local-variables)))
5889 (defun orgstruct-make-binding (fun n &rest keys)
5890 "Create a function for binding in the structure minor mode.
5891 FUN is the command to call inside a table. N is used to create a unique
5892 command name. KEYS are keys that should be checked in for a command
5893 to execute outside of tables."
5894 (eval
5895 (list 'defun
5896 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5897 '(arg)
5898 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5899 "Outside of structure, run the binding of `"
5900 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5901 "'.")
5902 '(interactive "p")
5903 (list 'if
5904 '(org-context-p 'headline 'item)
5905 (list 'org-run-like-in-org-mode (list 'quote fun))
5906 (list 'let '(orgstruct-mode)
5907 (list 'call-interactively
5908 (append '(or)
5909 (mapcar (lambda (k)
5910 (list 'key-binding k))
5911 keys)
5912 '('orgstruct-error))))))))
5914 (defun org-context-p (&rest contexts)
5915 "Check if local context is any of CONTEXTS.
5916 Possible values in the list of contexts are `table', `headline', and `item'."
5917 (let ((pos (point)))
5918 (goto-char (point-at-bol))
5919 (prog1 (or (and (memq 'table contexts)
5920 (looking-at "[ \t]*|"))
5921 (and (memq 'headline contexts)
5922 ;;????????? (looking-at "\\*+"))
5923 (looking-at outline-regexp))
5924 (and (memq 'item contexts)
5925 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5926 (goto-char pos))))
5928 (defun org-get-local-variables ()
5929 "Return a list of all local variables in an org-mode buffer."
5930 (let (varlist)
5931 (with-current-buffer (get-buffer-create "*Org tmp*")
5932 (erase-buffer)
5933 (org-mode)
5934 (setq varlist (buffer-local-variables)))
5935 (kill-buffer "*Org tmp*")
5936 (delq nil
5937 (mapcar
5938 (lambda (x)
5939 (setq x
5940 (if (symbolp x)
5941 (list x)
5942 (list (car x) (list 'quote (cdr x)))))
5943 (if (string-match
5944 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5945 (symbol-name (car x)))
5946 x nil))
5947 varlist))))
5949 ;;;###autoload
5950 (defun org-run-like-in-org-mode (cmd)
5951 (org-load-modules-maybe)
5952 (unless org-local-vars
5953 (setq org-local-vars (org-get-local-variables)))
5954 (eval (list 'let org-local-vars
5955 (list 'call-interactively (list 'quote cmd)))))
5957 ;;;; Archiving
5959 (defun org-get-category (&optional pos)
5960 "Get the category applying to position POS."
5961 (get-text-property (or pos (point)) 'org-category))
5963 (defun org-refresh-category-properties ()
5964 "Refresh category text properties in the buffer."
5965 (let ((def-cat (cond
5966 ((null org-category)
5967 (if buffer-file-name
5968 (file-name-sans-extension
5969 (file-name-nondirectory buffer-file-name))
5970 "???"))
5971 ((symbolp org-category) (symbol-name org-category))
5972 (t org-category)))
5973 beg end cat pos optionp)
5974 (org-unmodified
5975 (save-excursion
5976 (save-restriction
5977 (widen)
5978 (goto-char (point-min))
5979 (put-text-property (point) (point-max) 'org-category def-cat)
5980 (while (re-search-forward
5981 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5982 (setq pos (match-end 0)
5983 optionp (equal (char-after (match-beginning 0)) ?#)
5984 cat (org-trim (match-string 2)))
5985 (if optionp
5986 (setq beg (point-at-bol) end (point-max))
5987 (org-back-to-heading t)
5988 (setq beg (point) end (org-end-of-subtree t t)))
5989 (put-text-property beg end 'org-category cat)
5990 (goto-char pos)))))))
5993 ;;;; Link Stuff
5995 ;;; Link abbreviations
5997 (defun org-link-expand-abbrev (link)
5998 "Apply replacements as defined in `org-link-abbrev-alist."
5999 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6000 (let* ((key (match-string 1 link))
6001 (as (or (assoc key org-link-abbrev-alist-local)
6002 (assoc key org-link-abbrev-alist)))
6003 (tag (and (match-end 2) (match-string 3 link)))
6004 rpl)
6005 (if (not as)
6006 link
6007 (setq rpl (cdr as))
6008 (cond
6009 ((symbolp rpl) (funcall rpl tag))
6010 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6011 ((string-match "%h" rpl)
6012 (replace-match (url-hexify-string (or tag "")) t t rpl))
6013 (t (concat rpl tag)))))
6014 link))
6016 ;;; Storing and inserting links
6018 (defvar org-insert-link-history nil
6019 "Minibuffer history for links inserted with `org-insert-link'.")
6021 (defvar org-stored-links nil
6022 "Contains the links stored with `org-store-link'.")
6024 (defvar org-store-link-plist nil
6025 "Plist with info about the most recently link created with `org-store-link'.")
6027 (defvar org-link-protocols nil
6028 "Link protocols added to Org-mode using `org-add-link-type'.")
6030 (defvar org-store-link-functions nil
6031 "List of functions that are called to create and store a link.
6032 Each function will be called in turn until one returns a non-nil
6033 value. Each function should check if it is responsible for creating
6034 this link (for example by looking at the major mode).
6035 If not, it must exit and return nil.
6036 If yes, it should return a non-nil value after a calling
6037 `org-store-link-props' with a list of properties and values.
6038 Special properties are:
6040 :type The link prefix. like \"http\". This must be given.
6041 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6042 This is obligatory as well.
6043 :description Optional default description for the second pair
6044 of brackets in an Org-mode link. The user can still change
6045 this when inserting this link into an Org-mode buffer.
6047 In addition to these, any additional properties can be specified
6048 and then used in remember templates.")
6050 (defun org-add-link-type (type &optional follow export)
6051 "Add TYPE to the list of `org-link-types'.
6052 Re-compute all regular expressions depending on `org-link-types'
6054 FOLLOW and EXPORT are two functions.
6056 FOLLOW should take the link path as the single argument and do whatever
6057 is necessary to follow the link, for example find a file or display
6058 a mail message.
6060 EXPORT should format the link path for export to one of the export formats.
6061 It should be a function accepting three arguments:
6063 path the path of the link, the text after the prefix (like \"http:\")
6064 desc the description of the link, if any, nil if there was no descripton
6065 format the export format, a symbol like `html' or `latex'.
6067 The function may use the FORMAT information to return different values
6068 depending on the format. The return value will be put literally into
6069 the exported file.
6070 Org-mode has a built-in default for exporting links. If you are happy with
6071 this default, there is no need to define an export function for the link
6072 type. For a simple example of an export function, see `org-bbdb.el'."
6073 (add-to-list 'org-link-types type t)
6074 (org-make-link-regexps)
6075 (if (assoc type org-link-protocols)
6076 (setcdr (assoc type org-link-protocols) (list follow export))
6077 (push (list type follow export) org-link-protocols)))
6080 ;;;###autoload
6081 (defun org-store-link (arg)
6082 "\\<org-mode-map>Store an org-link to the current location.
6083 This link is added to `org-stored-links' and can later be inserted
6084 into an org-buffer with \\[org-insert-link].
6086 For some link types, a prefix arg is interpreted:
6087 For links to usenet articles, arg negates `org-gnus-prefere-web-links'.
6088 For file links, arg negates `org-context-in-file-links'."
6089 (interactive "P")
6090 (org-load-modules-maybe)
6091 (setq org-store-link-plist nil) ; reset
6092 (let (link cpltxt desc description search txt)
6093 (cond
6095 ((run-hook-with-args-until-success 'org-store-link-functions)
6096 (setq link (plist-get org-store-link-plist :link)
6097 desc (or (plist-get org-store-link-plist :description) link)))
6099 ((eq major-mode 'calendar-mode)
6100 (let ((cd (calendar-cursor-to-date)))
6101 (setq link
6102 (format-time-string
6103 (car org-time-stamp-formats)
6104 (apply 'encode-time
6105 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6106 nil nil nil))))
6107 (org-store-link-props :type "calendar" :date cd)))
6109 ((eq major-mode 'w3-mode)
6110 (setq cpltxt (url-view-url t)
6111 link (org-make-link cpltxt))
6112 (org-store-link-props :type "w3" :url (url-view-url t)))
6114 ((eq major-mode 'w3m-mode)
6115 (setq cpltxt (or w3m-current-title w3m-current-url)
6116 link (org-make-link w3m-current-url))
6117 (org-store-link-props :type "w3m" :url (url-view-url t)))
6119 ((setq search (run-hook-with-args-until-success
6120 'org-create-file-search-functions))
6121 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6122 "::" search))
6123 (setq cpltxt (or description link)))
6125 ((eq major-mode 'image-mode)
6126 (setq cpltxt (concat "file:"
6127 (abbreviate-file-name buffer-file-name))
6128 link (org-make-link cpltxt))
6129 (org-store-link-props :type "image" :file buffer-file-name))
6131 ((eq major-mode 'dired-mode)
6132 ;; link to the file in the current line
6133 (setq cpltxt (concat "file:"
6134 (abbreviate-file-name
6135 (expand-file-name
6136 (dired-get-filename nil t))))
6137 link (org-make-link cpltxt)))
6139 ((and buffer-file-name (org-mode-p))
6140 ;; Just link to current headline
6141 (setq cpltxt (concat "file:"
6142 (abbreviate-file-name buffer-file-name)))
6143 ;; Add a context search string
6144 (when (org-xor org-context-in-file-links arg)
6145 ;; Check if we are on a target
6146 (if (org-in-regexp "<<\\(.*?\\)>>")
6147 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6148 (setq txt (cond
6149 ((org-on-heading-p) nil)
6150 ((org-region-active-p)
6151 (buffer-substring (region-beginning) (region-end)))
6152 (t nil)))
6153 (when (or (null txt) (string-match "\\S-" txt))
6154 (setq cpltxt
6155 (concat cpltxt "::"
6156 (condition-case nil
6157 (org-make-org-heading-search-string txt)
6158 (error "")))
6159 desc "NONE"))))
6160 (if (string-match "::\\'" cpltxt)
6161 (setq cpltxt (substring cpltxt 0 -2)))
6162 (setq link (org-make-link cpltxt)))
6164 ((buffer-file-name (buffer-base-buffer))
6165 ;; Just link to this file here.
6166 (setq cpltxt (concat "file:"
6167 (abbreviate-file-name
6168 (buffer-file-name (buffer-base-buffer)))))
6169 ;; Add a context string
6170 (when (org-xor org-context-in-file-links arg)
6171 (setq txt (if (org-region-active-p)
6172 (buffer-substring (region-beginning) (region-end))
6173 (buffer-substring (point-at-bol) (point-at-eol))))
6174 ;; Only use search option if there is some text.
6175 (when (string-match "\\S-" txt)
6176 (setq cpltxt
6177 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6178 desc "NONE")))
6179 (setq link (org-make-link cpltxt)))
6181 ((interactive-p)
6182 (error "Cannot link to a buffer which is not visiting a file"))
6184 (t (setq link nil)))
6186 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6187 (setq link (or link cpltxt)
6188 desc (or desc cpltxt))
6189 (if (equal desc "NONE") (setq desc nil))
6191 (if (and (interactive-p) link)
6192 (progn
6193 (setq org-stored-links
6194 (cons (list link desc) org-stored-links))
6195 (message "Stored: %s" (or desc link)))
6196 (and link (org-make-link-string link desc)))))
6198 (defun org-store-link-props (&rest plist)
6199 "Store link properties, extract names and addresses."
6200 (let (x adr)
6201 (when (setq x (plist-get plist :from))
6202 (setq adr (mail-extract-address-components x))
6203 (setq plist (plist-put plist :fromname (car adr)))
6204 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6205 (when (setq x (plist-get plist :to))
6206 (setq adr (mail-extract-address-components x))
6207 (setq plist (plist-put plist :toname (car adr)))
6208 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6209 (let ((from (plist-get plist :from))
6210 (to (plist-get plist :to)))
6211 (when (and from to org-from-is-user-regexp)
6212 (setq plist
6213 (plist-put plist :fromto
6214 (if (string-match org-from-is-user-regexp from)
6215 (concat "to %t")
6216 (concat "from %f"))))))
6217 (setq org-store-link-plist plist))
6219 (defun org-add-link-props (&rest plist)
6220 "Add these properties to the link property list."
6221 (let (key value)
6222 (while plist
6223 (setq key (pop plist) value (pop plist))
6224 (setq org-store-link-plist
6225 (plist-put org-store-link-plist key value)))))
6227 (defun org-email-link-description (&optional fmt)
6228 "Return the description part of an email link.
6229 This takes information from `org-store-link-plist' and formats it
6230 according to FMT (default from `org-email-link-description-format')."
6231 (setq fmt (or fmt org-email-link-description-format))
6232 (let* ((p org-store-link-plist)
6233 (to (plist-get p :toaddress))
6234 (from (plist-get p :fromaddress))
6235 (table
6236 (list
6237 (cons "%c" (plist-get p :fromto))
6238 (cons "%F" (plist-get p :from))
6239 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6240 (cons "%T" (plist-get p :to))
6241 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6242 (cons "%s" (plist-get p :subject))
6243 (cons "%m" (plist-get p :message-id)))))
6244 (when (string-match "%c" fmt)
6245 ;; Check if the user wrote this message
6246 (if (and org-from-is-user-regexp from to
6247 (save-match-data (string-match org-from-is-user-regexp from)))
6248 (setq fmt (replace-match "to %t" t t fmt))
6249 (setq fmt (replace-match "from %f" t t fmt))))
6250 (org-replace-escapes fmt table)))
6252 (defun org-make-org-heading-search-string (&optional string heading)
6253 "Make search string for STRING or current headline."
6254 (interactive)
6255 (let ((s (or string (org-get-heading))))
6256 (unless (and string (not heading))
6257 ;; We are using a headline, clean up garbage in there.
6258 (if (string-match org-todo-regexp s)
6259 (setq s (replace-match "" t t s)))
6260 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6261 (setq s (replace-match "" t t s)))
6262 (setq s (org-trim s))
6263 (if (string-match (concat "^\\(" org-quote-string "\\|"
6264 org-comment-string "\\)") s)
6265 (setq s (replace-match "" t t s)))
6266 (while (string-match org-ts-regexp s)
6267 (setq s (replace-match "" t t s))))
6268 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6269 (setq s (replace-match " " t t s)))
6270 (or string (setq s (concat "*" s))) ; Add * for headlines
6271 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6273 (defun org-make-link (&rest strings)
6274 "Concatenate STRINGS."
6275 (apply 'concat strings))
6277 (defun org-make-link-string (link &optional description)
6278 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6279 (unless (string-match "\\S-" link)
6280 (error "Empty link"))
6281 (when (stringp description)
6282 ;; Remove brackets from the description, they are fatal.
6283 (while (string-match "\\[" description)
6284 (setq description (replace-match "{" t t description)))
6285 (while (string-match "\\]" description)
6286 (setq description (replace-match "}" t t description))))
6287 (when (equal (org-link-escape link) description)
6288 ;; No description needed, it is identical
6289 (setq description nil))
6290 (when (and (not description)
6291 (not (equal link (org-link-escape link))))
6292 (setq description (org-extract-attributes link)))
6293 (concat "[[" (org-link-escape link) "]"
6294 (if description (concat "[" description "]") "")
6295 "]"))
6297 (defconst org-link-escape-chars
6298 '((?\ . "%20")
6299 (?\[ . "%5B")
6300 (?\] . "%5D")
6301 (?\340 . "%E0") ; `a
6302 (?\342 . "%E2") ; ^a
6303 (?\347 . "%E7") ; ,c
6304 (?\350 . "%E8") ; `e
6305 (?\351 . "%E9") ; 'e
6306 (?\352 . "%EA") ; ^e
6307 (?\356 . "%EE") ; ^i
6308 (?\364 . "%F4") ; ^o
6309 (?\371 . "%F9") ; `u
6310 (?\373 . "%FB") ; ^u
6311 (?\; . "%3B")
6312 (?? . "%3F")
6313 (?= . "%3D")
6314 (?+ . "%2B")
6316 "Association list of escapes for some characters problematic in links.
6317 This is the list that is used for internal purposes.")
6319 (defconst org-link-escape-chars-browser
6320 '((?\ . "%20")) ; 32 for the SPC char
6321 "Association list of escapes for some characters problematic in links.
6322 This is the list that is used before handing over to the browser.")
6324 (defun org-link-escape (text &optional table)
6325 "Escape charaters in TEXT that are problematic for links."
6326 (setq table (or table org-link-escape-chars))
6327 (when text
6328 (let ((re (mapconcat (lambda (x) (regexp-quote
6329 (char-to-string (car x))))
6330 table "\\|")))
6331 (while (string-match re text)
6332 (setq text
6333 (replace-match
6334 (cdr (assoc (string-to-char (match-string 0 text))
6335 table))
6336 t t text)))
6337 text)))
6339 (defun org-link-unescape (text &optional table)
6340 "Reverse the action of `org-link-escape'."
6341 (setq table (or table org-link-escape-chars))
6342 (when text
6343 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6344 table "\\|")))
6345 (while (string-match re text)
6346 (setq text
6347 (replace-match
6348 (char-to-string (car (rassoc (match-string 0 text) table)))
6349 t t text)))
6350 text)))
6352 (defun org-xor (a b)
6353 "Exclusive or."
6354 (if a (not b) b))
6356 (defun org-get-header (header)
6357 "Find a header field in the current buffer."
6358 (save-excursion
6359 (goto-char (point-min))
6360 (let ((case-fold-search t) s)
6361 (cond
6362 ((eq header 'from)
6363 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6364 (setq s (match-string 1)))
6365 (while (string-match "\"" s)
6366 (setq s (replace-match "" t t s)))
6367 (if (string-match "[<(].*" s)
6368 (setq s (replace-match "" t t s))))
6369 ((eq header 'message-id)
6370 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6371 (setq s (match-string 1))))
6372 ((eq header 'subject)
6373 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6374 (setq s (match-string 1)))))
6375 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6376 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6377 s)))
6380 (defun org-fixup-message-id-for-http (s)
6381 "Replace special characters in a message id, so it can be used in an http query."
6382 (while (string-match "<" s)
6383 (setq s (replace-match "%3C" t t s)))
6384 (while (string-match ">" s)
6385 (setq s (replace-match "%3E" t t s)))
6386 (while (string-match "@" s)
6387 (setq s (replace-match "%40" t t s)))
6390 ;;;###autoload
6391 (defun org-insert-link-global ()
6392 "Insert a link like Org-mode does.
6393 This command can be called in any mode to insert a link in Org-mode syntax."
6394 (interactive)
6395 (org-load-modules-maybe)
6396 (org-run-like-in-org-mode 'org-insert-link))
6398 (defun org-insert-link (&optional complete-file link-location)
6399 "Insert a link. At the prompt, enter the link.
6401 Completion can be used to insert any of the link protocol prefixes like
6402 http or ftp in use.
6404 The history can be used to select a link previously stored with
6405 `org-store-link'. When the empty string is entered (i.e. if you just
6406 press RET at the prompt), the link defaults to the most recently
6407 stored link. As SPC triggers completion in the minibuffer, you need to
6408 use M-SPC or C-q SPC to force the insertion of a space character.
6410 You will also be prompted for a description, and if one is given, it will
6411 be displayed in the buffer instead of the link.
6413 If there is already a link at point, this command will allow you to edit link
6414 and description parts.
6416 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6417 be selected using completion. The path to the file will be relative to the
6418 current directory if the file is in the current directory or a subdirectory.
6419 Otherwise, the link will be the absolute path as completed in the minibuffer
6420 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6421 option `org-link-file-path-type'.
6423 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6424 the current directory or below.
6426 With three \\[universal-argument] prefixes, negate the meaning of
6427 `org-keep-stored-link-after-insertion'.
6429 If `org-make-link-description-function' is non-nil, this function will be
6430 called with the link target, and the result will be the default
6431 link description.
6433 If the LINK-LOCATION parameter is non-nil, this value will be
6434 used as the link location instead of reading one interactively."
6435 (interactive "P")
6436 (let* ((wcf (current-window-configuration))
6437 (region (if (org-region-active-p)
6438 (buffer-substring (region-beginning) (region-end))))
6439 (remove (and region (list (region-beginning) (region-end))))
6440 (desc region)
6441 tmphist ; byte-compile incorrectly complains about this
6442 (link link-location)
6443 entry file)
6444 (cond
6445 (link-location) ; specified by arg, just use it.
6446 ((org-in-regexp org-bracket-link-regexp 1)
6447 ;; We do have a link at point, and we are going to edit it.
6448 (setq remove (list (match-beginning 0) (match-end 0)))
6449 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6450 (setq link (read-string "Link: "
6451 (org-link-unescape
6452 (org-match-string-no-properties 1)))))
6453 ((or (org-in-regexp org-angle-link-re)
6454 (org-in-regexp org-plain-link-re))
6455 ;; Convert to bracket link
6456 (setq remove (list (match-beginning 0) (match-end 0))
6457 link (read-string "Link: "
6458 (org-remove-angle-brackets (match-string 0)))))
6459 ((member complete-file '((4) (16)))
6460 ;; Completing read for file names.
6461 (setq file (read-file-name "File: "))
6462 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6463 (pwd1 (file-name-as-directory (abbreviate-file-name
6464 (expand-file-name ".")))))
6465 (cond
6466 ((equal complete-file '(16))
6467 (setq link (org-make-link
6468 "file:"
6469 (abbreviate-file-name (expand-file-name file)))))
6470 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6471 (setq link (org-make-link "file:" (match-string 1 file))))
6472 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6473 (expand-file-name file))
6474 (setq link (org-make-link
6475 "file:" (match-string 1 (expand-file-name file)))))
6476 (t (setq link (org-make-link "file:" file))))))
6478 ;; Read link, with completion for stored links.
6479 (with-output-to-temp-buffer "*Org Links*"
6480 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6481 (when org-stored-links
6482 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6483 (princ (mapconcat
6484 (lambda (x)
6485 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6486 (reverse org-stored-links) "\n"))))
6487 (let ((cw (selected-window)))
6488 (select-window (get-buffer-window "*Org Links*"))
6489 (org-fit-window-to-buffer)
6490 (setq truncate-lines t)
6491 (select-window cw))
6492 ;; Fake a link history, containing the stored links.
6493 (setq tmphist (append (mapcar 'car org-stored-links)
6494 org-insert-link-history))
6495 (unwind-protect
6496 (setq link (org-completing-read
6497 "Link: "
6498 (append
6499 (mapcar (lambda (x) (list (concat (car x) ":")))
6500 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6501 (mapcar (lambda (x) (list (concat x ":")))
6502 org-link-types))
6503 nil nil nil
6504 'tmphist
6505 (or (car (car org-stored-links)))))
6506 (set-window-configuration wcf)
6507 (kill-buffer "*Org Links*"))
6508 (setq entry (assoc link org-stored-links))
6509 (or entry (push link org-insert-link-history))
6510 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6511 (not org-keep-stored-link-after-insertion))
6512 (setq org-stored-links (delq (assoc link org-stored-links)
6513 org-stored-links)))
6514 (setq desc (or desc (nth 1 entry)))))
6516 (if (string-match org-plain-link-re link)
6517 ;; URL-like link, normalize the use of angular brackets.
6518 (setq link (org-make-link (org-remove-angle-brackets link))))
6520 ;; Check if we are linking to the current file with a search option
6521 ;; If yes, simplify the link by using only the search option.
6522 (when (and buffer-file-name
6523 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6524 (let* ((path (match-string 1 link))
6525 (case-fold-search nil)
6526 (search (match-string 2 link)))
6527 (save-match-data
6528 (if (equal (file-truename buffer-file-name) (file-truename path))
6529 ;; We are linking to this same file, with a search option
6530 (setq link search)))))
6532 ;; Check if we can/should use a relative path. If yes, simplify the link
6533 (when (string-match "^file:\\(.*\\)" link)
6534 (let* ((path (match-string 1 link))
6535 (origpath path)
6536 (case-fold-search nil))
6537 (cond
6538 ((or (eq org-link-file-path-type 'absolute)
6539 (equal complete-file '(16)))
6540 (setq path (abbreviate-file-name (expand-file-name path))))
6541 ((eq org-link-file-path-type 'noabbrev)
6542 (setq path (expand-file-name path)))
6543 ((eq org-link-file-path-type 'relative)
6544 (setq path (file-relative-name path)))
6546 (save-match-data
6547 (if (string-match (concat "^" (regexp-quote
6548 (file-name-as-directory
6549 (expand-file-name "."))))
6550 (expand-file-name path))
6551 ;; We are linking a file with relative path name.
6552 (setq path (substring (expand-file-name path)
6553 (match-end 0)))
6554 (setq path (abbreviate-file-name (expand-file-name path)))))))
6555 (setq link (concat "file:" path))
6556 (if (equal desc origpath)
6557 (setq desc path))))
6559 (if org-make-link-description-function
6560 (setq desc (funcall org-make-link-description-function link desc)))
6562 (setq desc (read-string "Description: " desc))
6563 (unless (string-match "\\S-" desc) (setq desc nil))
6564 (if remove (apply 'delete-region remove))
6565 (insert (org-make-link-string link desc))))
6567 (defun org-completing-read (&rest args)
6568 "Completing-read with SPACE being a normal character."
6569 (let ((minibuffer-local-completion-map
6570 (copy-keymap minibuffer-local-completion-map)))
6571 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6572 (apply 'org-ido-completing-read args)))
6574 (defun org-ido-completing-read (&rest args)
6575 "Completing-read using `ido-mode' speedups if available"
6576 (if (and org-completion-use-ido
6577 (fboundp 'ido-completing-read)
6578 (boundp 'ido-mode) ido-mode
6579 (listp (second args)))
6580 (apply 'ido-completing-read (concat "i:" (car args)) (cdr args))
6581 (apply 'completing-read args)))
6583 (defun org-extract-attributes (s)
6584 "Extract the attributes cookie from a string and set as text property."
6585 (let (a attr (start 0) key value)
6586 (save-match-data
6587 (when (string-match "{{\\([^}]+\\)}}$" s)
6588 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6589 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6590 (setq key (match-string 1 a) value (match-string 2 a)
6591 start (match-end 0)
6592 attr (plist-put attr (intern key) value))))
6593 (org-add-props s nil 'org-attributes attr))
6596 (defun org-attributes-to-string (plist)
6597 "Format a property list into an HTML attribute list."
6598 (let ((s "") key value)
6599 (while plist
6600 (setq key (pop plist) value (pop plist))
6601 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6604 ;;; Opening/following a link
6606 (defvar org-link-search-failed nil)
6608 (defun org-next-link ()
6609 "Move forward to the next link.
6610 If the link is in hidden text, expose it."
6611 (interactive)
6612 (when (and org-link-search-failed (eq this-command last-command))
6613 (goto-char (point-min))
6614 (message "Link search wrapped back to beginning of buffer"))
6615 (setq org-link-search-failed nil)
6616 (let* ((pos (point))
6617 (ct (org-context))
6618 (a (assoc :link ct)))
6619 (if a (goto-char (nth 2 a)))
6620 (if (re-search-forward org-any-link-re nil t)
6621 (progn
6622 (goto-char (match-beginning 0))
6623 (if (org-invisible-p) (org-show-context)))
6624 (goto-char pos)
6625 (setq org-link-search-failed t)
6626 (error "No further link found"))))
6628 (defun org-previous-link ()
6629 "Move backward to the previous link.
6630 If the link is in hidden text, expose it."
6631 (interactive)
6632 (when (and org-link-search-failed (eq this-command last-command))
6633 (goto-char (point-max))
6634 (message "Link search wrapped back to end of buffer"))
6635 (setq org-link-search-failed nil)
6636 (let* ((pos (point))
6637 (ct (org-context))
6638 (a (assoc :link ct)))
6639 (if a (goto-char (nth 1 a)))
6640 (if (re-search-backward org-any-link-re nil t)
6641 (progn
6642 (goto-char (match-beginning 0))
6643 (if (org-invisible-p) (org-show-context)))
6644 (goto-char pos)
6645 (setq org-link-search-failed t)
6646 (error "No further link found"))))
6648 (defun org-translate-link (s)
6649 "Translate a link string if a translation function has been defined."
6650 (if (and org-link-translation-function
6651 (fboundp org-link-translation-function)
6652 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6653 (progn
6654 (setq s (funcall org-link-translation-function
6655 (match-string 1) (match-string 2)))
6656 (concat (car s) ":" (cdr s)))
6659 (defun org-translate-link-from-planner (type path)
6660 "Translate a link from Emacs Planner syntax so that Org can follow it.
6661 This is still an experimental function, your mileage may vary."
6662 (cond
6663 ((member type '("http" "https" "news" "ftp"))
6664 ;; standard Internet links are the same.
6665 nil)
6666 ((and (equal type "irc") (string-match "^//" path))
6667 ;; Planner has two / at the beginning of an irc link, we have 1.
6668 ;; We should have zero, actually....
6669 (setq path (substring path 1)))
6670 ((and (equal type "lisp") (string-match "^/" path))
6671 ;; Planner has a slash, we do not.
6672 (setq type "elisp" path (substring path 1)))
6673 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6674 ;; A typical message link. Planner has the id after the fina slash,
6675 ;; we separate it with a hash mark
6676 (setq path (concat (match-string 1 path) "#"
6677 (org-remove-angle-brackets (match-string 2 path)))))
6679 (cons type path))
6681 (defun org-find-file-at-mouse (ev)
6682 "Open file link or URL at mouse."
6683 (interactive "e")
6684 (mouse-set-point ev)
6685 (org-open-at-point 'in-emacs))
6687 (defun org-open-at-mouse (ev)
6688 "Open file link or URL at mouse."
6689 (interactive "e")
6690 (mouse-set-point ev)
6691 (if (eq major-mode 'org-agenda-mode)
6692 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6693 (org-open-at-point))
6695 (defvar org-window-config-before-follow-link nil
6696 "The window configuration before following a link.
6697 This is saved in case the need arises to restore it.")
6699 (defvar org-open-link-marker (make-marker)
6700 "Marker pointing to the location where `org-open-at-point; was called.")
6702 ;;;###autoload
6703 (defun org-open-at-point-global ()
6704 "Follow a link like Org-mode does.
6705 This command can be called in any mode to follow a link that has
6706 Org-mode syntax."
6707 (interactive)
6708 (org-run-like-in-org-mode 'org-open-at-point))
6710 ;;;###autoload
6711 (defun org-open-link-from-string (s &optional arg)
6712 "Open a link in the string S, as if it was in Org-mode."
6713 (interactive "sLink: \nP")
6714 (with-temp-buffer
6715 (let ((org-inhibit-startup t))
6716 (org-mode)
6717 (insert s)
6718 (goto-char (point-min))
6719 (org-open-at-point arg))))
6721 (defun org-open-at-point (&optional in-emacs)
6722 "Open link at or after point.
6723 If there is no link at point, this function will search forward up to
6724 the end of the current subtree.
6725 Normally, files will be opened by an appropriate application. If the
6726 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6727 With a double prefix argument, try to open outside of Emacs, in the
6728 application the system uses for this file type."
6729 (interactive "P")
6730 (org-load-modules-maybe)
6731 (move-marker org-open-link-marker (point))
6732 (setq org-window-config-before-follow-link (current-window-configuration))
6733 (org-remove-occur-highlights nil nil t)
6734 (if (org-at-timestamp-p t)
6735 (org-follow-timestamp-link)
6736 (let (type path link line search (pos (point)))
6737 (catch 'match
6738 (save-excursion
6739 (skip-chars-forward "^]\n\r")
6740 (when (org-in-regexp org-bracket-link-regexp)
6741 (setq link (org-extract-attributes
6742 (org-link-unescape (org-match-string-no-properties 1))))
6743 (while (string-match " *\n *" link)
6744 (setq link (replace-match " " t t link)))
6745 (setq link (org-link-expand-abbrev link))
6746 (cond
6747 ((or (file-name-absolute-p link)
6748 (string-match "^\\.\\.?/" link))
6749 (setq type "file" path link))
6750 ((string-match org-link-re-with-space3 link)
6751 (setq type (match-string 1 link) path (match-string 2 link)))
6752 (t (setq type "thisfile" path link)))
6753 (throw 'match t)))
6755 (when (get-text-property (point) 'org-linked-text)
6756 (setq type "thisfile"
6757 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6758 (1+ (point)) (point))
6759 path (buffer-substring
6760 (previous-single-property-change pos 'org-linked-text)
6761 (next-single-property-change pos 'org-linked-text)))
6762 (throw 'match t))
6764 (save-excursion
6765 (when (or (org-in-regexp org-angle-link-re)
6766 (org-in-regexp org-plain-link-re))
6767 (setq type (match-string 1) path (match-string 2))
6768 (throw 'match t)))
6769 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6770 (setq type "tree-match"
6771 path (match-string 1))
6772 (throw 'match t))
6773 (save-excursion
6774 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6775 (setq type "tags"
6776 path (match-string 1))
6777 (while (string-match ":" path)
6778 (setq path (replace-match "+" t t path)))
6779 (throw 'match t))))
6780 (unless path
6781 (error "No link found"))
6782 ;; Remove any trailing spaces in path
6783 (if (string-match " +\\'" path)
6784 (setq path (replace-match "" t t path)))
6785 (if (and org-link-translation-function
6786 (fboundp org-link-translation-function))
6787 ;; Check if we need to translate the link
6788 (let ((tmp (funcall org-link-translation-function type path)))
6789 (setq type (car tmp) path (cdr tmp))))
6791 (cond
6793 ((assoc type org-link-protocols)
6794 (funcall (nth 1 (assoc type org-link-protocols)) path))
6796 ((equal type "mailto")
6797 (let ((cmd (car org-link-mailto-program))
6798 (args (cdr org-link-mailto-program)) args1
6799 (address path) (subject "") a)
6800 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6801 (setq address (match-string 1 path)
6802 subject (org-link-escape (match-string 2 path))))
6803 (while args
6804 (cond
6805 ((not (stringp (car args))) (push (pop args) args1))
6806 (t (setq a (pop args))
6807 (if (string-match "%a" a)
6808 (setq a (replace-match address t t a)))
6809 (if (string-match "%s" a)
6810 (setq a (replace-match subject t t a)))
6811 (push a args1))))
6812 (apply cmd (nreverse args1))))
6814 ((member type '("http" "https" "ftp" "news"))
6815 (browse-url (concat type ":" (org-link-escape
6816 path org-link-escape-chars-browser))))
6818 ((member type '("message"))
6819 (browse-url (concat type ":" path)))
6821 ((string= type "tags")
6822 (org-tags-view in-emacs path))
6823 ((string= type "thisfile")
6824 (if in-emacs
6825 (switch-to-buffer-other-window
6826 (org-get-buffer-for-internal-link (current-buffer)))
6827 (org-mark-ring-push))
6828 (let ((cmd `(org-link-search
6829 ,path
6830 ,(cond ((equal in-emacs '(4)) 'occur)
6831 ((equal in-emacs '(16)) 'org-occur)
6832 (t nil))
6833 ,pos)))
6834 (condition-case nil (eval cmd)
6835 (error (progn (widen) (eval cmd))))))
6837 ((string= type "tree-match")
6838 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6840 ((string= type "file")
6841 (if (string-match "::\\([0-9]+\\)\\'" path)
6842 (setq line (string-to-number (match-string 1 path))
6843 path (substring path 0 (match-beginning 0)))
6844 (if (string-match "::\\(.+\\)\\'" path)
6845 (setq search (match-string 1 path)
6846 path (substring path 0 (match-beginning 0)))))
6847 (if (string-match "[*?{]" (file-name-nondirectory path))
6848 (dired path)
6849 (org-open-file path in-emacs line search)))
6851 ((string= type "news")
6852 (require 'org-gnus)
6853 (org-gnus-follow-link path))
6855 ((string= type "shell")
6856 (let ((cmd path))
6857 (if (or (not org-confirm-shell-link-function)
6858 (funcall org-confirm-shell-link-function
6859 (format "Execute \"%s\" in shell? "
6860 (org-add-props cmd nil
6861 'face 'org-warning))))
6862 (progn
6863 (message "Executing %s" cmd)
6864 (shell-command cmd))
6865 (error "Abort"))))
6867 ((string= type "elisp")
6868 (let ((cmd path))
6869 (if (or (not org-confirm-elisp-link-function)
6870 (funcall org-confirm-elisp-link-function
6871 (format "Execute \"%s\" as elisp? "
6872 (org-add-props cmd nil
6873 'face 'org-warning))))
6874 (message "%s => %s" cmd
6875 (if (equal (string-to-char cmd) ?\()
6876 (call-interactively (read cmd))
6877 (eval (read cmd))))
6878 (error "Abort"))))
6881 (browse-url-at-point)))))
6882 (move-marker org-open-link-marker nil)
6883 (run-hook-with-args 'org-follow-link-hook))
6885 ;;;; Time estimates
6887 (defun org-get-effort (&optional pom)
6888 "Get the effort estimate for the current entry."
6889 (org-entry-get pom org-effort-property))
6891 ;;; File search
6893 (defvar org-create-file-search-functions nil
6894 "List of functions to construct the right search string for a file link.
6895 These functions are called in turn with point at the location to
6896 which the link should point.
6898 A function in the hook should first test if it would like to
6899 handle this file type, for example by checking the major-mode or
6900 the file extension. If it decides not to handle this file, it
6901 should just return nil to give other functions a chance. If it
6902 does handle the file, it must return the search string to be used
6903 when following the link. The search string will be part of the
6904 file link, given after a double colon, and `org-open-at-point'
6905 will automatically search for it. If special measures must be
6906 taken to make the search successful, another function should be
6907 added to the companion hook `org-execute-file-search-functions',
6908 which see.
6910 A function in this hook may also use `setq' to set the variable
6911 `description' to provide a suggestion for the descriptive text to
6912 be used for this link when it gets inserted into an Org-mode
6913 buffer with \\[org-insert-link].")
6915 (defvar org-execute-file-search-functions nil
6916 "List of functions to execute a file search triggered by a link.
6918 Functions added to this hook must accept a single argument, the
6919 search string that was part of the file link, the part after the
6920 double colon. The function must first check if it would like to
6921 handle this search, for example by checking the major-mode or the
6922 file extension. If it decides not to handle this search, it
6923 should just return nil to give other functions a chance. If it
6924 does handle the search, it must return a non-nil value to keep
6925 other functions from trying.
6927 Each function can access the current prefix argument through the
6928 variable `current-prefix-argument'. Note that a single prefix is
6929 used to force opening a link in Emacs, so it may be good to only
6930 use a numeric or double prefix to guide the search function.
6932 In case this is needed, a function in this hook can also restore
6933 the window configuration before `org-open-at-point' was called using:
6935 (set-window-configuration org-window-config-before-follow-link)")
6937 (defun org-link-search (s &optional type avoid-pos)
6938 "Search for a link search option.
6939 If S is surrounded by forward slashes, it is interpreted as a
6940 regular expression. In org-mode files, this will create an `org-occur'
6941 sparse tree. In ordinary files, `occur' will be used to list matches.
6942 If the current buffer is in `dired-mode', grep will be used to search
6943 in all files. If AVOID-POS is given, ignore matches near that position."
6944 (let ((case-fold-search t)
6945 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6946 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6947 (append '(("") (" ") ("\t") ("\n"))
6948 org-emphasis-alist)
6949 "\\|") "\\)"))
6950 (pos (point))
6951 (pre nil) (post nil)
6952 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6953 (cond
6954 ;; First check if there are any special
6955 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6956 ;; Now try the builtin stuff
6957 ((save-excursion
6958 (goto-char (point-min))
6959 (and
6960 (re-search-forward
6961 (concat "<<" (regexp-quote s0) ">>") nil t)
6962 (setq type 'dedicated
6963 pos (match-beginning 0))))
6964 ;; There is an exact target for this
6965 (goto-char pos))
6966 ((string-match "^/\\(.*\\)/$" s)
6967 ;; A regular expression
6968 (cond
6969 ((org-mode-p)
6970 (org-occur (match-string 1 s)))
6971 ;;((eq major-mode 'dired-mode)
6972 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6973 (t (org-do-occur (match-string 1 s)))))
6975 ;; A normal search strings
6976 (when (equal (string-to-char s) ?*)
6977 ;; Anchor on headlines, post may include tags.
6978 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6979 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6980 s (substring s 1)))
6981 (remove-text-properties
6982 0 (length s)
6983 '(face nil mouse-face nil keymap nil fontified nil) s)
6984 ;; Make a series of regular expressions to find a match
6985 (setq words (org-split-string s "[ \n\r\t]+")
6987 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6988 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6989 "\\)" markers)
6990 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6991 re2a (concat "[ \t\r\n]" re2a_)
6992 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6993 re4 (concat "[^a-zA-Z_]" re4_)
6995 re1 (concat pre re2 post)
6996 re3 (concat pre (if pre re4_ re4) post)
6997 re5 (concat pre ".*" re4)
6998 re2 (concat pre re2)
6999 re2a (concat pre (if pre re2a_ re2a))
7000 re4 (concat pre (if pre re4_ re4))
7001 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7002 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7003 re5 "\\)"
7005 (cond
7006 ((eq type 'org-occur) (org-occur reall))
7007 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7008 (t (goto-char (point-min))
7009 (setq type 'fuzzy)
7010 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7011 (org-search-not-self 1 re1 nil t)
7012 (org-search-not-self 1 re2 nil t)
7013 (org-search-not-self 1 re2a nil t)
7014 (org-search-not-self 1 re3 nil t)
7015 (org-search-not-self 1 re4 nil t)
7016 (org-search-not-self 1 re5 nil t)
7018 (goto-char (match-beginning 1))
7019 (goto-char pos)
7020 (error "No match")))))
7022 ;; Normal string-search
7023 (goto-char (point-min))
7024 (if (search-forward s nil t)
7025 (goto-char (match-beginning 0))
7026 (error "No match"))))
7027 (and (org-mode-p) (org-show-context 'link-search))
7028 type))
7030 (defun org-search-not-self (group &rest args)
7031 "Execute `re-search-forward', but only accept matches that do not
7032 enclose the position of `org-open-link-marker'."
7033 (let ((m org-open-link-marker))
7034 (catch 'exit
7035 (while (apply 're-search-forward args)
7036 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7037 (goto-char (match-end group))
7038 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7039 (> (match-beginning 0) (marker-position m))
7040 (< (match-end 0) (marker-position m)))
7041 (save-match-data
7042 (or (not (org-in-regexp
7043 org-bracket-link-analytic-regexp 1))
7044 (not (match-end 4)) ; no description
7045 (and (<= (match-beginning 4) (point))
7046 (>= (match-end 4) (point))))))
7047 (throw 'exit (point))))))))
7049 (defun org-get-buffer-for-internal-link (buffer)
7050 "Return a buffer to be used for displaying the link target of internal links."
7051 (cond
7052 ((not org-display-internal-link-with-indirect-buffer)
7053 buffer)
7054 ((string-match "(Clone)$" (buffer-name buffer))
7055 (message "Buffer is already a clone, not making another one")
7056 ;; we also do not modify visibility in this case
7057 buffer)
7058 (t ; make a new indirect buffer for displaying the link
7059 (let* ((bn (buffer-name buffer))
7060 (ibn (concat bn "(Clone)"))
7061 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7062 (with-current-buffer ib (org-overview))
7063 ib))))
7065 (defun org-do-occur (regexp &optional cleanup)
7066 "Call the Emacs command `occur'.
7067 If CLEANUP is non-nil, remove the printout of the regular expression
7068 in the *Occur* buffer. This is useful if the regex is long and not useful
7069 to read."
7070 (occur regexp)
7071 (when cleanup
7072 (let ((cwin (selected-window)) win beg end)
7073 (when (setq win (get-buffer-window "*Occur*"))
7074 (select-window win))
7075 (goto-char (point-min))
7076 (when (re-search-forward "match[a-z]+" nil t)
7077 (setq beg (match-end 0))
7078 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7079 (setq end (1- (match-beginning 0)))))
7080 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7081 (goto-char (point-min))
7082 (select-window cwin))))
7084 ;;; The mark ring for links jumps
7086 (defvar org-mark-ring nil
7087 "Mark ring for positions before jumps in Org-mode.")
7088 (defvar org-mark-ring-last-goto nil
7089 "Last position in the mark ring used to go back.")
7090 ;; Fill and close the ring
7091 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7092 (loop for i from 1 to org-mark-ring-length do
7093 (push (make-marker) org-mark-ring))
7094 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7095 org-mark-ring)
7097 (defun org-mark-ring-push (&optional pos buffer)
7098 "Put the current position or POS into the mark ring and rotate it."
7099 (interactive)
7100 (setq pos (or pos (point)))
7101 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7102 (move-marker (car org-mark-ring)
7103 (or pos (point))
7104 (or buffer (current-buffer)))
7105 (message "%s"
7106 (substitute-command-keys
7107 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7109 (defun org-mark-ring-goto (&optional n)
7110 "Jump to the previous position in the mark ring.
7111 With prefix arg N, jump back that many stored positions. When
7112 called several times in succession, walk through the entire ring.
7113 Org-mode commands jumping to a different position in the current file,
7114 or to another Org-mode file, automatically push the old position
7115 onto the ring."
7116 (interactive "p")
7117 (let (p m)
7118 (if (eq last-command this-command)
7119 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7120 (setq p org-mark-ring))
7121 (setq org-mark-ring-last-goto p)
7122 (setq m (car p))
7123 (switch-to-buffer (marker-buffer m))
7124 (goto-char m)
7125 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7127 (defun org-remove-angle-brackets (s)
7128 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7129 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7131 (defun org-add-angle-brackets (s)
7132 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7133 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7135 (defun org-remove-double-quotes (s)
7136 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7137 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7140 ;;; Following specific links
7142 (defun org-follow-timestamp-link ()
7143 (cond
7144 ((org-at-date-range-p t)
7145 (let ((org-agenda-start-on-weekday)
7146 (t1 (match-string 1))
7147 (t2 (match-string 2)))
7148 (setq t1 (time-to-days (org-time-string-to-time t1))
7149 t2 (time-to-days (org-time-string-to-time t2)))
7150 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7151 ((org-at-timestamp-p t)
7152 (org-agenda-list nil (time-to-days (org-time-string-to-time
7153 (substring (match-string 1) 0 10)))
7155 (t (error "This should not happen"))))
7158 ;;; Following file links
7159 (defvar org-wait nil)
7160 (defun org-open-file (path &optional in-emacs line search)
7161 "Open the file at PATH.
7162 First, this expands any special file name abbreviations. Then the
7163 configuration variable `org-file-apps' is checked if it contains an
7164 entry for this file type, and if yes, the corresponding command is launched.
7166 If no application is found, Emacs simply visits the file.
7168 With optional prefix argument IN-EMACS, Emacs will visit the file.
7169 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7170 and o use an external application to visit the file.
7172 Optional LINE specifies a line to go to, optional SEARCH a string to
7173 search for. If LINE or SEARCH is given, the file will always be
7174 opened in Emacs.
7175 If the file does not exist, an error is thrown."
7176 (setq in-emacs (or in-emacs line search))
7177 (let* ((file (if (equal path "")
7178 buffer-file-name
7179 (substitute-in-file-name (expand-file-name path))))
7180 (apps (append org-file-apps (org-default-apps)))
7181 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7182 (dirp (if remp nil (file-directory-p file)))
7183 (file (if (and dirp org-open-directory-means-index-dot-org)
7184 (concat (file-name-as-directory file) "index.org")
7185 file))
7186 (a-m-a-p (assq 'auto-mode apps))
7187 (dfile (downcase file))
7188 (old-buffer (current-buffer))
7189 (old-pos (point))
7190 (old-mode major-mode)
7191 ext cmd)
7192 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7193 (setq ext (match-string 1 dfile))
7194 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7195 (setq ext (match-string 1 dfile))))
7196 (cond
7197 ((equal in-emacs '(16))
7198 (setq cmd (cdr (assoc 'system apps))))
7199 (in-emacs (setq cmd 'emacs))
7201 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7202 (and dirp (cdr (assoc 'directory apps)))
7203 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7204 'string-match)
7205 (cdr (assoc ext apps))
7206 (cdr (assoc t apps))))))
7207 (when (eq cmd 'system)
7208 (setq cmd (cdr (assoc 'system apps))))
7209 (when (eq cmd 'default)
7210 (setq cmd (cdr (assoc t apps))))
7211 (when (eq cmd 'mailcap)
7212 (require 'mailcap)
7213 (mailcap-parse-mailcaps)
7214 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7215 (command (mailcap-mime-info mime-type)))
7216 (if (stringp command)
7217 (setq cmd command)
7218 (setq cmd 'emacs))))
7219 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7220 (not (file-exists-p file))
7221 (not org-open-non-existing-files))
7222 (error "No such file: %s" file))
7223 (cond
7224 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7225 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7226 (while (string-match "['\"]%s['\"]" cmd)
7227 (setq cmd (replace-match "%s" t t cmd)))
7228 (while (string-match "%s" cmd)
7229 (setq cmd (replace-match
7230 (save-match-data
7231 (shell-quote-argument
7232 (convert-standard-filename file)))
7233 t t cmd)))
7234 (save-window-excursion
7235 (start-process-shell-command cmd nil cmd)
7236 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7238 ((or (stringp cmd)
7239 (eq cmd 'emacs))
7240 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7241 (widen)
7242 (if line (goto-line line)
7243 (if search (org-link-search search))))
7244 ((consp cmd)
7245 (let ((file (convert-standard-filename file)))
7246 (eval cmd)))
7247 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7248 (and (org-mode-p) (eq old-mode 'org-mode)
7249 (or (not (equal old-buffer (current-buffer)))
7250 (not (equal old-pos (point))))
7251 (org-mark-ring-push old-pos old-buffer))))
7253 (defun org-default-apps ()
7254 "Return the default applications for this operating system."
7255 (cond
7256 ((eq system-type 'darwin)
7257 org-file-apps-defaults-macosx)
7258 ((eq system-type 'windows-nt)
7259 org-file-apps-defaults-windowsnt)
7260 (t org-file-apps-defaults-gnu)))
7262 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7263 "Convert extensions to regular expressions in the cars of LIST.
7264 Also, weed out any non-string entries, because the return value is used
7265 only for regexp matching.
7266 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7267 point to the symbol `emacs', indicating that the file should
7268 be opened in Emacs."
7269 (append
7270 (delq nil
7271 (mapcar (lambda (x)
7272 (if (not (stringp (car x)))
7274 (if (string-match "\\W" (car x))
7276 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7277 list))
7278 (if add-auto-mode
7279 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7281 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7282 (defun org-file-remote-p (file)
7283 "Test whether FILE specifies a location on a remote system.
7284 Return non-nil if the location is indeed remote.
7286 For example, the filename \"/user@host:/foo\" specifies a location
7287 on the system \"/user@host:\"."
7288 (cond ((fboundp 'file-remote-p)
7289 (file-remote-p file))
7290 ((fboundp 'tramp-handle-file-remote-p)
7291 (tramp-handle-file-remote-p file))
7292 ((and (boundp 'ange-ftp-name-format)
7293 (string-match (car ange-ftp-name-format) file))
7295 (t nil)))
7298 ;;;; Refiling
7300 (defun org-get-org-file ()
7301 "Read a filename, with default directory `org-directory'."
7302 (let ((default (or org-default-notes-file remember-data-file)))
7303 (read-file-name (format "File name [%s]: " default)
7304 (file-name-as-directory org-directory)
7305 default)))
7307 (defun org-notes-order-reversed-p ()
7308 "Check if the current file should receive notes in reversed order."
7309 (cond
7310 ((not org-reverse-note-order) nil)
7311 ((eq t org-reverse-note-order) t)
7312 ((not (listp org-reverse-note-order)) nil)
7313 (t (catch 'exit
7314 (let ((all org-reverse-note-order)
7315 entry)
7316 (while (setq entry (pop all))
7317 (if (string-match (car entry) buffer-file-name)
7318 (throw 'exit (cdr entry))))
7319 nil)))))
7321 (defvar org-refile-target-table nil
7322 "The list of refile targets, created by `org-refile'.")
7324 (defvar org-agenda-new-buffers nil
7325 "Buffers created to visit agenda files.")
7327 (defun org-get-refile-targets (&optional default-buffer)
7328 "Produce a table with refile targets."
7329 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7330 targets txt re files f desc descre)
7331 (with-current-buffer (or default-buffer (current-buffer))
7332 (while (setq entry (pop entries))
7333 (setq files (car entry) desc (cdr entry))
7334 (cond
7335 ((null files) (setq files (list (current-buffer))))
7336 ((eq files 'org-agenda-files)
7337 (setq files (org-agenda-files 'unrestricted)))
7338 ((and (symbolp files) (fboundp files))
7339 (setq files (funcall files)))
7340 ((and (symbolp files) (boundp files))
7341 (setq files (symbol-value files))))
7342 (if (stringp files) (setq files (list files)))
7343 (cond
7344 ((eq (car desc) :tag)
7345 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7346 ((eq (car desc) :todo)
7347 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7348 ((eq (car desc) :regexp)
7349 (setq descre (cdr desc)))
7350 ((eq (car desc) :level)
7351 (setq descre (concat "^\\*\\{" (number-to-string
7352 (if org-odd-levels-only
7353 (1- (* 2 (cdr desc)))
7354 (cdr desc)))
7355 "\\}[ \t]")))
7356 ((eq (car desc) :maxlevel)
7357 (setq descre (concat "^\\*\\{1," (number-to-string
7358 (if org-odd-levels-only
7359 (1- (* 2 (cdr desc)))
7360 (cdr desc)))
7361 "\\}[ \t]")))
7362 (t (error "Bad refiling target description %s" desc)))
7363 (while (setq f (pop files))
7364 (save-excursion
7365 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7366 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7367 (save-excursion
7368 (save-restriction
7369 (widen)
7370 (goto-char (point-min))
7371 (while (re-search-forward descre nil t)
7372 (goto-char (point-at-bol))
7373 (when (looking-at org-complex-heading-regexp)
7374 (setq txt (org-link-display-format (match-string 4))
7375 re (concat "^" (regexp-quote
7376 (buffer-substring (match-beginning 1)
7377 (match-end 4)))))
7378 (if (match-end 5) (setq re (concat re "[ \t]+"
7379 (regexp-quote
7380 (match-string 5)))))
7381 (setq re (concat re "[ \t]*$"))
7382 (when org-refile-use-outline-path
7383 (setq txt (mapconcat 'org-protect-slash
7384 (append
7385 (if (eq org-refile-use-outline-path 'file)
7386 (list (file-name-nondirectory
7387 (buffer-file-name (buffer-base-buffer))))
7388 (if (eq org-refile-use-outline-path 'full-file-path)
7389 (list (buffer-file-name (buffer-base-buffer)))))
7390 (org-get-outline-path)
7391 (list txt))
7392 "/")))
7393 (push (list txt f re (point)) targets))
7394 (goto-char (point-at-eol))))))))
7395 (nreverse targets))))
7397 (defun org-protect-slash (s)
7398 (while (string-match "/" s)
7399 (setq s (replace-match "\\" t t s)))
7402 (defun org-get-outline-path ()
7403 "Return the outline path to the current entry, as a list."
7404 (let (rtn)
7405 (save-excursion
7406 (while (org-up-heading-safe)
7407 (when (looking-at org-complex-heading-regexp)
7408 (push (org-match-string-no-properties 4) rtn)))
7409 rtn)))
7411 (defvar org-refile-history nil
7412 "History for refiling operations.")
7414 (defun org-refile (&optional goto default-buffer)
7415 "Move the entry at point to another heading.
7416 The list of target headings is compiled using the information in
7417 `org-refile-targets', which see. This list is created before each use
7418 and will therefore always be up-to-date.
7420 At the target location, the entry is filed as a subitem of the target heading.
7421 Depending on `org-reverse-note-order', the new subitem will either be the
7422 first or the last subitem.
7424 If there is an active region, all entries in that region will be moved.
7425 However, the region must fulfil the requirement that the first heading
7426 is the first one sets the top-level of the moved text - at most siblings
7427 below it are allowed.
7429 With prefix arg GOTO, the command will only visit the target location,
7430 not actually move anything.
7431 With a double prefix `C-u C-u', go to the location where the last refiling
7432 operation has put the subtree."
7433 (interactive "P")
7434 (let* ((cbuf (current-buffer))
7435 (regionp (org-region-active-p))
7436 (region-start (and regionp (region-beginning)))
7437 (region-end (and regionp (region-end)))
7438 (region-length (and regionp (- region-end region-start)))
7439 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7440 pos it nbuf file re level reversed)
7441 (when regionp (goto-char region-start)
7442 (unless (org-kill-is-subtree-p
7443 (buffer-substring region-start region-end))
7444 (error "The region is not a (sequence of) subtree(s)")))
7445 (if (equal goto '(16))
7446 (org-refile-goto-last-stored)
7447 (when (setq it (org-refile-get-location
7448 (if goto "Goto: " "Refile to: ") default-buffer))
7449 (setq file (nth 1 it)
7450 re (nth 2 it)
7451 pos (nth 3 it))
7452 (setq nbuf (or (find-buffer-visiting file)
7453 (find-file-noselect file)))
7454 (if goto
7455 (progn
7456 (switch-to-buffer nbuf)
7457 (goto-char pos)
7458 (org-show-context 'org-goto))
7459 (if regionp
7460 (progn
7461 (kill-new (buffer-substring region-start region-end))
7462 (org-save-markers-in-region region-start region-end))
7463 (org-copy-subtree 1 nil t))
7464 (save-excursion
7465 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7466 (find-file-noselect file))))
7467 (setq reversed (org-notes-order-reversed-p))
7468 (save-excursion
7469 (save-restriction
7470 (widen)
7471 (goto-char pos)
7472 (looking-at outline-regexp)
7473 (setq level (org-get-valid-level (funcall outline-level) 1))
7474 (goto-char
7475 (if reversed
7476 (or (outline-next-heading) (point-max))
7477 (or (save-excursion (outline-get-next-sibling))
7478 (org-end-of-subtree t t)
7479 (point-max))))
7480 (if (not (bolp)) (newline))
7481 (bookmark-set "org-refile-last-stored")
7482 (org-paste-subtree level))))
7483 (if regionp
7484 (delete-region (point) (+ (point) region-length))
7485 (org-cut-subtree))
7486 (setq org-markers-to-move nil)
7487 (message "Refiled to \"%s\"" (car it)))))))
7489 (defun org-refile-goto-last-stored ()
7490 "Go to the location where the last refile was stored."
7491 (interactive)
7492 (bookmark-jump "org-refile-last-stored")
7493 (message "This is the location of the last refile"))
7495 (defun org-refile-get-location (&optional prompt default-buffer)
7496 "Prompt the user for a refile location, using PROMPT."
7497 (let ((org-refile-targets org-refile-targets)
7498 (org-refile-use-outline-path org-refile-use-outline-path))
7499 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7500 (unless org-refile-target-table
7501 (error "No refile targets"))
7502 (let* ((cbuf (current-buffer))
7503 (cfunc (if org-refile-use-outline-path
7504 'org-olpath-completing-read
7505 'org-ido-completing-read))
7506 (extra (if org-refile-use-outline-path "/" ""))
7507 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7508 (fname (and filename (file-truename filename)))
7509 (tbl (mapcar
7510 (lambda (x)
7511 (if (not (equal fname (file-truename (nth 1 x))))
7512 (cons (concat (car x) extra " ("
7513 (file-name-nondirectory (nth 1 x)) ")")
7514 (cdr x))
7515 (cons (concat (car x) extra) (cdr x))))
7516 org-refile-target-table))
7517 (completion-ignore-case t))
7518 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7519 tbl)))
7521 (defun org-olpath-completing-read (prompt collection &rest args)
7522 "Read an outline path like a file name."
7523 (let ((thetable collection))
7524 (apply
7525 'org-ido-completing-read prompt
7526 (lambda (string predicate &optional flag)
7527 (let (rtn r s f (l (length string)))
7528 (cond
7529 ((eq flag nil)
7530 ;; try completion
7531 (try-completion string thetable))
7532 ((eq flag t)
7533 ;; all-completions
7534 (setq rtn (all-completions string thetable predicate))
7535 (mapcar
7536 (lambda (x)
7537 (setq r (substring x l))
7538 (if (string-match " ([^)]*)$" x)
7539 (setq f (match-string 0 x))
7540 (setq f ""))
7541 (if (string-match "/" r)
7542 (concat string (substring r 0 (match-end 0)) f)
7544 rtn))
7545 ((eq flag 'lambda)
7546 ;; exact match?
7547 (assoc string thetable)))
7549 args)))
7551 ;;;; Dynamic blocks
7553 (defun org-find-dblock (name)
7554 "Find the first dynamic block with name NAME in the buffer.
7555 If not found, stay at current position and return nil."
7556 (let (pos)
7557 (save-excursion
7558 (goto-char (point-min))
7559 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7560 nil t)
7561 (match-beginning 0))))
7562 (if pos (goto-char pos))
7563 pos))
7565 (defconst org-dblock-start-re
7566 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7567 "Matches the startline of a dynamic block, with parameters.")
7569 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7570 "Matches the end of a dyhamic block.")
7572 (defun org-create-dblock (plist)
7573 "Create a dynamic block section, with parameters taken from PLIST.
7574 PLIST must containe a :name entry which is used as name of the block."
7575 (unless (bolp) (newline))
7576 (let ((name (plist-get plist :name)))
7577 (insert "#+BEGIN: " name)
7578 (while plist
7579 (if (eq (car plist) :name)
7580 (setq plist (cddr plist))
7581 (insert " " (prin1-to-string (pop plist)))))
7582 (insert "\n\n#+END:\n")
7583 (beginning-of-line -2)))
7585 (defun org-prepare-dblock ()
7586 "Prepare dynamic block for refresh.
7587 This empties the block, puts the cursor at the insert position and returns
7588 the property list including an extra property :name with the block name."
7589 (unless (looking-at org-dblock-start-re)
7590 (error "Not at a dynamic block"))
7591 (let* ((begdel (1+ (match-end 0)))
7592 (name (org-no-properties (match-string 1)))
7593 (params (append (list :name name)
7594 (read (concat "(" (match-string 3) ")")))))
7595 (unless (re-search-forward org-dblock-end-re nil t)
7596 (error "Dynamic block not terminated"))
7597 (setq params
7598 (append params
7599 (list :content (buffer-substring
7600 begdel (match-beginning 0)))))
7601 (delete-region begdel (match-beginning 0))
7602 (goto-char begdel)
7603 (open-line 1)
7604 params))
7606 (defun org-map-dblocks (&optional command)
7607 "Apply COMMAND to all dynamic blocks in the current buffer.
7608 If COMMAND is not given, use `org-update-dblock'."
7609 (let ((cmd (or command 'org-update-dblock))
7610 pos)
7611 (save-excursion
7612 (goto-char (point-min))
7613 (while (re-search-forward org-dblock-start-re nil t)
7614 (goto-char (setq pos (match-beginning 0)))
7615 (condition-case nil
7616 (funcall cmd)
7617 (error (message "Error during update of dynamic block")))
7618 (goto-char pos)
7619 (unless (re-search-forward org-dblock-end-re nil t)
7620 (error "Dynamic block not terminated"))))))
7622 (defun org-dblock-update (&optional arg)
7623 "User command for updating dynamic blocks.
7624 Update the dynamic block at point. With prefix ARG, update all dynamic
7625 blocks in the buffer."
7626 (interactive "P")
7627 (if arg
7628 (org-update-all-dblocks)
7629 (or (looking-at org-dblock-start-re)
7630 (org-beginning-of-dblock))
7631 (org-update-dblock)))
7633 (defun org-update-dblock ()
7634 "Update the dynamic block at point
7635 This means to empty the block, parse for parameters and then call
7636 the correct writing function."
7637 (save-window-excursion
7638 (let* ((pos (point))
7639 (line (org-current-line))
7640 (params (org-prepare-dblock))
7641 (name (plist-get params :name))
7642 (cmd (intern (concat "org-dblock-write:" name))))
7643 (message "Updating dynamic block `%s' at line %d..." name line)
7644 (funcall cmd params)
7645 (message "Updating dynamic block `%s' at line %d...done" name line)
7646 (goto-char pos))))
7648 (defun org-beginning-of-dblock ()
7649 "Find the beginning of the dynamic block at point.
7650 Error if there is no scuh block at point."
7651 (let ((pos (point))
7652 beg)
7653 (end-of-line 1)
7654 (if (and (re-search-backward org-dblock-start-re nil t)
7655 (setq beg (match-beginning 0))
7656 (re-search-forward org-dblock-end-re nil t)
7657 (> (match-end 0) pos))
7658 (goto-char beg)
7659 (goto-char pos)
7660 (error "Not in a dynamic block"))))
7662 (defun org-update-all-dblocks ()
7663 "Update all dynamic blocks in the buffer.
7664 This function can be used in a hook."
7665 (when (org-mode-p)
7666 (org-map-dblocks 'org-update-dblock)))
7669 ;;;; Completion
7671 (defconst org-additional-option-like-keywords
7672 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7673 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7674 "BEGIN_EXAMPLE" "END_EXAMPLE"
7675 "BEGIN_QUOTE" "END_QUOTE"
7676 "BEGIN_VERSE" "END_VERSE"
7677 "BEGIN_SRC" "END_SRC"))
7679 (defcustom org-structure-template-alist
7681 ("s" "#+begin_src ?\n\n#+end_src"
7682 "<src lang=\"?\">\n\n</src>")
7683 ("e" "#+begin_example\n?\n#+end_example"
7684 "<example>\n?\n</example>")
7685 ("q" "#+begin_quote\n?\n#+end_quote"
7686 "<quote>\n?\n</quote>")
7687 ("v" "#+begin_verse\n?\n#+end_verse"
7688 "<verse>\n?\n/verse>")
7689 ("l" "#+begin_latex\n?\n#+end_latex"
7690 "<literal style=\"latex\">\n?\n</literal>")
7691 ("L" "#+latex: "
7692 "<literal style=\"latex\">?</literal>")
7693 ("h" "#+begin_html\n?\n#+end_html"
7694 "<literal style=\"html\">\n?\n</literal>")
7695 ("H" "#+html: "
7696 "<literal style=\"html\">?</literal>")
7697 ("a" "#+begin_ascii\n?\n#+end_ascii")
7698 ("A" "#+ascii: ")
7699 ("i" "#+include %file ?"
7700 "<include file=%file markup=\"?\">")
7702 "Structure completion elements.
7703 This is a list of abbreviation keys and values. The value gets inserted
7704 it you type @samp{.} followed by the key and then the completion key,
7705 usually `M-TAB'. %file will be replaced by a file name after prompting
7706 for the file uning completion.
7707 There are two templates for each key, the first uses the original Org syntax,
7708 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7709 the default when the /org-mtags.el/ module has been loaded. See also the
7710 variable `org-mtags-prefere-muse-templates'.
7711 This is an experimental feature, it is undecided if it is going to stay in."
7712 :group 'org-completion
7713 :type '(repeat
7714 (string :tag "Key")
7715 (string :tag "Template")
7716 (string :tag "Muse Template")))
7718 (defun org-try-structure-completion ()
7719 "Try to complete a structure template before point.
7720 This looks for strings like \"<e\" on an otherwise empty line and
7721 expands them."
7722 (let ((l (buffer-substring (point-at-bol) (point)))
7724 (when (and (looking-at "[ \t]*$")
7725 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7726 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7727 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7728 (match-beginning 1)) a)
7729 t)))
7731 (defun org-complete-expand-structure-template (start cell)
7732 "Expand a structure template."
7733 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7734 (rpl (nth (if musep 2 1) cell)))
7735 (delete-region start (point))
7736 (when (string-match "\\`#\\+" rpl)
7737 (cond
7738 ((bolp))
7739 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7740 (delete-region (point-at-bol) (point)))
7741 (t (newline))))
7742 (setq start (point))
7743 (if (string-match "%file" rpl)
7744 (setq rpl (replace-match
7745 (concat
7746 "\""
7747 (save-match-data
7748 (abbreviate-file-name (read-file-name "Include file: ")))
7749 "\"")
7750 t t rpl)))
7751 (insert rpl)
7752 (if (re-search-backward "\\?" start t) (delete-char 1))))
7755 (defun org-complete (&optional arg)
7756 "Perform completion on word at point.
7757 At the beginning of a headline, this completes TODO keywords as given in
7758 `org-todo-keywords'.
7759 If the current word is preceded by a backslash, completes the TeX symbols
7760 that are supported for HTML support.
7761 If the current word is preceded by \"#+\", completes special words for
7762 setting file options.
7763 In the line after \"#+STARTUP:, complete valid keywords.\"
7764 At all other locations, this simply calls the value of
7765 `org-completion-fallback-command'."
7766 (interactive "P")
7767 (org-without-partial-completion
7768 (catch 'exit
7769 (let* ((a nil)
7770 (end (point))
7771 (beg1 (save-excursion
7772 (skip-chars-backward (org-re "[:alnum:]_@"))
7773 (point)))
7774 (beg (save-excursion
7775 (skip-chars-backward "a-zA-Z0-9_:$")
7776 (point)))
7777 (confirm (lambda (x) (stringp (car x))))
7778 (searchhead (equal (char-before beg) ?*))
7779 (struct
7780 (when (and (member (char-before beg1) '(?. ?<))
7781 (setq a (assoc (buffer-substring beg1 (point))
7782 org-structure-template-alist)))
7783 (org-complete-expand-structure-template (1- beg1) a)
7784 (throw 'exit t)))
7785 (tag (and (equal (char-before beg1) ?:)
7786 (equal (char-after (point-at-bol)) ?*)))
7787 (prop (and (equal (char-before beg1) ?:)
7788 (not (equal (char-after (point-at-bol)) ?*))))
7789 (texp (equal (char-before beg) ?\\))
7790 (link (equal (char-before beg) ?\[))
7791 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7792 beg)
7793 "#+"))
7794 (startup (string-match "^#\\+STARTUP:.*"
7795 (buffer-substring (point-at-bol) (point))))
7796 (completion-ignore-case opt)
7797 (type nil)
7798 (tbl nil)
7799 (table (cond
7800 (opt
7801 (setq type :opt)
7802 (require 'org-exp)
7803 (append
7804 (mapcar
7805 (lambda (x)
7806 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7807 (cons (match-string 2 x) (match-string 1 x)))
7808 (org-split-string (org-get-current-options) "\n"))
7809 (mapcar 'list org-additional-option-like-keywords)))
7810 (startup
7811 (setq type :startup)
7812 org-startup-options)
7813 (link (append org-link-abbrev-alist-local
7814 org-link-abbrev-alist))
7815 (texp
7816 (setq type :tex)
7817 org-html-entities)
7818 ((string-match "\\`\\*+[ \t]+\\'"
7819 (buffer-substring (point-at-bol) beg))
7820 (setq type :todo)
7821 (mapcar 'list org-todo-keywords-1))
7822 (searchhead
7823 (setq type :searchhead)
7824 (save-excursion
7825 (goto-char (point-min))
7826 (while (re-search-forward org-todo-line-regexp nil t)
7827 (push (list
7828 (org-make-org-heading-search-string
7829 (match-string 3) t))
7830 tbl)))
7831 tbl)
7832 (tag (setq type :tag beg beg1)
7833 (or org-tag-alist (org-get-buffer-tags)))
7834 (prop (setq type :prop beg beg1)
7835 (mapcar 'list (org-buffer-property-keys nil t t)))
7836 (t (progn
7837 (call-interactively org-completion-fallback-command)
7838 (throw 'exit nil)))))
7839 (pattern (buffer-substring-no-properties beg end))
7840 (completion (try-completion pattern table confirm)))
7841 (cond ((eq completion t)
7842 (if (not (assoc (upcase pattern) table))
7843 (message "Already complete")
7844 (if (and (equal type :opt)
7845 (not (member (car (assoc (upcase pattern) table))
7846 org-additional-option-like-keywords)))
7847 (insert (substring (cdr (assoc (upcase pattern) table))
7848 (length pattern)))
7849 (if (memq type '(:tag :prop)) (insert ":")))))
7850 ((null completion)
7851 (message "Can't find completion for \"%s\"" pattern)
7852 (ding))
7853 ((not (string= pattern completion))
7854 (delete-region beg end)
7855 (if (string-match " +$" completion)
7856 (setq completion (replace-match "" t t completion)))
7857 (insert completion)
7858 (if (get-buffer-window "*Completions*")
7859 (delete-window (get-buffer-window "*Completions*")))
7860 (if (assoc completion table)
7861 (if (eq type :todo) (insert " ")
7862 (if (memq type '(:tag :prop)) (insert ":"))))
7863 (if (and (equal type :opt) (assoc completion table))
7864 (message "%s" (substitute-command-keys
7865 "Press \\[org-complete] again to insert example settings"))))
7867 (message "Making completion list...")
7868 (let ((list (sort (all-completions pattern table confirm)
7869 'string<)))
7870 (with-output-to-temp-buffer "*Completions*"
7871 (condition-case nil
7872 ;; Protection needed for XEmacs and emacs 21
7873 (display-completion-list list pattern)
7874 (error (display-completion-list list)))))
7875 (message "Making completion list...%s" "done")))))))
7877 ;;;; TODO, DEADLINE, Comments
7879 (defun org-toggle-comment ()
7880 "Change the COMMENT state of an entry."
7881 (interactive)
7882 (save-excursion
7883 (org-back-to-heading)
7884 (let (case-fold-search)
7885 (if (looking-at (concat outline-regexp
7886 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7887 (replace-match "" t t nil 1)
7888 (if (looking-at outline-regexp)
7889 (progn
7890 (goto-char (match-end 0))
7891 (insert org-comment-string " ")))))))
7893 (defvar org-last-todo-state-is-todo nil
7894 "This is non-nil when the last TODO state change led to a TODO state.
7895 If the last change removed the TODO tag or switched to DONE, then
7896 this is nil.")
7898 (defvar org-setting-tags nil) ; dynamically skiped
7900 (defun org-parse-local-options (string var)
7901 "Parse STRING for startup setting relevant for variable VAR."
7902 (let ((rtn (symbol-value var))
7903 e opts)
7904 (save-match-data
7905 (if (or (not string) (not (string-match "\\S-" string)))
7907 (setq opts (delq nil (mapcar (lambda (x)
7908 (setq e (assoc x org-startup-options))
7909 (if (eq (nth 1 e) var) e nil))
7910 (org-split-string string "[ \t]+"))))
7911 (if (not opts)
7913 (setq rtn nil)
7914 (while (setq e (pop opts))
7915 (if (not (nth 3 e))
7916 (setq rtn (nth 2 e))
7917 (if (not (listp rtn)) (setq rtn nil))
7918 (push (nth 2 e) rtn)))
7919 rtn)))))
7921 (defvar org-blocker-hook nil
7922 "Hook for functions that are allowed to block a state change.
7924 Each function gets as its single argument a property list, see
7925 `org-trigger-hook' for more information about this list.
7927 If any of the functions in this hook returns nil, the state change
7928 is blocked.")
7930 (defvar org-trigger-hook nil
7931 "Hook for functions that are triggered by a state change.
7933 Each function gets as its single argument a property list with at least
7934 the following elements:
7936 (:type type-of-change :position pos-at-entry-start
7937 :from old-state :to new-state)
7939 Depending on the type, more properties may be present.
7941 This mechanism is currently implemented for:
7943 TODO state changes
7944 ------------------
7945 :type todo-state-change
7946 :from previous state (keyword as a string), or nil
7947 :to new state (keyword as a string), or nil")
7949 (defvar org-agenda-headline-snapshot-before-repeat)
7950 (defun org-todo (&optional arg)
7951 "Change the TODO state of an item.
7952 The state of an item is given by a keyword at the start of the heading,
7953 like
7954 *** TODO Write paper
7955 *** DONE Call mom
7957 The different keywords are specified in the variable `org-todo-keywords'.
7958 By default the available states are \"TODO\" and \"DONE\".
7959 So for this example: when the item starts with TODO, it is changed to DONE.
7960 When it starts with DONE, the DONE is removed. And when neither TODO nor
7961 DONE are present, add TODO at the beginning of the heading.
7963 With C-u prefix arg, use completion to determine the new state.
7964 With numeric prefix arg, switch to that state.
7966 For calling through lisp, arg is also interpreted in the following way:
7967 'none -> empty state
7968 \"\"(empty string) -> switch to empty state
7969 'done -> switch to DONE
7970 'nextset -> switch to the next set of keywords
7971 'previousset -> switch to the previous set of keywords
7972 \"WAITING\" -> switch to the specified keyword, but only if it
7973 really is a member of `org-todo-keywords'."
7974 (interactive "P")
7975 (save-excursion
7976 (catch 'exit
7977 (org-back-to-heading)
7978 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7979 (or (looking-at (concat " +" org-todo-regexp " *"))
7980 (looking-at " *"))
7981 (let* ((match-data (match-data))
7982 (startpos (point-at-bol))
7983 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7984 (org-log-done org-log-done)
7985 (org-log-repeat org-log-repeat)
7986 (org-todo-log-states org-todo-log-states)
7987 (this (match-string 1))
7988 (hl-pos (match-beginning 0))
7989 (head (org-get-todo-sequence-head this))
7990 (ass (assoc head org-todo-kwd-alist))
7991 (interpret (nth 1 ass))
7992 (done-word (nth 3 ass))
7993 (final-done-word (nth 4 ass))
7994 (last-state (or this ""))
7995 (completion-ignore-case t)
7996 (member (member this org-todo-keywords-1))
7997 (tail (cdr member))
7998 (state (cond
7999 ((and org-todo-key-trigger
8000 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8001 (and (not arg) org-use-fast-todo-selection
8002 (not (eq org-use-fast-todo-selection 'prefix)))))
8003 ;; Use fast selection
8004 (org-fast-todo-selection))
8005 ((and (equal arg '(4))
8006 (or (not org-use-fast-todo-selection)
8007 (not org-todo-key-trigger)))
8008 ;; Read a state with completion
8009 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8010 org-todo-keywords-1)
8011 nil t))
8012 ((eq arg 'right)
8013 (if this
8014 (if tail (car tail) nil)
8015 (car org-todo-keywords-1)))
8016 ((eq arg 'left)
8017 (if (equal member org-todo-keywords-1)
8019 (if this
8020 (nth (- (length org-todo-keywords-1) (length tail) 2)
8021 org-todo-keywords-1)
8022 (org-last org-todo-keywords-1))))
8023 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8024 (setq arg nil))) ; hack to fall back to cycling
8025 (arg
8026 ;; user or caller requests a specific state
8027 (cond
8028 ((equal arg "") nil)
8029 ((eq arg 'none) nil)
8030 ((eq arg 'done) (or done-word (car org-done-keywords)))
8031 ((eq arg 'nextset)
8032 (or (car (cdr (member head org-todo-heads)))
8033 (car org-todo-heads)))
8034 ((eq arg 'previousset)
8035 (let ((org-todo-heads (reverse org-todo-heads)))
8036 (or (car (cdr (member head org-todo-heads)))
8037 (car org-todo-heads))))
8038 ((car (member arg org-todo-keywords-1)))
8039 ((nth (1- (prefix-numeric-value arg))
8040 org-todo-keywords-1))))
8041 ((null member) (or head (car org-todo-keywords-1)))
8042 ((equal this final-done-word) nil) ;; -> make empty
8043 ((null tail) nil) ;; -> first entry
8044 ((eq interpret 'sequence)
8045 (car tail))
8046 ((memq interpret '(type priority))
8047 (if (eq this-command last-command)
8048 (car tail)
8049 (if (> (length tail) 0)
8050 (or done-word (car org-done-keywords))
8051 nil)))
8052 (t nil)))
8053 (next (if state (concat " " state " ") " "))
8054 (change-plist (list :type 'todo-state-change :from this :to state
8055 :position startpos))
8056 dolog now-done-p)
8057 (when org-blocker-hook
8058 (unless (save-excursion
8059 (save-match-data
8060 (run-hook-with-args-until-failure
8061 'org-blocker-hook change-plist)))
8062 (if (interactive-p)
8063 (error "TODO state change from %s to %s blocked" this state)
8064 ;; fail silently
8065 (message "TODO state change from %s to %s blocked" this state)
8066 (throw 'exit nil))))
8067 (store-match-data match-data)
8068 (replace-match next t t)
8069 (unless (pos-visible-in-window-p hl-pos)
8070 (message "TODO state changed to %s" (org-trim next)))
8071 (unless head
8072 (setq head (org-get-todo-sequence-head state)
8073 ass (assoc head org-todo-kwd-alist)
8074 interpret (nth 1 ass)
8075 done-word (nth 3 ass)
8076 final-done-word (nth 4 ass)))
8077 (when (memq arg '(nextset previousset))
8078 (message "Keyword-Set %d/%d: %s"
8079 (- (length org-todo-sets) -1
8080 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8081 (length org-todo-sets)
8082 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8083 (setq org-last-todo-state-is-todo
8084 (not (member state org-done-keywords)))
8085 (setq now-done-p (and (member state org-done-keywords)
8086 (not (member this org-done-keywords))))
8087 (and logging (org-local-logging logging))
8088 (when (and (or org-todo-log-states org-log-done)
8089 (not (memq arg '(nextset previousset))))
8090 ;; we need to look at recording a time and note
8091 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8092 (nth 2 (assoc this org-todo-log-states))))
8093 (when (and state
8094 (member state org-not-done-keywords)
8095 (not (member this org-not-done-keywords)))
8096 ;; This is now a todo state and was not one before
8097 ;; If there was a CLOSED time stamp, get rid of it.
8098 (org-add-planning-info nil nil 'closed))
8099 (when (and now-done-p org-log-done)
8100 ;; It is now done, and it was not done before
8101 (org-add-planning-info 'closed (org-current-time))
8102 (if (and (not dolog) (eq 'note org-log-done))
8103 (org-add-log-setup 'done state 'findpos 'note)))
8104 (when (and state dolog)
8105 ;; This is a non-nil state, and we need to log it
8106 (org-add-log-setup 'state state 'findpos dolog)))
8107 ;; Fixup tag positioning
8108 (org-todo-trigger-tag-changes state)
8109 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8110 (when org-provide-todo-statistics
8111 (org-update-parent-todo-statistics))
8112 (run-hooks 'org-after-todo-state-change-hook)
8113 (if (and arg (not (member state org-done-keywords)))
8114 (setq head (org-get-todo-sequence-head state)))
8115 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8116 ;; Do we need to trigger a repeat?
8117 (when now-done-p
8118 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8119 ;; This is for the agenda, take a snapshot of the headline.
8120 (save-match-data
8121 (setq org-agenda-headline-snapshot-before-repeat
8122 (org-get-heading))))
8123 (org-auto-repeat-maybe state))
8124 ;; Fixup cursor location if close to the keyword
8125 (if (and (outline-on-heading-p)
8126 (not (bolp))
8127 (save-excursion (beginning-of-line 1)
8128 (looking-at org-todo-line-regexp))
8129 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8130 (progn
8131 (goto-char (or (match-end 2) (match-end 1)))
8132 (just-one-space)))
8133 (when org-trigger-hook
8134 (save-excursion
8135 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8137 (defun org-update-parent-todo-statistics ()
8138 "Update any statistics cookie in the parent of the current headline."
8139 (interactive)
8140 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8141 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8142 (catch 'exit
8143 (save-excursion
8144 (setq level (org-up-heading-safe))
8145 (unless (and level
8146 (re-search-forward box-re (point-at-eol) t))
8147 (throw 'exit nil))
8148 (setq is-percent (match-end 2))
8149 (save-match-data
8150 (unless (outline-next-heading) (throw 'exit nil))
8151 (while (looking-at org-todo-line-regexp)
8152 (setq kwd (match-string 2))
8153 (and kwd (setq cnt-all (1+ cnt-all)))
8154 (and (member kwd org-done-keywords)
8155 (setq cnt-done (1+ cnt-done)))
8156 (condition-case nil
8157 (org-forward-same-level 1)
8158 (error (end-of-line 1)))))
8159 (replace-match
8160 (if is-percent
8161 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8162 (format "[%d/%d]" cnt-done cnt-all)))
8163 (run-hook-with-args 'org-after-todo-statistics-hook
8164 cnt-done (- cnt-all cnt-done))))))
8166 (defvar org-after-todo-statistics-hook nil
8167 "Hook that is called after a TODO statistics cookie has been updated.
8168 Each function is called with two arguments: the number of not-done entries
8169 and the number of done entries.
8171 For example, the following function, when added to this hook, will switch
8172 an entry to DONE when all children are done, and back to TODO when new
8173 entries are set to a TODO status. Note that this hook is only called
8174 when there is a statistics cookie in the headline!
8176 (defun org-summary-todo (n-done n-not-done)
8177 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8178 (let (org-log-done org-log-states) ; turn off logging
8179 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8182 (defun org-todo-trigger-tag-changes (state)
8183 "Apply the changes defined in `org-todo-state-tags-triggers'."
8184 (let ((l org-todo-state-tags-triggers)
8185 changes)
8186 (when (or (not state) (equal state ""))
8187 (setq changes (append changes (cdr (assoc "" l)))))
8188 (when (and (stringp state) (> (length state) 0))
8189 (setq changes (append changes (cdr (assoc state l)))))
8190 (when (member state org-not-done-keywords)
8191 (setq changes (append changes (cdr (assoc 'todo l)))))
8192 (when (member state org-done-keywords)
8193 (setq changes (append changes (cdr (assoc 'done l)))))
8194 (dolist (c changes)
8195 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8197 (defun org-local-logging (value)
8198 "Get logging settings from a property VALUE."
8199 (let* (words w a)
8200 ;; directly set the variables, they are already local.
8201 (setq org-log-done nil
8202 org-log-repeat nil
8203 org-todo-log-states nil)
8204 (setq words (org-split-string value))
8205 (while (setq w (pop words))
8206 (cond
8207 ((setq a (assoc w org-startup-options))
8208 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8209 (set (nth 1 a) (nth 2 a))))
8210 ((setq a (org-extract-log-state-settings w))
8211 (and (member (car a) org-todo-keywords-1)
8212 (push a org-todo-log-states)))))))
8214 (defun org-get-todo-sequence-head (kwd)
8215 "Return the head of the TODO sequence to which KWD belongs.
8216 If KWD is not set, check if there is a text property remembering the
8217 right sequence."
8218 (let (p)
8219 (cond
8220 ((not kwd)
8221 (or (get-text-property (point-at-bol) 'org-todo-head)
8222 (progn
8223 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8224 nil (point-at-eol)))
8225 (get-text-property p 'org-todo-head))))
8226 ((not (member kwd org-todo-keywords-1))
8227 (car org-todo-keywords-1))
8228 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8230 (defun org-fast-todo-selection ()
8231 "Fast TODO keyword selection with single keys.
8232 Returns the new TODO keyword, or nil if no state change should occur."
8233 (let* ((fulltable org-todo-key-alist)
8234 (done-keywords org-done-keywords) ;; needed for the faces.
8235 (maxlen (apply 'max (mapcar
8236 (lambda (x)
8237 (if (stringp (car x)) (string-width (car x)) 0))
8238 fulltable)))
8239 (expert nil)
8240 (fwidth (+ maxlen 3 1 3))
8241 (ncol (/ (- (window-width) 4) fwidth))
8242 tg cnt e c tbl
8243 groups ingroup)
8244 (save-window-excursion
8245 (if expert
8246 (set-buffer (get-buffer-create " *Org todo*"))
8247 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8248 (erase-buffer)
8249 (org-set-local 'org-done-keywords done-keywords)
8250 (setq tbl fulltable cnt 0)
8251 (while (setq e (pop tbl))
8252 (cond
8253 ((equal e '(:startgroup))
8254 (push '() groups) (setq ingroup t)
8255 (when (not (= cnt 0))
8256 (setq cnt 0)
8257 (insert "\n"))
8258 (insert "{ "))
8259 ((equal e '(:endgroup))
8260 (setq ingroup nil cnt 0)
8261 (insert "}\n"))
8263 (setq tg (car e) c (cdr e))
8264 (if ingroup (push tg (car groups)))
8265 (setq tg (org-add-props tg nil 'face
8266 (org-get-todo-face tg)))
8267 (if (and (= cnt 0) (not ingroup)) (insert " "))
8268 (insert "[" c "] " tg (make-string
8269 (- fwidth 4 (length tg)) ?\ ))
8270 (when (= (setq cnt (1+ cnt)) ncol)
8271 (insert "\n")
8272 (if ingroup (insert " "))
8273 (setq cnt 0)))))
8274 (insert "\n")
8275 (goto-char (point-min))
8276 (if (not expert) (org-fit-window-to-buffer))
8277 (message "[a-z..]:Set [SPC]:clear")
8278 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8279 (cond
8280 ((or (= c ?\C-g)
8281 (and (= c ?q) (not (rassoc c fulltable))))
8282 (setq quit-flag t))
8283 ((= c ?\ ) nil)
8284 ((setq e (rassoc c fulltable) tg (car e))
8286 (t (setq quit-flag t))))))
8288 (defun org-entry-is-todo-p ()
8289 (member (org-get-todo-state) org-not-done-keywords))
8291 (defun org-entry-is-done-p ()
8292 (member (org-get-todo-state) org-done-keywords))
8294 (defun org-get-todo-state ()
8295 (save-excursion
8296 (org-back-to-heading t)
8297 (and (looking-at org-todo-line-regexp)
8298 (match-end 2)
8299 (match-string 2))))
8301 (defun org-at-date-range-p (&optional inactive-ok)
8302 "Is the cursor inside a date range?"
8303 (interactive)
8304 (save-excursion
8305 (catch 'exit
8306 (let ((pos (point)))
8307 (skip-chars-backward "^[<\r\n")
8308 (skip-chars-backward "<[")
8309 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8310 (>= (match-end 0) pos)
8311 (throw 'exit t))
8312 (skip-chars-backward "^<[\r\n")
8313 (skip-chars-backward "<[")
8314 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8315 (>= (match-end 0) pos)
8316 (throw 'exit t)))
8317 nil)))
8319 (defun org-get-repeat ()
8320 "Check if there is a deadline/schedule with repeater in this entry."
8321 (save-match-data
8322 (save-excursion
8323 (org-back-to-heading t)
8324 (if (re-search-forward
8325 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8326 (match-string 1)))))
8328 (defvar org-last-changed-timestamp)
8329 (defvar org-last-inserted-timestamp)
8330 (defvar org-log-post-message)
8331 (defvar org-log-note-purpose)
8332 (defvar org-log-note-how)
8333 (defvar org-log-note-extra)
8334 (defun org-auto-repeat-maybe (done-word)
8335 "Check if the current headline contains a repeated deadline/schedule.
8336 If yes, set TODO state back to what it was and change the base date
8337 of repeating deadline/scheduled time stamps to new date.
8338 This function is run automatically after each state change to a DONE state."
8339 ;; last-state is dynamically scoped into this function
8340 (let* ((repeat (org-get-repeat))
8341 (aa (assoc last-state org-todo-kwd-alist))
8342 (interpret (nth 1 aa))
8343 (head (nth 2 aa))
8344 (whata '(("d" . day) ("m" . month) ("y" . year)))
8345 (msg "Entry repeats: ")
8346 (org-log-done nil)
8347 (org-todo-log-states nil)
8348 (nshiftmax 10) (nshift 0)
8349 re type n what ts mb0 time)
8350 (when repeat
8351 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8352 (org-todo (if (eq interpret 'type) last-state head))
8353 (when org-log-repeat
8354 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8355 (memq 'org-add-log-note post-command-hook))
8356 ;; OK, we are already setup for some record
8357 (if (eq org-log-repeat 'note)
8358 ;; make sure we take a note, not only a time stamp
8359 (setq org-log-note-how 'note))
8360 ;; Set up for taking a record
8361 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8362 'findpos org-log-repeat)))
8363 (org-back-to-heading t)
8364 (org-add-planning-info nil nil 'closed)
8365 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8366 org-deadline-time-regexp "\\)\\|\\("
8367 org-ts-regexp "\\)"))
8368 (while (re-search-forward
8369 re (save-excursion (outline-next-heading) (point)) t)
8370 (setq type (if (match-end 1) org-scheduled-string
8371 (if (match-end 3) org-deadline-string "Plain:"))
8372 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8373 mb0 (match-beginning 0))
8374 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8375 (setq n (string-to-number (match-string 2 ts))
8376 what (match-string 3 ts))
8377 (if (equal what "w") (setq n (* n 7) what "d"))
8378 ;; Preparation, see if we need to modify the start date for the change
8379 (when (match-end 1)
8380 (setq time (save-match-data (org-time-string-to-time ts)))
8381 (cond
8382 ((equal (match-string 1 ts) ".")
8383 ;; Shift starting date to today
8384 (org-timestamp-change
8385 (- (time-to-days (current-time)) (time-to-days time))
8386 'day))
8387 ((equal (match-string 1 ts) "+")
8388 (while (or (= nshift 0)
8389 (<= (time-to-days time) (time-to-days (current-time))))
8390 (when (= (incf nshift) nshiftmax)
8391 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8392 (error "Abort")))
8393 (org-timestamp-change n (cdr (assoc what whata)))
8394 (org-at-timestamp-p t)
8395 (setq ts (match-string 1))
8396 (setq time (save-match-data (org-time-string-to-time ts))))
8397 (org-timestamp-change (- n) (cdr (assoc what whata)))
8398 ;; rematch, so that we have everything in place for the real shift
8399 (org-at-timestamp-p t)
8400 (setq ts (match-string 1))
8401 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8402 (org-timestamp-change n (cdr (assoc what whata)))
8403 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8404 (setq org-log-post-message msg)
8405 (message "%s" msg))))
8407 (defun org-show-todo-tree (arg)
8408 "Make a compact tree which shows all headlines marked with TODO.
8409 The tree will show the lines where the regexp matches, and all higher
8410 headlines above the match.
8411 With a \\[universal-argument] prefix, also show the DONE entries.
8412 With a numeric prefix N, construct a sparse tree for the Nth element
8413 of `org-todo-keywords-1'."
8414 (interactive "P")
8415 (let ((case-fold-search nil)
8416 (kwd-re
8417 (cond ((null arg) org-not-done-regexp)
8418 ((equal arg '(4))
8419 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8420 (mapcar 'list org-todo-keywords-1))))
8421 (concat "\\("
8422 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8423 "\\)\\>")))
8424 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8425 (regexp-quote (nth (1- (prefix-numeric-value arg))
8426 org-todo-keywords-1)))
8427 (t (error "Invalid prefix argument: %s" arg)))))
8428 (message "%d TODO entries found"
8429 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8431 (defun org-deadline (&optional remove time)
8432 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8433 With argument REMOVE, remove any deadline from the item.
8434 When TIME is set, it should be an internal time specification, and the
8435 scheduling will use the corresponding date."
8436 (interactive "P")
8437 (if remove
8438 (progn
8439 (org-remove-timestamp-with-keyword org-deadline-string)
8440 (message "Item no longer has a deadline."))
8441 (if (org-get-repeat)
8442 (error "Cannot change deadline on task with repeater, please do that by hand")
8443 (org-add-planning-info 'deadline time 'closed)
8444 (message "Deadline on %s" org-last-inserted-timestamp))))
8446 (defun org-schedule (&optional remove time)
8447 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8448 With argument REMOVE, remove any scheduling date from the item.
8449 When TIME is set, it should be an internal time specification, and the
8450 scheduling will use the corresponding date."
8451 (interactive "P")
8452 (if remove
8453 (progn
8454 (org-remove-timestamp-with-keyword org-scheduled-string)
8455 (message "Item is no longer scheduled."))
8456 (if (org-get-repeat)
8457 (error "Cannot reschedule task with repeater, please do that by hand")
8458 (org-add-planning-info 'scheduled time 'closed)
8459 (message "Scheduled to %s" org-last-inserted-timestamp))))
8461 (defun org-remove-timestamp-with-keyword (keyword)
8462 "Remove all time stamps with KEYWORD in the current entry."
8463 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8464 beg)
8465 (save-excursion
8466 (org-back-to-heading t)
8467 (setq beg (point))
8468 (org-end-of-subtree t t)
8469 (while (re-search-backward re beg t)
8470 (replace-match "")
8471 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8472 (equal (char-before) ?\ ))
8473 (backward-delete-char 1)
8474 (if (string-match "^[ \t]*$" (buffer-substring
8475 (point-at-bol) (point-at-eol)))
8476 (delete-region (point-at-bol)
8477 (min (point-max) (1+ (point-at-eol))))))))))
8479 (defun org-add-planning-info (what &optional time &rest remove)
8480 "Insert new timestamp with keyword in the line directly after the headline.
8481 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8482 If non is given, the user is prompted for a date.
8483 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8484 be removed."
8485 (interactive)
8486 (let (org-time-was-given org-end-time-was-given ts
8487 end default-time default-input)
8489 (when (and (not time) (memq what '(scheduled deadline)))
8490 ;; Try to get a default date/time from existing timestamp
8491 (save-excursion
8492 (org-back-to-heading t)
8493 (setq end (save-excursion (outline-next-heading) (point)))
8494 (when (re-search-forward (if (eq what 'scheduled)
8495 org-scheduled-time-regexp
8496 org-deadline-time-regexp)
8497 end t)
8498 (setq ts (match-string 1)
8499 default-time
8500 (apply 'encode-time (org-parse-time-string ts))
8501 default-input (and ts (org-get-compact-tod ts))))))
8502 (when what
8503 ;; If necessary, get the time from the user
8504 (setq time (or time (org-read-date nil 'to-time nil nil
8505 default-time default-input))))
8507 (when (and org-insert-labeled-timestamps-at-point
8508 (member what '(scheduled deadline)))
8509 (insert
8510 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8511 (org-insert-time-stamp time org-time-was-given
8512 nil nil nil (list org-end-time-was-given))
8513 (setq what nil))
8514 (save-excursion
8515 (save-restriction
8516 (let (col list elt ts buffer-invisibility-spec)
8517 (org-back-to-heading t)
8518 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8519 (goto-char (match-end 1))
8520 (setq col (current-column))
8521 (goto-char (match-end 0))
8522 (if (eobp) (insert "\n") (forward-char 1))
8523 (if (and (not (looking-at outline-regexp))
8524 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8525 "[^\r\n]*"))
8526 (not (equal (match-string 1) org-clock-string)))
8527 (narrow-to-region (match-beginning 0) (match-end 0))
8528 (insert-before-markers "\n")
8529 (backward-char 1)
8530 (narrow-to-region (point) (point))
8531 (and org-adapt-indentation (org-indent-to-column col)))
8532 ;; Check if we have to remove something.
8533 (setq list (cons what remove))
8534 (while list
8535 (setq elt (pop list))
8536 (goto-char (point-min))
8537 (when (or (and (eq elt 'scheduled)
8538 (re-search-forward org-scheduled-time-regexp nil t))
8539 (and (eq elt 'deadline)
8540 (re-search-forward org-deadline-time-regexp nil t))
8541 (and (eq elt 'closed)
8542 (re-search-forward org-closed-time-regexp nil t)))
8543 (replace-match "")
8544 (if (looking-at "--+<[^>]+>") (replace-match ""))
8545 (if (looking-at " +") (replace-match ""))))
8546 (goto-char (point-max))
8547 (when what
8548 (insert
8549 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8550 (cond ((eq what 'scheduled) org-scheduled-string)
8551 ((eq what 'deadline) org-deadline-string)
8552 ((eq what 'closed) org-closed-string))
8553 " ")
8554 (setq ts (org-insert-time-stamp
8555 time
8556 (or org-time-was-given
8557 (and (eq what 'closed) org-log-done-with-time))
8558 (eq what 'closed)
8559 nil nil (list org-end-time-was-given)))
8560 (end-of-line 1))
8561 (goto-char (point-min))
8562 (widen)
8563 (if (and (looking-at "[ \t]+\n")
8564 (equal (char-before) ?\n))
8565 (delete-region (1- (point)) (point-at-eol)))
8566 ts)))))
8568 (defvar org-log-note-marker (make-marker))
8569 (defvar org-log-note-purpose nil)
8570 (defvar org-log-note-state nil)
8571 (defvar org-log-note-how nil)
8572 (defvar org-log-note-extra nil)
8573 (defvar org-log-note-window-configuration nil)
8574 (defvar org-log-note-return-to (make-marker))
8575 (defvar org-log-post-message nil
8576 "Message to be displayed after a log note has been stored.
8577 The auto-repeater uses this.")
8579 (defun org-add-note ()
8580 "Add a note to the current entry.
8581 This is done in the same way as adding a state change note."
8582 (interactive)
8583 (org-add-log-setup 'note nil 'findpos nil))
8585 (defvar org-property-end-re)
8586 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8587 "Set up the post command hook to take a note.
8588 If this is about to TODO state change, the new state is expected in STATE.
8589 When FINDPOS is non-nil, find the correct position for the note in
8590 the current entry. If not, assume that it can be inserted at point.
8591 HOW is an indicator what kind of note should be created.
8592 EXTRA is additional text that will be inserted into the notes buffer."
8593 (save-restriction
8594 (save-excursion
8595 (when findpos
8596 (org-back-to-heading t)
8597 (narrow-to-region (point) (save-excursion
8598 (outline-next-heading) (point)))
8599 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8600 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8601 "[^\r\n]*\\)?"))
8602 (goto-char (match-end 0))
8603 (when (and org-log-state-notes-insert-after-drawers
8604 (save-excursion
8605 (forward-line) (looking-at org-drawer-regexp)))
8606 (progn (forward-line)
8607 (while (looking-at org-drawer-regexp)
8608 (goto-char (match-end 0))
8609 (re-search-forward org-property-end-re (point-max) t)
8610 (forward-line))
8611 (forward-line -1)))
8612 (unless org-log-states-order-reversed
8613 (and (= (char-after) ?\n) (forward-char 1))
8614 (org-skip-over-state-notes)
8615 (skip-chars-backward " \t\n\r")))
8616 (move-marker org-log-note-marker (point))
8617 (setq org-log-note-purpose purpose
8618 org-log-note-state state
8619 org-log-note-how how
8620 org-log-note-extra extra)
8621 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8623 (defun org-skip-over-state-notes ()
8624 "Skip past the list of State notes in an entry."
8625 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8626 (while (looking-at "[ \t]*- State")
8627 (condition-case nil
8628 (org-next-item)
8629 (error (org-end-of-item)))))
8631 (defun org-add-log-note (&optional purpose)
8632 "Pop up a window for taking a note, and add this note later at point."
8633 (remove-hook 'post-command-hook 'org-add-log-note)
8634 (setq org-log-note-window-configuration (current-window-configuration))
8635 (delete-other-windows)
8636 (move-marker org-log-note-return-to (point))
8637 (switch-to-buffer (marker-buffer org-log-note-marker))
8638 (goto-char org-log-note-marker)
8639 (org-switch-to-buffer-other-window "*Org Note*")
8640 (erase-buffer)
8641 (if (memq org-log-note-how '(time state))
8642 (let (current-prefix-arg) (org-store-log-note))
8643 (let ((org-inhibit-startup t)) (org-mode))
8644 (insert (format "# Insert note for %s.
8645 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8646 (cond
8647 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8648 ((eq org-log-note-purpose 'done) "closed todo item")
8649 ((eq org-log-note-purpose 'state)
8650 (format "state change to \"%s\"" org-log-note-state))
8651 ((eq org-log-note-purpose 'note)
8652 "this entry")
8653 (t (error "This should not happen")))))
8654 (if org-log-note-extra (insert org-log-note-extra))
8655 (org-set-local 'org-finish-function 'org-store-log-note)))
8657 (defvar org-note-abort nil) ; dynamically scoped
8658 (defun org-store-log-note ()
8659 "Finish taking a log note, and insert it to where it belongs."
8660 (let ((txt (buffer-string))
8661 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8662 lines ind)
8663 (kill-buffer (current-buffer))
8664 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8665 (setq txt (replace-match "" t t txt)))
8666 (if (string-match "\\s-+\\'" txt)
8667 (setq txt (replace-match "" t t txt)))
8668 (setq lines (org-split-string txt "\n"))
8669 (when (and note (string-match "\\S-" note))
8670 (setq note
8671 (org-replace-escapes
8672 note
8673 (list (cons "%u" (user-login-name))
8674 (cons "%U" user-full-name)
8675 (cons "%t" (format-time-string
8676 (org-time-stamp-format 'long 'inactive)
8677 (current-time)))
8678 (cons "%s" (if org-log-note-state
8679 (concat "\"" org-log-note-state "\"")
8680 "")))))
8681 (if lines (setq note (concat note " \\\\")))
8682 (push note lines))
8683 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8684 (when lines
8685 (save-excursion
8686 (set-buffer (marker-buffer org-log-note-marker))
8687 (save-excursion
8688 (goto-char org-log-note-marker)
8689 (move-marker org-log-note-marker nil)
8690 (end-of-line 1)
8691 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8692 (indent-relative nil)
8693 (insert "- " (pop lines))
8694 (org-indent-line-function)
8695 (beginning-of-line 1)
8696 (looking-at "[ \t]*")
8697 (setq ind (concat (match-string 0) " "))
8698 (end-of-line 1)
8699 (while lines (insert "\n" ind (pop lines)))))))
8700 (set-window-configuration org-log-note-window-configuration)
8701 (with-current-buffer (marker-buffer org-log-note-return-to)
8702 (goto-char org-log-note-return-to))
8703 (move-marker org-log-note-return-to nil)
8704 (and org-log-post-message (message "%s" org-log-post-message)))
8706 (defun org-sparse-tree (&optional arg)
8707 "Create a sparse tree, prompt for the details.
8708 This command can create sparse trees. You first need to select the type
8709 of match used to create the tree:
8711 t Show entries with a specific TODO keyword.
8712 T Show entries selected by a tags match.
8713 p Enter a property name and its value (both with completion on existing
8714 names/values) and show entries with that property.
8715 r Show entries matching a regular expression
8716 d Show deadlines due within `org-deadline-warning-days'."
8717 (interactive "P")
8718 (let (ans kwd value)
8719 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8720 (setq ans (read-char-exclusive))
8721 (cond
8722 ((equal ans ?d)
8723 (call-interactively 'org-check-deadlines))
8724 ((equal ans ?b)
8725 (call-interactively 'org-check-before-date))
8726 ((equal ans ?t)
8727 (org-show-todo-tree '(4)))
8728 ((equal ans ?T)
8729 (call-interactively 'org-tags-sparse-tree))
8730 ((member ans '(?p ?P))
8731 (setq kwd (org-ido-completing-read "Property: "
8732 (mapcar 'list (org-buffer-property-keys))))
8733 (setq value (org-ido-completing-read "Value: "
8734 (mapcar 'list (org-property-values kwd))))
8735 (unless (string-match "\\`{.*}\\'" value)
8736 (setq value (concat "\"" value "\"")))
8737 (org-tags-sparse-tree arg (concat kwd "=" value)))
8738 ((member ans '(?r ?R ?/))
8739 (call-interactively 'org-occur))
8740 (t (error "No such sparse tree command \"%c\"" ans)))))
8742 (defvar org-occur-highlights nil
8743 "List of overlays used for occur matches.")
8744 (make-variable-buffer-local 'org-occur-highlights)
8745 (defvar org-occur-parameters nil
8746 "Parameters of the active org-occur calls.
8747 This is a list, each call to org-occur pushes as cons cell,
8748 containing the regular expression and the callback, onto the list.
8749 The list can contain several entries if `org-occur' has been called
8750 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8751 will only contain one set of parameters. When the highlights are
8752 removed (for example with `C-c C-c', or with the next edit (depending
8753 on `org-remove-highlights-with-change'), this variable is emptied
8754 as well.")
8755 (make-variable-buffer-local 'org-occur-parameters)
8757 (defun org-occur (regexp &optional keep-previous callback)
8758 "Make a compact tree which shows all matches of REGEXP.
8759 The tree will show the lines where the regexp matches, and all higher
8760 headlines above the match. It will also show the heading after the match,
8761 to make sure editing the matching entry is easy.
8762 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8763 call to `org-occur' will be kept, to allow stacking of calls to this
8764 command.
8765 If CALLBACK is non-nil, it is a function which is called to confirm
8766 that the match should indeed be shown."
8767 (interactive "sRegexp: \nP")
8768 (unless keep-previous
8769 (org-remove-occur-highlights nil nil t))
8770 (push (cons regexp callback) org-occur-parameters)
8771 (let ((cnt 0))
8772 (save-excursion
8773 (goto-char (point-min))
8774 (if (or (not keep-previous) ; do not want to keep
8775 (not org-occur-highlights)) ; no previous matches
8776 ;; hide everything
8777 (org-overview))
8778 (while (re-search-forward regexp nil t)
8779 (when (or (not callback)
8780 (save-match-data (funcall callback)))
8781 (setq cnt (1+ cnt))
8782 (when org-highlight-sparse-tree-matches
8783 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8784 (org-show-context 'occur-tree))))
8785 (when org-remove-highlights-with-change
8786 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8787 nil 'local))
8788 (unless org-sparse-tree-open-archived-trees
8789 (org-hide-archived-subtrees (point-min) (point-max)))
8790 (run-hooks 'org-occur-hook)
8791 (if (interactive-p)
8792 (message "%d match(es) for regexp %s" cnt regexp))
8793 cnt))
8795 (defun org-show-context (&optional key)
8796 "Make sure point and context and visible.
8797 How much context is shown depends upon the variables
8798 `org-show-hierarchy-above', `org-show-following-heading'. and
8799 `org-show-siblings'."
8800 (let ((heading-p (org-on-heading-p t))
8801 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8802 (following-p (org-get-alist-option org-show-following-heading key))
8803 (entry-p (org-get-alist-option org-show-entry-below key))
8804 (siblings-p (org-get-alist-option org-show-siblings key)))
8805 (catch 'exit
8806 ;; Show heading or entry text
8807 (if (and heading-p (not entry-p))
8808 (org-flag-heading nil) ; only show the heading
8809 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8810 (org-show-hidden-entry))) ; show entire entry
8811 (when following-p
8812 ;; Show next sibling, or heading below text
8813 (save-excursion
8814 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8815 (org-flag-heading nil))))
8816 (when siblings-p (org-show-siblings))
8817 (when hierarchy-p
8818 ;; show all higher headings, possibly with siblings
8819 (save-excursion
8820 (while (and (condition-case nil
8821 (progn (org-up-heading-all 1) t)
8822 (error nil))
8823 (not (bobp)))
8824 (org-flag-heading nil)
8825 (when siblings-p (org-show-siblings))))))))
8827 (defun org-reveal (&optional siblings)
8828 "Show current entry, hierarchy above it, and the following headline.
8829 This can be used to show a consistent set of context around locations
8830 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8831 not t for the search context.
8833 With optional argument SIBLINGS, on each level of the hierarchy all
8834 siblings are shown. This repairs the tree structure to what it would
8835 look like when opened with hierarchical calls to `org-cycle'."
8836 (interactive "P")
8837 (let ((org-show-hierarchy-above t)
8838 (org-show-following-heading t)
8839 (org-show-siblings (if siblings t org-show-siblings)))
8840 (org-show-context nil)))
8842 (defun org-highlight-new-match (beg end)
8843 "Highlight from BEG to END and mark the highlight is an occur headline."
8844 (let ((ov (org-make-overlay beg end)))
8845 (org-overlay-put ov 'face 'secondary-selection)
8846 (push ov org-occur-highlights)))
8848 (defun org-remove-occur-highlights (&optional beg end noremove)
8849 "Remove the occur highlights from the buffer.
8850 BEG and END are ignored. If NOREMOVE is nil, remove this function
8851 from the `before-change-functions' in the current buffer."
8852 (interactive)
8853 (unless org-inhibit-highlight-removal
8854 (mapc 'org-delete-overlay org-occur-highlights)
8855 (setq org-occur-highlights nil)
8856 (setq org-occur-parameters nil)
8857 (unless noremove
8858 (remove-hook 'before-change-functions
8859 'org-remove-occur-highlights 'local))))
8861 ;;;; Priorities
8863 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8864 "Regular expression matching the priority indicator.")
8866 (defvar org-remove-priority-next-time nil)
8868 (defun org-priority-up ()
8869 "Increase the priority of the current item."
8870 (interactive)
8871 (org-priority 'up))
8873 (defun org-priority-down ()
8874 "Decrease the priority of the current item."
8875 (interactive)
8876 (org-priority 'down))
8878 (defun org-priority (&optional action)
8879 "Change the priority of an item by ARG.
8880 ACTION can be `set', `up', `down', or a character."
8881 (interactive)
8882 (setq action (or action 'set))
8883 (let (current new news have remove)
8884 (save-excursion
8885 (org-back-to-heading)
8886 (if (looking-at org-priority-regexp)
8887 (setq current (string-to-char (match-string 2))
8888 have t)
8889 (setq current org-default-priority))
8890 (cond
8891 ((or (eq action 'set)
8892 (if (featurep 'xemacs) (characterp action) (integerp action)))
8893 (if (not (eq action 'set))
8894 (setq new action)
8895 (message "Priority %c-%c, SPC to remove: "
8896 org-highest-priority org-lowest-priority)
8897 (setq new (read-char-exclusive)))
8898 (if (and (= (upcase org-highest-priority) org-highest-priority)
8899 (= (upcase org-lowest-priority) org-lowest-priority))
8900 (setq new (upcase new)))
8901 (cond ((equal new ?\ ) (setq remove t))
8902 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8903 (error "Priority must be between `%c' and `%c'"
8904 org-highest-priority org-lowest-priority))))
8905 ((eq action 'up)
8906 (if (and (not have) (eq last-command this-command))
8907 (setq new org-lowest-priority)
8908 (setq new (if (and org-priority-start-cycle-with-default (not have))
8909 org-default-priority (1- current)))))
8910 ((eq action 'down)
8911 (if (and (not have) (eq last-command this-command))
8912 (setq new org-highest-priority)
8913 (setq new (if (and org-priority-start-cycle-with-default (not have))
8914 org-default-priority (1+ current)))))
8915 (t (error "Invalid action")))
8916 (if (or (< (upcase new) org-highest-priority)
8917 (> (upcase new) org-lowest-priority))
8918 (setq remove t))
8919 (setq news (format "%c" new))
8920 (if have
8921 (if remove
8922 (replace-match "" t t nil 1)
8923 (replace-match news t t nil 2))
8924 (if remove
8925 (error "No priority cookie found in line")
8926 (looking-at org-todo-line-regexp)
8927 (if (match-end 2)
8928 (progn
8929 (goto-char (match-end 2))
8930 (insert " [#" news "]"))
8931 (goto-char (match-beginning 3))
8932 (insert "[#" news "] ")))))
8933 (org-preserve-lc (org-set-tags nil 'align))
8934 (if remove
8935 (message "Priority removed")
8936 (message "Priority of current item set to %s" news))))
8939 (defun org-get-priority (s)
8940 "Find priority cookie and return priority."
8941 (save-match-data
8942 (if (not (string-match org-priority-regexp s))
8943 (* 1000 (- org-lowest-priority org-default-priority))
8944 (* 1000 (- org-lowest-priority
8945 (string-to-char (match-string 2 s)))))))
8947 ;;;; Tags
8949 (defvar org-agenda-archives-mode)
8950 (defun org-scan-tags (action matcher &optional todo-only)
8951 "Scan headline tags with inheritance and produce output ACTION.
8953 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8954 or `agenda' to produce an entry list for an agenda view. It can also be
8955 a Lisp form or a function that should be called at each matched headline, in
8956 this case the return value is a list of all return values from these calls.
8958 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8959 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8960 only lines with a TODO keyword are included in the output."
8961 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8962 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8963 (org-re
8964 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8965 (props (list 'face 'default
8966 'done-face 'org-done
8967 'undone-face 'default
8968 'mouse-face 'highlight
8969 'org-not-done-regexp org-not-done-regexp
8970 'org-todo-regexp org-todo-regexp
8971 'keymap org-agenda-keymap
8972 'help-echo
8973 (format "mouse-2 or RET jump to org file %s"
8974 (abbreviate-file-name
8975 (or (buffer-file-name (buffer-base-buffer))
8976 (buffer-name (buffer-base-buffer)))))))
8977 (case-fold-search nil)
8978 lspos tags tags-list
8979 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8980 (llast 0) rtn rtn1 level category i txt
8981 todo marker entry priority)
8982 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8983 (setq action (list 'lambda nil action)))
8984 (save-excursion
8985 (goto-char (point-min))
8986 (when (eq action 'sparse-tree)
8987 (org-overview)
8988 (org-remove-occur-highlights))
8989 (while (re-search-forward re nil t)
8990 (catch :skip
8991 (setq todo (if (match-end 1) (match-string 2))
8992 tags (if (match-end 4) (match-string 4)))
8993 (goto-char (setq lspos (1+ (match-beginning 0))))
8994 (setq level (org-reduced-level (funcall outline-level))
8995 category (org-get-category))
8996 (setq i llast llast level)
8997 ;; remove tag lists from same and sublevels
8998 (while (>= i level)
8999 (when (setq entry (assoc i tags-alist))
9000 (setq tags-alist (delete entry tags-alist)))
9001 (setq i (1- i)))
9002 ;; add the next tags
9003 (when tags
9004 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9005 tags-alist
9006 (cons (cons level tags) tags-alist)))
9007 ;; compile tags for current headline
9008 (setq tags-list
9009 (if org-use-tag-inheritance
9010 (apply 'append (mapcar 'cdr tags-alist))
9011 tags))
9012 (when (and tags org-use-tag-inheritance
9013 (not (eq t org-use-tag-inheritance)))
9014 ;; selective inheritance, remove uninherited ones
9015 (setcdr (car tags-alist)
9016 (org-remove-uniherited-tags (cdar tags-alist))))
9017 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9018 (let ((case-fold-search t)) (eval matcher))
9020 (not (member org-archive-tag tags-list))
9021 ;; we have an archive tag, should we use this anyway?
9022 (or (not org-agenda-skip-archived-trees)
9023 (and (eq action 'agenda) org-agenda-archives-mode))))
9024 (unless (eq action 'sparse-tree) (org-agenda-skip))
9026 ;; select this headline
9028 (cond
9029 ((eq action 'sparse-tree)
9030 (and org-highlight-sparse-tree-matches
9031 (org-get-heading) (match-end 0)
9032 (org-highlight-new-match
9033 (match-beginning 0) (match-beginning 1)))
9034 (org-show-context 'tags-tree))
9035 ((eq action 'agenda)
9036 (setq txt (org-format-agenda-item
9038 (concat
9039 (if org-tags-match-list-sublevels
9040 (make-string (1- level) ?.) "")
9041 (org-get-heading))
9042 category tags-list)
9043 priority (org-get-priority txt))
9044 (goto-char lspos)
9045 (setq marker (org-agenda-new-marker))
9046 (org-add-props txt props
9047 'org-marker marker 'org-hd-marker marker 'org-category category
9048 'priority priority 'type "tagsmatch")
9049 (push txt rtn))
9050 ((functionp action)
9051 (save-excursion
9052 (setq rtn1 (funcall action))
9053 (push rtn1 rtn))
9054 (goto-char (point-at-eol)))
9055 (t (error "Invalid action")))
9057 ;; if we are to skip sublevels, jump to end of subtree
9058 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9059 (when (and (eq action 'sparse-tree)
9060 (not org-sparse-tree-open-archived-trees))
9061 (org-hide-archived-subtrees (point-min) (point-max)))
9062 (nreverse rtn)))
9064 (defun org-remove-uniherited-tags (tags)
9065 "Remove all tags that are not inherited from the list TAGS."
9066 (cond
9067 ((eq org-use-tag-inheritance t) tags)
9068 ((not org-use-tag-inheritance) nil)
9069 ((stringp org-use-tag-inheritance)
9070 (delq nil (mapcar
9071 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9072 tags)))
9073 ((listp org-use-tag-inheritance)
9074 (delq nil (mapcar
9075 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
9076 tags)))))
9078 (defvar todo-only) ;; dynamically scoped
9080 (defun org-tags-sparse-tree (&optional todo-only match)
9081 "Create a sparse tree according to tags string MATCH.
9082 MATCH can contain positive and negative selection of tags, like
9083 \"+WORK+URGENT-WITHBOSS\".
9084 If optional argument TODO_ONLY is non-nil, only select lines that are
9085 also TODO lines."
9086 (interactive "P")
9087 (org-prepare-agenda-buffers (list (current-buffer)))
9088 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9090 (defvar org-cached-props nil)
9091 (defun org-cached-entry-get (pom property)
9092 (if (or (eq t org-use-property-inheritance)
9093 (and (stringp org-use-property-inheritance)
9094 (string-match org-use-property-inheritance property))
9095 (and (listp org-use-property-inheritance)
9096 (member property org-use-property-inheritance)))
9097 ;; Caching is not possible, check it directly
9098 (org-entry-get pom property 'inherit)
9099 ;; Get all properties, so that we can do complicated checks easily
9100 (cdr (assoc property (or org-cached-props
9101 (setq org-cached-props
9102 (org-entry-properties pom)))))))
9104 (defun org-global-tags-completion-table (&optional files)
9105 "Return the list of all tags in all agenda buffer/files."
9106 (save-excursion
9107 (org-uniquify
9108 (delq nil
9109 (apply 'append
9110 (mapcar
9111 (lambda (file)
9112 (set-buffer (find-file-noselect file))
9113 (append (org-get-buffer-tags)
9114 (mapcar (lambda (x) (if (stringp (car-safe x))
9115 (list (car-safe x)) nil))
9116 org-tag-alist)))
9117 (if (and files (car files))
9118 files
9119 (org-agenda-files))))))))
9121 (defun org-make-tags-matcher (match)
9122 "Create the TAGS//TODO matcher form for the selection string MATCH."
9123 ;; todo-only is scoped dynamically into this function, and the function
9124 ;; may change it it the matcher asksk for it.
9125 (unless match
9126 ;; Get a new match request, with completion
9127 (let ((org-last-tags-completion-table
9128 (org-global-tags-completion-table)))
9129 (setq match (org-ido-completing-read
9130 "Match: " 'org-tags-completion-function nil nil nil
9131 'org-tags-history))))
9133 ;; Parse the string and create a lisp form
9134 (let ((match0 match)
9135 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9136 minus tag mm
9137 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9138 orterms term orlist re-p str-p level-p level-op time-p
9139 prop-p pn pv po cat-p gv rest)
9140 (if (string-match "/+" match)
9141 ;; match contains also a todo-matching request
9142 (progn
9143 (setq tagsmatch (substring match 0 (match-beginning 0))
9144 todomatch (substring match (match-end 0)))
9145 (if (string-match "^!" todomatch)
9146 (setq todo-only t todomatch (substring todomatch 1)))
9147 (if (string-match "^\\s-*$" todomatch)
9148 (setq todomatch nil)))
9149 ;; only matching tags
9150 (setq tagsmatch match todomatch nil))
9152 ;; Make the tags matcher
9153 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9154 (setq tagsmatcher t)
9155 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9156 (while (setq term (pop orterms))
9157 (while (and (equal (substring term -1) "\\") orterms)
9158 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9159 (while (string-match re term)
9160 (setq rest (substring term (match-end 0))
9161 minus (and (match-end 1)
9162 (equal (match-string 1 term) "-"))
9163 tag (match-string 2 term)
9164 re-p (equal (string-to-char tag) ?{)
9165 level-p (match-end 4)
9166 prop-p (match-end 5)
9167 mm (cond
9168 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9169 (level-p
9170 (setq level-op (org-op-to-function (match-string 3 term)))
9171 `(,level-op level ,(string-to-number
9172 (match-string 4 term))))
9173 (prop-p
9174 (setq pn (match-string 5 term)
9175 po (match-string 6 term)
9176 pv (match-string 7 term)
9177 cat-p (equal pn "CATEGORY")
9178 re-p (equal (string-to-char pv) ?{)
9179 str-p (equal (string-to-char pv) ?\")
9180 time-p (save-match-data
9181 (string-match "^\"[[<].*[]>]\"$" pv))
9182 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9183 (if time-p (setq pv (org-matcher-time pv)))
9184 (setq po (org-op-to-function po (if time-p 'time str-p)))
9185 (cond
9186 ((equal pn "CATEGORY")
9187 (setq gv '(get-text-property (point) 'org-category)))
9188 ((equal pn "TODO")
9189 (setq gv 'todo))
9191 (setq gv `(org-cached-entry-get nil ,pn))))
9192 (if re-p
9193 (if (eq po 'org<>)
9194 `(not (string-match ,pv (or ,gv "")))
9195 `(string-match ,pv (or ,gv "")))
9196 (if str-p
9197 `(,po (or ,gv "") ,pv)
9198 `(,po (string-to-number (or ,gv ""))
9199 ,(string-to-number pv) ))))
9200 (t `(member ,(downcase tag) tags-list)))
9201 mm (if minus (list 'not mm) mm)
9202 term rest)
9203 (push mm tagsmatcher))
9204 (push (if (> (length tagsmatcher) 1)
9205 (cons 'and tagsmatcher)
9206 (car tagsmatcher))
9207 orlist)
9208 (setq tagsmatcher nil))
9209 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9210 (setq tagsmatcher
9211 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9212 ;; Make the todo matcher
9213 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9214 (setq todomatcher t)
9215 (setq orterms (org-split-string todomatch "|") orlist nil)
9216 (while (setq term (pop orterms))
9217 (while (string-match re term)
9218 (setq minus (and (match-end 1)
9219 (equal (match-string 1 term) "-"))
9220 kwd (match-string 2 term)
9221 re-p (equal (string-to-char kwd) ?{)
9222 term (substring term (match-end 0))
9223 mm (if re-p
9224 `(string-match ,(substring kwd 1 -1) todo)
9225 (list 'equal 'todo kwd))
9226 mm (if minus (list 'not mm) mm))
9227 (push mm todomatcher))
9228 (push (if (> (length todomatcher) 1)
9229 (cons 'and todomatcher)
9230 (car todomatcher))
9231 orlist)
9232 (setq todomatcher nil))
9233 (setq todomatcher (if (> (length orlist) 1)
9234 (cons 'or orlist) (car orlist))))
9236 ;; Return the string and lisp forms of the matcher
9237 (setq matcher (if todomatcher
9238 (list 'and tagsmatcher todomatcher)
9239 tagsmatcher))
9240 (cons match0 matcher)))
9242 (defun org-op-to-function (op &optional stringp)
9243 "Turn an operator into the appropriate function."
9244 (setq op
9245 (cond
9246 ((equal op "<" ) '(< string< org-time<))
9247 ((equal op ">" ) '(> org-string> org-time>))
9248 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9249 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9250 ((member op '("=" "==")) '(= string= org-time=))
9251 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9252 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9254 (defun org<> (a b) (not (= a b)))
9255 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9256 (defun org-string>= (a b) (not (string< a b)))
9257 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9258 (defun org-string<> (a b) (not (string= a b)))
9259 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9260 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9261 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9262 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9263 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9264 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9265 (defun org-2ft (s)
9266 "Convert S to a floating point time.
9267 If S is already a number, just return it. If it is a string, parse
9268 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9269 (cond
9270 ((numberp s) s)
9271 ((stringp s)
9272 (condition-case nil
9273 (float-time (apply 'encode-time (org-parse-time-string s)))
9274 (error 0.)))
9275 (t 0.)))
9277 (defun org-time-today ()
9278 "Time in seconds today at 0:00.
9279 Returns the float number of seconds since the beginning of the
9280 epoch to the beginning of today (00:00)."
9281 (float-time (apply 'encode-time
9282 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9284 (defun org-matcher-time (s)
9285 (cond
9286 ((string= s "<now>") (float-time))
9287 ((string= s "<today>") (org-time-today))
9288 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9289 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9290 (t (org-2ft s))))
9292 (defun org-match-any-p (re list)
9293 "Does re match any element of list?"
9294 (setq list (mapcar (lambda (x) (string-match re x)) list))
9295 (delq nil list))
9297 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9298 (defvar org-tags-overlay (org-make-overlay 1 1))
9299 (org-detach-overlay org-tags-overlay)
9301 (defun org-get-local-tags-at (&optional pos)
9302 "Get a list of tags defined in the current headline."
9303 (org-get-tags-at pos 'local))
9305 (defun org-get-local-tags ()
9306 "Get a list of tags defined in the current headline."
9307 (org-get-tags-at nil 'local))
9309 (defun org-get-tags-at (&optional pos local)
9310 "Get a list of all headline tags applicable at POS.
9311 POS defaults to point. If tags are inherited, the list contains
9312 the targets in the same sequence as the headlines appear, i.e.
9313 the tags of the current headline come last.
9314 When LOCAL is non-nil, only return tags from the current headline,
9315 ignore inherited ones."
9316 (interactive)
9317 (let (tags ltags lastpos parent)
9318 (save-excursion
9319 (save-restriction
9320 (widen)
9321 (goto-char (or pos (point)))
9322 (save-match-data
9323 (catch 'done
9324 (condition-case nil
9325 (progn
9326 (org-back-to-heading t)
9327 (while (not (equal lastpos (point)))
9328 (setq lastpos (point))
9329 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9330 (setq ltags (org-split-string
9331 (org-match-string-no-properties 1) ":"))
9332 (setq tags (append
9333 (if parent
9334 (org-remove-uniherited-tags ltags)
9335 ltags)
9336 tags)))
9337 (or org-use-tag-inheritance (throw 'done t))
9338 (if local (throw 'done t))
9339 (org-up-heading-all 1)
9340 (setq parent t)))
9341 (error nil)))))
9342 (append (org-remove-uniherited-tags org-file-tags) tags))))
9344 (defun org-toggle-tag (tag &optional onoff)
9345 "Toggle the tag TAG for the current line.
9346 If ONOFF is `on' or `off', don't toggle but set to this state."
9347 (unless (org-on-heading-p t) (error "Not on headling"))
9348 (let (res current)
9349 (save-excursion
9350 (beginning-of-line)
9351 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9352 (point-at-eol) t)
9353 (progn
9354 (setq current (match-string 1))
9355 (replace-match ""))
9356 (setq current ""))
9357 (setq current (nreverse (org-split-string current ":")))
9358 (cond
9359 ((eq onoff 'on)
9360 (setq res t)
9361 (or (member tag current) (push tag current)))
9362 ((eq onoff 'off)
9363 (or (not (member tag current)) (setq current (delete tag current))))
9364 (t (if (member tag current)
9365 (setq current (delete tag current))
9366 (setq res t)
9367 (push tag current))))
9368 (end-of-line 1)
9369 (if current
9370 (progn
9371 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9372 (org-set-tags nil t))
9373 (delete-horizontal-space))
9374 (run-hooks 'org-after-tags-change-hook))
9375 res))
9377 (defun org-align-tags-here (to-col)
9378 ;; Assumes that this is a headline
9379 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9380 (beginning-of-line 1)
9381 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9382 (< pos (match-beginning 2)))
9383 (progn
9384 (setq tags-l (- (match-end 2) (match-beginning 2)))
9385 (goto-char (match-beginning 1))
9386 (insert " ")
9387 (delete-region (point) (1+ (match-beginning 2)))
9388 (setq ncol (max (1+ (current-column))
9389 (1+ col)
9390 (if (> to-col 0)
9391 to-col
9392 (- (abs to-col) tags-l))))
9393 (setq p (point))
9394 (insert (make-string (- ncol (current-column)) ?\ ))
9395 (setq ncol (current-column))
9396 (when indent-tabs-mode (tabify p (point-at-eol)))
9397 (org-move-to-column (min ncol col) t))
9398 (goto-char pos))))
9400 (defun org-set-tags-command (&optional arg just-align)
9401 "Call the set-tags command for the current entry."
9402 (interactive "P")
9403 (if (org-on-heading-p)
9404 (org-set-tags arg just-align)
9405 (save-excursion
9406 (org-back-to-heading t)
9407 (org-set-tags arg just-align))))
9409 (defun org-set-tags (&optional arg just-align)
9410 "Set the tags for the current headline.
9411 With prefix ARG, realign all tags in headings in the current buffer."
9412 (interactive "P")
9413 (let* ((re (concat "^" outline-regexp))
9414 (current (org-get-tags-string))
9415 (col (current-column))
9416 (org-setting-tags t)
9417 table current-tags inherited-tags ; computed below when needed
9418 tags p0 c0 c1 rpl)
9419 (if arg
9420 (save-excursion
9421 (goto-char (point-min))
9422 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9423 (while (re-search-forward re nil t)
9424 (org-set-tags nil t)
9425 (end-of-line 1)))
9426 (message "All tags realigned to column %d" org-tags-column))
9427 (if just-align
9428 (setq tags current)
9429 ;; Get a new set of tags from the user
9430 (save-excursion
9431 (setq table (or org-tag-alist (org-get-buffer-tags))
9432 org-last-tags-completion-table table
9433 current-tags (org-split-string current ":")
9434 inherited-tags (nreverse
9435 (nthcdr (length current-tags)
9436 (nreverse (org-get-tags-at))))
9437 tags
9438 (if (or (eq t org-use-fast-tag-selection)
9439 (and org-use-fast-tag-selection
9440 (delq nil (mapcar 'cdr table))))
9441 (org-fast-tag-selection
9442 current-tags inherited-tags table
9443 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9444 (let ((org-add-colon-after-tag-completion t))
9445 (org-trim
9446 (org-without-partial-completion
9447 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9448 nil nil current 'org-tags-history)))))))
9449 (while (string-match "[-+&]+" tags)
9450 ;; No boolean logic, just a list
9451 (setq tags (replace-match ":" t t tags))))
9453 (if (string-match "\\`[\t ]*\\'" tags)
9454 (setq tags "")
9455 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9456 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9458 ;; Insert new tags at the correct column
9459 (beginning-of-line 1)
9460 (cond
9461 ((and (equal current "") (equal tags "")))
9462 ((re-search-forward
9463 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9464 (point-at-eol) t)
9465 (if (equal tags "")
9466 (setq rpl "")
9467 (goto-char (match-beginning 0))
9468 (setq c0 (current-column) p0 (point)
9469 c1 (max (1+ c0) (if (> org-tags-column 0)
9470 org-tags-column
9471 (- (- org-tags-column) (length tags))))
9472 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9473 (replace-match rpl t t)
9474 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9475 tags)
9476 (t (error "Tags alignment failed")))
9477 (org-move-to-column col)
9478 (unless just-align
9479 (run-hooks 'org-after-tags-change-hook)))))
9481 (defun org-change-tag-in-region (beg end tag off)
9482 "Add or remove TAG for each entry in the region.
9483 This works in the agenda, and also in an org-mode buffer."
9484 (interactive
9485 (list (region-beginning) (region-end)
9486 (let ((org-last-tags-completion-table
9487 (if (org-mode-p)
9488 (org-get-buffer-tags)
9489 (org-global-tags-completion-table))))
9490 (org-ido-completing-read
9491 "Tag: " 'org-tags-completion-function nil nil nil
9492 'org-tags-history))
9493 (progn
9494 (message "[s]et or [r]emove? ")
9495 (equal (read-char-exclusive) ?r))))
9496 (if (fboundp 'deactivate-mark) (deactivate-mark))
9497 (let ((agendap (equal major-mode 'org-agenda-mode))
9498 l1 l2 m buf pos newhead (cnt 0))
9499 (goto-char end)
9500 (setq l2 (1- (org-current-line)))
9501 (goto-char beg)
9502 (setq l1 (org-current-line))
9503 (loop for l from l1 to l2 do
9504 (goto-line l)
9505 (setq m (get-text-property (point) 'org-hd-marker))
9506 (when (or (and (org-mode-p) (org-on-heading-p))
9507 (and agendap m))
9508 (setq buf (if agendap (marker-buffer m) (current-buffer))
9509 pos (if agendap m (point)))
9510 (with-current-buffer buf
9511 (save-excursion
9512 (save-restriction
9513 (goto-char pos)
9514 (setq cnt (1+ cnt))
9515 (org-toggle-tag tag (if off 'off 'on))
9516 (setq newhead (org-get-heading)))))
9517 (and agendap (org-agenda-change-all-lines newhead m))))
9518 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9520 (defun org-tags-completion-function (string predicate &optional flag)
9521 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9522 (confirm (lambda (x) (stringp (car x)))))
9523 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9524 (setq s1 (match-string 1 string)
9525 s2 (match-string 2 string))
9526 (setq s1 "" s2 string))
9527 (cond
9528 ((eq flag nil)
9529 ;; try completion
9530 (setq rtn (try-completion s2 ctable confirm))
9531 (if (stringp rtn)
9532 (setq rtn
9533 (concat s1 s2 (substring rtn (length s2))
9534 (if (and org-add-colon-after-tag-completion
9535 (assoc rtn ctable))
9536 ":" ""))))
9537 rtn)
9538 ((eq flag t)
9539 ;; all-completions
9540 (all-completions s2 ctable confirm)
9542 ((eq flag 'lambda)
9543 ;; exact match?
9544 (assoc s2 ctable)))
9547 (defun org-fast-tag-insert (kwd tags face &optional end)
9548 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9549 (insert (format "%-12s" (concat kwd ":"))
9550 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9551 (or end "")))
9553 (defun org-fast-tag-show-exit (flag)
9554 (save-excursion
9555 (goto-line 3)
9556 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9557 (replace-match ""))
9558 (when flag
9559 (end-of-line 1)
9560 (org-move-to-column (- (window-width) 19) t)
9561 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9563 (defun org-set-current-tags-overlay (current prefix)
9564 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9565 (if (featurep 'xemacs)
9566 (org-overlay-display org-tags-overlay (concat prefix s)
9567 'secondary-selection)
9568 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9569 (org-overlay-display org-tags-overlay (concat prefix s)))))
9571 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9572 "Fast tag selection with single keys.
9573 CURRENT is the current list of tags in the headline, INHERITED is the
9574 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9575 possibly with grouping information. TODO-TABLE is a similar table with
9576 TODO keywords, should these have keys assigned to them.
9577 If the keys are nil, a-z are automatically assigned.
9578 Returns the new tags string, or nil to not change the current settings."
9579 (let* ((fulltable (append table todo-table))
9580 (maxlen (apply 'max (mapcar
9581 (lambda (x)
9582 (if (stringp (car x)) (string-width (car x)) 0))
9583 fulltable)))
9584 (buf (current-buffer))
9585 (expert (eq org-fast-tag-selection-single-key 'expert))
9586 (buffer-tags nil)
9587 (fwidth (+ maxlen 3 1 3))
9588 (ncol (/ (- (window-width) 4) fwidth))
9589 (i-face 'org-done)
9590 (c-face 'org-todo)
9591 tg cnt e c char c1 c2 ntable tbl rtn
9592 ov-start ov-end ov-prefix
9593 (exit-after-next org-fast-tag-selection-single-key)
9594 (done-keywords org-done-keywords)
9595 groups ingroup)
9596 (save-excursion
9597 (beginning-of-line 1)
9598 (if (looking-at
9599 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9600 (setq ov-start (match-beginning 1)
9601 ov-end (match-end 1)
9602 ov-prefix "")
9603 (setq ov-start (1- (point-at-eol))
9604 ov-end (1+ ov-start))
9605 (skip-chars-forward "^\n\r")
9606 (setq ov-prefix
9607 (concat
9608 (buffer-substring (1- (point)) (point))
9609 (if (> (current-column) org-tags-column)
9611 (make-string (- org-tags-column (current-column)) ?\ ))))))
9612 (org-move-overlay org-tags-overlay ov-start ov-end)
9613 (save-window-excursion
9614 (if expert
9615 (set-buffer (get-buffer-create " *Org tags*"))
9616 (delete-other-windows)
9617 (split-window-vertically)
9618 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9619 (erase-buffer)
9620 (org-set-local 'org-done-keywords done-keywords)
9621 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9622 (org-fast-tag-insert "Current" current c-face "\n\n")
9623 (org-fast-tag-show-exit exit-after-next)
9624 (org-set-current-tags-overlay current ov-prefix)
9625 (setq tbl fulltable char ?a cnt 0)
9626 (while (setq e (pop tbl))
9627 (cond
9628 ((equal e '(:startgroup))
9629 (push '() groups) (setq ingroup t)
9630 (when (not (= cnt 0))
9631 (setq cnt 0)
9632 (insert "\n"))
9633 (insert "{ "))
9634 ((equal e '(:endgroup))
9635 (setq ingroup nil cnt 0)
9636 (insert "}\n"))
9638 (setq tg (car e) c2 nil)
9639 (if (cdr e)
9640 (setq c (cdr e))
9641 ;; automatically assign a character.
9642 (setq c1 (string-to-char
9643 (downcase (substring
9644 tg (if (= (string-to-char tg) ?@) 1 0)))))
9645 (if (or (rassoc c1 ntable) (rassoc c1 table))
9646 (while (or (rassoc char ntable) (rassoc char table))
9647 (setq char (1+ char)))
9648 (setq c2 c1))
9649 (setq c (or c2 char)))
9650 (if ingroup (push tg (car groups)))
9651 (setq tg (org-add-props tg nil 'face
9652 (cond
9653 ((not (assoc tg table))
9654 (org-get-todo-face tg))
9655 ((member tg current) c-face)
9656 ((member tg inherited) i-face)
9657 (t nil))))
9658 (if (and (= cnt 0) (not ingroup)) (insert " "))
9659 (insert "[" c "] " tg (make-string
9660 (- fwidth 4 (length tg)) ?\ ))
9661 (push (cons tg c) ntable)
9662 (when (= (setq cnt (1+ cnt)) ncol)
9663 (insert "\n")
9664 (if ingroup (insert " "))
9665 (setq cnt 0)))))
9666 (setq ntable (nreverse ntable))
9667 (insert "\n")
9668 (goto-char (point-min))
9669 (if (not expert) (org-fit-window-to-buffer))
9670 (setq rtn
9671 (catch 'exit
9672 (while t
9673 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9674 (if groups " [!] no groups" " [!]groups")
9675 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9676 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9677 (cond
9678 ((= c ?\r) (throw 'exit t))
9679 ((= c ?!)
9680 (setq groups (not groups))
9681 (goto-char (point-min))
9682 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9683 ((= c ?\C-c)
9684 (if (not expert)
9685 (org-fast-tag-show-exit
9686 (setq exit-after-next (not exit-after-next)))
9687 (setq expert nil)
9688 (delete-other-windows)
9689 (split-window-vertically)
9690 (org-switch-to-buffer-other-window " *Org tags*")
9691 (org-fit-window-to-buffer)))
9692 ((or (= c ?\C-g)
9693 (and (= c ?q) (not (rassoc c ntable))))
9694 (org-detach-overlay org-tags-overlay)
9695 (setq quit-flag t))
9696 ((= c ?\ )
9697 (setq current nil)
9698 (if exit-after-next (setq exit-after-next 'now)))
9699 ((= c ?\t)
9700 (condition-case nil
9701 (setq tg (org-ido-completing-read
9702 "Tag: "
9703 (or buffer-tags
9704 (with-current-buffer buf
9705 (org-get-buffer-tags)))))
9706 (quit (setq tg "")))
9707 (when (string-match "\\S-" tg)
9708 (add-to-list 'buffer-tags (list tg))
9709 (if (member tg current)
9710 (setq current (delete tg current))
9711 (push tg current)))
9712 (if exit-after-next (setq exit-after-next 'now)))
9713 ((setq e (rassoc c todo-table) tg (car e))
9714 (with-current-buffer buf
9715 (save-excursion (org-todo tg)))
9716 (if exit-after-next (setq exit-after-next 'now)))
9717 ((setq e (rassoc c ntable) tg (car e))
9718 (if (member tg current)
9719 (setq current (delete tg current))
9720 (loop for g in groups do
9721 (if (member tg g)
9722 (mapc (lambda (x)
9723 (setq current (delete x current)))
9724 g)))
9725 (push tg current))
9726 (if exit-after-next (setq exit-after-next 'now))))
9728 ;; Create a sorted list
9729 (setq current
9730 (sort current
9731 (lambda (a b)
9732 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9733 (if (eq exit-after-next 'now) (throw 'exit t))
9734 (goto-char (point-min))
9735 (beginning-of-line 2)
9736 (delete-region (point) (point-at-eol))
9737 (org-fast-tag-insert "Current" current c-face)
9738 (org-set-current-tags-overlay current ov-prefix)
9739 (while (re-search-forward
9740 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9741 (setq tg (match-string 1))
9742 (add-text-properties
9743 (match-beginning 1) (match-end 1)
9744 (list 'face
9745 (cond
9746 ((member tg current) c-face)
9747 ((member tg inherited) i-face)
9748 (t (get-text-property (match-beginning 1) 'face))))))
9749 (goto-char (point-min)))))
9750 (org-detach-overlay org-tags-overlay)
9751 (if rtn
9752 (mapconcat 'identity current ":")
9753 nil))))
9755 (defun org-get-tags-string ()
9756 "Get the TAGS string in the current headline."
9757 (unless (org-on-heading-p t)
9758 (error "Not on a heading"))
9759 (save-excursion
9760 (beginning-of-line 1)
9761 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9762 (org-match-string-no-properties 1)
9763 "")))
9765 (defun org-get-tags ()
9766 "Get the list of tags specified in the current headline."
9767 (org-split-string (org-get-tags-string) ":"))
9769 (defun org-get-buffer-tags ()
9770 "Get a table of all tags used in the buffer, for completion."
9771 (let (tags)
9772 (save-excursion
9773 (goto-char (point-min))
9774 (while (re-search-forward
9775 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9776 (when (equal (char-after (point-at-bol 0)) ?*)
9777 (mapc (lambda (x) (add-to-list 'tags x))
9778 (org-split-string (org-match-string-no-properties 1) ":")))))
9779 (mapcar 'list tags)))
9781 ;;;; The mapping API
9783 ;;;###autoload
9784 (defun org-map-entries (func &optional match scope &rest skip)
9785 "Call FUNC at each headline selected by MATCH in SCOPE.
9787 FUNC is a function or a lisp form. The function will be called without
9788 arguments, with the cursor positioned at the beginning of the headline.
9789 The return values of all calls to the function will be collected and
9790 returned as a list.
9792 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9793 Only headlines that are matched by this query will be considered during
9794 the iteration. When MATCH is nil or t, all headlines will be
9795 visited by the iteration.
9797 SCOPE determines the scope of this command. It can be any of:
9799 nil The current buffer, respecting the restriction if any
9800 tree The subtree started with the entry at point
9801 file The current buffer, without restriction
9802 file-with-archives
9803 The current buffer, and any archives associated with it
9804 agenda All agenda files
9805 agenda-with-archives
9806 All agenda files with any archive files associated with them
9807 \(file1 file2 ...)
9808 If this is a list, all files in the list will be scanned
9810 The remaining args are treated as settings for the skipping facilities of
9811 the scanner. The following items can be given here:
9813 archive skip trees with the archive tag.
9814 comment skip trees with the COMMENT keyword
9815 function or Emacs Lisp form:
9816 will be used as value for `org-agenda-skip-function', so whenever
9817 the the function returns t, FUNC will not be called for that
9818 entry and search will continue from the point where the
9819 function leaves it."
9820 (let* ((org-agenda-archives-mode nil) ; just to make sure
9821 (org-agenda-skip-archived-trees (memq 'archive skip))
9822 (org-agenda-skip-comment-trees (memq 'comment skip))
9823 (org-agenda-skip-function
9824 (car (org-delete-all '(comment archive) skip)))
9825 (org-tags-match-list-sublevels t)
9826 matcher pos file
9827 org-todo-keywords-for-agenda
9828 org-done-keywords-for-agenda
9829 org-todo-keyword-alist-for-agenda
9830 org-tag-alist-for-agenda)
9832 (cond
9833 ((eq match t) (setq matcher t))
9834 ((eq match nil) (setq matcher t))
9835 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9837 (when (eq scope 'tree)
9838 (org-back-to-heading t)
9839 (org-narrow-to-subtree)
9840 (setq scope nil))
9842 (if (not scope)
9843 (progn
9844 (org-prepare-agenda-buffers
9845 (list (buffer-file-name (current-buffer))))
9846 (org-scan-tags func matcher))
9847 ;; Get the right scope
9848 (setq pos (point))
9849 (cond
9850 ((and scope (listp scope) (symbolp (car scope)))
9851 (setq scope (eval scope)))
9852 ((eq scope 'agenda)
9853 (setq scope (org-agenda-files t)))
9854 ((eq scope 'agenda-with-archives)
9855 (setq scope (org-agenda-files t))
9856 (setq scope (org-add-archive-files scope)))
9857 ((eq scope 'file)
9858 (setq scope (list (buffer-file-name))))
9859 ((eq scope 'file-with-archives)
9860 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9861 (org-prepare-agenda-buffers scope)
9862 (while (setq file (pop scope))
9863 (with-current-buffer (org-find-base-buffer-visiting file)
9864 (save-excursion
9865 (save-restriction
9866 (widen)
9867 (goto-char (point-min))
9868 (org-scan-tags func matcher))))))))
9870 ;;;; Properties
9872 ;;; Setting and retrieving properties
9874 (defconst org-special-properties
9875 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9876 "TIMESTAMP" "TIMESTAMP_IA")
9877 "The special properties valid in Org-mode.
9879 These are properties that are not defined in the property drawer,
9880 but in some other way.")
9882 (defconst org-default-properties
9883 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9884 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9885 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9886 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9887 "Some properties that are used by Org-mode for various purposes.
9888 Being in this list makes sure that they are offered for completion.")
9890 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9891 "Regular expression matching the first line of a property drawer.")
9893 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9894 "Regular expression matching the first line of a property drawer.")
9896 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9897 "Regular expression matching the first line of a property drawer.")
9899 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9900 "Regular expression matching the first line of a property drawer.")
9902 (defconst org-property-drawer-re
9903 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9904 org-property-end-re "\\)\n?")
9905 "Matches an entire property drawer.")
9907 (defconst org-clock-drawer-re
9908 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9909 org-property-end-re "\\)\n?")
9910 "Matches an entire clock drawer.")
9912 (defun org-property-action ()
9913 "Do an action on properties."
9914 (interactive)
9915 (let (c)
9916 (org-at-property-p)
9917 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9918 (setq c (read-char-exclusive))
9919 (cond
9920 ((equal c ?s)
9921 (call-interactively 'org-set-property))
9922 ((equal c ?d)
9923 (call-interactively 'org-delete-property))
9924 ((equal c ?D)
9925 (call-interactively 'org-delete-property-globally))
9926 ((equal c ?c)
9927 (call-interactively 'org-compute-property-at-point))
9928 (t (error "No such property action %c" c)))))
9930 (defun org-at-property-p ()
9931 "Is the cursor in a property line?"
9932 ;; FIXME: Does not check if we are actually in the drawer.
9933 ;; FIXME: also returns true on any drawers.....
9934 ;; This is used by C-c C-c for property action.
9935 (save-excursion
9936 (beginning-of-line 1)
9937 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9939 (defun org-get-property-block (&optional beg end force)
9940 "Return the (beg . end) range of the body of the property drawer.
9941 BEG and END can be beginning and end of subtree, if not given
9942 they will be found.
9943 If the drawer does not exist and FORCE is non-nil, create the drawer."
9944 (catch 'exit
9945 (save-excursion
9946 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9947 (end (or end (progn (outline-next-heading) (point)))))
9948 (goto-char beg)
9949 (if (re-search-forward org-property-start-re end t)
9950 (setq beg (1+ (match-end 0)))
9951 (if force
9952 (save-excursion
9953 (org-insert-property-drawer)
9954 (setq end (progn (outline-next-heading) (point))))
9955 (throw 'exit nil))
9956 (goto-char beg)
9957 (if (re-search-forward org-property-start-re end t)
9958 (setq beg (1+ (match-end 0)))))
9959 (if (re-search-forward org-property-end-re end t)
9960 (setq end (match-beginning 0))
9961 (or force (throw 'exit nil))
9962 (goto-char beg)
9963 (setq end beg)
9964 (org-indent-line-function)
9965 (insert ":END:\n"))
9966 (cons beg end)))))
9968 (defun org-entry-properties (&optional pom which)
9969 "Get all properties of the entry at point-or-marker POM.
9970 This includes the TODO keyword, the tags, time strings for deadline,
9971 scheduled, and clocking, and any additional properties defined in the
9972 entry. The return value is an alist, keys may occur multiple times
9973 if the property key was used several times.
9974 POM may also be nil, in which case the current entry is used.
9975 If WHICH is nil or `all', get all properties. If WHICH is
9976 `special' or `standard', only get that subclass."
9977 (setq which (or which 'all))
9978 (org-with-point-at pom
9979 (let ((clockstr (substring org-clock-string 0 -1))
9980 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9981 beg end range props sum-props key value string clocksum)
9982 (save-excursion
9983 (when (condition-case nil (org-back-to-heading t) (error nil))
9984 (setq beg (point))
9985 (setq sum-props (get-text-property (point) 'org-summaries))
9986 (setq clocksum (get-text-property (point) :org-clock-minutes))
9987 (outline-next-heading)
9988 (setq end (point))
9989 (when (memq which '(all special))
9990 ;; Get the special properties, like TODO and tags
9991 (goto-char beg)
9992 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9993 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9994 (when (looking-at org-priority-regexp)
9995 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9996 (when (and (setq value (org-get-tags-string))
9997 (string-match "\\S-" value))
9998 (push (cons "TAGS" value) props))
9999 (when (setq value (org-get-tags-at))
10000 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10001 props))
10002 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10003 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10004 string (if (equal key clockstr)
10005 (org-no-properties
10006 (org-trim
10007 (buffer-substring
10008 (match-beginning 3) (goto-char (point-at-eol)))))
10009 (substring (org-match-string-no-properties 3) 1 -1)))
10010 (unless key
10011 (if (= (char-after (match-beginning 3)) ?\[)
10012 (setq key "TIMESTAMP_IA")
10013 (setq key "TIMESTAMP")))
10014 (when (or (equal key clockstr) (not (assoc key props)))
10015 (push (cons key string) props)))
10019 (when (memq which '(all standard))
10020 ;; Get the standard properties, like :PORP: ...
10021 (setq range (org-get-property-block beg end))
10022 (when range
10023 (goto-char (car range))
10024 (while (re-search-forward
10025 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10026 (cdr range) t)
10027 (setq key (org-match-string-no-properties 1)
10028 value (org-trim (or (org-match-string-no-properties 2) "")))
10029 (unless (member key excluded)
10030 (push (cons key (or value "")) props)))))
10031 (if clocksum
10032 (push (cons "CLOCKSUM"
10033 (org-columns-number-to-string (/ (float clocksum) 60.)
10034 'add_times))
10035 props))
10036 (unless (assoc "CATEGORY" props)
10037 (setq value (or (org-get-category)
10038 (progn (org-refresh-category-properties)
10039 (org-get-category))))
10040 (push (cons "CATEGORY" value) props))
10041 (append sum-props (nreverse props)))))))
10043 (defun org-entry-get (pom property &optional inherit)
10044 "Get value of PROPERTY for entry at point-or-marker POM.
10045 If INHERIT is non-nil and the entry does not have the property,
10046 then also check higher levels of the hierarchy.
10047 If INHERIT is the symbol `selective', use inheritance only if the setting
10048 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10049 If the property is present but empty, the return value is the empty string.
10050 If the property is not present at all, nil is returned."
10051 (org-with-point-at pom
10052 (if (and inherit (if (eq inherit 'selective)
10053 (org-property-inherit-p property)
10055 (org-entry-get-with-inheritance property)
10056 (if (member property org-special-properties)
10057 ;; We need a special property. Use brute force, get all properties.
10058 (cdr (assoc property (org-entry-properties nil 'special)))
10059 (let ((range (org-get-property-block)))
10060 (if (and range
10061 (goto-char (car range))
10062 (re-search-forward
10063 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10064 (cdr range) t))
10065 ;; Found the property, return it.
10066 (if (match-end 1)
10067 (org-match-string-no-properties 1)
10068 "")))))))
10070 (defun org-property-or-variable-value (var &optional inherit)
10071 "Check if there is a property fixing the value of VAR.
10072 If yes, return this value. If not, return the current value of the variable."
10073 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10074 (if (and prop (stringp prop) (string-match "\\S-" prop))
10075 (read prop)
10076 (symbol-value var))))
10078 (defun org-entry-delete (pom property)
10079 "Delete the property PROPERTY from entry at point-or-marker POM."
10080 (org-with-point-at pom
10081 (if (member property org-special-properties)
10082 nil ; cannot delete these properties.
10083 (let ((range (org-get-property-block)))
10084 (if (and range
10085 (goto-char (car range))
10086 (re-search-forward
10087 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10088 (cdr range) t))
10089 (progn
10090 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10092 nil)))))
10094 ;; Multi-values properties are properties that contain multiple values
10095 ;; These values are assumed to be single words, separated by whitespace.
10096 (defun org-entry-add-to-multivalued-property (pom property value)
10097 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10098 (let* ((old (org-entry-get pom property))
10099 (values (and old (org-split-string old "[ \t]"))))
10100 (setq value (org-entry-protect-space value))
10101 (unless (member value values)
10102 (setq values (cons value values))
10103 (org-entry-put pom property
10104 (mapconcat 'identity values " ")))))
10106 (defun org-entry-remove-from-multivalued-property (pom property value)
10107 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10108 (let* ((old (org-entry-get pom property))
10109 (values (and old (org-split-string old "[ \t]"))))
10110 (setq value (org-entry-protect-space value))
10111 (when (member value values)
10112 (setq values (delete value values))
10113 (org-entry-put pom property
10114 (mapconcat 'identity values " ")))))
10116 (defun org-entry-member-in-multivalued-property (pom property value)
10117 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10118 (let* ((old (org-entry-get pom property))
10119 (values (and old (org-split-string old "[ \t]"))))
10120 (setq value (org-entry-protect-space value))
10121 (member value values)))
10123 (defun org-entry-get-multivalued-property (pom property)
10124 "Return a list of values in a multivalued property."
10125 (let* ((value (org-entry-get pom property))
10126 (values (and value (org-split-string value "[ \t]"))))
10127 (mapcar 'org-entry-restore-space values)))
10129 (defun org-entry-put-multivalued-property (pom property &rest values)
10130 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10131 VALUES should be a list of strings. Spaces will be protected."
10132 (org-entry-put pom property
10133 (mapconcat 'org-entry-protect-space values " "))
10134 (let* ((value (org-entry-get pom property))
10135 (values (and value (org-split-string value "[ \t]"))))
10136 (mapcar 'org-entry-restore-space values)))
10138 (defun org-entry-protect-space (s)
10139 "Protect spaces and newline in string S."
10140 (while (string-match " " s)
10141 (setq s (replace-match "%20" t t s)))
10142 (while (string-match "\n" s)
10143 (setq s (replace-match "%0A" t t s)))
10146 (defun org-entry-restore-space (s)
10147 "Restore spaces and newline in string S."
10148 (while (string-match "%20" s)
10149 (setq s (replace-match " " t t s)))
10150 (while (string-match "%0A" s)
10151 (setq s (replace-match "\n" t t s)))
10154 (defvar org-entry-property-inherited-from (make-marker)
10155 "Marker pointing to the entry from where a proerty was inherited.
10156 Each call to `org-entry-get-with-inheritance' will set this marker to the
10157 location of the entry where the inheriance search matched. If there was
10158 no match, the marker will point nowhere.
10159 Note that also `org-entry-get' calls this function, if the INHERIT flag
10160 is set.")
10162 (defun org-entry-get-with-inheritance (property)
10163 "Get entry property, and search higher levels if not present."
10164 (move-marker org-entry-property-inherited-from nil)
10165 (let (tmp)
10166 (save-excursion
10167 (save-restriction
10168 (widen)
10169 (catch 'ex
10170 (while t
10171 (when (setq tmp (org-entry-get nil property))
10172 (org-back-to-heading t)
10173 (move-marker org-entry-property-inherited-from (point))
10174 (throw 'ex tmp))
10175 (or (org-up-heading-safe) (throw 'ex nil)))))
10176 (or tmp
10177 (cdr (assoc property org-file-properties))
10178 (cdr (assoc property org-global-properties))
10179 (cdr (assoc property org-global-properties-fixed))))))
10181 (defun org-entry-put (pom property value)
10182 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10183 (org-with-point-at pom
10184 (org-back-to-heading t)
10185 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10186 range)
10187 (cond
10188 ((equal property "TODO")
10189 (when (and (stringp value) (string-match "\\S-" value)
10190 (not (member value org-todo-keywords-1)))
10191 (error "\"%s\" is not a valid TODO state" value))
10192 (if (or (not value)
10193 (not (string-match "\\S-" value)))
10194 (setq value 'none))
10195 (org-todo value)
10196 (org-set-tags nil 'align))
10197 ((equal property "PRIORITY")
10198 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10199 (string-to-char value) ?\ ))
10200 (org-set-tags nil 'align))
10201 ((equal property "SCHEDULED")
10202 (if (re-search-forward org-scheduled-time-regexp end t)
10203 (cond
10204 ((eq value 'earlier) (org-timestamp-change -1 'day))
10205 ((eq value 'later) (org-timestamp-change 1 'day))
10206 (t (call-interactively 'org-schedule)))
10207 (call-interactively 'org-schedule)))
10208 ((equal property "DEADLINE")
10209 (if (re-search-forward org-deadline-time-regexp end t)
10210 (cond
10211 ((eq value 'earlier) (org-timestamp-change -1 'day))
10212 ((eq value 'later) (org-timestamp-change 1 'day))
10213 (t (call-interactively 'org-deadline)))
10214 (call-interactively 'org-deadline)))
10215 ((member property org-special-properties)
10216 (error "The %s property can not yet be set with `org-entry-put'"
10217 property))
10218 (t ; a non-special property
10219 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10220 (setq range (org-get-property-block beg end 'force))
10221 (goto-char (car range))
10222 (if (re-search-forward
10223 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10224 (progn
10225 (delete-region (match-beginning 1) (match-end 1))
10226 (goto-char (match-beginning 1)))
10227 (goto-char (cdr range))
10228 (insert "\n")
10229 (backward-char 1)
10230 (org-indent-line-function)
10231 (insert ":" property ":"))
10232 (and value (insert " " value))
10233 (org-indent-line-function)))))))
10235 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10236 "Get all property keys in the current buffer.
10237 With INCLUDE-SPECIALS, also list the special properties that relect things
10238 like tags and TODO state.
10239 With INCLUDE-DEFAULTS, also include properties that has special meaning
10240 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10241 With INCLUDE-COLUMNS, also include property names given in COLUMN
10242 formats in the current buffer."
10243 (let (rtn range cfmt cols s p)
10244 (save-excursion
10245 (save-restriction
10246 (widen)
10247 (goto-char (point-min))
10248 (while (re-search-forward org-property-start-re nil t)
10249 (setq range (org-get-property-block))
10250 (goto-char (car range))
10251 (while (re-search-forward
10252 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10253 (cdr range) t)
10254 (add-to-list 'rtn (org-match-string-no-properties 1)))
10255 (outline-next-heading))))
10257 (when include-specials
10258 (setq rtn (append org-special-properties rtn)))
10260 (when include-defaults
10261 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10263 (when include-columns
10264 (save-excursion
10265 (save-restriction
10266 (widen)
10267 (goto-char (point-min))
10268 (while (re-search-forward
10269 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10270 nil t)
10271 (setq cfmt (match-string 2) s 0)
10272 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10273 cfmt s)
10274 (setq s (match-end 0)
10275 p (match-string 1 cfmt))
10276 (unless (or (equal p "ITEM")
10277 (member p org-special-properties))
10278 (add-to-list 'rtn (match-string 1 cfmt))))))))
10280 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10282 (defun org-property-values (key)
10283 "Return a list of all values of property KEY."
10284 (save-excursion
10285 (save-restriction
10286 (widen)
10287 (goto-char (point-min))
10288 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10289 values)
10290 (while (re-search-forward re nil t)
10291 (add-to-list 'values (org-trim (match-string 1))))
10292 (delete "" values)))))
10294 (defun org-insert-property-drawer ()
10295 "Insert a property drawer into the current entry."
10296 (interactive)
10297 (org-back-to-heading t)
10298 (looking-at outline-regexp)
10299 (let ((indent (- (match-end 0)(match-beginning 0)))
10300 (beg (point))
10301 (re (concat "^[ \t]*" org-keyword-time-regexp))
10302 end hiddenp)
10303 (outline-next-heading)
10304 (setq end (point))
10305 (goto-char beg)
10306 (while (re-search-forward re end t))
10307 (setq hiddenp (org-invisible-p))
10308 (end-of-line 1)
10309 (and (equal (char-after) ?\n) (forward-char 1))
10310 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10311 (beginning-of-line 2))
10312 (org-skip-over-state-notes)
10313 (skip-chars-backward " \t\n\r")
10314 (if (eq (char-before) ?*) (forward-char 1))
10315 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10316 (beginning-of-line 0)
10317 (org-indent-to-column indent)
10318 (beginning-of-line 2)
10319 (org-indent-to-column indent)
10320 (beginning-of-line 0)
10321 (if hiddenp
10322 (save-excursion
10323 (org-back-to-heading t)
10324 (hide-entry))
10325 (org-flag-drawer t))))
10327 (defun org-set-property (property value)
10328 "In the current entry, set PROPERTY to VALUE.
10329 When called interactively, this will prompt for a property name, offering
10330 completion on existing and default properties. And then it will prompt
10331 for a value, offering competion either on allowed values (via an inherited
10332 xxx_ALL property) or on existing values in other instances of this property
10333 in the current file."
10334 (interactive
10335 (let* ((completion-ignore-case t)
10336 (keys (org-buffer-property-keys nil t t))
10337 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10338 (prop (if (member prop0 keys)
10339 prop0
10340 (or (cdr (assoc (downcase prop0)
10341 (mapcar (lambda (x) (cons (downcase x) x))
10342 keys)))
10343 prop0)))
10344 (cur (org-entry-get nil prop))
10345 (allowed (org-property-get-allowed-values nil prop 'table))
10346 (existing (mapcar 'list (org-property-values prop)))
10347 (val (if allowed
10348 (org-completing-read "Value: " allowed nil 'req-match)
10349 (org-completing-read
10350 (concat "Value" (if (and cur (string-match "\\S-" cur))
10351 (concat "[" cur "]") "")
10352 ": ")
10353 existing nil nil "" nil cur))))
10354 (list prop (if (equal val "") cur val))))
10355 (unless (equal (org-entry-get nil property) value)
10356 (org-entry-put nil property value)))
10358 (defun org-delete-property (property)
10359 "In the current entry, delete PROPERTY."
10360 (interactive
10361 (let* ((completion-ignore-case t)
10362 (prop (org-ido-completing-read
10363 "Property: " (org-entry-properties nil 'standard))))
10364 (list prop)))
10365 (message "Property %s %s" property
10366 (if (org-entry-delete nil property)
10367 "deleted"
10368 "was not present in the entry")))
10370 (defun org-delete-property-globally (property)
10371 "Remove PROPERTY globally, from all entries."
10372 (interactive
10373 (let* ((completion-ignore-case t)
10374 (prop (org-ido-completing-read
10375 "Globally remove property: "
10376 (mapcar 'list (org-buffer-property-keys)))))
10377 (list prop)))
10378 (save-excursion
10379 (save-restriction
10380 (widen)
10381 (goto-char (point-min))
10382 (let ((cnt 0))
10383 (while (re-search-forward
10384 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10385 nil t)
10386 (setq cnt (1+ cnt))
10387 (replace-match ""))
10388 (message "Property \"%s\" removed from %d entries" property cnt)))))
10390 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10392 (defun org-compute-property-at-point ()
10393 "Compute the property at point.
10394 This looks for an enclosing column format, extracts the operator and
10395 then applies it to the proerty in the column format's scope."
10396 (interactive)
10397 (unless (org-at-property-p)
10398 (error "Not at a property"))
10399 (let ((prop (org-match-string-no-properties 2)))
10400 (org-columns-get-format-and-top-level)
10401 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10402 (error "No operator defined for property %s" prop))
10403 (org-columns-compute prop)))
10405 (defun org-property-get-allowed-values (pom property &optional table)
10406 "Get allowed values for the property PROPERTY.
10407 When TABLE is non-nil, return an alist that can directly be used for
10408 completion."
10409 (let (vals)
10410 (cond
10411 ((equal property "TODO")
10412 (setq vals (org-with-point-at pom
10413 (append org-todo-keywords-1 '("")))))
10414 ((equal property "PRIORITY")
10415 (let ((n org-lowest-priority))
10416 (while (>= n org-highest-priority)
10417 (push (char-to-string n) vals)
10418 (setq n (1- n)))))
10419 ((member property org-special-properties))
10421 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10423 (when (and vals (string-match "\\S-" vals))
10424 (setq vals (car (read-from-string (concat "(" vals ")"))))
10425 (setq vals (mapcar (lambda (x)
10426 (cond ((stringp x) x)
10427 ((numberp x) (number-to-string x))
10428 ((symbolp x) (symbol-name x))
10429 (t "???")))
10430 vals)))))
10431 (if table (mapcar 'list vals) vals)))
10433 (defun org-property-previous-allowed-value (&optional previous)
10434 "Switch to the next allowed value for this property."
10435 (interactive)
10436 (org-property-next-allowed-value t))
10438 (defun org-property-next-allowed-value (&optional previous)
10439 "Switch to the next allowed value for this property."
10440 (interactive)
10441 (unless (org-at-property-p)
10442 (error "Not at a property"))
10443 (let* ((key (match-string 2))
10444 (value (match-string 3))
10445 (allowed (or (org-property-get-allowed-values (point) key)
10446 (and (member value '("[ ]" "[-]" "[X]"))
10447 '("[ ]" "[X]"))))
10448 nval)
10449 (unless allowed
10450 (error "Allowed values for this property have not been defined"))
10451 (if previous (setq allowed (reverse allowed)))
10452 (if (member value allowed)
10453 (setq nval (car (cdr (member value allowed)))))
10454 (setq nval (or nval (car allowed)))
10455 (if (equal nval value)
10456 (error "Only one allowed value for this property"))
10457 (org-at-property-p)
10458 (replace-match (concat " :" key ": " nval) t t)
10459 (org-indent-line-function)
10460 (beginning-of-line 1)
10461 (skip-chars-forward " \t")))
10463 (defun org-find-entry-with-id (ident)
10464 "Locate the entry that contains the ID property with exact value IDENT.
10465 IDENT can be a string, a symbol or a number, this function will search for
10466 the string representation of it.
10467 Return the position where this entry starts, or nil if there is no such entry."
10468 (let ((id (cond
10469 ((stringp ident) ident)
10470 ((symbol-name ident) (symbol-name ident))
10471 ((numberp ident) (number-to-string ident))
10472 (t (error "IDENT %s must be a string, symbol or number" ident))))
10473 (case-fold-search nil))
10474 (save-excursion
10475 (save-restriction
10476 (widen)
10477 (goto-char (point-min))
10478 (when (re-search-forward
10479 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10480 nil t)
10481 (org-back-to-heading)
10482 (point))))))
10484 ;;;; Timestamps
10486 (defvar org-last-changed-timestamp nil)
10487 (defvar org-last-inserted-timestamp nil
10488 "The last time stamp inserted with `org-insert-time-stamp'.")
10489 (defvar org-time-was-given) ; dynamically scoped parameter
10490 (defvar org-end-time-was-given) ; dynamically scoped parameter
10491 (defvar org-ts-what) ; dynamically scoped parameter
10493 (defun org-time-stamp (arg &optional inactive)
10494 "Prompt for a date/time and insert a time stamp.
10495 If the user specifies a time like HH:MM, or if this command is called
10496 with a prefix argument, the time stamp will contain date and time.
10497 Otherwise, only the date will be included. All parts of a date not
10498 specified by the user will be filled in from the current date/time.
10499 So if you press just return without typing anything, the time stamp
10500 will represent the current date/time. If there is already a timestamp
10501 at the cursor, it will be modified."
10502 (interactive "P")
10503 (let* ((ts nil)
10504 (default-time
10505 ;; Default time is either today, or, when entering a range,
10506 ;; the range start.
10507 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10508 (save-excursion
10509 (re-search-backward
10510 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10511 (- (point) 20) t)))
10512 (apply 'encode-time (org-parse-time-string (match-string 1)))
10513 (current-time)))
10514 (default-input (and ts (org-get-compact-tod ts)))
10515 org-time-was-given org-end-time-was-given time)
10516 (cond
10517 ((and (org-at-timestamp-p t)
10518 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10519 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10520 (insert "--")
10521 (setq time (let ((this-command this-command))
10522 (org-read-date arg 'totime nil nil
10523 default-time default-input)))
10524 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10525 ((org-at-timestamp-p t)
10526 (setq time (let ((this-command this-command))
10527 (org-read-date arg 'totime nil nil default-time default-input)))
10528 (when (org-at-timestamp-p t) ; just to get the match data
10529 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10530 (replace-match "")
10531 (setq org-last-changed-timestamp
10532 (org-insert-time-stamp
10533 time (or org-time-was-given arg)
10534 inactive nil nil (list org-end-time-was-given))))
10535 (message "Timestamp updated"))
10537 (setq time (let ((this-command this-command))
10538 (org-read-date arg 'totime nil nil default-time default-input)))
10539 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10540 nil nil (list org-end-time-was-given))))))
10542 ;; FIXME: can we use this for something else, like computing time differences?
10543 (defun org-get-compact-tod (s)
10544 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10545 (let* ((t1 (match-string 1 s))
10546 (h1 (string-to-number (match-string 2 s)))
10547 (m1 (string-to-number (match-string 3 s)))
10548 (t2 (and (match-end 4) (match-string 5 s)))
10549 (h2 (and t2 (string-to-number (match-string 6 s))))
10550 (m2 (and t2 (string-to-number (match-string 7 s))))
10551 dh dm)
10552 (if (not t2)
10554 (setq dh (- h2 h1) dm (- m2 m1))
10555 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10556 (concat t1 "+" (number-to-string dh)
10557 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10559 (defun org-time-stamp-inactive (&optional arg)
10560 "Insert an inactive time stamp.
10561 An inactive time stamp is enclosed in square brackets instead of angle
10562 brackets. It is inactive in the sense that it does not trigger agenda entries,
10563 does not link to the calendar and cannot be changed with the S-cursor keys.
10564 So these are more for recording a certain time/date."
10565 (interactive "P")
10566 (org-time-stamp arg 'inactive))
10568 (defvar org-date-ovl (org-make-overlay 1 1))
10569 (org-overlay-put org-date-ovl 'face 'org-warning)
10570 (org-detach-overlay org-date-ovl)
10572 (defvar org-ans1) ; dynamically scoped parameter
10573 (defvar org-ans2) ; dynamically scoped parameter
10575 (defvar org-plain-time-of-day-regexp) ; defined below
10577 (defvar org-overriding-default-time nil) ; dynamically scoped
10578 (defvar org-read-date-overlay nil)
10579 (defvar org-dcst nil) ; dynamically scoped
10581 (defun org-read-date (&optional with-time to-time from-string prompt
10582 default-time default-input)
10583 "Read a date, possibly a time, and make things smooth for the user.
10584 The prompt will suggest to enter an ISO date, but you can also enter anything
10585 which will at least partially be understood by `parse-time-string'.
10586 Unrecognized parts of the date will default to the current day, month, year,
10587 hour and minute. If this command is called to replace a timestamp at point,
10588 of to enter the second timestamp of a range, the default time is taken from the
10589 existing stamp. For example,
10590 3-2-5 --> 2003-02-05
10591 feb 15 --> currentyear-02-15
10592 sep 12 9 --> 2009-09-12
10593 12:45 --> today 12:45
10594 22 sept 0:34 --> currentyear-09-22 0:34
10595 12 --> currentyear-currentmonth-12
10596 Fri --> nearest Friday (today or later)
10597 etc.
10599 Furthermore you can specify a relative date by giving, as the *first* thing
10600 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10601 change in days weeks, months, years.
10602 With a single plus or minus, the date is relative to today. With a double
10603 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10604 +4d --> four days from today
10605 +4 --> same as above
10606 +2w --> two weeks from today
10607 ++5 --> five days from default date
10609 The function understands only English month and weekday abbreviations,
10610 but this can be configured with the variables `parse-time-months' and
10611 `parse-time-weekdays'.
10613 While prompting, a calendar is popped up - you can also select the
10614 date with the mouse (button 1). The calendar shows a period of three
10615 months. To scroll it to other months, use the keys `>' and `<'.
10616 If you don't like the calendar, turn it off with
10617 \(setq org-read-date-popup-calendar nil)
10619 With optional argument TO-TIME, the date will immediately be converted
10620 to an internal time.
10621 With an optional argument WITH-TIME, the prompt will suggest to also
10622 insert a time. Note that when WITH-TIME is not set, you can still
10623 enter a time, and this function will inform the calling routine about
10624 this change. The calling routine may then choose to change the format
10625 used to insert the time stamp into the buffer to include the time.
10626 With optional argument FROM-STRING, read from this string instead from
10627 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10628 the time/date that is used for everything that is not specified by the
10629 user."
10630 (require 'parse-time)
10631 (let* ((org-time-stamp-rounding-minutes
10632 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10633 (org-dcst org-display-custom-times)
10634 (ct (org-current-time))
10635 (def (or org-overriding-default-time default-time ct))
10636 (defdecode (decode-time def))
10637 (dummy (progn
10638 (when (< (nth 2 defdecode) org-extend-today-until)
10639 (setcar (nthcdr 2 defdecode) -1)
10640 (setcar (nthcdr 1 defdecode) 59)
10641 (setq def (apply 'encode-time defdecode)
10642 defdecode (decode-time def)))))
10643 (calendar-move-hook nil)
10644 (calendar-view-diary-initially-flag nil)
10645 (view-diary-entries-initially nil)
10646 (calendar-view-holidays-initially-flag nil)
10647 (view-calendar-holidays-initially nil)
10648 (timestr (format-time-string
10649 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10650 (prompt (concat (if prompt (concat prompt " ") "")
10651 (format "Date+time [%s]: " timestr)))
10652 ans (org-ans0 "") org-ans1 org-ans2 final)
10654 (cond
10655 (from-string (setq ans from-string))
10656 (org-read-date-popup-calendar
10657 (save-excursion
10658 (save-window-excursion
10659 (calendar)
10660 (calendar-forward-day (- (time-to-days def)
10661 (calendar-absolute-from-gregorian
10662 (calendar-current-date))))
10663 (org-eval-in-calendar nil t)
10664 (let* ((old-map (current-local-map))
10665 (map (copy-keymap calendar-mode-map))
10666 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10667 (org-defkey map (kbd "RET") 'org-calendar-select)
10668 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10669 'org-calendar-select-mouse)
10670 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10671 'org-calendar-select-mouse)
10672 (org-defkey minibuffer-local-map [(meta shift left)]
10673 (lambda () (interactive)
10674 (org-eval-in-calendar '(calendar-backward-month 1))))
10675 (org-defkey minibuffer-local-map [(meta shift right)]
10676 (lambda () (interactive)
10677 (org-eval-in-calendar '(calendar-forward-month 1))))
10678 (org-defkey minibuffer-local-map [(meta shift up)]
10679 (lambda () (interactive)
10680 (org-eval-in-calendar '(calendar-backward-year 1))))
10681 (org-defkey minibuffer-local-map [(meta shift down)]
10682 (lambda () (interactive)
10683 (org-eval-in-calendar '(calendar-forward-year 1))))
10684 (org-defkey minibuffer-local-map [(shift up)]
10685 (lambda () (interactive)
10686 (org-eval-in-calendar '(calendar-backward-week 1))))
10687 (org-defkey minibuffer-local-map [(shift down)]
10688 (lambda () (interactive)
10689 (org-eval-in-calendar '(calendar-forward-week 1))))
10690 (org-defkey minibuffer-local-map [(shift left)]
10691 (lambda () (interactive)
10692 (org-eval-in-calendar '(calendar-backward-day 1))))
10693 (org-defkey minibuffer-local-map [(shift right)]
10694 (lambda () (interactive)
10695 (org-eval-in-calendar '(calendar-forward-day 1))))
10696 (org-defkey minibuffer-local-map ">"
10697 (lambda () (interactive)
10698 (org-eval-in-calendar '(scroll-calendar-left 1))))
10699 (org-defkey minibuffer-local-map "<"
10700 (lambda () (interactive)
10701 (org-eval-in-calendar '(scroll-calendar-right 1))))
10702 (unwind-protect
10703 (progn
10704 (use-local-map map)
10705 (add-hook 'post-command-hook 'org-read-date-display)
10706 (setq org-ans0 (read-string prompt default-input nil nil))
10707 ;; org-ans0: from prompt
10708 ;; org-ans1: from mouse click
10709 ;; org-ans2: from calendar motion
10710 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10711 (remove-hook 'post-command-hook 'org-read-date-display)
10712 (use-local-map old-map)
10713 (when org-read-date-overlay
10714 (org-delete-overlay org-read-date-overlay)
10715 (setq org-read-date-overlay nil)))))))
10717 (t ; Naked prompt only
10718 (unwind-protect
10719 (setq ans (read-string prompt default-input nil timestr))
10720 (when org-read-date-overlay
10721 (org-delete-overlay org-read-date-overlay)
10722 (setq org-read-date-overlay nil)))))
10724 (setq final (org-read-date-analyze ans def defdecode))
10726 (if to-time
10727 (apply 'encode-time final)
10728 (if (and (boundp 'org-time-was-given) org-time-was-given)
10729 (format "%04d-%02d-%02d %02d:%02d"
10730 (nth 5 final) (nth 4 final) (nth 3 final)
10731 (nth 2 final) (nth 1 final))
10732 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10733 (defvar def)
10734 (defvar defdecode)
10735 (defvar with-time)
10736 (defun org-read-date-display ()
10737 "Display the currrent date prompt interpretation in the minibuffer."
10738 (when org-read-date-display-live
10739 (when org-read-date-overlay
10740 (org-delete-overlay org-read-date-overlay))
10741 (let ((p (point)))
10742 (end-of-line 1)
10743 (while (not (equal (buffer-substring
10744 (max (point-min) (- (point) 4)) (point))
10745 " "))
10746 (insert " "))
10747 (goto-char p))
10748 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10749 " " (or org-ans1 org-ans2)))
10750 (org-end-time-was-given nil)
10751 (f (org-read-date-analyze ans def defdecode))
10752 (fmts (if org-dcst
10753 org-time-stamp-custom-formats
10754 org-time-stamp-formats))
10755 (fmt (if (or with-time
10756 (and (boundp 'org-time-was-given) org-time-was-given))
10757 (cdr fmts)
10758 (car fmts)))
10759 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10760 (when (and org-end-time-was-given
10761 (string-match org-plain-time-of-day-regexp txt))
10762 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10763 org-end-time-was-given
10764 (substring txt (match-end 0)))))
10765 (setq org-read-date-overlay
10766 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10767 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10769 (defun org-read-date-analyze (ans def defdecode)
10770 "Analyze the combined answer of the date prompt."
10771 ;; FIXME: cleanup and comment
10772 (let (delta deltan deltaw deltadef year month day
10773 hour minute second wday pm h2 m2 tl wday1
10774 iso-year iso-weekday iso-week iso-year iso-date)
10776 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10777 (setq ans "+0"))
10779 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10780 (setq ans (replace-match "" t t ans)
10781 deltan (car delta)
10782 deltaw (nth 1 delta)
10783 deltadef (nth 2 delta)))
10785 ;; Check if there is an iso week date in there
10786 ;; If yes, sore the info and ostpone interpreting it until the rest
10787 ;; of the parsing is done
10788 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10789 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10790 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10791 iso-week (string-to-number (match-string 2 ans)))
10792 (setq ans (replace-match "" t t ans)))
10794 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10795 (when (string-match
10796 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10797 (setq year (if (match-end 2)
10798 (string-to-number (match-string 2 ans))
10799 (string-to-number (format-time-string "%Y")))
10800 month (string-to-number (match-string 3 ans))
10801 day (string-to-number (match-string 4 ans)))
10802 (if (< year 100) (setq year (+ 2000 year)))
10803 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10804 t nil ans)))
10805 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10806 ;; If there is a time with am/pm, and *no* time without it, we convert
10807 ;; so that matching will be successful.
10808 (loop for i from 1 to 2 do ; twice, for end time as well
10809 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10810 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10811 (setq hour (string-to-number (match-string 1 ans))
10812 minute (if (match-end 3)
10813 (string-to-number (match-string 3 ans))
10815 pm (equal ?p
10816 (string-to-char (downcase (match-string 4 ans)))))
10817 (if (and (= hour 12) (not pm))
10818 (setq hour 0)
10819 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10820 (setq ans (replace-match (format "%02d:%02d" hour minute)
10821 t t ans))))
10823 ;; Check if a time range is given as a duration
10824 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10825 (setq hour (string-to-number (match-string 1 ans))
10826 h2 (+ hour (string-to-number (match-string 3 ans)))
10827 minute (string-to-number (match-string 2 ans))
10828 m2 (+ minute (if (match-end 5) (string-to-number
10829 (match-string 5 ans))0)))
10830 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10831 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10832 t t ans)))
10834 ;; Check if there is a time range
10835 (when (boundp 'org-end-time-was-given)
10836 (setq org-time-was-given nil)
10837 (when (and (string-match org-plain-time-of-day-regexp ans)
10838 (match-end 8))
10839 (setq org-end-time-was-given (match-string 8 ans))
10840 (setq ans (concat (substring ans 0 (match-beginning 7))
10841 (substring ans (match-end 7))))))
10843 (setq tl (parse-time-string ans)
10844 day (or (nth 3 tl) (nth 3 defdecode))
10845 month (or (nth 4 tl)
10846 (if (and org-read-date-prefer-future
10847 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10848 (1+ (nth 4 defdecode))
10849 (nth 4 defdecode)))
10850 year (or (nth 5 tl)
10851 (if (and org-read-date-prefer-future
10852 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10853 (1+ (nth 5 defdecode))
10854 (nth 5 defdecode)))
10855 hour (or (nth 2 tl) (nth 2 defdecode))
10856 minute (or (nth 1 tl) (nth 1 defdecode))
10857 second (or (nth 0 tl) 0)
10858 wday (nth 6 tl))
10860 ;; Special date definitions below
10861 (cond
10862 (iso-week
10863 ;; There was an iso week
10864 (setq year (or iso-year year)
10865 day (or iso-weekday wday 1)
10866 wday nil ; to make sure that the trigger below does not match
10867 iso-date (calendar-gregorian-from-absolute
10868 (calendar-absolute-from-iso
10869 (list iso-week day year))))
10870 ; FIXME: Should we also push ISO weeks into the future?
10871 ; (when (and org-read-date-prefer-future
10872 ; (not iso-year)
10873 ; (< (calendar-absolute-from-gregorian iso-date)
10874 ; (time-to-days (current-time))))
10875 ; (setq year (1+ year)
10876 ; iso-date (calendar-gregorian-from-absolute
10877 ; (calendar-absolute-from-iso
10878 ; (list iso-week day year)))))
10879 (setq month (car iso-date)
10880 year (nth 2 iso-date)
10881 day (nth 1 iso-date)))
10882 (deltan
10883 (unless deltadef
10884 (let ((now (decode-time (current-time))))
10885 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10886 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10887 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10888 ((equal deltaw "m") (setq month (+ month deltan)))
10889 ((equal deltaw "y") (setq year (+ year deltan)))))
10890 ((and wday (not (nth 3 tl)))
10891 ;; Weekday was given, but no day, so pick that day in the week
10892 ;; on or after the derived date.
10893 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10894 (unless (equal wday wday1)
10895 (setq day (+ day (% (- wday wday1 -7) 7))))))
10896 (if (and (boundp 'org-time-was-given)
10897 (nth 2 tl))
10898 (setq org-time-was-given t))
10899 (if (< year 100) (setq year (+ 2000 year)))
10900 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10901 (list second minute hour day month year)))
10903 (defvar parse-time-weekdays)
10905 (defun org-read-date-get-relative (s today default)
10906 "Check string S for special relative date string.
10907 TODAY and DEFAULT are internal times, for today and for a default.
10908 Return shift list (N what def-flag)
10909 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10910 N is the number of WHATs to shift.
10911 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10912 the DEFAULT date rather than TODAY."
10913 (when (and
10914 (string-match
10915 (concat
10916 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10917 "\\([0-9]+\\)?"
10918 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10919 "\\([ \t]\\|$\\)") s)
10920 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10921 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10922 (string-to-char (substring (match-string 1 s) -1))
10923 ?+))
10924 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10925 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10926 (what (if (match-end 3) (match-string 3 s) "d"))
10927 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10928 (date (if rel default today))
10929 (wday (nth 6 (decode-time date)))
10930 delta)
10931 (if wday1
10932 (progn
10933 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10934 (if (= dir ?-) (setq delta (- delta 7)))
10935 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10936 (list delta "d" rel))
10937 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10939 (defun org-eval-in-calendar (form &optional keepdate)
10940 "Eval FORM in the calendar window and return to current window.
10941 Also, store the cursor date in variable org-ans2."
10942 (let ((sw (selected-window)))
10943 (select-window (get-buffer-window "*Calendar*"))
10944 (eval form)
10945 (when (and (not keepdate) (calendar-cursor-to-date))
10946 (let* ((date (calendar-cursor-to-date))
10947 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10948 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10949 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10950 (select-window sw)))
10952 (defun org-calendar-select ()
10953 "Return to `org-read-date' with the date currently selected.
10954 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10955 (interactive)
10956 (when (calendar-cursor-to-date)
10957 (let* ((date (calendar-cursor-to-date))
10958 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10959 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10960 (if (active-minibuffer-window) (exit-minibuffer))))
10962 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10963 "Insert a date stamp for the date given by the internal TIME.
10964 WITH-HM means, use the stamp format that includes the time of the day.
10965 INACTIVE means use square brackets instead of angular ones, so that the
10966 stamp will not contribute to the agenda.
10967 PRE and POST are optional strings to be inserted before and after the
10968 stamp.
10969 The command returns the inserted time stamp."
10970 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10971 stamp)
10972 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10973 (insert-before-markers (or pre ""))
10974 (insert-before-markers (setq stamp (format-time-string fmt time)))
10975 (when (listp extra)
10976 (setq extra (car extra))
10977 (if (and (stringp extra)
10978 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10979 (setq extra (format "-%02d:%02d"
10980 (string-to-number (match-string 1 extra))
10981 (string-to-number (match-string 2 extra))))
10982 (setq extra nil)))
10983 (when extra
10984 (backward-char 1)
10985 (insert-before-markers extra)
10986 (forward-char 1))
10987 (insert-before-markers (or post ""))
10988 (setq org-last-inserted-timestamp stamp)))
10990 (defun org-toggle-time-stamp-overlays ()
10991 "Toggle the use of custom time stamp formats."
10992 (interactive)
10993 (setq org-display-custom-times (not org-display-custom-times))
10994 (unless org-display-custom-times
10995 (let ((p (point-min)) (bmp (buffer-modified-p)))
10996 (while (setq p (next-single-property-change p 'display))
10997 (if (and (get-text-property p 'display)
10998 (eq (get-text-property p 'face) 'org-date))
10999 (remove-text-properties
11000 p (setq p (next-single-property-change p 'display))
11001 '(display t))))
11002 (set-buffer-modified-p bmp)))
11003 (if (featurep 'xemacs)
11004 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11005 (org-restart-font-lock)
11006 (setq org-table-may-need-update t)
11007 (if org-display-custom-times
11008 (message "Time stamps are overlayed with custom format")
11009 (message "Time stamp overlays removed")))
11011 (defun org-display-custom-time (beg end)
11012 "Overlay modified time stamp format over timestamp between BEG and END."
11013 (let* ((ts (buffer-substring beg end))
11014 t1 w1 with-hm tf time str w2 (off 0))
11015 (save-match-data
11016 (setq t1 (org-parse-time-string ts t))
11017 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11018 (setq off (- (match-end 0) (match-beginning 0)))))
11019 (setq end (- end off))
11020 (setq w1 (- end beg)
11021 with-hm (and (nth 1 t1) (nth 2 t1))
11022 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11023 time (org-fix-decoded-time t1)
11024 str (org-add-props
11025 (format-time-string
11026 (substring tf 1 -1) (apply 'encode-time time))
11027 nil 'mouse-face 'highlight)
11028 w2 (length str))
11029 (if (not (= w2 w1))
11030 (add-text-properties (1+ beg) (+ 2 beg)
11031 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11032 (if (featurep 'xemacs)
11033 (progn
11034 (put-text-property beg end 'invisible t)
11035 (put-text-property beg end 'end-glyph (make-glyph str)))
11036 (put-text-property beg end 'display str))))
11038 (defun org-translate-time (string)
11039 "Translate all timestamps in STRING to custom format.
11040 But do this only if the variable `org-display-custom-times' is set."
11041 (when org-display-custom-times
11042 (save-match-data
11043 (let* ((start 0)
11044 (re org-ts-regexp-both)
11045 t1 with-hm inactive tf time str beg end)
11046 (while (setq start (string-match re string start))
11047 (setq beg (match-beginning 0)
11048 end (match-end 0)
11049 t1 (save-match-data
11050 (org-parse-time-string (substring string beg end) t))
11051 with-hm (and (nth 1 t1) (nth 2 t1))
11052 inactive (equal (substring string beg (1+ beg)) "[")
11053 tf (funcall (if with-hm 'cdr 'car)
11054 org-time-stamp-custom-formats)
11055 time (org-fix-decoded-time t1)
11056 str (format-time-string
11057 (concat
11058 (if inactive "[" "<") (substring tf 1 -1)
11059 (if inactive "]" ">"))
11060 (apply 'encode-time time))
11061 string (replace-match str t t string)
11062 start (+ start (length str)))))))
11063 string)
11065 (defun org-fix-decoded-time (time)
11066 "Set 0 instead of nil for the first 6 elements of time.
11067 Don't touch the rest."
11068 (let ((n 0))
11069 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11071 (defun org-days-to-time (timestamp-string)
11072 "Difference between TIMESTAMP-STRING and now in days."
11073 (- (time-to-days (org-time-string-to-time timestamp-string))
11074 (time-to-days (current-time))))
11076 (defun org-deadline-close (timestamp-string &optional ndays)
11077 "Is the time in TIMESTAMP-STRING close to the current date?"
11078 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11079 (and (< (org-days-to-time timestamp-string) ndays)
11080 (not (org-entry-is-done-p))))
11082 (defun org-get-wdays (ts)
11083 "Get the deadline lead time appropriate for timestring TS."
11084 (cond
11085 ((<= org-deadline-warning-days 0)
11086 ;; 0 or negative, enforce this value no matter what
11087 (- org-deadline-warning-days))
11088 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11089 ;; lead time is specified.
11090 (floor (* (string-to-number (match-string 1 ts))
11091 (cdr (assoc (match-string 2 ts)
11092 '(("d" . 1) ("w" . 7)
11093 ("m" . 30.4) ("y" . 365.25)))))))
11094 ;; go for the default.
11095 (t org-deadline-warning-days)))
11097 (defun org-calendar-select-mouse (ev)
11098 "Return to `org-read-date' with the date currently selected.
11099 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11100 (interactive "e")
11101 (mouse-set-point ev)
11102 (when (calendar-cursor-to-date)
11103 (let* ((date (calendar-cursor-to-date))
11104 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11105 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11106 (if (active-minibuffer-window) (exit-minibuffer))))
11108 (defun org-check-deadlines (ndays)
11109 "Check if there are any deadlines due or past due.
11110 A deadline is considered due if it happens within `org-deadline-warning-days'
11111 days from today's date. If the deadline appears in an entry marked DONE,
11112 it is not shown. The prefix arg NDAYS can be used to test that many
11113 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11114 (interactive "P")
11115 (let* ((org-warn-days
11116 (cond
11117 ((equal ndays '(4)) 100000)
11118 (ndays (prefix-numeric-value ndays))
11119 (t (abs org-deadline-warning-days))))
11120 (case-fold-search nil)
11121 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11122 (callback
11123 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11125 (message "%d deadlines past-due or due within %d days"
11126 (org-occur regexp nil callback)
11127 org-warn-days)))
11129 (defun org-check-before-date (date)
11130 "Check if there are deadlines or scheduled entries before DATE."
11131 (interactive (list (org-read-date)))
11132 (let ((case-fold-search nil)
11133 (regexp (concat "\\<\\(" org-deadline-string
11134 "\\|" org-scheduled-string
11135 "\\) *<\\([^>]+\\)>"))
11136 (callback
11137 (lambda () (time-less-p
11138 (org-time-string-to-time (match-string 2))
11139 (org-time-string-to-time date)))))
11140 (message "%d entries before %s"
11141 (org-occur regexp nil callback) date)))
11143 (defun org-evaluate-time-range (&optional to-buffer)
11144 "Evaluate a time range by computing the difference between start and end.
11145 Normally the result is just printed in the echo area, but with prefix arg
11146 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11147 If the time range is actually in a table, the result is inserted into the
11148 next column.
11149 For time difference computation, a year is assumed to be exactly 365
11150 days in order to avoid rounding problems."
11151 (interactive "P")
11153 (org-clock-update-time-maybe)
11154 (save-excursion
11155 (unless (org-at-date-range-p t)
11156 (goto-char (point-at-bol))
11157 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11158 (if (not (org-at-date-range-p t))
11159 (error "Not at a time-stamp range, and none found in current line")))
11160 (let* ((ts1 (match-string 1))
11161 (ts2 (match-string 2))
11162 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11163 (match-end (match-end 0))
11164 (time1 (org-time-string-to-time ts1))
11165 (time2 (org-time-string-to-time ts2))
11166 (t1 (time-to-seconds time1))
11167 (t2 (time-to-seconds time2))
11168 (diff (abs (- t2 t1)))
11169 (negative (< (- t2 t1) 0))
11170 ;; (ys (floor (* 365 24 60 60)))
11171 (ds (* 24 60 60))
11172 (hs (* 60 60))
11173 (fy "%dy %dd %02d:%02d")
11174 (fy1 "%dy %dd")
11175 (fd "%dd %02d:%02d")
11176 (fd1 "%dd")
11177 (fh "%02d:%02d")
11178 y d h m align)
11179 (if havetime
11180 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11182 d (floor (/ diff ds)) diff (mod diff ds)
11183 h (floor (/ diff hs)) diff (mod diff hs)
11184 m (floor (/ diff 60)))
11185 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11187 d (floor (+ (/ diff ds) 0.5))
11188 h 0 m 0))
11189 (if (not to-buffer)
11190 (message "%s" (org-make-tdiff-string y d h m))
11191 (if (org-at-table-p)
11192 (progn
11193 (goto-char match-end)
11194 (setq align t)
11195 (and (looking-at " *|") (goto-char (match-end 0))))
11196 (goto-char match-end))
11197 (if (looking-at
11198 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11199 (replace-match ""))
11200 (if negative (insert " -"))
11201 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11202 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11203 (insert " " (format fh h m))))
11204 (if align (org-table-align))
11205 (message "Time difference inserted")))))
11207 (defun org-make-tdiff-string (y d h m)
11208 (let ((fmt "")
11209 (l nil))
11210 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11211 l (push y l)))
11212 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11213 l (push d l)))
11214 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11215 l (push h l)))
11216 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11217 l (push m l)))
11218 (apply 'format fmt (nreverse l))))
11220 (defun org-time-string-to-time (s)
11221 (apply 'encode-time (org-parse-time-string s)))
11223 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11224 "Convert a time stamp to an absolute day number.
11225 If there is a specifyer for a cyclic time stamp, get the closest date to
11226 DAYNR.
11227 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11228 (cond
11229 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11230 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11231 daynr
11232 (+ daynr 1000)))
11233 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11234 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11235 (time-to-days (current-time))) (match-string 0 s)
11236 prefer show-all))
11237 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11239 (defun org-days-to-iso-week (days)
11240 "Return the iso week number."
11241 (require 'cal-iso)
11242 (car (calendar-iso-from-absolute days)))
11244 (defun org-small-year-to-year (year)
11245 "Convert 2-digit years into 4-digit years.
11246 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11247 The year 2000 cannot be abbreviated. Any year lager than 99
11248 is retrned unchanged."
11249 (if (< year 38)
11250 (setq year (+ 2000 year))
11251 (if (< year 100)
11252 (setq year (+ 1900 year))))
11253 year)
11255 (defun org-time-from-absolute (d)
11256 "Return the time corresponding to date D.
11257 D may be an absolute day number, or a calendar-type list (month day year)."
11258 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11259 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11261 (defun org-calendar-holiday ()
11262 "List of holidays, for Diary display in Org-mode."
11263 (require 'holidays)
11264 (let ((hl (funcall
11265 (if (fboundp 'calendar-check-holidays)
11266 'calendar-check-holidays 'check-calendar-holidays) date)))
11267 (if hl (mapconcat 'identity hl "; "))))
11269 (defun org-diary-sexp-entry (sexp entry date)
11270 "Process a SEXP diary ENTRY for DATE."
11271 (require 'diary-lib)
11272 (let ((result (if calendar-debug-sexp
11273 (let ((stack-trace-on-error t))
11274 (eval (car (read-from-string sexp))))
11275 (condition-case nil
11276 (eval (car (read-from-string sexp)))
11277 (error
11278 (beep)
11279 (message "Bad sexp at line %d in %s: %s"
11280 (org-current-line)
11281 (buffer-file-name) sexp)
11282 (sleep-for 2))))))
11283 (cond ((stringp result) result)
11284 ((and (consp result)
11285 (stringp (cdr result))) (cdr result))
11286 (result entry)
11287 (t nil))))
11289 (defun org-diary-to-ical-string (frombuf)
11290 "Get iCalendar entries from diary entries in buffer FROMBUF.
11291 This uses the icalendar.el library."
11292 (let* ((tmpdir (if (featurep 'xemacs)
11293 (temp-directory)
11294 temporary-file-directory))
11295 (tmpfile (make-temp-name
11296 (expand-file-name "orgics" tmpdir)))
11297 buf rtn b e)
11298 (save-excursion
11299 (set-buffer frombuf)
11300 (icalendar-export-region (point-min) (point-max) tmpfile)
11301 (setq buf (find-buffer-visiting tmpfile))
11302 (set-buffer buf)
11303 (goto-char (point-min))
11304 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11305 (setq b (match-beginning 0)))
11306 (goto-char (point-max))
11307 (if (re-search-backward "^END:VEVENT" nil t)
11308 (setq e (match-end 0)))
11309 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11310 (kill-buffer buf)
11311 (delete-file tmpfile)
11312 rtn))
11314 (defun org-closest-date (start current change prefer show-all)
11315 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11316 When PREFER is `past' return a date that is either CURRENT or past.
11317 When PREFER is `future', return a date that is either CURRENT or future.
11318 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11319 ;; Make the proper lists from the dates
11320 (catch 'exit
11321 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11322 dn dw sday cday n1 n2
11323 d m y y1 y2 date1 date2 nmonths nm ny m2)
11325 (setq start (org-date-to-gregorian start)
11326 current (org-date-to-gregorian
11327 (if show-all
11328 current
11329 (time-to-days (current-time))))
11330 sday (calendar-absolute-from-gregorian start)
11331 cday (calendar-absolute-from-gregorian current))
11333 (if (<= cday sday) (throw 'exit sday))
11335 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11336 (setq dn (string-to-number (match-string 1 change))
11337 dw (cdr (assoc (match-string 2 change) a1)))
11338 (error "Invalid change specifyer: %s" change))
11339 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11340 (cond
11341 ((eq dw 'day)
11342 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11343 n2 (+ n1 dn)))
11344 ((eq dw 'year)
11345 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11346 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11347 (setq date1 (list m d y1)
11348 n1 (calendar-absolute-from-gregorian date1)
11349 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11350 n2 (calendar-absolute-from-gregorian date2)))
11351 ((eq dw 'month)
11352 ;; approx number of month between the two dates
11353 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11354 ;; How often does dn fit in there?
11355 (setq d (nth 1 start) m (car start) y (nth 2 start)
11356 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11357 m (+ m nm)
11358 ny (floor (/ m 12))
11359 y (+ y ny)
11360 m (- m (* ny 12)))
11361 (while (> m 12) (setq m (- m 12) y (1+ y)))
11362 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11363 (setq m2 (+ m dn) y2 y)
11364 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11365 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11366 (while (<= n2 cday)
11367 (setq n1 n2 m m2 y y2)
11368 (setq m2 (+ m dn) y2 y)
11369 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11370 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11371 (if show-all
11372 (cond
11373 ((eq prefer 'past) n1)
11374 ((eq prefer 'future) (if (= cday n1) n1 n2))
11375 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11376 (cond
11377 ((eq prefer 'past) n1)
11378 ((eq prefer 'future) (if (= cday n1) n1 n2))
11379 (t (if (= cday n1) n1 n2)))))))
11381 (defun org-date-to-gregorian (date)
11382 "Turn any specification of DATE into a gregorian date for the calendar."
11383 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11384 ((and (listp date) (= (length date) 3)) date)
11385 ((stringp date)
11386 (setq date (org-parse-time-string date))
11387 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11388 ((listp date)
11389 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11391 (defun org-parse-time-string (s &optional nodefault)
11392 "Parse the standard Org-mode time string.
11393 This should be a lot faster than the normal `parse-time-string'.
11394 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11395 hour and minute fields will be nil if not given."
11396 (if (string-match org-ts-regexp0 s)
11397 (list 0
11398 (if (or (match-beginning 8) (not nodefault))
11399 (string-to-number (or (match-string 8 s) "0")))
11400 (if (or (match-beginning 7) (not nodefault))
11401 (string-to-number (or (match-string 7 s) "0")))
11402 (string-to-number (match-string 4 s))
11403 (string-to-number (match-string 3 s))
11404 (string-to-number (match-string 2 s))
11405 nil nil nil)
11406 (make-list 9 0)))
11408 (defun org-timestamp-up (&optional arg)
11409 "Increase the date item at the cursor by one.
11410 If the cursor is on the year, change the year. If it is on the month or
11411 the day, change that.
11412 With prefix ARG, change by that many units."
11413 (interactive "p")
11414 (org-timestamp-change (prefix-numeric-value arg)))
11416 (defun org-timestamp-down (&optional arg)
11417 "Decrease the date item at the cursor by one.
11418 If the cursor is on the year, change the year. If it is on the month or
11419 the day, change that.
11420 With prefix ARG, change by that many units."
11421 (interactive "p")
11422 (org-timestamp-change (- (prefix-numeric-value arg))))
11424 (defun org-timestamp-up-day (&optional arg)
11425 "Increase the date in the time stamp by one day.
11426 With prefix ARG, change that many days."
11427 (interactive "p")
11428 (if (and (not (org-at-timestamp-p t))
11429 (org-on-heading-p))
11430 (org-todo 'up)
11431 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11433 (defun org-timestamp-down-day (&optional arg)
11434 "Decrease the date in the time stamp by one day.
11435 With prefix ARG, change that many days."
11436 (interactive "p")
11437 (if (and (not (org-at-timestamp-p t))
11438 (org-on-heading-p))
11439 (org-todo 'down)
11440 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11442 (defun org-at-timestamp-p (&optional inactive-ok)
11443 "Determine if the cursor is in or at a timestamp."
11444 (interactive)
11445 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11446 (pos (point))
11447 (ans (or (looking-at tsr)
11448 (save-excursion
11449 (skip-chars-backward "^[<\n\r\t")
11450 (if (> (point) (point-min)) (backward-char 1))
11451 (and (looking-at tsr)
11452 (> (- (match-end 0) pos) -1))))))
11453 (and ans
11454 (boundp 'org-ts-what)
11455 (setq org-ts-what
11456 (cond
11457 ((= pos (match-beginning 0)) 'bracket)
11458 ((= pos (1- (match-end 0))) 'bracket)
11459 ((org-pos-in-match-range pos 2) 'year)
11460 ((org-pos-in-match-range pos 3) 'month)
11461 ((org-pos-in-match-range pos 7) 'hour)
11462 ((org-pos-in-match-range pos 8) 'minute)
11463 ((or (org-pos-in-match-range pos 4)
11464 (org-pos-in-match-range pos 5)) 'day)
11465 ((and (> pos (or (match-end 8) (match-end 5)))
11466 (< pos (match-end 0)))
11467 (- pos (or (match-end 8) (match-end 5))))
11468 (t 'day))))
11469 ans))
11471 (defun org-toggle-timestamp-type ()
11472 "Toggle the type (<active> or [inactive]) of a time stamp."
11473 (interactive)
11474 (when (org-at-timestamp-p t)
11475 (let ((beg (match-beginning 0)) (end (match-end 0))
11476 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11477 (save-excursion
11478 (goto-char beg)
11479 (while (re-search-forward "[][<>]" end t)
11480 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11481 t t)))
11482 (message "Timestamp is now %sactive"
11483 (if (equal (char-after beg) ?<) "" "in")))))
11485 (defun org-timestamp-change (n &optional what)
11486 "Change the date in the time stamp at point.
11487 The date will be changed by N times WHAT. WHAT can be `day', `month',
11488 `year', `minute', `second'. If WHAT is not given, the cursor position
11489 in the timestamp determines what will be changed."
11490 (let ((pos (point))
11491 with-hm inactive
11492 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11493 org-ts-what
11494 extra rem
11495 ts time time0)
11496 (if (not (org-at-timestamp-p t))
11497 (error "Not at a timestamp"))
11498 (if (and (not what) (eq org-ts-what 'bracket))
11499 (org-toggle-timestamp-type)
11500 (if (and (not what) (not (eq org-ts-what 'day))
11501 org-display-custom-times
11502 (get-text-property (point) 'display)
11503 (not (get-text-property (1- (point)) 'display)))
11504 (setq org-ts-what 'day))
11505 (setq org-ts-what (or what org-ts-what)
11506 inactive (= (char-after (match-beginning 0)) ?\[)
11507 ts (match-string 0))
11508 (replace-match "")
11509 (if (string-match
11510 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11512 (setq extra (match-string 1 ts)))
11513 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11514 (setq with-hm t))
11515 (setq time0 (org-parse-time-string ts))
11516 (when (and (eq org-ts-what 'minute)
11517 (eq current-prefix-arg nil))
11518 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11519 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11520 (setcar (cdr time0) (+ (nth 1 time0)
11521 (if (> n 0) (- rem) (- dm rem))))))
11522 (setq time
11523 (encode-time (or (car time0) 0)
11524 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11525 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11526 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11527 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11528 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11529 (nthcdr 6 time0)))
11530 (when (integerp org-ts-what)
11531 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11532 (if (eq what 'calendar)
11533 (let ((cal-date (org-get-date-from-calendar)))
11534 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11535 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11536 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11537 (setcar time0 (or (car time0) 0))
11538 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11539 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11540 (setq time (apply 'encode-time time0))))
11541 (setq org-last-changed-timestamp
11542 (org-insert-time-stamp time with-hm inactive nil nil extra))
11543 (org-clock-update-time-maybe)
11544 (goto-char pos)
11545 ;; Try to recenter the calendar window, if any
11546 (if (and org-calendar-follow-timestamp-change
11547 (get-buffer-window "*Calendar*" t)
11548 (memq org-ts-what '(day month year)))
11549 (org-recenter-calendar (time-to-days time))))))
11551 (defun org-modify-ts-extra (s pos n dm)
11552 "Change the different parts of the lead-time and repeat fields in timestamp."
11553 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11554 ng h m new rem)
11555 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11556 (cond
11557 ((or (org-pos-in-match-range pos 2)
11558 (org-pos-in-match-range pos 3))
11559 (setq m (string-to-number (match-string 3 s))
11560 h (string-to-number (match-string 2 s)))
11561 (if (org-pos-in-match-range pos 2)
11562 (setq h (+ h n))
11563 (setq n (* dm (org-no-warnings (signum n))))
11564 (when (not (= 0 (setq rem (% m dm))))
11565 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11566 (setq m (+ m n)))
11567 (if (< m 0) (setq m (+ m 60) h (1- h)))
11568 (if (> m 59) (setq m (- m 60) h (1+ h)))
11569 (setq h (min 24 (max 0 h)))
11570 (setq ng 1 new (format "-%02d:%02d" h m)))
11571 ((org-pos-in-match-range pos 6)
11572 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11573 ((org-pos-in-match-range pos 5)
11574 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11576 ((org-pos-in-match-range pos 9)
11577 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11578 ((org-pos-in-match-range pos 8)
11579 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11581 (when ng
11582 (setq s (concat
11583 (substring s 0 (match-beginning ng))
11585 (substring s (match-end ng))))))
11588 (defun org-recenter-calendar (date)
11589 "If the calendar is visible, recenter it to DATE."
11590 (let* ((win (selected-window))
11591 (cwin (get-buffer-window "*Calendar*" t))
11592 (calendar-move-hook nil))
11593 (when cwin
11594 (select-window cwin)
11595 (calendar-goto-date (if (listp date) date
11596 (calendar-gregorian-from-absolute date)))
11597 (select-window win))))
11599 (defun org-goto-calendar (&optional arg)
11600 "Go to the Emacs calendar at the current date.
11601 If there is a time stamp in the current line, go to that date.
11602 A prefix ARG can be used to force the current date."
11603 (interactive "P")
11604 (let ((tsr org-ts-regexp) diff
11605 (calendar-move-hook nil)
11606 (calendar-view-holidays-initially-flag nil)
11607 (view-calendar-holidays-initially nil)
11608 (calendar-view-diary-initially-flag nil)
11609 (view-diary-entries-initially nil))
11610 (if (or (org-at-timestamp-p)
11611 (save-excursion
11612 (beginning-of-line 1)
11613 (looking-at (concat ".*" tsr))))
11614 (let ((d1 (time-to-days (current-time)))
11615 (d2 (time-to-days
11616 (org-time-string-to-time (match-string 1)))))
11617 (setq diff (- d2 d1))))
11618 (calendar)
11619 (calendar-goto-today)
11620 (if (and diff (not arg)) (calendar-forward-day diff))))
11622 (defun org-get-date-from-calendar ()
11623 "Return a list (month day year) of date at point in calendar."
11624 (with-current-buffer "*Calendar*"
11625 (save-match-data
11626 (calendar-cursor-to-date))))
11628 (defun org-date-from-calendar ()
11629 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11630 If there is already a time stamp at the cursor position, update it."
11631 (interactive)
11632 (if (org-at-timestamp-p t)
11633 (org-timestamp-change 0 'calendar)
11634 (let ((cal-date (org-get-date-from-calendar)))
11635 (org-insert-time-stamp
11636 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11638 (defun org-minutes-to-hh:mm-string (m)
11639 "Compute H:MM from a number of minutes."
11640 (let ((h (/ m 60)))
11641 (setq m (- m (* 60 h)))
11642 (format org-time-clocksum-format h m)))
11644 (defun org-hh:mm-string-to-minutes (s)
11645 "Convert a string H:MM to a number of minutes."
11646 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11647 (+ (* (string-to-number (match-string 1 s)) 60)
11648 (string-to-number (match-string 2 s)))
11651 ;;;; Agenda files
11653 ;;;###autoload
11654 (defun org-iswitchb (&optional arg)
11655 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11656 With a prefix argument, restrict available to files.
11657 With two prefix arguments, restrict available buffers to agenda files.
11659 Due to some yet unresolved reason, the global function
11660 `iswitchb-mode' needs to be active for this function to work."
11661 (interactive "P")
11662 (require 'iswitchb)
11663 (let ((enabled iswitchb-mode) blist)
11664 (or enabled (iswitchb-mode 1))
11665 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11666 ((equal arg '(16)) (org-buffer-list 'agenda))
11667 (t (org-buffer-list))))
11668 (unwind-protect
11669 (let ((iswitchb-make-buflist-hook
11670 (lambda ()
11671 (setq iswitchb-temp-buflist
11672 (mapcar 'buffer-name blist)))))
11673 (switch-to-buffer
11674 (iswitchb-read-buffer
11675 "Switch-to: " nil t))
11676 (or enabled (iswitchb-mode -1))))))
11678 (defun org-buffer-list (&optional predicate exclude-tmp)
11679 "Return a list of Org buffers.
11680 PREDICATE can be `export', `files' or `agenda'.
11682 export restrict the list to Export buffers.
11683 files restrict the list to buffers visiting Org files.
11684 agenda restrict the list to buffers visiting agenda files.
11686 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11687 (let* ((bfn nil)
11688 (agenda-files (and (eq predicate 'agenda)
11689 (mapcar 'file-truename (org-agenda-files t))))
11690 (filter
11691 (cond
11692 ((eq predicate 'files)
11693 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11694 ((eq predicate 'export)
11695 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11696 ((eq predicate 'agenda)
11697 (lambda (b)
11698 (with-current-buffer b
11699 (and (eq major-mode 'org-mode)
11700 (setq bfn (buffer-file-name b))
11701 (member (file-truename bfn) agenda-files)))))
11702 (t (lambda (b) (with-current-buffer b
11703 (or (eq major-mode 'org-mode)
11704 (string-match "\*Org .*Export"
11705 (buffer-name b)))))))))
11706 (delq nil
11707 (mapcar
11708 (lambda(b)
11709 (if (and (funcall filter b)
11710 (or (not exclude-tmp)
11711 (not (string-match "tmp" (buffer-name b)))))
11713 nil))
11714 (buffer-list)))))
11716 (defun org-agenda-files (&optional unrestricted archives)
11717 "Get the list of agenda files.
11718 Optional UNRESTRICTED means return the full list even if a restriction
11719 is currently in place.
11720 When ARCHIVES is t, include all archive files hat are really being
11721 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11722 `org-agenda-archives-mode' is t."
11723 (let ((files
11724 (cond
11725 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11726 ((stringp org-agenda-files) (org-read-agenda-file-list))
11727 ((listp org-agenda-files) org-agenda-files)
11728 (t (error "Invalid value of `org-agenda-files'")))))
11729 (setq files (apply 'append
11730 (mapcar (lambda (f)
11731 (if (file-directory-p f)
11732 (directory-files
11733 f t org-agenda-file-regexp)
11734 (list f)))
11735 files)))
11736 (when org-agenda-skip-unavailable-files
11737 (setq files (delq nil
11738 (mapcar (function
11739 (lambda (file)
11740 (and (file-readable-p file) file)))
11741 files))))
11742 (when (or (eq archives t)
11743 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11744 (setq files (org-add-archive-files files)))
11745 files))
11747 (defun org-edit-agenda-file-list ()
11748 "Edit the list of agenda files.
11749 Depending on setup, this either uses customize to edit the variable
11750 `org-agenda-files', or it visits the file that is holding the list. In the
11751 latter case, the buffer is set up in a way that saving it automatically kills
11752 the buffer and restores the previous window configuration."
11753 (interactive)
11754 (if (stringp org-agenda-files)
11755 (let ((cw (current-window-configuration)))
11756 (find-file org-agenda-files)
11757 (org-set-local 'org-window-configuration cw)
11758 (org-add-hook 'after-save-hook
11759 (lambda ()
11760 (set-window-configuration
11761 (prog1 org-window-configuration
11762 (kill-buffer (current-buffer))))
11763 (org-install-agenda-files-menu)
11764 (message "New agenda file list installed"))
11765 nil 'local)
11766 (message "%s" (substitute-command-keys
11767 "Edit list and finish with \\[save-buffer]")))
11768 (customize-variable 'org-agenda-files)))
11770 (defun org-store-new-agenda-file-list (list)
11771 "Set new value for the agenda file list and save it correcly."
11772 (if (stringp org-agenda-files)
11773 (let ((f org-agenda-files) b)
11774 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11775 (with-temp-file f
11776 (insert (mapconcat 'identity list "\n") "\n")))
11777 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11778 (setq org-agenda-files list)
11779 (customize-save-variable 'org-agenda-files org-agenda-files))))
11781 (defun org-read-agenda-file-list ()
11782 "Read the list of agenda files from a file."
11783 (when (file-directory-p org-agenda-files)
11784 (error "`org-agenda-files' cannot be a single directory"))
11785 (when (stringp org-agenda-files)
11786 (with-temp-buffer
11787 (insert-file-contents org-agenda-files)
11788 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11791 ;;;###autoload
11792 (defun org-cycle-agenda-files ()
11793 "Cycle through the files in `org-agenda-files'.
11794 If the current buffer visits an agenda file, find the next one in the list.
11795 If the current buffer does not, find the first agenda file."
11796 (interactive)
11797 (let* ((fs (org-agenda-files t))
11798 (files (append fs (list (car fs))))
11799 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11800 file)
11801 (unless files (error "No agenda files"))
11802 (catch 'exit
11803 (while (setq file (pop files))
11804 (if (equal (file-truename file) tcf)
11805 (when (car files)
11806 (find-file (car files))
11807 (throw 'exit t))))
11808 (find-file (car fs)))
11809 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11811 (defun org-agenda-file-to-front (&optional to-end)
11812 "Move/add the current file to the top of the agenda file list.
11813 If the file is not present in the list, it is added to the front. If it is
11814 present, it is moved there. With optional argument TO-END, add/move to the
11815 end of the list."
11816 (interactive "P")
11817 (let ((org-agenda-skip-unavailable-files nil)
11818 (file-alist (mapcar (lambda (x)
11819 (cons (file-truename x) x))
11820 (org-agenda-files t)))
11821 (ctf (file-truename buffer-file-name))
11822 x had)
11823 (setq x (assoc ctf file-alist) had x)
11825 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11826 (if to-end
11827 (setq file-alist (append (delq x file-alist) (list x)))
11828 (setq file-alist (cons x (delq x file-alist))))
11829 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11830 (org-install-agenda-files-menu)
11831 (message "File %s to %s of agenda file list"
11832 (if had "moved" "added") (if to-end "end" "front"))))
11834 (defun org-remove-file (&optional file)
11835 "Remove current file from the list of files in variable `org-agenda-files'.
11836 These are the files which are being checked for agenda entries.
11837 Optional argument FILE means, use this file instead of the current."
11838 (interactive)
11839 (let* ((org-agenda-skip-unavailable-files nil)
11840 (file (or file buffer-file-name))
11841 (true-file (file-truename file))
11842 (afile (abbreviate-file-name file))
11843 (files (delq nil (mapcar
11844 (lambda (x)
11845 (if (equal true-file
11846 (file-truename x))
11847 nil x))
11848 (org-agenda-files t)))))
11849 (if (not (= (length files) (length (org-agenda-files t))))
11850 (progn
11851 (org-store-new-agenda-file-list files)
11852 (org-install-agenda-files-menu)
11853 (message "Removed file: %s" afile))
11854 (message "File was not in list: %s (not removed)" afile))))
11856 (defun org-file-menu-entry (file)
11857 (vector file (list 'find-file file) t))
11859 (defun org-check-agenda-file (file)
11860 "Make sure FILE exists. If not, ask user what to do."
11861 (when (not (file-exists-p file))
11862 (message "non-existent file %s. [R]emove from list or [A]bort?"
11863 (abbreviate-file-name file))
11864 (let ((r (downcase (read-char-exclusive))))
11865 (cond
11866 ((equal r ?r)
11867 (org-remove-file file)
11868 (throw 'nextfile t))
11869 (t (error "Abort"))))))
11871 (defun org-get-agenda-file-buffer (file)
11872 "Get a buffer visiting FILE. If the buffer needs to be created, add
11873 it to the list of buffers which might be released later."
11874 (let ((buf (org-find-base-buffer-visiting file)))
11875 (if buf
11876 buf ; just return it
11877 ;; Make a new buffer and remember it
11878 (setq buf (find-file-noselect file))
11879 (if buf (push buf org-agenda-new-buffers))
11880 buf)))
11882 (defun org-release-buffers (blist)
11883 "Release all buffers in list, asking the user for confirmation when needed.
11884 When a buffer is unmodified, it is just killed. When modified, it is saved
11885 \(if the user agrees) and then killed."
11886 (let (buf file)
11887 (while (setq buf (pop blist))
11888 (setq file (buffer-file-name buf))
11889 (when (and (buffer-modified-p buf)
11890 file
11891 (y-or-n-p (format "Save file %s? " file)))
11892 (with-current-buffer buf (save-buffer)))
11893 (kill-buffer buf))))
11895 (defun org-prepare-agenda-buffers (files)
11896 "Create buffers for all agenda files, protect archived trees and comments."
11897 (interactive)
11898 (let ((pa '(:org-archived t))
11899 (pc '(:org-comment t))
11900 (pall '(:org-archived t :org-comment t))
11901 (inhibit-read-only t)
11902 (rea (concat ":" org-archive-tag ":"))
11903 bmp file re)
11904 (save-excursion
11905 (save-restriction
11906 (while (setq file (pop files))
11907 (if (bufferp file)
11908 (set-buffer file)
11909 (org-check-agenda-file file)
11910 (set-buffer (org-get-agenda-file-buffer file)))
11911 (widen)
11912 (setq bmp (buffer-modified-p))
11913 (org-refresh-category-properties)
11914 (setq org-todo-keywords-for-agenda
11915 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11916 (setq org-done-keywords-for-agenda
11917 (append org-done-keywords-for-agenda org-done-keywords))
11918 (setq org-todo-keyword-alist-for-agenda
11919 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11920 (setq org-tag-alist-for-agenda
11921 (append org-tag-alist-for-agenda org-tag-alist))
11923 (save-excursion
11924 (remove-text-properties (point-min) (point-max) pall)
11925 (when org-agenda-skip-archived-trees
11926 (goto-char (point-min))
11927 (while (re-search-forward rea nil t)
11928 (if (org-on-heading-p t)
11929 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11930 (goto-char (point-min))
11931 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11932 (while (re-search-forward re nil t)
11933 (add-text-properties
11934 (match-beginning 0) (org-end-of-subtree t) pc)))
11935 (set-buffer-modified-p bmp))))
11936 (setq org-todo-keyword-alist-for-agenda
11937 (org-uniquify org-todo-keyword-alist-for-agenda)
11938 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11940 ;;;; Embedded LaTeX
11942 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11943 "Keymap for the minor `org-cdlatex-mode'.")
11945 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11946 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11947 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11948 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11949 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11951 (defvar org-cdlatex-texmathp-advice-is-done nil
11952 "Flag remembering if we have applied the advice to texmathp already.")
11954 (define-minor-mode org-cdlatex-mode
11955 "Toggle the minor `org-cdlatex-mode'.
11956 This mode supports entering LaTeX environment and math in LaTeX fragments
11957 in Org-mode.
11958 \\{org-cdlatex-mode-map}"
11959 nil " OCDL" nil
11960 (when org-cdlatex-mode (require 'cdlatex))
11961 (unless org-cdlatex-texmathp-advice-is-done
11962 (setq org-cdlatex-texmathp-advice-is-done t)
11963 (defadvice texmathp (around org-math-always-on activate)
11964 "Always return t in org-mode buffers.
11965 This is because we want to insert math symbols without dollars even outside
11966 the LaTeX math segments. If Orgmode thinks that point is actually inside
11967 en embedded LaTeX fragement, let texmathp do its job.
11968 \\[org-cdlatex-mode-map]"
11969 (interactive)
11970 (let (p)
11971 (cond
11972 ((not (org-mode-p)) ad-do-it)
11973 ((eq this-command 'cdlatex-math-symbol)
11974 (setq ad-return-value t
11975 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11977 (let ((p (org-inside-LaTeX-fragment-p)))
11978 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11979 (setq ad-return-value t
11980 texmathp-why '("Org-mode embedded math" . 0))
11981 (if p ad-do-it)))))))))
11983 (defun turn-on-org-cdlatex ()
11984 "Unconditionally turn on `org-cdlatex-mode'."
11985 (org-cdlatex-mode 1))
11987 (defun org-inside-LaTeX-fragment-p ()
11988 "Test if point is inside a LaTeX fragment.
11989 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11990 sequence appearing also before point.
11991 Even though the matchers for math are configurable, this function assumes
11992 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11993 delimiters are skipped when they have been removed by customization.
11994 The return value is nil, or a cons cell with the delimiter and
11995 and the position of this delimiter.
11997 This function does a reasonably good job, but can locally be fooled by
11998 for example currency specifications. For example it will assume being in
11999 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12000 fragments that are properly closed, but during editing, we have to live
12001 with the uncertainty caused by missing closing delimiters. This function
12002 looks only before point, not after."
12003 (catch 'exit
12004 (let ((pos (point))
12005 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12006 (lim (progn
12007 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12008 (point)))
12009 dd-on str (start 0) m re)
12010 (goto-char pos)
12011 (when dodollar
12012 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12013 re (nth 1 (assoc "$" org-latex-regexps)))
12014 (while (string-match re str start)
12015 (cond
12016 ((= (match-end 0) (length str))
12017 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12018 ((= (match-end 0) (- (length str) 5))
12019 (throw 'exit nil))
12020 (t (setq start (match-end 0))))))
12021 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12022 (goto-char pos)
12023 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12024 (and (match-beginning 2) (throw 'exit nil))
12025 ;; count $$
12026 (while (re-search-backward "\\$\\$" lim t)
12027 (setq dd-on (not dd-on)))
12028 (goto-char pos)
12029 (if dd-on (cons "$$" m))))))
12032 (defun org-try-cdlatex-tab ()
12033 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12034 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12035 - inside a LaTeX fragment, or
12036 - after the first word in a line, where an abbreviation expansion could
12037 insert a LaTeX environment."
12038 (when org-cdlatex-mode
12039 (cond
12040 ((save-excursion
12041 (skip-chars-backward "a-zA-Z0-9*")
12042 (skip-chars-backward " \t")
12043 (bolp))
12044 (cdlatex-tab) t)
12045 ((org-inside-LaTeX-fragment-p)
12046 (cdlatex-tab) t)
12047 (t nil))))
12049 (defun org-cdlatex-underscore-caret (&optional arg)
12050 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12051 Revert to the normal definition outside of these fragments."
12052 (interactive "P")
12053 (if (org-inside-LaTeX-fragment-p)
12054 (call-interactively 'cdlatex-sub-superscript)
12055 (let (org-cdlatex-mode)
12056 (call-interactively (key-binding (vector last-input-event))))))
12058 (defun org-cdlatex-math-modify (&optional arg)
12059 "Execute `cdlatex-math-modify' in LaTeX fragments.
12060 Revert to the normal definition outside of these fragments."
12061 (interactive "P")
12062 (if (org-inside-LaTeX-fragment-p)
12063 (call-interactively 'cdlatex-math-modify)
12064 (let (org-cdlatex-mode)
12065 (call-interactively (key-binding (vector last-input-event))))))
12067 (defvar org-latex-fragment-image-overlays nil
12068 "List of overlays carrying the images of latex fragments.")
12069 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12071 (defun org-remove-latex-fragment-image-overlays ()
12072 "Remove all overlays with LaTeX fragment images in current buffer."
12073 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12074 (setq org-latex-fragment-image-overlays nil))
12076 (defun org-preview-latex-fragment (&optional subtree)
12077 "Preview the LaTeX fragment at point, or all locally or globally.
12078 If the cursor is in a LaTeX fragment, create the image and overlay
12079 it over the source code. If there is no fragment at point, display
12080 all fragments in the current text, from one headline to the next. With
12081 prefix SUBTREE, display all fragments in the current subtree. With a
12082 double prefix `C-u C-u', or when the cursor is before the first headline,
12083 display all fragments in the buffer.
12084 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12085 (interactive "P")
12086 (org-remove-latex-fragment-image-overlays)
12087 (save-excursion
12088 (save-restriction
12089 (let (beg end at msg)
12090 (cond
12091 ((or (equal subtree '(16))
12092 (not (save-excursion
12093 (re-search-backward (concat "^" outline-regexp) nil t))))
12094 (setq beg (point-min) end (point-max)
12095 msg "Creating images for buffer...%s"))
12096 ((equal subtree '(4))
12097 (org-back-to-heading)
12098 (setq beg (point) end (org-end-of-subtree t)
12099 msg "Creating images for subtree...%s"))
12101 (if (setq at (org-inside-LaTeX-fragment-p))
12102 (goto-char (max (point-min) (- (cdr at) 2)))
12103 (org-back-to-heading))
12104 (setq beg (point) end (progn (outline-next-heading) (point))
12105 msg (if at "Creating image...%s"
12106 "Creating images for entry...%s"))))
12107 (message msg "")
12108 (narrow-to-region beg end)
12109 (goto-char beg)
12110 (org-format-latex
12111 (concat "ltxpng/" (file-name-sans-extension
12112 (file-name-nondirectory
12113 buffer-file-name)))
12114 default-directory 'overlays msg at 'forbuffer)
12115 (message msg "done. Use `C-c C-c' to remove images.")))))
12117 (defvar org-latex-regexps
12118 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12119 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12120 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12121 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12122 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12123 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12124 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12125 "Regular expressions for matching embedded LaTeX.")
12127 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12128 "Replace LaTeX fragments with links to an image, and produce images."
12129 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12130 (let* ((prefixnodir (file-name-nondirectory prefix))
12131 (absprefix (expand-file-name prefix dir))
12132 (todir (file-name-directory absprefix))
12133 (opt org-format-latex-options)
12134 (matchers (plist-get opt :matchers))
12135 (re-list org-latex-regexps)
12136 (cnt 0) txt link beg end re e checkdir
12137 m n block linkfile movefile ov)
12138 ;; Check if there are old images files with this prefix, and remove them
12139 (when (file-directory-p todir)
12140 (mapc 'delete-file
12141 (directory-files
12142 todir 'full
12143 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12144 ;; Check the different regular expressions
12145 (while (setq e (pop re-list))
12146 (setq m (car e) re (nth 1 e) n (nth 2 e)
12147 block (if (nth 3 e) "\n\n" ""))
12148 (when (member m matchers)
12149 (goto-char (point-min))
12150 (while (re-search-forward re nil t)
12151 (when (or (not at) (equal (cdr at) (match-beginning n)))
12152 (setq txt (match-string n)
12153 beg (match-beginning n) end (match-end n)
12154 cnt (1+ cnt)
12155 linkfile (format "%s_%04d.png" prefix cnt)
12156 movefile (format "%s_%04d.png" absprefix cnt)
12157 link (concat block "[[file:" linkfile "]]" block))
12158 (if msg (message msg cnt))
12159 (goto-char beg)
12160 (unless checkdir ; make sure the directory exists
12161 (setq checkdir t)
12162 (or (file-directory-p todir) (make-directory todir)))
12163 (org-create-formula-image
12164 txt movefile opt forbuffer)
12165 (if overlays
12166 (progn
12167 (setq ov (org-make-overlay beg end))
12168 (if (featurep 'xemacs)
12169 (progn
12170 (org-overlay-put ov 'invisible t)
12171 (org-overlay-put
12172 ov 'end-glyph
12173 (make-glyph (vector 'png :file movefile))))
12174 (org-overlay-put
12175 ov 'display
12176 (list 'image :type 'png :file movefile :ascent 'center)))
12177 (push ov org-latex-fragment-image-overlays)
12178 (goto-char end))
12179 (delete-region beg end)
12180 (insert link))))))))
12182 ;; This function borrows from Ganesh Swami's latex2png.el
12183 (defun org-create-formula-image (string tofile options buffer)
12184 (let* ((tmpdir (if (featurep 'xemacs)
12185 (temp-directory)
12186 temporary-file-directory))
12187 (texfilebase (make-temp-name
12188 (expand-file-name "orgtex" tmpdir)))
12189 (texfile (concat texfilebase ".tex"))
12190 (dvifile (concat texfilebase ".dvi"))
12191 (pngfile (concat texfilebase ".png"))
12192 (fnh (if (featurep 'xemacs)
12193 (font-height (get-face-font 'default))
12194 (face-attribute 'default :height nil)))
12195 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12196 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12197 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12198 "Black"))
12199 (bg (or (plist-get options (if buffer :background :html-background))
12200 "Transparent")))
12201 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12202 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12203 (with-temp-file texfile
12204 (insert org-format-latex-header
12205 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12206 (let ((dir default-directory))
12207 (condition-case nil
12208 (progn
12209 (cd tmpdir)
12210 (call-process "latex" nil nil nil texfile))
12211 (error nil))
12212 (cd dir))
12213 (if (not (file-exists-p dvifile))
12214 (progn (message "Failed to create dvi file from %s" texfile) nil)
12215 (condition-case nil
12216 (call-process "dvipng" nil nil nil
12217 "-E" "-fg" fg "-bg" bg
12218 "-D" dpi
12219 ;;"-x" scale "-y" scale
12220 "-T" "tight"
12221 "-o" pngfile
12222 dvifile)
12223 (error nil))
12224 (if (not (file-exists-p pngfile))
12225 (progn (message "Failed to create png file from %s" texfile) nil)
12226 ;; Use the requested file name and clean up
12227 (copy-file pngfile tofile 'replace)
12228 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12229 (delete-file (concat texfilebase e)))
12230 pngfile))))
12232 (defun org-dvipng-color (attr)
12233 "Return an rgb color specification for dvipng."
12234 (apply 'format "rgb %s %s %s"
12235 (mapcar 'org-normalize-color
12236 (color-values (face-attribute 'default attr nil)))))
12238 (defun org-normalize-color (value)
12239 "Return string to be used as color value for an RGB component."
12240 (format "%g" (/ value 65535.0)))
12243 ;;;; Key bindings
12245 ;; Make `C-c C-x' a prefix key
12246 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12248 ;; TAB key with modifiers
12249 (org-defkey org-mode-map "\C-i" 'org-cycle)
12250 (org-defkey org-mode-map [(tab)] 'org-cycle)
12251 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12252 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12253 (org-defkey org-mode-map "\M-\t" 'org-complete)
12254 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12255 ;; The following line is necessary under Suse GNU/Linux
12256 (unless (featurep 'xemacs)
12257 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12258 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12259 (define-key org-mode-map [backtab] 'org-shifttab)
12261 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12262 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12263 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12265 ;; Cursor keys with modifiers
12266 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12267 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12268 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12269 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12271 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12272 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12273 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12274 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12276 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12277 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12278 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12279 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12281 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12282 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12284 ;;; Extra keys for tty access.
12285 ;; We only set them when really needed because otherwise the
12286 ;; menus don't show the simple keys
12288 (when (or org-use-extra-keys
12289 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12290 (not window-system))
12291 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12292 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12293 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12294 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12295 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12296 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12297 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12298 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12299 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12300 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12301 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12302 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12303 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12304 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12305 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12306 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12307 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12308 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12309 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12310 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12311 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12312 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12314 ;; All the other keys
12316 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12317 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12318 (if (boundp 'narrow-map)
12319 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12320 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12321 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12322 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12323 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12324 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12325 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12326 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12327 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12328 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12329 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12330 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12331 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12332 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12333 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12334 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12335 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12336 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12337 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12338 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12339 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12340 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12341 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12342 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12343 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12344 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12345 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12346 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12347 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12348 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12349 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12350 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12351 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12352 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12353 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12354 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12355 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12356 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12357 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12358 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12359 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12360 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12361 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12362 (org-defkey org-mode-map "\C-c^" 'org-sort)
12363 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12364 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12365 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12366 (org-defkey org-mode-map "\C-m" 'org-return)
12367 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12368 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12369 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12370 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12371 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12372 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12373 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12374 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12375 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12376 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12377 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12378 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12379 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12380 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12381 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12382 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12384 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12385 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12386 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12387 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12389 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12390 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12391 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12392 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12393 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12394 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12395 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12396 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12397 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12398 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12399 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12400 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12402 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12404 (when (featurep 'xemacs)
12405 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12407 (defvar org-table-auto-blank-field) ; defined in org-table.el
12408 (defun org-self-insert-command (N)
12409 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12410 If the cursor is in a table looking at whitespace, the whitespace is
12411 overwritten, and the table is not marked as requiring realignment."
12412 (interactive "p")
12413 (if (and (org-table-p)
12414 (progn
12415 ;; check if we blank the field, and if that triggers align
12416 (and (featurep 'org-table) org-table-auto-blank-field
12417 (member last-command
12418 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12419 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12420 ;; got extra space, this field does not determine column width
12421 (let (org-table-may-need-update) (org-table-blank-field))
12422 ;; no extra space, this field may determine column width
12423 (org-table-blank-field)))
12425 (eq N 1)
12426 (looking-at "[^|\n]* |"))
12427 (let (org-table-may-need-update)
12428 (goto-char (1- (match-end 0)))
12429 (delete-backward-char 1)
12430 (goto-char (match-beginning 0))
12431 (self-insert-command N))
12432 (setq org-table-may-need-update t)
12433 (self-insert-command N)
12434 (org-fix-tags-on-the-fly)))
12436 (defun org-fix-tags-on-the-fly ()
12437 (when (and (equal (char-after (point-at-bol)) ?*)
12438 (org-on-heading-p))
12439 (org-align-tags-here org-tags-column)))
12441 (defun org-delete-backward-char (N)
12442 "Like `delete-backward-char', insert whitespace at field end in tables.
12443 When deleting backwards, in tables this function will insert whitespace in
12444 front of the next \"|\" separator, to keep the table aligned. The table will
12445 still be marked for re-alignment if the field did fill the entire column,
12446 because, in this case the deletion might narrow the column."
12447 (interactive "p")
12448 (if (and (org-table-p)
12449 (eq N 1)
12450 (string-match "|" (buffer-substring (point-at-bol) (point)))
12451 (looking-at ".*?|"))
12452 (let ((pos (point))
12453 (noalign (looking-at "[^|\n\r]* |"))
12454 (c org-table-may-need-update))
12455 (backward-delete-char N)
12456 (skip-chars-forward "^|")
12457 (insert " ")
12458 (goto-char (1- pos))
12459 ;; noalign: if there were two spaces at the end, this field
12460 ;; does not determine the width of the column.
12461 (if noalign (setq org-table-may-need-update c)))
12462 (backward-delete-char N)
12463 (org-fix-tags-on-the-fly)))
12465 (defun org-delete-char (N)
12466 "Like `delete-char', but insert whitespace at field end in tables.
12467 When deleting characters, in tables this function will insert whitespace in
12468 front of the next \"|\" separator, to keep the table aligned. The table will
12469 still be marked for re-alignment if the field did fill the entire column,
12470 because, in this case the deletion might narrow the column."
12471 (interactive "p")
12472 (if (and (org-table-p)
12473 (not (bolp))
12474 (not (= (char-after) ?|))
12475 (eq N 1))
12476 (if (looking-at ".*?|")
12477 (let ((pos (point))
12478 (noalign (looking-at "[^|\n\r]* |"))
12479 (c org-table-may-need-update))
12480 (replace-match (concat
12481 (substring (match-string 0) 1 -1)
12482 " |"))
12483 (goto-char pos)
12484 ;; noalign: if there were two spaces at the end, this field
12485 ;; does not determine the width of the column.
12486 (if noalign (setq org-table-may-need-update c)))
12487 (delete-char N))
12488 (delete-char N)
12489 (org-fix-tags-on-the-fly)))
12491 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12492 (put 'org-self-insert-command 'delete-selection t)
12493 (put 'orgtbl-self-insert-command 'delete-selection t)
12494 (put 'org-delete-char 'delete-selection 'supersede)
12495 (put 'org-delete-backward-char 'delete-selection 'supersede)
12497 ;; Make `flyspell-mode' delay after some commands
12498 (put 'org-self-insert-command 'flyspell-delayed t)
12499 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12500 (put 'org-delete-char 'flyspell-delayed t)
12501 (put 'org-delete-backward-char 'flyspell-delayed t)
12503 ;; Make pabbrev-mode expand after org-mode commands
12504 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12505 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12507 ;; How to do this: Measure non-white length of current string
12508 ;; If equal to column width, we should realign.
12510 (defun org-remap (map &rest commands)
12511 "In MAP, remap the functions given in COMMANDS.
12512 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12513 (let (new old)
12514 (while commands
12515 (setq old (pop commands) new (pop commands))
12516 (if (fboundp 'command-remapping)
12517 (org-defkey map (vector 'remap old) new)
12518 (substitute-key-definition old new map global-map)))))
12520 (when (eq org-enable-table-editor 'optimized)
12521 ;; If the user wants maximum table support, we need to hijack
12522 ;; some standard editing functions
12523 (org-remap org-mode-map
12524 'self-insert-command 'org-self-insert-command
12525 'delete-char 'org-delete-char
12526 'delete-backward-char 'org-delete-backward-char)
12527 (org-defkey org-mode-map "|" 'org-force-self-insert))
12529 (defun org-shiftcursor-error ()
12530 "Throw an error because Shift-Cursor command was applied in wrong context."
12531 (error "This command is active in special context like tables, headlines or timestamps"))
12533 (defun org-shifttab (&optional arg)
12534 "Global visibility cycling or move to previous table field.
12535 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12536 on context.
12537 See the individual commands for more information."
12538 (interactive "P")
12539 (cond
12540 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12541 ((integerp arg)
12542 (message "Content view to level: %d" arg)
12543 (org-content (prefix-numeric-value arg))
12544 (setq org-cycle-global-status 'overview))
12545 (t (call-interactively 'org-global-cycle))))
12547 (defun org-shiftmetaleft ()
12548 "Promote subtree or delete table column.
12549 Calls `org-promote-subtree', `org-outdent-item',
12550 or `org-table-delete-column', depending on context.
12551 See the individual commands for more information."
12552 (interactive)
12553 (cond
12554 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12555 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12556 ((org-at-item-p) (call-interactively 'org-outdent-item))
12557 (t (org-shiftcursor-error))))
12559 (defun org-shiftmetaright ()
12560 "Demote subtree or insert table column.
12561 Calls `org-demote-subtree', `org-indent-item',
12562 or `org-table-insert-column', depending on context.
12563 See the individual commands for more information."
12564 (interactive)
12565 (cond
12566 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12567 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12568 ((org-at-item-p) (call-interactively 'org-indent-item))
12569 (t (org-shiftcursor-error))))
12571 (defun org-shiftmetaup (&optional arg)
12572 "Move subtree up or kill table row.
12573 Calls `org-move-subtree-up' or `org-table-kill-row' or
12574 `org-move-item-up' depending on context. See the individual commands
12575 for more information."
12576 (interactive "P")
12577 (cond
12578 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12579 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12580 ((org-at-item-p) (call-interactively 'org-move-item-up))
12581 (t (org-shiftcursor-error))))
12582 (defun org-shiftmetadown (&optional arg)
12583 "Move subtree down or insert table row.
12584 Calls `org-move-subtree-down' or `org-table-insert-row' or
12585 `org-move-item-down', depending on context. See the individual
12586 commands for more information."
12587 (interactive "P")
12588 (cond
12589 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12590 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12591 ((org-at-item-p) (call-interactively 'org-move-item-down))
12592 (t (org-shiftcursor-error))))
12594 (defun org-metaleft (&optional arg)
12595 "Promote heading or move table column to left.
12596 Calls `org-do-promote' or `org-table-move-column', depending on context.
12597 With no specific context, calls the Emacs default `backward-word'.
12598 See the individual commands for more information."
12599 (interactive "P")
12600 (cond
12601 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12602 ((or (org-on-heading-p) (org-region-active-p))
12603 (call-interactively 'org-do-promote))
12604 ((org-at-item-p) (call-interactively 'org-outdent-item))
12605 (t (call-interactively 'backward-word))))
12607 (defun org-metaright (&optional arg)
12608 "Demote subtree or move table column to right.
12609 Calls `org-do-demote' or `org-table-move-column', depending on context.
12610 With no specific context, calls the Emacs default `forward-word'.
12611 See the individual commands for more information."
12612 (interactive "P")
12613 (cond
12614 ((org-at-table-p) (call-interactively 'org-table-move-column))
12615 ((or (org-on-heading-p) (org-region-active-p))
12616 (call-interactively 'org-do-demote))
12617 ((org-at-item-p) (call-interactively 'org-indent-item))
12618 (t (call-interactively 'forward-word))))
12620 (defun org-metaup (&optional arg)
12621 "Move subtree up or move table row up.
12622 Calls `org-move-subtree-up' or `org-table-move-row' or
12623 `org-move-item-up', depending on context. See the individual commands
12624 for more information."
12625 (interactive "P")
12626 (cond
12627 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12628 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12629 ((org-at-item-p) (call-interactively 'org-move-item-up))
12630 (t (transpose-lines 1) (beginning-of-line -1))))
12632 (defun org-metadown (&optional arg)
12633 "Move subtree down or move table row down.
12634 Calls `org-move-subtree-down' or `org-table-move-row' or
12635 `org-move-item-down', depending on context. See the individual
12636 commands for more information."
12637 (interactive "P")
12638 (cond
12639 ((org-at-table-p) (call-interactively 'org-table-move-row))
12640 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12641 ((org-at-item-p) (call-interactively 'org-move-item-down))
12642 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12644 (defun org-shiftup (&optional arg)
12645 "Increase item in timestamp or increase priority of current headline.
12646 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12647 depending on context. See the individual commands for more information."
12648 (interactive "P")
12649 (cond
12650 ((org-at-timestamp-p t)
12651 (call-interactively (if org-edit-timestamp-down-means-later
12652 'org-timestamp-down 'org-timestamp-up)))
12653 ((org-on-heading-p) (call-interactively 'org-priority-up))
12654 ((org-at-item-p) (call-interactively 'org-previous-item))
12655 ((org-clocktable-try-shift 'up arg))
12656 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12658 (defun org-shiftdown (&optional arg)
12659 "Decrease item in timestamp or decrease priority of current headline.
12660 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12661 depending on context. See the individual commands for more information."
12662 (interactive "P")
12663 (cond
12664 ((org-at-timestamp-p t)
12665 (call-interactively (if org-edit-timestamp-down-means-later
12666 'org-timestamp-up 'org-timestamp-down)))
12667 ((org-on-heading-p) (call-interactively 'org-priority-down))
12668 ((org-clocktable-try-shift 'down arg))
12669 (t (call-interactively 'org-next-item))))
12671 (defun org-shiftright (&optional arg)
12672 "Next TODO keyword or timestamp one day later, depending on context."
12673 (interactive "P")
12674 (cond
12675 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12676 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12677 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12678 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12679 ((org-clocktable-try-shift 'right arg))
12680 (t (org-shiftcursor-error))))
12682 (defun org-shiftleft (&optional arg)
12683 "Previous TODO keyword or timestamp one day earlier, depending on context."
12684 (interactive "P")
12685 (cond
12686 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12687 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12688 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12689 ((org-at-property-p)
12690 (call-interactively 'org-property-previous-allowed-value))
12691 ((org-clocktable-try-shift 'left arg))
12692 (t (org-shiftcursor-error))))
12694 (defun org-shiftcontrolright ()
12695 "Switch to next TODO set."
12696 (interactive)
12697 (cond
12698 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12699 (t (org-shiftcursor-error))))
12701 (defun org-shiftcontrolleft ()
12702 "Switch to previous TODO set."
12703 (interactive)
12704 (cond
12705 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12706 (t (org-shiftcursor-error))))
12708 (defun org-ctrl-c-ret ()
12709 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12710 (interactive)
12711 (cond
12712 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12713 (t (call-interactively 'org-insert-heading))))
12715 (defun org-copy-special ()
12716 "Copy region in table or copy current subtree.
12717 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12718 See the individual commands for more information."
12719 (interactive)
12720 (call-interactively
12721 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12723 (defun org-cut-special ()
12724 "Cut region in table or cut current subtree.
12725 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12726 See the individual commands for more information."
12727 (interactive)
12728 (call-interactively
12729 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12731 (defun org-paste-special (arg)
12732 "Paste rectangular region into table, or past subtree relative to level.
12733 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12734 See the individual commands for more information."
12735 (interactive "P")
12736 (if (org-at-table-p)
12737 (org-table-paste-rectangle)
12738 (org-paste-subtree arg)))
12740 (defun org-edit-special ()
12741 "Call a special editor for the stuff at point.
12742 When at a table, call the formula editor with `org-table-edit-formulas'.
12743 When at the first line of an src example, call `org-edit-src-code'.
12744 When in an #+include line, visit the include file. Otherwise call
12745 `ffap' to visit the file at point."
12746 (interactive)
12747 (cond
12748 ((org-at-table-p)
12749 (call-interactively 'org-table-edit-formulas))
12750 ((save-excursion
12751 (beginning-of-line 1)
12752 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12753 (find-file (org-trim (match-string 1))))
12754 ((org-edit-src-code))
12755 ((org-edit-fixed-width-region))
12756 (t (call-interactively 'ffap))))
12758 (defun org-ctrl-c-ctrl-c (&optional arg)
12759 "Set tags in headline, or update according to changed information at point.
12761 This command does many different things, depending on context:
12763 - If the cursor is in a headline, prompt for tags and insert them
12764 into the current line, aligned to `org-tags-column'. When called
12765 with prefix arg, realign all tags in the current buffer.
12767 - If the cursor is in one of the special #+KEYWORD lines, this
12768 triggers scanning the buffer for these lines and updating the
12769 information.
12771 - If the cursor is inside a table, realign the table. This command
12772 works even if the automatic table editor has been turned off.
12774 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12775 the entire table.
12777 - If the cursor is a the beginning of a dynamic block, update it.
12779 - If the cursor is inside a table created by the table.el package,
12780 activate that table.
12782 - If the current buffer is a remember buffer, close note and file
12783 it. A prefix argument of 1 files to the default location
12784 without further interaction. A prefix argument of 2 files to
12785 the currently clocking task.
12787 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12788 links in this buffer.
12790 - If the cursor is on a numbered item in a plain list, renumber the
12791 ordered list.
12793 - If the cursor is on a checkbox, toggle it."
12794 (interactive "P")
12795 (let ((org-enable-table-editor t))
12796 (cond
12797 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12798 org-occur-highlights
12799 org-latex-fragment-image-overlays)
12800 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12801 (org-remove-occur-highlights)
12802 (org-remove-latex-fragment-image-overlays)
12803 (message "Temporary highlights/overlays removed from current buffer"))
12804 ((and (local-variable-p 'org-finish-function (current-buffer))
12805 (fboundp org-finish-function))
12806 (funcall org-finish-function))
12807 ((org-at-property-p)
12808 (call-interactively 'org-property-action))
12809 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12810 ((org-on-heading-p) (call-interactively 'org-set-tags))
12811 ((org-at-table.el-p)
12812 (require 'table)
12813 (beginning-of-line 1)
12814 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12815 (call-interactively 'table-recognize-table))
12816 ((org-at-table-p)
12817 (org-table-maybe-eval-formula)
12818 (if arg
12819 (call-interactively 'org-table-recalculate)
12820 (org-table-maybe-recalculate-line))
12821 (call-interactively 'org-table-align))
12822 ((org-at-item-checkbox-p)
12823 (call-interactively 'org-toggle-checkbox))
12824 ((org-at-item-p)
12825 (call-interactively 'org-maybe-renumber-ordered-list))
12826 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12827 ;; Dynamic block
12828 (beginning-of-line 1)
12829 (save-excursion (org-update-dblock)))
12830 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12831 (cond
12832 ((equal (match-string 1) "TBLFM")
12833 ;; Recalculate the table before this line
12834 (save-excursion
12835 (beginning-of-line 1)
12836 (skip-chars-backward " \r\n\t")
12837 (if (org-at-table-p)
12838 (org-call-with-arg 'org-table-recalculate t))))
12840 ; (org-set-regexps-and-options)
12841 ; (org-restart-font-lock)
12842 (let ((org-inhibit-startup t)) (org-mode-restart))
12843 (message "Local setup has been refreshed"))))
12844 (t (error "C-c C-c can do nothing useful at this location.")))))
12846 (defun org-mode-restart ()
12847 "Restart Org-mode, to scan again for special lines.
12848 Also updates the keyword regular expressions."
12849 (interactive)
12850 (org-mode)
12851 (message "Org-mode restarted"))
12853 (defun org-kill-note-or-show-branches ()
12854 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12855 (interactive)
12856 (if (not org-finish-function)
12857 (call-interactively 'show-branches)
12858 (let ((org-note-abort t))
12859 (funcall org-finish-function))))
12861 (defun org-return (&optional indent)
12862 "Goto next table row or insert a newline.
12863 Calls `org-table-next-row' or `newline', depending on context.
12864 See the individual commands for more information."
12865 (interactive)
12866 (cond
12867 ((bobp) (if indent (newline-and-indent) (newline)))
12868 ((and (org-at-heading-p)
12869 (looking-at
12870 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12871 (org-show-entry)
12872 (end-of-line 1)
12873 (newline))
12874 ((org-at-table-p)
12875 (org-table-justify-field-maybe)
12876 (call-interactively 'org-table-next-row))
12877 (t (if indent (newline-and-indent) (newline)))))
12879 (defun org-return-indent ()
12880 "Goto next table row or insert a newline and indent.
12881 Calls `org-table-next-row' or `newline-and-indent', depending on
12882 context. See the individual commands for more information."
12883 (interactive)
12884 (org-return t))
12886 (defun org-ctrl-c-star ()
12887 "Compute table, or change heading status of lines.
12888 Calls `org-table-recalculate' or `org-toggle-region-headings',
12889 depending on context. This will also turn a plain list item or a normal
12890 line into a subheading."
12891 (interactive)
12892 (cond
12893 ((org-at-table-p)
12894 (call-interactively 'org-table-recalculate))
12895 ((org-region-active-p)
12896 ;; Convert all lines in region to list items
12897 (call-interactively 'org-toggle-region-headings))
12898 ((org-on-heading-p)
12899 (org-toggle-region-headings (point-at-bol)
12900 (min (1+ (point-at-eol)) (point-max))))
12901 ((org-at-item-p)
12902 ;; Convert to heading
12903 (let ((level (save-match-data
12904 (save-excursion
12905 (condition-case nil
12906 (progn
12907 (org-back-to-heading t)
12908 (funcall outline-level))
12909 (error 0))))))
12910 (replace-match
12911 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12912 (t (org-toggle-region-headings (point-at-bol)
12913 (min (1+ (point-at-eol)) (point-max))))))
12915 (defun org-ctrl-c-minus ()
12916 "Insert separator line in table or modify bullet status of line.
12917 Also turns a plain line or a region of lines into list items.
12918 Calls `org-table-insert-hline', `org-toggle-region-items', or
12919 `org-cycle-list-bullet', depending on context."
12920 (interactive)
12921 (cond
12922 ((org-at-table-p)
12923 (call-interactively 'org-table-insert-hline))
12924 ((org-on-heading-p)
12925 ;; Convert to item
12926 (save-excursion
12927 (beginning-of-line 1)
12928 (if (looking-at "\\*+ ")
12929 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12930 ((org-region-active-p)
12931 ;; Convert all lines in region to list items
12932 (call-interactively 'org-toggle-region-items))
12933 ((org-in-item-p)
12934 (call-interactively 'org-cycle-list-bullet))
12935 (t (org-toggle-region-items (point-at-bol)
12936 (min (1+ (point-at-eol)) (point-max))))))
12938 (defun org-toggle-region-items (beg end)
12939 "Convert all lines in region to list items.
12940 If the first line is already an item, convert all list items in the region
12941 to normal lines."
12942 (interactive "r")
12943 (let (l2 l)
12944 (save-excursion
12945 (goto-char end)
12946 (setq l2 (org-current-line))
12947 (goto-char beg)
12948 (beginning-of-line 1)
12949 (setq l (1- (org-current-line)))
12950 (if (org-at-item-p)
12951 ;; We already have items, de-itemize
12952 (while (< (setq l (1+ l)) l2)
12953 (when (org-at-item-p)
12954 (goto-char (match-beginning 2))
12955 (delete-region (match-beginning 2) (match-end 2))
12956 (and (looking-at "[ \t]+") (replace-match "")))
12957 (beginning-of-line 2))
12958 (while (< (setq l (1+ l)) l2)
12959 (unless (org-at-item-p)
12960 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12961 (replace-match "\\1- \\2")))
12962 (beginning-of-line 2))))))
12964 (defun org-toggle-region-headings (beg end)
12965 "Convert all lines in region to list items.
12966 If the first line is already an item, convert all list items in the region
12967 to normal lines."
12968 (interactive "r")
12969 (let (l2 l)
12970 (save-excursion
12971 (goto-char end)
12972 (setq l2 (org-current-line))
12973 (goto-char beg)
12974 (beginning-of-line 1)
12975 (setq l (1- (org-current-line)))
12976 (if (org-on-heading-p)
12977 ;; We already have headlines, de-star them
12978 (while (< (setq l (1+ l)) l2)
12979 (when (org-on-heading-p t)
12980 (and (looking-at outline-regexp) (replace-match "")))
12981 (beginning-of-line 2))
12982 (let* ((stars (save-excursion
12983 (re-search-backward org-complex-heading-regexp nil t)
12984 (or (match-string 1) "*")))
12985 (add-stars (if org-odd-levels-only "**" "*"))
12986 (rpl (concat stars add-stars " \\2")))
12987 (while (< (setq l (1+ l)) l2)
12988 (unless (org-on-heading-p)
12989 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12990 (replace-match rpl)))
12991 (beginning-of-line 2)))))))
12993 (defun org-meta-return (&optional arg)
12994 "Insert a new heading or wrap a region in a table.
12995 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12996 See the individual commands for more information."
12997 (interactive "P")
12998 (cond
12999 ((org-at-table-p)
13000 (call-interactively 'org-table-wrap-region))
13001 (t (call-interactively 'org-insert-heading))))
13003 ;;; Menu entries
13005 ;; Define the Org-mode menus
13006 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13007 '("Tbl"
13008 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13009 ["Next Field" org-cycle (org-at-table-p)]
13010 ["Previous Field" org-shifttab (org-at-table-p)]
13011 ["Next Row" org-return (org-at-table-p)]
13012 "--"
13013 ["Blank Field" org-table-blank-field (org-at-table-p)]
13014 ["Edit Field" org-table-edit-field (org-at-table-p)]
13015 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13016 "--"
13017 ("Column"
13018 ["Move Column Left" org-metaleft (org-at-table-p)]
13019 ["Move Column Right" org-metaright (org-at-table-p)]
13020 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13021 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13022 ("Row"
13023 ["Move Row Up" org-metaup (org-at-table-p)]
13024 ["Move Row Down" org-metadown (org-at-table-p)]
13025 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13026 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13027 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13028 "--"
13029 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13030 ("Rectangle"
13031 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13032 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13033 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13034 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13035 "--"
13036 ("Calculate"
13037 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13038 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13039 ["Edit Formulas" org-edit-special (org-at-table-p)]
13040 "--"
13041 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13042 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13043 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13044 "--"
13045 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13046 "--"
13047 ["Sum Column/Rectangle" org-table-sum
13048 (or (org-at-table-p) (org-region-active-p))]
13049 ["Which Column?" org-table-current-column (org-at-table-p)])
13050 ["Debug Formulas"
13051 org-table-toggle-formula-debugger
13052 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13053 ["Show Col/Row Numbers"
13054 org-table-toggle-coordinate-overlays
13055 :style toggle
13056 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13057 "--"
13058 ["Create" org-table-create (and (not (org-at-table-p))
13059 org-enable-table-editor)]
13060 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13061 ["Import from File" org-table-import (not (org-at-table-p))]
13062 ["Export to File" org-table-export (org-at-table-p)]
13063 "--"
13064 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13066 (easy-menu-define org-org-menu org-mode-map "Org menu"
13067 '("Org"
13068 ("Show/Hide"
13069 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13070 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13071 ["Sparse Tree..." org-sparse-tree t]
13072 ["Reveal Context" org-reveal t]
13073 ["Show All" show-all t]
13074 "--"
13075 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13076 "--"
13077 ["New Heading" org-insert-heading t]
13078 ("Navigate Headings"
13079 ["Up" outline-up-heading t]
13080 ["Next" outline-next-visible-heading t]
13081 ["Previous" outline-previous-visible-heading t]
13082 ["Next Same Level" outline-forward-same-level t]
13083 ["Previous Same Level" outline-backward-same-level t]
13084 "--"
13085 ["Jump" org-goto t])
13086 ("Edit Structure"
13087 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13088 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13089 "--"
13090 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13091 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13092 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13093 "--"
13094 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13095 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13096 ["Demote Heading" org-metaright (not (org-at-table-p))]
13097 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13098 "--"
13099 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13100 "--"
13101 ["Convert to odd levels" org-convert-to-odd-levels t]
13102 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13103 ("Editing"
13104 ["Emphasis..." org-emphasize t]
13105 ["Edit Source Example" org-edit-special t])
13106 ("Archive"
13107 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13108 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13109 ; :active t :keys "C-u C-c C-x C-a"]
13110 ["Sparse trees open ARCHIVE trees"
13111 (setq org-sparse-tree-open-archived-trees
13112 (not org-sparse-tree-open-archived-trees))
13113 :style toggle :selected org-sparse-tree-open-archived-trees]
13114 ["Cycling opens ARCHIVE trees"
13115 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13116 :style toggle :selected org-cycle-open-archived-trees]
13117 "--"
13118 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13119 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13120 ; ["Check and Move Children" (org-archive-subtree '(4))
13121 ; :active t :keys "C-u C-c C-x C-s"]
13123 "--"
13124 ("TODO Lists"
13125 ["TODO/DONE/-" org-todo t]
13126 ("Select keyword"
13127 ["Next keyword" org-shiftright (org-on-heading-p)]
13128 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13129 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13130 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13131 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13132 ["Show TODO Tree" org-show-todo-tree t]
13133 ["Global TODO list" org-todo-list t]
13134 "--"
13135 ["Set Priority" org-priority t]
13136 ["Priority Up" org-shiftup t]
13137 ["Priority Down" org-shiftdown t])
13138 ("TAGS and Properties"
13139 ["Set Tags" 'org-set-tags-command t]
13140 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13141 "--"
13142 ["Set property" 'org-set-property t]
13143 ["Column view of properties" org-columns t]
13144 ["Insert Column View DBlock" org-insert-columns-dblock t])
13145 ("Dates and Scheduling"
13146 ["Timestamp" org-time-stamp t]
13147 ["Timestamp (inactive)" org-time-stamp-inactive t]
13148 ("Change Date"
13149 ["1 Day Later" org-shiftright t]
13150 ["1 Day Earlier" org-shiftleft t]
13151 ["1 ... Later" org-shiftup t]
13152 ["1 ... Earlier" org-shiftdown t])
13153 ["Compute Time Range" org-evaluate-time-range t]
13154 ["Schedule Item" org-schedule t]
13155 ["Deadline" org-deadline t]
13156 "--"
13157 ["Custom time format" org-toggle-time-stamp-overlays
13158 :style radio :selected org-display-custom-times]
13159 "--"
13160 ["Goto Calendar" org-goto-calendar t]
13161 ["Date from Calendar" org-date-from-calendar t])
13162 ("Logging work"
13163 ["Clock in" org-clock-in t]
13164 ["Clock out" org-clock-out t]
13165 ["Clock cancel" org-clock-cancel t]
13166 ["Goto running clock" org-clock-goto t]
13167 ["Display times" org-clock-display t]
13168 ["Create clock table" org-clock-report t]
13169 "--"
13170 ["Record DONE time"
13171 (progn (setq org-log-done (not org-log-done))
13172 (message "Switching to %s will %s record a timestamp"
13173 (car org-done-keywords)
13174 (if org-log-done "automatically" "not")))
13175 :style toggle :selected org-log-done])
13176 "--"
13177 ["Agenda Command..." org-agenda t]
13178 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13179 ("File List for Agenda")
13180 ("Special views current file"
13181 ["TODO Tree" org-show-todo-tree t]
13182 ["Check Deadlines" org-check-deadlines t]
13183 ["Timeline" org-timeline t]
13184 ["Tags Tree" org-tags-sparse-tree t])
13185 "--"
13186 ("Hyperlinks"
13187 ["Store Link (Global)" org-store-link t]
13188 ["Insert Link" org-insert-link t]
13189 ["Follow Link" org-open-at-point t]
13190 "--"
13191 ["Next link" org-next-link t]
13192 ["Previous link" org-previous-link t]
13193 "--"
13194 ["Descriptive Links"
13195 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13196 :style radio
13197 :selected (member '(org-link) buffer-invisibility-spec)]
13198 ["Literal Links"
13199 (progn
13200 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13201 :style radio
13202 :selected (not (member '(org-link) buffer-invisibility-spec))])
13203 "--"
13204 ["Export/Publish..." org-export t]
13205 ("LaTeX"
13206 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13207 :selected org-cdlatex-mode]
13208 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13209 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13210 ["Modify math symbol" org-cdlatex-math-modify
13211 (org-inside-LaTeX-fragment-p)]
13212 ["Export LaTeX fragments as images"
13213 (if (featurep 'org-exp)
13214 (setq org-export-with-LaTeX-fragments
13215 (not org-export-with-LaTeX-fragments))
13216 (require 'org-exp))
13217 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13218 org-export-with-LaTeX-fragments)])
13219 "--"
13220 ("Documentation"
13221 ["Show Version" org-version t]
13222 ["Info Documentation" org-info t])
13223 ("Customize"
13224 ["Browse Org Group" org-customize t]
13225 "--"
13226 ["Expand This Menu" org-create-customize-menu
13227 (fboundp 'customize-menu-create)])
13228 "--"
13229 ["Refresh setup" org-mode-restart t]
13232 (defun org-info (&optional node)
13233 "Read documentation for Org-mode in the info system.
13234 With optional NODE, go directly to that node."
13235 (interactive)
13236 (info (format "(org)%s" (or node ""))))
13238 (defun org-install-agenda-files-menu ()
13239 (let ((bl (buffer-list)))
13240 (save-excursion
13241 (while bl
13242 (set-buffer (pop bl))
13243 (if (org-mode-p) (setq bl nil)))
13244 (when (org-mode-p)
13245 (easy-menu-change
13246 '("Org") "File List for Agenda"
13247 (append
13248 (list
13249 ["Edit File List" (org-edit-agenda-file-list) t]
13250 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13251 ["Remove Current File from List" org-remove-file t]
13252 ["Cycle through agenda files" org-cycle-agenda-files t]
13253 ["Occur in all agenda files" org-occur-in-agenda-files t]
13254 "--")
13255 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13257 ;;;; Documentation
13259 ;;;###autoload
13260 (defun org-require-autoloaded-modules ()
13261 (interactive)
13262 (mapc 'require
13263 '(org-agenda org-archive org-clock org-colview
13264 org-exp org-id org-export-latex org-publish
13265 org-remember org-table)))
13267 ;;;###autoload
13268 (defun org-customize ()
13269 "Call the customize function with org as argument."
13270 (interactive)
13271 (org-load-modules-maybe)
13272 (org-require-autoloaded-modules)
13273 (customize-browse 'org))
13275 (defun org-create-customize-menu ()
13276 "Create a full customization menu for Org-mode, insert it into the menu."
13277 (interactive)
13278 (org-load-modules-maybe)
13279 (org-require-autoloaded-modules)
13280 (if (fboundp 'customize-menu-create)
13281 (progn
13282 (easy-menu-change
13283 '("Org") "Customize"
13284 `(["Browse Org group" org-customize t]
13285 "--"
13286 ,(customize-menu-create 'org)
13287 ["Set" Custom-set t]
13288 ["Save" Custom-save t]
13289 ["Reset to Current" Custom-reset-current t]
13290 ["Reset to Saved" Custom-reset-saved t]
13291 ["Reset to Standard Settings" Custom-reset-standard t]))
13292 (message "\"Org\"-menu now contains full customization menu"))
13293 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13295 ;;;; Miscellaneous stuff
13297 ;;; Generally useful functions
13299 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13300 "Display the given MESSAGE as a warning."
13301 (if (fboundp 'display-warning)
13302 (display-warning 'org message
13303 (if (featurep 'xemacs)
13304 'warning
13305 :warning))
13306 (let ((buf (get-buffer-create "*Org warnings*")))
13307 (with-current-buffer buf
13308 (goto-char (point-max))
13309 (insert "Warning (Org): " message)
13310 (unless (bolp)
13311 (newline)))
13312 (display-buffer buf)
13313 (sit-for 0))))
13315 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13316 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13317 (if (and marker (marker-buffer marker)
13318 (buffer-live-p (marker-buffer marker)))
13319 (progn
13320 (switch-to-buffer (marker-buffer marker))
13321 (if (or (> marker (point-max)) (< marker (point-min)))
13322 (widen))
13323 (goto-char marker))
13324 (if bookmark
13325 (bookmark-jump bookmark)
13326 (error "Cannot find location"))))
13328 (defun org-quote-csv-field (s)
13329 "Quote field for inclusion in CSV material."
13330 (if (string-match "[\",]" s)
13331 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13334 (defun org-plist-delete (plist property)
13335 "Delete PROPERTY from PLIST.
13336 This is in contrast to merely setting it to 0."
13337 (let (p)
13338 (while plist
13339 (if (not (eq property (car plist)))
13340 (setq p (plist-put p (car plist) (nth 1 plist))))
13341 (setq plist (cddr plist)))
13344 (defun org-force-self-insert (N)
13345 "Needed to enforce self-insert under remapping."
13346 (interactive "p")
13347 (self-insert-command N))
13349 (defun org-string-width (s)
13350 "Compute width of string, ignoring invisible characters.
13351 This ignores character with invisibility property `org-link', and also
13352 characters with property `org-cwidth', because these will become invisible
13353 upon the next fontification round."
13354 (let (b l)
13355 (when (or (eq t buffer-invisibility-spec)
13356 (assq 'org-link buffer-invisibility-spec))
13357 (while (setq b (text-property-any 0 (length s)
13358 'invisible 'org-link s))
13359 (setq s (concat (substring s 0 b)
13360 (substring s (or (next-single-property-change
13361 b 'invisible s) (length s)))))))
13362 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13363 (setq s (concat (substring s 0 b)
13364 (substring s (or (next-single-property-change
13365 b 'org-cwidth s) (length s))))))
13366 (setq l (string-width s) b -1)
13367 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13368 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13371 (defun org-get-indentation (&optional line)
13372 "Get the indentation of the current line, interpreting tabs.
13373 When LINE is given, assume it represents a line and compute its indentation."
13374 (if line
13375 (if (string-match "^ *" (org-remove-tabs line))
13376 (match-end 0))
13377 (save-excursion
13378 (beginning-of-line 1)
13379 (skip-chars-forward " \t")
13380 (current-column))))
13382 (defun org-remove-tabs (s &optional width)
13383 "Replace tabulators in S with spaces.
13384 Assumes that s is a single line, starting in column 0."
13385 (setq width (or width tab-width))
13386 (while (string-match "\t" s)
13387 (setq s (replace-match
13388 (make-string
13389 (- (* width (/ (+ (match-beginning 0) width) width))
13390 (match-beginning 0)) ?\ )
13391 t t s)))
13394 (defun org-fix-indentation (line ind)
13395 "Fix indentation in LINE.
13396 IND is a cons cell with target and minimum indentation.
13397 If the current indenation in LINE is smaller than the minimum,
13398 leave it alone. If it is larger than ind, set it to the target."
13399 (let* ((l (org-remove-tabs line))
13400 (i (org-get-indentation l))
13401 (i1 (car ind)) (i2 (cdr ind)))
13402 (if (>= i i2) (setq l (substring line i2)))
13403 (if (> i1 0)
13404 (concat (make-string i1 ?\ ) l)
13405 l)))
13407 (defun org-base-buffer (buffer)
13408 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13409 (if (not buffer)
13410 buffer
13411 (or (buffer-base-buffer buffer)
13412 buffer)))
13414 (defun org-trim (s)
13415 "Remove whitespace at beginning and end of string."
13416 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13417 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13420 (defun org-wrap (string &optional width lines)
13421 "Wrap string to either a number of lines, or a width in characters.
13422 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13423 that costs. If there is a word longer than WIDTH, the text is actually
13424 wrapped to the length of that word.
13425 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13426 many lines, whatever width that takes.
13427 The return value is a list of lines, without newlines at the end."
13428 (let* ((words (org-split-string string "[ \t\n]+"))
13429 (maxword (apply 'max (mapcar 'org-string-width words)))
13430 w ll)
13431 (cond (width
13432 (org-do-wrap words (max maxword width)))
13433 (lines
13434 (setq w maxword)
13435 (setq ll (org-do-wrap words maxword))
13436 (if (<= (length ll) lines)
13438 (setq ll words)
13439 (while (> (length ll) lines)
13440 (setq w (1+ w))
13441 (setq ll (org-do-wrap words w)))
13442 ll))
13443 (t (error "Cannot wrap this")))))
13445 (defun org-do-wrap (words width)
13446 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13447 (let (lines line)
13448 (while words
13449 (setq line (pop words))
13450 (while (and words (< (+ (length line) (length (car words))) width))
13451 (setq line (concat line " " (pop words))))
13452 (setq lines (push line lines)))
13453 (nreverse lines)))
13455 (defun org-split-string (string &optional separators)
13456 "Splits STRING into substrings at SEPARATORS.
13457 No empty strings are returned if there are matches at the beginning
13458 and end of string."
13459 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13460 (start 0)
13461 notfirst
13462 (list nil))
13463 (while (and (string-match rexp string
13464 (if (and notfirst
13465 (= start (match-beginning 0))
13466 (< start (length string)))
13467 (1+ start) start))
13468 (< (match-beginning 0) (length string)))
13469 (setq notfirst t)
13470 (or (eq (match-beginning 0) 0)
13471 (and (eq (match-beginning 0) (match-end 0))
13472 (eq (match-beginning 0) start))
13473 (setq list
13474 (cons (substring string start (match-beginning 0))
13475 list)))
13476 (setq start (match-end 0)))
13477 (or (eq start (length string))
13478 (setq list
13479 (cons (substring string start)
13480 list)))
13481 (nreverse list)))
13483 (defun org-context ()
13484 "Return a list of contexts of the current cursor position.
13485 If several contexts apply, all are returned.
13486 Each context entry is a list with a symbol naming the context, and
13487 two positions indicating start and end of the context. Possible
13488 contexts are:
13490 :headline anywhere in a headline
13491 :headline-stars on the leading stars in a headline
13492 :todo-keyword on a TODO keyword (including DONE) in a headline
13493 :tags on the TAGS in a headline
13494 :priority on the priority cookie in a headline
13495 :item on the first line of a plain list item
13496 :item-bullet on the bullet/number of a plain list item
13497 :checkbox on the checkbox in a plain list item
13498 :table in an org-mode table
13499 :table-special on a special filed in a table
13500 :table-table in a table.el table
13501 :link on a hyperlink
13502 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13503 :target on a <<target>>
13504 :radio-target on a <<<radio-target>>>
13505 :latex-fragment on a LaTeX fragment
13506 :latex-preview on a LaTeX fragment with overlayed preview image
13508 This function expects the position to be visible because it uses font-lock
13509 faces as a help to recognize the following contexts: :table-special, :link,
13510 and :keyword."
13511 (let* ((f (get-text-property (point) 'face))
13512 (faces (if (listp f) f (list f)))
13513 (p (point)) clist o)
13514 ;; First the large context
13515 (cond
13516 ((org-on-heading-p t)
13517 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13518 (when (progn
13519 (beginning-of-line 1)
13520 (looking-at org-todo-line-tags-regexp))
13521 (push (org-point-in-group p 1 :headline-stars) clist)
13522 (push (org-point-in-group p 2 :todo-keyword) clist)
13523 (push (org-point-in-group p 4 :tags) clist))
13524 (goto-char p)
13525 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13526 (if (looking-at "\\[#[A-Z0-9]\\]")
13527 (push (org-point-in-group p 0 :priority) clist)))
13529 ((org-at-item-p)
13530 (push (org-point-in-group p 2 :item-bullet) clist)
13531 (push (list :item (point-at-bol)
13532 (save-excursion (org-end-of-item) (point)))
13533 clist)
13534 (and (org-at-item-checkbox-p)
13535 (push (org-point-in-group p 0 :checkbox) clist)))
13537 ((org-at-table-p)
13538 (push (list :table (org-table-begin) (org-table-end)) clist)
13539 (if (memq 'org-formula faces)
13540 (push (list :table-special
13541 (previous-single-property-change p 'face)
13542 (next-single-property-change p 'face)) clist)))
13543 ((org-at-table-p 'any)
13544 (push (list :table-table) clist)))
13545 (goto-char p)
13547 ;; Now the small context
13548 (cond
13549 ((org-at-timestamp-p)
13550 (push (org-point-in-group p 0 :timestamp) clist))
13551 ((memq 'org-link faces)
13552 (push (list :link
13553 (previous-single-property-change p 'face)
13554 (next-single-property-change p 'face)) clist))
13555 ((memq 'org-special-keyword faces)
13556 (push (list :keyword
13557 (previous-single-property-change p 'face)
13558 (next-single-property-change p 'face)) clist))
13559 ((org-on-target-p)
13560 (push (org-point-in-group p 0 :target) clist)
13561 (goto-char (1- (match-beginning 0)))
13562 (if (looking-at org-radio-target-regexp)
13563 (push (org-point-in-group p 0 :radio-target) clist))
13564 (goto-char p))
13565 ((setq o (car (delq nil
13566 (mapcar
13567 (lambda (x)
13568 (if (memq x org-latex-fragment-image-overlays) x))
13569 (org-overlays-at (point))))))
13570 (push (list :latex-fragment
13571 (org-overlay-start o) (org-overlay-end o)) clist)
13572 (push (list :latex-preview
13573 (org-overlay-start o) (org-overlay-end o)) clist))
13574 ((org-inside-LaTeX-fragment-p)
13575 ;; FIXME: positions wrong.
13576 (push (list :latex-fragment (point) (point)) clist)))
13578 (setq clist (nreverse (delq nil clist)))
13579 clist))
13581 ;; FIXME: Compare with at-regexp-p Do we need both?
13582 (defun org-in-regexp (re &optional nlines visually)
13583 "Check if point is inside a match of regexp.
13584 Normally only the current line is checked, but you can include NLINES extra
13585 lines both before and after point into the search.
13586 If VISUALLY is set, require that the cursor is not after the match but
13587 really on, so that the block visually is on the match."
13588 (catch 'exit
13589 (let ((pos (point))
13590 (eol (point-at-eol (+ 1 (or nlines 0))))
13591 (inc (if visually 1 0)))
13592 (save-excursion
13593 (beginning-of-line (- 1 (or nlines 0)))
13594 (while (re-search-forward re eol t)
13595 (if (and (<= (match-beginning 0) pos)
13596 (>= (+ inc (match-end 0)) pos))
13597 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13599 (defun org-at-regexp-p (regexp)
13600 "Is point inside a match of REGEXP in the current line?"
13601 (catch 'exit
13602 (save-excursion
13603 (let ((pos (point)) (end (point-at-eol)))
13604 (beginning-of-line 1)
13605 (while (re-search-forward regexp end t)
13606 (if (and (<= (match-beginning 0) pos)
13607 (>= (match-end 0) pos))
13608 (throw 'exit t)))
13609 nil))))
13611 (defun org-occur-in-agenda-files (regexp &optional nlines)
13612 "Call `multi-occur' with buffers for all agenda files."
13613 (interactive "sOrg-files matching: \np")
13614 (let* ((files (org-agenda-files))
13615 (tnames (mapcar 'file-truename files))
13616 (extra org-agenda-text-search-extra-files)
13618 (when (eq (car extra) 'agenda-archives)
13619 (setq extra (cdr extra))
13620 (setq files (org-add-archive-files files)))
13621 (while (setq f (pop extra))
13622 (unless (member (file-truename f) tnames)
13623 (add-to-list 'files f 'append)
13624 (add-to-list 'tnames (file-truename f) 'append)))
13625 (multi-occur
13626 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13627 regexp)))
13629 (if (boundp 'occur-mode-find-occurrence-hook)
13630 ;; Emacs 23
13631 (add-hook 'occur-mode-find-occurrence-hook
13632 (lambda ()
13633 (when (org-mode-p)
13634 (org-reveal))))
13635 ;; Emacs 22
13636 (defadvice occur-mode-goto-occurrence
13637 (after org-occur-reveal activate)
13638 (and (org-mode-p) (org-reveal)))
13639 (defadvice occur-mode-goto-occurrence-other-window
13640 (after org-occur-reveal activate)
13641 (and (org-mode-p) (org-reveal)))
13642 (defadvice occur-mode-display-occurrence
13643 (after org-occur-reveal activate)
13644 (when (org-mode-p)
13645 (let ((pos (occur-mode-find-occurrence)))
13646 (with-current-buffer (marker-buffer pos)
13647 (save-excursion
13648 (goto-char pos)
13649 (org-reveal)))))))
13651 (defun org-uniquify (list)
13652 "Remove duplicate elements from LIST."
13653 (let (res)
13654 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13655 res))
13657 (defun org-delete-all (elts list)
13658 "Remove all elements in ELTS from LIST."
13659 (while elts
13660 (setq list (delete (pop elts) list)))
13661 list)
13663 (defun org-back-over-empty-lines ()
13664 "Move backwards over witespace, to the beginning of the first empty line.
13665 Returns the number of empty lines passed."
13666 (let ((pos (point)))
13667 (skip-chars-backward " \t\n\r")
13668 (beginning-of-line 2)
13669 (goto-char (min (point) pos))
13670 (count-lines (point) pos)))
13672 (defun org-skip-whitespace ()
13673 (skip-chars-forward " \t\n\r"))
13675 (defun org-point-in-group (point group &optional context)
13676 "Check if POINT is in match-group GROUP.
13677 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13678 match. If the match group does ot exist or point is not inside it,
13679 return nil."
13680 (and (match-beginning group)
13681 (>= point (match-beginning group))
13682 (<= point (match-end group))
13683 (if context
13684 (list context (match-beginning group) (match-end group))
13685 t)))
13687 (defun org-switch-to-buffer-other-window (&rest args)
13688 "Switch to buffer in a second window on the current frame.
13689 In particular, do not allow pop-up frames."
13690 (let (pop-up-frames special-display-buffer-names special-display-regexps
13691 special-display-function)
13692 (apply 'switch-to-buffer-other-window args)))
13694 (defun org-combine-plists (&rest plists)
13695 "Create a single property list from all plists in PLISTS.
13696 The process starts by copying the first list, and then setting properties
13697 from the other lists. Settings in the last list are the most significant
13698 ones and overrule settings in the other lists."
13699 (let ((rtn (copy-sequence (pop plists)))
13700 p v ls)
13701 (while plists
13702 (setq ls (pop plists))
13703 (while ls
13704 (setq p (pop ls) v (pop ls))
13705 (setq rtn (plist-put rtn p v))))
13706 rtn))
13708 (defun org-move-line-down (arg)
13709 "Move the current line down. With prefix argument, move it past ARG lines."
13710 (interactive "p")
13711 (let ((col (current-column))
13712 beg end pos)
13713 (beginning-of-line 1) (setq beg (point))
13714 (beginning-of-line 2) (setq end (point))
13715 (beginning-of-line (+ 1 arg))
13716 (setq pos (move-marker (make-marker) (point)))
13717 (insert (delete-and-extract-region beg end))
13718 (goto-char pos)
13719 (org-move-to-column col)))
13721 (defun org-move-line-up (arg)
13722 "Move the current line up. With prefix argument, move it past ARG lines."
13723 (interactive "p")
13724 (let ((col (current-column))
13725 beg end pos)
13726 (beginning-of-line 1) (setq beg (point))
13727 (beginning-of-line 2) (setq end (point))
13728 (beginning-of-line (- arg))
13729 (setq pos (move-marker (make-marker) (point)))
13730 (insert (delete-and-extract-region beg end))
13731 (goto-char pos)
13732 (org-move-to-column col)))
13734 (defun org-replace-escapes (string table)
13735 "Replace %-escapes in STRING with values in TABLE.
13736 TABLE is an association list with keys like \"%a\" and string values.
13737 The sequences in STRING may contain normal field width and padding information,
13738 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13739 so values can contain further %-escapes if they are define later in TABLE."
13740 (let ((case-fold-search nil)
13741 e re rpl)
13742 (while (setq e (pop table))
13743 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13744 (while (string-match re string)
13745 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13746 (cdr e)))
13747 (setq string (replace-match rpl t t string))))
13748 string))
13751 (defun org-sublist (list start end)
13752 "Return a section of LIST, from START to END.
13753 Counting starts at 1."
13754 (let (rtn (c start))
13755 (setq list (nthcdr (1- start) list))
13756 (while (and list (<= c end))
13757 (push (pop list) rtn)
13758 (setq c (1+ c)))
13759 (nreverse rtn)))
13761 (defun org-find-base-buffer-visiting (file)
13762 "Like `find-buffer-visiting' but alway return the base buffer and
13763 not an indirect buffer."
13764 (let ((buf (find-buffer-visiting file)))
13765 (if buf
13766 (or (buffer-base-buffer buf) buf)
13767 nil)))
13769 (defun org-image-file-name-regexp ()
13770 "Return regexp matching the file names of images."
13771 (if (fboundp 'image-file-name-regexp)
13772 (image-file-name-regexp)
13773 (let ((image-file-name-extensions
13774 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13775 "xbm" "xpm" "pbm" "pgm" "ppm")))
13776 (concat "\\."
13777 (regexp-opt (nconc (mapcar 'upcase
13778 image-file-name-extensions)
13779 image-file-name-extensions)
13781 "\\'"))))
13783 (defun org-file-image-p (file)
13784 "Return non-nil if FILE is an image."
13785 (save-match-data
13786 (string-match (org-image-file-name-regexp) file)))
13788 (defun org-get-cursor-date ()
13789 "Return the date at cursor in as a time.
13790 This works in the calendar and in the agenda, anywhere else it just
13791 returns the current time."
13792 (let (date day defd)
13793 (cond
13794 ((eq major-mode 'calendar-mode)
13795 (setq date (calendar-cursor-to-date)
13796 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13797 ((eq major-mode 'org-agenda-mode)
13798 (setq day (get-text-property (point) 'day))
13799 (if day
13800 (setq date (calendar-gregorian-from-absolute day)
13801 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13802 (nth 2 date))))))
13803 (or defd (current-time))))
13805 (defvar org-agenda-action-marker (make-marker)
13806 "Marker pointing to the entry for the next agenda action.")
13808 (defun org-mark-entry-for-agenda-action ()
13809 "Mark the current entry as target of an agenda action.
13810 Agenda actions are actions executed from the agenda with the key `k',
13811 which make use of the date at the cursor."
13812 (interactive)
13813 (move-marker org-agenda-action-marker
13814 (save-excursion (org-back-to-heading t) (point))
13815 (current-buffer))
13816 (message
13817 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13819 ;;; Paragraph filling stuff.
13820 ;; We want this to be just right, so use the full arsenal.
13822 (defun org-indent-line-function ()
13823 "Indent line like previous, but further if previous was headline or item."
13824 (interactive)
13825 (let* ((pos (point))
13826 (itemp (org-at-item-p))
13827 column bpos bcol tpos tcol bullet btype bullet-type)
13828 ;; Find the previous relevant line
13829 (beginning-of-line 1)
13830 (cond
13831 ((looking-at "#") (setq column 0))
13832 ((looking-at "\\*+ ") (setq column 0))
13834 (beginning-of-line 0)
13835 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13836 (beginning-of-line 0))
13837 (cond
13838 ((looking-at "\\*+[ \t]+")
13839 (if (not org-adapt-indentation)
13840 (setq column 0)
13841 (goto-char (match-end 0))
13842 (setq column (current-column))))
13843 ((org-in-item-p)
13844 (org-beginning-of-item)
13845 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13846 (setq bpos (match-beginning 1) tpos (match-end 0)
13847 bcol (progn (goto-char bpos) (current-column))
13848 tcol (progn (goto-char tpos) (current-column))
13849 bullet (match-string 1)
13850 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13851 (if (> tcol (+ bcol org-description-max-indent))
13852 (setq tcol (+ bcol 5)))
13853 (if (not itemp)
13854 (setq column tcol)
13855 (goto-char pos)
13856 (beginning-of-line 1)
13857 (if (looking-at "\\S-")
13858 (progn
13859 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13860 (setq bullet (match-string 1)
13861 btype (if (string-match "[0-9]" bullet) "n" bullet))
13862 (setq column (if (equal btype bullet-type) bcol tcol)))
13863 (setq column (org-get-indentation)))))
13864 (t (setq column (org-get-indentation))))))
13865 (goto-char pos)
13866 (if (<= (current-column) (current-indentation))
13867 (org-indent-line-to column)
13868 (save-excursion (org-indent-line-to column)))
13869 (setq column (current-column))
13870 (beginning-of-line 1)
13871 (if (looking-at
13872 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13873 (replace-match (concat "\\1" (format org-property-format
13874 (match-string 2) (match-string 3)))
13875 t nil))
13876 (org-move-to-column column)))
13878 (defun org-set-autofill-regexps ()
13879 (interactive)
13880 ;; In the paragraph separator we include headlines, because filling
13881 ;; text in a line directly attached to a headline would otherwise
13882 ;; fill the headline as well.
13883 (org-set-local 'comment-start-skip "^#+[ \t]*")
13884 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13885 ;; The paragraph starter includes hand-formatted lists.
13886 (org-set-local 'paragraph-start
13887 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13888 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13889 ;; But only if the user has not turned off tables or fixed-width regions
13890 (org-set-local
13891 'auto-fill-inhibit-regexp
13892 (concat "\\*+ \\|#\\+"
13893 "\\|[ \t]*" org-keyword-time-regexp
13894 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13895 (concat
13896 "\\|[ \t]*["
13897 (if org-enable-table-editor "|" "")
13898 (if org-enable-fixed-width-editor ":" "")
13899 "]"))))
13900 ;; We use our own fill-paragraph function, to make sure that tables
13901 ;; and fixed-width regions are not wrapped. That function will pass
13902 ;; through to `fill-paragraph' when appropriate.
13903 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13904 ; Adaptive filling: To get full control, first make sure that
13905 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13906 (org-set-local 'adaptive-fill-regexp "\000")
13907 (org-set-local 'adaptive-fill-function
13908 'org-adaptive-fill-function)
13909 (org-set-local
13910 'align-mode-rules-list
13911 '((org-in-buffer-settings
13912 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13913 (modes . '(org-mode))))))
13915 (defun org-fill-paragraph (&optional justify)
13916 "Re-align a table, pass through to fill-paragraph if no table."
13917 (let ((table-p (org-at-table-p))
13918 (table.el-p (org-at-table.el-p)))
13919 (cond ((and (equal (char-after (point-at-bol)) ?*)
13920 (save-excursion (goto-char (point-at-bol))
13921 (looking-at outline-regexp)))
13922 t) ; skip headlines
13923 (table.el-p t) ; skip table.el tables
13924 (table-p (org-table-align) t) ; align org-mode tables
13925 (t nil)))) ; call paragraph-fill
13927 ;; For reference, this is the default value of adaptive-fill-regexp
13928 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13930 (defun org-adaptive-fill-function ()
13931 "Return a fill prefix for org-mode files.
13932 In particular, this makes sure hanging paragraphs for hand-formatted lists
13933 work correctly."
13934 (cond ((looking-at "#[ \t]+")
13935 (match-string 0))
13936 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13937 (save-excursion
13938 (if (> (match-end 1) (+ (match-beginning 1)
13939 org-description-max-indent))
13940 (goto-char (+ (match-beginning 1) 5))
13941 (goto-char (match-end 0)))
13942 (make-string (current-column) ?\ )))
13943 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13944 (save-excursion
13945 (goto-char (match-end 0))
13946 (make-string (current-column) ?\ )))
13947 (t nil)))
13949 ;;; Other stuff.
13951 (defun org-toggle-fixed-width-section (arg)
13952 "Toggle the fixed-width export.
13953 If there is no active region, the QUOTE keyword at the current headline is
13954 inserted or removed. When present, it causes the text between this headline
13955 and the next to be exported as fixed-width text, and unmodified.
13956 If there is an active region, this command adds or removes a colon as the
13957 first character of this line. If the first character of a line is a colon,
13958 this line is also exported in fixed-width font."
13959 (interactive "P")
13960 (let* ((cc 0)
13961 (regionp (org-region-active-p))
13962 (beg (if regionp (region-beginning) (point)))
13963 (end (if regionp (region-end)))
13964 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13965 (case-fold-search nil)
13966 (re "[ \t]*\\(:\\)")
13967 off)
13968 (if regionp
13969 (save-excursion
13970 (goto-char beg)
13971 (setq cc (current-column))
13972 (beginning-of-line 1)
13973 (setq off (looking-at re))
13974 (while (> nlines 0)
13975 (setq nlines (1- nlines))
13976 (beginning-of-line 1)
13977 (cond
13978 (arg
13979 (org-move-to-column cc t)
13980 (insert ":\n")
13981 (forward-line -1))
13982 ((and off (looking-at re))
13983 (replace-match "" t t nil 1))
13984 ((not off) (org-move-to-column cc t) (insert ":")))
13985 (forward-line 1)))
13986 (save-excursion
13987 (org-back-to-heading)
13988 (if (looking-at (concat outline-regexp
13989 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13990 (replace-match "" t t nil 1)
13991 (if (looking-at outline-regexp)
13992 (progn
13993 (goto-char (match-end 0))
13994 (insert org-quote-string " "))))))))
13996 ;;;; Functions extending outline functionality
13998 (defun org-beginning-of-line (&optional arg)
13999 "Go to the beginning of the current line. If that is invisible, continue
14000 to a visible line beginning. This makes the function of C-a more intuitive.
14001 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14002 first attempt, and only move to after the tags when the cursor is already
14003 beyond the end of the headline."
14004 (interactive "P")
14005 (let ((pos (point)) refpos)
14006 (beginning-of-line 1)
14007 (if (bobp)
14009 (backward-char 1)
14010 (if (org-invisible-p)
14011 (while (and (not (bobp)) (org-invisible-p))
14012 (backward-char 1)
14013 (beginning-of-line 1))
14014 (forward-char 1)))
14015 (when org-special-ctrl-a/e
14016 (cond
14017 ((and (looking-at org-complex-heading-regexp)
14018 (= (char-after (match-end 1)) ?\ ))
14019 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14020 (point-at-eol)))
14021 (goto-char
14022 (if (eq org-special-ctrl-a/e t)
14023 (cond ((> pos refpos) refpos)
14024 ((= pos (point)) refpos)
14025 (t (point)))
14026 (cond ((> pos (point)) (point))
14027 ((not (eq last-command this-command)) (point))
14028 (t refpos)))))
14029 ((org-at-item-p)
14030 (goto-char
14031 (if (eq org-special-ctrl-a/e t)
14032 (cond ((> pos (match-end 4)) (match-end 4))
14033 ((= pos (point)) (match-end 4))
14034 (t (point)))
14035 (cond ((> pos (point)) (point))
14036 ((not (eq last-command this-command)) (point))
14037 (t (match-end 4))))))))
14038 (org-no-warnings
14039 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14041 (defun org-end-of-line (&optional arg)
14042 "Go to the end of the line.
14043 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14044 first attempt, and only move to after the tags when the cursor is already
14045 beyond the end of the headline."
14046 (interactive "P")
14047 (if (or (not org-special-ctrl-a/e)
14048 (not (org-on-heading-p)))
14049 (end-of-line arg)
14050 (let ((pos (point)))
14051 (beginning-of-line 1)
14052 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14053 (if (eq org-special-ctrl-a/e t)
14054 (if (or (< pos (match-beginning 1))
14055 (= pos (match-end 0)))
14056 (goto-char (match-beginning 1))
14057 (goto-char (match-end 0)))
14058 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14059 (goto-char (match-end 0))
14060 (goto-char (match-beginning 1))))
14061 (end-of-line arg))))
14062 (org-no-warnings
14063 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14066 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14067 (define-key org-mode-map "\C-e" 'org-end-of-line)
14069 (defun org-kill-line (&optional arg)
14070 "Kill line, to tags or end of line."
14071 (interactive "P")
14072 (cond
14073 ((or (not org-special-ctrl-k)
14074 (bolp)
14075 (not (org-on-heading-p)))
14076 (call-interactively 'kill-line))
14077 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14078 (kill-region (point) (match-beginning 1))
14079 (org-set-tags nil t))
14080 (t (kill-region (point) (point-at-eol)))))
14082 (define-key org-mode-map "\C-k" 'org-kill-line)
14084 (defun org-yank (&optional arg)
14085 "Yank. If the kill is a subtree, treat it specially.
14086 This command will look at the current kill and check if is a single
14087 subtree, or a series of subtrees[1]. If it passes the test, and if the
14088 cursor is at the beginning of a line or after the stars of a currently
14089 empty headline, then the yank is handeled specially. How exactly depends
14090 on the value of the following variables, both set by default.
14092 org-yank-folded-subtrees
14093 When set, the subree(s) will be folded after insertion, but only
14094 if doing so would now swallow text after the yanked text.
14096 org-yank-adjusted-subtrees
14097 When set, the subtree will be promoted or demoted in order to
14098 fit into the local outline tree structure, which means that the level
14099 will be adjusted so that it becomes the smaller one of the two
14100 *visible* surrounding headings.
14102 Any prefix to this command will cause `yank' to be called directly with
14103 no special treatment. In particular, a simple `C-u' prefix will just
14104 plainly yank the text as it is.
14106 \[1] Basically, the test checks if the first non-white line is a heading
14107 and if there are no other headings with fewer stars."
14108 (interactive "P")
14109 (setq this-command 'yank)
14110 (if arg
14111 (call-interactively 'yank)
14112 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14113 (and (org-kill-is-subtree-p)
14114 (or (bolp)
14115 (and (looking-at "[ \t]*$")
14116 (string-match
14117 "\\`\\*+\\'"
14118 (buffer-substring (point-at-bol) (point)))))))
14119 swallowp)
14120 (cond
14121 ((and subtreep org-yank-folded-subtrees)
14122 (let ((beg (point))
14123 end)
14124 (if (and subtreep org-yank-adjusted-subtrees)
14125 (org-paste-subtree nil nil 'for-yank)
14126 (call-interactively 'yank))
14127 (setq end (point))
14128 (goto-char beg)
14129 (when (and (bolp) subtreep
14130 (not (setq swallowp
14131 (org-yank-folding-would-swallow-text beg end))))
14132 (or (looking-at outline-regexp)
14133 (re-search-forward (concat "^" outline-regexp) end t))
14134 (while (and (< (point) end) (looking-at outline-regexp))
14135 (hide-subtree)
14136 (org-cycle-show-empty-lines 'folded)
14137 (condition-case nil
14138 (outline-forward-same-level 1)
14139 (error (goto-char end)))))
14140 (when swallowp
14141 (message
14142 "Yanked text not folded because that would swallow text"))
14143 (goto-char end)
14144 (skip-chars-forward " \t\n\r")
14145 (beginning-of-line 1)
14146 (push-mark beg 'nomsg)))
14147 ((and subtreep org-yank-adjusted-subtrees)
14148 (let ((beg (point-at-bol)))
14149 (org-paste-subtree nil nil 'for-yank)
14150 (push-mark beg 'nomsg)))
14152 (call-interactively 'yank))))))
14154 (defun org-yank-folding-would-swallow-text (beg end)
14155 "Would hide-subtree at BEG swallow any text after END?"
14156 (let (level)
14157 (save-excursion
14158 (goto-char beg)
14159 (when (or (looking-at outline-regexp)
14160 (re-search-forward (concat "^" outline-regexp) end t))
14161 (setq level (org-outline-level)))
14162 (goto-char end)
14163 (skip-chars-forward " \t\r\n\v\f")
14164 (if (or (eobp)
14165 (and (bolp) (looking-at org-outline-regexp)
14166 (<= (org-outline-level) level)))
14167 nil ; Nothing would be swallowed
14168 t)))) ; something would swallow
14170 (define-key org-mode-map "\C-y" 'org-yank)
14172 (defun org-invisible-p ()
14173 "Check if point is at a character currently not visible."
14174 ;; Early versions of noutline don't have `outline-invisible-p'.
14175 (if (fboundp 'outline-invisible-p)
14176 (outline-invisible-p)
14177 (get-char-property (point) 'invisible)))
14179 (defun org-invisible-p2 ()
14180 "Check if point is at a character currently not visible."
14181 (save-excursion
14182 (if (and (eolp) (not (bobp))) (backward-char 1))
14183 ;; Early versions of noutline don't have `outline-invisible-p'.
14184 (if (fboundp 'outline-invisible-p)
14185 (outline-invisible-p)
14186 (get-char-property (point) 'invisible))))
14188 (defun org-back-to-heading (&optional invisible-ok)
14189 "Call `outline-back-to-heading', but provide a better error message."
14190 (condition-case nil
14191 (outline-back-to-heading invisible-ok)
14192 (error (error "Before first headline at position %d in buffer %s"
14193 (point) (current-buffer)))))
14195 (defalias 'org-on-heading-p 'outline-on-heading-p)
14196 (defalias 'org-at-heading-p 'outline-on-heading-p)
14197 (defun org-at-heading-or-item-p ()
14198 (or (org-on-heading-p) (org-at-item-p)))
14200 (defun org-on-target-p ()
14201 (or (org-in-regexp org-radio-target-regexp)
14202 (org-in-regexp org-target-regexp)))
14204 (defun org-up-heading-all (arg)
14205 "Move to the heading line of which the present line is a subheading.
14206 This function considers both visible and invisible heading lines.
14207 With argument, move up ARG levels."
14208 (if (fboundp 'outline-up-heading-all)
14209 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14210 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14212 (defun org-up-heading-safe ()
14213 "Move to the heading line of which the present line is a subheading.
14214 This version will not throw an error. It will return the level of the
14215 headline found, or nil if no higher level is found."
14216 (let ((pos (point)) start-level level
14217 (re (concat "^" outline-regexp)))
14218 (catch 'exit
14219 (org-back-to-heading t)
14220 (setq start-level (funcall outline-level))
14221 (if (equal start-level 1) (throw 'exit nil))
14222 (while (re-search-backward re nil t)
14223 (setq level (funcall outline-level))
14224 (if (< level start-level) (throw 'exit level)))
14225 nil)))
14227 (defun org-first-sibling-p ()
14228 "Is this heading the first child of its parents?"
14229 (interactive)
14230 (let ((re (concat "^" outline-regexp))
14231 level l)
14232 (unless (org-at-heading-p t)
14233 (error "Not at a heading"))
14234 (setq level (funcall outline-level))
14235 (save-excursion
14236 (if (not (re-search-backward re nil t))
14238 (setq l (funcall outline-level))
14239 (< l level)))))
14241 (defun org-goto-sibling (&optional previous)
14242 "Goto the next sibling, even if it is invisible.
14243 When PREVIOUS is set, go to the previous sibling instead. Returns t
14244 when a sibling was found. When none is found, return nil and don't
14245 move point."
14246 (let ((fun (if previous 're-search-backward 're-search-forward))
14247 (pos (point))
14248 (re (concat "^" outline-regexp))
14249 level l)
14250 (when (condition-case nil (org-back-to-heading t) (error nil))
14251 (setq level (funcall outline-level))
14252 (catch 'exit
14253 (or previous (forward-char 1))
14254 (while (funcall fun re nil t)
14255 (setq l (funcall outline-level))
14256 (when (< l level) (goto-char pos) (throw 'exit nil))
14257 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14258 (goto-char pos)
14259 nil))))
14261 (defun org-show-siblings ()
14262 "Show all siblings of the current headline."
14263 (save-excursion
14264 (while (org-goto-sibling) (org-flag-heading nil)))
14265 (save-excursion
14266 (while (org-goto-sibling 'previous)
14267 (org-flag-heading nil))))
14269 (defun org-show-hidden-entry ()
14270 "Show an entry where even the heading is hidden."
14271 (save-excursion
14272 (org-show-entry)))
14274 (defun org-flag-heading (flag &optional entry)
14275 "Flag the current heading. FLAG non-nil means make invisible.
14276 When ENTRY is non-nil, show the entire entry."
14277 (save-excursion
14278 (org-back-to-heading t)
14279 ;; Check if we should show the entire entry
14280 (if entry
14281 (progn
14282 (org-show-entry)
14283 (save-excursion
14284 (and (outline-next-heading)
14285 (org-flag-heading nil))))
14286 (outline-flag-region (max (point-min) (1- (point)))
14287 (save-excursion (outline-end-of-heading) (point))
14288 flag))))
14290 (defun org-forward-same-level (arg)
14291 "Move forward to the ARG'th subheading at same level as this one.
14292 Stop at the first and last subheadings of a superior heading.
14293 This is like outline-forward-same-level, but invisible headings are ok."
14294 (interactive "p")
14295 (org-back-to-heading t)
14296 (while (> arg 0)
14297 (let ((point-to-move-to (save-excursion
14298 (org-get-next-sibling))))
14299 (if point-to-move-to
14300 (progn
14301 (goto-char point-to-move-to)
14302 (setq arg (1- arg)))
14303 (progn
14304 (setq arg 0)
14305 (error "No following same-level heading"))))))
14307 (defun org-get-next-sibling ()
14308 "Move to next heading of the same level, and return point.
14309 If there is no such heading, return nil.
14310 This is like outline-next-sibling, but invisible headings are ok."
14311 (let ((level (funcall outline-level)))
14312 (outline-next-heading)
14313 (while (and (not (eobp)) (> (funcall outline-level) level))
14314 (outline-next-heading))
14315 (if (or (eobp) (< (funcall outline-level) level))
14317 (point))))
14319 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14320 ;; This is an exact copy of the original function, but it uses
14321 ;; `org-back-to-heading', to make it work also in invisible
14322 ;; trees. And is uses an invisible-OK argument.
14323 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14324 (org-back-to-heading invisible-OK)
14325 (let ((first t)
14326 (level (funcall outline-level)))
14327 (while (and (not (eobp))
14328 (or first (> (funcall outline-level) level)))
14329 (setq first nil)
14330 (outline-next-heading))
14331 (unless to-heading
14332 (if (memq (preceding-char) '(?\n ?\^M))
14333 (progn
14334 ;; Go to end of line before heading
14335 (forward-char -1)
14336 (if (memq (preceding-char) '(?\n ?\^M))
14337 ;; leave blank line before heading
14338 (forward-char -1))))))
14339 (point))
14341 (defun org-show-subtree ()
14342 "Show everything after this heading at deeper levels."
14343 (outline-flag-region
14344 (point)
14345 (save-excursion
14346 (outline-end-of-subtree) (outline-next-heading) (point))
14347 nil))
14349 (defun org-show-entry ()
14350 "Show the body directly following this heading.
14351 Show the heading too, if it is currently invisible."
14352 (interactive)
14353 (save-excursion
14354 (condition-case nil
14355 (progn
14356 (org-back-to-heading t)
14357 (outline-flag-region
14358 (max (point-min) (1- (point)))
14359 (save-excursion
14360 (re-search-forward
14361 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14362 (or (match-beginning 1) (point-max)))
14363 nil))
14364 (error nil))))
14366 (defun org-make-options-regexp (kwds)
14367 "Make a regular expression for keyword lines."
14368 (concat
14370 "#?[ \t]*\\+\\("
14371 (mapconcat 'regexp-quote kwds "\\|")
14372 "\\):[ \t]*"
14373 "\\(.+\\)"))
14375 ;; Make isearch reveal the necessary context
14376 (defun org-isearch-end ()
14377 "Reveal context after isearch exits."
14378 (when isearch-success ; only if search was successful
14379 (if (featurep 'xemacs)
14380 ;; Under XEmacs, the hook is run in the correct place,
14381 ;; we directly show the context.
14382 (org-show-context 'isearch)
14383 ;; In Emacs the hook runs *before* restoring the overlays.
14384 ;; So we have to use a one-time post-command-hook to do this.
14385 ;; (Emacs 22 has a special variable, see function `org-mode')
14386 (unless (and (boundp 'isearch-mode-end-hook-quit)
14387 isearch-mode-end-hook-quit)
14388 ;; Only when the isearch was not quitted.
14389 (org-add-hook 'post-command-hook 'org-isearch-post-command
14390 'append 'local)))))
14392 (defun org-isearch-post-command ()
14393 "Remove self from hook, and show context."
14394 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14395 (org-show-context 'isearch))
14398 ;;;; Integration with and fixes for other packages
14400 ;;; Imenu support
14402 (defvar org-imenu-markers nil
14403 "All markers currently used by Imenu.")
14404 (make-variable-buffer-local 'org-imenu-markers)
14406 (defun org-imenu-new-marker (&optional pos)
14407 "Return a new marker for use by Imenu, and remember the marker."
14408 (let ((m (make-marker)))
14409 (move-marker m (or pos (point)))
14410 (push m org-imenu-markers)
14413 (defun org-imenu-get-tree ()
14414 "Produce the index for Imenu."
14415 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14416 (setq org-imenu-markers nil)
14417 (let* ((n org-imenu-depth)
14418 (re (concat "^" outline-regexp))
14419 (subs (make-vector (1+ n) nil))
14420 (last-level 0)
14421 m tree level head)
14422 (save-excursion
14423 (save-restriction
14424 (widen)
14425 (goto-char (point-max))
14426 (while (re-search-backward re nil t)
14427 (setq level (org-reduced-level (funcall outline-level)))
14428 (when (<= level n)
14429 (looking-at org-complex-heading-regexp)
14430 (setq head (org-link-display-format
14431 (org-match-string-no-properties 4))
14432 m (org-imenu-new-marker))
14433 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14434 (if (>= level last-level)
14435 (push (cons head m) (aref subs level))
14436 (push (cons head (aref subs (1+ level))) (aref subs level))
14437 (loop for i from (1+ level) to n do (aset subs i nil)))
14438 (setq last-level level)))))
14439 (aref subs 1)))
14441 (eval-after-load "imenu"
14442 '(progn
14443 (add-hook 'imenu-after-jump-hook
14444 (lambda ()
14445 (if (eq major-mode 'org-mode)
14446 (org-show-context 'org-goto))))))
14448 (defun org-link-display-format (link)
14449 "Replace a link with either the description, or the link target
14450 if no description is present"
14451 (save-match-data
14452 (if (string-match org-bracket-link-analytic-regexp link)
14453 (replace-match (or (match-string 5 link)
14454 (concat (match-string 1 link)
14455 (match-string 3 link)))
14456 nil nil link)
14457 link)))
14459 ;; Speedbar support
14461 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14462 "Overlay marking the agenda restriction line in speedbar.")
14463 (org-overlay-put org-speedbar-restriction-lock-overlay
14464 'face 'org-agenda-restriction-lock)
14465 (org-overlay-put org-speedbar-restriction-lock-overlay
14466 'help-echo "Agendas are currently limited to this item.")
14467 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14469 (defun org-speedbar-set-agenda-restriction ()
14470 "Restrict future agenda commands to the location at point in speedbar.
14471 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14472 (interactive)
14473 (require 'org-agenda)
14474 (let (p m tp np dir txt w)
14475 (cond
14476 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14477 'org-imenu t))
14478 (setq m (get-text-property p 'org-imenu-marker))
14479 (save-excursion
14480 (save-restriction
14481 (set-buffer (marker-buffer m))
14482 (goto-char m)
14483 (org-agenda-set-restriction-lock 'subtree))))
14484 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14485 'speedbar-function 'speedbar-find-file))
14486 (setq tp (previous-single-property-change
14487 (1+ p) 'speedbar-function)
14488 np (next-single-property-change
14489 tp 'speedbar-function)
14490 dir (speedbar-line-directory)
14491 txt (buffer-substring-no-properties (or tp (point-min))
14492 (or np (point-max))))
14493 (save-excursion
14494 (save-restriction
14495 (set-buffer (find-file-noselect
14496 (let ((default-directory dir))
14497 (expand-file-name txt))))
14498 (unless (org-mode-p)
14499 (error "Cannot restrict to non-Org-mode file"))
14500 (org-agenda-set-restriction-lock 'file))))
14501 (t (error "Don't know how to restrict Org-mode's agenda")))
14502 (org-move-overlay org-speedbar-restriction-lock-overlay
14503 (point-at-bol) (point-at-eol))
14504 (setq current-prefix-arg nil)
14505 (org-agenda-maybe-redo)))
14507 (eval-after-load "speedbar"
14508 '(progn
14509 (speedbar-add-supported-extension ".org")
14510 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14511 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14512 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14513 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14514 (add-hook 'speedbar-visiting-tag-hook
14515 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14518 ;;; Fixes and Hacks for problems with other packages
14520 ;; Make flyspell not check words in links, to not mess up our keymap
14521 (defun org-mode-flyspell-verify ()
14522 "Don't let flyspell put overlays at active buttons."
14523 (not (get-text-property (point) 'keymap)))
14525 ;; Make `bookmark-jump' show the jump location if it was hidden.
14526 (eval-after-load "bookmark"
14527 '(if (boundp 'bookmark-after-jump-hook)
14528 ;; We can use the hook
14529 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14530 ;; Hook not available, use advice
14531 (defadvice bookmark-jump (after org-make-visible activate)
14532 "Make the position visible."
14533 (org-bookmark-jump-unhide))))
14535 ;; Make sure saveplace show the location if it was hidden
14536 (eval-after-load "saveplace"
14537 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14538 "Make the position visible."
14539 (org-bookmark-jump-unhide)))
14541 (defun org-bookmark-jump-unhide ()
14542 "Unhide the current position, to show the bookmark location."
14543 (and (org-mode-p)
14544 (or (org-invisible-p)
14545 (save-excursion (goto-char (max (point-min) (1- (point))))
14546 (org-invisible-p)))
14547 (org-show-context 'bookmark-jump)))
14549 ;; Make session.el ignore our circular variable
14550 (eval-after-load "session"
14551 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14553 ;;;; Experimental code
14555 (defun org-closed-in-range ()
14556 "Sparse tree of items closed in a certain time range.
14557 Still experimental, may disappear in the future."
14558 (interactive)
14559 ;; Get the time interval from the user.
14560 (let* ((time1 (time-to-seconds
14561 (org-read-date nil 'to-time nil "Starting date: ")))
14562 (time2 (time-to-seconds
14563 (org-read-date nil 'to-time nil "End date:")))
14564 ;; callback function
14565 (callback (lambda ()
14566 (let ((time
14567 (time-to-seconds
14568 (apply 'encode-time
14569 (org-parse-time-string
14570 (match-string 1))))))
14571 ;; check if time in interval
14572 (and (>= time time1) (<= time time2))))))
14573 ;; make tree, check each match with the callback
14574 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14577 ;;;; Finish up
14579 (provide 'org)
14581 (run-hooks 'org-load-hook)
14583 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14585 ;;; org.el ends here