Release 6.13
[org-mode.git] / lisp / org.el
blobd25d9c5cf5e5e9f9c695124805553be4cf966d70
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.13
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.13"
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 :value :tag) (string))
1326 (cons :tag "TODO keyword" (const :value :todo) (string))
1327 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1328 (cons :tag "Level number" (const :value :level) (integer))
1329 (cons :tag "Max Level number" (const :value :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-completion
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 The value of this variable is a string, consisting of two parts,
2641 separated by a double-colon. The first part is a filename and
2642 the second part is a headline.
2644 When the filename is omitted, archiving happens in the same file.
2645 %s in the filename will be replaced by the current file
2646 name (without the directory part). Archiving to a different file
2647 is useful to keep archived entries from contributing to the
2648 Org-mode Agenda.
2650 The archived entries will be filed as subtrees of the specified
2651 headline. When the headline is omitted, the subtrees are simply
2652 filed away at the end of the file, as top-level entries.
2654 Here are a few examples:
2655 \"%s_archive::\"
2656 If the current file is Projects.org, archive in file
2657 Projects.org_archive, as top-level trees. This is the default.
2659 \"::* Archived Tasks\"
2660 Archive in the current file, under the top-level headline
2661 \"* Archived Tasks\".
2663 \"~/org/archive.org::\"
2664 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2666 \"basement::** Finished Tasks\"
2667 Archive in file ./basement (relative path), as level 3 trees
2668 below the level 2 heading \"** Finished Tasks\".
2670 You may set this option on a per-file basis by adding to the buffer a
2671 line like
2673 #+ARCHIVE: basement::** Finished Tasks
2675 You may also define it locally for a subtree by setting an ARCHIVE property
2676 in the entry. If such a property is found in an entry, or anywhere up
2677 the hierarchy, it will be used."
2678 :group 'org-archive
2679 :type 'string)
2681 (defcustom org-archive-tag "ARCHIVE"
2682 "The tag that marks a subtree as archived.
2683 An archived subtree does not open during visibility cycling, and does
2684 not contribute to the agenda listings.
2685 After changing this, font-lock must be restarted in the relevant buffers to
2686 get the proper fontification."
2687 :group 'org-archive
2688 :group 'org-keywords
2689 :type 'string)
2691 (defcustom org-agenda-skip-archived-trees t
2692 "Non-nil means, the agenda will skip any items located in archived trees.
2693 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2694 variable is no longer recommended, you should leave it at the value t.
2695 Instead, use the key `v' to cycle the archives-mode in the agenda."
2696 :group 'org-archive
2697 :group 'org-agenda-skip
2698 :type 'boolean)
2700 (defcustom org-cycle-open-archived-trees nil
2701 "Non-nil means, `org-cycle' will open archived trees.
2702 An archived tree is a tree marked with the tag ARCHIVE.
2703 When nil, archived trees will stay folded. You can still open them with
2704 normal outline commands like `show-all', but not with the cycling commands."
2705 :group 'org-archive
2706 :group 'org-cycle
2707 :type 'boolean)
2709 (defcustom org-sparse-tree-open-archived-trees nil
2710 "Non-nil means sparse tree construction shows matches in archived trees.
2711 When nil, matches in these trees are highlighted, but the trees are kept in
2712 collapsed state."
2713 :group 'org-archive
2714 :group 'org-sparse-trees
2715 :type 'boolean)
2717 (defun org-cycle-hide-archived-subtrees (state)
2718 "Re-hide all archived subtrees after a visibility state change."
2719 (when (and (not org-cycle-open-archived-trees)
2720 (not (memq state '(overview folded))))
2721 (save-excursion
2722 (let* ((globalp (memq state '(contents all)))
2723 (beg (if globalp (point-min) (point)))
2724 (end (if globalp (point-max) (org-end-of-subtree t))))
2725 (org-hide-archived-subtrees beg end)
2726 (goto-char beg)
2727 (if (looking-at (concat ".*:" org-archive-tag ":"))
2728 (message "%s" (substitute-command-keys
2729 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2731 (defun org-force-cycle-archived ()
2732 "Cycle subtree even if it is archived."
2733 (interactive)
2734 (setq this-command 'org-cycle)
2735 (let ((org-cycle-open-archived-trees t))
2736 (call-interactively 'org-cycle)))
2738 (defun org-hide-archived-subtrees (beg end)
2739 "Re-hide all archived subtrees after a visibility state change."
2740 (save-excursion
2741 (let* ((re (concat ":" org-archive-tag ":")))
2742 (goto-char beg)
2743 (while (re-search-forward re end t)
2744 (and (org-on-heading-p) (hide-subtree))
2745 (org-end-of-subtree t)))))
2747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2749 (eval-and-compile
2750 (org-autoload "org-archive"
2751 '(org-add-archive-files org-archive-subtree
2752 org-archive-to-archive-sibling org-toggle-archive-tag)))
2754 ;; Autoload Column View Code
2756 (declare-function org-columns-number-to-string "org-colview")
2757 (declare-function org-columns-get-format-and-top-level "org-colview")
2758 (declare-function org-columns-compute "org-colview")
2760 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2761 '(org-columns-number-to-string org-columns-get-format-and-top-level
2762 org-columns-compute org-agenda-columns org-columns-remove-overlays
2763 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2765 ;; Autoload ID code
2767 (org-autoload "org-id"
2768 '(org-id-get-create org-id-new org-id-copy org-id-get
2769 org-id-get-with-outline-path-completion
2770 org-id-get-with-outline-drilling
2771 org-id-goto org-id-find))
2773 ;;; Variables for pre-computed regular expressions, all buffer local
2775 (defvar org-drawer-regexp nil
2776 "Matches first line of a hidden block.")
2777 (make-variable-buffer-local 'org-drawer-regexp)
2778 (defvar org-todo-regexp nil
2779 "Matches any of the TODO state keywords.")
2780 (make-variable-buffer-local 'org-todo-regexp)
2781 (defvar org-not-done-regexp nil
2782 "Matches any of the TODO state keywords except the last one.")
2783 (make-variable-buffer-local 'org-not-done-regexp)
2784 (defvar org-todo-line-regexp nil
2785 "Matches a headline and puts TODO state into group 2 if present.")
2786 (make-variable-buffer-local 'org-todo-line-regexp)
2787 (defvar org-complex-heading-regexp nil
2788 "Matches a headline and puts everything into groups:
2789 group 1: the stars
2790 group 2: The todo keyword, maybe
2791 group 3: Priority cookie
2792 group 4: True headline
2793 group 5: Tags")
2794 (make-variable-buffer-local 'org-complex-heading-regexp)
2795 (defvar org-todo-line-tags-regexp nil
2796 "Matches a headline and puts TODO state into group 2 if present.
2797 Also put tags into group 4 if tags are present.")
2798 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2799 (defvar org-nl-done-regexp nil
2800 "Matches newline followed by a headline with the DONE keyword.")
2801 (make-variable-buffer-local 'org-nl-done-regexp)
2802 (defvar org-looking-at-done-regexp nil
2803 "Matches the DONE keyword a point.")
2804 (make-variable-buffer-local 'org-looking-at-done-regexp)
2805 (defvar org-ds-keyword-length 12
2806 "Maximum length of the Deadline and SCHEDULED keywords.")
2807 (make-variable-buffer-local 'org-ds-keyword-length)
2808 (defvar org-deadline-regexp nil
2809 "Matches the DEADLINE keyword.")
2810 (make-variable-buffer-local 'org-deadline-regexp)
2811 (defvar org-deadline-time-regexp nil
2812 "Matches the DEADLINE keyword together with a time stamp.")
2813 (make-variable-buffer-local 'org-deadline-time-regexp)
2814 (defvar org-deadline-line-regexp nil
2815 "Matches the DEADLINE keyword and the rest of the line.")
2816 (make-variable-buffer-local 'org-deadline-line-regexp)
2817 (defvar org-scheduled-regexp nil
2818 "Matches the SCHEDULED keyword.")
2819 (make-variable-buffer-local 'org-scheduled-regexp)
2820 (defvar org-scheduled-time-regexp nil
2821 "Matches the SCHEDULED keyword together with a time stamp.")
2822 (make-variable-buffer-local 'org-scheduled-time-regexp)
2823 (defvar org-closed-time-regexp nil
2824 "Matches the CLOSED keyword together with a time stamp.")
2825 (make-variable-buffer-local 'org-closed-time-regexp)
2827 (defvar org-keyword-time-regexp nil
2828 "Matches any of the 4 keywords, together with the time stamp.")
2829 (make-variable-buffer-local 'org-keyword-time-regexp)
2830 (defvar org-keyword-time-not-clock-regexp nil
2831 "Matches any of the 3 keywords, together with the time stamp.")
2832 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2833 (defvar org-maybe-keyword-time-regexp nil
2834 "Matches a timestamp, possibly preceeded by a keyword.")
2835 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2836 (defvar org-planning-or-clock-line-re nil
2837 "Matches a line with planning or clock info.")
2838 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2840 (defconst org-plain-time-of-day-regexp
2841 (concat
2842 "\\(\\<[012]?[0-9]"
2843 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2844 "\\(--?"
2845 "\\(\\<[012]?[0-9]"
2846 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2847 "\\)?")
2848 "Regular expression to match a plain time or time range.
2849 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2850 groups carry important information:
2851 0 the full match
2852 1 the first time, range or not
2853 8 the second time, if it is a range.")
2855 (defconst org-plain-time-extension-regexp
2856 (concat
2857 "\\(\\<[012]?[0-9]"
2858 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2859 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2860 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2861 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2862 groups carry important information:
2863 0 the full match
2864 7 hours of duration
2865 9 minutes of duration")
2867 (defconst org-stamp-time-of-day-regexp
2868 (concat
2869 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2870 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2871 "\\(--?"
2872 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2873 "Regular expression to match a timestamp time or time range.
2874 After a match, the following groups carry important information:
2875 0 the full match
2876 1 date plus weekday, for backreferencing to make sure both times on same day
2877 2 the first time, range or not
2878 4 the second time, if it is a range.")
2880 (defconst org-startup-options
2881 '(("fold" org-startup-folded t)
2882 ("overview" org-startup-folded t)
2883 ("nofold" org-startup-folded nil)
2884 ("showall" org-startup-folded nil)
2885 ("content" org-startup-folded content)
2886 ("hidestars" org-hide-leading-stars t)
2887 ("showstars" org-hide-leading-stars nil)
2888 ("odd" org-odd-levels-only t)
2889 ("oddeven" org-odd-levels-only nil)
2890 ("align" org-startup-align-all-tables t)
2891 ("noalign" org-startup-align-all-tables nil)
2892 ("customtime" org-display-custom-times t)
2893 ("logdone" org-log-done time)
2894 ("lognotedone" org-log-done note)
2895 ("nologdone" org-log-done nil)
2896 ("lognoteclock-out" org-log-note-clock-out t)
2897 ("nolognoteclock-out" org-log-note-clock-out nil)
2898 ("logrepeat" org-log-repeat state)
2899 ("lognoterepeat" org-log-repeat note)
2900 ("nologrepeat" org-log-repeat nil)
2901 ("constcgs" constants-unit-system cgs)
2902 ("constSI" constants-unit-system SI))
2903 "Variable associated with STARTUP options for org-mode.
2904 Each element is a list of three items: The startup options as written
2905 in the #+STARTUP line, the corresponding variable, and the value to
2906 set this variable to if the option is found. An optional forth element PUSH
2907 means to push this value onto the list in the variable.")
2909 (defun org-set-regexps-and-options ()
2910 "Precompute regular expressions for current buffer."
2911 (when (org-mode-p)
2912 (org-set-local 'org-todo-kwd-alist nil)
2913 (org-set-local 'org-todo-key-alist nil)
2914 (org-set-local 'org-todo-key-trigger nil)
2915 (org-set-local 'org-todo-keywords-1 nil)
2916 (org-set-local 'org-done-keywords nil)
2917 (org-set-local 'org-todo-heads nil)
2918 (org-set-local 'org-todo-sets nil)
2919 (org-set-local 'org-todo-log-states nil)
2920 (org-set-local 'org-file-properties nil)
2921 (org-set-local 'org-file-tags nil)
2922 (let ((re (org-make-options-regexp
2923 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2924 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2925 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2926 (splitre "[ \t]+")
2927 kwds kws0 kwsa key log value cat arch tags const links hw dws
2928 tail sep kws1 prio props ftags drawers
2929 ext-setup-or-nil setup-contents (start 0))
2930 (save-excursion
2931 (save-restriction
2932 (widen)
2933 (goto-char (point-min))
2934 (while (or (and ext-setup-or-nil
2935 (string-match re ext-setup-or-nil start)
2936 (setq start (match-end 0)))
2937 (and (setq ext-setup-or-nil nil start 0)
2938 (re-search-forward re nil t)))
2939 (setq key (upcase (match-string 1 ext-setup-or-nil))
2940 value (org-match-string-no-properties 2 ext-setup-or-nil))
2941 (cond
2942 ((equal key "CATEGORY")
2943 (if (string-match "[ \t]+$" value)
2944 (setq value (replace-match "" t t value)))
2945 (setq cat value))
2946 ((member key '("SEQ_TODO" "TODO"))
2947 (push (cons 'sequence (org-split-string value splitre)) kwds))
2948 ((equal key "TYP_TODO")
2949 (push (cons 'type (org-split-string value splitre)) kwds))
2950 ((equal key "TAGS")
2951 (setq tags (append tags (org-split-string value splitre))))
2952 ((equal key "COLUMNS")
2953 (org-set-local 'org-columns-default-format value))
2954 ((equal key "LINK")
2955 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2956 (push (cons (match-string 1 value)
2957 (org-trim (match-string 2 value)))
2958 links)))
2959 ((equal key "PRIORITIES")
2960 (setq prio (org-split-string value " +")))
2961 ((equal key "PROPERTY")
2962 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2963 (push (cons (match-string 1 value) (match-string 2 value))
2964 props)))
2965 ((equal key "FILETAGS")
2966 (when (string-match "\\S-" value)
2967 (setq ftags
2968 (append
2969 ftags
2970 (apply 'append
2971 (mapcar (lambda (x) (org-split-string x ":"))
2972 (org-split-string value)))))))
2973 ((equal key "DRAWERS")
2974 (setq drawers (org-split-string value splitre)))
2975 ((equal key "CONSTANTS")
2976 (setq const (append const (org-split-string value splitre))))
2977 ((equal key "STARTUP")
2978 (let ((opts (org-split-string value splitre))
2979 l var val)
2980 (while (setq l (pop opts))
2981 (when (setq l (assoc l org-startup-options))
2982 (setq var (nth 1 l) val (nth 2 l))
2983 (if (not (nth 3 l))
2984 (set (make-local-variable var) val)
2985 (if (not (listp (symbol-value var)))
2986 (set (make-local-variable var) nil))
2987 (set (make-local-variable var) (symbol-value var))
2988 (add-to-list var val))))))
2989 ((equal key "ARCHIVE")
2990 (string-match " *$" value)
2991 (setq arch (replace-match "" t t value))
2992 (remove-text-properties 0 (length arch)
2993 '(face t fontified t) arch))
2994 ((equal key "SETUPFILE")
2995 (setq setup-contents (org-file-contents
2996 (expand-file-name
2997 (org-remove-double-quotes value))
2998 'noerror))
2999 (if (not ext-setup-or-nil)
3000 (setq ext-setup-or-nil setup-contents start 0)
3001 (setq ext-setup-or-nil
3002 (concat (substring ext-setup-or-nil 0 start)
3003 "\n" setup-contents "\n"
3004 (substring ext-setup-or-nil start)))))
3005 ))))
3006 (when cat
3007 (org-set-local 'org-category (intern cat))
3008 (push (cons "CATEGORY" cat) props))
3009 (when prio
3010 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3011 (setq prio (mapcar 'string-to-char prio))
3012 (org-set-local 'org-highest-priority (nth 0 prio))
3013 (org-set-local 'org-lowest-priority (nth 1 prio))
3014 (org-set-local 'org-default-priority (nth 2 prio)))
3015 (and props (org-set-local 'org-file-properties (nreverse props)))
3016 (and ftags (org-set-local 'org-file-tags ftags))
3017 (and drawers (org-set-local 'org-drawers drawers))
3018 (and arch (org-set-local 'org-archive-location arch))
3019 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3020 ;; Process the TODO keywords
3021 (unless kwds
3022 ;; Use the global values as if they had been given locally.
3023 (setq kwds (default-value 'org-todo-keywords))
3024 (if (stringp (car kwds))
3025 (setq kwds (list (cons org-todo-interpretation
3026 (default-value 'org-todo-keywords)))))
3027 (setq kwds (reverse kwds)))
3028 (setq kwds (nreverse kwds))
3029 (let (inter kws kw)
3030 (while (setq kws (pop kwds))
3031 (setq inter (pop kws) sep (member "|" kws)
3032 kws0 (delete "|" (copy-sequence kws))
3033 kwsa nil
3034 kws1 (mapcar
3035 (lambda (x)
3036 ;; 1 2
3037 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3038 (progn
3039 (setq kw (match-string 1 x)
3040 key (and (match-end 2) (match-string 2 x))
3041 log (org-extract-log-state-settings x))
3042 (push (cons kw (and key (string-to-char key))) kwsa)
3043 (and log (push log org-todo-log-states))
3045 (error "Invalid TODO keyword %s" x)))
3046 kws0)
3047 kwsa (if kwsa (append '((:startgroup))
3048 (nreverse kwsa)
3049 '((:endgroup))))
3050 hw (car kws1)
3051 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3052 tail (list inter hw (car dws) (org-last dws)))
3053 (add-to-list 'org-todo-heads hw 'append)
3054 (push kws1 org-todo-sets)
3055 (setq org-done-keywords (append org-done-keywords dws nil))
3056 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3057 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3058 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3059 (setq org-todo-sets (nreverse org-todo-sets)
3060 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3061 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3062 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3063 ;; Process the constants
3064 (when const
3065 (let (e cst)
3066 (while (setq e (pop const))
3067 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3068 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3069 (setq org-table-formula-constants-local cst)))
3071 ;; Process the tags.
3072 (when tags
3073 (let (e tgs)
3074 (while (setq e (pop tags))
3075 (cond
3076 ((equal e "{") (push '(:startgroup) tgs))
3077 ((equal e "}") (push '(:endgroup) tgs))
3078 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3079 (push (cons (match-string 1 e)
3080 (string-to-char (match-string 2 e)))
3081 tgs))
3082 (t (push (list e) tgs))))
3083 (org-set-local 'org-tag-alist nil)
3084 (while (setq e (pop tgs))
3085 (or (and (stringp (car e))
3086 (assoc (car e) org-tag-alist))
3087 (push e org-tag-alist)))))
3089 ;; Compute the regular expressions and other local variables
3090 (if (not org-done-keywords)
3091 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3092 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3093 (length org-scheduled-string)
3094 (length org-clock-string)
3095 (length org-closed-string)))
3096 org-drawer-regexp
3097 (concat "^[ \t]*:\\("
3098 (mapconcat 'regexp-quote org-drawers "\\|")
3099 "\\):[ \t]*$")
3100 org-not-done-keywords
3101 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3102 org-todo-regexp
3103 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3104 "\\|") "\\)\\>")
3105 org-not-done-regexp
3106 (concat "\\<\\("
3107 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3108 "\\)\\>")
3109 org-todo-line-regexp
3110 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3111 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3112 "\\)\\>\\)?[ \t]*\\(.*\\)")
3113 org-complex-heading-regexp
3114 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3115 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3116 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3117 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3118 org-nl-done-regexp
3119 (concat "\n\\*+[ \t]+"
3120 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3121 "\\)" "\\>")
3122 org-todo-line-tags-regexp
3123 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3124 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3125 (org-re
3126 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3127 org-looking-at-done-regexp
3128 (concat "^" "\\(?:"
3129 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3130 "\\>")
3131 org-deadline-regexp (concat "\\<" org-deadline-string)
3132 org-deadline-time-regexp
3133 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3134 org-deadline-line-regexp
3135 (concat "\\<\\(" org-deadline-string "\\).*")
3136 org-scheduled-regexp
3137 (concat "\\<" org-scheduled-string)
3138 org-scheduled-time-regexp
3139 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3140 org-closed-time-regexp
3141 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3142 org-keyword-time-regexp
3143 (concat "\\<\\(" org-scheduled-string
3144 "\\|" org-deadline-string
3145 "\\|" org-closed-string
3146 "\\|" org-clock-string "\\)"
3147 " *[[<]\\([^]>]+\\)[]>]")
3148 org-keyword-time-not-clock-regexp
3149 (concat "\\<\\(" org-scheduled-string
3150 "\\|" org-deadline-string
3151 "\\|" org-closed-string
3152 "\\)"
3153 " *[[<]\\([^]>]+\\)[]>]")
3154 org-maybe-keyword-time-regexp
3155 (concat "\\(\\<\\(" org-scheduled-string
3156 "\\|" org-deadline-string
3157 "\\|" org-closed-string
3158 "\\|" org-clock-string "\\)\\)?"
3159 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3160 org-planning-or-clock-line-re
3161 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3162 "\\|" org-deadline-string
3163 "\\|" org-closed-string "\\|" org-clock-string
3164 "\\)\\>\\)")
3166 (org-compute-latex-and-specials-regexp)
3167 (org-set-font-lock-defaults))))
3169 (defun org-file-contents (file &optional noerror)
3170 "Return the contents of FILE, as a string."
3171 (if (or (not file)
3172 (not (file-readable-p file)))
3173 (if noerror
3174 (progn
3175 (message "Cannot read file %s" file)
3176 (ding) (sit-for 2)
3178 (error "Cannot read file %s" file))
3179 (with-temp-buffer
3180 (insert-file-contents file)
3181 (buffer-string))))
3183 (defun org-extract-log-state-settings (x)
3184 "Extract the log state setting from a TODO keyword string.
3185 This will extract info from a string like \"WAIT(w@/!)\"."
3186 (let (kw key log1 log2)
3187 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3188 (setq kw (match-string 1 x)
3189 key (and (match-end 2) (match-string 2 x))
3190 log1 (and (match-end 3) (match-string 3 x))
3191 log2 (and (match-end 4) (match-string 4 x)))
3192 (and (or log1 log2)
3193 (list kw
3194 (and log1 (if (equal log1 "!") 'time 'note))
3195 (and log2 (if (equal log2 "!") 'time 'note)))))))
3197 (defun org-remove-keyword-keys (list)
3198 "Remove a pair of parenthesis at the end of each string in LIST."
3199 (mapcar (lambda (x)
3200 (if (string-match "(.*)$" x)
3201 (substring x 0 (match-beginning 0))
3203 list))
3205 ;; FIXME: this could be done much better, using second characters etc.
3206 (defun org-assign-fast-keys (alist)
3207 "Assign fast keys to a keyword-key alist.
3208 Respect keys that are already there."
3209 (let (new e k c c1 c2 (char ?a))
3210 (while (setq e (pop alist))
3211 (cond
3212 ((equal e '(:startgroup)) (push e new))
3213 ((equal e '(:endgroup)) (push e new))
3215 (setq k (car e) c2 nil)
3216 (if (cdr e)
3217 (setq c (cdr e))
3218 ;; automatically assign a character.
3219 (setq c1 (string-to-char
3220 (downcase (substring
3221 k (if (= (string-to-char k) ?@) 1 0)))))
3222 (if (or (rassoc c1 new) (rassoc c1 alist))
3223 (while (or (rassoc char new) (rassoc char alist))
3224 (setq char (1+ char)))
3225 (setq c2 c1))
3226 (setq c (or c2 char)))
3227 (push (cons k c) new))))
3228 (nreverse new)))
3230 ;;; Some variables used in various places
3232 (defvar org-window-configuration nil
3233 "Used in various places to store a window configuration.")
3234 (defvar org-finish-function nil
3235 "Function to be called when `C-c C-c' is used.
3236 This is for getting out of special buffers like remember.")
3239 ;; FIXME: Occasionally check by commenting these, to make sure
3240 ;; no other functions uses these, forgetting to let-bind them.
3241 (defvar entry)
3242 (defvar state)
3243 (defvar last-state)
3244 (defvar date)
3245 (defvar description)
3247 ;; Defined somewhere in this file, but used before definition.
3248 (defvar org-html-entities)
3249 (defvar org-struct-menu)
3250 (defvar org-org-menu)
3251 (defvar org-tbl-menu)
3252 (defvar org-agenda-keymap)
3254 ;;;; Define the Org-mode
3256 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3257 (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."))
3260 ;; We use a before-change function to check if a table might need
3261 ;; an update.
3262 (defvar org-table-may-need-update t
3263 "Indicates that a table might need an update.
3264 This variable is set by `org-before-change-function'.
3265 `org-table-align' sets it back to nil.")
3266 (defun org-before-change-function (beg end)
3267 "Every change indicates that a table might need an update."
3268 (setq org-table-may-need-update t))
3269 (defvar org-mode-map)
3270 (defvar org-mode-hook nil)
3271 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3272 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3273 (defvar org-table-buffer-is-an nil)
3274 (defconst org-outline-regexp "\\*+ ")
3276 ;;;###autoload
3277 (define-derived-mode org-mode outline-mode "Org"
3278 "Outline-based notes management and organizer, alias
3279 \"Carsten's outline-mode for keeping track of everything.\"
3281 Org-mode develops organizational tasks around a NOTES file which
3282 contains information about projects as plain text. Org-mode is
3283 implemented on top of outline-mode, which is ideal to keep the content
3284 of large files well structured. It supports ToDo items, deadlines and
3285 time stamps, which magically appear in the diary listing of the Emacs
3286 calendar. Tables are easily created with a built-in table editor.
3287 Plain text URL-like links connect to websites, emails (VM), Usenet
3288 messages (Gnus), BBDB entries, and any files related to the project.
3289 For printing and sharing of notes, an Org-mode file (or a part of it)
3290 can be exported as a structured ASCII or HTML file.
3292 The following commands are available:
3294 \\{org-mode-map}"
3296 ;; Get rid of Outline menus, they are not needed
3297 ;; Need to do this here because define-derived-mode sets up
3298 ;; the keymap so late. Still, it is a waste to call this each time
3299 ;; we switch another buffer into org-mode.
3300 (if (featurep 'xemacs)
3301 (when (boundp 'outline-mode-menu-heading)
3302 ;; Assume this is Greg's port, it used easymenu
3303 (easy-menu-remove outline-mode-menu-heading)
3304 (easy-menu-remove outline-mode-menu-show)
3305 (easy-menu-remove outline-mode-menu-hide))
3306 (define-key org-mode-map [menu-bar headings] 'undefined)
3307 (define-key org-mode-map [menu-bar hide] 'undefined)
3308 (define-key org-mode-map [menu-bar show] 'undefined))
3310 (org-load-modules-maybe)
3311 (easy-menu-add org-org-menu)
3312 (easy-menu-add org-tbl-menu)
3313 (org-install-agenda-files-menu)
3314 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3315 (org-add-to-invisibility-spec '(org-cwidth))
3316 (when (featurep 'xemacs)
3317 (org-set-local 'line-move-ignore-invisible t))
3318 (org-set-local 'outline-regexp org-outline-regexp)
3319 (org-set-local 'outline-level 'org-outline-level)
3320 (when (and org-ellipsis
3321 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3322 (fboundp 'make-glyph-code))
3323 (unless org-display-table
3324 (setq org-display-table (make-display-table)))
3325 (set-display-table-slot
3326 org-display-table 4
3327 (vconcat (mapcar
3328 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3329 org-ellipsis)))
3330 (if (stringp org-ellipsis) org-ellipsis "..."))))
3331 (setq buffer-display-table org-display-table))
3332 (org-set-regexps-and-options)
3333 ;; Calc embedded
3334 (org-set-local 'calc-embedded-open-mode "# ")
3335 (modify-syntax-entry ?# "<")
3336 (modify-syntax-entry ?@ "w")
3337 (if org-startup-truncated (setq truncate-lines t))
3338 (org-set-local 'font-lock-unfontify-region-function
3339 'org-unfontify-region)
3340 ;; Activate before-change-function
3341 (org-set-local 'org-table-may-need-update t)
3342 (org-add-hook 'before-change-functions 'org-before-change-function nil
3343 'local)
3344 ;; Check for running clock before killing a buffer
3345 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3346 ;; Paragraphs and auto-filling
3347 (org-set-autofill-regexps)
3348 (setq indent-line-function 'org-indent-line-function)
3349 (org-update-radio-target-regexp)
3351 ;; Comment characters
3352 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3353 (org-set-local 'comment-padding " ")
3355 ;; Align options lines
3356 (org-set-local
3357 'align-mode-rules-list
3358 '((org-in-buffer-settings
3359 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3360 (modes . '(org-mode)))))
3362 ;; Imenu
3363 (org-set-local 'imenu-create-index-function
3364 'org-imenu-get-tree)
3366 ;; Make isearch reveal context
3367 (if (or (featurep 'xemacs)
3368 (not (boundp 'outline-isearch-open-invisible-function)))
3369 ;; Emacs 21 and XEmacs make use of the hook
3370 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3371 ;; Emacs 22 deals with this through a special variable
3372 (org-set-local 'outline-isearch-open-invisible-function
3373 (lambda (&rest ignore) (org-show-context 'isearch))))
3375 ;; If empty file that did not turn on org-mode automatically, make it to.
3376 (if (and org-insert-mode-line-in-empty-file
3377 (interactive-p)
3378 (= (point-min) (point-max)))
3379 (insert "# -*- mode: org -*-\n\n"))
3381 (unless org-inhibit-startup
3382 (when org-startup-align-all-tables
3383 (let ((bmp (buffer-modified-p)))
3384 (org-table-map-tables 'org-table-align)
3385 (set-buffer-modified-p bmp)))
3386 (org-set-startup-visibility)))
3388 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3390 (defun org-current-time ()
3391 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3392 (if (> (car org-time-stamp-rounding-minutes) 1)
3393 (let ((r (car org-time-stamp-rounding-minutes))
3394 (time (decode-time)))
3395 (apply 'encode-time
3396 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3397 (nthcdr 2 time))))
3398 (current-time)))
3400 ;;;; Font-Lock stuff, including the activators
3402 (defvar org-mouse-map (make-sparse-keymap))
3403 (org-defkey org-mouse-map
3404 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3405 (org-defkey org-mouse-map
3406 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3407 (when org-mouse-1-follows-link
3408 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3409 (when org-tab-follows-link
3410 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3411 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3412 (when org-return-follows-link
3413 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3414 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3416 (require 'font-lock)
3418 (defconst org-non-link-chars "]\t\n\r<>")
3419 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3420 "shell" "elisp"))
3421 (defvar org-link-types-re nil
3422 "Matches a link that has a url-like prefix like \"http:\"")
3423 (defvar org-link-re-with-space nil
3424 "Matches a link with spaces, optional angular brackets around it.")
3425 (defvar org-link-re-with-space2 nil
3426 "Matches a link with spaces, optional angular brackets around it.")
3427 (defvar org-link-re-with-space3 nil
3428 "Matches a link with spaces, only for internal part in bracket links.")
3429 (defvar org-angle-link-re nil
3430 "Matches link with angular brackets, spaces are allowed.")
3431 (defvar org-plain-link-re nil
3432 "Matches plain link, without spaces.")
3433 (defvar org-bracket-link-regexp nil
3434 "Matches a link in double brackets.")
3435 (defvar org-bracket-link-analytic-regexp nil
3436 "Regular expression used to analyze links.
3437 Here is what the match groups contain after a match:
3438 1: http:
3439 2: http
3440 3: path
3441 4: [desc]
3442 5: desc")
3443 (defvar org-any-link-re nil
3444 "Regular expression matching any link.")
3446 (defun org-make-link-regexps ()
3447 "Update the link regular expressions.
3448 This should be called after the variable `org-link-types' has changed."
3449 (setq org-link-types-re
3450 (concat
3451 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3452 org-link-re-with-space
3453 (concat
3454 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3455 "\\([^" org-non-link-chars " ]"
3456 "[^" org-non-link-chars "]*"
3457 "[^" org-non-link-chars " ]\\)>?")
3458 org-link-re-with-space2
3459 (concat
3460 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3461 "\\([^" org-non-link-chars " ]"
3462 "[^\t\n\r]*"
3463 "[^" org-non-link-chars " ]\\)>?")
3464 org-link-re-with-space3
3465 (concat
3466 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3467 "\\([^" org-non-link-chars " ]"
3468 "[^\t\n\r]*\\)")
3469 org-angle-link-re
3470 (concat
3471 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3472 "\\([^" org-non-link-chars " ]"
3473 "[^" org-non-link-chars "]*"
3474 "\\)>")
3475 org-plain-link-re
3476 (concat
3477 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3478 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3479 org-bracket-link-regexp
3480 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3481 org-bracket-link-analytic-regexp
3482 (concat
3483 "\\[\\["
3484 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3485 "\\([^]]+\\)"
3486 "\\]"
3487 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3488 "\\]")
3489 org-any-link-re
3490 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3491 org-angle-link-re "\\)\\|\\("
3492 org-plain-link-re "\\)")))
3494 (org-make-link-regexps)
3496 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3497 "Regular expression for fast time stamp matching.")
3498 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3499 "Regular expression for fast time stamp matching.")
3500 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3501 "Regular expression matching time strings for analysis.
3502 This one does not require the space after the date, so it can be used
3503 on a string that terminates immediately after the date.")
3504 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3505 "Regular expression matching time strings for analysis.")
3506 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3507 "Regular expression matching time stamps, with groups.")
3508 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3509 "Regular expression matching time stamps (also [..]), with groups.")
3510 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3511 "Regular expression matching a time stamp range.")
3512 (defconst org-tr-regexp-both
3513 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3514 "Regular expression matching a time stamp range.")
3515 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3516 org-ts-regexp "\\)?")
3517 "Regular expression matching a time stamp or time stamp range.")
3518 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3519 org-ts-regexp-both "\\)?")
3520 "Regular expression matching a time stamp or time stamp range.
3521 The time stamps may be either active or inactive.")
3523 (defvar org-emph-face nil)
3525 (defun org-do-emphasis-faces (limit)
3526 "Run through the buffer and add overlays to links."
3527 (let (rtn)
3528 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3529 (if (not (= (char-after (match-beginning 3))
3530 (char-after (match-beginning 4))))
3531 (progn
3532 (setq rtn t)
3533 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3534 'face
3535 (nth 1 (assoc (match-string 3)
3536 org-emphasis-alist)))
3537 (add-text-properties (match-beginning 2) (match-end 2)
3538 '(font-lock-multiline t))
3539 (when org-hide-emphasis-markers
3540 (add-text-properties (match-end 4) (match-beginning 5)
3541 '(invisible org-link))
3542 (add-text-properties (match-beginning 3) (match-end 3)
3543 '(invisible org-link)))))
3544 (backward-char 1))
3545 rtn))
3547 (defun org-emphasize (&optional char)
3548 "Insert or change an emphasis, i.e. a font like bold or italic.
3549 If there is an active region, change that region to a new emphasis.
3550 If there is no region, just insert the marker characters and position
3551 the cursor between them.
3552 CHAR should be either the marker character, or the first character of the
3553 HTML tag associated with that emphasis. If CHAR is a space, the means
3554 to remove the emphasis of the selected region.
3555 If char is not given (for example in an interactive call) it
3556 will be prompted for."
3557 (interactive)
3558 (let ((eal org-emphasis-alist) e det
3559 (erc org-emphasis-regexp-components)
3560 (prompt "")
3561 (string "") beg end move tag c s)
3562 (if (org-region-active-p)
3563 (setq beg (region-beginning) end (region-end)
3564 string (buffer-substring beg end))
3565 (setq move t))
3567 (while (setq e (pop eal))
3568 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3569 c (aref tag 0))
3570 (push (cons c (string-to-char (car e))) det)
3571 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3572 (substring tag 1)))))
3573 (setq det (nreverse det))
3574 (unless char
3575 (message "%s" (concat "Emphasis marker or tag:" prompt))
3576 (setq char (read-char-exclusive)))
3577 (setq char (or (cdr (assoc char det)) char))
3578 (if (equal char ?\ )
3579 (setq s "" move nil)
3580 (unless (assoc (char-to-string char) org-emphasis-alist)
3581 (error "No such emphasis marker: \"%c\"" char))
3582 (setq s (char-to-string char)))
3583 (while (and (> (length string) 1)
3584 (equal (substring string 0 1) (substring string -1))
3585 (assoc (substring string 0 1) org-emphasis-alist))
3586 (setq string (substring string 1 -1)))
3587 (setq string (concat s string s))
3588 (if beg (delete-region beg end))
3589 (unless (or (bolp)
3590 (string-match (concat "[" (nth 0 erc) "\n]")
3591 (char-to-string (char-before (point)))))
3592 (insert " "))
3593 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3594 (char-to-string (char-after (point))))
3595 (insert " ") (backward-char 1))
3596 (insert string)
3597 (and move (backward-char 1))))
3599 (defconst org-nonsticky-props
3600 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3603 (defun org-activate-plain-links (limit)
3604 "Run through the buffer and add overlays to links."
3605 (catch 'exit
3606 (let (f)
3607 (while (re-search-forward org-plain-link-re limit t)
3608 (setq f (get-text-property (match-beginning 0) 'face))
3609 (if (or (eq f 'org-tag)
3610 (and (listp f) (memq 'org-tag f)))
3612 (add-text-properties (match-beginning 0) (match-end 0)
3613 (list 'mouse-face 'highlight
3614 'rear-nonsticky org-nonsticky-props
3615 'keymap org-mouse-map
3617 (throw 'exit t))))))
3619 (defun org-activate-code (limit)
3620 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3621 (progn
3622 (remove-text-properties (match-beginning 0) (match-end 0)
3623 '(display t invisible t intangible t))
3624 t)))
3626 (defun org-activate-angle-links (limit)
3627 "Run through the buffer and add overlays to links."
3628 (if (re-search-forward org-angle-link-re limit t)
3629 (progn
3630 (add-text-properties (match-beginning 0) (match-end 0)
3631 (list 'mouse-face 'highlight
3632 'rear-nonsticky org-nonsticky-props
3633 'keymap org-mouse-map
3635 t)))
3637 (defun org-activate-bracket-links (limit)
3638 "Run through the buffer and add overlays to bracketed links."
3639 (if (re-search-forward org-bracket-link-regexp limit t)
3640 (let* ((help (concat "LINK: "
3641 (org-match-string-no-properties 1)))
3642 ;; FIXME: above we should remove the escapes.
3643 ;; but that requires another match, protecting match data,
3644 ;; a lot of overhead for font-lock.
3645 (ip (org-maybe-intangible
3646 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3647 'keymap org-mouse-map 'mouse-face 'highlight
3648 'font-lock-multiline t 'help-echo help)))
3649 (vp (list 'rear-nonsticky org-nonsticky-props
3650 'keymap org-mouse-map 'mouse-face 'highlight
3651 ' font-lock-multiline t 'help-echo help)))
3652 ;; We need to remove the invisible property here. Table narrowing
3653 ;; may have made some of this invisible.
3654 (remove-text-properties (match-beginning 0) (match-end 0)
3655 '(invisible nil))
3656 (if (match-end 3)
3657 (progn
3658 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3659 (add-text-properties (match-beginning 3) (match-end 3) vp)
3660 (add-text-properties (match-end 3) (match-end 0) ip))
3661 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3662 (add-text-properties (match-beginning 1) (match-end 1) vp)
3663 (add-text-properties (match-end 1) (match-end 0) ip))
3664 t)))
3666 (defun org-activate-dates (limit)
3667 "Run through the buffer and add overlays to dates."
3668 (if (re-search-forward org-tsr-regexp-both limit t)
3669 (progn
3670 (add-text-properties (match-beginning 0) (match-end 0)
3671 (list 'mouse-face 'highlight
3672 'rear-nonsticky org-nonsticky-props
3673 'keymap org-mouse-map))
3674 (when org-display-custom-times
3675 (if (match-end 3)
3676 (org-display-custom-time (match-beginning 3) (match-end 3)))
3677 (org-display-custom-time (match-beginning 1) (match-end 1)))
3678 t)))
3680 (defvar org-target-link-regexp nil
3681 "Regular expression matching radio targets in plain text.")
3682 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3683 "Regular expression matching a link target.")
3684 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3685 "Regular expression matching a radio target.")
3686 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3687 "Regular expression matching any target.")
3689 (defun org-activate-target-links (limit)
3690 "Run through the buffer and add overlays to target matches."
3691 (when org-target-link-regexp
3692 (let ((case-fold-search t))
3693 (if (re-search-forward org-target-link-regexp limit t)
3694 (progn
3695 (add-text-properties (match-beginning 0) (match-end 0)
3696 (list 'mouse-face 'highlight
3697 'rear-nonsticky org-nonsticky-props
3698 'keymap org-mouse-map
3699 'help-echo "Radio target link"
3700 'org-linked-text t))
3701 t)))))
3703 (defun org-update-radio-target-regexp ()
3704 "Find all radio targets in this file and update the regular expression."
3705 (interactive)
3706 (when (memq 'radio org-activate-links)
3707 (setq org-target-link-regexp
3708 (org-make-target-link-regexp (org-all-targets 'radio)))
3709 (org-restart-font-lock)))
3711 (defun org-hide-wide-columns (limit)
3712 (let (s e)
3713 (setq s (text-property-any (point) (or limit (point-max))
3714 'org-cwidth t))
3715 (when s
3716 (setq e (next-single-property-change s 'org-cwidth))
3717 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3718 (goto-char e)
3719 t)))
3721 (defvar org-latex-and-specials-regexp nil
3722 "Regular expression for highlighting export special stuff.")
3723 (defvar org-match-substring-regexp)
3724 (defvar org-match-substring-with-braces-regexp)
3725 (defvar org-export-html-special-string-regexps)
3727 (defun org-compute-latex-and-specials-regexp ()
3728 "Compute regular expression for stuff treated specially by exporters."
3729 (if (not org-highlight-latex-fragments-and-specials)
3730 (org-set-local 'org-latex-and-specials-regexp nil)
3731 (require 'org-exp)
3732 (let*
3733 ((matchers (plist-get org-format-latex-options :matchers))
3734 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3735 org-latex-regexps)))
3736 (options (org-combine-plists (org-default-export-plist)
3737 (org-infile-export-plist)))
3738 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3739 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3740 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3741 (org-export-html-expand (plist-get options :expand-quoted-html))
3742 (org-export-with-special-strings (plist-get options :special-strings))
3743 (re-sub
3744 (cond
3745 ((equal org-export-with-sub-superscripts '{})
3746 (list org-match-substring-with-braces-regexp))
3747 (org-export-with-sub-superscripts
3748 (list org-match-substring-regexp))
3749 (t nil)))
3750 (re-latex
3751 (if org-export-with-LaTeX-fragments
3752 (mapcar (lambda (x) (nth 1 x)) latexs)))
3753 (re-macros
3754 (if org-export-with-TeX-macros
3755 (list (concat "\\\\"
3756 (regexp-opt
3757 (append (mapcar 'car org-html-entities)
3758 (if (boundp 'org-latex-entities)
3759 org-latex-entities nil))
3760 'words))) ; FIXME
3762 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3763 (re-special (if org-export-with-special-strings
3764 (mapcar (lambda (x) (car x))
3765 org-export-html-special-string-regexps)))
3766 (re-rest
3767 (delq nil
3768 (list
3769 (if org-export-html-expand "@<[^>\n]+>")
3770 ))))
3771 (org-set-local
3772 'org-latex-and-specials-regexp
3773 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3774 re-rest) "\\|")))))
3776 (defun org-do-latex-and-special-faces (limit)
3777 "Run through the buffer and add overlays to links."
3778 (when org-latex-and-specials-regexp
3779 (let (rtn d)
3780 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3781 limit t))
3782 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3783 'face))
3784 '(org-code org-verbatim underline)))
3785 (progn
3786 (setq rtn t
3787 d (cond ((member (char-after (1+ (match-beginning 0)))
3788 '(?_ ?^)) 1)
3789 (t 0)))
3790 (font-lock-prepend-text-property
3791 (+ d (match-beginning 0)) (match-end 0)
3792 'face 'org-latex-and-export-specials)
3793 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3794 '(font-lock-multiline t)))))
3795 rtn)))
3797 (defun org-restart-font-lock ()
3798 "Restart font-lock-mode, to force refontification."
3799 (when (and (boundp 'font-lock-mode) font-lock-mode)
3800 (font-lock-mode -1)
3801 (font-lock-mode 1)))
3803 (defun org-all-targets (&optional radio)
3804 "Return a list of all targets in this file.
3805 With optional argument RADIO, only find radio targets."
3806 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3807 rtn)
3808 (save-excursion
3809 (goto-char (point-min))
3810 (while (re-search-forward re nil t)
3811 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3812 rtn)))
3814 (defun org-make-target-link-regexp (targets)
3815 "Make regular expression matching all strings in TARGETS.
3816 The regular expression finds the targets also if there is a line break
3817 between words."
3818 (and targets
3819 (concat
3820 "\\<\\("
3821 (mapconcat
3822 (lambda (x)
3823 (while (string-match " +" x)
3824 (setq x (replace-match "\\s-+" t t x)))
3826 targets
3827 "\\|")
3828 "\\)\\>")))
3830 (defun org-activate-tags (limit)
3831 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3832 (progn
3833 (add-text-properties (match-beginning 1) (match-end 1)
3834 (list 'mouse-face 'highlight
3835 'rear-nonsticky org-nonsticky-props
3836 'keymap org-mouse-map))
3837 t)))
3839 (defun org-outline-level ()
3840 (save-excursion
3841 (looking-at outline-regexp)
3842 (if (match-beginning 1)
3843 (+ (org-get-string-indentation (match-string 1)) 1000)
3844 (1- (- (match-end 0) (match-beginning 0))))))
3846 (defvar org-font-lock-keywords nil)
3848 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3849 "Regular expression matching a property line.")
3851 (defvar org-font-lock-hook nil
3852 "Functions to be called for special font lock stuff.")
3854 (defun org-font-lock-hook (limit)
3855 (run-hook-with-args 'org-font-lock-hook limit))
3857 (defun org-set-font-lock-defaults ()
3858 (let* ((em org-fontify-emphasized-text)
3859 (lk org-activate-links)
3860 (org-font-lock-extra-keywords
3861 (list
3862 ;; Call the hook
3863 '(org-font-lock-hook)
3864 ;; Headlines
3865 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3866 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3867 ;; Table lines
3868 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3869 (1 'org-table t))
3870 ;; Table internals
3871 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3872 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3873 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3874 ;; Drawers
3875 (list org-drawer-regexp '(0 'org-special-keyword t))
3876 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3877 ;; Properties
3878 (list org-property-re
3879 '(1 'org-special-keyword t)
3880 '(3 'org-property-value t))
3881 (if org-format-transports-properties-p
3882 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3883 ;; Links
3884 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3885 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3886 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3887 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3888 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3889 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3890 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3891 '(org-hide-wide-columns (0 nil append))
3892 ;; TODO lines
3893 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3894 '(1 (org-get-todo-face 1) t))
3895 ;; DONE
3896 (if org-fontify-done-headline
3897 (list (concat "^[*]+ +\\<\\("
3898 (mapconcat 'regexp-quote org-done-keywords "\\|")
3899 "\\)\\(.*\\)")
3900 '(2 'org-headline-done t))
3901 nil)
3902 ;; Priorities
3903 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3904 ;; Special keywords
3905 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3906 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3907 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3908 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3909 ;; Emphasis
3910 (if em
3911 (if (featurep 'xemacs)
3912 '(org-do-emphasis-faces (0 nil append))
3913 '(org-do-emphasis-faces)))
3914 ;; Checkboxes
3915 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3916 2 'bold prepend)
3917 (if org-provide-checkbox-statistics
3918 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3919 (0 (org-get-checkbox-statistics-face) t)))
3920 ;; Description list items
3921 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3922 2 'bold prepend)
3923 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3924 '(1 'org-archived prepend))
3925 ;; Specials
3926 '(org-do-latex-and-special-faces)
3927 ;; Code
3928 '(org-activate-code (1 'org-code t))
3929 ;; COMMENT
3930 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3931 "\\|" org-quote-string "\\)\\>")
3932 '(1 'org-special-keyword t))
3933 '("^#.*" (0 'font-lock-comment-face t))
3935 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3936 ;; Now set the full font-lock-keywords
3937 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3938 (org-set-local 'font-lock-defaults
3939 '(org-font-lock-keywords t nil nil backward-paragraph))
3940 (kill-local-variable 'font-lock-keywords) nil))
3942 (defvar org-m nil)
3943 (defvar org-l nil)
3944 (defvar org-f nil)
3945 (defun org-get-level-face (n)
3946 "Get the right face for match N in font-lock matching of healdines."
3947 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3948 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3949 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3950 (cond
3951 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3952 ((eq n 2) org-f)
3953 (t (if org-level-color-stars-only nil org-f))))
3955 (defun org-get-todo-face (kwd)
3956 "Get the right face for a TODO keyword KWD.
3957 If KWD is a number, get the corresponding match group."
3958 (if (numberp kwd) (setq kwd (match-string kwd)))
3959 (or (cdr (assoc kwd org-todo-keyword-faces))
3960 (and (member kwd org-done-keywords) 'org-done)
3961 'org-todo))
3963 (defun org-unfontify-region (beg end &optional maybe_loudly)
3964 "Remove fontification and activation overlays from links."
3965 (font-lock-default-unfontify-region beg end)
3966 (let* ((buffer-undo-list t)
3967 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3968 (inhibit-modification-hooks t)
3969 deactivate-mark buffer-file-name buffer-file-truename)
3970 (remove-text-properties beg end
3971 '(mouse-face t keymap t org-linked-text t
3972 invisible t intangible t))))
3974 ;;;; Visibility cycling, including org-goto and indirect buffer
3976 ;;; Cycling
3978 (defvar org-cycle-global-status nil)
3979 (make-variable-buffer-local 'org-cycle-global-status)
3980 (defvar org-cycle-subtree-status nil)
3981 (make-variable-buffer-local 'org-cycle-subtree-status)
3983 ;;;###autoload
3984 (defun org-cycle (&optional arg)
3985 "Visibility cycling for Org-mode.
3987 - When this function is called with a prefix argument, rotate the entire
3988 buffer through 3 states (global cycling)
3989 1. OVERVIEW: Show only top-level headlines.
3990 2. CONTENTS: Show all headlines of all levels, but no body text.
3991 3. SHOW ALL: Show everything.
3992 When called with two C-u C-u prefixes, switch to the startup visibility,
3993 determined by the variable `org-startup-folded', and by any VISIBILITY
3994 properties in the buffer.
3995 When called with three C-u C-u C-u prefixed, show the entire buffer,
3996 including drawers.
3998 - When point is at the beginning of a headline, rotate the subtree started
3999 by this line through 3 different states (local cycling)
4000 1. FOLDED: Only the main headline is shown.
4001 2. CHILDREN: The main headline and the direct children are shown.
4002 From this state, you can move to one of the children
4003 and zoom in further.
4004 3. SUBTREE: Show the entire subtree, including body text.
4006 - When there is a numeric prefix, go up to a heading with level ARG, do
4007 a `show-subtree' and return to the previous cursor position. If ARG
4008 is negative, go up that many levels.
4010 - When point is not at the beginning of a headline, execute the global
4011 binding for TAB, which is re-indenting the line. See the option
4012 `org-cycle-emulate-tab' for details.
4014 - Special case: if point is at the beginning of the buffer and there is
4015 no headline in line 1, this function will act as if called with prefix arg.
4016 But only if also the variable `org-cycle-global-at-bob' is t."
4017 (interactive "P")
4018 (org-load-modules-maybe)
4019 (let* ((outline-regexp
4020 (if (and (org-mode-p) org-cycle-include-plain-lists)
4021 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4022 outline-regexp))
4023 (bob-special (and org-cycle-global-at-bob (bobp)
4024 (not (looking-at outline-regexp))))
4025 (org-cycle-hook
4026 (if bob-special
4027 (delq 'org-optimize-window-after-visibility-change
4028 (copy-sequence org-cycle-hook))
4029 org-cycle-hook))
4030 (pos (point)))
4032 (if (or bob-special (equal arg '(4)))
4033 ;; special case: use global cycling
4034 (setq arg t))
4036 (cond
4038 ((equal arg '(16))
4039 (org-set-startup-visibility)
4040 (message "Startup visibility, plus VISIBILITY properties"))
4042 ((equal arg '(64))
4043 (show-all)
4044 (message "Entire buffer visible, including drawers"))
4046 ((org-at-table-p 'any)
4047 ;; Enter the table or move to the next field in the table
4048 (or (org-table-recognize-table.el)
4049 (progn
4050 (if arg (org-table-edit-field t)
4051 (org-table-justify-field-maybe)
4052 (call-interactively 'org-table-next-field)))))
4054 ((eq arg t) ;; Global cycling
4056 (cond
4057 ((and (eq last-command this-command)
4058 (eq org-cycle-global-status 'overview))
4059 ;; We just created the overview - now do table of contents
4060 ;; This can be slow in very large buffers, so indicate action
4061 (message "CONTENTS...")
4062 (org-content)
4063 (message "CONTENTS...done")
4064 (setq org-cycle-global-status 'contents)
4065 (run-hook-with-args 'org-cycle-hook 'contents))
4067 ((and (eq last-command this-command)
4068 (eq org-cycle-global-status 'contents))
4069 ;; We just showed the table of contents - now show everything
4070 (show-all)
4071 (message "SHOW ALL")
4072 (setq org-cycle-global-status 'all)
4073 (run-hook-with-args 'org-cycle-hook 'all))
4076 ;; Default action: go to overview
4077 (org-overview)
4078 (message "OVERVIEW")
4079 (setq org-cycle-global-status 'overview)
4080 (run-hook-with-args 'org-cycle-hook 'overview))))
4082 ((and org-drawers org-drawer-regexp
4083 (save-excursion
4084 (beginning-of-line 1)
4085 (looking-at org-drawer-regexp)))
4086 ;; Toggle block visibility
4087 (org-flag-drawer
4088 (not (get-char-property (match-end 0) 'invisible))))
4090 ((integerp arg)
4091 ;; Show-subtree, ARG levels up from here.
4092 (save-excursion
4093 (org-back-to-heading)
4094 (outline-up-heading (if (< arg 0) (- arg)
4095 (- (funcall outline-level) arg)))
4096 (org-show-subtree)))
4098 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4099 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4100 ;; At a heading: rotate between three different views
4101 (org-back-to-heading)
4102 (let ((goal-column 0) eoh eol eos)
4103 ;; First, some boundaries
4104 (save-excursion
4105 (org-back-to-heading)
4106 (save-excursion
4107 (beginning-of-line 2)
4108 (while (and (not (eobp)) ;; this is like `next-line'
4109 (get-char-property (1- (point)) 'invisible))
4110 (beginning-of-line 2)) (setq eol (point)))
4111 (outline-end-of-heading) (setq eoh (point))
4112 (org-end-of-subtree t)
4113 (unless (eobp)
4114 (skip-chars-forward " \t\n")
4115 (beginning-of-line 1) ; in case this is an item
4117 (setq eos (1- (point))))
4118 ;; Find out what to do next and set `this-command'
4119 (cond
4120 ((= eos eoh)
4121 ;; Nothing is hidden behind this heading
4122 (message "EMPTY ENTRY")
4123 (setq org-cycle-subtree-status nil)
4124 (save-excursion
4125 (goto-char eos)
4126 (outline-next-heading)
4127 (if (org-invisible-p) (org-flag-heading nil))))
4128 ((or (>= eol eos)
4129 (not (string-match "\\S-" (buffer-substring eol eos))))
4130 ;; Entire subtree is hidden in one line: open it
4131 (org-show-entry)
4132 (show-children)
4133 (message "CHILDREN")
4134 (save-excursion
4135 (goto-char eos)
4136 (outline-next-heading)
4137 (if (org-invisible-p) (org-flag-heading nil)))
4138 (setq org-cycle-subtree-status 'children)
4139 (run-hook-with-args 'org-cycle-hook 'children))
4140 ((and (eq last-command this-command)
4141 (eq org-cycle-subtree-status 'children))
4142 ;; We just showed the children, now show everything.
4143 (org-show-subtree)
4144 (message "SUBTREE")
4145 (setq org-cycle-subtree-status 'subtree)
4146 (run-hook-with-args 'org-cycle-hook 'subtree))
4148 ;; Default action: hide the subtree.
4149 (hide-subtree)
4150 (message "FOLDED")
4151 (setq org-cycle-subtree-status 'folded)
4152 (run-hook-with-args 'org-cycle-hook 'folded)))))
4154 ;; TAB emulation and template completion
4155 (buffer-read-only (org-back-to-heading))
4157 ((org-try-structure-completion))
4159 ((org-try-cdlatex-tab))
4161 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4162 (or (not (bolp))
4163 (not (looking-at outline-regexp))))
4164 (call-interactively (global-key-binding "\t")))
4166 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4167 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4168 (or (and (eq org-cycle-emulate-tab 'white)
4169 (= (match-end 0) (point-at-eol)))
4170 (and (eq org-cycle-emulate-tab 'whitestart)
4171 (>= (match-end 0) pos))))
4173 (eq org-cycle-emulate-tab t))
4174 (call-interactively (global-key-binding "\t")))
4176 (t (save-excursion
4177 (org-back-to-heading)
4178 (org-cycle))))))
4180 ;;;###autoload
4181 (defun org-global-cycle (&optional arg)
4182 "Cycle the global visibility. For details see `org-cycle'.
4183 With C-u prefix arg, switch to startup visibility.
4184 With a numeric prefix, show all headlines up to that level."
4185 (interactive "P")
4186 (let ((org-cycle-include-plain-lists
4187 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4188 (cond
4189 ((integerp arg)
4190 (show-all)
4191 (hide-sublevels arg)
4192 (setq org-cycle-global-status 'contents))
4193 ((equal arg '(4))
4194 (org-set-startup-visibility)
4195 (message "Startup visibility, plus VISIBILITY properties."))
4197 (org-cycle '(4))))))
4199 (defun org-set-startup-visibility ()
4200 "Set the visibility required by startup options and properties."
4201 (cond
4202 ((eq org-startup-folded t)
4203 (org-cycle '(4)))
4204 ((eq org-startup-folded 'content)
4205 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4206 (org-cycle '(4)) (org-cycle '(4)))))
4207 (org-set-visibility-according-to-property 'no-cleanup)
4208 (org-cycle-hide-archived-subtrees 'all)
4209 (org-cycle-hide-drawers 'all)
4210 (org-cycle-show-empty-lines 'all))
4212 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4213 "Switch subtree visibilities according to :VISIBILITY: property."
4214 (interactive)
4215 (let (state)
4216 (save-excursion
4217 (goto-char (point-min))
4218 (while (re-search-forward
4219 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4220 nil t)
4221 (setq state (match-string 1))
4222 (save-excursion
4223 (org-back-to-heading t)
4224 (hide-subtree)
4225 (org-reveal)
4226 (cond
4227 ((equal state '("fold" "folded"))
4228 (hide-subtree))
4229 ((equal state "children")
4230 (org-show-hidden-entry)
4231 (show-children))
4232 ((equal state "content")
4233 (save-excursion
4234 (save-restriction
4235 (org-narrow-to-subtree)
4236 (org-content))))
4237 ((member state '("all" "showall"))
4238 (show-subtree)))))
4239 (unless no-cleanup
4240 (org-cycle-hide-archived-subtrees 'all)
4241 (org-cycle-hide-drawers 'all)
4242 (org-cycle-show-empty-lines 'all)))))
4244 (defun org-overview ()
4245 "Switch to overview mode, shoing only top-level headlines.
4246 Really, this shows all headlines with level equal or greater than the level
4247 of the first headline in the buffer. This is important, because if the
4248 first headline is not level one, then (hide-sublevels 1) gives confusing
4249 results."
4250 (interactive)
4251 (let ((level (save-excursion
4252 (goto-char (point-min))
4253 (if (re-search-forward (concat "^" outline-regexp) nil t)
4254 (progn
4255 (goto-char (match-beginning 0))
4256 (funcall outline-level))))))
4257 (and level (hide-sublevels level))))
4259 (defun org-content (&optional arg)
4260 "Show all headlines in the buffer, like a table of contents.
4261 With numerical argument N, show content up to level N."
4262 (interactive "P")
4263 (save-excursion
4264 ;; Visit all headings and show their offspring
4265 (and (integerp arg) (org-overview))
4266 (goto-char (point-max))
4267 (catch 'exit
4268 (while (and (progn (condition-case nil
4269 (outline-previous-visible-heading 1)
4270 (error (goto-char (point-min))))
4272 (looking-at outline-regexp))
4273 (if (integerp arg)
4274 (show-children (1- arg))
4275 (show-branches))
4276 (if (bobp) (throw 'exit nil))))))
4279 (defun org-optimize-window-after-visibility-change (state)
4280 "Adjust the window after a change in outline visibility.
4281 This function is the default value of the hook `org-cycle-hook'."
4282 (when (get-buffer-window (current-buffer))
4283 (cond
4284 ; ((eq state 'overview) (org-first-headline-recenter 1))
4285 ; ((eq state 'overview) (org-beginning-of-line))
4286 ((eq state 'content) nil)
4287 ((eq state 'all) nil)
4288 ((eq state 'folded) nil)
4289 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4290 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4292 (defun org-compact-display-after-subtree-move ()
4293 (let (beg end)
4294 (save-excursion
4295 (if (org-up-heading-safe)
4296 (progn
4297 (hide-subtree)
4298 (show-entry)
4299 (show-children)
4300 (org-cycle-show-empty-lines 'children)
4301 (org-cycle-hide-drawers 'children))
4302 (org-overview)))))
4304 (defun org-cycle-show-empty-lines (state)
4305 "Show empty lines above all visible headlines.
4306 The region to be covered depends on STATE when called through
4307 `org-cycle-hook'. Lisp program can use t for STATE to get the
4308 entire buffer covered. Note that an empty line is only shown if there
4309 are at least `org-cycle-separator-lines' empty lines before the headeline."
4310 (when (> org-cycle-separator-lines 0)
4311 (save-excursion
4312 (let* ((n org-cycle-separator-lines)
4313 (re (cond
4314 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4315 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4316 (t (let ((ns (number-to-string (- n 2))))
4317 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4318 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4319 beg end)
4320 (cond
4321 ((memq state '(overview contents t))
4322 (setq beg (point-min) end (point-max)))
4323 ((memq state '(children folded))
4324 (setq beg (point) end (progn (org-end-of-subtree t t)
4325 (beginning-of-line 2)
4326 (point)))))
4327 (when beg
4328 (goto-char beg)
4329 (while (re-search-forward re end t)
4330 (if (not (get-char-property (match-end 1) 'invisible))
4331 (outline-flag-region
4332 (match-beginning 1) (match-end 1) nil)))))))
4333 ;; Never hide empty lines at the end of the file.
4334 (save-excursion
4335 (goto-char (point-max))
4336 (outline-previous-heading)
4337 (outline-end-of-heading)
4338 (if (and (looking-at "[ \t\n]+")
4339 (= (match-end 0) (point-max)))
4340 (outline-flag-region (point) (match-end 0) nil))))
4342 (defun org-show-empty-lines-in-parent ()
4343 "Move to the parent and re-show empty lines before visible headlines."
4344 (save-excursion
4345 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4346 (org-cycle-show-empty-lines context))))
4348 (defun org-cycle-hide-drawers (state)
4349 "Re-hide all drawers after a visibility state change."
4350 (when (and (org-mode-p)
4351 (not (memq state '(overview folded))))
4352 (save-excursion
4353 (let* ((globalp (memq state '(contents all)))
4354 (beg (if globalp (point-min) (point)))
4355 (end (if globalp (point-max) (org-end-of-subtree t))))
4356 (goto-char beg)
4357 (while (re-search-forward org-drawer-regexp end t)
4358 (org-flag-drawer t))))))
4360 (defun org-flag-drawer (flag)
4361 (save-excursion
4362 (beginning-of-line 1)
4363 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4364 (let ((b (match-end 0))
4365 (outline-regexp org-outline-regexp))
4366 (if (re-search-forward
4367 "^[ \t]*:END:"
4368 (save-excursion (outline-next-heading) (point)) t)
4369 (outline-flag-region b (point-at-eol) flag)
4370 (error ":END: line missing"))))))
4372 (defun org-subtree-end-visible-p ()
4373 "Is the end of the current subtree visible?"
4374 (pos-visible-in-window-p
4375 (save-excursion (org-end-of-subtree t) (point))))
4377 (defun org-first-headline-recenter (&optional N)
4378 "Move cursor to the first headline and recenter the headline.
4379 Optional argument N means, put the headline into the Nth line of the window."
4380 (goto-char (point-min))
4381 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4382 (beginning-of-line)
4383 (recenter (prefix-numeric-value N))))
4385 ;;; Org-goto
4387 (defvar org-goto-window-configuration nil)
4388 (defvar org-goto-marker nil)
4389 (defvar org-goto-map
4390 (let ((map (make-sparse-keymap)))
4391 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4392 (while (setq cmd (pop cmds))
4393 (substitute-key-definition cmd cmd map global-map)))
4394 (suppress-keymap map)
4395 (org-defkey map "\C-m" 'org-goto-ret)
4396 (org-defkey map [(return)] 'org-goto-ret)
4397 (org-defkey map [(left)] 'org-goto-left)
4398 (org-defkey map [(right)] 'org-goto-right)
4399 (org-defkey map [(control ?g)] 'org-goto-quit)
4400 (org-defkey map "\C-i" 'org-cycle)
4401 (org-defkey map [(tab)] 'org-cycle)
4402 (org-defkey map [(down)] 'outline-next-visible-heading)
4403 (org-defkey map [(up)] 'outline-previous-visible-heading)
4404 (if org-goto-auto-isearch
4405 (if (fboundp 'define-key-after)
4406 (define-key-after map [t] 'org-goto-local-auto-isearch)
4407 nil)
4408 (org-defkey map "q" 'org-goto-quit)
4409 (org-defkey map "n" 'outline-next-visible-heading)
4410 (org-defkey map "p" 'outline-previous-visible-heading)
4411 (org-defkey map "f" 'outline-forward-same-level)
4412 (org-defkey map "b" 'outline-backward-same-level)
4413 (org-defkey map "u" 'outline-up-heading))
4414 (org-defkey map "/" 'org-occur)
4415 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4416 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4417 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4418 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4419 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4420 map))
4422 (defconst org-goto-help
4423 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4424 RET=jump to location [Q]uit and return to previous location
4425 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4427 (defvar org-goto-start-pos) ; dynamically scoped parameter
4429 ;; FIXME: Docstring doe not mention both interfaces
4430 (defun org-goto (&optional alternative-interface)
4431 "Look up a different location in the current file, keeping current visibility.
4433 When you want look-up or go to a different location in a document, the
4434 fastest way is often to fold the entire buffer and then dive into the tree.
4435 This method has the disadvantage, that the previous location will be folded,
4436 which may not be what you want.
4438 This command works around this by showing a copy of the current buffer
4439 in an indirect buffer, in overview mode. You can dive into the tree in
4440 that copy, use org-occur and incremental search to find a location.
4441 When pressing RET or `Q', the command returns to the original buffer in
4442 which the visibility is still unchanged. After RET is will also jump to
4443 the location selected in the indirect buffer and expose the
4444 the headline hierarchy above."
4445 (interactive "P")
4446 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4447 (org-refile-use-outline-path t)
4448 (interface
4449 (if (not alternative-interface)
4450 org-goto-interface
4451 (if (eq org-goto-interface 'outline)
4452 'outline-path-completion
4453 'outline)))
4454 (org-goto-start-pos (point))
4455 (selected-point
4456 (if (eq interface 'outline)
4457 (car (org-get-location (current-buffer) org-goto-help))
4458 (nth 3 (org-refile-get-location "Goto: ")))))
4459 (if selected-point
4460 (progn
4461 (org-mark-ring-push org-goto-start-pos)
4462 (goto-char selected-point)
4463 (if (or (org-invisible-p) (org-invisible-p2))
4464 (org-show-context 'org-goto)))
4465 (message "Quit"))))
4467 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4468 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4469 (defvar org-goto-local-auto-isearch-map) ; defined below
4471 (defun org-get-location (buf help)
4472 "Let the user select a location in the Org-mode buffer BUF.
4473 This function uses a recursive edit. It returns the selected position
4474 or nil."
4475 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4476 (isearch-hide-immediately nil)
4477 (isearch-search-fun-function
4478 (lambda () 'org-goto-local-search-headings))
4479 (org-goto-selected-point org-goto-exit-command))
4480 (save-excursion
4481 (save-window-excursion
4482 (delete-other-windows)
4483 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4484 (switch-to-buffer
4485 (condition-case nil
4486 (make-indirect-buffer (current-buffer) "*org-goto*")
4487 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4488 (with-output-to-temp-buffer "*Help*"
4489 (princ help))
4490 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4491 (setq buffer-read-only nil)
4492 (let ((org-startup-truncated t)
4493 (org-startup-folded nil)
4494 (org-startup-align-all-tables nil))
4495 (org-mode)
4496 (org-overview))
4497 (setq buffer-read-only t)
4498 (if (and (boundp 'org-goto-start-pos)
4499 (integer-or-marker-p org-goto-start-pos))
4500 (let ((org-show-hierarchy-above t)
4501 (org-show-siblings t)
4502 (org-show-following-heading t))
4503 (goto-char org-goto-start-pos)
4504 (and (org-invisible-p) (org-show-context)))
4505 (goto-char (point-min)))
4506 (org-beginning-of-line)
4507 (message "Select location and press RET")
4508 (use-local-map org-goto-map)
4509 (recursive-edit)
4511 (kill-buffer "*org-goto*")
4512 (cons org-goto-selected-point org-goto-exit-command)))
4514 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4515 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4516 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4517 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4519 (defun org-goto-local-search-headings (string bound noerror)
4520 "Search and make sure that any matches are in headlines."
4521 (catch 'return
4522 (while (if isearch-forward
4523 (search-forward string bound noerror)
4524 (search-backward string bound noerror))
4525 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4526 (and (member :headline context)
4527 (not (member :tags context))))
4528 (throw 'return (point))))))
4530 (defun org-goto-local-auto-isearch ()
4531 "Start isearch."
4532 (interactive)
4533 (goto-char (point-min))
4534 (let ((keys (this-command-keys)))
4535 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4536 (isearch-mode t)
4537 (isearch-process-search-char (string-to-char keys)))))
4539 (defun org-goto-ret (&optional arg)
4540 "Finish `org-goto' by going to the new location."
4541 (interactive "P")
4542 (setq org-goto-selected-point (point)
4543 org-goto-exit-command 'return)
4544 (throw 'exit nil))
4546 (defun org-goto-left ()
4547 "Finish `org-goto' by going to the new location."
4548 (interactive)
4549 (if (org-on-heading-p)
4550 (progn
4551 (beginning-of-line 1)
4552 (setq org-goto-selected-point (point)
4553 org-goto-exit-command 'left)
4554 (throw 'exit nil))
4555 (error "Not on a heading")))
4557 (defun org-goto-right ()
4558 "Finish `org-goto' by going to the new location."
4559 (interactive)
4560 (if (org-on-heading-p)
4561 (progn
4562 (setq org-goto-selected-point (point)
4563 org-goto-exit-command 'right)
4564 (throw 'exit nil))
4565 (error "Not on a heading")))
4567 (defun org-goto-quit ()
4568 "Finish `org-goto' without cursor motion."
4569 (interactive)
4570 (setq org-goto-selected-point nil)
4571 (setq org-goto-exit-command 'quit)
4572 (throw 'exit nil))
4574 ;;; Indirect buffer display of subtrees
4576 (defvar org-indirect-dedicated-frame nil
4577 "This is the frame being used for indirect tree display.")
4578 (defvar org-last-indirect-buffer nil)
4580 (defun org-tree-to-indirect-buffer (&optional arg)
4581 "Create indirect buffer and narrow it to current subtree.
4582 With numerical prefix ARG, go up to this level and then take that tree.
4583 If ARG is negative, go up that many levels.
4584 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4585 indirect buffer previously made with this command, to avoid proliferation of
4586 indirect buffers. However, when you call the command with a `C-u' prefix, or
4587 when `org-indirect-buffer-display' is `new-frame', the last buffer
4588 is kept so that you can work with several indirect buffers at the same time.
4589 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4590 requests that a new frame be made for the new buffer, so that the dedicated
4591 frame is not changed."
4592 (interactive "P")
4593 (let ((cbuf (current-buffer))
4594 (cwin (selected-window))
4595 (pos (point))
4596 beg end level heading ibuf)
4597 (save-excursion
4598 (org-back-to-heading t)
4599 (when (numberp arg)
4600 (setq level (org-outline-level))
4601 (if (< arg 0) (setq arg (+ level arg)))
4602 (while (> (setq level (org-outline-level)) arg)
4603 (outline-up-heading 1 t)))
4604 (setq beg (point)
4605 heading (org-get-heading))
4606 (org-end-of-subtree t) (setq end (point)))
4607 (if (and (buffer-live-p org-last-indirect-buffer)
4608 (not (eq org-indirect-buffer-display 'new-frame))
4609 (not arg))
4610 (kill-buffer org-last-indirect-buffer))
4611 (setq ibuf (org-get-indirect-buffer cbuf)
4612 org-last-indirect-buffer ibuf)
4613 (cond
4614 ((or (eq org-indirect-buffer-display 'new-frame)
4615 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4616 (select-frame (make-frame))
4617 (delete-other-windows)
4618 (switch-to-buffer ibuf)
4619 (org-set-frame-title heading))
4620 ((eq org-indirect-buffer-display 'dedicated-frame)
4621 (raise-frame
4622 (select-frame (or (and org-indirect-dedicated-frame
4623 (frame-live-p org-indirect-dedicated-frame)
4624 org-indirect-dedicated-frame)
4625 (setq org-indirect-dedicated-frame (make-frame)))))
4626 (delete-other-windows)
4627 (switch-to-buffer ibuf)
4628 (org-set-frame-title (concat "Indirect: " heading)))
4629 ((eq org-indirect-buffer-display 'current-window)
4630 (switch-to-buffer ibuf))
4631 ((eq org-indirect-buffer-display 'other-window)
4632 (pop-to-buffer ibuf))
4633 (t (error "Invalid value.")))
4634 (if (featurep 'xemacs)
4635 (save-excursion (org-mode) (turn-on-font-lock)))
4636 (narrow-to-region beg end)
4637 (show-all)
4638 (goto-char pos)
4639 (and (window-live-p cwin) (select-window cwin))))
4641 (defun org-get-indirect-buffer (&optional buffer)
4642 (setq buffer (or buffer (current-buffer)))
4643 (let ((n 1) (base (buffer-name buffer)) bname)
4644 (while (buffer-live-p
4645 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4646 (setq n (1+ n)))
4647 (condition-case nil
4648 (make-indirect-buffer buffer bname 'clone)
4649 (error (make-indirect-buffer buffer bname)))))
4651 (defun org-set-frame-title (title)
4652 "Set the title of the current frame to the string TITLE."
4653 ;; FIXME: how to name a single frame in XEmacs???
4654 (unless (featurep 'xemacs)
4655 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4657 ;;;; Structure editing
4659 ;;; Inserting headlines
4661 (defun org-insert-heading (&optional force-heading)
4662 "Insert a new heading or item with same depth at point.
4663 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4664 If point is at the beginning of a headline, insert a sibling before the
4665 current headline. If point is not at the beginning, do not split the line,
4666 but create the new headline after the current line."
4667 (interactive "P")
4668 (if (= (buffer-size) 0)
4669 (insert "\n* ")
4670 (when (or force-heading (not (org-insert-item)))
4671 (let* ((head (save-excursion
4672 (condition-case nil
4673 (progn
4674 (org-back-to-heading)
4675 (match-string 0))
4676 (error "*"))))
4677 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4678 pos hide-previous previous-pos)
4679 (cond
4680 ((and (org-on-heading-p) (bolp)
4681 (or (bobp)
4682 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4683 ;; insert before the current line
4684 (open-line (if blank 2 1)))
4685 ((and (bolp)
4686 (or (bobp)
4687 (save-excursion
4688 (backward-char 1) (not (org-invisible-p)))))
4689 ;; insert right here
4690 nil)
4692 ;; somewhere in the line
4693 (save-excursion
4694 (setq previous-pos (point-at-bol))
4695 (end-of-line)
4696 (setq hide-previous (org-invisible-p)))
4697 (and org-insert-heading-respect-content (org-show-subtree))
4698 (let ((split
4699 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4700 (save-excursion
4701 (let ((p (point)))
4702 (goto-char (point-at-bol))
4703 (and (looking-at org-complex-heading-regexp)
4704 (> p (match-beginning 4)))))))
4705 tags pos)
4706 (cond
4707 (org-insert-heading-respect-content
4708 (org-end-of-subtree nil t)
4709 (or (bolp) (newline))
4710 (open-line 1))
4711 ((org-on-heading-p)
4712 (when hide-previous
4713 (show-children)
4714 (org-show-entry))
4715 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4716 (setq tags (and (match-end 2) (match-string 2)))
4717 (and (match-end 1)
4718 (delete-region (match-beginning 1) (match-end 1)))
4719 (setq pos (point-at-bol))
4720 (or split (end-of-line 1))
4721 (delete-horizontal-space)
4722 (newline (if blank 2 1))
4723 (when tags
4724 (save-excursion
4725 (goto-char pos)
4726 (end-of-line 1)
4727 (insert " " tags)
4728 (org-set-tags nil 'align))))
4730 (or split (end-of-line 1))
4731 (newline (if blank 2 1)))))))
4732 (insert head) (just-one-space)
4733 (setq pos (point))
4734 (end-of-line 1)
4735 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4736 (when (and org-insert-heading-respect-content hide-previous)
4737 (save-excursion
4738 (goto-char previous-pos)
4739 (hide-subtree)))
4740 (run-hooks 'org-insert-heading-hook)))))
4742 (defun org-get-heading (&optional no-tags)
4743 "Return the heading of the current entry, without the stars."
4744 (save-excursion
4745 (org-back-to-heading t)
4746 (if (looking-at
4747 (if no-tags
4748 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4749 "\\*+[ \t]+\\([^\r\n]*\\)"))
4750 (match-string 1) "")))
4752 (defun org-insert-heading-after-current ()
4753 "Insert a new heading with same level as current, after current subtree."
4754 (interactive)
4755 (org-back-to-heading)
4756 (org-insert-heading)
4757 (org-move-subtree-down)
4758 (end-of-line 1))
4760 (defun org-insert-heading-respect-content ()
4761 (interactive)
4762 (let ((org-insert-heading-respect-content t))
4763 (org-insert-heading t)))
4765 (defun org-insert-todo-heading-respect-content (&optional force-state)
4766 (interactive "P")
4767 (let ((org-insert-heading-respect-content t))
4768 (org-insert-todo-heading force-state t)))
4770 (defun org-insert-todo-heading (arg &optional force-heading)
4771 "Insert a new heading with the same level and TODO state as current heading.
4772 If the heading has no TODO state, or if the state is DONE, use the first
4773 state (TODO by default). Also with prefix arg, force first state."
4774 (interactive "P")
4775 (when (or force-heading (not (org-insert-item 'checkbox)))
4776 (org-insert-heading force-heading)
4777 (save-excursion
4778 (org-back-to-heading)
4779 (outline-previous-heading)
4780 (looking-at org-todo-line-regexp))
4781 (if (or arg
4782 (not (match-beginning 2))
4783 (member (match-string 2) org-done-keywords))
4784 (insert (car org-todo-keywords-1) " ")
4785 (insert (match-string 2) " "))
4786 (when org-provide-todo-statistics
4787 (org-update-parent-todo-statistics))))
4789 (defun org-insert-subheading (arg)
4790 "Insert a new subheading and demote it.
4791 Works for outline headings and for plain lists alike."
4792 (interactive "P")
4793 (org-insert-heading arg)
4794 (cond
4795 ((org-on-heading-p) (org-do-demote))
4796 ((org-at-item-p) (org-indent-item 1))))
4798 (defun org-insert-todo-subheading (arg)
4799 "Insert a new subheading with TODO keyword or checkbox and demote it.
4800 Works for outline headings and for plain lists alike."
4801 (interactive "P")
4802 (org-insert-todo-heading arg)
4803 (cond
4804 ((org-on-heading-p) (org-do-demote))
4805 ((org-at-item-p) (org-indent-item 1))))
4807 ;;; Promotion and Demotion
4809 (defun org-promote-subtree ()
4810 "Promote the entire subtree.
4811 See also `org-promote'."
4812 (interactive)
4813 (save-excursion
4814 (org-map-tree 'org-promote))
4815 (org-fix-position-after-promote))
4817 (defun org-demote-subtree ()
4818 "Demote the entire subtree. See `org-demote'.
4819 See also `org-promote'."
4820 (interactive)
4821 (save-excursion
4822 (org-map-tree 'org-demote))
4823 (org-fix-position-after-promote))
4826 (defun org-do-promote ()
4827 "Promote the current heading higher up the tree.
4828 If the region is active in `transient-mark-mode', promote all headings
4829 in the region."
4830 (interactive)
4831 (save-excursion
4832 (if (org-region-active-p)
4833 (org-map-region 'org-promote (region-beginning) (region-end))
4834 (org-promote)))
4835 (org-fix-position-after-promote))
4837 (defun org-do-demote ()
4838 "Demote the current heading lower down the tree.
4839 If the region is active in `transient-mark-mode', demote all headings
4840 in the region."
4841 (interactive)
4842 (save-excursion
4843 (if (org-region-active-p)
4844 (org-map-region 'org-demote (region-beginning) (region-end))
4845 (org-demote)))
4846 (org-fix-position-after-promote))
4848 (defun org-fix-position-after-promote ()
4849 "Make sure that after pro/demotion cursor position is right."
4850 (let ((pos (point)))
4851 (when (save-excursion
4852 (beginning-of-line 1)
4853 (looking-at org-todo-line-regexp)
4854 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4855 (cond ((eobp) (insert " "))
4856 ((eolp) (insert " "))
4857 ((equal (char-after) ?\ ) (forward-char 1))))))
4859 (defun org-reduced-level (l)
4860 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4862 (defun org-get-valid-level (level &optional change)
4863 "Rectify a level change under the influence of `org-odd-levels-only'
4864 LEVEL is a current level, CHANGE is by how much the level should be
4865 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4866 even level numbers will become the next higher odd number."
4867 (if org-odd-levels-only
4868 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4869 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4870 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4871 (max 1 (+ level change))))
4873 (if (boundp 'define-obsolete-function-alias)
4874 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4875 (define-obsolete-function-alias 'org-get-legal-level
4876 'org-get-valid-level)
4877 (define-obsolete-function-alias 'org-get-legal-level
4878 'org-get-valid-level "23.1")))
4880 (defun org-promote ()
4881 "Promote the current heading higher up the tree.
4882 If the region is active in `transient-mark-mode', promote all headings
4883 in the region."
4884 (org-back-to-heading t)
4885 (let* ((level (save-match-data (funcall outline-level)))
4886 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4887 (diff (abs (- level (length up-head) -1))))
4888 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4889 (replace-match up-head nil t)
4890 ;; Fixup tag positioning
4891 (and org-auto-align-tags (org-set-tags nil t))
4892 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4894 (defun org-demote ()
4895 "Demote the current heading lower down the tree.
4896 If the region is active in `transient-mark-mode', demote all headings
4897 in the region."
4898 (org-back-to-heading t)
4899 (let* ((level (save-match-data (funcall outline-level)))
4900 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4901 (diff (abs (- level (length down-head) -1))))
4902 (replace-match down-head nil t)
4903 ;; Fixup tag positioning
4904 (and org-auto-align-tags (org-set-tags nil t))
4905 (if org-adapt-indentation (org-fixup-indentation diff))))
4907 (defun org-map-tree (fun)
4908 "Call FUN for every heading underneath the current one."
4909 (org-back-to-heading)
4910 (let ((level (funcall outline-level)))
4911 (save-excursion
4912 (funcall fun)
4913 (while (and (progn
4914 (outline-next-heading)
4915 (> (funcall outline-level) level))
4916 (not (eobp)))
4917 (funcall fun)))))
4919 (defun org-map-region (fun beg end)
4920 "Call FUN for every heading between BEG and END."
4921 (let ((org-ignore-region t))
4922 (save-excursion
4923 (setq end (copy-marker end))
4924 (goto-char beg)
4925 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4926 (< (point) end))
4927 (funcall fun))
4928 (while (and (progn
4929 (outline-next-heading)
4930 (< (point) end))
4931 (not (eobp)))
4932 (funcall fun)))))
4934 (defun org-fixup-indentation (diff)
4935 "Change the indentation in the current entry by DIFF
4936 However, if any line in the current entry has no indentation, or if it
4937 would end up with no indentation after the change, nothing at all is done."
4938 (save-excursion
4939 (let ((end (save-excursion (outline-next-heading)
4940 (point-marker)))
4941 (prohibit (if (> diff 0)
4942 "^\\S-"
4943 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4944 col)
4945 (unless (save-excursion (end-of-line 1)
4946 (re-search-forward prohibit end t))
4947 (while (and (< (point) end)
4948 (re-search-forward "^[ \t]+" end t))
4949 (goto-char (match-end 0))
4950 (setq col (current-column))
4951 (if (< diff 0) (replace-match ""))
4952 (org-indent-to-column (+ diff col))))
4953 (move-marker end nil))))
4955 (defun org-convert-to-odd-levels ()
4956 "Convert an org-mode file with all levels allowed to one with odd levels.
4957 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4958 level 5 etc."
4959 (interactive)
4960 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4961 (let ((org-odd-levels-only nil) n)
4962 (save-excursion
4963 (goto-char (point-min))
4964 (while (re-search-forward "^\\*\\*+ " nil t)
4965 (setq n (- (length (match-string 0)) 2))
4966 (while (>= (setq n (1- n)) 0)
4967 (org-demote))
4968 (end-of-line 1))))))
4971 (defun org-convert-to-oddeven-levels ()
4972 "Convert an org-mode file with only odd levels to one with odd and even levels.
4973 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4974 section with an even level, conversion would destroy the structure of the file. An error
4975 is signaled in this case."
4976 (interactive)
4977 (goto-char (point-min))
4978 ;; First check if there are no even levels
4979 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4980 (org-show-context t)
4981 (error "Not all levels are odd in this file. Conversion not possible."))
4982 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4983 (let ((org-odd-levels-only nil) n)
4984 (save-excursion
4985 (goto-char (point-min))
4986 (while (re-search-forward "^\\*\\*+ " nil t)
4987 (setq n (/ (1- (length (match-string 0))) 2))
4988 (while (>= (setq n (1- n)) 0)
4989 (org-promote))
4990 (end-of-line 1))))))
4992 (defun org-tr-level (n)
4993 "Make N odd if required."
4994 (if org-odd-levels-only (1+ (/ n 2)) n))
4996 ;;; Vertical tree motion, cutting and pasting of subtrees
4998 (defun org-move-subtree-up (&optional arg)
4999 "Move the current subtree up past ARG headlines of the same level."
5000 (interactive "p")
5001 (org-move-subtree-down (- (prefix-numeric-value arg))))
5003 (defun org-move-subtree-down (&optional arg)
5004 "Move the current subtree down past ARG headlines of the same level."
5005 (interactive "p")
5006 (setq arg (prefix-numeric-value arg))
5007 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5008 'outline-get-last-sibling))
5009 (ins-point (make-marker))
5010 (cnt (abs arg))
5011 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5012 ;; Select the tree
5013 (org-back-to-heading)
5014 (setq beg0 (point))
5015 (save-excursion
5016 (setq ne-beg (org-back-over-empty-lines))
5017 (setq beg (point)))
5018 (save-match-data
5019 (save-excursion (outline-end-of-heading)
5020 (setq folded (org-invisible-p)))
5021 (outline-end-of-subtree))
5022 (outline-next-heading)
5023 (setq ne-end (org-back-over-empty-lines))
5024 (setq end (point))
5025 (goto-char beg0)
5026 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5027 ;; include less whitespace
5028 (save-excursion
5029 (goto-char beg)
5030 (forward-line (- ne-beg ne-end))
5031 (setq beg (point))))
5032 ;; Find insertion point, with error handling
5033 (while (> cnt 0)
5034 (or (and (funcall movfunc) (looking-at outline-regexp))
5035 (progn (goto-char beg0)
5036 (error "Cannot move past superior level or buffer limit")))
5037 (setq cnt (1- cnt)))
5038 (if (> arg 0)
5039 ;; Moving forward - still need to move over subtree
5040 (progn (org-end-of-subtree t t)
5041 (save-excursion
5042 (org-back-over-empty-lines)
5043 (or (bolp) (newline)))))
5044 (setq ne-ins (org-back-over-empty-lines))
5045 (move-marker ins-point (point))
5046 (setq txt (buffer-substring beg end))
5047 (org-save-markers-in-region beg end)
5048 (delete-region beg end)
5049 (outline-flag-region (1- beg) beg nil)
5050 (outline-flag-region (1- (point)) (point) nil)
5051 (let ((bbb (point)))
5052 (insert-before-markers txt)
5053 (org-reinstall-markers-in-region bbb)
5054 (move-marker ins-point bbb))
5055 (or (bolp) (insert "\n"))
5056 (setq ins-end (point))
5057 (goto-char ins-point)
5058 (org-skip-whitespace)
5059 (when (and (< arg 0)
5060 (org-first-sibling-p)
5061 (> ne-ins ne-beg))
5062 ;; Move whitespace back to beginning
5063 (save-excursion
5064 (goto-char ins-end)
5065 (let ((kill-whole-line t))
5066 (kill-line (- ne-ins ne-beg)) (point)))
5067 (insert (make-string (- ne-ins ne-beg) ?\n)))
5068 (move-marker ins-point nil)
5069 (org-compact-display-after-subtree-move)
5070 (org-show-empty-lines-in-parent)
5071 (unless folded
5072 (org-show-entry)
5073 (show-children)
5074 (org-cycle-hide-drawers 'children))))
5076 (defvar org-subtree-clip ""
5077 "Clipboard for cut and paste of subtrees.
5078 This is actually only a copy of the kill, because we use the normal kill
5079 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5081 (defvar org-subtree-clip-folded nil
5082 "Was the last copied subtree folded?
5083 This is used to fold the tree back after pasting.")
5085 (defun org-cut-subtree (&optional n)
5086 "Cut the current subtree into the clipboard.
5087 With prefix arg N, cut this many sequential subtrees.
5088 This is a short-hand for marking the subtree and then cutting it."
5089 (interactive "p")
5090 (org-copy-subtree n 'cut))
5092 (defun org-copy-subtree (&optional n cut force-store-markers)
5093 "Cut the current subtree into the clipboard.
5094 With prefix arg N, cut this many sequential subtrees.
5095 This is a short-hand for marking the subtree and then copying it.
5096 If CUT is non-nil, actually cut the subtree.
5097 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5098 of some markers in the region, even if CUT is non-nil. This is
5099 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5100 (interactive "p")
5101 (let (beg end folded (beg0 (point)))
5102 (if (interactive-p)
5103 (org-back-to-heading nil) ; take what looks like a subtree
5104 (org-back-to-heading t)) ; take what is really there
5105 (org-back-over-empty-lines)
5106 (setq beg (point))
5107 (skip-chars-forward " \t\r\n")
5108 (save-match-data
5109 (save-excursion (outline-end-of-heading)
5110 (setq folded (org-invisible-p)))
5111 (condition-case nil
5112 (outline-forward-same-level (1- n))
5113 (error nil))
5114 (org-end-of-subtree t t))
5115 (org-back-over-empty-lines)
5116 (setq end (point))
5117 (goto-char beg0)
5118 (when (> end beg)
5119 (setq org-subtree-clip-folded folded)
5120 (when (or cut force-store-markers)
5121 (org-save-markers-in-region beg end))
5122 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5123 (setq org-subtree-clip (current-kill 0))
5124 (message "%s: Subtree(s) with %d characters"
5125 (if cut "Cut" "Copied")
5126 (length org-subtree-clip)))))
5128 (defun org-paste-subtree (&optional level tree for-yank)
5129 "Paste the clipboard as a subtree, with modification of headline level.
5130 The entire subtree is promoted or demoted in order to match a new headline
5131 level.
5133 If the cursor is at the beginning of a headline, the same level as
5134 that headline is used to paste the tree
5136 If not, the new level is derived from the *visible* headings
5137 before and after the insertion point, and taken to be the inferior headline
5138 level of the two. So if the previous visible heading is level 3 and the
5139 next is level 4 (or vice versa), level 4 will be used for insertion.
5140 This makes sure that the subtree remains an independent subtree and does
5141 not swallow low level entries.
5143 You can also force a different level, either by using a numeric prefix
5144 argument, or by inserting the heading marker by hand. For example, if the
5145 cursor is after \"*****\", then the tree will be shifted to level 5.
5147 If optional TREE is given, use this text instead of the kill ring.
5149 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5150 move back over whitespace before inserting, and move point to the end of
5151 the inserted text when done."
5152 (interactive "P")
5153 (unless (org-kill-is-subtree-p tree)
5154 (error "%s"
5155 (substitute-command-keys
5156 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5157 (let* ((visp (not (org-invisible-p)))
5158 (txt (or tree (and kill-ring (current-kill 0))))
5159 (^re (concat "^\\(" outline-regexp "\\)"))
5160 (re (concat "\\(" outline-regexp "\\)"))
5161 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5163 (old-level (if (string-match ^re txt)
5164 (- (match-end 0) (match-beginning 0) 1)
5165 -1))
5166 (force-level (cond (level (prefix-numeric-value level))
5167 ((and (looking-at "[ \t]*$")
5168 (string-match
5169 ^re_ (buffer-substring
5170 (point-at-bol) (point))))
5171 (- (match-end 1) (match-beginning 1)))
5172 ((and (bolp)
5173 (looking-at org-outline-regexp))
5174 (- (match-end 0) (point) 1))
5175 (t nil)))
5176 (previous-level (save-excursion
5177 (condition-case nil
5178 (progn
5179 (outline-previous-visible-heading 1)
5180 (if (looking-at re)
5181 (- (match-end 0) (match-beginning 0) 1)
5183 (error 1))))
5184 (next-level (save-excursion
5185 (condition-case nil
5186 (progn
5187 (or (looking-at outline-regexp)
5188 (outline-next-visible-heading 1))
5189 (if (looking-at re)
5190 (- (match-end 0) (match-beginning 0) 1)
5192 (error 1))))
5193 (new-level (or force-level (max previous-level next-level)))
5194 (shift (if (or (= old-level -1)
5195 (= new-level -1)
5196 (= old-level new-level))
5198 (- new-level old-level)))
5199 (delta (if (> shift 0) -1 1))
5200 (func (if (> shift 0) 'org-demote 'org-promote))
5201 (org-odd-levels-only nil)
5202 beg end newend)
5203 ;; Remove the forced level indicator
5204 (if force-level
5205 (delete-region (point-at-bol) (point)))
5206 ;; Paste
5207 (beginning-of-line 1)
5208 (unless for-yank (org-back-over-empty-lines))
5209 (setq beg (point))
5210 (insert-before-markers txt)
5211 (unless (string-match "\n\\'" txt) (insert "\n"))
5212 (setq newend (point))
5213 (org-reinstall-markers-in-region beg)
5214 (setq end (point))
5215 (goto-char beg)
5216 (skip-chars-forward " \t\n\r")
5217 (setq beg (point))
5218 (if (and (org-invisible-p) visp)
5219 (save-excursion (outline-show-heading)))
5220 ;; Shift if necessary
5221 (unless (= shift 0)
5222 (save-restriction
5223 (narrow-to-region beg end)
5224 (while (not (= shift 0))
5225 (org-map-region func (point-min) (point-max))
5226 (setq shift (+ delta shift)))
5227 (goto-char (point-min))
5228 (setq newend (point-max))))
5229 (when (or (interactive-p) for-yank)
5230 (message "Clipboard pasted as level %d subtree" new-level))
5231 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5232 kill-ring
5233 (eq org-subtree-clip (current-kill 0))
5234 org-subtree-clip-folded)
5235 ;; The tree was folded before it was killed/copied
5236 (hide-subtree))
5237 (and for-yank (goto-char newend))))
5239 (defun org-kill-is-subtree-p (&optional txt)
5240 "Check if the current kill is an outline subtree, or a set of trees.
5241 Returns nil if kill does not start with a headline, or if the first
5242 headline level is not the largest headline level in the tree.
5243 So this will actually accept several entries of equal levels as well,
5244 which is OK for `org-paste-subtree'.
5245 If optional TXT is given, check this string instead of the current kill."
5246 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5247 (start-level (and kill
5248 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5249 org-outline-regexp "\\)")
5250 kill)
5251 (- (match-end 2) (match-beginning 2) 1)))
5252 (re (concat "^" org-outline-regexp))
5253 (start (1+ (or (match-beginning 2) -1))))
5254 (if (not start-level)
5255 (progn
5256 nil) ;; does not even start with a heading
5257 (catch 'exit
5258 (while (setq start (string-match re kill (1+ start)))
5259 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5260 (throw 'exit nil)))
5261 t))))
5263 (defvar org-markers-to-move nil
5264 "Markers that should be moved with a cut-and-paste operation.
5265 Those markers are stored together with their positions relative to
5266 the start of the region.")
5268 (defun org-save-markers-in-region (beg end)
5269 "Check markers in region.
5270 If these markers are between BEG and END, record their position relative
5271 to BEG, so that after moving the block of text, we can put the markers back
5272 into place.
5273 This function gets called just before an entry or tree gets cut from the
5274 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5275 called immediately, to move the markers with the entries."
5276 (setq org-markers-to-move nil)
5277 (when (featurep 'org-clock)
5278 (org-clock-save-markers-for-cut-and-paste beg end))
5279 (when (featurep 'org-agenda)
5280 (org-agenda-save-markers-for-cut-and-paste beg end)))
5282 (defun org-check-and-save-marker (marker beg end)
5283 "Check if MARKER is between BEG and END.
5284 If yes, remember the marker and the distance to BEG."
5285 (when (and (marker-buffer marker)
5286 (equal (marker-buffer marker) (current-buffer)))
5287 (if (and (>= marker beg) (< marker end))
5288 (push (cons marker (- marker beg)) org-markers-to-move))))
5290 (defun org-reinstall-markers-in-region (beg)
5291 "Move all remembered markers to their position relative to BEG."
5292 (mapc (lambda (x)
5293 (move-marker (car x) (+ beg (cdr x))))
5294 org-markers-to-move)
5295 (setq org-markers-to-move nil))
5297 (defun org-narrow-to-subtree ()
5298 "Narrow buffer to the current subtree."
5299 (interactive)
5300 (save-excursion
5301 (save-match-data
5302 (narrow-to-region
5303 (progn (org-back-to-heading) (point))
5304 (progn (org-end-of-subtree t) (point))))))
5307 ;;; Outline Sorting
5309 (defun org-sort (with-case)
5310 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5311 Optional argument WITH-CASE means sort case-sensitively."
5312 (interactive "P")
5313 (if (org-at-table-p)
5314 (org-call-with-arg 'org-table-sort-lines with-case)
5315 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5317 (defun org-sort-remove-invisible (s)
5318 (remove-text-properties 0 (length s) org-rm-props s)
5319 (while (string-match org-bracket-link-regexp s)
5320 (setq s (replace-match (if (match-end 2)
5321 (match-string 3 s)
5322 (match-string 1 s)) t t s)))
5325 (defvar org-priority-regexp) ; defined later in the file
5327 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5328 "Sort entries on a certain level of an outline tree.
5329 If there is an active region, the entries in the region are sorted.
5330 Else, if the cursor is before the first entry, sort the top-level items.
5331 Else, the children of the entry at point are sorted.
5333 Sorting can be alphabetically, numerically, and by date/time as given by
5334 the first time stamp in the entry. The command prompts for the sorting
5335 type unless it has been given to the function through the SORTING-TYPE
5336 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5337 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5338 called with point at the beginning of the record. It must return either
5339 a string or a number that should serve as the sorting key for that record.
5341 Comparing entries ignores case by default. However, with an optional argument
5342 WITH-CASE, the sorting considers case as well."
5343 (interactive "P")
5344 (let ((case-func (if with-case 'identity 'downcase))
5345 start beg end stars re re2
5346 txt what tmp plain-list-p)
5347 ;; Find beginning and end of region to sort
5348 (cond
5349 ((org-region-active-p)
5350 ;; we will sort the region
5351 (setq end (region-end)
5352 what "region")
5353 (goto-char (region-beginning))
5354 (if (not (org-on-heading-p)) (outline-next-heading))
5355 (setq start (point)))
5356 ((org-at-item-p)
5357 ;; we will sort this plain list
5358 (org-beginning-of-item-list) (setq start (point))
5359 (org-end-of-item-list) (setq end (point))
5360 (goto-char start)
5361 (setq plain-list-p t
5362 what "plain list"))
5363 ((or (org-on-heading-p)
5364 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5365 ;; we will sort the children of the current headline
5366 (org-back-to-heading)
5367 (setq start (point)
5368 end (progn (org-end-of-subtree t t)
5369 (org-back-over-empty-lines)
5370 (point))
5371 what "children")
5372 (goto-char start)
5373 (show-subtree)
5374 (outline-next-heading))
5376 ;; we will sort the top-level entries in this file
5377 (goto-char (point-min))
5378 (or (org-on-heading-p) (outline-next-heading))
5379 (setq start (point) end (point-max) what "top-level")
5380 (goto-char start)
5381 (show-all)))
5383 (setq beg (point))
5384 (if (>= beg end) (error "Nothing to sort"))
5386 (unless plain-list-p
5387 (looking-at "\\(\\*+\\)")
5388 (setq stars (match-string 1)
5389 re (concat "^" (regexp-quote stars) " +")
5390 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5391 txt (buffer-substring beg end))
5392 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5393 (if (and (not (equal stars "*")) (string-match re2 txt))
5394 (error "Region to sort contains a level above the first entry")))
5396 (unless sorting-type
5397 (message
5398 (if plain-list-p
5399 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5400 "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:")
5401 what)
5402 (setq sorting-type (read-char-exclusive))
5404 (and (= (downcase sorting-type) ?f)
5405 (setq getkey-func
5406 (org-ido-completing-read "Sort using function: "
5407 obarray 'fboundp t nil nil))
5408 (setq getkey-func (intern getkey-func)))
5410 (and (= (downcase sorting-type) ?r)
5411 (setq property
5412 (org-ido-completing-read "Property: "
5413 (mapcar 'list (org-buffer-property-keys t))
5414 nil t))))
5416 (message "Sorting entries...")
5418 (save-restriction
5419 (narrow-to-region start end)
5421 (let ((dcst (downcase sorting-type))
5422 (now (current-time)))
5423 (sort-subr
5424 (/= dcst sorting-type)
5425 ;; This function moves to the beginning character of the "record" to
5426 ;; be sorted.
5427 (if plain-list-p
5428 (lambda nil
5429 (if (org-at-item-p) t (goto-char (point-max))))
5430 (lambda nil
5431 (if (re-search-forward re nil t)
5432 (goto-char (match-beginning 0))
5433 (goto-char (point-max)))))
5434 ;; This function moves to the last character of the "record" being
5435 ;; sorted.
5436 (if plain-list-p
5437 'org-end-of-item
5438 (lambda nil
5439 (save-match-data
5440 (condition-case nil
5441 (outline-forward-same-level 1)
5442 (error
5443 (goto-char (point-max)))))))
5445 ;; This function returns the value that gets sorted against.
5446 (if plain-list-p
5447 (lambda nil
5448 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5449 (cond
5450 ((= dcst ?n)
5451 (string-to-number (buffer-substring (match-end 0)
5452 (point-at-eol))))
5453 ((= dcst ?a)
5454 (buffer-substring (match-end 0) (point-at-eol)))
5455 ((= dcst ?t)
5456 (if (re-search-forward org-ts-regexp
5457 (point-at-eol) t)
5458 (org-time-string-to-time (match-string 0))
5459 now))
5460 ((= dcst ?f)
5461 (if getkey-func
5462 (progn
5463 (setq tmp (funcall getkey-func))
5464 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5465 tmp)
5466 (error "Invalid key function `%s'" getkey-func)))
5467 (t (error "Invalid sorting type `%c'" sorting-type)))))
5468 (lambda nil
5469 (cond
5470 ((= dcst ?n)
5471 (if (looking-at org-complex-heading-regexp)
5472 (string-to-number (match-string 4))
5473 nil))
5474 ((= dcst ?a)
5475 (if (looking-at org-complex-heading-regexp)
5476 (funcall case-func (match-string 4))
5477 nil))
5478 ((= dcst ?t)
5479 (if (re-search-forward org-ts-regexp
5480 (save-excursion
5481 (forward-line 2)
5482 (point)) t)
5483 (org-time-string-to-time (match-string 0))
5484 now))
5485 ((= dcst ?p)
5486 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5487 (string-to-char (match-string 2))
5488 org-default-priority))
5489 ((= dcst ?r)
5490 (or (org-entry-get nil property) ""))
5491 ((= dcst ?o)
5492 (if (looking-at org-complex-heading-regexp)
5493 (- 9999 (length (member (match-string 2)
5494 org-todo-keywords-1)))))
5495 ((= dcst ?f)
5496 (if getkey-func
5497 (progn
5498 (setq tmp (funcall getkey-func))
5499 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5500 tmp)
5501 (error "Invalid key function `%s'" getkey-func)))
5502 (t (error "Invalid sorting type `%c'" sorting-type)))))
5504 (cond
5505 ((= dcst ?a) 'string<)
5506 ((= dcst ?t) 'time-less-p)
5507 (t nil)))))
5508 (message "Sorting entries...done")))
5510 (defun org-do-sort (table what &optional with-case sorting-type)
5511 "Sort TABLE of WHAT according to SORTING-TYPE.
5512 The user will be prompted for the SORTING-TYPE if the call to this
5513 function does not specify it. WHAT is only for the prompt, to indicate
5514 what is being sorted. The sorting key will be extracted from
5515 the car of the elements of the table.
5516 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5517 (unless sorting-type
5518 (message
5519 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5520 what)
5521 (setq sorting-type (read-char-exclusive)))
5522 (let ((dcst (downcase sorting-type))
5523 extractfun comparefun)
5524 ;; Define the appropriate functions
5525 (cond
5526 ((= dcst ?n)
5527 (setq extractfun 'string-to-number
5528 comparefun (if (= dcst sorting-type) '< '>)))
5529 ((= dcst ?a)
5530 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5531 (lambda(x) (downcase (org-sort-remove-invisible x))))
5532 comparefun (if (= dcst sorting-type)
5533 'string<
5534 (lambda (a b) (and (not (string< a b))
5535 (not (string= a b)))))))
5536 ((= dcst ?t)
5537 (setq extractfun
5538 (lambda (x)
5539 (if (string-match org-ts-regexp x)
5540 (time-to-seconds
5541 (org-time-string-to-time (match-string 0 x)))
5543 comparefun (if (= dcst sorting-type) '< '>)))
5544 (t (error "Invalid sorting type `%c'" sorting-type)))
5546 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5547 table)
5548 (lambda (a b) (funcall comparefun (car a) (car b))))))
5550 ;;; Editing source examples
5552 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5553 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5554 (defvar org-edit-src-force-single-line nil)
5555 (defvar org-edit-src-from-org-mode nil)
5556 (defvar org-edit-src-picture nil)
5558 (define-minor-mode org-exit-edit-mode
5559 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5561 (defun org-edit-src-code ()
5562 "Edit the source code example at point.
5563 An indirect buffer is created, and that buffer is then narrowed to the
5564 example at point and switched to the correct language mode. When done,
5565 exit by killing the buffer with \\[org-edit-src-exit]."
5566 (interactive)
5567 (let ((line (org-current-line))
5568 (case-fold-search t)
5569 (msg (substitute-command-keys
5570 "Edit, then exit with C-c ' (C-c and single quote)"))
5571 (info (org-edit-src-find-region-and-lang))
5572 (org-mode-p (eq major-mode 'org-mode))
5573 beg end lang lang-f single)
5574 (if (not info)
5576 (setq beg (nth 0 info)
5577 end (nth 1 info)
5578 lang (nth 2 info)
5579 single (nth 3 info)
5580 lang-f (intern (concat lang "-mode")))
5581 (unless (functionp lang-f)
5582 (error "No such language mode: %s" lang-f))
5583 (goto-line line)
5584 (if (get-buffer "*Org Edit Src Example*")
5585 (kill-buffer "*Org Edit Src Example*"))
5586 (switch-to-buffer (make-indirect-buffer (current-buffer)
5587 "*Org Edit Src Example*"))
5588 (narrow-to-region beg end)
5589 (remove-text-properties beg end '(display nil invisible nil
5590 intangible nil))
5591 (let ((org-inhibit-startup t))
5592 (funcall lang-f))
5593 (set (make-local-variable 'org-edit-src-force-single-line) single)
5594 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5595 (when org-mode-p
5596 (goto-char (point-min))
5597 (while (re-search-forward "^," nil t)
5598 (replace-match "")))
5599 (goto-line line)
5600 (org-exit-edit-mode)
5601 (org-set-local 'header-line-format msg)
5602 (message "%s" msg)
5603 t)))
5605 (defun org-edit-fixed-width-region ()
5606 "Edit the fixed-width ascii drawing at point.
5607 This must be a region where each line starts with ca colon followed by
5608 a space character.
5609 An indirect buffer is created, and that buffer is then narrowed to the
5610 example at point and switched to artist-mode. When done,
5611 exit by killing the buffer with \\[org-edit-src-exit]."
5612 (interactive)
5613 (let ((line (org-current-line))
5614 (case-fold-search t)
5615 (msg (substitute-command-keys
5616 "Edit, then exit with C-c ' (C-c and single quote)"))
5617 (org-mode-p (eq major-mode 'org-mode))
5618 beg end lang lang-f)
5619 (beginning-of-line 1)
5620 (if (looking-at "[ \t]*[^:\n \t]")
5622 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5623 (setq beg (point) end beg)
5624 (save-excursion
5625 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5626 (setq beg (point-at-bol 2))
5627 (setq beg (point))))
5628 (save-excursion
5629 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5630 (setq end (1- (match-beginning 0)))
5631 (setq end (point))))
5632 (goto-line line))
5633 (if (get-buffer "*Org Edit Picture*")
5634 (kill-buffer "*Org Edit Picture*"))
5635 (switch-to-buffer (make-indirect-buffer (current-buffer)
5636 "*Org Edit Picture*"))
5637 (narrow-to-region beg end)
5638 (remove-text-properties beg end '(display nil invisible nil
5639 intangible nil))
5640 (when (fboundp 'font-lock-unfontify-region)
5641 (font-lock-unfontify-region (point-min) (point-max)))
5642 (cond
5643 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5644 (fundamental-mode)
5645 (artist-mode 1))
5646 (t (funcall org-edit-fixed-width-region-mode)))
5647 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5648 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5649 (set (make-local-variable 'org-edit-src-picture) t)
5650 (goto-char (point-min))
5651 (while (re-search-forward "^[ \t]*: ?" nil t)
5652 (replace-match ""))
5653 (goto-line line)
5654 (org-exit-edit-mode)
5655 (org-set-local 'header-line-format msg)
5656 (message "%s" msg)
5657 t)))
5660 (defun org-edit-src-find-region-and-lang ()
5661 "Find the region and language for a local edit.
5662 Return a list with beginning and end of the region, a string representing
5663 the language, a switch telling of the content should be in a single line."
5664 (let ((re-list
5665 (append
5666 org-edit-src-region-extra
5668 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5669 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5670 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5671 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5672 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5673 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5674 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5675 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5676 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5677 ("^#\\+html:" "\n" "html" single-line)
5678 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5679 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5680 ("^#\\+latex:" "\n" "latex" single-line)
5681 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5682 ("^#\\+ascii:" "\n" "ascii" single-line)
5684 (pos (point))
5685 re re1 re2 single beg end lang)
5686 (catch 'exit
5687 (while (setq entry (pop re-list))
5688 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5689 single (nth 3 entry))
5690 (save-excursion
5691 (if (or (looking-at re1)
5692 (re-search-backward re1 nil t))
5693 (progn
5694 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5695 (if (and (re-search-forward re2 nil t)
5696 (>= (match-end 0) pos))
5697 (throw 'exit (list beg (match-beginning 0) lang single))))
5698 (if (or (looking-at re2)
5699 (re-search-forward re2 nil t))
5700 (progn
5701 (setq end (match-beginning 0))
5702 (if (and (re-search-backward re1 nil t)
5703 (<= (match-beginning 0) pos))
5704 (throw 'exit
5705 (list (match-end 0) end
5706 (org-edit-src-get-lang lang) single)))))))))))
5708 (defun org-edit-src-get-lang (lang)
5709 "Extract the src language."
5710 (let ((m (match-string 0)))
5711 (cond
5712 ((stringp lang) lang)
5713 ((integerp lang) (match-string lang))
5714 ((and (eq lang 'lang)
5715 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5716 (match-string 1 m))
5717 ((and (eq lang 'style)
5718 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5719 (match-string 1 m))
5720 (t "fundamental"))))
5722 (defun org-edit-src-exit ()
5723 "Exit special edit and protect problematic lines."
5724 (interactive)
5725 (unless (buffer-base-buffer (current-buffer))
5726 (error "This is not an indirect buffer, something is wrong..."))
5727 (unless (> (point-min) 1)
5728 (error "This buffer is not narrowed, something is wrong..."))
5729 (goto-char (point-min))
5730 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5731 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5732 (when (org-bound-and-true-p org-edit-src-force-single-line)
5733 (goto-char (point-min))
5734 (while (re-search-forward "\n" nil t)
5735 (replace-match " "))
5736 (goto-char (point-min))
5737 (if (looking-at "\\s-*") (replace-match " "))
5738 (if (re-search-forward "\\s-+\\'" nil t)
5739 (replace-match "")))
5740 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5741 (goto-char (point-min))
5742 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5743 (replace-match ",\\1"))
5744 (when font-lock-mode
5745 (font-lock-unfontify-region (point-min) (point-max)))
5746 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5747 (when (org-bound-and-true-p org-edit-src-picture)
5748 (untabify (point-min) (point-max))
5749 (goto-char (point-min))
5750 (while (re-search-forward "^" nil t)
5751 (replace-match ": "))
5752 (when font-lock-mode
5753 (font-lock-unfontify-region (point-min) (point-max)))
5754 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5755 (kill-buffer (current-buffer))
5756 (and (org-mode-p) (org-restart-font-lock)))
5759 ;;; The orgstruct minor mode
5761 ;; Define a minor mode which can be used in other modes in order to
5762 ;; integrate the org-mode structure editing commands.
5764 ;; This is really a hack, because the org-mode structure commands use
5765 ;; keys which normally belong to the major mode. Here is how it
5766 ;; works: The minor mode defines all the keys necessary to operate the
5767 ;; structure commands, but wraps the commands into a function which
5768 ;; tests if the cursor is currently at a headline or a plain list
5769 ;; item. If that is the case, the structure command is used,
5770 ;; temporarily setting many Org-mode variables like regular
5771 ;; expressions for filling etc. However, when any of those keys is
5772 ;; used at a different location, function uses `key-binding' to look
5773 ;; up if the key has an associated command in another currently active
5774 ;; keymap (minor modes, major mode, global), and executes that
5775 ;; command. There might be problems if any of the keys is otherwise
5776 ;; used as a prefix key.
5778 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5779 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5780 ;; addresses this by checking explicitly for both bindings.
5782 (defvar orgstruct-mode-map (make-sparse-keymap)
5783 "Keymap for the minor `orgstruct-mode'.")
5785 (defvar org-local-vars nil
5786 "List of local variables, for use by `orgstruct-mode'")
5788 ;;;###autoload
5789 (define-minor-mode orgstruct-mode
5790 "Toggle the minor more `orgstruct-mode'.
5791 This mode is for using Org-mode structure commands in other modes.
5792 The following key behave as if Org-mode was active, if the cursor
5793 is on a headline, or on a plain list item (both in the definition
5794 of Org-mode).
5796 M-up Move entry/item up
5797 M-down Move entry/item down
5798 M-left Promote
5799 M-right Demote
5800 M-S-up Move entry/item up
5801 M-S-down Move entry/item down
5802 M-S-left Promote subtree
5803 M-S-right Demote subtree
5804 M-q Fill paragraph and items like in Org-mode
5805 C-c ^ Sort entries
5806 C-c - Cycle list bullet
5807 TAB Cycle item visibility
5808 M-RET Insert new heading/item
5809 S-M-RET Insert new TODO heading / Chekbox item
5810 C-c C-c Set tags / toggle checkbox"
5811 nil " OrgStruct" nil
5812 (org-load-modules-maybe)
5813 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5815 ;;;###autoload
5816 (defun turn-on-orgstruct ()
5817 "Unconditionally turn on `orgstruct-mode'."
5818 (orgstruct-mode 1))
5820 ;;;###autoload
5821 (defun turn-on-orgstruct++ ()
5822 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5823 In addition to setting orgstruct-mode, this also exports all indentation and
5824 autofilling variables from org-mode into the buffer. Note that turning
5825 off orgstruct-mode will *not* remove these additional settings."
5826 (orgstruct-mode 1)
5827 (let (var val)
5828 (mapc
5829 (lambda (x)
5830 (when (string-match
5831 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5832 (symbol-name (car x)))
5833 (setq var (car x) val (nth 1 x))
5834 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5835 org-local-vars)))
5837 (defun orgstruct-error ()
5838 "Error when there is no default binding for a structure key."
5839 (interactive)
5840 (error "This key has no function outside structure elements"))
5842 (defun orgstruct-setup ()
5843 "Setup orgstruct keymaps."
5844 (let ((nfunc 0)
5845 (bindings
5846 (list
5847 '([(meta up)] org-metaup)
5848 '([(meta down)] org-metadown)
5849 '([(meta left)] org-metaleft)
5850 '([(meta right)] org-metaright)
5851 '([(meta shift up)] org-shiftmetaup)
5852 '([(meta shift down)] org-shiftmetadown)
5853 '([(meta shift left)] org-shiftmetaleft)
5854 '([(meta shift right)] org-shiftmetaright)
5855 '([(shift up)] org-shiftup)
5856 '([(shift down)] org-shiftdown)
5857 '([(shift left)] org-shiftleft)
5858 '([(shift right)] org-shiftright)
5859 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5860 '("\M-q" fill-paragraph)
5861 '("\C-c^" org-sort)
5862 '("\C-c-" org-cycle-list-bullet)))
5863 elt key fun cmd)
5864 (while (setq elt (pop bindings))
5865 (setq nfunc (1+ nfunc))
5866 (setq key (org-key (car elt))
5867 fun (nth 1 elt)
5868 cmd (orgstruct-make-binding fun nfunc key))
5869 (org-defkey orgstruct-mode-map key cmd))
5871 ;; Special treatment needed for TAB and RET
5872 (org-defkey orgstruct-mode-map [(tab)]
5873 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5874 (org-defkey orgstruct-mode-map "\C-i"
5875 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5877 (org-defkey orgstruct-mode-map "\M-\C-m"
5878 (orgstruct-make-binding 'org-insert-heading 105
5879 "\M-\C-m" [(meta return)]))
5880 (org-defkey orgstruct-mode-map [(meta return)]
5881 (orgstruct-make-binding 'org-insert-heading 106
5882 [(meta return)] "\M-\C-m"))
5884 (org-defkey orgstruct-mode-map [(shift meta return)]
5885 (orgstruct-make-binding 'org-insert-todo-heading 107
5886 [(meta return)] "\M-\C-m"))
5888 (unless org-local-vars
5889 (setq org-local-vars (org-get-local-variables)))
5893 (defun orgstruct-make-binding (fun n &rest keys)
5894 "Create a function for binding in the structure minor mode.
5895 FUN is the command to call inside a table. N is used to create a unique
5896 command name. KEYS are keys that should be checked in for a command
5897 to execute outside of tables."
5898 (eval
5899 (list 'defun
5900 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5901 '(arg)
5902 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5903 "Outside of structure, run the binding of `"
5904 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5905 "'.")
5906 '(interactive "p")
5907 (list 'if
5908 '(org-context-p 'headline 'item)
5909 (list 'org-run-like-in-org-mode (list 'quote fun))
5910 (list 'let '(orgstruct-mode)
5911 (list 'call-interactively
5912 (append '(or)
5913 (mapcar (lambda (k)
5914 (list 'key-binding k))
5915 keys)
5916 '('orgstruct-error))))))))
5918 (defun org-context-p (&rest contexts)
5919 "Check if local context is any of CONTEXTS.
5920 Possible values in the list of contexts are `table', `headline', and `item'."
5921 (let ((pos (point)))
5922 (goto-char (point-at-bol))
5923 (prog1 (or (and (memq 'table contexts)
5924 (looking-at "[ \t]*|"))
5925 (and (memq 'headline contexts)
5926 ;;????????? (looking-at "\\*+"))
5927 (looking-at outline-regexp))
5928 (and (memq 'item contexts)
5929 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5930 (goto-char pos))))
5932 (defun org-get-local-variables ()
5933 "Return a list of all local variables in an org-mode buffer."
5934 (let (varlist)
5935 (with-current-buffer (get-buffer-create "*Org tmp*")
5936 (erase-buffer)
5937 (org-mode)
5938 (setq varlist (buffer-local-variables)))
5939 (kill-buffer "*Org tmp*")
5940 (delq nil
5941 (mapcar
5942 (lambda (x)
5943 (setq x
5944 (if (symbolp x)
5945 (list x)
5946 (list (car x) (list 'quote (cdr x)))))
5947 (if (string-match
5948 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5949 (symbol-name (car x)))
5950 x nil))
5951 varlist))))
5953 ;;;###autoload
5954 (defun org-run-like-in-org-mode (cmd)
5955 (org-load-modules-maybe)
5956 (unless org-local-vars
5957 (setq org-local-vars (org-get-local-variables)))
5958 (eval (list 'let org-local-vars
5959 (list 'call-interactively (list 'quote cmd)))))
5961 ;;;; Archiving
5963 (defun org-get-category (&optional pos)
5964 "Get the category applying to position POS."
5965 (get-text-property (or pos (point)) 'org-category))
5967 (defun org-refresh-category-properties ()
5968 "Refresh category text properties in the buffer."
5969 (let ((def-cat (cond
5970 ((null org-category)
5971 (if buffer-file-name
5972 (file-name-sans-extension
5973 (file-name-nondirectory buffer-file-name))
5974 "???"))
5975 ((symbolp org-category) (symbol-name org-category))
5976 (t org-category)))
5977 beg end cat pos optionp)
5978 (org-unmodified
5979 (save-excursion
5980 (save-restriction
5981 (widen)
5982 (goto-char (point-min))
5983 (put-text-property (point) (point-max) 'org-category def-cat)
5984 (while (re-search-forward
5985 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5986 (setq pos (match-end 0)
5987 optionp (equal (char-after (match-beginning 0)) ?#)
5988 cat (org-trim (match-string 2)))
5989 (if optionp
5990 (setq beg (point-at-bol) end (point-max))
5991 (org-back-to-heading t)
5992 (setq beg (point) end (org-end-of-subtree t t)))
5993 (put-text-property beg end 'org-category cat)
5994 (goto-char pos)))))))
5997 ;;;; Link Stuff
5999 ;;; Link abbreviations
6001 (defun org-link-expand-abbrev (link)
6002 "Apply replacements as defined in `org-link-abbrev-alist."
6003 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6004 (let* ((key (match-string 1 link))
6005 (as (or (assoc key org-link-abbrev-alist-local)
6006 (assoc key org-link-abbrev-alist)))
6007 (tag (and (match-end 2) (match-string 3 link)))
6008 rpl)
6009 (if (not as)
6010 link
6011 (setq rpl (cdr as))
6012 (cond
6013 ((symbolp rpl) (funcall rpl tag))
6014 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6015 ((string-match "%h" rpl)
6016 (replace-match (url-hexify-string (or tag "")) t t rpl))
6017 (t (concat rpl tag)))))
6018 link))
6020 ;;; Storing and inserting links
6022 (defvar org-insert-link-history nil
6023 "Minibuffer history for links inserted with `org-insert-link'.")
6025 (defvar org-stored-links nil
6026 "Contains the links stored with `org-store-link'.")
6028 (defvar org-store-link-plist nil
6029 "Plist with info about the most recently link created with `org-store-link'.")
6031 (defvar org-link-protocols nil
6032 "Link protocols added to Org-mode using `org-add-link-type'.")
6034 (defvar org-store-link-functions nil
6035 "List of functions that are called to create and store a link.
6036 Each function will be called in turn until one returns a non-nil
6037 value. Each function should check if it is responsible for creating
6038 this link (for example by looking at the major mode).
6039 If not, it must exit and return nil.
6040 If yes, it should return a non-nil value after a calling
6041 `org-store-link-props' with a list of properties and values.
6042 Special properties are:
6044 :type The link prefix. like \"http\". This must be given.
6045 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6046 This is obligatory as well.
6047 :description Optional default description for the second pair
6048 of brackets in an Org-mode link. The user can still change
6049 this when inserting this link into an Org-mode buffer.
6051 In addition to these, any additional properties can be specified
6052 and then used in remember templates.")
6054 (defun org-add-link-type (type &optional follow export)
6055 "Add TYPE to the list of `org-link-types'.
6056 Re-compute all regular expressions depending on `org-link-types'
6058 FOLLOW and EXPORT are two functions.
6060 FOLLOW should take the link path as the single argument and do whatever
6061 is necessary to follow the link, for example find a file or display
6062 a mail message.
6064 EXPORT should format the link path for export to one of the export formats.
6065 It should be a function accepting three arguments:
6067 path the path of the link, the text after the prefix (like \"http:\")
6068 desc the description of the link, if any, nil if there was no descripton
6069 format the export format, a symbol like `html' or `latex'.
6071 The function may use the FORMAT information to return different values
6072 depending on the format. The return value will be put literally into
6073 the exported file.
6074 Org-mode has a built-in default for exporting links. If you are happy with
6075 this default, there is no need to define an export function for the link
6076 type. For a simple example of an export function, see `org-bbdb.el'."
6077 (add-to-list 'org-link-types type t)
6078 (org-make-link-regexps)
6079 (if (assoc type org-link-protocols)
6080 (setcdr (assoc type org-link-protocols) (list follow export))
6081 (push (list type follow export) org-link-protocols)))
6084 ;;;###autoload
6085 (defun org-store-link (arg)
6086 "\\<org-mode-map>Store an org-link to the current location.
6087 This link is added to `org-stored-links' and can later be inserted
6088 into an org-buffer with \\[org-insert-link].
6090 For some link types, a prefix arg is interpreted:
6091 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6092 For file links, arg negates `org-context-in-file-links'."
6093 (interactive "P")
6094 (org-load-modules-maybe)
6095 (setq org-store-link-plist nil) ; reset
6096 (let (link cpltxt desc description search txt)
6097 (cond
6099 ((run-hook-with-args-until-success 'org-store-link-functions)
6100 (setq link (plist-get org-store-link-plist :link)
6101 desc (or (plist-get org-store-link-plist :description) link)))
6103 ((eq major-mode 'calendar-mode)
6104 (let ((cd (calendar-cursor-to-date)))
6105 (setq link
6106 (format-time-string
6107 (car org-time-stamp-formats)
6108 (apply 'encode-time
6109 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6110 nil nil nil))))
6111 (org-store-link-props :type "calendar" :date cd)))
6113 ((eq major-mode 'w3-mode)
6114 (setq cpltxt (url-view-url t)
6115 link (org-make-link cpltxt))
6116 (org-store-link-props :type "w3" :url (url-view-url t)))
6118 ((eq major-mode 'w3m-mode)
6119 (setq cpltxt (or w3m-current-title w3m-current-url)
6120 link (org-make-link w3m-current-url))
6121 (org-store-link-props :type "w3m" :url (url-view-url t)))
6123 ((setq search (run-hook-with-args-until-success
6124 'org-create-file-search-functions))
6125 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6126 "::" search))
6127 (setq cpltxt (or description link)))
6129 ((eq major-mode 'image-mode)
6130 (setq cpltxt (concat "file:"
6131 (abbreviate-file-name buffer-file-name))
6132 link (org-make-link cpltxt))
6133 (org-store-link-props :type "image" :file buffer-file-name))
6135 ((eq major-mode 'dired-mode)
6136 ;; link to the file in the current line
6137 (setq cpltxt (concat "file:"
6138 (abbreviate-file-name
6139 (expand-file-name
6140 (dired-get-filename nil t))))
6141 link (org-make-link cpltxt)))
6143 ((and buffer-file-name (org-mode-p))
6144 ;; Just link to current headline
6145 (setq cpltxt (concat "file:"
6146 (abbreviate-file-name buffer-file-name)))
6147 ;; Add a context search string
6148 (when (org-xor org-context-in-file-links arg)
6149 ;; Check if we are on a target
6150 (if (org-in-regexp "<<\\(.*?\\)>>")
6151 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6152 (setq txt (cond
6153 ((org-on-heading-p) nil)
6154 ((org-region-active-p)
6155 (buffer-substring (region-beginning) (region-end)))
6156 (t nil)))
6157 (when (or (null txt) (string-match "\\S-" txt))
6158 (setq cpltxt
6159 (concat cpltxt "::"
6160 (condition-case nil
6161 (org-make-org-heading-search-string txt)
6162 (error "")))
6163 desc "NONE"))))
6164 (if (string-match "::\\'" cpltxt)
6165 (setq cpltxt (substring cpltxt 0 -2)))
6166 (setq link (org-make-link cpltxt)))
6168 ((buffer-file-name (buffer-base-buffer))
6169 ;; Just link to this file here.
6170 (setq cpltxt (concat "file:"
6171 (abbreviate-file-name
6172 (buffer-file-name (buffer-base-buffer)))))
6173 ;; Add a context string
6174 (when (org-xor org-context-in-file-links arg)
6175 (setq txt (if (org-region-active-p)
6176 (buffer-substring (region-beginning) (region-end))
6177 (buffer-substring (point-at-bol) (point-at-eol))))
6178 ;; Only use search option if there is some text.
6179 (when (string-match "\\S-" txt)
6180 (setq cpltxt
6181 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6182 desc "NONE")))
6183 (setq link (org-make-link cpltxt)))
6185 ((interactive-p)
6186 (error "Cannot link to a buffer which is not visiting a file"))
6188 (t (setq link nil)))
6190 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6191 (setq link (or link cpltxt)
6192 desc (or desc cpltxt))
6193 (if (equal desc "NONE") (setq desc nil))
6195 (if (and (interactive-p) link)
6196 (progn
6197 (setq org-stored-links
6198 (cons (list link desc) org-stored-links))
6199 (message "Stored: %s" (or desc link)))
6200 (and link (org-make-link-string link desc)))))
6202 (defun org-store-link-props (&rest plist)
6203 "Store link properties, extract names and addresses."
6204 (let (x adr)
6205 (when (setq x (plist-get plist :from))
6206 (setq adr (mail-extract-address-components x))
6207 (setq plist (plist-put plist :fromname (car adr)))
6208 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6209 (when (setq x (plist-get plist :to))
6210 (setq adr (mail-extract-address-components x))
6211 (setq plist (plist-put plist :toname (car adr)))
6212 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6213 (let ((from (plist-get plist :from))
6214 (to (plist-get plist :to)))
6215 (when (and from to org-from-is-user-regexp)
6216 (setq plist
6217 (plist-put plist :fromto
6218 (if (string-match org-from-is-user-regexp from)
6219 (concat "to %t")
6220 (concat "from %f"))))))
6221 (setq org-store-link-plist plist))
6223 (defun org-add-link-props (&rest plist)
6224 "Add these properties to the link property list."
6225 (let (key value)
6226 (while plist
6227 (setq key (pop plist) value (pop plist))
6228 (setq org-store-link-plist
6229 (plist-put org-store-link-plist key value)))))
6231 (defun org-email-link-description (&optional fmt)
6232 "Return the description part of an email link.
6233 This takes information from `org-store-link-plist' and formats it
6234 according to FMT (default from `org-email-link-description-format')."
6235 (setq fmt (or fmt org-email-link-description-format))
6236 (let* ((p org-store-link-plist)
6237 (to (plist-get p :toaddress))
6238 (from (plist-get p :fromaddress))
6239 (table
6240 (list
6241 (cons "%c" (plist-get p :fromto))
6242 (cons "%F" (plist-get p :from))
6243 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6244 (cons "%T" (plist-get p :to))
6245 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6246 (cons "%s" (plist-get p :subject))
6247 (cons "%m" (plist-get p :message-id)))))
6248 (when (string-match "%c" fmt)
6249 ;; Check if the user wrote this message
6250 (if (and org-from-is-user-regexp from to
6251 (save-match-data (string-match org-from-is-user-regexp from)))
6252 (setq fmt (replace-match "to %t" t t fmt))
6253 (setq fmt (replace-match "from %f" t t fmt))))
6254 (org-replace-escapes fmt table)))
6256 (defun org-make-org-heading-search-string (&optional string heading)
6257 "Make search string for STRING or current headline."
6258 (interactive)
6259 (let ((s (or string (org-get-heading))))
6260 (unless (and string (not heading))
6261 ;; We are using a headline, clean up garbage in there.
6262 (if (string-match org-todo-regexp s)
6263 (setq s (replace-match "" t t s)))
6264 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6265 (setq s (replace-match "" t t s)))
6266 (setq s (org-trim s))
6267 (if (string-match (concat "^\\(" org-quote-string "\\|"
6268 org-comment-string "\\)") s)
6269 (setq s (replace-match "" t t s)))
6270 (while (string-match org-ts-regexp s)
6271 (setq s (replace-match "" t t s))))
6272 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6273 (setq s (replace-match " " t t s)))
6274 (or string (setq s (concat "*" s))) ; Add * for headlines
6275 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6277 (defun org-make-link (&rest strings)
6278 "Concatenate STRINGS."
6279 (apply 'concat strings))
6281 (defun org-make-link-string (link &optional description)
6282 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6283 (unless (string-match "\\S-" link)
6284 (error "Empty link"))
6285 (when (stringp description)
6286 ;; Remove brackets from the description, they are fatal.
6287 (while (string-match "\\[" description)
6288 (setq description (replace-match "{" t t description)))
6289 (while (string-match "\\]" description)
6290 (setq description (replace-match "}" t t description))))
6291 (when (equal (org-link-escape link) description)
6292 ;; No description needed, it is identical
6293 (setq description nil))
6294 (when (and (not description)
6295 (not (equal link (org-link-escape link))))
6296 (setq description (org-extract-attributes link)))
6297 (concat "[[" (org-link-escape link) "]"
6298 (if description (concat "[" description "]") "")
6299 "]"))
6301 (defconst org-link-escape-chars
6302 '((?\ . "%20")
6303 (?\[ . "%5B")
6304 (?\] . "%5D")
6305 (?\340 . "%E0") ; `a
6306 (?\342 . "%E2") ; ^a
6307 (?\347 . "%E7") ; ,c
6308 (?\350 . "%E8") ; `e
6309 (?\351 . "%E9") ; 'e
6310 (?\352 . "%EA") ; ^e
6311 (?\356 . "%EE") ; ^i
6312 (?\364 . "%F4") ; ^o
6313 (?\371 . "%F9") ; `u
6314 (?\373 . "%FB") ; ^u
6315 (?\; . "%3B")
6316 (?? . "%3F")
6317 (?= . "%3D")
6318 (?+ . "%2B")
6320 "Association list of escapes for some characters problematic in links.
6321 This is the list that is used for internal purposes.")
6323 (defconst org-link-escape-chars-browser
6324 '((?\ . "%20")) ; 32 for the SPC char
6325 "Association list of escapes for some characters problematic in links.
6326 This is the list that is used before handing over to the browser.")
6328 (defun org-link-escape (text &optional table)
6329 "Escape charaters in TEXT that are problematic for links."
6330 (setq table (or table org-link-escape-chars))
6331 (when text
6332 (let ((re (mapconcat (lambda (x) (regexp-quote
6333 (char-to-string (car x))))
6334 table "\\|")))
6335 (while (string-match re text)
6336 (setq text
6337 (replace-match
6338 (cdr (assoc (string-to-char (match-string 0 text))
6339 table))
6340 t t text)))
6341 text)))
6343 (defun org-link-unescape (text &optional table)
6344 "Reverse the action of `org-link-escape'."
6345 (setq table (or table org-link-escape-chars))
6346 (when text
6347 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6348 table "\\|")))
6349 (while (string-match re text)
6350 (setq text
6351 (replace-match
6352 (char-to-string (car (rassoc (match-string 0 text) table)))
6353 t t text)))
6354 text)))
6356 (defun org-xor (a b)
6357 "Exclusive or."
6358 (if a (not b) b))
6360 (defun org-get-header (header)
6361 "Find a header field in the current buffer."
6362 (save-excursion
6363 (goto-char (point-min))
6364 (let ((case-fold-search t) s)
6365 (cond
6366 ((eq header 'from)
6367 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6368 (setq s (match-string 1)))
6369 (while (string-match "\"" s)
6370 (setq s (replace-match "" t t s)))
6371 (if (string-match "[<(].*" s)
6372 (setq s (replace-match "" t t s))))
6373 ((eq header 'message-id)
6374 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6375 (setq s (match-string 1))))
6376 ((eq header 'subject)
6377 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6378 (setq s (match-string 1)))))
6379 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6380 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6381 s)))
6384 (defun org-fixup-message-id-for-http (s)
6385 "Replace special characters in a message id, so it can be used in an http query."
6386 (while (string-match "<" s)
6387 (setq s (replace-match "%3C" t t s)))
6388 (while (string-match ">" s)
6389 (setq s (replace-match "%3E" t t s)))
6390 (while (string-match "@" s)
6391 (setq s (replace-match "%40" t t s)))
6394 ;;;###autoload
6395 (defun org-insert-link-global ()
6396 "Insert a link like Org-mode does.
6397 This command can be called in any mode to insert a link in Org-mode syntax."
6398 (interactive)
6399 (org-load-modules-maybe)
6400 (org-run-like-in-org-mode 'org-insert-link))
6402 (defun org-insert-link (&optional complete-file link-location)
6403 "Insert a link. At the prompt, enter the link.
6405 Completion can be used to insert any of the link protocol prefixes like
6406 http or ftp in use.
6408 The history can be used to select a link previously stored with
6409 `org-store-link'. When the empty string is entered (i.e. if you just
6410 press RET at the prompt), the link defaults to the most recently
6411 stored link. As SPC triggers completion in the minibuffer, you need to
6412 use M-SPC or C-q SPC to force the insertion of a space character.
6414 You will also be prompted for a description, and if one is given, it will
6415 be displayed in the buffer instead of the link.
6417 If there is already a link at point, this command will allow you to edit link
6418 and description parts.
6420 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6421 be selected using completion. The path to the file will be relative to the
6422 current directory if the file is in the current directory or a subdirectory.
6423 Otherwise, the link will be the absolute path as completed in the minibuffer
6424 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6425 option `org-link-file-path-type'.
6427 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6428 the current directory or below.
6430 With three \\[universal-argument] prefixes, negate the meaning of
6431 `org-keep-stored-link-after-insertion'.
6433 If `org-make-link-description-function' is non-nil, this function will be
6434 called with the link target, and the result will be the default
6435 link description.
6437 If the LINK-LOCATION parameter is non-nil, this value will be
6438 used as the link location instead of reading one interactively."
6439 (interactive "P")
6440 (let* ((wcf (current-window-configuration))
6441 (region (if (org-region-active-p)
6442 (buffer-substring (region-beginning) (region-end))))
6443 (remove (and region (list (region-beginning) (region-end))))
6444 (desc region)
6445 tmphist ; byte-compile incorrectly complains about this
6446 (link link-location)
6447 entry file)
6448 (cond
6449 (link-location) ; specified by arg, just use it.
6450 ((org-in-regexp org-bracket-link-regexp 1)
6451 ;; We do have a link at point, and we are going to edit it.
6452 (setq remove (list (match-beginning 0) (match-end 0)))
6453 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6454 (setq link (read-string "Link: "
6455 (org-link-unescape
6456 (org-match-string-no-properties 1)))))
6457 ((or (org-in-regexp org-angle-link-re)
6458 (org-in-regexp org-plain-link-re))
6459 ;; Convert to bracket link
6460 (setq remove (list (match-beginning 0) (match-end 0))
6461 link (read-string "Link: "
6462 (org-remove-angle-brackets (match-string 0)))))
6463 ((member complete-file '((4) (16)))
6464 ;; Completing read for file names.
6465 (setq file (read-file-name "File: "))
6466 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6467 (pwd1 (file-name-as-directory (abbreviate-file-name
6468 (expand-file-name ".")))))
6469 (cond
6470 ((equal complete-file '(16))
6471 (setq link (org-make-link
6472 "file:"
6473 (abbreviate-file-name (expand-file-name file)))))
6474 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6475 (setq link (org-make-link "file:" (match-string 1 file))))
6476 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6477 (expand-file-name file))
6478 (setq link (org-make-link
6479 "file:" (match-string 1 (expand-file-name file)))))
6480 (t (setq link (org-make-link "file:" file))))))
6482 ;; Read link, with completion for stored links.
6483 (with-output-to-temp-buffer "*Org Links*"
6484 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6485 (when org-stored-links
6486 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6487 (princ (mapconcat
6488 (lambda (x)
6489 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6490 (reverse org-stored-links) "\n"))))
6491 (let ((cw (selected-window)))
6492 (select-window (get-buffer-window "*Org Links*"))
6493 (org-fit-window-to-buffer)
6494 (setq truncate-lines t)
6495 (select-window cw))
6496 ;; Fake a link history, containing the stored links.
6497 (setq tmphist (append (mapcar 'car org-stored-links)
6498 org-insert-link-history))
6499 (unwind-protect
6500 (setq link (org-completing-read
6501 "Link: "
6502 (append
6503 (mapcar (lambda (x) (list (concat (car x) ":")))
6504 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6505 (mapcar (lambda (x) (list (concat x ":")))
6506 org-link-types))
6507 nil nil nil
6508 'tmphist
6509 (or (car (car org-stored-links)))))
6510 (set-window-configuration wcf)
6511 (kill-buffer "*Org Links*"))
6512 (setq entry (assoc link org-stored-links))
6513 (or entry (push link org-insert-link-history))
6514 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6515 (not org-keep-stored-link-after-insertion))
6516 (setq org-stored-links (delq (assoc link org-stored-links)
6517 org-stored-links)))
6518 (setq desc (or desc (nth 1 entry)))))
6520 (if (string-match org-plain-link-re link)
6521 ;; URL-like link, normalize the use of angular brackets.
6522 (setq link (org-make-link (org-remove-angle-brackets link))))
6524 ;; Check if we are linking to the current file with a search option
6525 ;; If yes, simplify the link by using only the search option.
6526 (when (and buffer-file-name
6527 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6528 (let* ((path (match-string 1 link))
6529 (case-fold-search nil)
6530 (search (match-string 2 link)))
6531 (save-match-data
6532 (if (equal (file-truename buffer-file-name) (file-truename path))
6533 ;; We are linking to this same file, with a search option
6534 (setq link search)))))
6536 ;; Check if we can/should use a relative path. If yes, simplify the link
6537 (when (string-match "^file:\\(.*\\)" link)
6538 (let* ((path (match-string 1 link))
6539 (origpath path)
6540 (case-fold-search nil))
6541 (cond
6542 ((or (eq org-link-file-path-type 'absolute)
6543 (equal complete-file '(16)))
6544 (setq path (abbreviate-file-name (expand-file-name path))))
6545 ((eq org-link-file-path-type 'noabbrev)
6546 (setq path (expand-file-name path)))
6547 ((eq org-link-file-path-type 'relative)
6548 (setq path (file-relative-name path)))
6550 (save-match-data
6551 (if (string-match (concat "^" (regexp-quote
6552 (file-name-as-directory
6553 (expand-file-name "."))))
6554 (expand-file-name path))
6555 ;; We are linking a file with relative path name.
6556 (setq path (substring (expand-file-name path)
6557 (match-end 0)))
6558 (setq path (abbreviate-file-name (expand-file-name path)))))))
6559 (setq link (concat "file:" path))
6560 (if (equal desc origpath)
6561 (setq desc path))))
6563 (if org-make-link-description-function
6564 (setq desc (funcall org-make-link-description-function link desc)))
6566 (setq desc (read-string "Description: " desc))
6567 (unless (string-match "\\S-" desc) (setq desc nil))
6568 (if remove (apply 'delete-region remove))
6569 (insert (org-make-link-string link desc))))
6571 (defun org-completing-read (&rest args)
6572 "Completing-read with SPACE being a normal character."
6573 (let ((minibuffer-local-completion-map
6574 (copy-keymap minibuffer-local-completion-map)))
6575 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6576 (apply 'org-ido-completing-read args)))
6578 (defun org-ido-completing-read (&rest args)
6579 "Completing-read using `ido-mode' speedups if available"
6580 (if (and org-completion-use-ido
6581 (fboundp 'ido-completing-read)
6582 (boundp 'ido-mode) ido-mode
6583 (listp (second args)))
6584 (apply 'ido-completing-read (concat (car args)) (cdr args))
6585 (apply 'completing-read args)))
6587 (defun org-extract-attributes (s)
6588 "Extract the attributes cookie from a string and set as text property."
6589 (let (a attr (start 0) key value)
6590 (save-match-data
6591 (when (string-match "{{\\([^}]+\\)}}$" s)
6592 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6593 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6594 (setq key (match-string 1 a) value (match-string 2 a)
6595 start (match-end 0)
6596 attr (plist-put attr (intern key) value))))
6597 (org-add-props s nil 'org-attributes attr))
6600 (defun org-attributes-to-string (plist)
6601 "Format a property list into an HTML attribute list."
6602 (let ((s "") key value)
6603 (while plist
6604 (setq key (pop plist) value (pop plist))
6605 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6608 ;;; Opening/following a link
6610 (defvar org-link-search-failed nil)
6612 (defun org-next-link ()
6613 "Move forward to the next link.
6614 If the link is in hidden text, expose it."
6615 (interactive)
6616 (when (and org-link-search-failed (eq this-command last-command))
6617 (goto-char (point-min))
6618 (message "Link search wrapped back to beginning of buffer"))
6619 (setq org-link-search-failed nil)
6620 (let* ((pos (point))
6621 (ct (org-context))
6622 (a (assoc :link ct)))
6623 (if a (goto-char (nth 2 a)))
6624 (if (re-search-forward org-any-link-re nil t)
6625 (progn
6626 (goto-char (match-beginning 0))
6627 (if (org-invisible-p) (org-show-context)))
6628 (goto-char pos)
6629 (setq org-link-search-failed t)
6630 (error "No further link found"))))
6632 (defun org-previous-link ()
6633 "Move backward to the previous link.
6634 If the link is in hidden text, expose it."
6635 (interactive)
6636 (when (and org-link-search-failed (eq this-command last-command))
6637 (goto-char (point-max))
6638 (message "Link search wrapped back to end of buffer"))
6639 (setq org-link-search-failed nil)
6640 (let* ((pos (point))
6641 (ct (org-context))
6642 (a (assoc :link ct)))
6643 (if a (goto-char (nth 1 a)))
6644 (if (re-search-backward org-any-link-re nil t)
6645 (progn
6646 (goto-char (match-beginning 0))
6647 (if (org-invisible-p) (org-show-context)))
6648 (goto-char pos)
6649 (setq org-link-search-failed t)
6650 (error "No further link found"))))
6652 (defun org-translate-link (s)
6653 "Translate a link string if a translation function has been defined."
6654 (if (and org-link-translation-function
6655 (fboundp org-link-translation-function)
6656 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6657 (progn
6658 (setq s (funcall org-link-translation-function
6659 (match-string 1) (match-string 2)))
6660 (concat (car s) ":" (cdr s)))
6663 (defun org-translate-link-from-planner (type path)
6664 "Translate a link from Emacs Planner syntax so that Org can follow it.
6665 This is still an experimental function, your mileage may vary."
6666 (cond
6667 ((member type '("http" "https" "news" "ftp"))
6668 ;; standard Internet links are the same.
6669 nil)
6670 ((and (equal type "irc") (string-match "^//" path))
6671 ;; Planner has two / at the beginning of an irc link, we have 1.
6672 ;; We should have zero, actually....
6673 (setq path (substring path 1)))
6674 ((and (equal type "lisp") (string-match "^/" path))
6675 ;; Planner has a slash, we do not.
6676 (setq type "elisp" path (substring path 1)))
6677 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6678 ;; A typical message link. Planner has the id after the fina slash,
6679 ;; we separate it with a hash mark
6680 (setq path (concat (match-string 1 path) "#"
6681 (org-remove-angle-brackets (match-string 2 path)))))
6683 (cons type path))
6685 (defun org-find-file-at-mouse (ev)
6686 "Open file link or URL at mouse."
6687 (interactive "e")
6688 (mouse-set-point ev)
6689 (org-open-at-point 'in-emacs))
6691 (defun org-open-at-mouse (ev)
6692 "Open file link or URL at mouse."
6693 (interactive "e")
6694 (mouse-set-point ev)
6695 (if (eq major-mode 'org-agenda-mode)
6696 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6697 (org-open-at-point))
6699 (defvar org-window-config-before-follow-link nil
6700 "The window configuration before following a link.
6701 This is saved in case the need arises to restore it.")
6703 (defvar org-open-link-marker (make-marker)
6704 "Marker pointing to the location where `org-open-at-point; was called.")
6706 ;;;###autoload
6707 (defun org-open-at-point-global ()
6708 "Follow a link like Org-mode does.
6709 This command can be called in any mode to follow a link that has
6710 Org-mode syntax."
6711 (interactive)
6712 (org-run-like-in-org-mode 'org-open-at-point))
6714 ;;;###autoload
6715 (defun org-open-link-from-string (s &optional arg)
6716 "Open a link in the string S, as if it was in Org-mode."
6717 (interactive "sLink: \nP")
6718 (with-temp-buffer
6719 (let ((org-inhibit-startup t))
6720 (org-mode)
6721 (insert s)
6722 (goto-char (point-min))
6723 (org-open-at-point arg))))
6725 (defun org-open-at-point (&optional in-emacs)
6726 "Open link at or after point.
6727 If there is no link at point, this function will search forward up to
6728 the end of the current subtree.
6729 Normally, files will be opened by an appropriate application. If the
6730 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6731 With a double prefix argument, try to open outside of Emacs, in the
6732 application the system uses for this file type."
6733 (interactive "P")
6734 (org-load-modules-maybe)
6735 (move-marker org-open-link-marker (point))
6736 (setq org-window-config-before-follow-link (current-window-configuration))
6737 (org-remove-occur-highlights nil nil t)
6738 (if (org-at-timestamp-p t)
6739 (org-follow-timestamp-link)
6740 (let (type path link line search (pos (point)))
6741 (catch 'match
6742 (save-excursion
6743 (skip-chars-forward "^]\n\r")
6744 (when (org-in-regexp org-bracket-link-regexp)
6745 (setq link (org-extract-attributes
6746 (org-link-unescape (org-match-string-no-properties 1))))
6747 (while (string-match " *\n *" link)
6748 (setq link (replace-match " " t t link)))
6749 (setq link (org-link-expand-abbrev link))
6750 (cond
6751 ((or (file-name-absolute-p link)
6752 (string-match "^\\.\\.?/" link))
6753 (setq type "file" path link))
6754 ((string-match org-link-re-with-space3 link)
6755 (setq type (match-string 1 link) path (match-string 2 link)))
6756 (t (setq type "thisfile" path link)))
6757 (throw 'match t)))
6759 (when (get-text-property (point) 'org-linked-text)
6760 (setq type "thisfile"
6761 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6762 (1+ (point)) (point))
6763 path (buffer-substring
6764 (previous-single-property-change pos 'org-linked-text)
6765 (next-single-property-change pos 'org-linked-text)))
6766 (throw 'match t))
6768 (save-excursion
6769 (when (or (org-in-regexp org-angle-link-re)
6770 (org-in-regexp org-plain-link-re))
6771 (setq type (match-string 1) path (match-string 2))
6772 (throw 'match t)))
6773 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6774 (setq type "tree-match"
6775 path (match-string 1))
6776 (throw 'match t))
6777 (save-excursion
6778 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6779 (setq type "tags"
6780 path (match-string 1))
6781 (while (string-match ":" path)
6782 (setq path (replace-match "+" t t path)))
6783 (throw 'match t))))
6784 (unless path
6785 (error "No link found"))
6786 ;; Remove any trailing spaces in path
6787 (if (string-match " +\\'" path)
6788 (setq path (replace-match "" t t path)))
6789 (if (and org-link-translation-function
6790 (fboundp org-link-translation-function))
6791 ;; Check if we need to translate the link
6792 (let ((tmp (funcall org-link-translation-function type path)))
6793 (setq type (car tmp) path (cdr tmp))))
6795 (cond
6797 ((assoc type org-link-protocols)
6798 (funcall (nth 1 (assoc type org-link-protocols)) path))
6800 ((equal type "mailto")
6801 (let ((cmd (car org-link-mailto-program))
6802 (args (cdr org-link-mailto-program)) args1
6803 (address path) (subject "") a)
6804 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6805 (setq address (match-string 1 path)
6806 subject (org-link-escape (match-string 2 path))))
6807 (while args
6808 (cond
6809 ((not (stringp (car args))) (push (pop args) args1))
6810 (t (setq a (pop args))
6811 (if (string-match "%a" a)
6812 (setq a (replace-match address t t a)))
6813 (if (string-match "%s" a)
6814 (setq a (replace-match subject t t a)))
6815 (push a args1))))
6816 (apply cmd (nreverse args1))))
6818 ((member type '("http" "https" "ftp" "news"))
6819 (browse-url (concat type ":" (org-link-escape
6820 path org-link-escape-chars-browser))))
6822 ((member type '("message"))
6823 (browse-url (concat type ":" path)))
6825 ((string= type "tags")
6826 (org-tags-view in-emacs path))
6827 ((string= type "thisfile")
6828 (if in-emacs
6829 (switch-to-buffer-other-window
6830 (org-get-buffer-for-internal-link (current-buffer)))
6831 (org-mark-ring-push))
6832 (let ((cmd `(org-link-search
6833 ,path
6834 ,(cond ((equal in-emacs '(4)) 'occur)
6835 ((equal in-emacs '(16)) 'org-occur)
6836 (t nil))
6837 ,pos)))
6838 (condition-case nil (eval cmd)
6839 (error (progn (widen) (eval cmd))))))
6841 ((string= type "tree-match")
6842 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6844 ((string= type "file")
6845 (if (string-match "::\\([0-9]+\\)\\'" path)
6846 (setq line (string-to-number (match-string 1 path))
6847 path (substring path 0 (match-beginning 0)))
6848 (if (string-match "::\\(.+\\)\\'" path)
6849 (setq search (match-string 1 path)
6850 path (substring path 0 (match-beginning 0)))))
6851 (if (string-match "[*?{]" (file-name-nondirectory path))
6852 (dired path)
6853 (org-open-file path in-emacs line search)))
6855 ((string= type "news")
6856 (require 'org-gnus)
6857 (org-gnus-follow-link path))
6859 ((string= type "shell")
6860 (let ((cmd path))
6861 (if (or (not org-confirm-shell-link-function)
6862 (funcall org-confirm-shell-link-function
6863 (format "Execute \"%s\" in shell? "
6864 (org-add-props cmd nil
6865 'face 'org-warning))))
6866 (progn
6867 (message "Executing %s" cmd)
6868 (shell-command cmd))
6869 (error "Abort"))))
6871 ((string= type "elisp")
6872 (let ((cmd path))
6873 (if (or (not org-confirm-elisp-link-function)
6874 (funcall org-confirm-elisp-link-function
6875 (format "Execute \"%s\" as elisp? "
6876 (org-add-props cmd nil
6877 'face 'org-warning))))
6878 (message "%s => %s" cmd
6879 (if (equal (string-to-char cmd) ?\()
6880 (eval (read cmd))
6881 (call-interactively (read cmd))))
6882 (error "Abort"))))
6885 (browse-url-at-point)))))
6886 (move-marker org-open-link-marker nil)
6887 (run-hook-with-args 'org-follow-link-hook))
6889 ;;;; Time estimates
6891 (defun org-get-effort (&optional pom)
6892 "Get the effort estimate for the current entry."
6893 (org-entry-get pom org-effort-property))
6895 ;;; File search
6897 (defvar org-create-file-search-functions nil
6898 "List of functions to construct the right search string for a file link.
6899 These functions are called in turn with point at the location to
6900 which the link should point.
6902 A function in the hook should first test if it would like to
6903 handle this file type, for example by checking the major-mode or
6904 the file extension. If it decides not to handle this file, it
6905 should just return nil to give other functions a chance. If it
6906 does handle the file, it must return the search string to be used
6907 when following the link. The search string will be part of the
6908 file link, given after a double colon, and `org-open-at-point'
6909 will automatically search for it. If special measures must be
6910 taken to make the search successful, another function should be
6911 added to the companion hook `org-execute-file-search-functions',
6912 which see.
6914 A function in this hook may also use `setq' to set the variable
6915 `description' to provide a suggestion for the descriptive text to
6916 be used for this link when it gets inserted into an Org-mode
6917 buffer with \\[org-insert-link].")
6919 (defvar org-execute-file-search-functions nil
6920 "List of functions to execute a file search triggered by a link.
6922 Functions added to this hook must accept a single argument, the
6923 search string that was part of the file link, the part after the
6924 double colon. The function must first check if it would like to
6925 handle this search, for example by checking the major-mode or the
6926 file extension. If it decides not to handle this search, it
6927 should just return nil to give other functions a chance. If it
6928 does handle the search, it must return a non-nil value to keep
6929 other functions from trying.
6931 Each function can access the current prefix argument through the
6932 variable `current-prefix-argument'. Note that a single prefix is
6933 used to force opening a link in Emacs, so it may be good to only
6934 use a numeric or double prefix to guide the search function.
6936 In case this is needed, a function in this hook can also restore
6937 the window configuration before `org-open-at-point' was called using:
6939 (set-window-configuration org-window-config-before-follow-link)")
6941 (defun org-link-search (s &optional type avoid-pos)
6942 "Search for a link search option.
6943 If S is surrounded by forward slashes, it is interpreted as a
6944 regular expression. In org-mode files, this will create an `org-occur'
6945 sparse tree. In ordinary files, `occur' will be used to list matches.
6946 If the current buffer is in `dired-mode', grep will be used to search
6947 in all files. If AVOID-POS is given, ignore matches near that position."
6948 (let ((case-fold-search t)
6949 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6950 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6951 (append '(("") (" ") ("\t") ("\n"))
6952 org-emphasis-alist)
6953 "\\|") "\\)"))
6954 (pos (point))
6955 (pre nil) (post nil)
6956 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6957 (cond
6958 ;; First check if there are any special
6959 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6960 ;; Now try the builtin stuff
6961 ((save-excursion
6962 (goto-char (point-min))
6963 (and
6964 (re-search-forward
6965 (concat "<<" (regexp-quote s0) ">>") nil t)
6966 (setq type 'dedicated
6967 pos (match-beginning 0))))
6968 ;; There is an exact target for this
6969 (goto-char pos))
6970 ((string-match "^/\\(.*\\)/$" s)
6971 ;; A regular expression
6972 (cond
6973 ((org-mode-p)
6974 (org-occur (match-string 1 s)))
6975 ;;((eq major-mode 'dired-mode)
6976 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6977 (t (org-do-occur (match-string 1 s)))))
6979 ;; A normal search strings
6980 (when (equal (string-to-char s) ?*)
6981 ;; Anchor on headlines, post may include tags.
6982 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6983 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6984 s (substring s 1)))
6985 (remove-text-properties
6986 0 (length s)
6987 '(face nil mouse-face nil keymap nil fontified nil) s)
6988 ;; Make a series of regular expressions to find a match
6989 (setq words (org-split-string s "[ \n\r\t]+")
6991 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6992 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6993 "\\)" markers)
6994 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6995 re2a (concat "[ \t\r\n]" re2a_)
6996 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6997 re4 (concat "[^a-zA-Z_]" re4_)
6999 re1 (concat pre re2 post)
7000 re3 (concat pre (if pre re4_ re4) post)
7001 re5 (concat pre ".*" re4)
7002 re2 (concat pre re2)
7003 re2a (concat pre (if pre re2a_ re2a))
7004 re4 (concat pre (if pre re4_ re4))
7005 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7006 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7007 re5 "\\)"
7009 (cond
7010 ((eq type 'org-occur) (org-occur reall))
7011 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7012 (t (goto-char (point-min))
7013 (setq type 'fuzzy)
7014 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7015 (org-search-not-self 1 re1 nil t)
7016 (org-search-not-self 1 re2 nil t)
7017 (org-search-not-self 1 re2a nil t)
7018 (org-search-not-self 1 re3 nil t)
7019 (org-search-not-self 1 re4 nil t)
7020 (org-search-not-self 1 re5 nil t)
7022 (goto-char (match-beginning 1))
7023 (goto-char pos)
7024 (error "No match")))))
7026 ;; Normal string-search
7027 (goto-char (point-min))
7028 (if (search-forward s nil t)
7029 (goto-char (match-beginning 0))
7030 (error "No match"))))
7031 (and (org-mode-p) (org-show-context 'link-search))
7032 type))
7034 (defun org-search-not-self (group &rest args)
7035 "Execute `re-search-forward', but only accept matches that do not
7036 enclose the position of `org-open-link-marker'."
7037 (let ((m org-open-link-marker))
7038 (catch 'exit
7039 (while (apply 're-search-forward args)
7040 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7041 (goto-char (match-end group))
7042 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7043 (> (match-beginning 0) (marker-position m))
7044 (< (match-end 0) (marker-position m)))
7045 (save-match-data
7046 (or (not (org-in-regexp
7047 org-bracket-link-analytic-regexp 1))
7048 (not (match-end 4)) ; no description
7049 (and (<= (match-beginning 4) (point))
7050 (>= (match-end 4) (point))))))
7051 (throw 'exit (point))))))))
7053 (defun org-get-buffer-for-internal-link (buffer)
7054 "Return a buffer to be used for displaying the link target of internal links."
7055 (cond
7056 ((not org-display-internal-link-with-indirect-buffer)
7057 buffer)
7058 ((string-match "(Clone)$" (buffer-name buffer))
7059 (message "Buffer is already a clone, not making another one")
7060 ;; we also do not modify visibility in this case
7061 buffer)
7062 (t ; make a new indirect buffer for displaying the link
7063 (let* ((bn (buffer-name buffer))
7064 (ibn (concat bn "(Clone)"))
7065 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7066 (with-current-buffer ib (org-overview))
7067 ib))))
7069 (defun org-do-occur (regexp &optional cleanup)
7070 "Call the Emacs command `occur'.
7071 If CLEANUP is non-nil, remove the printout of the regular expression
7072 in the *Occur* buffer. This is useful if the regex is long and not useful
7073 to read."
7074 (occur regexp)
7075 (when cleanup
7076 (let ((cwin (selected-window)) win beg end)
7077 (when (setq win (get-buffer-window "*Occur*"))
7078 (select-window win))
7079 (goto-char (point-min))
7080 (when (re-search-forward "match[a-z]+" nil t)
7081 (setq beg (match-end 0))
7082 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7083 (setq end (1- (match-beginning 0)))))
7084 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7085 (goto-char (point-min))
7086 (select-window cwin))))
7088 ;;; The mark ring for links jumps
7090 (defvar org-mark-ring nil
7091 "Mark ring for positions before jumps in Org-mode.")
7092 (defvar org-mark-ring-last-goto nil
7093 "Last position in the mark ring used to go back.")
7094 ;; Fill and close the ring
7095 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7096 (loop for i from 1 to org-mark-ring-length do
7097 (push (make-marker) org-mark-ring))
7098 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7099 org-mark-ring)
7101 (defun org-mark-ring-push (&optional pos buffer)
7102 "Put the current position or POS into the mark ring and rotate it."
7103 (interactive)
7104 (setq pos (or pos (point)))
7105 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7106 (move-marker (car org-mark-ring)
7107 (or pos (point))
7108 (or buffer (current-buffer)))
7109 (message "%s"
7110 (substitute-command-keys
7111 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7113 (defun org-mark-ring-goto (&optional n)
7114 "Jump to the previous position in the mark ring.
7115 With prefix arg N, jump back that many stored positions. When
7116 called several times in succession, walk through the entire ring.
7117 Org-mode commands jumping to a different position in the current file,
7118 or to another Org-mode file, automatically push the old position
7119 onto the ring."
7120 (interactive "p")
7121 (let (p m)
7122 (if (eq last-command this-command)
7123 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7124 (setq p org-mark-ring))
7125 (setq org-mark-ring-last-goto p)
7126 (setq m (car p))
7127 (switch-to-buffer (marker-buffer m))
7128 (goto-char m)
7129 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7131 (defun org-remove-angle-brackets (s)
7132 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7133 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7135 (defun org-add-angle-brackets (s)
7136 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7137 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7139 (defun org-remove-double-quotes (s)
7140 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7141 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7144 ;;; Following specific links
7146 (defun org-follow-timestamp-link ()
7147 (cond
7148 ((org-at-date-range-p t)
7149 (let ((org-agenda-start-on-weekday)
7150 (t1 (match-string 1))
7151 (t2 (match-string 2)))
7152 (setq t1 (time-to-days (org-time-string-to-time t1))
7153 t2 (time-to-days (org-time-string-to-time t2)))
7154 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7155 ((org-at-timestamp-p t)
7156 (org-agenda-list nil (time-to-days (org-time-string-to-time
7157 (substring (match-string 1) 0 10)))
7159 (t (error "This should not happen"))))
7162 ;;; Following file links
7163 (defvar org-wait nil)
7164 (defun org-open-file (path &optional in-emacs line search)
7165 "Open the file at PATH.
7166 First, this expands any special file name abbreviations. Then the
7167 configuration variable `org-file-apps' is checked if it contains an
7168 entry for this file type, and if yes, the corresponding command is launched.
7170 If no application is found, Emacs simply visits the file.
7172 With optional prefix argument IN-EMACS, Emacs will visit the file.
7173 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7174 and o use an external application to visit the file.
7176 Optional LINE specifies a line to go to, optional SEARCH a string to
7177 search for. If LINE or SEARCH is given, the file will always be
7178 opened in Emacs.
7179 If the file does not exist, an error is thrown."
7180 (setq in-emacs (or in-emacs line search))
7181 (let* ((file (if (equal path "")
7182 buffer-file-name
7183 (substitute-in-file-name (expand-file-name path))))
7184 (apps (append org-file-apps (org-default-apps)))
7185 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7186 (dirp (if remp nil (file-directory-p file)))
7187 (file (if (and dirp org-open-directory-means-index-dot-org)
7188 (concat (file-name-as-directory file) "index.org")
7189 file))
7190 (a-m-a-p (assq 'auto-mode apps))
7191 (dfile (downcase file))
7192 (old-buffer (current-buffer))
7193 (old-pos (point))
7194 (old-mode major-mode)
7195 ext cmd)
7196 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7197 (setq ext (match-string 1 dfile))
7198 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7199 (setq ext (match-string 1 dfile))))
7200 (cond
7201 ((equal in-emacs '(16))
7202 (setq cmd (cdr (assoc 'system apps))))
7203 (in-emacs (setq cmd 'emacs))
7205 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7206 (and dirp (cdr (assoc 'directory apps)))
7207 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7208 'string-match)
7209 (cdr (assoc ext apps))
7210 (cdr (assoc t apps))))))
7211 (when (eq cmd 'system)
7212 (setq cmd (cdr (assoc 'system apps))))
7213 (when (eq cmd 'default)
7214 (setq cmd (cdr (assoc t apps))))
7215 (when (eq cmd 'mailcap)
7216 (require 'mailcap)
7217 (mailcap-parse-mailcaps)
7218 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7219 (command (mailcap-mime-info mime-type)))
7220 (if (stringp command)
7221 (setq cmd command)
7222 (setq cmd 'emacs))))
7223 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7224 (not (file-exists-p file))
7225 (not org-open-non-existing-files))
7226 (error "No such file: %s" file))
7227 (cond
7228 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7229 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7230 (while (string-match "['\"]%s['\"]" cmd)
7231 (setq cmd (replace-match "%s" t t cmd)))
7232 (while (string-match "%s" cmd)
7233 (setq cmd (replace-match
7234 (save-match-data
7235 (shell-quote-argument
7236 (convert-standard-filename file)))
7237 t t cmd)))
7238 (save-window-excursion
7239 (start-process-shell-command cmd nil cmd)
7240 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7242 ((or (stringp cmd)
7243 (eq cmd 'emacs))
7244 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7245 (widen)
7246 (if line (goto-line line)
7247 (if search (org-link-search search))))
7248 ((consp cmd)
7249 (let ((file (convert-standard-filename file)))
7250 (eval cmd)))
7251 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7252 (and (org-mode-p) (eq old-mode 'org-mode)
7253 (or (not (equal old-buffer (current-buffer)))
7254 (not (equal old-pos (point))))
7255 (org-mark-ring-push old-pos old-buffer))))
7257 (defun org-default-apps ()
7258 "Return the default applications for this operating system."
7259 (cond
7260 ((eq system-type 'darwin)
7261 org-file-apps-defaults-macosx)
7262 ((eq system-type 'windows-nt)
7263 org-file-apps-defaults-windowsnt)
7264 (t org-file-apps-defaults-gnu)))
7266 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7267 "Convert extensions to regular expressions in the cars of LIST.
7268 Also, weed out any non-string entries, because the return value is used
7269 only for regexp matching.
7270 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7271 point to the symbol `emacs', indicating that the file should
7272 be opened in Emacs."
7273 (append
7274 (delq nil
7275 (mapcar (lambda (x)
7276 (if (not (stringp (car x)))
7278 (if (string-match "\\W" (car x))
7280 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7281 list))
7282 (if add-auto-mode
7283 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7285 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7286 (defun org-file-remote-p (file)
7287 "Test whether FILE specifies a location on a remote system.
7288 Return non-nil if the location is indeed remote.
7290 For example, the filename \"/user@host:/foo\" specifies a location
7291 on the system \"/user@host:\"."
7292 (cond ((fboundp 'file-remote-p)
7293 (file-remote-p file))
7294 ((fboundp 'tramp-handle-file-remote-p)
7295 (tramp-handle-file-remote-p file))
7296 ((and (boundp 'ange-ftp-name-format)
7297 (string-match (car ange-ftp-name-format) file))
7299 (t nil)))
7302 ;;;; Refiling
7304 (defun org-get-org-file ()
7305 "Read a filename, with default directory `org-directory'."
7306 (let ((default (or org-default-notes-file remember-data-file)))
7307 (read-file-name (format "File name [%s]: " default)
7308 (file-name-as-directory org-directory)
7309 default)))
7311 (defun org-notes-order-reversed-p ()
7312 "Check if the current file should receive notes in reversed order."
7313 (cond
7314 ((not org-reverse-note-order) nil)
7315 ((eq t org-reverse-note-order) t)
7316 ((not (listp org-reverse-note-order)) nil)
7317 (t (catch 'exit
7318 (let ((all org-reverse-note-order)
7319 entry)
7320 (while (setq entry (pop all))
7321 (if (string-match (car entry) buffer-file-name)
7322 (throw 'exit (cdr entry))))
7323 nil)))))
7325 (defvar org-refile-target-table nil
7326 "The list of refile targets, created by `org-refile'.")
7328 (defvar org-agenda-new-buffers nil
7329 "Buffers created to visit agenda files.")
7331 (defun org-get-refile-targets (&optional default-buffer)
7332 "Produce a table with refile targets."
7333 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7334 targets txt re files f desc descre)
7335 (with-current-buffer (or default-buffer (current-buffer))
7336 (while (setq entry (pop entries))
7337 (setq files (car entry) desc (cdr entry))
7338 (cond
7339 ((null files) (setq files (list (current-buffer))))
7340 ((eq files 'org-agenda-files)
7341 (setq files (org-agenda-files 'unrestricted)))
7342 ((and (symbolp files) (fboundp files))
7343 (setq files (funcall files)))
7344 ((and (symbolp files) (boundp files))
7345 (setq files (symbol-value files))))
7346 (if (stringp files) (setq files (list files)))
7347 (cond
7348 ((eq (car desc) :tag)
7349 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7350 ((eq (car desc) :todo)
7351 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7352 ((eq (car desc) :regexp)
7353 (setq descre (cdr desc)))
7354 ((eq (car desc) :level)
7355 (setq descre (concat "^\\*\\{" (number-to-string
7356 (if org-odd-levels-only
7357 (1- (* 2 (cdr desc)))
7358 (cdr desc)))
7359 "\\}[ \t]")))
7360 ((eq (car desc) :maxlevel)
7361 (setq descre (concat "^\\*\\{1," (number-to-string
7362 (if org-odd-levels-only
7363 (1- (* 2 (cdr desc)))
7364 (cdr desc)))
7365 "\\}[ \t]")))
7366 (t (error "Bad refiling target description %s" desc)))
7367 (while (setq f (pop files))
7368 (save-excursion
7369 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7370 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7371 (save-excursion
7372 (save-restriction
7373 (widen)
7374 (goto-char (point-min))
7375 (while (re-search-forward descre nil t)
7376 (goto-char (point-at-bol))
7377 (when (looking-at org-complex-heading-regexp)
7378 (setq txt (org-link-display-format (match-string 4))
7379 re (concat "^" (regexp-quote
7380 (buffer-substring (match-beginning 1)
7381 (match-end 4)))))
7382 (if (match-end 5) (setq re (concat re "[ \t]+"
7383 (regexp-quote
7384 (match-string 5)))))
7385 (setq re (concat re "[ \t]*$"))
7386 (when org-refile-use-outline-path
7387 (setq txt (mapconcat 'org-protect-slash
7388 (append
7389 (if (eq org-refile-use-outline-path 'file)
7390 (list (file-name-nondirectory
7391 (buffer-file-name (buffer-base-buffer))))
7392 (if (eq org-refile-use-outline-path 'full-file-path)
7393 (list (buffer-file-name (buffer-base-buffer)))))
7394 (org-get-outline-path)
7395 (list txt))
7396 "/")))
7397 (push (list txt f re (point)) targets))
7398 (goto-char (point-at-eol))))))))
7399 (nreverse targets))))
7401 (defun org-protect-slash (s)
7402 (while (string-match "/" s)
7403 (setq s (replace-match "\\" t t s)))
7406 (defun org-get-outline-path ()
7407 "Return the outline path to the current entry, as a list."
7408 (let (rtn)
7409 (save-excursion
7410 (while (org-up-heading-safe)
7411 (when (looking-at org-complex-heading-regexp)
7412 (push (org-match-string-no-properties 4) rtn)))
7413 rtn)))
7415 (defvar org-refile-history nil
7416 "History for refiling operations.")
7418 (defun org-refile (&optional goto default-buffer)
7419 "Move the entry at point to another heading.
7420 The list of target headings is compiled using the information in
7421 `org-refile-targets', which see. This list is created before each use
7422 and will therefore always be up-to-date.
7424 At the target location, the entry is filed as a subitem of the target heading.
7425 Depending on `org-reverse-note-order', the new subitem will either be the
7426 first or the last subitem.
7428 If there is an active region, all entries in that region will be moved.
7429 However, the region must fulfil the requirement that the first heading
7430 is the first one sets the top-level of the moved text - at most siblings
7431 below it are allowed.
7433 With prefix arg GOTO, the command will only visit the target location,
7434 not actually move anything.
7435 With a double prefix `C-u C-u', go to the location where the last refiling
7436 operation has put the subtree."
7437 (interactive "P")
7438 (let* ((cbuf (current-buffer))
7439 (regionp (org-region-active-p))
7440 (region-start (and regionp (region-beginning)))
7441 (region-end (and regionp (region-end)))
7442 (region-length (and regionp (- region-end region-start)))
7443 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7444 pos it nbuf file re level reversed)
7445 (when regionp (goto-char region-start)
7446 (unless (org-kill-is-subtree-p
7447 (buffer-substring region-start region-end))
7448 (error "The region is not a (sequence of) subtree(s)")))
7449 (if (equal goto '(16))
7450 (org-refile-goto-last-stored)
7451 (when (setq it (org-refile-get-location
7452 (if goto "Goto: " "Refile to: ") default-buffer))
7453 (setq file (nth 1 it)
7454 re (nth 2 it)
7455 pos (nth 3 it))
7456 (setq nbuf (or (find-buffer-visiting file)
7457 (find-file-noselect file)))
7458 (if goto
7459 (progn
7460 (switch-to-buffer nbuf)
7461 (goto-char pos)
7462 (org-show-context 'org-goto))
7463 (if regionp
7464 (progn
7465 (kill-new (buffer-substring region-start region-end))
7466 (org-save-markers-in-region region-start region-end))
7467 (org-copy-subtree 1 nil t))
7468 (save-excursion
7469 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7470 (find-file-noselect file))))
7471 (setq reversed (org-notes-order-reversed-p))
7472 (save-excursion
7473 (save-restriction
7474 (widen)
7475 (goto-char pos)
7476 (looking-at outline-regexp)
7477 (setq level (org-get-valid-level (funcall outline-level) 1))
7478 (goto-char
7479 (if reversed
7480 (or (outline-next-heading) (point-max))
7481 (or (save-excursion (outline-get-next-sibling))
7482 (org-end-of-subtree t t)
7483 (point-max))))
7484 (if (not (bolp)) (newline))
7485 (bookmark-set "org-refile-last-stored")
7486 (org-paste-subtree level))))
7487 (if regionp
7488 (delete-region (point) (+ (point) region-length))
7489 (org-cut-subtree))
7490 (setq org-markers-to-move nil)
7491 (message "Refiled to \"%s\"" (car it)))))))
7493 (defun org-refile-goto-last-stored ()
7494 "Go to the location where the last refile was stored."
7495 (interactive)
7496 (bookmark-jump "org-refile-last-stored")
7497 (message "This is the location of the last refile"))
7499 (defun org-refile-get-location (&optional prompt default-buffer)
7500 "Prompt the user for a refile location, using PROMPT."
7501 (let ((org-refile-targets org-refile-targets)
7502 (org-refile-use-outline-path org-refile-use-outline-path))
7503 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7504 (unless org-refile-target-table
7505 (error "No refile targets"))
7506 (let* ((cbuf (current-buffer))
7507 (cfunc (if org-refile-use-outline-path
7508 'org-olpath-completing-read
7509 'org-ido-completing-read))
7510 (extra (if org-refile-use-outline-path "/" ""))
7511 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7512 (fname (and filename (file-truename filename)))
7513 (tbl (mapcar
7514 (lambda (x)
7515 (if (not (equal fname (file-truename (nth 1 x))))
7516 (cons (concat (car x) extra " ("
7517 (file-name-nondirectory (nth 1 x)) ")")
7518 (cdr x))
7519 (cons (concat (car x) extra) (cdr x))))
7520 org-refile-target-table))
7521 (completion-ignore-case t))
7522 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7523 tbl)))
7525 (defun org-olpath-completing-read (prompt collection &rest args)
7526 "Read an outline path like a file name."
7527 (let ((thetable collection))
7528 (apply
7529 'org-ido-completing-read prompt
7530 (lambda (string predicate &optional flag)
7531 (let (rtn r s f (l (length string)))
7532 (cond
7533 ((eq flag nil)
7534 ;; try completion
7535 (try-completion string thetable))
7536 ((eq flag t)
7537 ;; all-completions
7538 (setq rtn (all-completions string thetable predicate))
7539 (mapcar
7540 (lambda (x)
7541 (setq r (substring x l))
7542 (if (string-match " ([^)]*)$" x)
7543 (setq f (match-string 0 x))
7544 (setq f ""))
7545 (if (string-match "/" r)
7546 (concat string (substring r 0 (match-end 0)) f)
7548 rtn))
7549 ((eq flag 'lambda)
7550 ;; exact match?
7551 (assoc string thetable)))
7553 args)))
7555 ;;;; Dynamic blocks
7557 (defun org-find-dblock (name)
7558 "Find the first dynamic block with name NAME in the buffer.
7559 If not found, stay at current position and return nil."
7560 (let (pos)
7561 (save-excursion
7562 (goto-char (point-min))
7563 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7564 nil t)
7565 (match-beginning 0))))
7566 (if pos (goto-char pos))
7567 pos))
7569 (defconst org-dblock-start-re
7570 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7571 "Matches the startline of a dynamic block, with parameters.")
7573 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7574 "Matches the end of a dyhamic block.")
7576 (defun org-create-dblock (plist)
7577 "Create a dynamic block section, with parameters taken from PLIST.
7578 PLIST must containe a :name entry which is used as name of the block."
7579 (unless (bolp) (newline))
7580 (let ((name (plist-get plist :name)))
7581 (insert "#+BEGIN: " name)
7582 (while plist
7583 (if (eq (car plist) :name)
7584 (setq plist (cddr plist))
7585 (insert " " (prin1-to-string (pop plist)))))
7586 (insert "\n\n#+END:\n")
7587 (beginning-of-line -2)))
7589 (defun org-prepare-dblock ()
7590 "Prepare dynamic block for refresh.
7591 This empties the block, puts the cursor at the insert position and returns
7592 the property list including an extra property :name with the block name."
7593 (unless (looking-at org-dblock-start-re)
7594 (error "Not at a dynamic block"))
7595 (let* ((begdel (1+ (match-end 0)))
7596 (name (org-no-properties (match-string 1)))
7597 (params (append (list :name name)
7598 (read (concat "(" (match-string 3) ")")))))
7599 (unless (re-search-forward org-dblock-end-re nil t)
7600 (error "Dynamic block not terminated"))
7601 (setq params
7602 (append params
7603 (list :content (buffer-substring
7604 begdel (match-beginning 0)))))
7605 (delete-region begdel (match-beginning 0))
7606 (goto-char begdel)
7607 (open-line 1)
7608 params))
7610 (defun org-map-dblocks (&optional command)
7611 "Apply COMMAND to all dynamic blocks in the current buffer.
7612 If COMMAND is not given, use `org-update-dblock'."
7613 (let ((cmd (or command 'org-update-dblock))
7614 pos)
7615 (save-excursion
7616 (goto-char (point-min))
7617 (while (re-search-forward org-dblock-start-re nil t)
7618 (goto-char (setq pos (match-beginning 0)))
7619 (condition-case nil
7620 (funcall cmd)
7621 (error (message "Error during update of dynamic block")))
7622 (goto-char pos)
7623 (unless (re-search-forward org-dblock-end-re nil t)
7624 (error "Dynamic block not terminated"))))))
7626 (defun org-dblock-update (&optional arg)
7627 "User command for updating dynamic blocks.
7628 Update the dynamic block at point. With prefix ARG, update all dynamic
7629 blocks in the buffer."
7630 (interactive "P")
7631 (if arg
7632 (org-update-all-dblocks)
7633 (or (looking-at org-dblock-start-re)
7634 (org-beginning-of-dblock))
7635 (org-update-dblock)))
7637 (defun org-update-dblock ()
7638 "Update the dynamic block at point
7639 This means to empty the block, parse for parameters and then call
7640 the correct writing function."
7641 (save-window-excursion
7642 (let* ((pos (point))
7643 (line (org-current-line))
7644 (params (org-prepare-dblock))
7645 (name (plist-get params :name))
7646 (cmd (intern (concat "org-dblock-write:" name))))
7647 (message "Updating dynamic block `%s' at line %d..." name line)
7648 (funcall cmd params)
7649 (message "Updating dynamic block `%s' at line %d...done" name line)
7650 (goto-char pos))))
7652 (defun org-beginning-of-dblock ()
7653 "Find the beginning of the dynamic block at point.
7654 Error if there is no scuh block at point."
7655 (let ((pos (point))
7656 beg)
7657 (end-of-line 1)
7658 (if (and (re-search-backward org-dblock-start-re nil t)
7659 (setq beg (match-beginning 0))
7660 (re-search-forward org-dblock-end-re nil t)
7661 (> (match-end 0) pos))
7662 (goto-char beg)
7663 (goto-char pos)
7664 (error "Not in a dynamic block"))))
7666 (defun org-update-all-dblocks ()
7667 "Update all dynamic blocks in the buffer.
7668 This function can be used in a hook."
7669 (when (org-mode-p)
7670 (org-map-dblocks 'org-update-dblock)))
7673 ;;;; Completion
7675 (defconst org-additional-option-like-keywords
7676 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7677 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7678 "BEGIN_EXAMPLE" "END_EXAMPLE"
7679 "BEGIN_QUOTE" "END_QUOTE"
7680 "BEGIN_VERSE" "END_VERSE"
7681 "BEGIN_SRC" "END_SRC"))
7683 (defcustom org-structure-template-alist
7685 ("s" "#+begin_src ?\n\n#+end_src"
7686 "<src lang=\"?\">\n\n</src>")
7687 ("e" "#+begin_example\n?\n#+end_example"
7688 "<example>\n?\n</example>")
7689 ("q" "#+begin_quote\n?\n#+end_quote"
7690 "<quote>\n?\n</quote>")
7691 ("v" "#+begin_verse\n?\n#+end_verse"
7692 "<verse>\n?\n/verse>")
7693 ("l" "#+begin_latex\n?\n#+end_latex"
7694 "<literal style=\"latex\">\n?\n</literal>")
7695 ("L" "#+latex: "
7696 "<literal style=\"latex\">?</literal>")
7697 ("h" "#+begin_html\n?\n#+end_html"
7698 "<literal style=\"html\">\n?\n</literal>")
7699 ("H" "#+html: "
7700 "<literal style=\"html\">?</literal>")
7701 ("a" "#+begin_ascii\n?\n#+end_ascii")
7702 ("A" "#+ascii: ")
7703 ("i" "#+include %file ?"
7704 "<include file=%file markup=\"?\">")
7706 "Structure completion elements.
7707 This is a list of abbreviation keys and values. The value gets inserted
7708 it you type @samp{.} followed by the key and then the completion key,
7709 usually `M-TAB'. %file will be replaced by a file name after prompting
7710 for the file uning completion.
7711 There are two templates for each key, the first uses the original Org syntax,
7712 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7713 the default when the /org-mtags.el/ module has been loaded. See also the
7714 variable `org-mtags-prefer-muse-templates'.
7715 This is an experimental feature, it is undecided if it is going to stay in."
7716 :group 'org-completion
7717 :type '(repeat
7718 (string :tag "Key")
7719 (string :tag "Template")
7720 (string :tag "Muse Template")))
7722 (defun org-try-structure-completion ()
7723 "Try to complete a structure template before point.
7724 This looks for strings like \"<e\" on an otherwise empty line and
7725 expands them."
7726 (let ((l (buffer-substring (point-at-bol) (point)))
7728 (when (and (looking-at "[ \t]*$")
7729 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7730 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7731 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7732 (match-beginning 1)) a)
7733 t)))
7735 (defun org-complete-expand-structure-template (start cell)
7736 "Expand a structure template."
7737 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7738 (rpl (nth (if musep 2 1) cell)))
7739 (delete-region start (point))
7740 (when (string-match "\\`#\\+" rpl)
7741 (cond
7742 ((bolp))
7743 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7744 (delete-region (point-at-bol) (point)))
7745 (t (newline))))
7746 (setq start (point))
7747 (if (string-match "%file" rpl)
7748 (setq rpl (replace-match
7749 (concat
7750 "\""
7751 (save-match-data
7752 (abbreviate-file-name (read-file-name "Include file: ")))
7753 "\"")
7754 t t rpl)))
7755 (insert rpl)
7756 (if (re-search-backward "\\?" start t) (delete-char 1))))
7759 (defun org-complete (&optional arg)
7760 "Perform completion on word at point.
7761 At the beginning of a headline, this completes TODO keywords as given in
7762 `org-todo-keywords'.
7763 If the current word is preceded by a backslash, completes the TeX symbols
7764 that are supported for HTML support.
7765 If the current word is preceded by \"#+\", completes special words for
7766 setting file options.
7767 In the line after \"#+STARTUP:, complete valid keywords.\"
7768 At all other locations, this simply calls the value of
7769 `org-completion-fallback-command'."
7770 (interactive "P")
7771 (org-without-partial-completion
7772 (catch 'exit
7773 (let* ((a nil)
7774 (end (point))
7775 (beg1 (save-excursion
7776 (skip-chars-backward (org-re "[:alnum:]_@"))
7777 (point)))
7778 (beg (save-excursion
7779 (skip-chars-backward "a-zA-Z0-9_:$")
7780 (point)))
7781 (confirm (lambda (x) (stringp (car x))))
7782 (searchhead (equal (char-before beg) ?*))
7783 (struct
7784 (when (and (member (char-before beg1) '(?. ?<))
7785 (setq a (assoc (buffer-substring beg1 (point))
7786 org-structure-template-alist)))
7787 (org-complete-expand-structure-template (1- beg1) a)
7788 (throw 'exit t)))
7789 (tag (and (equal (char-before beg1) ?:)
7790 (equal (char-after (point-at-bol)) ?*)))
7791 (prop (and (equal (char-before beg1) ?:)
7792 (not (equal (char-after (point-at-bol)) ?*))))
7793 (texp (equal (char-before beg) ?\\))
7794 (link (equal (char-before beg) ?\[))
7795 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7796 beg)
7797 "#+"))
7798 (startup (string-match "^#\\+STARTUP:.*"
7799 (buffer-substring (point-at-bol) (point))))
7800 (completion-ignore-case opt)
7801 (type nil)
7802 (tbl nil)
7803 (table (cond
7804 (opt
7805 (setq type :opt)
7806 (require 'org-exp)
7807 (append
7808 (mapcar
7809 (lambda (x)
7810 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7811 (cons (match-string 2 x) (match-string 1 x)))
7812 (org-split-string (org-get-current-options) "\n"))
7813 (mapcar 'list org-additional-option-like-keywords)))
7814 (startup
7815 (setq type :startup)
7816 org-startup-options)
7817 (link (append org-link-abbrev-alist-local
7818 org-link-abbrev-alist))
7819 (texp
7820 (setq type :tex)
7821 org-html-entities)
7822 ((string-match "\\`\\*+[ \t]+\\'"
7823 (buffer-substring (point-at-bol) beg))
7824 (setq type :todo)
7825 (mapcar 'list org-todo-keywords-1))
7826 (searchhead
7827 (setq type :searchhead)
7828 (save-excursion
7829 (goto-char (point-min))
7830 (while (re-search-forward org-todo-line-regexp nil t)
7831 (push (list
7832 (org-make-org-heading-search-string
7833 (match-string 3) t))
7834 tbl)))
7835 tbl)
7836 (tag (setq type :tag beg beg1)
7837 (or org-tag-alist (org-get-buffer-tags)))
7838 (prop (setq type :prop beg beg1)
7839 (mapcar 'list (org-buffer-property-keys nil t t)))
7840 (t (progn
7841 (call-interactively org-completion-fallback-command)
7842 (throw 'exit nil)))))
7843 (pattern (buffer-substring-no-properties beg end))
7844 (completion (try-completion pattern table confirm)))
7845 (cond ((eq completion t)
7846 (if (not (assoc (upcase pattern) table))
7847 (message "Already complete")
7848 (if (and (equal type :opt)
7849 (not (member (car (assoc (upcase pattern) table))
7850 org-additional-option-like-keywords)))
7851 (insert (substring (cdr (assoc (upcase pattern) table))
7852 (length pattern)))
7853 (if (memq type '(:tag :prop)) (insert ":")))))
7854 ((null completion)
7855 (message "Can't find completion for \"%s\"" pattern)
7856 (ding))
7857 ((not (string= pattern completion))
7858 (delete-region beg end)
7859 (if (string-match " +$" completion)
7860 (setq completion (replace-match "" t t completion)))
7861 (insert completion)
7862 (if (get-buffer-window "*Completions*")
7863 (delete-window (get-buffer-window "*Completions*")))
7864 (if (assoc completion table)
7865 (if (eq type :todo) (insert " ")
7866 (if (memq type '(:tag :prop)) (insert ":"))))
7867 (if (and (equal type :opt) (assoc completion table))
7868 (message "%s" (substitute-command-keys
7869 "Press \\[org-complete] again to insert example settings"))))
7871 (message "Making completion list...")
7872 (let ((list (sort (all-completions pattern table confirm)
7873 'string<)))
7874 (with-output-to-temp-buffer "*Completions*"
7875 (condition-case nil
7876 ;; Protection needed for XEmacs and emacs 21
7877 (display-completion-list list pattern)
7878 (error (display-completion-list list)))))
7879 (message "Making completion list...%s" "done")))))))
7881 ;;;; TODO, DEADLINE, Comments
7883 (defun org-toggle-comment ()
7884 "Change the COMMENT state of an entry."
7885 (interactive)
7886 (save-excursion
7887 (org-back-to-heading)
7888 (let (case-fold-search)
7889 (if (looking-at (concat outline-regexp
7890 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7891 (replace-match "" t t nil 1)
7892 (if (looking-at outline-regexp)
7893 (progn
7894 (goto-char (match-end 0))
7895 (insert org-comment-string " ")))))))
7897 (defvar org-last-todo-state-is-todo nil
7898 "This is non-nil when the last TODO state change led to a TODO state.
7899 If the last change removed the TODO tag or switched to DONE, then
7900 this is nil.")
7902 (defvar org-setting-tags nil) ; dynamically skiped
7904 (defun org-parse-local-options (string var)
7905 "Parse STRING for startup setting relevant for variable VAR."
7906 (let ((rtn (symbol-value var))
7907 e opts)
7908 (save-match-data
7909 (if (or (not string) (not (string-match "\\S-" string)))
7911 (setq opts (delq nil (mapcar (lambda (x)
7912 (setq e (assoc x org-startup-options))
7913 (if (eq (nth 1 e) var) e nil))
7914 (org-split-string string "[ \t]+"))))
7915 (if (not opts)
7917 (setq rtn nil)
7918 (while (setq e (pop opts))
7919 (if (not (nth 3 e))
7920 (setq rtn (nth 2 e))
7921 (if (not (listp rtn)) (setq rtn nil))
7922 (push (nth 2 e) rtn)))
7923 rtn)))))
7925 (defvar org-blocker-hook nil
7926 "Hook for functions that are allowed to block a state change.
7928 Each function gets as its single argument a property list, see
7929 `org-trigger-hook' for more information about this list.
7931 If any of the functions in this hook returns nil, the state change
7932 is blocked.")
7934 (defvar org-trigger-hook nil
7935 "Hook for functions that are triggered by a state change.
7937 Each function gets as its single argument a property list with at least
7938 the following elements:
7940 (:type type-of-change :position pos-at-entry-start
7941 :from old-state :to new-state)
7943 Depending on the type, more properties may be present.
7945 This mechanism is currently implemented for:
7947 TODO state changes
7948 ------------------
7949 :type todo-state-change
7950 :from previous state (keyword as a string), or nil
7951 :to new state (keyword as a string), or nil")
7953 (defvar org-agenda-headline-snapshot-before-repeat)
7954 (defun org-todo (&optional arg)
7955 "Change the TODO state of an item.
7956 The state of an item is given by a keyword at the start of the heading,
7957 like
7958 *** TODO Write paper
7959 *** DONE Call mom
7961 The different keywords are specified in the variable `org-todo-keywords'.
7962 By default the available states are \"TODO\" and \"DONE\".
7963 So for this example: when the item starts with TODO, it is changed to DONE.
7964 When it starts with DONE, the DONE is removed. And when neither TODO nor
7965 DONE are present, add TODO at the beginning of the heading.
7967 With C-u prefix arg, use completion to determine the new state.
7968 With numeric prefix arg, switch to that state.
7970 For calling through lisp, arg is also interpreted in the following way:
7971 'none -> empty state
7972 \"\"(empty string) -> switch to empty state
7973 'done -> switch to DONE
7974 'nextset -> switch to the next set of keywords
7975 'previousset -> switch to the previous set of keywords
7976 \"WAITING\" -> switch to the specified keyword, but only if it
7977 really is a member of `org-todo-keywords'."
7978 (interactive "P")
7979 (save-excursion
7980 (catch 'exit
7981 (org-back-to-heading)
7982 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7983 (or (looking-at (concat " +" org-todo-regexp " *"))
7984 (looking-at " *"))
7985 (let* ((match-data (match-data))
7986 (startpos (point-at-bol))
7987 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7988 (org-log-done org-log-done)
7989 (org-log-repeat org-log-repeat)
7990 (org-todo-log-states org-todo-log-states)
7991 (this (match-string 1))
7992 (hl-pos (match-beginning 0))
7993 (head (org-get-todo-sequence-head this))
7994 (ass (assoc head org-todo-kwd-alist))
7995 (interpret (nth 1 ass))
7996 (done-word (nth 3 ass))
7997 (final-done-word (nth 4 ass))
7998 (last-state (or this ""))
7999 (completion-ignore-case t)
8000 (member (member this org-todo-keywords-1))
8001 (tail (cdr member))
8002 (state (cond
8003 ((and org-todo-key-trigger
8004 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8005 (and (not arg) org-use-fast-todo-selection
8006 (not (eq org-use-fast-todo-selection 'prefix)))))
8007 ;; Use fast selection
8008 (org-fast-todo-selection))
8009 ((and (equal arg '(4))
8010 (or (not org-use-fast-todo-selection)
8011 (not org-todo-key-trigger)))
8012 ;; Read a state with completion
8013 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8014 org-todo-keywords-1)
8015 nil t))
8016 ((eq arg 'right)
8017 (if this
8018 (if tail (car tail) nil)
8019 (car org-todo-keywords-1)))
8020 ((eq arg 'left)
8021 (if (equal member org-todo-keywords-1)
8023 (if this
8024 (nth (- (length org-todo-keywords-1) (length tail) 2)
8025 org-todo-keywords-1)
8026 (org-last org-todo-keywords-1))))
8027 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8028 (setq arg nil))) ; hack to fall back to cycling
8029 (arg
8030 ;; user or caller requests a specific state
8031 (cond
8032 ((equal arg "") nil)
8033 ((eq arg 'none) nil)
8034 ((eq arg 'done) (or done-word (car org-done-keywords)))
8035 ((eq arg 'nextset)
8036 (or (car (cdr (member head org-todo-heads)))
8037 (car org-todo-heads)))
8038 ((eq arg 'previousset)
8039 (let ((org-todo-heads (reverse org-todo-heads)))
8040 (or (car (cdr (member head org-todo-heads)))
8041 (car org-todo-heads))))
8042 ((car (member arg org-todo-keywords-1)))
8043 ((nth (1- (prefix-numeric-value arg))
8044 org-todo-keywords-1))))
8045 ((null member) (or head (car org-todo-keywords-1)))
8046 ((equal this final-done-word) nil) ;; -> make empty
8047 ((null tail) nil) ;; -> first entry
8048 ((eq interpret 'sequence)
8049 (car tail))
8050 ((memq interpret '(type priority))
8051 (if (eq this-command last-command)
8052 (car tail)
8053 (if (> (length tail) 0)
8054 (or done-word (car org-done-keywords))
8055 nil)))
8056 (t nil)))
8057 (next (if state (concat " " state " ") " "))
8058 (change-plist (list :type 'todo-state-change :from this :to state
8059 :position startpos))
8060 dolog now-done-p)
8061 (when org-blocker-hook
8062 (unless (save-excursion
8063 (save-match-data
8064 (run-hook-with-args-until-failure
8065 'org-blocker-hook change-plist)))
8066 (if (interactive-p)
8067 (error "TODO state change from %s to %s blocked" this state)
8068 ;; fail silently
8069 (message "TODO state change from %s to %s blocked" this state)
8070 (throw 'exit nil))))
8071 (store-match-data match-data)
8072 (replace-match next t t)
8073 (unless (pos-visible-in-window-p hl-pos)
8074 (message "TODO state changed to %s" (org-trim next)))
8075 (unless head
8076 (setq head (org-get-todo-sequence-head state)
8077 ass (assoc head org-todo-kwd-alist)
8078 interpret (nth 1 ass)
8079 done-word (nth 3 ass)
8080 final-done-word (nth 4 ass)))
8081 (when (memq arg '(nextset previousset))
8082 (message "Keyword-Set %d/%d: %s"
8083 (- (length org-todo-sets) -1
8084 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8085 (length org-todo-sets)
8086 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8087 (setq org-last-todo-state-is-todo
8088 (not (member state org-done-keywords)))
8089 (setq now-done-p (and (member state org-done-keywords)
8090 (not (member this org-done-keywords))))
8091 (and logging (org-local-logging logging))
8092 (when (and (or org-todo-log-states org-log-done)
8093 (not (memq arg '(nextset previousset))))
8094 ;; we need to look at recording a time and note
8095 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8096 (nth 2 (assoc this org-todo-log-states))))
8097 (when (and state
8098 (member state org-not-done-keywords)
8099 (not (member this org-not-done-keywords)))
8100 ;; This is now a todo state and was not one before
8101 ;; If there was a CLOSED time stamp, get rid of it.
8102 (org-add-planning-info nil nil 'closed))
8103 (when (and now-done-p org-log-done)
8104 ;; It is now done, and it was not done before
8105 (org-add-planning-info 'closed (org-current-time))
8106 (if (and (not dolog) (eq 'note org-log-done))
8107 (org-add-log-setup 'done state 'findpos 'note)))
8108 (when (and state dolog)
8109 ;; This is a non-nil state, and we need to log it
8110 (org-add-log-setup 'state state 'findpos dolog)))
8111 ;; Fixup tag positioning
8112 (org-todo-trigger-tag-changes state)
8113 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8114 (when org-provide-todo-statistics
8115 (org-update-parent-todo-statistics))
8116 (run-hooks 'org-after-todo-state-change-hook)
8117 (if (and arg (not (member state org-done-keywords)))
8118 (setq head (org-get-todo-sequence-head state)))
8119 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8120 ;; Do we need to trigger a repeat?
8121 (when now-done-p
8122 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8123 ;; This is for the agenda, take a snapshot of the headline.
8124 (save-match-data
8125 (setq org-agenda-headline-snapshot-before-repeat
8126 (org-get-heading))))
8127 (org-auto-repeat-maybe state))
8128 ;; Fixup cursor location if close to the keyword
8129 (if (and (outline-on-heading-p)
8130 (not (bolp))
8131 (save-excursion (beginning-of-line 1)
8132 (looking-at org-todo-line-regexp))
8133 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8134 (progn
8135 (goto-char (or (match-end 2) (match-end 1)))
8136 (just-one-space)))
8137 (when org-trigger-hook
8138 (save-excursion
8139 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8141 (defun org-update-parent-todo-statistics ()
8142 "Update any statistics cookie in the parent of the current headline."
8143 (interactive)
8144 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8145 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8146 (catch 'exit
8147 (save-excursion
8148 (setq level (org-up-heading-safe))
8149 (unless (and level
8150 (re-search-forward box-re (point-at-eol) t))
8151 (throw 'exit nil))
8152 (setq is-percent (match-end 2))
8153 (save-match-data
8154 (unless (outline-next-heading) (throw 'exit nil))
8155 (while (looking-at org-todo-line-regexp)
8156 (setq kwd (match-string 2))
8157 (and kwd (setq cnt-all (1+ cnt-all)))
8158 (and (member kwd org-done-keywords)
8159 (setq cnt-done (1+ cnt-done)))
8160 (condition-case nil
8161 (org-forward-same-level 1)
8162 (error (end-of-line 1)))))
8163 (replace-match
8164 (if is-percent
8165 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8166 (format "[%d/%d]" cnt-done cnt-all)))
8167 (run-hook-with-args 'org-after-todo-statistics-hook
8168 cnt-done (- cnt-all cnt-done))))))
8170 (defvar org-after-todo-statistics-hook nil
8171 "Hook that is called after a TODO statistics cookie has been updated.
8172 Each function is called with two arguments: the number of not-done entries
8173 and the number of done entries.
8175 For example, the following function, when added to this hook, will switch
8176 an entry to DONE when all children are done, and back to TODO when new
8177 entries are set to a TODO status. Note that this hook is only called
8178 when there is a statistics cookie in the headline!
8180 (defun org-summary-todo (n-done n-not-done)
8181 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8182 (let (org-log-done org-log-states) ; turn off logging
8183 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8186 (defun org-todo-trigger-tag-changes (state)
8187 "Apply the changes defined in `org-todo-state-tags-triggers'."
8188 (let ((l org-todo-state-tags-triggers)
8189 changes)
8190 (when (or (not state) (equal state ""))
8191 (setq changes (append changes (cdr (assoc "" l)))))
8192 (when (and (stringp state) (> (length state) 0))
8193 (setq changes (append changes (cdr (assoc state l)))))
8194 (when (member state org-not-done-keywords)
8195 (setq changes (append changes (cdr (assoc 'todo l)))))
8196 (when (member state org-done-keywords)
8197 (setq changes (append changes (cdr (assoc 'done l)))))
8198 (dolist (c changes)
8199 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8201 (defun org-local-logging (value)
8202 "Get logging settings from a property VALUE."
8203 (let* (words w a)
8204 ;; directly set the variables, they are already local.
8205 (setq org-log-done nil
8206 org-log-repeat nil
8207 org-todo-log-states nil)
8208 (setq words (org-split-string value))
8209 (while (setq w (pop words))
8210 (cond
8211 ((setq a (assoc w org-startup-options))
8212 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8213 (set (nth 1 a) (nth 2 a))))
8214 ((setq a (org-extract-log-state-settings w))
8215 (and (member (car a) org-todo-keywords-1)
8216 (push a org-todo-log-states)))))))
8218 (defun org-get-todo-sequence-head (kwd)
8219 "Return the head of the TODO sequence to which KWD belongs.
8220 If KWD is not set, check if there is a text property remembering the
8221 right sequence."
8222 (let (p)
8223 (cond
8224 ((not kwd)
8225 (or (get-text-property (point-at-bol) 'org-todo-head)
8226 (progn
8227 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8228 nil (point-at-eol)))
8229 (get-text-property p 'org-todo-head))))
8230 ((not (member kwd org-todo-keywords-1))
8231 (car org-todo-keywords-1))
8232 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8234 (defun org-fast-todo-selection ()
8235 "Fast TODO keyword selection with single keys.
8236 Returns the new TODO keyword, or nil if no state change should occur."
8237 (let* ((fulltable org-todo-key-alist)
8238 (done-keywords org-done-keywords) ;; needed for the faces.
8239 (maxlen (apply 'max (mapcar
8240 (lambda (x)
8241 (if (stringp (car x)) (string-width (car x)) 0))
8242 fulltable)))
8243 (expert nil)
8244 (fwidth (+ maxlen 3 1 3))
8245 (ncol (/ (- (window-width) 4) fwidth))
8246 tg cnt e c tbl
8247 groups ingroup)
8248 (save-window-excursion
8249 (if expert
8250 (set-buffer (get-buffer-create " *Org todo*"))
8251 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8252 (erase-buffer)
8253 (org-set-local 'org-done-keywords done-keywords)
8254 (setq tbl fulltable cnt 0)
8255 (while (setq e (pop tbl))
8256 (cond
8257 ((equal e '(:startgroup))
8258 (push '() groups) (setq ingroup t)
8259 (when (not (= cnt 0))
8260 (setq cnt 0)
8261 (insert "\n"))
8262 (insert "{ "))
8263 ((equal e '(:endgroup))
8264 (setq ingroup nil cnt 0)
8265 (insert "}\n"))
8267 (setq tg (car e) c (cdr e))
8268 (if ingroup (push tg (car groups)))
8269 (setq tg (org-add-props tg nil 'face
8270 (org-get-todo-face tg)))
8271 (if (and (= cnt 0) (not ingroup)) (insert " "))
8272 (insert "[" c "] " tg (make-string
8273 (- fwidth 4 (length tg)) ?\ ))
8274 (when (= (setq cnt (1+ cnt)) ncol)
8275 (insert "\n")
8276 (if ingroup (insert " "))
8277 (setq cnt 0)))))
8278 (insert "\n")
8279 (goto-char (point-min))
8280 (if (not expert) (org-fit-window-to-buffer))
8281 (message "[a-z..]:Set [SPC]:clear")
8282 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8283 (cond
8284 ((or (= c ?\C-g)
8285 (and (= c ?q) (not (rassoc c fulltable))))
8286 (setq quit-flag t))
8287 ((= c ?\ ) nil)
8288 ((setq e (rassoc c fulltable) tg (car e))
8290 (t (setq quit-flag t))))))
8292 (defun org-entry-is-todo-p ()
8293 (member (org-get-todo-state) org-not-done-keywords))
8295 (defun org-entry-is-done-p ()
8296 (member (org-get-todo-state) org-done-keywords))
8298 (defun org-get-todo-state ()
8299 (save-excursion
8300 (org-back-to-heading t)
8301 (and (looking-at org-todo-line-regexp)
8302 (match-end 2)
8303 (match-string 2))))
8305 (defun org-at-date-range-p (&optional inactive-ok)
8306 "Is the cursor inside a date range?"
8307 (interactive)
8308 (save-excursion
8309 (catch 'exit
8310 (let ((pos (point)))
8311 (skip-chars-backward "^[<\r\n")
8312 (skip-chars-backward "<[")
8313 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8314 (>= (match-end 0) pos)
8315 (throw 'exit t))
8316 (skip-chars-backward "^<[\r\n")
8317 (skip-chars-backward "<[")
8318 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8319 (>= (match-end 0) pos)
8320 (throw 'exit t)))
8321 nil)))
8323 (defun org-get-repeat ()
8324 "Check if there is a deadline/schedule with repeater in this entry."
8325 (save-match-data
8326 (save-excursion
8327 (org-back-to-heading t)
8328 (if (re-search-forward
8329 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8330 (match-string 1)))))
8332 (defvar org-last-changed-timestamp)
8333 (defvar org-last-inserted-timestamp)
8334 (defvar org-log-post-message)
8335 (defvar org-log-note-purpose)
8336 (defvar org-log-note-how)
8337 (defvar org-log-note-extra)
8338 (defun org-auto-repeat-maybe (done-word)
8339 "Check if the current headline contains a repeated deadline/schedule.
8340 If yes, set TODO state back to what it was and change the base date
8341 of repeating deadline/scheduled time stamps to new date.
8342 This function is run automatically after each state change to a DONE state."
8343 ;; last-state is dynamically scoped into this function
8344 (let* ((repeat (org-get-repeat))
8345 (aa (assoc last-state org-todo-kwd-alist))
8346 (interpret (nth 1 aa))
8347 (head (nth 2 aa))
8348 (whata '(("d" . day) ("m" . month) ("y" . year)))
8349 (msg "Entry repeats: ")
8350 (org-log-done nil)
8351 (org-todo-log-states nil)
8352 (nshiftmax 10) (nshift 0)
8353 re type n what ts mb0 time)
8354 (when repeat
8355 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8356 (org-todo (if (eq interpret 'type) last-state head))
8357 (when org-log-repeat
8358 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8359 (memq 'org-add-log-note post-command-hook))
8360 ;; OK, we are already setup for some record
8361 (if (eq org-log-repeat 'note)
8362 ;; make sure we take a note, not only a time stamp
8363 (setq org-log-note-how 'note))
8364 ;; Set up for taking a record
8365 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8366 'findpos org-log-repeat)))
8367 (org-back-to-heading t)
8368 (org-add-planning-info nil nil 'closed)
8369 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8370 org-deadline-time-regexp "\\)\\|\\("
8371 org-ts-regexp "\\)"))
8372 (while (re-search-forward
8373 re (save-excursion (outline-next-heading) (point)) t)
8374 (setq type (if (match-end 1) org-scheduled-string
8375 (if (match-end 3) org-deadline-string "Plain:"))
8376 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8377 mb0 (match-beginning 0))
8378 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8379 (setq n (string-to-number (match-string 2 ts))
8380 what (match-string 3 ts))
8381 (if (equal what "w") (setq n (* n 7) what "d"))
8382 ;; Preparation, see if we need to modify the start date for the change
8383 (when (match-end 1)
8384 (setq time (save-match-data (org-time-string-to-time ts)))
8385 (cond
8386 ((equal (match-string 1 ts) ".")
8387 ;; Shift starting date to today
8388 (org-timestamp-change
8389 (- (time-to-days (current-time)) (time-to-days time))
8390 'day))
8391 ((equal (match-string 1 ts) "+")
8392 (while (or (= nshift 0)
8393 (<= (time-to-days time) (time-to-days (current-time))))
8394 (when (= (incf nshift) nshiftmax)
8395 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8396 (error "Abort")))
8397 (org-timestamp-change n (cdr (assoc what whata)))
8398 (org-at-timestamp-p t)
8399 (setq ts (match-string 1))
8400 (setq time (save-match-data (org-time-string-to-time ts))))
8401 (org-timestamp-change (- n) (cdr (assoc what whata)))
8402 ;; rematch, so that we have everything in place for the real shift
8403 (org-at-timestamp-p t)
8404 (setq ts (match-string 1))
8405 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8406 (org-timestamp-change n (cdr (assoc what whata)))
8407 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8408 (setq org-log-post-message msg)
8409 (message "%s" msg))))
8411 (defun org-show-todo-tree (arg)
8412 "Make a compact tree which shows all headlines marked with TODO.
8413 The tree will show the lines where the regexp matches, and all higher
8414 headlines above the match.
8415 With a \\[universal-argument] prefix, also show the DONE entries.
8416 With a numeric prefix N, construct a sparse tree for the Nth element
8417 of `org-todo-keywords-1'."
8418 (interactive "P")
8419 (let ((case-fold-search nil)
8420 (kwd-re
8421 (cond ((null arg) org-not-done-regexp)
8422 ((equal arg '(4))
8423 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8424 (mapcar 'list org-todo-keywords-1))))
8425 (concat "\\("
8426 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8427 "\\)\\>")))
8428 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8429 (regexp-quote (nth (1- (prefix-numeric-value arg))
8430 org-todo-keywords-1)))
8431 (t (error "Invalid prefix argument: %s" arg)))))
8432 (message "%d TODO entries found"
8433 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8435 (defun org-deadline (&optional remove time)
8436 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8437 With argument REMOVE, remove any deadline from the item.
8438 When TIME is set, it should be an internal time specification, and the
8439 scheduling will use the corresponding date."
8440 (interactive "P")
8441 (if remove
8442 (progn
8443 (org-remove-timestamp-with-keyword org-deadline-string)
8444 (message "Item no longer has a deadline."))
8445 (if (org-get-repeat)
8446 (error "Cannot change deadline on task with repeater, please do that by hand")
8447 (org-add-planning-info 'deadline time 'closed)
8448 (message "Deadline on %s" org-last-inserted-timestamp))))
8450 (defun org-schedule (&optional remove time)
8451 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8452 With argument REMOVE, remove any scheduling date from the item.
8453 When TIME is set, it should be an internal time specification, and the
8454 scheduling will use the corresponding date."
8455 (interactive "P")
8456 (if remove
8457 (progn
8458 (org-remove-timestamp-with-keyword org-scheduled-string)
8459 (message "Item is no longer scheduled."))
8460 (if (org-get-repeat)
8461 (error "Cannot reschedule task with repeater, please do that by hand")
8462 (org-add-planning-info 'scheduled time 'closed)
8463 (message "Scheduled to %s" org-last-inserted-timestamp))))
8465 (defun org-remove-timestamp-with-keyword (keyword)
8466 "Remove all time stamps with KEYWORD in the current entry."
8467 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8468 beg)
8469 (save-excursion
8470 (org-back-to-heading t)
8471 (setq beg (point))
8472 (org-end-of-subtree t t)
8473 (while (re-search-backward re beg t)
8474 (replace-match "")
8475 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8476 (equal (char-before) ?\ ))
8477 (backward-delete-char 1)
8478 (if (string-match "^[ \t]*$" (buffer-substring
8479 (point-at-bol) (point-at-eol)))
8480 (delete-region (point-at-bol)
8481 (min (point-max) (1+ (point-at-eol))))))))))
8483 (defun org-add-planning-info (what &optional time &rest remove)
8484 "Insert new timestamp with keyword in the line directly after the headline.
8485 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8486 If non is given, the user is prompted for a date.
8487 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8488 be removed."
8489 (interactive)
8490 (let (org-time-was-given org-end-time-was-given ts
8491 end default-time default-input)
8493 (when (and (not time) (memq what '(scheduled deadline)))
8494 ;; Try to get a default date/time from existing timestamp
8495 (save-excursion
8496 (org-back-to-heading t)
8497 (setq end (save-excursion (outline-next-heading) (point)))
8498 (when (re-search-forward (if (eq what 'scheduled)
8499 org-scheduled-time-regexp
8500 org-deadline-time-regexp)
8501 end t)
8502 (setq ts (match-string 1)
8503 default-time
8504 (apply 'encode-time (org-parse-time-string ts))
8505 default-input (and ts (org-get-compact-tod ts))))))
8506 (when what
8507 ;; If necessary, get the time from the user
8508 (setq time (or time (org-read-date nil 'to-time nil nil
8509 default-time default-input))))
8511 (when (and org-insert-labeled-timestamps-at-point
8512 (member what '(scheduled deadline)))
8513 (insert
8514 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8515 (org-insert-time-stamp time org-time-was-given
8516 nil nil nil (list org-end-time-was-given))
8517 (setq what nil))
8518 (save-excursion
8519 (save-restriction
8520 (let (col list elt ts buffer-invisibility-spec)
8521 (org-back-to-heading t)
8522 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8523 (goto-char (match-end 1))
8524 (setq col (current-column))
8525 (goto-char (match-end 0))
8526 (if (eobp) (insert "\n") (forward-char 1))
8527 (if (and (not (looking-at outline-regexp))
8528 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8529 "[^\r\n]*"))
8530 (not (equal (match-string 1) org-clock-string)))
8531 (narrow-to-region (match-beginning 0) (match-end 0))
8532 (insert-before-markers "\n")
8533 (backward-char 1)
8534 (narrow-to-region (point) (point))
8535 (and org-adapt-indentation (org-indent-to-column col)))
8536 ;; Check if we have to remove something.
8537 (setq list (cons what remove))
8538 (while list
8539 (setq elt (pop list))
8540 (goto-char (point-min))
8541 (when (or (and (eq elt 'scheduled)
8542 (re-search-forward org-scheduled-time-regexp nil t))
8543 (and (eq elt 'deadline)
8544 (re-search-forward org-deadline-time-regexp nil t))
8545 (and (eq elt 'closed)
8546 (re-search-forward org-closed-time-regexp nil t)))
8547 (replace-match "")
8548 (if (looking-at "--+<[^>]+>") (replace-match ""))
8549 (if (looking-at " +") (replace-match ""))))
8550 (goto-char (point-max))
8551 (when what
8552 (insert
8553 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8554 (cond ((eq what 'scheduled) org-scheduled-string)
8555 ((eq what 'deadline) org-deadline-string)
8556 ((eq what 'closed) org-closed-string))
8557 " ")
8558 (setq ts (org-insert-time-stamp
8559 time
8560 (or org-time-was-given
8561 (and (eq what 'closed) org-log-done-with-time))
8562 (eq what 'closed)
8563 nil nil (list org-end-time-was-given)))
8564 (end-of-line 1))
8565 (goto-char (point-min))
8566 (widen)
8567 (if (and (looking-at "[ \t]+\n")
8568 (equal (char-before) ?\n))
8569 (delete-region (1- (point)) (point-at-eol)))
8570 ts)))))
8572 (defvar org-log-note-marker (make-marker))
8573 (defvar org-log-note-purpose nil)
8574 (defvar org-log-note-state nil)
8575 (defvar org-log-note-how nil)
8576 (defvar org-log-note-extra nil)
8577 (defvar org-log-note-window-configuration nil)
8578 (defvar org-log-note-return-to (make-marker))
8579 (defvar org-log-post-message nil
8580 "Message to be displayed after a log note has been stored.
8581 The auto-repeater uses this.")
8583 (defun org-add-note ()
8584 "Add a note to the current entry.
8585 This is done in the same way as adding a state change note."
8586 (interactive)
8587 (org-add-log-setup 'note nil 'findpos nil))
8589 (defvar org-property-end-re)
8590 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8591 "Set up the post command hook to take a note.
8592 If this is about to TODO state change, the new state is expected in STATE.
8593 When FINDPOS is non-nil, find the correct position for the note in
8594 the current entry. If not, assume that it can be inserted at point.
8595 HOW is an indicator what kind of note should be created.
8596 EXTRA is additional text that will be inserted into the notes buffer."
8597 (save-restriction
8598 (save-excursion
8599 (when findpos
8600 (org-back-to-heading t)
8601 (narrow-to-region (point) (save-excursion
8602 (outline-next-heading) (point)))
8603 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8604 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8605 "[^\r\n]*\\)?"))
8606 (goto-char (match-end 0))
8607 (when (and org-log-state-notes-insert-after-drawers
8608 (save-excursion
8609 (forward-line) (looking-at org-drawer-regexp)))
8610 (progn (forward-line)
8611 (while (looking-at org-drawer-regexp)
8612 (goto-char (match-end 0))
8613 (re-search-forward org-property-end-re (point-max) t)
8614 (forward-line))
8615 (forward-line -1)))
8616 (unless org-log-states-order-reversed
8617 (and (= (char-after) ?\n) (forward-char 1))
8618 (org-skip-over-state-notes)
8619 (skip-chars-backward " \t\n\r")))
8620 (move-marker org-log-note-marker (point))
8621 (setq org-log-note-purpose purpose
8622 org-log-note-state state
8623 org-log-note-how how
8624 org-log-note-extra extra)
8625 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8627 (defun org-skip-over-state-notes ()
8628 "Skip past the list of State notes in an entry."
8629 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8630 (while (looking-at "[ \t]*- State")
8631 (condition-case nil
8632 (org-next-item)
8633 (error (org-end-of-item)))))
8635 (defun org-add-log-note (&optional purpose)
8636 "Pop up a window for taking a note, and add this note later at point."
8637 (remove-hook 'post-command-hook 'org-add-log-note)
8638 (setq org-log-note-window-configuration (current-window-configuration))
8639 (delete-other-windows)
8640 (move-marker org-log-note-return-to (point))
8641 (switch-to-buffer (marker-buffer org-log-note-marker))
8642 (goto-char org-log-note-marker)
8643 (org-switch-to-buffer-other-window "*Org Note*")
8644 (erase-buffer)
8645 (if (memq org-log-note-how '(time state))
8646 (let (current-prefix-arg) (org-store-log-note))
8647 (let ((org-inhibit-startup t)) (org-mode))
8648 (insert (format "# Insert note for %s.
8649 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8650 (cond
8651 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8652 ((eq org-log-note-purpose 'done) "closed todo item")
8653 ((eq org-log-note-purpose 'state)
8654 (format "state change to \"%s\"" org-log-note-state))
8655 ((eq org-log-note-purpose 'note)
8656 "this entry")
8657 (t (error "This should not happen")))))
8658 (if org-log-note-extra (insert org-log-note-extra))
8659 (org-set-local 'org-finish-function 'org-store-log-note)))
8661 (defvar org-note-abort nil) ; dynamically scoped
8662 (defun org-store-log-note ()
8663 "Finish taking a log note, and insert it to where it belongs."
8664 (let ((txt (buffer-string))
8665 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8666 lines ind)
8667 (kill-buffer (current-buffer))
8668 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8669 (setq txt (replace-match "" t t txt)))
8670 (if (string-match "\\s-+\\'" txt)
8671 (setq txt (replace-match "" t t txt)))
8672 (setq lines (org-split-string txt "\n"))
8673 (when (and note (string-match "\\S-" note))
8674 (setq note
8675 (org-replace-escapes
8676 note
8677 (list (cons "%u" (user-login-name))
8678 (cons "%U" user-full-name)
8679 (cons "%t" (format-time-string
8680 (org-time-stamp-format 'long 'inactive)
8681 (current-time)))
8682 (cons "%s" (if org-log-note-state
8683 (concat "\"" org-log-note-state "\"")
8684 "")))))
8685 (if lines (setq note (concat note " \\\\")))
8686 (push note lines))
8687 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8688 (when lines
8689 (save-excursion
8690 (set-buffer (marker-buffer org-log-note-marker))
8691 (save-excursion
8692 (goto-char org-log-note-marker)
8693 (move-marker org-log-note-marker nil)
8694 (end-of-line 1)
8695 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8696 (indent-relative nil)
8697 (insert "- " (pop lines))
8698 (org-indent-line-function)
8699 (beginning-of-line 1)
8700 (looking-at "[ \t]*")
8701 (setq ind (concat (match-string 0) " "))
8702 (end-of-line 1)
8703 (while lines (insert "\n" ind (pop lines)))))))
8704 (set-window-configuration org-log-note-window-configuration)
8705 (with-current-buffer (marker-buffer org-log-note-return-to)
8706 (goto-char org-log-note-return-to))
8707 (move-marker org-log-note-return-to nil)
8708 (and org-log-post-message (message "%s" org-log-post-message)))
8710 (defun org-sparse-tree (&optional arg)
8711 "Create a sparse tree, prompt for the details.
8712 This command can create sparse trees. You first need to select the type
8713 of match used to create the tree:
8715 t Show entries with a specific TODO keyword.
8716 T Show entries selected by a tags match.
8717 p Enter a property name and its value (both with completion on existing
8718 names/values) and show entries with that property.
8719 r Show entries matching a regular expression
8720 d Show deadlines due within `org-deadline-warning-days'."
8721 (interactive "P")
8722 (let (ans kwd value)
8723 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8724 (setq ans (read-char-exclusive))
8725 (cond
8726 ((equal ans ?d)
8727 (call-interactively 'org-check-deadlines))
8728 ((equal ans ?b)
8729 (call-interactively 'org-check-before-date))
8730 ((equal ans ?t)
8731 (org-show-todo-tree '(4)))
8732 ((equal ans ?T)
8733 (call-interactively 'org-tags-sparse-tree))
8734 ((member ans '(?p ?P))
8735 (setq kwd (org-ido-completing-read "Property: "
8736 (mapcar 'list (org-buffer-property-keys))))
8737 (setq value (org-ido-completing-read "Value: "
8738 (mapcar 'list (org-property-values kwd))))
8739 (unless (string-match "\\`{.*}\\'" value)
8740 (setq value (concat "\"" value "\"")))
8741 (org-tags-sparse-tree arg (concat kwd "=" value)))
8742 ((member ans '(?r ?R ?/))
8743 (call-interactively 'org-occur))
8744 (t (error "No such sparse tree command \"%c\"" ans)))))
8746 (defvar org-occur-highlights nil
8747 "List of overlays used for occur matches.")
8748 (make-variable-buffer-local 'org-occur-highlights)
8749 (defvar org-occur-parameters nil
8750 "Parameters of the active org-occur calls.
8751 This is a list, each call to org-occur pushes as cons cell,
8752 containing the regular expression and the callback, onto the list.
8753 The list can contain several entries if `org-occur' has been called
8754 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8755 will only contain one set of parameters. When the highlights are
8756 removed (for example with `C-c C-c', or with the next edit (depending
8757 on `org-remove-highlights-with-change'), this variable is emptied
8758 as well.")
8759 (make-variable-buffer-local 'org-occur-parameters)
8761 (defun org-occur (regexp &optional keep-previous callback)
8762 "Make a compact tree which shows all matches of REGEXP.
8763 The tree will show the lines where the regexp matches, and all higher
8764 headlines above the match. It will also show the heading after the match,
8765 to make sure editing the matching entry is easy.
8766 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8767 call to `org-occur' will be kept, to allow stacking of calls to this
8768 command.
8769 If CALLBACK is non-nil, it is a function which is called to confirm
8770 that the match should indeed be shown."
8771 (interactive "sRegexp: \nP")
8772 (unless keep-previous
8773 (org-remove-occur-highlights nil nil t))
8774 (push (cons regexp callback) org-occur-parameters)
8775 (let ((cnt 0))
8776 (save-excursion
8777 (goto-char (point-min))
8778 (if (or (not keep-previous) ; do not want to keep
8779 (not org-occur-highlights)) ; no previous matches
8780 ;; hide everything
8781 (org-overview))
8782 (while (re-search-forward regexp nil t)
8783 (when (or (not callback)
8784 (save-match-data (funcall callback)))
8785 (setq cnt (1+ cnt))
8786 (when org-highlight-sparse-tree-matches
8787 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8788 (org-show-context 'occur-tree))))
8789 (when org-remove-highlights-with-change
8790 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8791 nil 'local))
8792 (unless org-sparse-tree-open-archived-trees
8793 (org-hide-archived-subtrees (point-min) (point-max)))
8794 (run-hooks 'org-occur-hook)
8795 (if (interactive-p)
8796 (message "%d match(es) for regexp %s" cnt regexp))
8797 cnt))
8799 (defun org-show-context (&optional key)
8800 "Make sure point and context and visible.
8801 How much context is shown depends upon the variables
8802 `org-show-hierarchy-above', `org-show-following-heading'. and
8803 `org-show-siblings'."
8804 (let ((heading-p (org-on-heading-p t))
8805 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8806 (following-p (org-get-alist-option org-show-following-heading key))
8807 (entry-p (org-get-alist-option org-show-entry-below key))
8808 (siblings-p (org-get-alist-option org-show-siblings key)))
8809 (catch 'exit
8810 ;; Show heading or entry text
8811 (if (and heading-p (not entry-p))
8812 (org-flag-heading nil) ; only show the heading
8813 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8814 (org-show-hidden-entry))) ; show entire entry
8815 (when following-p
8816 ;; Show next sibling, or heading below text
8817 (save-excursion
8818 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8819 (org-flag-heading nil))))
8820 (when siblings-p (org-show-siblings))
8821 (when hierarchy-p
8822 ;; show all higher headings, possibly with siblings
8823 (save-excursion
8824 (while (and (condition-case nil
8825 (progn (org-up-heading-all 1) t)
8826 (error nil))
8827 (not (bobp)))
8828 (org-flag-heading nil)
8829 (when siblings-p (org-show-siblings))))))))
8831 (defun org-reveal (&optional siblings)
8832 "Show current entry, hierarchy above it, and the following headline.
8833 This can be used to show a consistent set of context around locations
8834 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8835 not t for the search context.
8837 With optional argument SIBLINGS, on each level of the hierarchy all
8838 siblings are shown. This repairs the tree structure to what it would
8839 look like when opened with hierarchical calls to `org-cycle'."
8840 (interactive "P")
8841 (let ((org-show-hierarchy-above t)
8842 (org-show-following-heading t)
8843 (org-show-siblings (if siblings t org-show-siblings)))
8844 (org-show-context nil)))
8846 (defun org-highlight-new-match (beg end)
8847 "Highlight from BEG to END and mark the highlight is an occur headline."
8848 (let ((ov (org-make-overlay beg end)))
8849 (org-overlay-put ov 'face 'secondary-selection)
8850 (push ov org-occur-highlights)))
8852 (defun org-remove-occur-highlights (&optional beg end noremove)
8853 "Remove the occur highlights from the buffer.
8854 BEG and END are ignored. If NOREMOVE is nil, remove this function
8855 from the `before-change-functions' in the current buffer."
8856 (interactive)
8857 (unless org-inhibit-highlight-removal
8858 (mapc 'org-delete-overlay org-occur-highlights)
8859 (setq org-occur-highlights nil)
8860 (setq org-occur-parameters nil)
8861 (unless noremove
8862 (remove-hook 'before-change-functions
8863 'org-remove-occur-highlights 'local))))
8865 ;;;; Priorities
8867 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8868 "Regular expression matching the priority indicator.")
8870 (defvar org-remove-priority-next-time nil)
8872 (defun org-priority-up ()
8873 "Increase the priority of the current item."
8874 (interactive)
8875 (org-priority 'up))
8877 (defun org-priority-down ()
8878 "Decrease the priority of the current item."
8879 (interactive)
8880 (org-priority 'down))
8882 (defun org-priority (&optional action)
8883 "Change the priority of an item by ARG.
8884 ACTION can be `set', `up', `down', or a character."
8885 (interactive)
8886 (setq action (or action 'set))
8887 (let (current new news have remove)
8888 (save-excursion
8889 (org-back-to-heading)
8890 (if (looking-at org-priority-regexp)
8891 (setq current (string-to-char (match-string 2))
8892 have t)
8893 (setq current org-default-priority))
8894 (cond
8895 ((or (eq action 'set)
8896 (if (featurep 'xemacs) (characterp action) (integerp action)))
8897 (if (not (eq action 'set))
8898 (setq new action)
8899 (message "Priority %c-%c, SPC to remove: "
8900 org-highest-priority org-lowest-priority)
8901 (setq new (read-char-exclusive)))
8902 (if (and (= (upcase org-highest-priority) org-highest-priority)
8903 (= (upcase org-lowest-priority) org-lowest-priority))
8904 (setq new (upcase new)))
8905 (cond ((equal new ?\ ) (setq remove t))
8906 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8907 (error "Priority must be between `%c' and `%c'"
8908 org-highest-priority org-lowest-priority))))
8909 ((eq action 'up)
8910 (if (and (not have) (eq last-command this-command))
8911 (setq new org-lowest-priority)
8912 (setq new (if (and org-priority-start-cycle-with-default (not have))
8913 org-default-priority (1- current)))))
8914 ((eq action 'down)
8915 (if (and (not have) (eq last-command this-command))
8916 (setq new org-highest-priority)
8917 (setq new (if (and org-priority-start-cycle-with-default (not have))
8918 org-default-priority (1+ current)))))
8919 (t (error "Invalid action")))
8920 (if (or (< (upcase new) org-highest-priority)
8921 (> (upcase new) org-lowest-priority))
8922 (setq remove t))
8923 (setq news (format "%c" new))
8924 (if have
8925 (if remove
8926 (replace-match "" t t nil 1)
8927 (replace-match news t t nil 2))
8928 (if remove
8929 (error "No priority cookie found in line")
8930 (looking-at org-todo-line-regexp)
8931 (if (match-end 2)
8932 (progn
8933 (goto-char (match-end 2))
8934 (insert " [#" news "]"))
8935 (goto-char (match-beginning 3))
8936 (insert "[#" news "] ")))))
8937 (org-preserve-lc (org-set-tags nil 'align))
8938 (if remove
8939 (message "Priority removed")
8940 (message "Priority of current item set to %s" news))))
8943 (defun org-get-priority (s)
8944 "Find priority cookie and return priority."
8945 (save-match-data
8946 (if (not (string-match org-priority-regexp s))
8947 (* 1000 (- org-lowest-priority org-default-priority))
8948 (* 1000 (- org-lowest-priority
8949 (string-to-char (match-string 2 s)))))))
8951 ;;;; Tags
8953 (defvar org-agenda-archives-mode)
8954 (defun org-scan-tags (action matcher &optional todo-only)
8955 "Scan headline tags with inheritance and produce output ACTION.
8957 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8958 or `agenda' to produce an entry list for an agenda view. It can also be
8959 a Lisp form or a function that should be called at each matched headline, in
8960 this case the return value is a list of all return values from these calls.
8962 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8963 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8964 only lines with a TODO keyword are included in the output."
8965 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8966 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8967 (org-re
8968 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8969 (props (list 'face 'default
8970 'done-face 'org-done
8971 'undone-face 'default
8972 'mouse-face 'highlight
8973 'org-not-done-regexp org-not-done-regexp
8974 'org-todo-regexp org-todo-regexp
8975 'keymap org-agenda-keymap
8976 'help-echo
8977 (format "mouse-2 or RET jump to org file %s"
8978 (abbreviate-file-name
8979 (or (buffer-file-name (buffer-base-buffer))
8980 (buffer-name (buffer-base-buffer)))))))
8981 (case-fold-search nil)
8982 lspos tags tags-list
8983 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8984 (llast 0) rtn rtn1 level category i txt
8985 todo marker entry priority)
8986 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8987 (setq action (list 'lambda nil action)))
8988 (save-excursion
8989 (goto-char (point-min))
8990 (when (eq action 'sparse-tree)
8991 (org-overview)
8992 (org-remove-occur-highlights))
8993 (while (re-search-forward re nil t)
8994 (catch :skip
8995 (setq todo (if (match-end 1) (match-string 2))
8996 tags (if (match-end 4) (match-string 4)))
8997 (goto-char (setq lspos (1+ (match-beginning 0))))
8998 (setq level (org-reduced-level (funcall outline-level))
8999 category (org-get-category))
9000 (setq i llast llast level)
9001 ;; remove tag lists from same and sublevels
9002 (while (>= i level)
9003 (when (setq entry (assoc i tags-alist))
9004 (setq tags-alist (delete entry tags-alist)))
9005 (setq i (1- i)))
9006 ;; add the next tags
9007 (when tags
9008 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9009 tags-alist
9010 (cons (cons level tags) tags-alist)))
9011 ;; compile tags for current headline
9012 (setq tags-list
9013 (if org-use-tag-inheritance
9014 (apply 'append (mapcar 'cdr tags-alist))
9015 tags))
9016 (when (and tags org-use-tag-inheritance
9017 (not (eq t org-use-tag-inheritance)))
9018 ;; selective inheritance, remove uninherited ones
9019 (setcdr (car tags-alist)
9020 (org-remove-uniherited-tags (cdar tags-alist))))
9021 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9022 (let ((case-fold-search t)) (eval matcher))
9024 (not (member org-archive-tag tags-list))
9025 ;; we have an archive tag, should we use this anyway?
9026 (or (not org-agenda-skip-archived-trees)
9027 (and (eq action 'agenda) org-agenda-archives-mode))))
9028 (unless (eq action 'sparse-tree) (org-agenda-skip))
9030 ;; select this headline
9032 (cond
9033 ((eq action 'sparse-tree)
9034 (and org-highlight-sparse-tree-matches
9035 (org-get-heading) (match-end 0)
9036 (org-highlight-new-match
9037 (match-beginning 0) (match-beginning 1)))
9038 (org-show-context 'tags-tree))
9039 ((eq action 'agenda)
9040 (setq txt (org-format-agenda-item
9042 (concat
9043 (if org-tags-match-list-sublevels
9044 (make-string (1- level) ?.) "")
9045 (org-get-heading))
9046 category tags-list)
9047 priority (org-get-priority txt))
9048 (goto-char lspos)
9049 (setq marker (org-agenda-new-marker))
9050 (org-add-props txt props
9051 'org-marker marker 'org-hd-marker marker 'org-category category
9052 'priority priority 'type "tagsmatch")
9053 (push txt rtn))
9054 ((functionp action)
9055 (save-excursion
9056 (setq rtn1 (funcall action))
9057 (push rtn1 rtn))
9058 (goto-char (point-at-eol)))
9059 (t (error "Invalid action")))
9061 ;; if we are to skip sublevels, jump to end of subtree
9062 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9063 (when (and (eq action 'sparse-tree)
9064 (not org-sparse-tree-open-archived-trees))
9065 (org-hide-archived-subtrees (point-min) (point-max)))
9066 (nreverse rtn)))
9068 (defun org-remove-uniherited-tags (tags)
9069 "Remove all tags that are not inherited from the list TAGS."
9070 (cond
9071 ((eq org-use-tag-inheritance t) tags)
9072 ((not org-use-tag-inheritance) nil)
9073 ((stringp org-use-tag-inheritance)
9074 (delq nil (mapcar
9075 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9076 tags)))
9077 ((listp org-use-tag-inheritance)
9078 (delq nil (mapcar
9079 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
9080 tags)))))
9082 (defvar todo-only) ;; dynamically scoped
9084 (defun org-tags-sparse-tree (&optional todo-only match)
9085 "Create a sparse tree according to tags string MATCH.
9086 MATCH can contain positive and negative selection of tags, like
9087 \"+WORK+URGENT-WITHBOSS\".
9088 If optional argument TODO_ONLY is non-nil, only select lines that are
9089 also TODO lines."
9090 (interactive "P")
9091 (org-prepare-agenda-buffers (list (current-buffer)))
9092 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9094 (defvar org-cached-props nil)
9095 (defun org-cached-entry-get (pom property)
9096 (if (or (eq t org-use-property-inheritance)
9097 (and (stringp org-use-property-inheritance)
9098 (string-match org-use-property-inheritance property))
9099 (and (listp org-use-property-inheritance)
9100 (member property org-use-property-inheritance)))
9101 ;; Caching is not possible, check it directly
9102 (org-entry-get pom property 'inherit)
9103 ;; Get all properties, so that we can do complicated checks easily
9104 (cdr (assoc property (or org-cached-props
9105 (setq org-cached-props
9106 (org-entry-properties pom)))))))
9108 (defun org-global-tags-completion-table (&optional files)
9109 "Return the list of all tags in all agenda buffer/files."
9110 (save-excursion
9111 (org-uniquify
9112 (delq nil
9113 (apply 'append
9114 (mapcar
9115 (lambda (file)
9116 (set-buffer (find-file-noselect file))
9117 (append (org-get-buffer-tags)
9118 (mapcar (lambda (x) (if (stringp (car-safe x))
9119 (list (car-safe x)) nil))
9120 org-tag-alist)))
9121 (if (and files (car files))
9122 files
9123 (org-agenda-files))))))))
9125 (defun org-make-tags-matcher (match)
9126 "Create the TAGS//TODO matcher form for the selection string MATCH."
9127 ;; todo-only is scoped dynamically into this function, and the function
9128 ;; may change it it the matcher asksk for it.
9129 (unless match
9130 ;; Get a new match request, with completion
9131 (let ((org-last-tags-completion-table
9132 (org-global-tags-completion-table)))
9133 (setq match (org-ido-completing-read
9134 "Match: " 'org-tags-completion-function nil nil nil
9135 'org-tags-history))))
9137 ;; Parse the string and create a lisp form
9138 (let ((match0 match)
9139 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9140 minus tag mm
9141 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9142 orterms term orlist re-p str-p level-p level-op time-p
9143 prop-p pn pv po cat-p gv rest)
9144 (if (string-match "/+" match)
9145 ;; match contains also a todo-matching request
9146 (progn
9147 (setq tagsmatch (substring match 0 (match-beginning 0))
9148 todomatch (substring match (match-end 0)))
9149 (if (string-match "^!" todomatch)
9150 (setq todo-only t todomatch (substring todomatch 1)))
9151 (if (string-match "^\\s-*$" todomatch)
9152 (setq todomatch nil)))
9153 ;; only matching tags
9154 (setq tagsmatch match todomatch nil))
9156 ;; Make the tags matcher
9157 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9158 (setq tagsmatcher t)
9159 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9160 (while (setq term (pop orterms))
9161 (while (and (equal (substring term -1) "\\") orterms)
9162 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9163 (while (string-match re term)
9164 (setq rest (substring term (match-end 0))
9165 minus (and (match-end 1)
9166 (equal (match-string 1 term) "-"))
9167 tag (match-string 2 term)
9168 re-p (equal (string-to-char tag) ?{)
9169 level-p (match-end 4)
9170 prop-p (match-end 5)
9171 mm (cond
9172 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9173 (level-p
9174 (setq level-op (org-op-to-function (match-string 3 term)))
9175 `(,level-op level ,(string-to-number
9176 (match-string 4 term))))
9177 (prop-p
9178 (setq pn (match-string 5 term)
9179 po (match-string 6 term)
9180 pv (match-string 7 term)
9181 cat-p (equal pn "CATEGORY")
9182 re-p (equal (string-to-char pv) ?{)
9183 str-p (equal (string-to-char pv) ?\")
9184 time-p (save-match-data
9185 (string-match "^\"[[<].*[]>]\"$" pv))
9186 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9187 (if time-p (setq pv (org-matcher-time pv)))
9188 (setq po (org-op-to-function po (if time-p 'time str-p)))
9189 (cond
9190 ((equal pn "CATEGORY")
9191 (setq gv '(get-text-property (point) 'org-category)))
9192 ((equal pn "TODO")
9193 (setq gv 'todo))
9195 (setq gv `(org-cached-entry-get nil ,pn))))
9196 (if re-p
9197 (if (eq po 'org<>)
9198 `(not (string-match ,pv (or ,gv "")))
9199 `(string-match ,pv (or ,gv "")))
9200 (if str-p
9201 `(,po (or ,gv "") ,pv)
9202 `(,po (string-to-number (or ,gv ""))
9203 ,(string-to-number pv) ))))
9204 (t `(member ,(downcase tag) tags-list)))
9205 mm (if minus (list 'not mm) mm)
9206 term rest)
9207 (push mm tagsmatcher))
9208 (push (if (> (length tagsmatcher) 1)
9209 (cons 'and tagsmatcher)
9210 (car tagsmatcher))
9211 orlist)
9212 (setq tagsmatcher nil))
9213 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9214 (setq tagsmatcher
9215 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9216 ;; Make the todo matcher
9217 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9218 (setq todomatcher t)
9219 (setq orterms (org-split-string todomatch "|") orlist nil)
9220 (while (setq term (pop orterms))
9221 (while (string-match re term)
9222 (setq minus (and (match-end 1)
9223 (equal (match-string 1 term) "-"))
9224 kwd (match-string 2 term)
9225 re-p (equal (string-to-char kwd) ?{)
9226 term (substring term (match-end 0))
9227 mm (if re-p
9228 `(string-match ,(substring kwd 1 -1) todo)
9229 (list 'equal 'todo kwd))
9230 mm (if minus (list 'not mm) mm))
9231 (push mm todomatcher))
9232 (push (if (> (length todomatcher) 1)
9233 (cons 'and todomatcher)
9234 (car todomatcher))
9235 orlist)
9236 (setq todomatcher nil))
9237 (setq todomatcher (if (> (length orlist) 1)
9238 (cons 'or orlist) (car orlist))))
9240 ;; Return the string and lisp forms of the matcher
9241 (setq matcher (if todomatcher
9242 (list 'and tagsmatcher todomatcher)
9243 tagsmatcher))
9244 (cons match0 matcher)))
9246 (defun org-op-to-function (op &optional stringp)
9247 "Turn an operator into the appropriate function."
9248 (setq op
9249 (cond
9250 ((equal op "<" ) '(< string< org-time<))
9251 ((equal op ">" ) '(> org-string> org-time>))
9252 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9253 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9254 ((member op '("=" "==")) '(= string= org-time=))
9255 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9256 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9258 (defun org<> (a b) (not (= a b)))
9259 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9260 (defun org-string>= (a b) (not (string< a b)))
9261 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9262 (defun org-string<> (a b) (not (string= a b)))
9263 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9264 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9265 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9266 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9267 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9268 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9269 (defun org-2ft (s)
9270 "Convert S to a floating point time.
9271 If S is already a number, just return it. If it is a string, parse
9272 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9273 (cond
9274 ((numberp s) s)
9275 ((stringp s)
9276 (condition-case nil
9277 (float-time (apply 'encode-time (org-parse-time-string s)))
9278 (error 0.)))
9279 (t 0.)))
9281 (defun org-time-today ()
9282 "Time in seconds today at 0:00.
9283 Returns the float number of seconds since the beginning of the
9284 epoch to the beginning of today (00:00)."
9285 (float-time (apply 'encode-time
9286 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9288 (defun org-matcher-time (s)
9289 (cond
9290 ((string= s "<now>") (float-time))
9291 ((string= s "<today>") (org-time-today))
9292 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9293 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9294 (t (org-2ft s))))
9296 (defun org-match-any-p (re list)
9297 "Does re match any element of list?"
9298 (setq list (mapcar (lambda (x) (string-match re x)) list))
9299 (delq nil list))
9301 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9302 (defvar org-tags-overlay (org-make-overlay 1 1))
9303 (org-detach-overlay org-tags-overlay)
9305 (defun org-get-local-tags-at (&optional pos)
9306 "Get a list of tags defined in the current headline."
9307 (org-get-tags-at pos 'local))
9309 (defun org-get-local-tags ()
9310 "Get a list of tags defined in the current headline."
9311 (org-get-tags-at nil 'local))
9313 (defun org-get-tags-at (&optional pos local)
9314 "Get a list of all headline tags applicable at POS.
9315 POS defaults to point. If tags are inherited, the list contains
9316 the targets in the same sequence as the headlines appear, i.e.
9317 the tags of the current headline come last.
9318 When LOCAL is non-nil, only return tags from the current headline,
9319 ignore inherited ones."
9320 (interactive)
9321 (let (tags ltags lastpos parent)
9322 (save-excursion
9323 (save-restriction
9324 (widen)
9325 (goto-char (or pos (point)))
9326 (save-match-data
9327 (catch 'done
9328 (condition-case nil
9329 (progn
9330 (org-back-to-heading t)
9331 (while (not (equal lastpos (point)))
9332 (setq lastpos (point))
9333 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9334 (setq ltags (org-split-string
9335 (org-match-string-no-properties 1) ":"))
9336 (setq tags (append
9337 (if parent
9338 (org-remove-uniherited-tags ltags)
9339 ltags)
9340 tags)))
9341 (or org-use-tag-inheritance (throw 'done t))
9342 (if local (throw 'done t))
9343 (org-up-heading-all 1)
9344 (setq parent t)))
9345 (error nil)))))
9346 (append (org-remove-uniherited-tags org-file-tags) tags))))
9348 (defun org-toggle-tag (tag &optional onoff)
9349 "Toggle the tag TAG for the current line.
9350 If ONOFF is `on' or `off', don't toggle but set to this state."
9351 (unless (org-on-heading-p t) (error "Not on headling"))
9352 (let (res current)
9353 (save-excursion
9354 (beginning-of-line)
9355 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9356 (point-at-eol) t)
9357 (progn
9358 (setq current (match-string 1))
9359 (replace-match ""))
9360 (setq current ""))
9361 (setq current (nreverse (org-split-string current ":")))
9362 (cond
9363 ((eq onoff 'on)
9364 (setq res t)
9365 (or (member tag current) (push tag current)))
9366 ((eq onoff 'off)
9367 (or (not (member tag current)) (setq current (delete tag current))))
9368 (t (if (member tag current)
9369 (setq current (delete tag current))
9370 (setq res t)
9371 (push tag current))))
9372 (end-of-line 1)
9373 (if current
9374 (progn
9375 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9376 (org-set-tags nil t))
9377 (delete-horizontal-space))
9378 (run-hooks 'org-after-tags-change-hook))
9379 res))
9381 (defun org-align-tags-here (to-col)
9382 ;; Assumes that this is a headline
9383 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9384 (beginning-of-line 1)
9385 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9386 (< pos (match-beginning 2)))
9387 (progn
9388 (setq tags-l (- (match-end 2) (match-beginning 2)))
9389 (goto-char (match-beginning 1))
9390 (insert " ")
9391 (delete-region (point) (1+ (match-beginning 2)))
9392 (setq ncol (max (1+ (current-column))
9393 (1+ col)
9394 (if (> to-col 0)
9395 to-col
9396 (- (abs to-col) tags-l))))
9397 (setq p (point))
9398 (insert (make-string (- ncol (current-column)) ?\ ))
9399 (setq ncol (current-column))
9400 (when indent-tabs-mode (tabify p (point-at-eol)))
9401 (org-move-to-column (min ncol col) t))
9402 (goto-char pos))))
9404 (defun org-set-tags-command (&optional arg just-align)
9405 "Call the set-tags command for the current entry."
9406 (interactive "P")
9407 (if (org-on-heading-p)
9408 (org-set-tags arg just-align)
9409 (save-excursion
9410 (org-back-to-heading t)
9411 (org-set-tags arg just-align))))
9413 (defun org-set-tags (&optional arg just-align)
9414 "Set the tags for the current headline.
9415 With prefix ARG, realign all tags in headings in the current buffer."
9416 (interactive "P")
9417 (let* ((re (concat "^" outline-regexp))
9418 (current (org-get-tags-string))
9419 (col (current-column))
9420 (org-setting-tags t)
9421 table current-tags inherited-tags ; computed below when needed
9422 tags p0 c0 c1 rpl)
9423 (if arg
9424 (save-excursion
9425 (goto-char (point-min))
9426 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9427 (while (re-search-forward re nil t)
9428 (org-set-tags nil t)
9429 (end-of-line 1)))
9430 (message "All tags realigned to column %d" org-tags-column))
9431 (if just-align
9432 (setq tags current)
9433 ;; Get a new set of tags from the user
9434 (save-excursion
9435 (setq table (or org-tag-alist (org-get-buffer-tags))
9436 org-last-tags-completion-table table
9437 current-tags (org-split-string current ":")
9438 inherited-tags (nreverse
9439 (nthcdr (length current-tags)
9440 (nreverse (org-get-tags-at))))
9441 tags
9442 (if (or (eq t org-use-fast-tag-selection)
9443 (and org-use-fast-tag-selection
9444 (delq nil (mapcar 'cdr table))))
9445 (org-fast-tag-selection
9446 current-tags inherited-tags table
9447 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9448 (let ((org-add-colon-after-tag-completion t))
9449 (org-trim
9450 (org-without-partial-completion
9451 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9452 nil nil current 'org-tags-history)))))))
9453 (while (string-match "[-+&]+" tags)
9454 ;; No boolean logic, just a list
9455 (setq tags (replace-match ":" t t tags))))
9457 (if (string-match "\\`[\t ]*\\'" tags)
9458 (setq tags "")
9459 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9460 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9462 ;; Insert new tags at the correct column
9463 (beginning-of-line 1)
9464 (cond
9465 ((and (equal current "") (equal tags "")))
9466 ((re-search-forward
9467 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9468 (point-at-eol) t)
9469 (if (equal tags "")
9470 (setq rpl "")
9471 (goto-char (match-beginning 0))
9472 (setq c0 (current-column) p0 (point)
9473 c1 (max (1+ c0) (if (> org-tags-column 0)
9474 org-tags-column
9475 (- (- org-tags-column) (length tags))))
9476 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9477 (replace-match rpl t t)
9478 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9479 tags)
9480 (t (error "Tags alignment failed")))
9481 (org-move-to-column col)
9482 (unless just-align
9483 (run-hooks 'org-after-tags-change-hook)))))
9485 (defun org-change-tag-in-region (beg end tag off)
9486 "Add or remove TAG for each entry in the region.
9487 This works in the agenda, and also in an org-mode buffer."
9488 (interactive
9489 (list (region-beginning) (region-end)
9490 (let ((org-last-tags-completion-table
9491 (if (org-mode-p)
9492 (org-get-buffer-tags)
9493 (org-global-tags-completion-table))))
9494 (org-ido-completing-read
9495 "Tag: " 'org-tags-completion-function nil nil nil
9496 'org-tags-history))
9497 (progn
9498 (message "[s]et or [r]emove? ")
9499 (equal (read-char-exclusive) ?r))))
9500 (if (fboundp 'deactivate-mark) (deactivate-mark))
9501 (let ((agendap (equal major-mode 'org-agenda-mode))
9502 l1 l2 m buf pos newhead (cnt 0))
9503 (goto-char end)
9504 (setq l2 (1- (org-current-line)))
9505 (goto-char beg)
9506 (setq l1 (org-current-line))
9507 (loop for l from l1 to l2 do
9508 (goto-line l)
9509 (setq m (get-text-property (point) 'org-hd-marker))
9510 (when (or (and (org-mode-p) (org-on-heading-p))
9511 (and agendap m))
9512 (setq buf (if agendap (marker-buffer m) (current-buffer))
9513 pos (if agendap m (point)))
9514 (with-current-buffer buf
9515 (save-excursion
9516 (save-restriction
9517 (goto-char pos)
9518 (setq cnt (1+ cnt))
9519 (org-toggle-tag tag (if off 'off 'on))
9520 (setq newhead (org-get-heading)))))
9521 (and agendap (org-agenda-change-all-lines newhead m))))
9522 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9524 (defun org-tags-completion-function (string predicate &optional flag)
9525 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9526 (confirm (lambda (x) (stringp (car x)))))
9527 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9528 (setq s1 (match-string 1 string)
9529 s2 (match-string 2 string))
9530 (setq s1 "" s2 string))
9531 (cond
9532 ((eq flag nil)
9533 ;; try completion
9534 (setq rtn (try-completion s2 ctable confirm))
9535 (if (stringp rtn)
9536 (setq rtn
9537 (concat s1 s2 (substring rtn (length s2))
9538 (if (and org-add-colon-after-tag-completion
9539 (assoc rtn ctable))
9540 ":" ""))))
9541 rtn)
9542 ((eq flag t)
9543 ;; all-completions
9544 (all-completions s2 ctable confirm)
9546 ((eq flag 'lambda)
9547 ;; exact match?
9548 (assoc s2 ctable)))
9551 (defun org-fast-tag-insert (kwd tags face &optional end)
9552 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9553 (insert (format "%-12s" (concat kwd ":"))
9554 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9555 (or end "")))
9557 (defun org-fast-tag-show-exit (flag)
9558 (save-excursion
9559 (goto-line 3)
9560 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9561 (replace-match ""))
9562 (when flag
9563 (end-of-line 1)
9564 (org-move-to-column (- (window-width) 19) t)
9565 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9567 (defun org-set-current-tags-overlay (current prefix)
9568 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9569 (if (featurep 'xemacs)
9570 (org-overlay-display org-tags-overlay (concat prefix s)
9571 'secondary-selection)
9572 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9573 (org-overlay-display org-tags-overlay (concat prefix s)))))
9575 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9576 "Fast tag selection with single keys.
9577 CURRENT is the current list of tags in the headline, INHERITED is the
9578 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9579 possibly with grouping information. TODO-TABLE is a similar table with
9580 TODO keywords, should these have keys assigned to them.
9581 If the keys are nil, a-z are automatically assigned.
9582 Returns the new tags string, or nil to not change the current settings."
9583 (let* ((fulltable (append table todo-table))
9584 (maxlen (apply 'max (mapcar
9585 (lambda (x)
9586 (if (stringp (car x)) (string-width (car x)) 0))
9587 fulltable)))
9588 (buf (current-buffer))
9589 (expert (eq org-fast-tag-selection-single-key 'expert))
9590 (buffer-tags nil)
9591 (fwidth (+ maxlen 3 1 3))
9592 (ncol (/ (- (window-width) 4) fwidth))
9593 (i-face 'org-done)
9594 (c-face 'org-todo)
9595 tg cnt e c char c1 c2 ntable tbl rtn
9596 ov-start ov-end ov-prefix
9597 (exit-after-next org-fast-tag-selection-single-key)
9598 (done-keywords org-done-keywords)
9599 groups ingroup)
9600 (save-excursion
9601 (beginning-of-line 1)
9602 (if (looking-at
9603 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9604 (setq ov-start (match-beginning 1)
9605 ov-end (match-end 1)
9606 ov-prefix "")
9607 (setq ov-start (1- (point-at-eol))
9608 ov-end (1+ ov-start))
9609 (skip-chars-forward "^\n\r")
9610 (setq ov-prefix
9611 (concat
9612 (buffer-substring (1- (point)) (point))
9613 (if (> (current-column) org-tags-column)
9615 (make-string (- org-tags-column (current-column)) ?\ ))))))
9616 (org-move-overlay org-tags-overlay ov-start ov-end)
9617 (save-window-excursion
9618 (if expert
9619 (set-buffer (get-buffer-create " *Org tags*"))
9620 (delete-other-windows)
9621 (split-window-vertically)
9622 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9623 (erase-buffer)
9624 (org-set-local 'org-done-keywords done-keywords)
9625 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9626 (org-fast-tag-insert "Current" current c-face "\n\n")
9627 (org-fast-tag-show-exit exit-after-next)
9628 (org-set-current-tags-overlay current ov-prefix)
9629 (setq tbl fulltable char ?a cnt 0)
9630 (while (setq e (pop tbl))
9631 (cond
9632 ((equal e '(:startgroup))
9633 (push '() groups) (setq ingroup t)
9634 (when (not (= cnt 0))
9635 (setq cnt 0)
9636 (insert "\n"))
9637 (insert "{ "))
9638 ((equal e '(:endgroup))
9639 (setq ingroup nil cnt 0)
9640 (insert "}\n"))
9642 (setq tg (car e) c2 nil)
9643 (if (cdr e)
9644 (setq c (cdr e))
9645 ;; automatically assign a character.
9646 (setq c1 (string-to-char
9647 (downcase (substring
9648 tg (if (= (string-to-char tg) ?@) 1 0)))))
9649 (if (or (rassoc c1 ntable) (rassoc c1 table))
9650 (while (or (rassoc char ntable) (rassoc char table))
9651 (setq char (1+ char)))
9652 (setq c2 c1))
9653 (setq c (or c2 char)))
9654 (if ingroup (push tg (car groups)))
9655 (setq tg (org-add-props tg nil 'face
9656 (cond
9657 ((not (assoc tg table))
9658 (org-get-todo-face tg))
9659 ((member tg current) c-face)
9660 ((member tg inherited) i-face)
9661 (t nil))))
9662 (if (and (= cnt 0) (not ingroup)) (insert " "))
9663 (insert "[" c "] " tg (make-string
9664 (- fwidth 4 (length tg)) ?\ ))
9665 (push (cons tg c) ntable)
9666 (when (= (setq cnt (1+ cnt)) ncol)
9667 (insert "\n")
9668 (if ingroup (insert " "))
9669 (setq cnt 0)))))
9670 (setq ntable (nreverse ntable))
9671 (insert "\n")
9672 (goto-char (point-min))
9673 (if (not expert) (org-fit-window-to-buffer))
9674 (setq rtn
9675 (catch 'exit
9676 (while t
9677 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9678 (if groups " [!] no groups" " [!]groups")
9679 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9680 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9681 (cond
9682 ((= c ?\r) (throw 'exit t))
9683 ((= c ?!)
9684 (setq groups (not groups))
9685 (goto-char (point-min))
9686 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9687 ((= c ?\C-c)
9688 (if (not expert)
9689 (org-fast-tag-show-exit
9690 (setq exit-after-next (not exit-after-next)))
9691 (setq expert nil)
9692 (delete-other-windows)
9693 (split-window-vertically)
9694 (org-switch-to-buffer-other-window " *Org tags*")
9695 (org-fit-window-to-buffer)))
9696 ((or (= c ?\C-g)
9697 (and (= c ?q) (not (rassoc c ntable))))
9698 (org-detach-overlay org-tags-overlay)
9699 (setq quit-flag t))
9700 ((= c ?\ )
9701 (setq current nil)
9702 (if exit-after-next (setq exit-after-next 'now)))
9703 ((= c ?\t)
9704 (condition-case nil
9705 (setq tg (org-ido-completing-read
9706 "Tag: "
9707 (or buffer-tags
9708 (with-current-buffer buf
9709 (org-get-buffer-tags)))))
9710 (quit (setq tg "")))
9711 (when (string-match "\\S-" tg)
9712 (add-to-list 'buffer-tags (list tg))
9713 (if (member tg current)
9714 (setq current (delete tg current))
9715 (push tg current)))
9716 (if exit-after-next (setq exit-after-next 'now)))
9717 ((setq e (rassoc c todo-table) tg (car e))
9718 (with-current-buffer buf
9719 (save-excursion (org-todo tg)))
9720 (if exit-after-next (setq exit-after-next 'now)))
9721 ((setq e (rassoc c ntable) tg (car e))
9722 (if (member tg current)
9723 (setq current (delete tg current))
9724 (loop for g in groups do
9725 (if (member tg g)
9726 (mapc (lambda (x)
9727 (setq current (delete x current)))
9728 g)))
9729 (push tg current))
9730 (if exit-after-next (setq exit-after-next 'now))))
9732 ;; Create a sorted list
9733 (setq current
9734 (sort current
9735 (lambda (a b)
9736 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9737 (if (eq exit-after-next 'now) (throw 'exit t))
9738 (goto-char (point-min))
9739 (beginning-of-line 2)
9740 (delete-region (point) (point-at-eol))
9741 (org-fast-tag-insert "Current" current c-face)
9742 (org-set-current-tags-overlay current ov-prefix)
9743 (while (re-search-forward
9744 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9745 (setq tg (match-string 1))
9746 (add-text-properties
9747 (match-beginning 1) (match-end 1)
9748 (list 'face
9749 (cond
9750 ((member tg current) c-face)
9751 ((member tg inherited) i-face)
9752 (t (get-text-property (match-beginning 1) 'face))))))
9753 (goto-char (point-min)))))
9754 (org-detach-overlay org-tags-overlay)
9755 (if rtn
9756 (mapconcat 'identity current ":")
9757 nil))))
9759 (defun org-get-tags-string ()
9760 "Get the TAGS string in the current headline."
9761 (unless (org-on-heading-p t)
9762 (error "Not on a heading"))
9763 (save-excursion
9764 (beginning-of-line 1)
9765 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9766 (org-match-string-no-properties 1)
9767 "")))
9769 (defun org-get-tags ()
9770 "Get the list of tags specified in the current headline."
9771 (org-split-string (org-get-tags-string) ":"))
9773 (defun org-get-buffer-tags ()
9774 "Get a table of all tags used in the buffer, for completion."
9775 (let (tags)
9776 (save-excursion
9777 (goto-char (point-min))
9778 (while (re-search-forward
9779 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9780 (when (equal (char-after (point-at-bol 0)) ?*)
9781 (mapc (lambda (x) (add-to-list 'tags x))
9782 (org-split-string (org-match-string-no-properties 1) ":")))))
9783 (mapcar 'list tags)))
9785 ;;;; The mapping API
9787 ;;;###autoload
9788 (defun org-map-entries (func &optional match scope &rest skip)
9789 "Call FUNC at each headline selected by MATCH in SCOPE.
9791 FUNC is a function or a lisp form. The function will be called without
9792 arguments, with the cursor positioned at the beginning of the headline.
9793 The return values of all calls to the function will be collected and
9794 returned as a list.
9796 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9797 Only headlines that are matched by this query will be considered during
9798 the iteration. When MATCH is nil or t, all headlines will be
9799 visited by the iteration.
9801 SCOPE determines the scope of this command. It can be any of:
9803 nil The current buffer, respecting the restriction if any
9804 tree The subtree started with the entry at point
9805 file The current buffer, without restriction
9806 file-with-archives
9807 The current buffer, and any archives associated with it
9808 agenda All agenda files
9809 agenda-with-archives
9810 All agenda files with any archive files associated with them
9811 \(file1 file2 ...)
9812 If this is a list, all files in the list will be scanned
9814 The remaining args are treated as settings for the skipping facilities of
9815 the scanner. The following items can be given here:
9817 archive skip trees with the archive tag.
9818 comment skip trees with the COMMENT keyword
9819 function or Emacs Lisp form:
9820 will be used as value for `org-agenda-skip-function', so whenever
9821 the the function returns t, FUNC will not be called for that
9822 entry and search will continue from the point where the
9823 function leaves it."
9824 (let* ((org-agenda-archives-mode nil) ; just to make sure
9825 (org-agenda-skip-archived-trees (memq 'archive skip))
9826 (org-agenda-skip-comment-trees (memq 'comment skip))
9827 (org-agenda-skip-function
9828 (car (org-delete-all '(comment archive) skip)))
9829 (org-tags-match-list-sublevels t)
9830 matcher pos file
9831 org-todo-keywords-for-agenda
9832 org-done-keywords-for-agenda
9833 org-todo-keyword-alist-for-agenda
9834 org-tag-alist-for-agenda)
9836 (cond
9837 ((eq match t) (setq matcher t))
9838 ((eq match nil) (setq matcher t))
9839 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9841 (when (eq scope 'tree)
9842 (org-back-to-heading t)
9843 (org-narrow-to-subtree)
9844 (setq scope nil))
9846 (if (not scope)
9847 (progn
9848 (org-prepare-agenda-buffers
9849 (list (buffer-file-name (current-buffer))))
9850 (org-scan-tags func matcher))
9851 ;; Get the right scope
9852 (setq pos (point))
9853 (cond
9854 ((and scope (listp scope) (symbolp (car scope)))
9855 (setq scope (eval scope)))
9856 ((eq scope 'agenda)
9857 (setq scope (org-agenda-files t)))
9858 ((eq scope 'agenda-with-archives)
9859 (setq scope (org-agenda-files t))
9860 (setq scope (org-add-archive-files scope)))
9861 ((eq scope 'file)
9862 (setq scope (list (buffer-file-name))))
9863 ((eq scope 'file-with-archives)
9864 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9865 (org-prepare-agenda-buffers scope)
9866 (while (setq file (pop scope))
9867 (with-current-buffer (org-find-base-buffer-visiting file)
9868 (save-excursion
9869 (save-restriction
9870 (widen)
9871 (goto-char (point-min))
9872 (org-scan-tags func matcher))))))))
9874 ;;;; Properties
9876 ;;; Setting and retrieving properties
9878 (defconst org-special-properties
9879 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9880 "TIMESTAMP" "TIMESTAMP_IA")
9881 "The special properties valid in Org-mode.
9883 These are properties that are not defined in the property drawer,
9884 but in some other way.")
9886 (defconst org-default-properties
9887 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9888 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9889 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9890 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9891 "Some properties that are used by Org-mode for various purposes.
9892 Being in this list makes sure that they are offered for completion.")
9894 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9895 "Regular expression matching the first line of a property drawer.")
9897 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9898 "Regular expression matching the first line of a property drawer.")
9900 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9901 "Regular expression matching the first line of a property drawer.")
9903 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9904 "Regular expression matching the first line of a property drawer.")
9906 (defconst org-property-drawer-re
9907 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9908 org-property-end-re "\\)\n?")
9909 "Matches an entire property drawer.")
9911 (defconst org-clock-drawer-re
9912 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9913 org-property-end-re "\\)\n?")
9914 "Matches an entire clock drawer.")
9916 (defun org-property-action ()
9917 "Do an action on properties."
9918 (interactive)
9919 (let (c)
9920 (org-at-property-p)
9921 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9922 (setq c (read-char-exclusive))
9923 (cond
9924 ((equal c ?s)
9925 (call-interactively 'org-set-property))
9926 ((equal c ?d)
9927 (call-interactively 'org-delete-property))
9928 ((equal c ?D)
9929 (call-interactively 'org-delete-property-globally))
9930 ((equal c ?c)
9931 (call-interactively 'org-compute-property-at-point))
9932 (t (error "No such property action %c" c)))))
9934 (defun org-at-property-p ()
9935 "Is the cursor in a property line?"
9936 ;; FIXME: Does not check if we are actually in the drawer.
9937 ;; FIXME: also returns true on any drawers.....
9938 ;; This is used by C-c C-c for property action.
9939 (save-excursion
9940 (beginning-of-line 1)
9941 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9943 (defun org-get-property-block (&optional beg end force)
9944 "Return the (beg . end) range of the body of the property drawer.
9945 BEG and END can be beginning and end of subtree, if not given
9946 they will be found.
9947 If the drawer does not exist and FORCE is non-nil, create the drawer."
9948 (catch 'exit
9949 (save-excursion
9950 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9951 (end (or end (progn (outline-next-heading) (point)))))
9952 (goto-char beg)
9953 (if (re-search-forward org-property-start-re end t)
9954 (setq beg (1+ (match-end 0)))
9955 (if force
9956 (save-excursion
9957 (org-insert-property-drawer)
9958 (setq end (progn (outline-next-heading) (point))))
9959 (throw 'exit nil))
9960 (goto-char beg)
9961 (if (re-search-forward org-property-start-re end t)
9962 (setq beg (1+ (match-end 0)))))
9963 (if (re-search-forward org-property-end-re end t)
9964 (setq end (match-beginning 0))
9965 (or force (throw 'exit nil))
9966 (goto-char beg)
9967 (setq end beg)
9968 (org-indent-line-function)
9969 (insert ":END:\n"))
9970 (cons beg end)))))
9972 (defun org-entry-properties (&optional pom which)
9973 "Get all properties of the entry at point-or-marker POM.
9974 This includes the TODO keyword, the tags, time strings for deadline,
9975 scheduled, and clocking, and any additional properties defined in the
9976 entry. The return value is an alist, keys may occur multiple times
9977 if the property key was used several times.
9978 POM may also be nil, in which case the current entry is used.
9979 If WHICH is nil or `all', get all properties. If WHICH is
9980 `special' or `standard', only get that subclass."
9981 (setq which (or which 'all))
9982 (org-with-point-at pom
9983 (let ((clockstr (substring org-clock-string 0 -1))
9984 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9985 beg end range props sum-props key value string clocksum)
9986 (save-excursion
9987 (when (condition-case nil (org-back-to-heading t) (error nil))
9988 (setq beg (point))
9989 (setq sum-props (get-text-property (point) 'org-summaries))
9990 (setq clocksum (get-text-property (point) :org-clock-minutes))
9991 (outline-next-heading)
9992 (setq end (point))
9993 (when (memq which '(all special))
9994 ;; Get the special properties, like TODO and tags
9995 (goto-char beg)
9996 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9997 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9998 (when (looking-at org-priority-regexp)
9999 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10000 (when (and (setq value (org-get-tags-string))
10001 (string-match "\\S-" value))
10002 (push (cons "TAGS" value) props))
10003 (when (setq value (org-get-tags-at))
10004 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10005 props))
10006 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10007 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10008 string (if (equal key clockstr)
10009 (org-no-properties
10010 (org-trim
10011 (buffer-substring
10012 (match-beginning 3) (goto-char (point-at-eol)))))
10013 (substring (org-match-string-no-properties 3) 1 -1)))
10014 (unless key
10015 (if (= (char-after (match-beginning 3)) ?\[)
10016 (setq key "TIMESTAMP_IA")
10017 (setq key "TIMESTAMP")))
10018 (when (or (equal key clockstr) (not (assoc key props)))
10019 (push (cons key string) props)))
10023 (when (memq which '(all standard))
10024 ;; Get the standard properties, like :PORP: ...
10025 (setq range (org-get-property-block beg end))
10026 (when range
10027 (goto-char (car range))
10028 (while (re-search-forward
10029 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10030 (cdr range) t)
10031 (setq key (org-match-string-no-properties 1)
10032 value (org-trim (or (org-match-string-no-properties 2) "")))
10033 (unless (member key excluded)
10034 (push (cons key (or value "")) props)))))
10035 (if clocksum
10036 (push (cons "CLOCKSUM"
10037 (org-columns-number-to-string (/ (float clocksum) 60.)
10038 'add_times))
10039 props))
10040 (unless (assoc "CATEGORY" props)
10041 (setq value (or (org-get-category)
10042 (progn (org-refresh-category-properties)
10043 (org-get-category))))
10044 (push (cons "CATEGORY" value) props))
10045 (append sum-props (nreverse props)))))))
10047 (defun org-entry-get (pom property &optional inherit)
10048 "Get value of PROPERTY for entry at point-or-marker POM.
10049 If INHERIT is non-nil and the entry does not have the property,
10050 then also check higher levels of the hierarchy.
10051 If INHERIT is the symbol `selective', use inheritance only if the setting
10052 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10053 If the property is present but empty, the return value is the empty string.
10054 If the property is not present at all, nil is returned."
10055 (org-with-point-at pom
10056 (if (and inherit (if (eq inherit 'selective)
10057 (org-property-inherit-p property)
10059 (org-entry-get-with-inheritance property)
10060 (if (member property org-special-properties)
10061 ;; We need a special property. Use brute force, get all properties.
10062 (cdr (assoc property (org-entry-properties nil 'special)))
10063 (let ((range (org-get-property-block)))
10064 (if (and range
10065 (goto-char (car range))
10066 (re-search-forward
10067 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10068 (cdr range) t))
10069 ;; Found the property, return it.
10070 (if (match-end 1)
10071 (org-match-string-no-properties 1)
10072 "")))))))
10074 (defun org-property-or-variable-value (var &optional inherit)
10075 "Check if there is a property fixing the value of VAR.
10076 If yes, return this value. If not, return the current value of the variable."
10077 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10078 (if (and prop (stringp prop) (string-match "\\S-" prop))
10079 (read prop)
10080 (symbol-value var))))
10082 (defun org-entry-delete (pom property)
10083 "Delete the property PROPERTY from entry at point-or-marker POM."
10084 (org-with-point-at pom
10085 (if (member property org-special-properties)
10086 nil ; cannot delete these properties.
10087 (let ((range (org-get-property-block)))
10088 (if (and range
10089 (goto-char (car range))
10090 (re-search-forward
10091 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10092 (cdr range) t))
10093 (progn
10094 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10096 nil)))))
10098 ;; Multi-values properties are properties that contain multiple values
10099 ;; These values are assumed to be single words, separated by whitespace.
10100 (defun org-entry-add-to-multivalued-property (pom property value)
10101 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10102 (let* ((old (org-entry-get pom property))
10103 (values (and old (org-split-string old "[ \t]"))))
10104 (setq value (org-entry-protect-space value))
10105 (unless (member value values)
10106 (setq values (cons value values))
10107 (org-entry-put pom property
10108 (mapconcat 'identity values " ")))))
10110 (defun org-entry-remove-from-multivalued-property (pom property value)
10111 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10112 (let* ((old (org-entry-get pom property))
10113 (values (and old (org-split-string old "[ \t]"))))
10114 (setq value (org-entry-protect-space value))
10115 (when (member value values)
10116 (setq values (delete value values))
10117 (org-entry-put pom property
10118 (mapconcat 'identity values " ")))))
10120 (defun org-entry-member-in-multivalued-property (pom property value)
10121 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10122 (let* ((old (org-entry-get pom property))
10123 (values (and old (org-split-string old "[ \t]"))))
10124 (setq value (org-entry-protect-space value))
10125 (member value values)))
10127 (defun org-entry-get-multivalued-property (pom property)
10128 "Return a list of values in a multivalued property."
10129 (let* ((value (org-entry-get pom property))
10130 (values (and value (org-split-string value "[ \t]"))))
10131 (mapcar 'org-entry-restore-space values)))
10133 (defun org-entry-put-multivalued-property (pom property &rest values)
10134 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10135 VALUES should be a list of strings. Spaces will be protected."
10136 (org-entry-put pom property
10137 (mapconcat 'org-entry-protect-space values " "))
10138 (let* ((value (org-entry-get pom property))
10139 (values (and value (org-split-string value "[ \t]"))))
10140 (mapcar 'org-entry-restore-space values)))
10142 (defun org-entry-protect-space (s)
10143 "Protect spaces and newline in string S."
10144 (while (string-match " " s)
10145 (setq s (replace-match "%20" t t s)))
10146 (while (string-match "\n" s)
10147 (setq s (replace-match "%0A" t t s)))
10150 (defun org-entry-restore-space (s)
10151 "Restore spaces and newline in string S."
10152 (while (string-match "%20" s)
10153 (setq s (replace-match " " t t s)))
10154 (while (string-match "%0A" s)
10155 (setq s (replace-match "\n" t t s)))
10158 (defvar org-entry-property-inherited-from (make-marker)
10159 "Marker pointing to the entry from where a proerty was inherited.
10160 Each call to `org-entry-get-with-inheritance' will set this marker to the
10161 location of the entry where the inheriance search matched. If there was
10162 no match, the marker will point nowhere.
10163 Note that also `org-entry-get' calls this function, if the INHERIT flag
10164 is set.")
10166 (defun org-entry-get-with-inheritance (property)
10167 "Get entry property, and search higher levels if not present."
10168 (move-marker org-entry-property-inherited-from nil)
10169 (let (tmp)
10170 (save-excursion
10171 (save-restriction
10172 (widen)
10173 (catch 'ex
10174 (while t
10175 (when (setq tmp (org-entry-get nil property))
10176 (org-back-to-heading t)
10177 (move-marker org-entry-property-inherited-from (point))
10178 (throw 'ex tmp))
10179 (or (org-up-heading-safe) (throw 'ex nil)))))
10180 (or tmp
10181 (cdr (assoc property org-file-properties))
10182 (cdr (assoc property org-global-properties))
10183 (cdr (assoc property org-global-properties-fixed))))))
10185 (defun org-entry-put (pom property value)
10186 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10187 (org-with-point-at pom
10188 (org-back-to-heading t)
10189 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10190 range)
10191 (cond
10192 ((equal property "TODO")
10193 (when (and (stringp value) (string-match "\\S-" value)
10194 (not (member value org-todo-keywords-1)))
10195 (error "\"%s\" is not a valid TODO state" value))
10196 (if (or (not value)
10197 (not (string-match "\\S-" value)))
10198 (setq value 'none))
10199 (org-todo value)
10200 (org-set-tags nil 'align))
10201 ((equal property "PRIORITY")
10202 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10203 (string-to-char value) ?\ ))
10204 (org-set-tags nil 'align))
10205 ((equal property "SCHEDULED")
10206 (if (re-search-forward org-scheduled-time-regexp end t)
10207 (cond
10208 ((eq value 'earlier) (org-timestamp-change -1 'day))
10209 ((eq value 'later) (org-timestamp-change 1 'day))
10210 (t (call-interactively 'org-schedule)))
10211 (call-interactively 'org-schedule)))
10212 ((equal property "DEADLINE")
10213 (if (re-search-forward org-deadline-time-regexp end t)
10214 (cond
10215 ((eq value 'earlier) (org-timestamp-change -1 'day))
10216 ((eq value 'later) (org-timestamp-change 1 'day))
10217 (t (call-interactively 'org-deadline)))
10218 (call-interactively 'org-deadline)))
10219 ((member property org-special-properties)
10220 (error "The %s property can not yet be set with `org-entry-put'"
10221 property))
10222 (t ; a non-special property
10223 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10224 (setq range (org-get-property-block beg end 'force))
10225 (goto-char (car range))
10226 (if (re-search-forward
10227 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10228 (progn
10229 (delete-region (match-beginning 1) (match-end 1))
10230 (goto-char (match-beginning 1)))
10231 (goto-char (cdr range))
10232 (insert "\n")
10233 (backward-char 1)
10234 (org-indent-line-function)
10235 (insert ":" property ":"))
10236 (and value (insert " " value))
10237 (org-indent-line-function)))))))
10239 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10240 "Get all property keys in the current buffer.
10241 With INCLUDE-SPECIALS, also list the special properties that relect things
10242 like tags and TODO state.
10243 With INCLUDE-DEFAULTS, also include properties that has special meaning
10244 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10245 With INCLUDE-COLUMNS, also include property names given in COLUMN
10246 formats in the current buffer."
10247 (let (rtn range cfmt cols s p)
10248 (save-excursion
10249 (save-restriction
10250 (widen)
10251 (goto-char (point-min))
10252 (while (re-search-forward org-property-start-re nil t)
10253 (setq range (org-get-property-block))
10254 (goto-char (car range))
10255 (while (re-search-forward
10256 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10257 (cdr range) t)
10258 (add-to-list 'rtn (org-match-string-no-properties 1)))
10259 (outline-next-heading))))
10261 (when include-specials
10262 (setq rtn (append org-special-properties rtn)))
10264 (when include-defaults
10265 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10267 (when include-columns
10268 (save-excursion
10269 (save-restriction
10270 (widen)
10271 (goto-char (point-min))
10272 (while (re-search-forward
10273 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10274 nil t)
10275 (setq cfmt (match-string 2) s 0)
10276 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10277 cfmt s)
10278 (setq s (match-end 0)
10279 p (match-string 1 cfmt))
10280 (unless (or (equal p "ITEM")
10281 (member p org-special-properties))
10282 (add-to-list 'rtn (match-string 1 cfmt))))))))
10284 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10286 (defun org-property-values (key)
10287 "Return a list of all values of property KEY."
10288 (save-excursion
10289 (save-restriction
10290 (widen)
10291 (goto-char (point-min))
10292 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10293 values)
10294 (while (re-search-forward re nil t)
10295 (add-to-list 'values (org-trim (match-string 1))))
10296 (delete "" values)))))
10298 (defun org-insert-property-drawer ()
10299 "Insert a property drawer into the current entry."
10300 (interactive)
10301 (org-back-to-heading t)
10302 (looking-at outline-regexp)
10303 (let ((indent (- (match-end 0)(match-beginning 0)))
10304 (beg (point))
10305 (re (concat "^[ \t]*" org-keyword-time-regexp))
10306 end hiddenp)
10307 (outline-next-heading)
10308 (setq end (point))
10309 (goto-char beg)
10310 (while (re-search-forward re end t))
10311 (setq hiddenp (org-invisible-p))
10312 (end-of-line 1)
10313 (and (equal (char-after) ?\n) (forward-char 1))
10314 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10315 (beginning-of-line 2))
10316 (org-skip-over-state-notes)
10317 (skip-chars-backward " \t\n\r")
10318 (if (eq (char-before) ?*) (forward-char 1))
10319 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10320 (beginning-of-line 0)
10321 (org-indent-to-column indent)
10322 (beginning-of-line 2)
10323 (org-indent-to-column indent)
10324 (beginning-of-line 0)
10325 (if hiddenp
10326 (save-excursion
10327 (org-back-to-heading t)
10328 (hide-entry))
10329 (org-flag-drawer t))))
10331 (defun org-set-property (property value)
10332 "In the current entry, set PROPERTY to VALUE.
10333 When called interactively, this will prompt for a property name, offering
10334 completion on existing and default properties. And then it will prompt
10335 for a value, offering competion either on allowed values (via an inherited
10336 xxx_ALL property) or on existing values in other instances of this property
10337 in the current file."
10338 (interactive
10339 (let* ((completion-ignore-case t)
10340 (keys (org-buffer-property-keys nil t t))
10341 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10342 (prop (if (member prop0 keys)
10343 prop0
10344 (or (cdr (assoc (downcase prop0)
10345 (mapcar (lambda (x) (cons (downcase x) x))
10346 keys)))
10347 prop0)))
10348 (cur (org-entry-get nil prop))
10349 (allowed (org-property-get-allowed-values nil prop 'table))
10350 (existing (mapcar 'list (org-property-values prop)))
10351 (val (if allowed
10352 (org-completing-read "Value: " allowed nil 'req-match)
10353 (org-completing-read
10354 (concat "Value" (if (and cur (string-match "\\S-" cur))
10355 (concat "[" cur "]") "")
10356 ": ")
10357 existing nil nil "" nil cur))))
10358 (list prop (if (equal val "") cur val))))
10359 (unless (equal (org-entry-get nil property) value)
10360 (org-entry-put nil property value)))
10362 (defun org-delete-property (property)
10363 "In the current entry, delete PROPERTY."
10364 (interactive
10365 (let* ((completion-ignore-case t)
10366 (prop (org-ido-completing-read
10367 "Property: " (org-entry-properties nil 'standard))))
10368 (list prop)))
10369 (message "Property %s %s" property
10370 (if (org-entry-delete nil property)
10371 "deleted"
10372 "was not present in the entry")))
10374 (defun org-delete-property-globally (property)
10375 "Remove PROPERTY globally, from all entries."
10376 (interactive
10377 (let* ((completion-ignore-case t)
10378 (prop (org-ido-completing-read
10379 "Globally remove property: "
10380 (mapcar 'list (org-buffer-property-keys)))))
10381 (list prop)))
10382 (save-excursion
10383 (save-restriction
10384 (widen)
10385 (goto-char (point-min))
10386 (let ((cnt 0))
10387 (while (re-search-forward
10388 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10389 nil t)
10390 (setq cnt (1+ cnt))
10391 (replace-match ""))
10392 (message "Property \"%s\" removed from %d entries" property cnt)))))
10394 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10396 (defun org-compute-property-at-point ()
10397 "Compute the property at point.
10398 This looks for an enclosing column format, extracts the operator and
10399 then applies it to the proerty in the column format's scope."
10400 (interactive)
10401 (unless (org-at-property-p)
10402 (error "Not at a property"))
10403 (let ((prop (org-match-string-no-properties 2)))
10404 (org-columns-get-format-and-top-level)
10405 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10406 (error "No operator defined for property %s" prop))
10407 (org-columns-compute prop)))
10409 (defun org-property-get-allowed-values (pom property &optional table)
10410 "Get allowed values for the property PROPERTY.
10411 When TABLE is non-nil, return an alist that can directly be used for
10412 completion."
10413 (let (vals)
10414 (cond
10415 ((equal property "TODO")
10416 (setq vals (org-with-point-at pom
10417 (append org-todo-keywords-1 '("")))))
10418 ((equal property "PRIORITY")
10419 (let ((n org-lowest-priority))
10420 (while (>= n org-highest-priority)
10421 (push (char-to-string n) vals)
10422 (setq n (1- n)))))
10423 ((member property org-special-properties))
10425 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10427 (when (and vals (string-match "\\S-" vals))
10428 (setq vals (car (read-from-string (concat "(" vals ")"))))
10429 (setq vals (mapcar (lambda (x)
10430 (cond ((stringp x) x)
10431 ((numberp x) (number-to-string x))
10432 ((symbolp x) (symbol-name x))
10433 (t "???")))
10434 vals)))))
10435 (if table (mapcar 'list vals) vals)))
10437 (defun org-property-previous-allowed-value (&optional previous)
10438 "Switch to the next allowed value for this property."
10439 (interactive)
10440 (org-property-next-allowed-value t))
10442 (defun org-property-next-allowed-value (&optional previous)
10443 "Switch to the next allowed value for this property."
10444 (interactive)
10445 (unless (org-at-property-p)
10446 (error "Not at a property"))
10447 (let* ((key (match-string 2))
10448 (value (match-string 3))
10449 (allowed (or (org-property-get-allowed-values (point) key)
10450 (and (member value '("[ ]" "[-]" "[X]"))
10451 '("[ ]" "[X]"))))
10452 nval)
10453 (unless allowed
10454 (error "Allowed values for this property have not been defined"))
10455 (if previous (setq allowed (reverse allowed)))
10456 (if (member value allowed)
10457 (setq nval (car (cdr (member value allowed)))))
10458 (setq nval (or nval (car allowed)))
10459 (if (equal nval value)
10460 (error "Only one allowed value for this property"))
10461 (org-at-property-p)
10462 (replace-match (concat " :" key ": " nval) t t)
10463 (org-indent-line-function)
10464 (beginning-of-line 1)
10465 (skip-chars-forward " \t")))
10467 (defun org-find-entry-with-id (ident)
10468 "Locate the entry that contains the ID property with exact value IDENT.
10469 IDENT can be a string, a symbol or a number, this function will search for
10470 the string representation of it.
10471 Return the position where this entry starts, or nil if there is no such entry."
10472 (let ((id (cond
10473 ((stringp ident) ident)
10474 ((symbol-name ident) (symbol-name ident))
10475 ((numberp ident) (number-to-string ident))
10476 (t (error "IDENT %s must be a string, symbol or number" ident))))
10477 (case-fold-search nil))
10478 (save-excursion
10479 (save-restriction
10480 (widen)
10481 (goto-char (point-min))
10482 (when (re-search-forward
10483 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10484 nil t)
10485 (org-back-to-heading)
10486 (point))))))
10488 ;;;; Timestamps
10490 (defvar org-last-changed-timestamp nil)
10491 (defvar org-last-inserted-timestamp nil
10492 "The last time stamp inserted with `org-insert-time-stamp'.")
10493 (defvar org-time-was-given) ; dynamically scoped parameter
10494 (defvar org-end-time-was-given) ; dynamically scoped parameter
10495 (defvar org-ts-what) ; dynamically scoped parameter
10497 (defun org-time-stamp (arg &optional inactive)
10498 "Prompt for a date/time and insert a time stamp.
10499 If the user specifies a time like HH:MM, or if this command is called
10500 with a prefix argument, the time stamp will contain date and time.
10501 Otherwise, only the date will be included. All parts of a date not
10502 specified by the user will be filled in from the current date/time.
10503 So if you press just return without typing anything, the time stamp
10504 will represent the current date/time. If there is already a timestamp
10505 at the cursor, it will be modified."
10506 (interactive "P")
10507 (let* ((ts nil)
10508 (default-time
10509 ;; Default time is either today, or, when entering a range,
10510 ;; the range start.
10511 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10512 (save-excursion
10513 (re-search-backward
10514 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10515 (- (point) 20) t)))
10516 (apply 'encode-time (org-parse-time-string (match-string 1)))
10517 (current-time)))
10518 (default-input (and ts (org-get-compact-tod ts)))
10519 org-time-was-given org-end-time-was-given time)
10520 (cond
10521 ((and (org-at-timestamp-p t)
10522 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10523 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10524 (insert "--")
10525 (setq time (let ((this-command this-command))
10526 (org-read-date arg 'totime nil nil
10527 default-time default-input)))
10528 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10529 ((org-at-timestamp-p t)
10530 (setq time (let ((this-command this-command))
10531 (org-read-date arg 'totime nil nil default-time default-input)))
10532 (when (org-at-timestamp-p t) ; just to get the match data
10533 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10534 (replace-match "")
10535 (setq org-last-changed-timestamp
10536 (org-insert-time-stamp
10537 time (or org-time-was-given arg)
10538 inactive nil nil (list org-end-time-was-given))))
10539 (message "Timestamp updated"))
10541 (setq time (let ((this-command this-command))
10542 (org-read-date arg 'totime nil nil default-time default-input)))
10543 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10544 nil nil (list org-end-time-was-given))))))
10546 ;; FIXME: can we use this for something else, like computing time differences?
10547 (defun org-get-compact-tod (s)
10548 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10549 (let* ((t1 (match-string 1 s))
10550 (h1 (string-to-number (match-string 2 s)))
10551 (m1 (string-to-number (match-string 3 s)))
10552 (t2 (and (match-end 4) (match-string 5 s)))
10553 (h2 (and t2 (string-to-number (match-string 6 s))))
10554 (m2 (and t2 (string-to-number (match-string 7 s))))
10555 dh dm)
10556 (if (not t2)
10558 (setq dh (- h2 h1) dm (- m2 m1))
10559 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10560 (concat t1 "+" (number-to-string dh)
10561 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10563 (defun org-time-stamp-inactive (&optional arg)
10564 "Insert an inactive time stamp.
10565 An inactive time stamp is enclosed in square brackets instead of angle
10566 brackets. It is inactive in the sense that it does not trigger agenda entries,
10567 does not link to the calendar and cannot be changed with the S-cursor keys.
10568 So these are more for recording a certain time/date."
10569 (interactive "P")
10570 (org-time-stamp arg 'inactive))
10572 (defvar org-date-ovl (org-make-overlay 1 1))
10573 (org-overlay-put org-date-ovl 'face 'org-warning)
10574 (org-detach-overlay org-date-ovl)
10576 (defvar org-ans1) ; dynamically scoped parameter
10577 (defvar org-ans2) ; dynamically scoped parameter
10579 (defvar org-plain-time-of-day-regexp) ; defined below
10581 (defvar org-overriding-default-time nil) ; dynamically scoped
10582 (defvar org-read-date-overlay nil)
10583 (defvar org-dcst nil) ; dynamically scoped
10585 (defun org-read-date (&optional with-time to-time from-string prompt
10586 default-time default-input)
10587 "Read a date, possibly a time, and make things smooth for the user.
10588 The prompt will suggest to enter an ISO date, but you can also enter anything
10589 which will at least partially be understood by `parse-time-string'.
10590 Unrecognized parts of the date will default to the current day, month, year,
10591 hour and minute. If this command is called to replace a timestamp at point,
10592 of to enter the second timestamp of a range, the default time is taken from the
10593 existing stamp. For example,
10594 3-2-5 --> 2003-02-05
10595 feb 15 --> currentyear-02-15
10596 sep 12 9 --> 2009-09-12
10597 12:45 --> today 12:45
10598 22 sept 0:34 --> currentyear-09-22 0:34
10599 12 --> currentyear-currentmonth-12
10600 Fri --> nearest Friday (today or later)
10601 etc.
10603 Furthermore you can specify a relative date by giving, as the *first* thing
10604 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10605 change in days weeks, months, years.
10606 With a single plus or minus, the date is relative to today. With a double
10607 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10608 +4d --> four days from today
10609 +4 --> same as above
10610 +2w --> two weeks from today
10611 ++5 --> five days from default date
10613 The function understands only English month and weekday abbreviations,
10614 but this can be configured with the variables `parse-time-months' and
10615 `parse-time-weekdays'.
10617 While prompting, a calendar is popped up - you can also select the
10618 date with the mouse (button 1). The calendar shows a period of three
10619 months. To scroll it to other months, use the keys `>' and `<'.
10620 If you don't like the calendar, turn it off with
10621 \(setq org-read-date-popup-calendar nil)
10623 With optional argument TO-TIME, the date will immediately be converted
10624 to an internal time.
10625 With an optional argument WITH-TIME, the prompt will suggest to also
10626 insert a time. Note that when WITH-TIME is not set, you can still
10627 enter a time, and this function will inform the calling routine about
10628 this change. The calling routine may then choose to change the format
10629 used to insert the time stamp into the buffer to include the time.
10630 With optional argument FROM-STRING, read from this string instead from
10631 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10632 the time/date that is used for everything that is not specified by the
10633 user."
10634 (require 'parse-time)
10635 (let* ((org-time-stamp-rounding-minutes
10636 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10637 (org-dcst org-display-custom-times)
10638 (ct (org-current-time))
10639 (def (or org-overriding-default-time default-time ct))
10640 (defdecode (decode-time def))
10641 (dummy (progn
10642 (when (< (nth 2 defdecode) org-extend-today-until)
10643 (setcar (nthcdr 2 defdecode) -1)
10644 (setcar (nthcdr 1 defdecode) 59)
10645 (setq def (apply 'encode-time defdecode)
10646 defdecode (decode-time def)))))
10647 (calendar-move-hook nil)
10648 (calendar-view-diary-initially-flag nil)
10649 (view-diary-entries-initially nil)
10650 (calendar-view-holidays-initially-flag nil)
10651 (view-calendar-holidays-initially nil)
10652 (timestr (format-time-string
10653 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10654 (prompt (concat (if prompt (concat prompt " ") "")
10655 (format "Date+time [%s]: " timestr)))
10656 ans (org-ans0 "") org-ans1 org-ans2 final)
10658 (cond
10659 (from-string (setq ans from-string))
10660 (org-read-date-popup-calendar
10661 (save-excursion
10662 (save-window-excursion
10663 (calendar)
10664 (calendar-forward-day (- (time-to-days def)
10665 (calendar-absolute-from-gregorian
10666 (calendar-current-date))))
10667 (org-eval-in-calendar nil t)
10668 (let* ((old-map (current-local-map))
10669 (map (copy-keymap calendar-mode-map))
10670 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10671 (org-defkey map (kbd "RET") 'org-calendar-select)
10672 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10673 'org-calendar-select-mouse)
10674 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10675 'org-calendar-select-mouse)
10676 (org-defkey minibuffer-local-map [(meta shift left)]
10677 (lambda () (interactive)
10678 (org-eval-in-calendar '(calendar-backward-month 1))))
10679 (org-defkey minibuffer-local-map [(meta shift right)]
10680 (lambda () (interactive)
10681 (org-eval-in-calendar '(calendar-forward-month 1))))
10682 (org-defkey minibuffer-local-map [(meta shift up)]
10683 (lambda () (interactive)
10684 (org-eval-in-calendar '(calendar-backward-year 1))))
10685 (org-defkey minibuffer-local-map [(meta shift down)]
10686 (lambda () (interactive)
10687 (org-eval-in-calendar '(calendar-forward-year 1))))
10688 (org-defkey minibuffer-local-map [(shift up)]
10689 (lambda () (interactive)
10690 (org-eval-in-calendar '(calendar-backward-week 1))))
10691 (org-defkey minibuffer-local-map [(shift down)]
10692 (lambda () (interactive)
10693 (org-eval-in-calendar '(calendar-forward-week 1))))
10694 (org-defkey minibuffer-local-map [(shift left)]
10695 (lambda () (interactive)
10696 (org-eval-in-calendar '(calendar-backward-day 1))))
10697 (org-defkey minibuffer-local-map [(shift right)]
10698 (lambda () (interactive)
10699 (org-eval-in-calendar '(calendar-forward-day 1))))
10700 (org-defkey minibuffer-local-map ">"
10701 (lambda () (interactive)
10702 (org-eval-in-calendar '(scroll-calendar-left 1))))
10703 (org-defkey minibuffer-local-map "<"
10704 (lambda () (interactive)
10705 (org-eval-in-calendar '(scroll-calendar-right 1))))
10706 (unwind-protect
10707 (progn
10708 (use-local-map map)
10709 (add-hook 'post-command-hook 'org-read-date-display)
10710 (setq org-ans0 (read-string prompt default-input nil nil))
10711 ;; org-ans0: from prompt
10712 ;; org-ans1: from mouse click
10713 ;; org-ans2: from calendar motion
10714 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10715 (remove-hook 'post-command-hook 'org-read-date-display)
10716 (use-local-map old-map)
10717 (when org-read-date-overlay
10718 (org-delete-overlay org-read-date-overlay)
10719 (setq org-read-date-overlay nil)))))))
10721 (t ; Naked prompt only
10722 (unwind-protect
10723 (setq ans (read-string prompt default-input nil timestr))
10724 (when org-read-date-overlay
10725 (org-delete-overlay org-read-date-overlay)
10726 (setq org-read-date-overlay nil)))))
10728 (setq final (org-read-date-analyze ans def defdecode))
10730 (if to-time
10731 (apply 'encode-time final)
10732 (if (and (boundp 'org-time-was-given) org-time-was-given)
10733 (format "%04d-%02d-%02d %02d:%02d"
10734 (nth 5 final) (nth 4 final) (nth 3 final)
10735 (nth 2 final) (nth 1 final))
10736 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10737 (defvar def)
10738 (defvar defdecode)
10739 (defvar with-time)
10740 (defun org-read-date-display ()
10741 "Display the currrent date prompt interpretation in the minibuffer."
10742 (when org-read-date-display-live
10743 (when org-read-date-overlay
10744 (org-delete-overlay org-read-date-overlay))
10745 (let ((p (point)))
10746 (end-of-line 1)
10747 (while (not (equal (buffer-substring
10748 (max (point-min) (- (point) 4)) (point))
10749 " "))
10750 (insert " "))
10751 (goto-char p))
10752 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10753 " " (or org-ans1 org-ans2)))
10754 (org-end-time-was-given nil)
10755 (f (org-read-date-analyze ans def defdecode))
10756 (fmts (if org-dcst
10757 org-time-stamp-custom-formats
10758 org-time-stamp-formats))
10759 (fmt (if (or with-time
10760 (and (boundp 'org-time-was-given) org-time-was-given))
10761 (cdr fmts)
10762 (car fmts)))
10763 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10764 (when (and org-end-time-was-given
10765 (string-match org-plain-time-of-day-regexp txt))
10766 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10767 org-end-time-was-given
10768 (substring txt (match-end 0)))))
10769 (setq org-read-date-overlay
10770 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10771 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10773 (defun org-read-date-analyze (ans def defdecode)
10774 "Analyze the combined answer of the date prompt."
10775 ;; FIXME: cleanup and comment
10776 (let (delta deltan deltaw deltadef year month day
10777 hour minute second wday pm h2 m2 tl wday1
10778 iso-year iso-weekday iso-week iso-year iso-date)
10780 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10781 (setq ans "+0"))
10783 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10784 (setq ans (replace-match "" t t ans)
10785 deltan (car delta)
10786 deltaw (nth 1 delta)
10787 deltadef (nth 2 delta)))
10789 ;; Check if there is an iso week date in there
10790 ;; If yes, sore the info and ostpone interpreting it until the rest
10791 ;; of the parsing is done
10792 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10793 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10794 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10795 iso-week (string-to-number (match-string 2 ans)))
10796 (setq ans (replace-match "" t t ans)))
10798 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10799 (when (string-match
10800 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10801 (setq year (if (match-end 2)
10802 (string-to-number (match-string 2 ans))
10803 (string-to-number (format-time-string "%Y")))
10804 month (string-to-number (match-string 3 ans))
10805 day (string-to-number (match-string 4 ans)))
10806 (if (< year 100) (setq year (+ 2000 year)))
10807 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10808 t nil ans)))
10809 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10810 ;; If there is a time with am/pm, and *no* time without it, we convert
10811 ;; so that matching will be successful.
10812 (loop for i from 1 to 2 do ; twice, for end time as well
10813 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10814 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10815 (setq hour (string-to-number (match-string 1 ans))
10816 minute (if (match-end 3)
10817 (string-to-number (match-string 3 ans))
10819 pm (equal ?p
10820 (string-to-char (downcase (match-string 4 ans)))))
10821 (if (and (= hour 12) (not pm))
10822 (setq hour 0)
10823 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10824 (setq ans (replace-match (format "%02d:%02d" hour minute)
10825 t t ans))))
10827 ;; Check if a time range is given as a duration
10828 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10829 (setq hour (string-to-number (match-string 1 ans))
10830 h2 (+ hour (string-to-number (match-string 3 ans)))
10831 minute (string-to-number (match-string 2 ans))
10832 m2 (+ minute (if (match-end 5) (string-to-number
10833 (match-string 5 ans))0)))
10834 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10835 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10836 t t ans)))
10838 ;; Check if there is a time range
10839 (when (boundp 'org-end-time-was-given)
10840 (setq org-time-was-given nil)
10841 (when (and (string-match org-plain-time-of-day-regexp ans)
10842 (match-end 8))
10843 (setq org-end-time-was-given (match-string 8 ans))
10844 (setq ans (concat (substring ans 0 (match-beginning 7))
10845 (substring ans (match-end 7))))))
10847 (setq tl (parse-time-string ans)
10848 day (or (nth 3 tl) (nth 3 defdecode))
10849 month (or (nth 4 tl)
10850 (if (and org-read-date-prefer-future
10851 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10852 (1+ (nth 4 defdecode))
10853 (nth 4 defdecode)))
10854 year (or (nth 5 tl)
10855 (if (and org-read-date-prefer-future
10856 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10857 (1+ (nth 5 defdecode))
10858 (nth 5 defdecode)))
10859 hour (or (nth 2 tl) (nth 2 defdecode))
10860 minute (or (nth 1 tl) (nth 1 defdecode))
10861 second (or (nth 0 tl) 0)
10862 wday (nth 6 tl))
10864 ;; Special date definitions below
10865 (cond
10866 (iso-week
10867 ;; There was an iso week
10868 (setq year (or iso-year year)
10869 day (or iso-weekday wday 1)
10870 wday nil ; to make sure that the trigger below does not match
10871 iso-date (calendar-gregorian-from-absolute
10872 (calendar-absolute-from-iso
10873 (list iso-week day year))))
10874 ; FIXME: Should we also push ISO weeks into the future?
10875 ; (when (and org-read-date-prefer-future
10876 ; (not iso-year)
10877 ; (< (calendar-absolute-from-gregorian iso-date)
10878 ; (time-to-days (current-time))))
10879 ; (setq year (1+ year)
10880 ; iso-date (calendar-gregorian-from-absolute
10881 ; (calendar-absolute-from-iso
10882 ; (list iso-week day year)))))
10883 (setq month (car iso-date)
10884 year (nth 2 iso-date)
10885 day (nth 1 iso-date)))
10886 (deltan
10887 (unless deltadef
10888 (let ((now (decode-time (current-time))))
10889 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10890 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10891 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10892 ((equal deltaw "m") (setq month (+ month deltan)))
10893 ((equal deltaw "y") (setq year (+ year deltan)))))
10894 ((and wday (not (nth 3 tl)))
10895 ;; Weekday was given, but no day, so pick that day in the week
10896 ;; on or after the derived date.
10897 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10898 (unless (equal wday wday1)
10899 (setq day (+ day (% (- wday wday1 -7) 7))))))
10900 (if (and (boundp 'org-time-was-given)
10901 (nth 2 tl))
10902 (setq org-time-was-given t))
10903 (if (< year 100) (setq year (+ 2000 year)))
10904 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10905 (list second minute hour day month year)))
10907 (defvar parse-time-weekdays)
10909 (defun org-read-date-get-relative (s today default)
10910 "Check string S for special relative date string.
10911 TODAY and DEFAULT are internal times, for today and for a default.
10912 Return shift list (N what def-flag)
10913 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10914 N is the number of WHATs to shift.
10915 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10916 the DEFAULT date rather than TODAY."
10917 (when (and
10918 (string-match
10919 (concat
10920 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10921 "\\([0-9]+\\)?"
10922 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10923 "\\([ \t]\\|$\\)") s)
10924 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10925 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10926 (string-to-char (substring (match-string 1 s) -1))
10927 ?+))
10928 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10929 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10930 (what (if (match-end 3) (match-string 3 s) "d"))
10931 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10932 (date (if rel default today))
10933 (wday (nth 6 (decode-time date)))
10934 delta)
10935 (if wday1
10936 (progn
10937 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10938 (if (= dir ?-) (setq delta (- delta 7)))
10939 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10940 (list delta "d" rel))
10941 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10943 (defun org-eval-in-calendar (form &optional keepdate)
10944 "Eval FORM in the calendar window and return to current window.
10945 Also, store the cursor date in variable org-ans2."
10946 (let ((sw (selected-window)))
10947 (select-window (get-buffer-window "*Calendar*"))
10948 (eval form)
10949 (when (and (not keepdate) (calendar-cursor-to-date))
10950 (let* ((date (calendar-cursor-to-date))
10951 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10952 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10953 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10954 (select-window sw)))
10956 (defun org-calendar-select ()
10957 "Return to `org-read-date' with the date currently selected.
10958 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10959 (interactive)
10960 (when (calendar-cursor-to-date)
10961 (let* ((date (calendar-cursor-to-date))
10962 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10963 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10964 (if (active-minibuffer-window) (exit-minibuffer))))
10966 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10967 "Insert a date stamp for the date given by the internal TIME.
10968 WITH-HM means, use the stamp format that includes the time of the day.
10969 INACTIVE means use square brackets instead of angular ones, so that the
10970 stamp will not contribute to the agenda.
10971 PRE and POST are optional strings to be inserted before and after the
10972 stamp.
10973 The command returns the inserted time stamp."
10974 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10975 stamp)
10976 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10977 (insert-before-markers (or pre ""))
10978 (insert-before-markers (setq stamp (format-time-string fmt time)))
10979 (when (listp extra)
10980 (setq extra (car extra))
10981 (if (and (stringp extra)
10982 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10983 (setq extra (format "-%02d:%02d"
10984 (string-to-number (match-string 1 extra))
10985 (string-to-number (match-string 2 extra))))
10986 (setq extra nil)))
10987 (when extra
10988 (backward-char 1)
10989 (insert-before-markers extra)
10990 (forward-char 1))
10991 (insert-before-markers (or post ""))
10992 (setq org-last-inserted-timestamp stamp)))
10994 (defun org-toggle-time-stamp-overlays ()
10995 "Toggle the use of custom time stamp formats."
10996 (interactive)
10997 (setq org-display-custom-times (not org-display-custom-times))
10998 (unless org-display-custom-times
10999 (let ((p (point-min)) (bmp (buffer-modified-p)))
11000 (while (setq p (next-single-property-change p 'display))
11001 (if (and (get-text-property p 'display)
11002 (eq (get-text-property p 'face) 'org-date))
11003 (remove-text-properties
11004 p (setq p (next-single-property-change p 'display))
11005 '(display t))))
11006 (set-buffer-modified-p bmp)))
11007 (if (featurep 'xemacs)
11008 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11009 (org-restart-font-lock)
11010 (setq org-table-may-need-update t)
11011 (if org-display-custom-times
11012 (message "Time stamps are overlayed with custom format")
11013 (message "Time stamp overlays removed")))
11015 (defun org-display-custom-time (beg end)
11016 "Overlay modified time stamp format over timestamp between BEG and END."
11017 (let* ((ts (buffer-substring beg end))
11018 t1 w1 with-hm tf time str w2 (off 0))
11019 (save-match-data
11020 (setq t1 (org-parse-time-string ts t))
11021 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11022 (setq off (- (match-end 0) (match-beginning 0)))))
11023 (setq end (- end off))
11024 (setq w1 (- end beg)
11025 with-hm (and (nth 1 t1) (nth 2 t1))
11026 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11027 time (org-fix-decoded-time t1)
11028 str (org-add-props
11029 (format-time-string
11030 (substring tf 1 -1) (apply 'encode-time time))
11031 nil 'mouse-face 'highlight)
11032 w2 (length str))
11033 (if (not (= w2 w1))
11034 (add-text-properties (1+ beg) (+ 2 beg)
11035 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11036 (if (featurep 'xemacs)
11037 (progn
11038 (put-text-property beg end 'invisible t)
11039 (put-text-property beg end 'end-glyph (make-glyph str)))
11040 (put-text-property beg end 'display str))))
11042 (defun org-translate-time (string)
11043 "Translate all timestamps in STRING to custom format.
11044 But do this only if the variable `org-display-custom-times' is set."
11045 (when org-display-custom-times
11046 (save-match-data
11047 (let* ((start 0)
11048 (re org-ts-regexp-both)
11049 t1 with-hm inactive tf time str beg end)
11050 (while (setq start (string-match re string start))
11051 (setq beg (match-beginning 0)
11052 end (match-end 0)
11053 t1 (save-match-data
11054 (org-parse-time-string (substring string beg end) t))
11055 with-hm (and (nth 1 t1) (nth 2 t1))
11056 inactive (equal (substring string beg (1+ beg)) "[")
11057 tf (funcall (if with-hm 'cdr 'car)
11058 org-time-stamp-custom-formats)
11059 time (org-fix-decoded-time t1)
11060 str (format-time-string
11061 (concat
11062 (if inactive "[" "<") (substring tf 1 -1)
11063 (if inactive "]" ">"))
11064 (apply 'encode-time time))
11065 string (replace-match str t t string)
11066 start (+ start (length str)))))))
11067 string)
11069 (defun org-fix-decoded-time (time)
11070 "Set 0 instead of nil for the first 6 elements of time.
11071 Don't touch the rest."
11072 (let ((n 0))
11073 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11075 (defun org-days-to-time (timestamp-string)
11076 "Difference between TIMESTAMP-STRING and now in days."
11077 (- (time-to-days (org-time-string-to-time timestamp-string))
11078 (time-to-days (current-time))))
11080 (defun org-deadline-close (timestamp-string &optional ndays)
11081 "Is the time in TIMESTAMP-STRING close to the current date?"
11082 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11083 (and (< (org-days-to-time timestamp-string) ndays)
11084 (not (org-entry-is-done-p))))
11086 (defun org-get-wdays (ts)
11087 "Get the deadline lead time appropriate for timestring TS."
11088 (cond
11089 ((<= org-deadline-warning-days 0)
11090 ;; 0 or negative, enforce this value no matter what
11091 (- org-deadline-warning-days))
11092 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11093 ;; lead time is specified.
11094 (floor (* (string-to-number (match-string 1 ts))
11095 (cdr (assoc (match-string 2 ts)
11096 '(("d" . 1) ("w" . 7)
11097 ("m" . 30.4) ("y" . 365.25)))))))
11098 ;; go for the default.
11099 (t org-deadline-warning-days)))
11101 (defun org-calendar-select-mouse (ev)
11102 "Return to `org-read-date' with the date currently selected.
11103 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11104 (interactive "e")
11105 (mouse-set-point ev)
11106 (when (calendar-cursor-to-date)
11107 (let* ((date (calendar-cursor-to-date))
11108 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11109 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11110 (if (active-minibuffer-window) (exit-minibuffer))))
11112 (defun org-check-deadlines (ndays)
11113 "Check if there are any deadlines due or past due.
11114 A deadline is considered due if it happens within `org-deadline-warning-days'
11115 days from today's date. If the deadline appears in an entry marked DONE,
11116 it is not shown. The prefix arg NDAYS can be used to test that many
11117 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11118 (interactive "P")
11119 (let* ((org-warn-days
11120 (cond
11121 ((equal ndays '(4)) 100000)
11122 (ndays (prefix-numeric-value ndays))
11123 (t (abs org-deadline-warning-days))))
11124 (case-fold-search nil)
11125 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11126 (callback
11127 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11129 (message "%d deadlines past-due or due within %d days"
11130 (org-occur regexp nil callback)
11131 org-warn-days)))
11133 (defun org-check-before-date (date)
11134 "Check if there are deadlines or scheduled entries before DATE."
11135 (interactive (list (org-read-date)))
11136 (let ((case-fold-search nil)
11137 (regexp (concat "\\<\\(" org-deadline-string
11138 "\\|" org-scheduled-string
11139 "\\) *<\\([^>]+\\)>"))
11140 (callback
11141 (lambda () (time-less-p
11142 (org-time-string-to-time (match-string 2))
11143 (org-time-string-to-time date)))))
11144 (message "%d entries before %s"
11145 (org-occur regexp nil callback) date)))
11147 (defun org-evaluate-time-range (&optional to-buffer)
11148 "Evaluate a time range by computing the difference between start and end.
11149 Normally the result is just printed in the echo area, but with prefix arg
11150 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11151 If the time range is actually in a table, the result is inserted into the
11152 next column.
11153 For time difference computation, a year is assumed to be exactly 365
11154 days in order to avoid rounding problems."
11155 (interactive "P")
11157 (org-clock-update-time-maybe)
11158 (save-excursion
11159 (unless (org-at-date-range-p t)
11160 (goto-char (point-at-bol))
11161 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11162 (if (not (org-at-date-range-p t))
11163 (error "Not at a time-stamp range, and none found in current line")))
11164 (let* ((ts1 (match-string 1))
11165 (ts2 (match-string 2))
11166 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11167 (match-end (match-end 0))
11168 (time1 (org-time-string-to-time ts1))
11169 (time2 (org-time-string-to-time ts2))
11170 (t1 (time-to-seconds time1))
11171 (t2 (time-to-seconds time2))
11172 (diff (abs (- t2 t1)))
11173 (negative (< (- t2 t1) 0))
11174 ;; (ys (floor (* 365 24 60 60)))
11175 (ds (* 24 60 60))
11176 (hs (* 60 60))
11177 (fy "%dy %dd %02d:%02d")
11178 (fy1 "%dy %dd")
11179 (fd "%dd %02d:%02d")
11180 (fd1 "%dd")
11181 (fh "%02d:%02d")
11182 y d h m align)
11183 (if havetime
11184 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11186 d (floor (/ diff ds)) diff (mod diff ds)
11187 h (floor (/ diff hs)) diff (mod diff hs)
11188 m (floor (/ diff 60)))
11189 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11191 d (floor (+ (/ diff ds) 0.5))
11192 h 0 m 0))
11193 (if (not to-buffer)
11194 (message "%s" (org-make-tdiff-string y d h m))
11195 (if (org-at-table-p)
11196 (progn
11197 (goto-char match-end)
11198 (setq align t)
11199 (and (looking-at " *|") (goto-char (match-end 0))))
11200 (goto-char match-end))
11201 (if (looking-at
11202 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11203 (replace-match ""))
11204 (if negative (insert " -"))
11205 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11206 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11207 (insert " " (format fh h m))))
11208 (if align (org-table-align))
11209 (message "Time difference inserted")))))
11211 (defun org-make-tdiff-string (y d h m)
11212 (let ((fmt "")
11213 (l nil))
11214 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11215 l (push y l)))
11216 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11217 l (push d l)))
11218 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11219 l (push h l)))
11220 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11221 l (push m l)))
11222 (apply 'format fmt (nreverse l))))
11224 (defun org-time-string-to-time (s)
11225 (apply 'encode-time (org-parse-time-string s)))
11227 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11228 "Convert a time stamp to an absolute day number.
11229 If there is a specifyer for a cyclic time stamp, get the closest date to
11230 DAYNR.
11231 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11232 (cond
11233 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11234 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11235 daynr
11236 (+ daynr 1000)))
11237 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11238 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11239 (time-to-days (current-time))) (match-string 0 s)
11240 prefer show-all))
11241 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11243 (defun org-days-to-iso-week (days)
11244 "Return the iso week number."
11245 (require 'cal-iso)
11246 (car (calendar-iso-from-absolute days)))
11248 (defun org-small-year-to-year (year)
11249 "Convert 2-digit years into 4-digit years.
11250 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11251 The year 2000 cannot be abbreviated. Any year lager than 99
11252 is retrned unchanged."
11253 (if (< year 38)
11254 (setq year (+ 2000 year))
11255 (if (< year 100)
11256 (setq year (+ 1900 year))))
11257 year)
11259 (defun org-time-from-absolute (d)
11260 "Return the time corresponding to date D.
11261 D may be an absolute day number, or a calendar-type list (month day year)."
11262 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11263 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11265 (defun org-calendar-holiday ()
11266 "List of holidays, for Diary display in Org-mode."
11267 (require 'holidays)
11268 (let ((hl (funcall
11269 (if (fboundp 'calendar-check-holidays)
11270 'calendar-check-holidays 'check-calendar-holidays) date)))
11271 (if hl (mapconcat 'identity hl "; "))))
11273 (defun org-diary-sexp-entry (sexp entry date)
11274 "Process a SEXP diary ENTRY for DATE."
11275 (require 'diary-lib)
11276 (let ((result (if calendar-debug-sexp
11277 (let ((stack-trace-on-error t))
11278 (eval (car (read-from-string sexp))))
11279 (condition-case nil
11280 (eval (car (read-from-string sexp)))
11281 (error
11282 (beep)
11283 (message "Bad sexp at line %d in %s: %s"
11284 (org-current-line)
11285 (buffer-file-name) sexp)
11286 (sleep-for 2))))))
11287 (cond ((stringp result) result)
11288 ((and (consp result)
11289 (stringp (cdr result))) (cdr result))
11290 (result entry)
11291 (t nil))))
11293 (defun org-diary-to-ical-string (frombuf)
11294 "Get iCalendar entries from diary entries in buffer FROMBUF.
11295 This uses the icalendar.el library."
11296 (let* ((tmpdir (if (featurep 'xemacs)
11297 (temp-directory)
11298 temporary-file-directory))
11299 (tmpfile (make-temp-name
11300 (expand-file-name "orgics" tmpdir)))
11301 buf rtn b e)
11302 (save-excursion
11303 (set-buffer frombuf)
11304 (icalendar-export-region (point-min) (point-max) tmpfile)
11305 (setq buf (find-buffer-visiting tmpfile))
11306 (set-buffer buf)
11307 (goto-char (point-min))
11308 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11309 (setq b (match-beginning 0)))
11310 (goto-char (point-max))
11311 (if (re-search-backward "^END:VEVENT" nil t)
11312 (setq e (match-end 0)))
11313 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11314 (kill-buffer buf)
11315 (delete-file tmpfile)
11316 rtn))
11318 (defun org-closest-date (start current change prefer show-all)
11319 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11320 When PREFER is `past' return a date that is either CURRENT or past.
11321 When PREFER is `future', return a date that is either CURRENT or future.
11322 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11323 ;; Make the proper lists from the dates
11324 (catch 'exit
11325 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11326 dn dw sday cday n1 n2
11327 d m y y1 y2 date1 date2 nmonths nm ny m2)
11329 (setq start (org-date-to-gregorian start)
11330 current (org-date-to-gregorian
11331 (if show-all
11332 current
11333 (time-to-days (current-time))))
11334 sday (calendar-absolute-from-gregorian start)
11335 cday (calendar-absolute-from-gregorian current))
11337 (if (<= cday sday) (throw 'exit sday))
11339 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11340 (setq dn (string-to-number (match-string 1 change))
11341 dw (cdr (assoc (match-string 2 change) a1)))
11342 (error "Invalid change specifyer: %s" change))
11343 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11344 (cond
11345 ((eq dw 'day)
11346 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11347 n2 (+ n1 dn)))
11348 ((eq dw 'year)
11349 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11350 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11351 (setq date1 (list m d y1)
11352 n1 (calendar-absolute-from-gregorian date1)
11353 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11354 n2 (calendar-absolute-from-gregorian date2)))
11355 ((eq dw 'month)
11356 ;; approx number of month between the two dates
11357 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11358 ;; How often does dn fit in there?
11359 (setq d (nth 1 start) m (car start) y (nth 2 start)
11360 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11361 m (+ m nm)
11362 ny (floor (/ m 12))
11363 y (+ y ny)
11364 m (- m (* ny 12)))
11365 (while (> m 12) (setq m (- m 12) y (1+ y)))
11366 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11367 (setq m2 (+ m dn) y2 y)
11368 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11369 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11370 (while (<= n2 cday)
11371 (setq n1 n2 m m2 y y2)
11372 (setq m2 (+ m dn) y2 y)
11373 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11374 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11375 (if show-all
11376 (cond
11377 ((eq prefer 'past) n1)
11378 ((eq prefer 'future) (if (= cday n1) n1 n2))
11379 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11380 (cond
11381 ((eq prefer 'past) n1)
11382 ((eq prefer 'future) (if (= cday n1) n1 n2))
11383 (t (if (= cday n1) n1 n2)))))))
11385 (defun org-date-to-gregorian (date)
11386 "Turn any specification of DATE into a gregorian date for the calendar."
11387 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11388 ((and (listp date) (= (length date) 3)) date)
11389 ((stringp date)
11390 (setq date (org-parse-time-string date))
11391 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11392 ((listp date)
11393 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11395 (defun org-parse-time-string (s &optional nodefault)
11396 "Parse the standard Org-mode time string.
11397 This should be a lot faster than the normal `parse-time-string'.
11398 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11399 hour and minute fields will be nil if not given."
11400 (if (string-match org-ts-regexp0 s)
11401 (list 0
11402 (if (or (match-beginning 8) (not nodefault))
11403 (string-to-number (or (match-string 8 s) "0")))
11404 (if (or (match-beginning 7) (not nodefault))
11405 (string-to-number (or (match-string 7 s) "0")))
11406 (string-to-number (match-string 4 s))
11407 (string-to-number (match-string 3 s))
11408 (string-to-number (match-string 2 s))
11409 nil nil nil)
11410 (make-list 9 0)))
11412 (defun org-timestamp-up (&optional arg)
11413 "Increase the date item at the cursor by one.
11414 If the cursor is on the year, change the year. If it is on the month or
11415 the day, change that.
11416 With prefix ARG, change by that many units."
11417 (interactive "p")
11418 (org-timestamp-change (prefix-numeric-value arg)))
11420 (defun org-timestamp-down (&optional arg)
11421 "Decrease the date item at the cursor by one.
11422 If the cursor is on the year, change the year. If it is on the month or
11423 the day, change that.
11424 With prefix ARG, change by that many units."
11425 (interactive "p")
11426 (org-timestamp-change (- (prefix-numeric-value arg))))
11428 (defun org-timestamp-up-day (&optional arg)
11429 "Increase the date in the time stamp by one day.
11430 With prefix ARG, change that many days."
11431 (interactive "p")
11432 (if (and (not (org-at-timestamp-p t))
11433 (org-on-heading-p))
11434 (org-todo 'up)
11435 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11437 (defun org-timestamp-down-day (&optional arg)
11438 "Decrease the date in the time stamp by one day.
11439 With prefix ARG, change that many days."
11440 (interactive "p")
11441 (if (and (not (org-at-timestamp-p t))
11442 (org-on-heading-p))
11443 (org-todo 'down)
11444 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11446 (defun org-at-timestamp-p (&optional inactive-ok)
11447 "Determine if the cursor is in or at a timestamp."
11448 (interactive)
11449 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11450 (pos (point))
11451 (ans (or (looking-at tsr)
11452 (save-excursion
11453 (skip-chars-backward "^[<\n\r\t")
11454 (if (> (point) (point-min)) (backward-char 1))
11455 (and (looking-at tsr)
11456 (> (- (match-end 0) pos) -1))))))
11457 (and ans
11458 (boundp 'org-ts-what)
11459 (setq org-ts-what
11460 (cond
11461 ((= pos (match-beginning 0)) 'bracket)
11462 ((= pos (1- (match-end 0))) 'bracket)
11463 ((org-pos-in-match-range pos 2) 'year)
11464 ((org-pos-in-match-range pos 3) 'month)
11465 ((org-pos-in-match-range pos 7) 'hour)
11466 ((org-pos-in-match-range pos 8) 'minute)
11467 ((or (org-pos-in-match-range pos 4)
11468 (org-pos-in-match-range pos 5)) 'day)
11469 ((and (> pos (or (match-end 8) (match-end 5)))
11470 (< pos (match-end 0)))
11471 (- pos (or (match-end 8) (match-end 5))))
11472 (t 'day))))
11473 ans))
11475 (defun org-toggle-timestamp-type ()
11476 "Toggle the type (<active> or [inactive]) of a time stamp."
11477 (interactive)
11478 (when (org-at-timestamp-p t)
11479 (let ((beg (match-beginning 0)) (end (match-end 0))
11480 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11481 (save-excursion
11482 (goto-char beg)
11483 (while (re-search-forward "[][<>]" end t)
11484 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11485 t t)))
11486 (message "Timestamp is now %sactive"
11487 (if (equal (char-after beg) ?<) "" "in")))))
11489 (defun org-timestamp-change (n &optional what)
11490 "Change the date in the time stamp at point.
11491 The date will be changed by N times WHAT. WHAT can be `day', `month',
11492 `year', `minute', `second'. If WHAT is not given, the cursor position
11493 in the timestamp determines what will be changed."
11494 (let ((pos (point))
11495 with-hm inactive
11496 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11497 org-ts-what
11498 extra rem
11499 ts time time0)
11500 (if (not (org-at-timestamp-p t))
11501 (error "Not at a timestamp"))
11502 (if (and (not what) (eq org-ts-what 'bracket))
11503 (org-toggle-timestamp-type)
11504 (if (and (not what) (not (eq org-ts-what 'day))
11505 org-display-custom-times
11506 (get-text-property (point) 'display)
11507 (not (get-text-property (1- (point)) 'display)))
11508 (setq org-ts-what 'day))
11509 (setq org-ts-what (or what org-ts-what)
11510 inactive (= (char-after (match-beginning 0)) ?\[)
11511 ts (match-string 0))
11512 (replace-match "")
11513 (if (string-match
11514 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11516 (setq extra (match-string 1 ts)))
11517 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11518 (setq with-hm t))
11519 (setq time0 (org-parse-time-string ts))
11520 (when (and (eq org-ts-what 'minute)
11521 (eq current-prefix-arg nil))
11522 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11523 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11524 (setcar (cdr time0) (+ (nth 1 time0)
11525 (if (> n 0) (- rem) (- dm rem))))))
11526 (setq time
11527 (encode-time (or (car time0) 0)
11528 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11529 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11530 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11531 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11532 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11533 (nthcdr 6 time0)))
11534 (when (integerp org-ts-what)
11535 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11536 (if (eq what 'calendar)
11537 (let ((cal-date (org-get-date-from-calendar)))
11538 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11539 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11540 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11541 (setcar time0 (or (car time0) 0))
11542 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11543 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11544 (setq time (apply 'encode-time time0))))
11545 (setq org-last-changed-timestamp
11546 (org-insert-time-stamp time with-hm inactive nil nil extra))
11547 (org-clock-update-time-maybe)
11548 (goto-char pos)
11549 ;; Try to recenter the calendar window, if any
11550 (if (and org-calendar-follow-timestamp-change
11551 (get-buffer-window "*Calendar*" t)
11552 (memq org-ts-what '(day month year)))
11553 (org-recenter-calendar (time-to-days time))))))
11555 (defun org-modify-ts-extra (s pos n dm)
11556 "Change the different parts of the lead-time and repeat fields in timestamp."
11557 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11558 ng h m new rem)
11559 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11560 (cond
11561 ((or (org-pos-in-match-range pos 2)
11562 (org-pos-in-match-range pos 3))
11563 (setq m (string-to-number (match-string 3 s))
11564 h (string-to-number (match-string 2 s)))
11565 (if (org-pos-in-match-range pos 2)
11566 (setq h (+ h n))
11567 (setq n (* dm (org-no-warnings (signum n))))
11568 (when (not (= 0 (setq rem (% m dm))))
11569 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11570 (setq m (+ m n)))
11571 (if (< m 0) (setq m (+ m 60) h (1- h)))
11572 (if (> m 59) (setq m (- m 60) h (1+ h)))
11573 (setq h (min 24 (max 0 h)))
11574 (setq ng 1 new (format "-%02d:%02d" h m)))
11575 ((org-pos-in-match-range pos 6)
11576 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11577 ((org-pos-in-match-range pos 5)
11578 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11580 ((org-pos-in-match-range pos 9)
11581 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11582 ((org-pos-in-match-range pos 8)
11583 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11585 (when ng
11586 (setq s (concat
11587 (substring s 0 (match-beginning ng))
11589 (substring s (match-end ng))))))
11592 (defun org-recenter-calendar (date)
11593 "If the calendar is visible, recenter it to DATE."
11594 (let* ((win (selected-window))
11595 (cwin (get-buffer-window "*Calendar*" t))
11596 (calendar-move-hook nil))
11597 (when cwin
11598 (select-window cwin)
11599 (calendar-goto-date (if (listp date) date
11600 (calendar-gregorian-from-absolute date)))
11601 (select-window win))))
11603 (defun org-goto-calendar (&optional arg)
11604 "Go to the Emacs calendar at the current date.
11605 If there is a time stamp in the current line, go to that date.
11606 A prefix ARG can be used to force the current date."
11607 (interactive "P")
11608 (let ((tsr org-ts-regexp) diff
11609 (calendar-move-hook nil)
11610 (calendar-view-holidays-initially-flag nil)
11611 (view-calendar-holidays-initially nil)
11612 (calendar-view-diary-initially-flag nil)
11613 (view-diary-entries-initially nil))
11614 (if (or (org-at-timestamp-p)
11615 (save-excursion
11616 (beginning-of-line 1)
11617 (looking-at (concat ".*" tsr))))
11618 (let ((d1 (time-to-days (current-time)))
11619 (d2 (time-to-days
11620 (org-time-string-to-time (match-string 1)))))
11621 (setq diff (- d2 d1))))
11622 (calendar)
11623 (calendar-goto-today)
11624 (if (and diff (not arg)) (calendar-forward-day diff))))
11626 (defun org-get-date-from-calendar ()
11627 "Return a list (month day year) of date at point in calendar."
11628 (with-current-buffer "*Calendar*"
11629 (save-match-data
11630 (calendar-cursor-to-date))))
11632 (defun org-date-from-calendar ()
11633 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11634 If there is already a time stamp at the cursor position, update it."
11635 (interactive)
11636 (if (org-at-timestamp-p t)
11637 (org-timestamp-change 0 'calendar)
11638 (let ((cal-date (org-get-date-from-calendar)))
11639 (org-insert-time-stamp
11640 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11642 (defun org-minutes-to-hh:mm-string (m)
11643 "Compute H:MM from a number of minutes."
11644 (let ((h (/ m 60)))
11645 (setq m (- m (* 60 h)))
11646 (format org-time-clocksum-format h m)))
11648 (defun org-hh:mm-string-to-minutes (s)
11649 "Convert a string H:MM to a number of minutes."
11650 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11651 (+ (* (string-to-number (match-string 1 s)) 60)
11652 (string-to-number (match-string 2 s)))
11655 ;;;; Agenda files
11657 ;;;###autoload
11658 (defun org-iswitchb (&optional arg)
11659 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11660 With a prefix argument, restrict available to files.
11661 With two prefix arguments, restrict available buffers to agenda files.
11663 Due to some yet unresolved reason, the global function
11664 `iswitchb-mode' needs to be active for this function to work."
11665 (interactive "P")
11666 (require 'iswitchb)
11667 (let ((enabled iswitchb-mode) blist)
11668 (or enabled (iswitchb-mode 1))
11669 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11670 ((equal arg '(16)) (org-buffer-list 'agenda))
11671 (t (org-buffer-list))))
11672 (unwind-protect
11673 (let ((iswitchb-make-buflist-hook
11674 (lambda ()
11675 (setq iswitchb-temp-buflist
11676 (mapcar 'buffer-name blist)))))
11677 (switch-to-buffer
11678 (iswitchb-read-buffer
11679 "Switch-to: " nil t))
11680 (or enabled (iswitchb-mode -1))))))
11682 (defun org-buffer-list (&optional predicate exclude-tmp)
11683 "Return a list of Org buffers.
11684 PREDICATE can be `export', `files' or `agenda'.
11686 export restrict the list to Export buffers.
11687 files restrict the list to buffers visiting Org files.
11688 agenda restrict the list to buffers visiting agenda files.
11690 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11691 (let* ((bfn nil)
11692 (agenda-files (and (eq predicate 'agenda)
11693 (mapcar 'file-truename (org-agenda-files t))))
11694 (filter
11695 (cond
11696 ((eq predicate 'files)
11697 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11698 ((eq predicate 'export)
11699 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11700 ((eq predicate 'agenda)
11701 (lambda (b)
11702 (with-current-buffer b
11703 (and (eq major-mode 'org-mode)
11704 (setq bfn (buffer-file-name b))
11705 (member (file-truename bfn) agenda-files)))))
11706 (t (lambda (b) (with-current-buffer b
11707 (or (eq major-mode 'org-mode)
11708 (string-match "\*Org .*Export"
11709 (buffer-name b)))))))))
11710 (delq nil
11711 (mapcar
11712 (lambda(b)
11713 (if (and (funcall filter b)
11714 (or (not exclude-tmp)
11715 (not (string-match "tmp" (buffer-name b)))))
11717 nil))
11718 (buffer-list)))))
11720 (defun org-agenda-files (&optional unrestricted archives)
11721 "Get the list of agenda files.
11722 Optional UNRESTRICTED means return the full list even if a restriction
11723 is currently in place.
11724 When ARCHIVES is t, include all archive files hat are really being
11725 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11726 `org-agenda-archives-mode' is t."
11727 (let ((files
11728 (cond
11729 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11730 ((stringp org-agenda-files) (org-read-agenda-file-list))
11731 ((listp org-agenda-files) org-agenda-files)
11732 (t (error "Invalid value of `org-agenda-files'")))))
11733 (setq files (apply 'append
11734 (mapcar (lambda (f)
11735 (if (file-directory-p f)
11736 (directory-files
11737 f t org-agenda-file-regexp)
11738 (list f)))
11739 files)))
11740 (when org-agenda-skip-unavailable-files
11741 (setq files (delq nil
11742 (mapcar (function
11743 (lambda (file)
11744 (and (file-readable-p file) file)))
11745 files))))
11746 (when (or (eq archives t)
11747 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11748 (setq files (org-add-archive-files files)))
11749 files))
11751 (defun org-edit-agenda-file-list ()
11752 "Edit the list of agenda files.
11753 Depending on setup, this either uses customize to edit the variable
11754 `org-agenda-files', or it visits the file that is holding the list. In the
11755 latter case, the buffer is set up in a way that saving it automatically kills
11756 the buffer and restores the previous window configuration."
11757 (interactive)
11758 (if (stringp org-agenda-files)
11759 (let ((cw (current-window-configuration)))
11760 (find-file org-agenda-files)
11761 (org-set-local 'org-window-configuration cw)
11762 (org-add-hook 'after-save-hook
11763 (lambda ()
11764 (set-window-configuration
11765 (prog1 org-window-configuration
11766 (kill-buffer (current-buffer))))
11767 (org-install-agenda-files-menu)
11768 (message "New agenda file list installed"))
11769 nil 'local)
11770 (message "%s" (substitute-command-keys
11771 "Edit list and finish with \\[save-buffer]")))
11772 (customize-variable 'org-agenda-files)))
11774 (defun org-store-new-agenda-file-list (list)
11775 "Set new value for the agenda file list and save it correcly."
11776 (if (stringp org-agenda-files)
11777 (let ((f org-agenda-files) b)
11778 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11779 (with-temp-file f
11780 (insert (mapconcat 'identity list "\n") "\n")))
11781 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11782 (setq org-agenda-files list)
11783 (customize-save-variable 'org-agenda-files org-agenda-files))))
11785 (defun org-read-agenda-file-list ()
11786 "Read the list of agenda files from a file."
11787 (when (file-directory-p org-agenda-files)
11788 (error "`org-agenda-files' cannot be a single directory"))
11789 (when (stringp org-agenda-files)
11790 (with-temp-buffer
11791 (insert-file-contents org-agenda-files)
11792 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11795 ;;;###autoload
11796 (defun org-cycle-agenda-files ()
11797 "Cycle through the files in `org-agenda-files'.
11798 If the current buffer visits an agenda file, find the next one in the list.
11799 If the current buffer does not, find the first agenda file."
11800 (interactive)
11801 (let* ((fs (org-agenda-files t))
11802 (files (append fs (list (car fs))))
11803 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11804 file)
11805 (unless files (error "No agenda files"))
11806 (catch 'exit
11807 (while (setq file (pop files))
11808 (if (equal (file-truename file) tcf)
11809 (when (car files)
11810 (find-file (car files))
11811 (throw 'exit t))))
11812 (find-file (car fs)))
11813 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11815 (defun org-agenda-file-to-front (&optional to-end)
11816 "Move/add the current file to the top of the agenda file list.
11817 If the file is not present in the list, it is added to the front. If it is
11818 present, it is moved there. With optional argument TO-END, add/move to the
11819 end of the list."
11820 (interactive "P")
11821 (let ((org-agenda-skip-unavailable-files nil)
11822 (file-alist (mapcar (lambda (x)
11823 (cons (file-truename x) x))
11824 (org-agenda-files t)))
11825 (ctf (file-truename buffer-file-name))
11826 x had)
11827 (setq x (assoc ctf file-alist) had x)
11829 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11830 (if to-end
11831 (setq file-alist (append (delq x file-alist) (list x)))
11832 (setq file-alist (cons x (delq x file-alist))))
11833 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11834 (org-install-agenda-files-menu)
11835 (message "File %s to %s of agenda file list"
11836 (if had "moved" "added") (if to-end "end" "front"))))
11838 (defun org-remove-file (&optional file)
11839 "Remove current file from the list of files in variable `org-agenda-files'.
11840 These are the files which are being checked for agenda entries.
11841 Optional argument FILE means, use this file instead of the current."
11842 (interactive)
11843 (let* ((org-agenda-skip-unavailable-files nil)
11844 (file (or file buffer-file-name))
11845 (true-file (file-truename file))
11846 (afile (abbreviate-file-name file))
11847 (files (delq nil (mapcar
11848 (lambda (x)
11849 (if (equal true-file
11850 (file-truename x))
11851 nil x))
11852 (org-agenda-files t)))))
11853 (if (not (= (length files) (length (org-agenda-files t))))
11854 (progn
11855 (org-store-new-agenda-file-list files)
11856 (org-install-agenda-files-menu)
11857 (message "Removed file: %s" afile))
11858 (message "File was not in list: %s (not removed)" afile))))
11860 (defun org-file-menu-entry (file)
11861 (vector file (list 'find-file file) t))
11863 (defun org-check-agenda-file (file)
11864 "Make sure FILE exists. If not, ask user what to do."
11865 (when (not (file-exists-p file))
11866 (message "non-existent file %s. [R]emove from list or [A]bort?"
11867 (abbreviate-file-name file))
11868 (let ((r (downcase (read-char-exclusive))))
11869 (cond
11870 ((equal r ?r)
11871 (org-remove-file file)
11872 (throw 'nextfile t))
11873 (t (error "Abort"))))))
11875 (defun org-get-agenda-file-buffer (file)
11876 "Get a buffer visiting FILE. If the buffer needs to be created, add
11877 it to the list of buffers which might be released later."
11878 (let ((buf (org-find-base-buffer-visiting file)))
11879 (if buf
11880 buf ; just return it
11881 ;; Make a new buffer and remember it
11882 (setq buf (find-file-noselect file))
11883 (if buf (push buf org-agenda-new-buffers))
11884 buf)))
11886 (defun org-release-buffers (blist)
11887 "Release all buffers in list, asking the user for confirmation when needed.
11888 When a buffer is unmodified, it is just killed. When modified, it is saved
11889 \(if the user agrees) and then killed."
11890 (let (buf file)
11891 (while (setq buf (pop blist))
11892 (setq file (buffer-file-name buf))
11893 (when (and (buffer-modified-p buf)
11894 file
11895 (y-or-n-p (format "Save file %s? " file)))
11896 (with-current-buffer buf (save-buffer)))
11897 (kill-buffer buf))))
11899 (defun org-prepare-agenda-buffers (files)
11900 "Create buffers for all agenda files, protect archived trees and comments."
11901 (interactive)
11902 (let ((pa '(:org-archived t))
11903 (pc '(:org-comment t))
11904 (pall '(:org-archived t :org-comment t))
11905 (inhibit-read-only t)
11906 (rea (concat ":" org-archive-tag ":"))
11907 bmp file re)
11908 (save-excursion
11909 (save-restriction
11910 (while (setq file (pop files))
11911 (if (bufferp file)
11912 (set-buffer file)
11913 (org-check-agenda-file file)
11914 (set-buffer (org-get-agenda-file-buffer file)))
11915 (widen)
11916 (setq bmp (buffer-modified-p))
11917 (org-refresh-category-properties)
11918 (setq org-todo-keywords-for-agenda
11919 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11920 (setq org-done-keywords-for-agenda
11921 (append org-done-keywords-for-agenda org-done-keywords))
11922 (setq org-todo-keyword-alist-for-agenda
11923 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11924 (setq org-tag-alist-for-agenda
11925 (append org-tag-alist-for-agenda org-tag-alist))
11927 (save-excursion
11928 (remove-text-properties (point-min) (point-max) pall)
11929 (when org-agenda-skip-archived-trees
11930 (goto-char (point-min))
11931 (while (re-search-forward rea nil t)
11932 (if (org-on-heading-p t)
11933 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11934 (goto-char (point-min))
11935 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11936 (while (re-search-forward re nil t)
11937 (add-text-properties
11938 (match-beginning 0) (org-end-of-subtree t) pc)))
11939 (set-buffer-modified-p bmp))))
11940 (setq org-todo-keyword-alist-for-agenda
11941 (org-uniquify org-todo-keyword-alist-for-agenda)
11942 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11944 ;;;; Embedded LaTeX
11946 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11947 "Keymap for the minor `org-cdlatex-mode'.")
11949 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11950 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11951 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11952 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11953 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11955 (defvar org-cdlatex-texmathp-advice-is-done nil
11956 "Flag remembering if we have applied the advice to texmathp already.")
11958 (define-minor-mode org-cdlatex-mode
11959 "Toggle the minor `org-cdlatex-mode'.
11960 This mode supports entering LaTeX environment and math in LaTeX fragments
11961 in Org-mode.
11962 \\{org-cdlatex-mode-map}"
11963 nil " OCDL" nil
11964 (when org-cdlatex-mode (require 'cdlatex))
11965 (unless org-cdlatex-texmathp-advice-is-done
11966 (setq org-cdlatex-texmathp-advice-is-done t)
11967 (defadvice texmathp (around org-math-always-on activate)
11968 "Always return t in org-mode buffers.
11969 This is because we want to insert math symbols without dollars even outside
11970 the LaTeX math segments. If Orgmode thinks that point is actually inside
11971 en embedded LaTeX fragement, let texmathp do its job.
11972 \\[org-cdlatex-mode-map]"
11973 (interactive)
11974 (let (p)
11975 (cond
11976 ((not (org-mode-p)) ad-do-it)
11977 ((eq this-command 'cdlatex-math-symbol)
11978 (setq ad-return-value t
11979 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11981 (let ((p (org-inside-LaTeX-fragment-p)))
11982 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11983 (setq ad-return-value t
11984 texmathp-why '("Org-mode embedded math" . 0))
11985 (if p ad-do-it)))))))))
11987 (defun turn-on-org-cdlatex ()
11988 "Unconditionally turn on `org-cdlatex-mode'."
11989 (org-cdlatex-mode 1))
11991 (defun org-inside-LaTeX-fragment-p ()
11992 "Test if point is inside a LaTeX fragment.
11993 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11994 sequence appearing also before point.
11995 Even though the matchers for math are configurable, this function assumes
11996 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11997 delimiters are skipped when they have been removed by customization.
11998 The return value is nil, or a cons cell with the delimiter and
11999 and the position of this delimiter.
12001 This function does a reasonably good job, but can locally be fooled by
12002 for example currency specifications. For example it will assume being in
12003 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12004 fragments that are properly closed, but during editing, we have to live
12005 with the uncertainty caused by missing closing delimiters. This function
12006 looks only before point, not after."
12007 (catch 'exit
12008 (let ((pos (point))
12009 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12010 (lim (progn
12011 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12012 (point)))
12013 dd-on str (start 0) m re)
12014 (goto-char pos)
12015 (when dodollar
12016 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12017 re (nth 1 (assoc "$" org-latex-regexps)))
12018 (while (string-match re str start)
12019 (cond
12020 ((= (match-end 0) (length str))
12021 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12022 ((= (match-end 0) (- (length str) 5))
12023 (throw 'exit nil))
12024 (t (setq start (match-end 0))))))
12025 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12026 (goto-char pos)
12027 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12028 (and (match-beginning 2) (throw 'exit nil))
12029 ;; count $$
12030 (while (re-search-backward "\\$\\$" lim t)
12031 (setq dd-on (not dd-on)))
12032 (goto-char pos)
12033 (if dd-on (cons "$$" m))))))
12036 (defun org-try-cdlatex-tab ()
12037 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12038 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12039 - inside a LaTeX fragment, or
12040 - after the first word in a line, where an abbreviation expansion could
12041 insert a LaTeX environment."
12042 (when org-cdlatex-mode
12043 (cond
12044 ((save-excursion
12045 (skip-chars-backward "a-zA-Z0-9*")
12046 (skip-chars-backward " \t")
12047 (bolp))
12048 (cdlatex-tab) t)
12049 ((org-inside-LaTeX-fragment-p)
12050 (cdlatex-tab) t)
12051 (t nil))))
12053 (defun org-cdlatex-underscore-caret (&optional arg)
12054 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12055 Revert to the normal definition outside of these fragments."
12056 (interactive "P")
12057 (if (org-inside-LaTeX-fragment-p)
12058 (call-interactively 'cdlatex-sub-superscript)
12059 (let (org-cdlatex-mode)
12060 (call-interactively (key-binding (vector last-input-event))))))
12062 (defun org-cdlatex-math-modify (&optional arg)
12063 "Execute `cdlatex-math-modify' in LaTeX fragments.
12064 Revert to the normal definition outside of these fragments."
12065 (interactive "P")
12066 (if (org-inside-LaTeX-fragment-p)
12067 (call-interactively 'cdlatex-math-modify)
12068 (let (org-cdlatex-mode)
12069 (call-interactively (key-binding (vector last-input-event))))))
12071 (defvar org-latex-fragment-image-overlays nil
12072 "List of overlays carrying the images of latex fragments.")
12073 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12075 (defun org-remove-latex-fragment-image-overlays ()
12076 "Remove all overlays with LaTeX fragment images in current buffer."
12077 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12078 (setq org-latex-fragment-image-overlays nil))
12080 (defun org-preview-latex-fragment (&optional subtree)
12081 "Preview the LaTeX fragment at point, or all locally or globally.
12082 If the cursor is in a LaTeX fragment, create the image and overlay
12083 it over the source code. If there is no fragment at point, display
12084 all fragments in the current text, from one headline to the next. With
12085 prefix SUBTREE, display all fragments in the current subtree. With a
12086 double prefix `C-u C-u', or when the cursor is before the first headline,
12087 display all fragments in the buffer.
12088 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12089 (interactive "P")
12090 (org-remove-latex-fragment-image-overlays)
12091 (save-excursion
12092 (save-restriction
12093 (let (beg end at msg)
12094 (cond
12095 ((or (equal subtree '(16))
12096 (not (save-excursion
12097 (re-search-backward (concat "^" outline-regexp) nil t))))
12098 (setq beg (point-min) end (point-max)
12099 msg "Creating images for buffer...%s"))
12100 ((equal subtree '(4))
12101 (org-back-to-heading)
12102 (setq beg (point) end (org-end-of-subtree t)
12103 msg "Creating images for subtree...%s"))
12105 (if (setq at (org-inside-LaTeX-fragment-p))
12106 (goto-char (max (point-min) (- (cdr at) 2)))
12107 (org-back-to-heading))
12108 (setq beg (point) end (progn (outline-next-heading) (point))
12109 msg (if at "Creating image...%s"
12110 "Creating images for entry...%s"))))
12111 (message msg "")
12112 (narrow-to-region beg end)
12113 (goto-char beg)
12114 (org-format-latex
12115 (concat "ltxpng/" (file-name-sans-extension
12116 (file-name-nondirectory
12117 buffer-file-name)))
12118 default-directory 'overlays msg at 'forbuffer)
12119 (message msg "done. Use `C-c C-c' to remove images.")))))
12121 (defvar org-latex-regexps
12122 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12123 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12124 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12125 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12126 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12127 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12128 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12129 "Regular expressions for matching embedded LaTeX.")
12131 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12132 "Replace LaTeX fragments with links to an image, and produce images."
12133 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12134 (let* ((prefixnodir (file-name-nondirectory prefix))
12135 (absprefix (expand-file-name prefix dir))
12136 (todir (file-name-directory absprefix))
12137 (opt org-format-latex-options)
12138 (matchers (plist-get opt :matchers))
12139 (re-list org-latex-regexps)
12140 (cnt 0) txt link beg end re e checkdir
12141 m n block linkfile movefile ov)
12142 ;; Check if there are old images files with this prefix, and remove them
12143 (when (file-directory-p todir)
12144 (mapc 'delete-file
12145 (directory-files
12146 todir 'full
12147 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12148 ;; Check the different regular expressions
12149 (while (setq e (pop re-list))
12150 (setq m (car e) re (nth 1 e) n (nth 2 e)
12151 block (if (nth 3 e) "\n\n" ""))
12152 (when (member m matchers)
12153 (goto-char (point-min))
12154 (while (re-search-forward re nil t)
12155 (when (or (not at) (equal (cdr at) (match-beginning n)))
12156 (setq txt (match-string n)
12157 beg (match-beginning n) end (match-end n)
12158 cnt (1+ cnt)
12159 linkfile (format "%s_%04d.png" prefix cnt)
12160 movefile (format "%s_%04d.png" absprefix cnt)
12161 link (concat block "[[file:" linkfile "]]" block))
12162 (if msg (message msg cnt))
12163 (goto-char beg)
12164 (unless checkdir ; make sure the directory exists
12165 (setq checkdir t)
12166 (or (file-directory-p todir) (make-directory todir)))
12167 (org-create-formula-image
12168 txt movefile opt forbuffer)
12169 (if overlays
12170 (progn
12171 (setq ov (org-make-overlay beg end))
12172 (if (featurep 'xemacs)
12173 (progn
12174 (org-overlay-put ov 'invisible t)
12175 (org-overlay-put
12176 ov 'end-glyph
12177 (make-glyph (vector 'png :file movefile))))
12178 (org-overlay-put
12179 ov 'display
12180 (list 'image :type 'png :file movefile :ascent 'center)))
12181 (push ov org-latex-fragment-image-overlays)
12182 (goto-char end))
12183 (delete-region beg end)
12184 (insert link))))))))
12186 ;; This function borrows from Ganesh Swami's latex2png.el
12187 (defun org-create-formula-image (string tofile options buffer)
12188 (let* ((tmpdir (if (featurep 'xemacs)
12189 (temp-directory)
12190 temporary-file-directory))
12191 (texfilebase (make-temp-name
12192 (expand-file-name "orgtex" tmpdir)))
12193 (texfile (concat texfilebase ".tex"))
12194 (dvifile (concat texfilebase ".dvi"))
12195 (pngfile (concat texfilebase ".png"))
12196 (fnh (if (featurep 'xemacs)
12197 (font-height (get-face-font 'default))
12198 (face-attribute 'default :height nil)))
12199 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12200 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12201 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12202 "Black"))
12203 (bg (or (plist-get options (if buffer :background :html-background))
12204 "Transparent")))
12205 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12206 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12207 (with-temp-file texfile
12208 (insert org-format-latex-header
12209 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12210 (let ((dir default-directory))
12211 (condition-case nil
12212 (progn
12213 (cd tmpdir)
12214 (call-process "latex" nil nil nil texfile))
12215 (error nil))
12216 (cd dir))
12217 (if (not (file-exists-p dvifile))
12218 (progn (message "Failed to create dvi file from %s" texfile) nil)
12219 (condition-case nil
12220 (call-process "dvipng" nil nil nil
12221 "-E" "-fg" fg "-bg" bg
12222 "-D" dpi
12223 ;;"-x" scale "-y" scale
12224 "-T" "tight"
12225 "-o" pngfile
12226 dvifile)
12227 (error nil))
12228 (if (not (file-exists-p pngfile))
12229 (progn (message "Failed to create png file from %s" texfile) nil)
12230 ;; Use the requested file name and clean up
12231 (copy-file pngfile tofile 'replace)
12232 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12233 (delete-file (concat texfilebase e)))
12234 pngfile))))
12236 (defun org-dvipng-color (attr)
12237 "Return an rgb color specification for dvipng."
12238 (apply 'format "rgb %s %s %s"
12239 (mapcar 'org-normalize-color
12240 (color-values (face-attribute 'default attr nil)))))
12242 (defun org-normalize-color (value)
12243 "Return string to be used as color value for an RGB component."
12244 (format "%g" (/ value 65535.0)))
12247 ;;;; Key bindings
12249 ;; Make `C-c C-x' a prefix key
12250 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12252 ;; TAB key with modifiers
12253 (org-defkey org-mode-map "\C-i" 'org-cycle)
12254 (org-defkey org-mode-map [(tab)] 'org-cycle)
12255 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12256 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12257 (org-defkey org-mode-map "\M-\t" 'org-complete)
12258 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12259 ;; The following line is necessary under Suse GNU/Linux
12260 (unless (featurep 'xemacs)
12261 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12262 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12263 (define-key org-mode-map [backtab] 'org-shifttab)
12265 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12266 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12267 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12269 ;; Cursor keys with modifiers
12270 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12271 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12272 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12273 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12275 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12276 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12277 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12278 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12280 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12281 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12282 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12283 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12285 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12286 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12288 ;;; Extra keys for tty access.
12289 ;; We only set them when really needed because otherwise the
12290 ;; menus don't show the simple keys
12292 (when (or org-use-extra-keys
12293 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12294 (not window-system))
12295 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12296 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12297 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12298 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12299 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12300 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12301 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12302 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12303 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12304 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12305 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12306 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12307 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12308 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12309 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12310 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12311 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12312 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12313 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12314 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12315 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12316 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12318 ;; All the other keys
12320 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12321 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12322 (if (boundp 'narrow-map)
12323 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12324 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12325 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12326 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12327 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12328 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12329 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12330 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12331 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12332 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12333 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12334 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12335 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12336 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12337 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12338 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12339 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12340 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12341 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12342 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12343 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12344 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12345 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12346 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12347 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12348 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12349 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12350 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12351 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12352 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12353 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12354 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12355 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12356 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12357 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12358 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12359 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12360 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12361 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12362 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12363 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12364 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12365 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12366 (org-defkey org-mode-map "\C-c^" 'org-sort)
12367 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12368 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12369 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12370 (org-defkey org-mode-map "\C-m" 'org-return)
12371 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12372 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12373 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12374 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12375 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12376 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12377 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12378 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12379 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12380 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12381 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12382 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12383 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12384 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12385 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12386 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12388 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12389 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12390 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12391 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12393 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12394 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12395 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12396 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12397 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12398 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12399 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12400 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12401 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12402 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12403 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12404 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12406 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12408 (when (featurep 'xemacs)
12409 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12411 (defvar org-table-auto-blank-field) ; defined in org-table.el
12412 (defun org-self-insert-command (N)
12413 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12414 If the cursor is in a table looking at whitespace, the whitespace is
12415 overwritten, and the table is not marked as requiring realignment."
12416 (interactive "p")
12417 (if (and (org-table-p)
12418 (progn
12419 ;; check if we blank the field, and if that triggers align
12420 (and (featurep 'org-table) org-table-auto-blank-field
12421 (member last-command
12422 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12423 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12424 ;; got extra space, this field does not determine column width
12425 (let (org-table-may-need-update) (org-table-blank-field))
12426 ;; no extra space, this field may determine column width
12427 (org-table-blank-field)))
12429 (eq N 1)
12430 (looking-at "[^|\n]* |"))
12431 (let (org-table-may-need-update)
12432 (goto-char (1- (match-end 0)))
12433 (delete-backward-char 1)
12434 (goto-char (match-beginning 0))
12435 (self-insert-command N))
12436 (setq org-table-may-need-update t)
12437 (self-insert-command N)
12438 (org-fix-tags-on-the-fly)))
12440 (defun org-fix-tags-on-the-fly ()
12441 (when (and (equal (char-after (point-at-bol)) ?*)
12442 (org-on-heading-p))
12443 (org-align-tags-here org-tags-column)))
12445 (defun org-delete-backward-char (N)
12446 "Like `delete-backward-char', insert whitespace at field end in tables.
12447 When deleting backwards, in tables this function will insert whitespace in
12448 front of the next \"|\" separator, to keep the table aligned. The table will
12449 still be marked for re-alignment if the field did fill the entire column,
12450 because, in this case the deletion might narrow the column."
12451 (interactive "p")
12452 (if (and (org-table-p)
12453 (eq N 1)
12454 (string-match "|" (buffer-substring (point-at-bol) (point)))
12455 (looking-at ".*?|"))
12456 (let ((pos (point))
12457 (noalign (looking-at "[^|\n\r]* |"))
12458 (c org-table-may-need-update))
12459 (backward-delete-char N)
12460 (skip-chars-forward "^|")
12461 (insert " ")
12462 (goto-char (1- pos))
12463 ;; noalign: if there were two spaces at the end, this field
12464 ;; does not determine the width of the column.
12465 (if noalign (setq org-table-may-need-update c)))
12466 (backward-delete-char N)
12467 (org-fix-tags-on-the-fly)))
12469 (defun org-delete-char (N)
12470 "Like `delete-char', but insert whitespace at field end in tables.
12471 When deleting characters, in tables this function will insert whitespace in
12472 front of the next \"|\" separator, to keep the table aligned. The table will
12473 still be marked for re-alignment if the field did fill the entire column,
12474 because, in this case the deletion might narrow the column."
12475 (interactive "p")
12476 (if (and (org-table-p)
12477 (not (bolp))
12478 (not (= (char-after) ?|))
12479 (eq N 1))
12480 (if (looking-at ".*?|")
12481 (let ((pos (point))
12482 (noalign (looking-at "[^|\n\r]* |"))
12483 (c org-table-may-need-update))
12484 (replace-match (concat
12485 (substring (match-string 0) 1 -1)
12486 " |"))
12487 (goto-char pos)
12488 ;; noalign: if there were two spaces at the end, this field
12489 ;; does not determine the width of the column.
12490 (if noalign (setq org-table-may-need-update c)))
12491 (delete-char N))
12492 (delete-char N)
12493 (org-fix-tags-on-the-fly)))
12495 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12496 (put 'org-self-insert-command 'delete-selection t)
12497 (put 'orgtbl-self-insert-command 'delete-selection t)
12498 (put 'org-delete-char 'delete-selection 'supersede)
12499 (put 'org-delete-backward-char 'delete-selection 'supersede)
12501 ;; Make `flyspell-mode' delay after some commands
12502 (put 'org-self-insert-command 'flyspell-delayed t)
12503 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12504 (put 'org-delete-char 'flyspell-delayed t)
12505 (put 'org-delete-backward-char 'flyspell-delayed t)
12507 ;; Make pabbrev-mode expand after org-mode commands
12508 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12509 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12511 ;; How to do this: Measure non-white length of current string
12512 ;; If equal to column width, we should realign.
12514 (defun org-remap (map &rest commands)
12515 "In MAP, remap the functions given in COMMANDS.
12516 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12517 (let (new old)
12518 (while commands
12519 (setq old (pop commands) new (pop commands))
12520 (if (fboundp 'command-remapping)
12521 (org-defkey map (vector 'remap old) new)
12522 (substitute-key-definition old new map global-map)))))
12524 (when (eq org-enable-table-editor 'optimized)
12525 ;; If the user wants maximum table support, we need to hijack
12526 ;; some standard editing functions
12527 (org-remap org-mode-map
12528 'self-insert-command 'org-self-insert-command
12529 'delete-char 'org-delete-char
12530 'delete-backward-char 'org-delete-backward-char)
12531 (org-defkey org-mode-map "|" 'org-force-self-insert))
12533 (defun org-shiftcursor-error ()
12534 "Throw an error because Shift-Cursor command was applied in wrong context."
12535 (error "This command is active in special context like tables, headlines or timestamps"))
12537 (defun org-shifttab (&optional arg)
12538 "Global visibility cycling or move to previous table field.
12539 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12540 on context.
12541 See the individual commands for more information."
12542 (interactive "P")
12543 (cond
12544 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12545 ((integerp arg)
12546 (message "Content view to level: %d" arg)
12547 (org-content (prefix-numeric-value arg))
12548 (setq org-cycle-global-status 'overview))
12549 (t (call-interactively 'org-global-cycle))))
12551 (defun org-shiftmetaleft ()
12552 "Promote subtree or delete table column.
12553 Calls `org-promote-subtree', `org-outdent-item',
12554 or `org-table-delete-column', depending on context.
12555 See the individual commands for more information."
12556 (interactive)
12557 (cond
12558 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12559 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12560 ((org-at-item-p) (call-interactively 'org-outdent-item))
12561 (t (org-shiftcursor-error))))
12563 (defun org-shiftmetaright ()
12564 "Demote subtree or insert table column.
12565 Calls `org-demote-subtree', `org-indent-item',
12566 or `org-table-insert-column', depending on context.
12567 See the individual commands for more information."
12568 (interactive)
12569 (cond
12570 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12571 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12572 ((org-at-item-p) (call-interactively 'org-indent-item))
12573 (t (org-shiftcursor-error))))
12575 (defun org-shiftmetaup (&optional arg)
12576 "Move subtree up or kill table row.
12577 Calls `org-move-subtree-up' or `org-table-kill-row' or
12578 `org-move-item-up' depending on context. See the individual commands
12579 for more information."
12580 (interactive "P")
12581 (cond
12582 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12583 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12584 ((org-at-item-p) (call-interactively 'org-move-item-up))
12585 (t (org-shiftcursor-error))))
12586 (defun org-shiftmetadown (&optional arg)
12587 "Move subtree down or insert table row.
12588 Calls `org-move-subtree-down' or `org-table-insert-row' or
12589 `org-move-item-down', depending on context. See the individual
12590 commands for more information."
12591 (interactive "P")
12592 (cond
12593 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12594 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12595 ((org-at-item-p) (call-interactively 'org-move-item-down))
12596 (t (org-shiftcursor-error))))
12598 (defun org-metaleft (&optional arg)
12599 "Promote heading or move table column to left.
12600 Calls `org-do-promote' or `org-table-move-column', depending on context.
12601 With no specific context, calls the Emacs default `backward-word'.
12602 See the individual commands for more information."
12603 (interactive "P")
12604 (cond
12605 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12606 ((or (org-on-heading-p) (org-region-active-p))
12607 (call-interactively 'org-do-promote))
12608 ((org-at-item-p) (call-interactively 'org-outdent-item))
12609 (t (call-interactively 'backward-word))))
12611 (defun org-metaright (&optional arg)
12612 "Demote subtree or move table column to right.
12613 Calls `org-do-demote' or `org-table-move-column', depending on context.
12614 With no specific context, calls the Emacs default `forward-word'.
12615 See the individual commands for more information."
12616 (interactive "P")
12617 (cond
12618 ((org-at-table-p) (call-interactively 'org-table-move-column))
12619 ((or (org-on-heading-p) (org-region-active-p))
12620 (call-interactively 'org-do-demote))
12621 ((org-at-item-p) (call-interactively 'org-indent-item))
12622 (t (call-interactively 'forward-word))))
12624 (defun org-metaup (&optional arg)
12625 "Move subtree up or move table row up.
12626 Calls `org-move-subtree-up' or `org-table-move-row' or
12627 `org-move-item-up', depending on context. See the individual commands
12628 for more information."
12629 (interactive "P")
12630 (cond
12631 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12632 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12633 ((org-at-item-p) (call-interactively 'org-move-item-up))
12634 (t (transpose-lines 1) (beginning-of-line -1))))
12636 (defun org-metadown (&optional arg)
12637 "Move subtree down or move table row down.
12638 Calls `org-move-subtree-down' or `org-table-move-row' or
12639 `org-move-item-down', depending on context. See the individual
12640 commands for more information."
12641 (interactive "P")
12642 (cond
12643 ((org-at-table-p) (call-interactively 'org-table-move-row))
12644 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12645 ((org-at-item-p) (call-interactively 'org-move-item-down))
12646 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12648 (defun org-shiftup (&optional arg)
12649 "Increase item in timestamp or increase priority of current headline.
12650 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12651 depending on context. See the individual commands for more information."
12652 (interactive "P")
12653 (cond
12654 ((org-at-timestamp-p t)
12655 (call-interactively (if org-edit-timestamp-down-means-later
12656 'org-timestamp-down 'org-timestamp-up)))
12657 ((org-on-heading-p) (call-interactively 'org-priority-up))
12658 ((org-at-item-p) (call-interactively 'org-previous-item))
12659 ((org-clocktable-try-shift 'up arg))
12660 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12662 (defun org-shiftdown (&optional arg)
12663 "Decrease item in timestamp or decrease priority of current headline.
12664 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12665 depending on context. See the individual commands for more information."
12666 (interactive "P")
12667 (cond
12668 ((org-at-timestamp-p t)
12669 (call-interactively (if org-edit-timestamp-down-means-later
12670 'org-timestamp-up 'org-timestamp-down)))
12671 ((org-on-heading-p) (call-interactively 'org-priority-down))
12672 ((org-clocktable-try-shift 'down arg))
12673 (t (call-interactively 'org-next-item))))
12675 (defun org-shiftright (&optional arg)
12676 "Cycle the thing at point or in the current line, depending on context.
12677 Depending on context, this does one of the following:
12679 - switch a timestamp at point one day into the future
12680 - on a headline, switch to the next TODO keyword.
12681 - on an item, switch entire list to the next bullet type
12682 - on a property line, switch to the next allowed value
12683 - on a clocktable definition line, move time block into the future"
12684 (interactive "P")
12685 (cond
12686 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12687 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12688 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12689 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12690 ((org-clocktable-try-shift 'right arg))
12691 (t (org-shiftcursor-error))))
12693 (defun org-shiftleft (&optional arg)
12694 "Cycle the thing at point or in the current line, depending on context.
12695 Depending on context, this does one of the following:
12697 - switch a timestamp at point one day into the past
12698 - on a headline, switch to the previous TODO keyword.
12699 - on an item, switch entire list to the previous bullet type
12700 - on a property line, switch to the previous allowed value
12701 - on a clocktable definition line, move time block into the past"
12702 (interactive "P")
12703 (cond
12704 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12705 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12706 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12707 ((org-at-property-p)
12708 (call-interactively 'org-property-previous-allowed-value))
12709 ((org-clocktable-try-shift 'left arg))
12710 (t (org-shiftcursor-error))))
12712 (defun org-shiftcontrolright ()
12713 "Switch to next TODO set."
12714 (interactive)
12715 (cond
12716 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12717 (t (org-shiftcursor-error))))
12719 (defun org-shiftcontrolleft ()
12720 "Switch to previous TODO set."
12721 (interactive)
12722 (cond
12723 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12724 (t (org-shiftcursor-error))))
12726 (defun org-ctrl-c-ret ()
12727 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12728 (interactive)
12729 (cond
12730 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12731 (t (call-interactively 'org-insert-heading))))
12733 (defun org-copy-special ()
12734 "Copy region in table or copy current subtree.
12735 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12736 See the individual commands for more information."
12737 (interactive)
12738 (call-interactively
12739 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12741 (defun org-cut-special ()
12742 "Cut region in table or cut current subtree.
12743 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12744 See the individual commands for more information."
12745 (interactive)
12746 (call-interactively
12747 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12749 (defun org-paste-special (arg)
12750 "Paste rectangular region into table, or past subtree relative to level.
12751 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12752 See the individual commands for more information."
12753 (interactive "P")
12754 (if (org-at-table-p)
12755 (org-table-paste-rectangle)
12756 (org-paste-subtree arg)))
12758 (defun org-edit-special ()
12759 "Call a special editor for the stuff at point.
12760 When at a table, call the formula editor with `org-table-edit-formulas'.
12761 When at the first line of an src example, call `org-edit-src-code'.
12762 When in an #+include line, visit the include file. Otherwise call
12763 `ffap' to visit the file at point."
12764 (interactive)
12765 (cond
12766 ((org-at-table-p)
12767 (call-interactively 'org-table-edit-formulas))
12768 ((save-excursion
12769 (beginning-of-line 1)
12770 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12771 (find-file (org-trim (match-string 1))))
12772 ((org-edit-src-code))
12773 ((org-edit-fixed-width-region))
12774 (t (call-interactively 'ffap))))
12776 (defun org-ctrl-c-ctrl-c (&optional arg)
12777 "Set tags in headline, or update according to changed information at point.
12779 This command does many different things, depending on context:
12781 - If the cursor is in a headline, prompt for tags and insert them
12782 into the current line, aligned to `org-tags-column'. When called
12783 with prefix arg, realign all tags in the current buffer.
12785 - If the cursor is in one of the special #+KEYWORD lines, this
12786 triggers scanning the buffer for these lines and updating the
12787 information.
12789 - If the cursor is inside a table, realign the table. This command
12790 works even if the automatic table editor has been turned off.
12792 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12793 the entire table.
12795 - If the cursor is a the beginning of a dynamic block, update it.
12797 - If the cursor is inside a table created by the table.el package,
12798 activate that table.
12800 - If the current buffer is a remember buffer, close note and file
12801 it. A prefix argument of 1 files to the default location
12802 without further interaction. A prefix argument of 2 files to
12803 the currently clocking task.
12805 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12806 links in this buffer.
12808 - If the cursor is on a numbered item in a plain list, renumber the
12809 ordered list.
12811 - If the cursor is on a checkbox, toggle it."
12812 (interactive "P")
12813 (let ((org-enable-table-editor t))
12814 (cond
12815 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12816 org-occur-highlights
12817 org-latex-fragment-image-overlays)
12818 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12819 (org-remove-occur-highlights)
12820 (org-remove-latex-fragment-image-overlays)
12821 (message "Temporary highlights/overlays removed from current buffer"))
12822 ((and (local-variable-p 'org-finish-function (current-buffer))
12823 (fboundp org-finish-function))
12824 (funcall org-finish-function))
12825 ((org-at-property-p)
12826 (call-interactively 'org-property-action))
12827 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12828 ((org-on-heading-p) (call-interactively 'org-set-tags))
12829 ((org-at-table.el-p)
12830 (require 'table)
12831 (beginning-of-line 1)
12832 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12833 (call-interactively 'table-recognize-table))
12834 ((org-at-table-p)
12835 (org-table-maybe-eval-formula)
12836 (if arg
12837 (call-interactively 'org-table-recalculate)
12838 (org-table-maybe-recalculate-line))
12839 (call-interactively 'org-table-align))
12840 ((org-at-item-checkbox-p)
12841 (call-interactively 'org-toggle-checkbox))
12842 ((org-at-item-p)
12843 (call-interactively 'org-maybe-renumber-ordered-list))
12844 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12845 ;; Dynamic block
12846 (beginning-of-line 1)
12847 (save-excursion (org-update-dblock)))
12848 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12849 (cond
12850 ((equal (match-string 1) "TBLFM")
12851 ;; Recalculate the table before this line
12852 (save-excursion
12853 (beginning-of-line 1)
12854 (skip-chars-backward " \r\n\t")
12855 (if (org-at-table-p)
12856 (org-call-with-arg 'org-table-recalculate t))))
12858 ; (org-set-regexps-and-options)
12859 ; (org-restart-font-lock)
12860 (let ((org-inhibit-startup t)) (org-mode-restart))
12861 (message "Local setup has been refreshed"))))
12862 (t (error "C-c C-c can do nothing useful at this location.")))))
12864 (defun org-mode-restart ()
12865 "Restart Org-mode, to scan again for special lines.
12866 Also updates the keyword regular expressions."
12867 (interactive)
12868 (org-mode)
12869 (message "Org-mode restarted"))
12871 (defun org-kill-note-or-show-branches ()
12872 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12873 (interactive)
12874 (if (not org-finish-function)
12875 (call-interactively 'show-branches)
12876 (let ((org-note-abort t))
12877 (funcall org-finish-function))))
12879 (defun org-return (&optional indent)
12880 "Goto next table row or insert a newline.
12881 Calls `org-table-next-row' or `newline', depending on context.
12882 See the individual commands for more information."
12883 (interactive)
12884 (cond
12885 ((bobp) (if indent (newline-and-indent) (newline)))
12886 ((and (org-at-heading-p)
12887 (looking-at
12888 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12889 (org-show-entry)
12890 (end-of-line 1)
12891 (newline))
12892 ((org-at-table-p)
12893 (org-table-justify-field-maybe)
12894 (call-interactively 'org-table-next-row))
12895 (t (if indent (newline-and-indent) (newline)))))
12897 (defun org-return-indent ()
12898 "Goto next table row or insert a newline and indent.
12899 Calls `org-table-next-row' or `newline-and-indent', depending on
12900 context. See the individual commands for more information."
12901 (interactive)
12902 (org-return t))
12904 (defun org-ctrl-c-star ()
12905 "Compute table, or change heading status of lines.
12906 Calls `org-table-recalculate' or `org-toggle-region-headings',
12907 depending on context. This will also turn a plain list item or a normal
12908 line into a subheading."
12909 (interactive)
12910 (cond
12911 ((org-at-table-p)
12912 (call-interactively 'org-table-recalculate))
12913 ((org-region-active-p)
12914 ;; Convert all lines in region to list items
12915 (call-interactively 'org-toggle-region-headings))
12916 ((org-on-heading-p)
12917 (org-toggle-region-headings (point-at-bol)
12918 (min (1+ (point-at-eol)) (point-max))))
12919 ((org-at-item-p)
12920 ;; Convert to heading
12921 (let ((level (save-match-data
12922 (save-excursion
12923 (condition-case nil
12924 (progn
12925 (org-back-to-heading t)
12926 (funcall outline-level))
12927 (error 0))))))
12928 (replace-match
12929 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12930 (t (org-toggle-region-headings (point-at-bol)
12931 (min (1+ (point-at-eol)) (point-max))))))
12933 (defun org-ctrl-c-minus ()
12934 "Insert separator line in table or modify bullet status of line.
12935 Also turns a plain line or a region of lines into list items.
12936 Calls `org-table-insert-hline', `org-toggle-region-items', or
12937 `org-cycle-list-bullet', depending on context."
12938 (interactive)
12939 (cond
12940 ((org-at-table-p)
12941 (call-interactively 'org-table-insert-hline))
12942 ((org-on-heading-p)
12943 ;; Convert to item
12944 (save-excursion
12945 (beginning-of-line 1)
12946 (if (looking-at "\\*+ ")
12947 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12948 ((org-region-active-p)
12949 ;; Convert all lines in region to list items
12950 (call-interactively 'org-toggle-region-items))
12951 ((org-in-item-p)
12952 (call-interactively 'org-cycle-list-bullet))
12953 (t (org-toggle-region-items (point-at-bol)
12954 (min (1+ (point-at-eol)) (point-max))))))
12956 (defun org-toggle-region-items (beg end)
12957 "Convert all lines in region to list items.
12958 If the first line is already an item, convert all list items in the region
12959 to normal lines."
12960 (interactive "r")
12961 (let (l2 l)
12962 (save-excursion
12963 (goto-char end)
12964 (setq l2 (org-current-line))
12965 (goto-char beg)
12966 (beginning-of-line 1)
12967 (setq l (1- (org-current-line)))
12968 (if (org-at-item-p)
12969 ;; We already have items, de-itemize
12970 (while (< (setq l (1+ l)) l2)
12971 (when (org-at-item-p)
12972 (goto-char (match-beginning 2))
12973 (delete-region (match-beginning 2) (match-end 2))
12974 (and (looking-at "[ \t]+") (replace-match "")))
12975 (beginning-of-line 2))
12976 (while (< (setq l (1+ l)) l2)
12977 (unless (org-at-item-p)
12978 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12979 (replace-match "\\1- \\2")))
12980 (beginning-of-line 2))))))
12982 (defun org-toggle-region-headings (beg end)
12983 "Convert all lines in region to list items.
12984 If the first line is already an item, convert all list items in the region
12985 to normal lines."
12986 (interactive "r")
12987 (let (l2 l)
12988 (save-excursion
12989 (goto-char end)
12990 (setq l2 (org-current-line))
12991 (goto-char beg)
12992 (beginning-of-line 1)
12993 (setq l (1- (org-current-line)))
12994 (if (org-on-heading-p)
12995 ;; We already have headlines, de-star them
12996 (while (< (setq l (1+ l)) l2)
12997 (when (org-on-heading-p t)
12998 (and (looking-at outline-regexp) (replace-match "")))
12999 (beginning-of-line 2))
13000 (let* ((stars (save-excursion
13001 (re-search-backward org-complex-heading-regexp nil t)
13002 (or (match-string 1) "*")))
13003 (add-stars (if org-odd-levels-only "**" "*"))
13004 (rpl (concat stars add-stars " \\2")))
13005 (while (< (setq l (1+ l)) l2)
13006 (unless (org-on-heading-p)
13007 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13008 (replace-match rpl)))
13009 (beginning-of-line 2)))))))
13011 (defun org-meta-return (&optional arg)
13012 "Insert a new heading or wrap a region in a table.
13013 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13014 See the individual commands for more information."
13015 (interactive "P")
13016 (cond
13017 ((org-at-table-p)
13018 (call-interactively 'org-table-wrap-region))
13019 (t (call-interactively 'org-insert-heading))))
13021 ;;; Menu entries
13023 ;; Define the Org-mode menus
13024 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13025 '("Tbl"
13026 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13027 ["Next Field" org-cycle (org-at-table-p)]
13028 ["Previous Field" org-shifttab (org-at-table-p)]
13029 ["Next Row" org-return (org-at-table-p)]
13030 "--"
13031 ["Blank Field" org-table-blank-field (org-at-table-p)]
13032 ["Edit Field" org-table-edit-field (org-at-table-p)]
13033 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13034 "--"
13035 ("Column"
13036 ["Move Column Left" org-metaleft (org-at-table-p)]
13037 ["Move Column Right" org-metaright (org-at-table-p)]
13038 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13039 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13040 ("Row"
13041 ["Move Row Up" org-metaup (org-at-table-p)]
13042 ["Move Row Down" org-metadown (org-at-table-p)]
13043 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13044 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13045 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13046 "--"
13047 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13048 ("Rectangle"
13049 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13050 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13051 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13052 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13053 "--"
13054 ("Calculate"
13055 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13056 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13057 ["Edit Formulas" org-edit-special (org-at-table-p)]
13058 "--"
13059 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13060 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13061 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13062 "--"
13063 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13064 "--"
13065 ["Sum Column/Rectangle" org-table-sum
13066 (or (org-at-table-p) (org-region-active-p))]
13067 ["Which Column?" org-table-current-column (org-at-table-p)])
13068 ["Debug Formulas"
13069 org-table-toggle-formula-debugger
13070 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13071 ["Show Col/Row Numbers"
13072 org-table-toggle-coordinate-overlays
13073 :style toggle
13074 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13075 "--"
13076 ["Create" org-table-create (and (not (org-at-table-p))
13077 org-enable-table-editor)]
13078 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13079 ["Import from File" org-table-import (not (org-at-table-p))]
13080 ["Export to File" org-table-export (org-at-table-p)]
13081 "--"
13082 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13084 (easy-menu-define org-org-menu org-mode-map "Org menu"
13085 '("Org"
13086 ("Show/Hide"
13087 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13088 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13089 ["Sparse Tree..." org-sparse-tree t]
13090 ["Reveal Context" org-reveal t]
13091 ["Show All" show-all t]
13092 "--"
13093 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13094 "--"
13095 ["New Heading" org-insert-heading t]
13096 ("Navigate Headings"
13097 ["Up" outline-up-heading t]
13098 ["Next" outline-next-visible-heading t]
13099 ["Previous" outline-previous-visible-heading t]
13100 ["Next Same Level" outline-forward-same-level t]
13101 ["Previous Same Level" outline-backward-same-level t]
13102 "--"
13103 ["Jump" org-goto t])
13104 ("Edit Structure"
13105 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13106 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13107 "--"
13108 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13109 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13110 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13111 "--"
13112 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13113 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13114 ["Demote Heading" org-metaright (not (org-at-table-p))]
13115 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13116 "--"
13117 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13118 "--"
13119 ["Convert to odd levels" org-convert-to-odd-levels t]
13120 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13121 ("Editing"
13122 ["Emphasis..." org-emphasize t]
13123 ["Edit Source Example" org-edit-special t])
13124 ("Archive"
13125 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13126 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13127 ; :active t :keys "C-u C-c C-x C-a"]
13128 ["Sparse trees open ARCHIVE trees"
13129 (setq org-sparse-tree-open-archived-trees
13130 (not org-sparse-tree-open-archived-trees))
13131 :style toggle :selected org-sparse-tree-open-archived-trees]
13132 ["Cycling opens ARCHIVE trees"
13133 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13134 :style toggle :selected org-cycle-open-archived-trees]
13135 "--"
13136 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13137 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13138 ; ["Check and Move Children" (org-archive-subtree '(4))
13139 ; :active t :keys "C-u C-c C-x C-s"]
13141 "--"
13142 ("TODO Lists"
13143 ["TODO/DONE/-" org-todo t]
13144 ("Select keyword"
13145 ["Next keyword" org-shiftright (org-on-heading-p)]
13146 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13147 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13148 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13149 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13150 ["Show TODO Tree" org-show-todo-tree t]
13151 ["Global TODO list" org-todo-list t]
13152 "--"
13153 ["Set Priority" org-priority t]
13154 ["Priority Up" org-shiftup t]
13155 ["Priority Down" org-shiftdown t])
13156 ("TAGS and Properties"
13157 ["Set Tags" 'org-set-tags-command t]
13158 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13159 "--"
13160 ["Set property" 'org-set-property t]
13161 ["Column view of properties" org-columns t]
13162 ["Insert Column View DBlock" org-insert-columns-dblock t])
13163 ("Dates and Scheduling"
13164 ["Timestamp" org-time-stamp t]
13165 ["Timestamp (inactive)" org-time-stamp-inactive t]
13166 ("Change Date"
13167 ["1 Day Later" org-shiftright t]
13168 ["1 Day Earlier" org-shiftleft t]
13169 ["1 ... Later" org-shiftup t]
13170 ["1 ... Earlier" org-shiftdown t])
13171 ["Compute Time Range" org-evaluate-time-range t]
13172 ["Schedule Item" org-schedule t]
13173 ["Deadline" org-deadline t]
13174 "--"
13175 ["Custom time format" org-toggle-time-stamp-overlays
13176 :style radio :selected org-display-custom-times]
13177 "--"
13178 ["Goto Calendar" org-goto-calendar t]
13179 ["Date from Calendar" org-date-from-calendar t])
13180 ("Logging work"
13181 ["Clock in" org-clock-in t]
13182 ["Clock out" org-clock-out t]
13183 ["Clock cancel" org-clock-cancel t]
13184 ["Goto running clock" org-clock-goto t]
13185 ["Display times" org-clock-display t]
13186 ["Create clock table" org-clock-report t]
13187 "--"
13188 ["Record DONE time"
13189 (progn (setq org-log-done (not org-log-done))
13190 (message "Switching to %s will %s record a timestamp"
13191 (car org-done-keywords)
13192 (if org-log-done "automatically" "not")))
13193 :style toggle :selected org-log-done])
13194 "--"
13195 ["Agenda Command..." org-agenda t]
13196 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13197 ("File List for Agenda")
13198 ("Special views current file"
13199 ["TODO Tree" org-show-todo-tree t]
13200 ["Check Deadlines" org-check-deadlines t]
13201 ["Timeline" org-timeline t]
13202 ["Tags Tree" org-tags-sparse-tree t])
13203 "--"
13204 ("Hyperlinks"
13205 ["Store Link (Global)" org-store-link t]
13206 ["Insert Link" org-insert-link t]
13207 ["Follow Link" org-open-at-point t]
13208 "--"
13209 ["Next link" org-next-link t]
13210 ["Previous link" org-previous-link t]
13211 "--"
13212 ["Descriptive Links"
13213 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13214 :style radio
13215 :selected (member '(org-link) buffer-invisibility-spec)]
13216 ["Literal Links"
13217 (progn
13218 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13219 :style radio
13220 :selected (not (member '(org-link) buffer-invisibility-spec))])
13221 "--"
13222 ["Export/Publish..." org-export t]
13223 ("LaTeX"
13224 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13225 :selected org-cdlatex-mode]
13226 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13227 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13228 ["Modify math symbol" org-cdlatex-math-modify
13229 (org-inside-LaTeX-fragment-p)]
13230 ["Export LaTeX fragments as images"
13231 (if (featurep 'org-exp)
13232 (setq org-export-with-LaTeX-fragments
13233 (not org-export-with-LaTeX-fragments))
13234 (require 'org-exp))
13235 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13236 org-export-with-LaTeX-fragments)])
13237 "--"
13238 ("Documentation"
13239 ["Show Version" org-version t]
13240 ["Info Documentation" org-info t])
13241 ("Customize"
13242 ["Browse Org Group" org-customize t]
13243 "--"
13244 ["Expand This Menu" org-create-customize-menu
13245 (fboundp 'customize-menu-create)])
13246 "--"
13247 ["Refresh setup" org-mode-restart t]
13250 (defun org-info (&optional node)
13251 "Read documentation for Org-mode in the info system.
13252 With optional NODE, go directly to that node."
13253 (interactive)
13254 (info (format "(org)%s" (or node ""))))
13256 (defun org-install-agenda-files-menu ()
13257 (let ((bl (buffer-list)))
13258 (save-excursion
13259 (while bl
13260 (set-buffer (pop bl))
13261 (if (org-mode-p) (setq bl nil)))
13262 (when (org-mode-p)
13263 (easy-menu-change
13264 '("Org") "File List for Agenda"
13265 (append
13266 (list
13267 ["Edit File List" (org-edit-agenda-file-list) t]
13268 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13269 ["Remove Current File from List" org-remove-file t]
13270 ["Cycle through agenda files" org-cycle-agenda-files t]
13271 ["Occur in all agenda files" org-occur-in-agenda-files t]
13272 "--")
13273 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13275 ;;;; Documentation
13277 ;;;###autoload
13278 (defun org-require-autoloaded-modules ()
13279 (interactive)
13280 (mapc 'require
13281 '(org-agenda org-archive org-clock org-colview
13282 org-exp org-id org-export-latex org-publish
13283 org-remember org-table)))
13285 ;;;###autoload
13286 (defun org-customize ()
13287 "Call the customize function with org as argument."
13288 (interactive)
13289 (org-load-modules-maybe)
13290 (org-require-autoloaded-modules)
13291 (customize-browse 'org))
13293 (defun org-create-customize-menu ()
13294 "Create a full customization menu for Org-mode, insert it into the menu."
13295 (interactive)
13296 (org-load-modules-maybe)
13297 (org-require-autoloaded-modules)
13298 (if (fboundp 'customize-menu-create)
13299 (progn
13300 (easy-menu-change
13301 '("Org") "Customize"
13302 `(["Browse Org group" org-customize t]
13303 "--"
13304 ,(customize-menu-create 'org)
13305 ["Set" Custom-set t]
13306 ["Save" Custom-save t]
13307 ["Reset to Current" Custom-reset-current t]
13308 ["Reset to Saved" Custom-reset-saved t]
13309 ["Reset to Standard Settings" Custom-reset-standard t]))
13310 (message "\"Org\"-menu now contains full customization menu"))
13311 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13313 ;;;; Miscellaneous stuff
13315 ;;; Generally useful functions
13317 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13318 "Display the given MESSAGE as a warning."
13319 (if (fboundp 'display-warning)
13320 (display-warning 'org message
13321 (if (featurep 'xemacs)
13322 'warning
13323 :warning))
13324 (let ((buf (get-buffer-create "*Org warnings*")))
13325 (with-current-buffer buf
13326 (goto-char (point-max))
13327 (insert "Warning (Org): " message)
13328 (unless (bolp)
13329 (newline)))
13330 (display-buffer buf)
13331 (sit-for 0))))
13333 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13334 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13335 (if (and marker (marker-buffer marker)
13336 (buffer-live-p (marker-buffer marker)))
13337 (progn
13338 (switch-to-buffer (marker-buffer marker))
13339 (if (or (> marker (point-max)) (< marker (point-min)))
13340 (widen))
13341 (goto-char marker))
13342 (if bookmark
13343 (bookmark-jump bookmark)
13344 (error "Cannot find location"))))
13346 (defun org-quote-csv-field (s)
13347 "Quote field for inclusion in CSV material."
13348 (if (string-match "[\",]" s)
13349 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13352 (defun org-plist-delete (plist property)
13353 "Delete PROPERTY from PLIST.
13354 This is in contrast to merely setting it to 0."
13355 (let (p)
13356 (while plist
13357 (if (not (eq property (car plist)))
13358 (setq p (plist-put p (car plist) (nth 1 plist))))
13359 (setq plist (cddr plist)))
13362 (defun org-force-self-insert (N)
13363 "Needed to enforce self-insert under remapping."
13364 (interactive "p")
13365 (self-insert-command N))
13367 (defun org-string-width (s)
13368 "Compute width of string, ignoring invisible characters.
13369 This ignores character with invisibility property `org-link', and also
13370 characters with property `org-cwidth', because these will become invisible
13371 upon the next fontification round."
13372 (let (b l)
13373 (when (or (eq t buffer-invisibility-spec)
13374 (assq 'org-link buffer-invisibility-spec))
13375 (while (setq b (text-property-any 0 (length s)
13376 'invisible 'org-link s))
13377 (setq s (concat (substring s 0 b)
13378 (substring s (or (next-single-property-change
13379 b 'invisible s) (length s)))))))
13380 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13381 (setq s (concat (substring s 0 b)
13382 (substring s (or (next-single-property-change
13383 b 'org-cwidth s) (length s))))))
13384 (setq l (string-width s) b -1)
13385 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13386 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13389 (defun org-get-indentation (&optional line)
13390 "Get the indentation of the current line, interpreting tabs.
13391 When LINE is given, assume it represents a line and compute its indentation."
13392 (if line
13393 (if (string-match "^ *" (org-remove-tabs line))
13394 (match-end 0))
13395 (save-excursion
13396 (beginning-of-line 1)
13397 (skip-chars-forward " \t")
13398 (current-column))))
13400 (defun org-remove-tabs (s &optional width)
13401 "Replace tabulators in S with spaces.
13402 Assumes that s is a single line, starting in column 0."
13403 (setq width (or width tab-width))
13404 (while (string-match "\t" s)
13405 (setq s (replace-match
13406 (make-string
13407 (- (* width (/ (+ (match-beginning 0) width) width))
13408 (match-beginning 0)) ?\ )
13409 t t s)))
13412 (defun org-fix-indentation (line ind)
13413 "Fix indentation in LINE.
13414 IND is a cons cell with target and minimum indentation.
13415 If the current indenation in LINE is smaller than the minimum,
13416 leave it alone. If it is larger than ind, set it to the target."
13417 (let* ((l (org-remove-tabs line))
13418 (i (org-get-indentation l))
13419 (i1 (car ind)) (i2 (cdr ind)))
13420 (if (>= i i2) (setq l (substring line i2)))
13421 (if (> i1 0)
13422 (concat (make-string i1 ?\ ) l)
13423 l)))
13425 (defun org-base-buffer (buffer)
13426 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13427 (if (not buffer)
13428 buffer
13429 (or (buffer-base-buffer buffer)
13430 buffer)))
13432 (defun org-trim (s)
13433 "Remove whitespace at beginning and end of string."
13434 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13435 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13438 (defun org-wrap (string &optional width lines)
13439 "Wrap string to either a number of lines, or a width in characters.
13440 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13441 that costs. If there is a word longer than WIDTH, the text is actually
13442 wrapped to the length of that word.
13443 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13444 many lines, whatever width that takes.
13445 The return value is a list of lines, without newlines at the end."
13446 (let* ((words (org-split-string string "[ \t\n]+"))
13447 (maxword (apply 'max (mapcar 'org-string-width words)))
13448 w ll)
13449 (cond (width
13450 (org-do-wrap words (max maxword width)))
13451 (lines
13452 (setq w maxword)
13453 (setq ll (org-do-wrap words maxword))
13454 (if (<= (length ll) lines)
13456 (setq ll words)
13457 (while (> (length ll) lines)
13458 (setq w (1+ w))
13459 (setq ll (org-do-wrap words w)))
13460 ll))
13461 (t (error "Cannot wrap this")))))
13463 (defun org-do-wrap (words width)
13464 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13465 (let (lines line)
13466 (while words
13467 (setq line (pop words))
13468 (while (and words (< (+ (length line) (length (car words))) width))
13469 (setq line (concat line " " (pop words))))
13470 (setq lines (push line lines)))
13471 (nreverse lines)))
13473 (defun org-split-string (string &optional separators)
13474 "Splits STRING into substrings at SEPARATORS.
13475 No empty strings are returned if there are matches at the beginning
13476 and end of string."
13477 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13478 (start 0)
13479 notfirst
13480 (list nil))
13481 (while (and (string-match rexp string
13482 (if (and notfirst
13483 (= start (match-beginning 0))
13484 (< start (length string)))
13485 (1+ start) start))
13486 (< (match-beginning 0) (length string)))
13487 (setq notfirst t)
13488 (or (eq (match-beginning 0) 0)
13489 (and (eq (match-beginning 0) (match-end 0))
13490 (eq (match-beginning 0) start))
13491 (setq list
13492 (cons (substring string start (match-beginning 0))
13493 list)))
13494 (setq start (match-end 0)))
13495 (or (eq start (length string))
13496 (setq list
13497 (cons (substring string start)
13498 list)))
13499 (nreverse list)))
13501 (defun org-context ()
13502 "Return a list of contexts of the current cursor position.
13503 If several contexts apply, all are returned.
13504 Each context entry is a list with a symbol naming the context, and
13505 two positions indicating start and end of the context. Possible
13506 contexts are:
13508 :headline anywhere in a headline
13509 :headline-stars on the leading stars in a headline
13510 :todo-keyword on a TODO keyword (including DONE) in a headline
13511 :tags on the TAGS in a headline
13512 :priority on the priority cookie in a headline
13513 :item on the first line of a plain list item
13514 :item-bullet on the bullet/number of a plain list item
13515 :checkbox on the checkbox in a plain list item
13516 :table in an org-mode table
13517 :table-special on a special filed in a table
13518 :table-table in a table.el table
13519 :link on a hyperlink
13520 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13521 :target on a <<target>>
13522 :radio-target on a <<<radio-target>>>
13523 :latex-fragment on a LaTeX fragment
13524 :latex-preview on a LaTeX fragment with overlayed preview image
13526 This function expects the position to be visible because it uses font-lock
13527 faces as a help to recognize the following contexts: :table-special, :link,
13528 and :keyword."
13529 (let* ((f (get-text-property (point) 'face))
13530 (faces (if (listp f) f (list f)))
13531 (p (point)) clist o)
13532 ;; First the large context
13533 (cond
13534 ((org-on-heading-p t)
13535 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13536 (when (progn
13537 (beginning-of-line 1)
13538 (looking-at org-todo-line-tags-regexp))
13539 (push (org-point-in-group p 1 :headline-stars) clist)
13540 (push (org-point-in-group p 2 :todo-keyword) clist)
13541 (push (org-point-in-group p 4 :tags) clist))
13542 (goto-char p)
13543 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13544 (if (looking-at "\\[#[A-Z0-9]\\]")
13545 (push (org-point-in-group p 0 :priority) clist)))
13547 ((org-at-item-p)
13548 (push (org-point-in-group p 2 :item-bullet) clist)
13549 (push (list :item (point-at-bol)
13550 (save-excursion (org-end-of-item) (point)))
13551 clist)
13552 (and (org-at-item-checkbox-p)
13553 (push (org-point-in-group p 0 :checkbox) clist)))
13555 ((org-at-table-p)
13556 (push (list :table (org-table-begin) (org-table-end)) clist)
13557 (if (memq 'org-formula faces)
13558 (push (list :table-special
13559 (previous-single-property-change p 'face)
13560 (next-single-property-change p 'face)) clist)))
13561 ((org-at-table-p 'any)
13562 (push (list :table-table) clist)))
13563 (goto-char p)
13565 ;; Now the small context
13566 (cond
13567 ((org-at-timestamp-p)
13568 (push (org-point-in-group p 0 :timestamp) clist))
13569 ((memq 'org-link faces)
13570 (push (list :link
13571 (previous-single-property-change p 'face)
13572 (next-single-property-change p 'face)) clist))
13573 ((memq 'org-special-keyword faces)
13574 (push (list :keyword
13575 (previous-single-property-change p 'face)
13576 (next-single-property-change p 'face)) clist))
13577 ((org-on-target-p)
13578 (push (org-point-in-group p 0 :target) clist)
13579 (goto-char (1- (match-beginning 0)))
13580 (if (looking-at org-radio-target-regexp)
13581 (push (org-point-in-group p 0 :radio-target) clist))
13582 (goto-char p))
13583 ((setq o (car (delq nil
13584 (mapcar
13585 (lambda (x)
13586 (if (memq x org-latex-fragment-image-overlays) x))
13587 (org-overlays-at (point))))))
13588 (push (list :latex-fragment
13589 (org-overlay-start o) (org-overlay-end o)) clist)
13590 (push (list :latex-preview
13591 (org-overlay-start o) (org-overlay-end o)) clist))
13592 ((org-inside-LaTeX-fragment-p)
13593 ;; FIXME: positions wrong.
13594 (push (list :latex-fragment (point) (point)) clist)))
13596 (setq clist (nreverse (delq nil clist)))
13597 clist))
13599 ;; FIXME: Compare with at-regexp-p Do we need both?
13600 (defun org-in-regexp (re &optional nlines visually)
13601 "Check if point is inside a match of regexp.
13602 Normally only the current line is checked, but you can include NLINES extra
13603 lines both before and after point into the search.
13604 If VISUALLY is set, require that the cursor is not after the match but
13605 really on, so that the block visually is on the match."
13606 (catch 'exit
13607 (let ((pos (point))
13608 (eol (point-at-eol (+ 1 (or nlines 0))))
13609 (inc (if visually 1 0)))
13610 (save-excursion
13611 (beginning-of-line (- 1 (or nlines 0)))
13612 (while (re-search-forward re eol t)
13613 (if (and (<= (match-beginning 0) pos)
13614 (>= (+ inc (match-end 0)) pos))
13615 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13617 (defun org-at-regexp-p (regexp)
13618 "Is point inside a match of REGEXP in the current line?"
13619 (catch 'exit
13620 (save-excursion
13621 (let ((pos (point)) (end (point-at-eol)))
13622 (beginning-of-line 1)
13623 (while (re-search-forward regexp end t)
13624 (if (and (<= (match-beginning 0) pos)
13625 (>= (match-end 0) pos))
13626 (throw 'exit t)))
13627 nil))))
13629 (defun org-occur-in-agenda-files (regexp &optional nlines)
13630 "Call `multi-occur' with buffers for all agenda files."
13631 (interactive "sOrg-files matching: \np")
13632 (let* ((files (org-agenda-files))
13633 (tnames (mapcar 'file-truename files))
13634 (extra org-agenda-text-search-extra-files)
13636 (when (eq (car extra) 'agenda-archives)
13637 (setq extra (cdr extra))
13638 (setq files (org-add-archive-files files)))
13639 (while (setq f (pop extra))
13640 (unless (member (file-truename f) tnames)
13641 (add-to-list 'files f 'append)
13642 (add-to-list 'tnames (file-truename f) 'append)))
13643 (multi-occur
13644 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13645 regexp)))
13647 (if (boundp 'occur-mode-find-occurrence-hook)
13648 ;; Emacs 23
13649 (add-hook 'occur-mode-find-occurrence-hook
13650 (lambda ()
13651 (when (org-mode-p)
13652 (org-reveal))))
13653 ;; Emacs 22
13654 (defadvice occur-mode-goto-occurrence
13655 (after org-occur-reveal activate)
13656 (and (org-mode-p) (org-reveal)))
13657 (defadvice occur-mode-goto-occurrence-other-window
13658 (after org-occur-reveal activate)
13659 (and (org-mode-p) (org-reveal)))
13660 (defadvice occur-mode-display-occurrence
13661 (after org-occur-reveal activate)
13662 (when (org-mode-p)
13663 (let ((pos (occur-mode-find-occurrence)))
13664 (with-current-buffer (marker-buffer pos)
13665 (save-excursion
13666 (goto-char pos)
13667 (org-reveal)))))))
13669 (defun org-uniquify (list)
13670 "Remove duplicate elements from LIST."
13671 (let (res)
13672 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13673 res))
13675 (defun org-delete-all (elts list)
13676 "Remove all elements in ELTS from LIST."
13677 (while elts
13678 (setq list (delete (pop elts) list)))
13679 list)
13681 (defun org-back-over-empty-lines ()
13682 "Move backwards over witespace, to the beginning of the first empty line.
13683 Returns the number of empty lines passed."
13684 (let ((pos (point)))
13685 (skip-chars-backward " \t\n\r")
13686 (beginning-of-line 2)
13687 (goto-char (min (point) pos))
13688 (count-lines (point) pos)))
13690 (defun org-skip-whitespace ()
13691 (skip-chars-forward " \t\n\r"))
13693 (defun org-point-in-group (point group &optional context)
13694 "Check if POINT is in match-group GROUP.
13695 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13696 match. If the match group does ot exist or point is not inside it,
13697 return nil."
13698 (and (match-beginning group)
13699 (>= point (match-beginning group))
13700 (<= point (match-end group))
13701 (if context
13702 (list context (match-beginning group) (match-end group))
13703 t)))
13705 (defun org-switch-to-buffer-other-window (&rest args)
13706 "Switch to buffer in a second window on the current frame.
13707 In particular, do not allow pop-up frames."
13708 (let (pop-up-frames special-display-buffer-names special-display-regexps
13709 special-display-function)
13710 (apply 'switch-to-buffer-other-window args)))
13712 (defun org-combine-plists (&rest plists)
13713 "Create a single property list from all plists in PLISTS.
13714 The process starts by copying the first list, and then setting properties
13715 from the other lists. Settings in the last list are the most significant
13716 ones and overrule settings in the other lists."
13717 (let ((rtn (copy-sequence (pop plists)))
13718 p v ls)
13719 (while plists
13720 (setq ls (pop plists))
13721 (while ls
13722 (setq p (pop ls) v (pop ls))
13723 (setq rtn (plist-put rtn p v))))
13724 rtn))
13726 (defun org-move-line-down (arg)
13727 "Move the current line down. With prefix argument, move it past ARG lines."
13728 (interactive "p")
13729 (let ((col (current-column))
13730 beg end pos)
13731 (beginning-of-line 1) (setq beg (point))
13732 (beginning-of-line 2) (setq end (point))
13733 (beginning-of-line (+ 1 arg))
13734 (setq pos (move-marker (make-marker) (point)))
13735 (insert (delete-and-extract-region beg end))
13736 (goto-char pos)
13737 (org-move-to-column col)))
13739 (defun org-move-line-up (arg)
13740 "Move the current line up. With prefix argument, move it past ARG lines."
13741 (interactive "p")
13742 (let ((col (current-column))
13743 beg end pos)
13744 (beginning-of-line 1) (setq beg (point))
13745 (beginning-of-line 2) (setq end (point))
13746 (beginning-of-line (- arg))
13747 (setq pos (move-marker (make-marker) (point)))
13748 (insert (delete-and-extract-region beg end))
13749 (goto-char pos)
13750 (org-move-to-column col)))
13752 (defun org-replace-escapes (string table)
13753 "Replace %-escapes in STRING with values in TABLE.
13754 TABLE is an association list with keys like \"%a\" and string values.
13755 The sequences in STRING may contain normal field width and padding information,
13756 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13757 so values can contain further %-escapes if they are define later in TABLE."
13758 (let ((case-fold-search nil)
13759 e re rpl)
13760 (while (setq e (pop table))
13761 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13762 (while (string-match re string)
13763 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13764 (cdr e)))
13765 (setq string (replace-match rpl t t string))))
13766 string))
13769 (defun org-sublist (list start end)
13770 "Return a section of LIST, from START to END.
13771 Counting starts at 1."
13772 (let (rtn (c start))
13773 (setq list (nthcdr (1- start) list))
13774 (while (and list (<= c end))
13775 (push (pop list) rtn)
13776 (setq c (1+ c)))
13777 (nreverse rtn)))
13779 (defun org-find-base-buffer-visiting (file)
13780 "Like `find-buffer-visiting' but alway return the base buffer and
13781 not an indirect buffer."
13782 (let ((buf (find-buffer-visiting file)))
13783 (if buf
13784 (or (buffer-base-buffer buf) buf)
13785 nil)))
13787 (defun org-image-file-name-regexp ()
13788 "Return regexp matching the file names of images."
13789 (if (fboundp 'image-file-name-regexp)
13790 (image-file-name-regexp)
13791 (let ((image-file-name-extensions
13792 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13793 "xbm" "xpm" "pbm" "pgm" "ppm")))
13794 (concat "\\."
13795 (regexp-opt (nconc (mapcar 'upcase
13796 image-file-name-extensions)
13797 image-file-name-extensions)
13799 "\\'"))))
13801 (defun org-file-image-p (file)
13802 "Return non-nil if FILE is an image."
13803 (save-match-data
13804 (string-match (org-image-file-name-regexp) file)))
13806 (defun org-get-cursor-date ()
13807 "Return the date at cursor in as a time.
13808 This works in the calendar and in the agenda, anywhere else it just
13809 returns the current time."
13810 (let (date day defd)
13811 (cond
13812 ((eq major-mode 'calendar-mode)
13813 (setq date (calendar-cursor-to-date)
13814 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13815 ((eq major-mode 'org-agenda-mode)
13816 (setq day (get-text-property (point) 'day))
13817 (if day
13818 (setq date (calendar-gregorian-from-absolute day)
13819 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13820 (nth 2 date))))))
13821 (or defd (current-time))))
13823 (defvar org-agenda-action-marker (make-marker)
13824 "Marker pointing to the entry for the next agenda action.")
13826 (defun org-mark-entry-for-agenda-action ()
13827 "Mark the current entry as target of an agenda action.
13828 Agenda actions are actions executed from the agenda with the key `k',
13829 which make use of the date at the cursor."
13830 (interactive)
13831 (move-marker org-agenda-action-marker
13832 (save-excursion (org-back-to-heading t) (point))
13833 (current-buffer))
13834 (message
13835 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13837 ;;; Paragraph filling stuff.
13838 ;; We want this to be just right, so use the full arsenal.
13840 (defun org-indent-line-function ()
13841 "Indent line like previous, but further if previous was headline or item."
13842 (interactive)
13843 (let* ((pos (point))
13844 (itemp (org-at-item-p))
13845 column bpos bcol tpos tcol bullet btype bullet-type)
13846 ;; Find the previous relevant line
13847 (beginning-of-line 1)
13848 (cond
13849 ((looking-at "#") (setq column 0))
13850 ((looking-at "\\*+ ") (setq column 0))
13852 (beginning-of-line 0)
13853 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13854 (beginning-of-line 0))
13855 (cond
13856 ((looking-at "\\*+[ \t]+")
13857 (if (not org-adapt-indentation)
13858 (setq column 0)
13859 (goto-char (match-end 0))
13860 (setq column (current-column))))
13861 ((org-in-item-p)
13862 (org-beginning-of-item)
13863 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13864 (setq bpos (match-beginning 1) tpos (match-end 0)
13865 bcol (progn (goto-char bpos) (current-column))
13866 tcol (progn (goto-char tpos) (current-column))
13867 bullet (match-string 1)
13868 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13869 (if (> tcol (+ bcol org-description-max-indent))
13870 (setq tcol (+ bcol 5)))
13871 (if (not itemp)
13872 (setq column tcol)
13873 (goto-char pos)
13874 (beginning-of-line 1)
13875 (if (looking-at "\\S-")
13876 (progn
13877 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13878 (setq bullet (match-string 1)
13879 btype (if (string-match "[0-9]" bullet) "n" bullet))
13880 (setq column (if (equal btype bullet-type) bcol tcol)))
13881 (setq column (org-get-indentation)))))
13882 (t (setq column (org-get-indentation))))))
13883 (goto-char pos)
13884 (if (<= (current-column) (current-indentation))
13885 (org-indent-line-to column)
13886 (save-excursion (org-indent-line-to column)))
13887 (setq column (current-column))
13888 (beginning-of-line 1)
13889 (if (looking-at
13890 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13891 (replace-match (concat "\\1" (format org-property-format
13892 (match-string 2) (match-string 3)))
13893 t nil))
13894 (org-move-to-column column)))
13896 (defun org-set-autofill-regexps ()
13897 (interactive)
13898 ;; In the paragraph separator we include headlines, because filling
13899 ;; text in a line directly attached to a headline would otherwise
13900 ;; fill the headline as well.
13901 (org-set-local 'comment-start-skip "^#+[ \t]*")
13902 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13903 ;; The paragraph starter includes hand-formatted lists.
13904 (org-set-local 'paragraph-start
13905 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13906 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13907 ;; But only if the user has not turned off tables or fixed-width regions
13908 (org-set-local
13909 'auto-fill-inhibit-regexp
13910 (concat "\\*+ \\|#\\+"
13911 "\\|[ \t]*" org-keyword-time-regexp
13912 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13913 (concat
13914 "\\|[ \t]*["
13915 (if org-enable-table-editor "|" "")
13916 (if org-enable-fixed-width-editor ":" "")
13917 "]"))))
13918 ;; We use our own fill-paragraph function, to make sure that tables
13919 ;; and fixed-width regions are not wrapped. That function will pass
13920 ;; through to `fill-paragraph' when appropriate.
13921 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13922 ; Adaptive filling: To get full control, first make sure that
13923 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13924 (org-set-local 'adaptive-fill-regexp "\000")
13925 (org-set-local 'adaptive-fill-function
13926 'org-adaptive-fill-function)
13927 (org-set-local
13928 'align-mode-rules-list
13929 '((org-in-buffer-settings
13930 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13931 (modes . '(org-mode))))))
13933 (defun org-fill-paragraph (&optional justify)
13934 "Re-align a table, pass through to fill-paragraph if no table."
13935 (let ((table-p (org-at-table-p))
13936 (table.el-p (org-at-table.el-p)))
13937 (cond ((and (equal (char-after (point-at-bol)) ?*)
13938 (save-excursion (goto-char (point-at-bol))
13939 (looking-at outline-regexp)))
13940 t) ; skip headlines
13941 (table.el-p t) ; skip table.el tables
13942 (table-p (org-table-align) t) ; align org-mode tables
13943 (t nil)))) ; call paragraph-fill
13945 ;; For reference, this is the default value of adaptive-fill-regexp
13946 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13948 (defun org-adaptive-fill-function ()
13949 "Return a fill prefix for org-mode files.
13950 In particular, this makes sure hanging paragraphs for hand-formatted lists
13951 work correctly."
13952 (cond ((looking-at "#[ \t]+")
13953 (match-string 0))
13954 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13955 (save-excursion
13956 (if (> (match-end 1) (+ (match-beginning 1)
13957 org-description-max-indent))
13958 (goto-char (+ (match-beginning 1) 5))
13959 (goto-char (match-end 0)))
13960 (make-string (current-column) ?\ )))
13961 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
13962 (save-excursion
13963 (goto-char (match-end 0))
13964 (make-string (current-column) ?\ )))
13965 (t nil)))
13967 ;;; Other stuff.
13969 (defun org-toggle-fixed-width-section (arg)
13970 "Toggle the fixed-width export.
13971 If there is no active region, the QUOTE keyword at the current headline is
13972 inserted or removed. When present, it causes the text between this headline
13973 and the next to be exported as fixed-width text, and unmodified.
13974 If there is an active region, this command adds or removes a colon as the
13975 first character of this line. If the first character of a line is a colon,
13976 this line is also exported in fixed-width font."
13977 (interactive "P")
13978 (let* ((cc 0)
13979 (regionp (org-region-active-p))
13980 (beg (if regionp (region-beginning) (point)))
13981 (end (if regionp (region-end)))
13982 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13983 (case-fold-search nil)
13984 (re "[ \t]*\\(:\\)")
13985 off)
13986 (if regionp
13987 (save-excursion
13988 (goto-char beg)
13989 (setq cc (current-column))
13990 (beginning-of-line 1)
13991 (setq off (looking-at re))
13992 (while (> nlines 0)
13993 (setq nlines (1- nlines))
13994 (beginning-of-line 1)
13995 (cond
13996 (arg
13997 (org-move-to-column cc t)
13998 (insert ":\n")
13999 (forward-line -1))
14000 ((and off (looking-at re))
14001 (replace-match "" t t nil 1))
14002 ((not off) (org-move-to-column cc t) (insert ":")))
14003 (forward-line 1)))
14004 (save-excursion
14005 (org-back-to-heading)
14006 (if (looking-at (concat outline-regexp
14007 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14008 (replace-match "" t t nil 1)
14009 (if (looking-at outline-regexp)
14010 (progn
14011 (goto-char (match-end 0))
14012 (insert org-quote-string " "))))))))
14014 ;;;; Functions extending outline functionality
14016 (defun org-beginning-of-line (&optional arg)
14017 "Go to the beginning of the current line. If that is invisible, continue
14018 to a visible line beginning. This makes the function of C-a more intuitive.
14019 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14020 first attempt, and only move to after the tags when the cursor is already
14021 beyond the end of the headline."
14022 (interactive "P")
14023 (let ((pos (point)) refpos)
14024 (beginning-of-line 1)
14025 (if (bobp)
14027 (backward-char 1)
14028 (if (org-invisible-p)
14029 (while (and (not (bobp)) (org-invisible-p))
14030 (backward-char 1)
14031 (beginning-of-line 1))
14032 (forward-char 1)))
14033 (when org-special-ctrl-a/e
14034 (cond
14035 ((and (looking-at org-complex-heading-regexp)
14036 (= (char-after (match-end 1)) ?\ ))
14037 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14038 (point-at-eol)))
14039 (goto-char
14040 (if (eq org-special-ctrl-a/e t)
14041 (cond ((> pos refpos) refpos)
14042 ((= pos (point)) refpos)
14043 (t (point)))
14044 (cond ((> pos (point)) (point))
14045 ((not (eq last-command this-command)) (point))
14046 (t refpos)))))
14047 ((org-at-item-p)
14048 (goto-char
14049 (if (eq org-special-ctrl-a/e t)
14050 (cond ((> pos (match-end 4)) (match-end 4))
14051 ((= pos (point)) (match-end 4))
14052 (t (point)))
14053 (cond ((> pos (point)) (point))
14054 ((not (eq last-command this-command)) (point))
14055 (t (match-end 4))))))))
14056 (org-no-warnings
14057 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14059 (defun org-end-of-line (&optional arg)
14060 "Go to the end of the line.
14061 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14062 first attempt, and only move to after the tags when the cursor is already
14063 beyond the end of the headline."
14064 (interactive "P")
14065 (if (or (not org-special-ctrl-a/e)
14066 (not (org-on-heading-p)))
14067 (end-of-line arg)
14068 (let ((pos (point)))
14069 (beginning-of-line 1)
14070 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14071 (if (eq org-special-ctrl-a/e t)
14072 (if (or (< pos (match-beginning 1))
14073 (= pos (match-end 0)))
14074 (goto-char (match-beginning 1))
14075 (goto-char (match-end 0)))
14076 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14077 (goto-char (match-end 0))
14078 (goto-char (match-beginning 1))))
14079 (end-of-line arg))))
14080 (org-no-warnings
14081 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14084 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14085 (define-key org-mode-map "\C-e" 'org-end-of-line)
14087 (defun org-kill-line (&optional arg)
14088 "Kill line, to tags or end of line."
14089 (interactive "P")
14090 (cond
14091 ((or (not org-special-ctrl-k)
14092 (bolp)
14093 (not (org-on-heading-p)))
14094 (call-interactively 'kill-line))
14095 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14096 (kill-region (point) (match-beginning 1))
14097 (org-set-tags nil t))
14098 (t (kill-region (point) (point-at-eol)))))
14100 (define-key org-mode-map "\C-k" 'org-kill-line)
14102 (defun org-yank (&optional arg)
14103 "Yank. If the kill is a subtree, treat it specially.
14104 This command will look at the current kill and check if is a single
14105 subtree, or a series of subtrees[1]. If it passes the test, and if the
14106 cursor is at the beginning of a line or after the stars of a currently
14107 empty headline, then the yank is handeled specially. How exactly depends
14108 on the value of the following variables, both set by default.
14110 org-yank-folded-subtrees
14111 When set, the subree(s) will be folded after insertion, but only
14112 if doing so would now swallow text after the yanked text.
14114 org-yank-adjusted-subtrees
14115 When set, the subtree will be promoted or demoted in order to
14116 fit into the local outline tree structure, which means that the level
14117 will be adjusted so that it becomes the smaller one of the two
14118 *visible* surrounding headings.
14120 Any prefix to this command will cause `yank' to be called directly with
14121 no special treatment. In particular, a simple `C-u' prefix will just
14122 plainly yank the text as it is.
14124 \[1] Basically, the test checks if the first non-white line is a heading
14125 and if there are no other headings with fewer stars."
14126 (interactive "P")
14127 (setq this-command 'yank)
14128 (if arg
14129 (call-interactively 'yank)
14130 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14131 (and (org-kill-is-subtree-p)
14132 (or (bolp)
14133 (and (looking-at "[ \t]*$")
14134 (string-match
14135 "\\`\\*+\\'"
14136 (buffer-substring (point-at-bol) (point)))))))
14137 swallowp)
14138 (cond
14139 ((and subtreep org-yank-folded-subtrees)
14140 (let ((beg (point))
14141 end)
14142 (if (and subtreep org-yank-adjusted-subtrees)
14143 (org-paste-subtree nil nil 'for-yank)
14144 (call-interactively 'yank))
14145 (setq end (point))
14146 (goto-char beg)
14147 (when (and (bolp) subtreep
14148 (not (setq swallowp
14149 (org-yank-folding-would-swallow-text beg end))))
14150 (or (looking-at outline-regexp)
14151 (re-search-forward (concat "^" outline-regexp) end t))
14152 (while (and (< (point) end) (looking-at outline-regexp))
14153 (hide-subtree)
14154 (org-cycle-show-empty-lines 'folded)
14155 (condition-case nil
14156 (outline-forward-same-level 1)
14157 (error (goto-char end)))))
14158 (when swallowp
14159 (message
14160 "Yanked text not folded because that would swallow text"))
14161 (goto-char end)
14162 (skip-chars-forward " \t\n\r")
14163 (beginning-of-line 1)
14164 (push-mark beg 'nomsg)))
14165 ((and subtreep org-yank-adjusted-subtrees)
14166 (let ((beg (point-at-bol)))
14167 (org-paste-subtree nil nil 'for-yank)
14168 (push-mark beg 'nomsg)))
14170 (call-interactively 'yank))))))
14172 (defun org-yank-folding-would-swallow-text (beg end)
14173 "Would hide-subtree at BEG swallow any text after END?"
14174 (let (level)
14175 (save-excursion
14176 (goto-char beg)
14177 (when (or (looking-at outline-regexp)
14178 (re-search-forward (concat "^" outline-regexp) end t))
14179 (setq level (org-outline-level)))
14180 (goto-char end)
14181 (skip-chars-forward " \t\r\n\v\f")
14182 (if (or (eobp)
14183 (and (bolp) (looking-at org-outline-regexp)
14184 (<= (org-outline-level) level)))
14185 nil ; Nothing would be swallowed
14186 t)))) ; something would swallow
14188 (define-key org-mode-map "\C-y" 'org-yank)
14190 (defun org-invisible-p ()
14191 "Check if point is at a character currently not visible."
14192 ;; Early versions of noutline don't have `outline-invisible-p'.
14193 (if (fboundp 'outline-invisible-p)
14194 (outline-invisible-p)
14195 (get-char-property (point) 'invisible)))
14197 (defun org-invisible-p2 ()
14198 "Check if point is at a character currently not visible."
14199 (save-excursion
14200 (if (and (eolp) (not (bobp))) (backward-char 1))
14201 ;; Early versions of noutline don't have `outline-invisible-p'.
14202 (if (fboundp 'outline-invisible-p)
14203 (outline-invisible-p)
14204 (get-char-property (point) 'invisible))))
14206 (defun org-back-to-heading (&optional invisible-ok)
14207 "Call `outline-back-to-heading', but provide a better error message."
14208 (condition-case nil
14209 (outline-back-to-heading invisible-ok)
14210 (error (error "Before first headline at position %d in buffer %s"
14211 (point) (current-buffer)))))
14213 (defalias 'org-on-heading-p 'outline-on-heading-p)
14214 (defalias 'org-at-heading-p 'outline-on-heading-p)
14215 (defun org-at-heading-or-item-p ()
14216 (or (org-on-heading-p) (org-at-item-p)))
14218 (defun org-on-target-p ()
14219 (or (org-in-regexp org-radio-target-regexp)
14220 (org-in-regexp org-target-regexp)))
14222 (defun org-up-heading-all (arg)
14223 "Move to the heading line of which the present line is a subheading.
14224 This function considers both visible and invisible heading lines.
14225 With argument, move up ARG levels."
14226 (if (fboundp 'outline-up-heading-all)
14227 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14228 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14230 (defun org-up-heading-safe ()
14231 "Move to the heading line of which the present line is a subheading.
14232 This version will not throw an error. It will return the level of the
14233 headline found, or nil if no higher level is found."
14234 (let ((pos (point)) start-level level
14235 (re (concat "^" outline-regexp)))
14236 (catch 'exit
14237 (org-back-to-heading t)
14238 (setq start-level (funcall outline-level))
14239 (if (equal start-level 1) (throw 'exit nil))
14240 (while (re-search-backward re nil t)
14241 (setq level (funcall outline-level))
14242 (if (< level start-level) (throw 'exit level)))
14243 nil)))
14245 (defun org-first-sibling-p ()
14246 "Is this heading the first child of its parents?"
14247 (interactive)
14248 (let ((re (concat "^" outline-regexp))
14249 level l)
14250 (unless (org-at-heading-p t)
14251 (error "Not at a heading"))
14252 (setq level (funcall outline-level))
14253 (save-excursion
14254 (if (not (re-search-backward re nil t))
14256 (setq l (funcall outline-level))
14257 (< l level)))))
14259 (defun org-goto-sibling (&optional previous)
14260 "Goto the next sibling, even if it is invisible.
14261 When PREVIOUS is set, go to the previous sibling instead. Returns t
14262 when a sibling was found. When none is found, return nil and don't
14263 move point."
14264 (let ((fun (if previous 're-search-backward 're-search-forward))
14265 (pos (point))
14266 (re (concat "^" outline-regexp))
14267 level l)
14268 (when (condition-case nil (org-back-to-heading t) (error nil))
14269 (setq level (funcall outline-level))
14270 (catch 'exit
14271 (or previous (forward-char 1))
14272 (while (funcall fun re nil t)
14273 (setq l (funcall outline-level))
14274 (when (< l level) (goto-char pos) (throw 'exit nil))
14275 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14276 (goto-char pos)
14277 nil))))
14279 (defun org-show-siblings ()
14280 "Show all siblings of the current headline."
14281 (save-excursion
14282 (while (org-goto-sibling) (org-flag-heading nil)))
14283 (save-excursion
14284 (while (org-goto-sibling 'previous)
14285 (org-flag-heading nil))))
14287 (defun org-show-hidden-entry ()
14288 "Show an entry where even the heading is hidden."
14289 (save-excursion
14290 (org-show-entry)))
14292 (defun org-flag-heading (flag &optional entry)
14293 "Flag the current heading. FLAG non-nil means make invisible.
14294 When ENTRY is non-nil, show the entire entry."
14295 (save-excursion
14296 (org-back-to-heading t)
14297 ;; Check if we should show the entire entry
14298 (if entry
14299 (progn
14300 (org-show-entry)
14301 (save-excursion
14302 (and (outline-next-heading)
14303 (org-flag-heading nil))))
14304 (outline-flag-region (max (point-min) (1- (point)))
14305 (save-excursion (outline-end-of-heading) (point))
14306 flag))))
14308 (defun org-forward-same-level (arg)
14309 "Move forward to the ARG'th subheading at same level as this one.
14310 Stop at the first and last subheadings of a superior heading.
14311 This is like outline-forward-same-level, but invisible headings are ok."
14312 (interactive "p")
14313 (org-back-to-heading t)
14314 (while (> arg 0)
14315 (let ((point-to-move-to (save-excursion
14316 (org-get-next-sibling))))
14317 (if point-to-move-to
14318 (progn
14319 (goto-char point-to-move-to)
14320 (setq arg (1- arg)))
14321 (progn
14322 (setq arg 0)
14323 (error "No following same-level heading"))))))
14325 (defun org-get-next-sibling ()
14326 "Move to next heading of the same level, and return point.
14327 If there is no such heading, return nil.
14328 This is like outline-next-sibling, but invisible headings are ok."
14329 (let ((level (funcall outline-level)))
14330 (outline-next-heading)
14331 (while (and (not (eobp)) (> (funcall outline-level) level))
14332 (outline-next-heading))
14333 (if (or (eobp) (< (funcall outline-level) level))
14335 (point))))
14337 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14338 ;; This is an exact copy of the original function, but it uses
14339 ;; `org-back-to-heading', to make it work also in invisible
14340 ;; trees. And is uses an invisible-OK argument.
14341 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14342 (org-back-to-heading invisible-OK)
14343 (let ((first t)
14344 (level (funcall outline-level)))
14345 (while (and (not (eobp))
14346 (or first (> (funcall outline-level) level)))
14347 (setq first nil)
14348 (outline-next-heading))
14349 (unless to-heading
14350 (if (memq (preceding-char) '(?\n ?\^M))
14351 (progn
14352 ;; Go to end of line before heading
14353 (forward-char -1)
14354 (if (memq (preceding-char) '(?\n ?\^M))
14355 ;; leave blank line before heading
14356 (forward-char -1))))))
14357 (point))
14359 (defun org-show-subtree ()
14360 "Show everything after this heading at deeper levels."
14361 (outline-flag-region
14362 (point)
14363 (save-excursion
14364 (outline-end-of-subtree) (outline-next-heading) (point))
14365 nil))
14367 (defun org-show-entry ()
14368 "Show the body directly following this heading.
14369 Show the heading too, if it is currently invisible."
14370 (interactive)
14371 (save-excursion
14372 (condition-case nil
14373 (progn
14374 (org-back-to-heading t)
14375 (outline-flag-region
14376 (max (point-min) (1- (point)))
14377 (save-excursion
14378 (re-search-forward
14379 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14380 (or (match-beginning 1) (point-max)))
14381 nil))
14382 (error nil))))
14384 (defun org-make-options-regexp (kwds)
14385 "Make a regular expression for keyword lines."
14386 (concat
14388 "#?[ \t]*\\+\\("
14389 (mapconcat 'regexp-quote kwds "\\|")
14390 "\\):[ \t]*"
14391 "\\(.+\\)"))
14393 ;; Make isearch reveal the necessary context
14394 (defun org-isearch-end ()
14395 "Reveal context after isearch exits."
14396 (when isearch-success ; only if search was successful
14397 (if (featurep 'xemacs)
14398 ;; Under XEmacs, the hook is run in the correct place,
14399 ;; we directly show the context.
14400 (org-show-context 'isearch)
14401 ;; In Emacs the hook runs *before* restoring the overlays.
14402 ;; So we have to use a one-time post-command-hook to do this.
14403 ;; (Emacs 22 has a special variable, see function `org-mode')
14404 (unless (and (boundp 'isearch-mode-end-hook-quit)
14405 isearch-mode-end-hook-quit)
14406 ;; Only when the isearch was not quitted.
14407 (org-add-hook 'post-command-hook 'org-isearch-post-command
14408 'append 'local)))))
14410 (defun org-isearch-post-command ()
14411 "Remove self from hook, and show context."
14412 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14413 (org-show-context 'isearch))
14416 ;;;; Integration with and fixes for other packages
14418 ;;; Imenu support
14420 (defvar org-imenu-markers nil
14421 "All markers currently used by Imenu.")
14422 (make-variable-buffer-local 'org-imenu-markers)
14424 (defun org-imenu-new-marker (&optional pos)
14425 "Return a new marker for use by Imenu, and remember the marker."
14426 (let ((m (make-marker)))
14427 (move-marker m (or pos (point)))
14428 (push m org-imenu-markers)
14431 (defun org-imenu-get-tree ()
14432 "Produce the index for Imenu."
14433 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14434 (setq org-imenu-markers nil)
14435 (let* ((n org-imenu-depth)
14436 (re (concat "^" outline-regexp))
14437 (subs (make-vector (1+ n) nil))
14438 (last-level 0)
14439 m tree level head)
14440 (save-excursion
14441 (save-restriction
14442 (widen)
14443 (goto-char (point-max))
14444 (while (re-search-backward re nil t)
14445 (setq level (org-reduced-level (funcall outline-level)))
14446 (when (<= level n)
14447 (looking-at org-complex-heading-regexp)
14448 (setq head (org-link-display-format
14449 (org-match-string-no-properties 4))
14450 m (org-imenu-new-marker))
14451 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14452 (if (>= level last-level)
14453 (push (cons head m) (aref subs level))
14454 (push (cons head (aref subs (1+ level))) (aref subs level))
14455 (loop for i from (1+ level) to n do (aset subs i nil)))
14456 (setq last-level level)))))
14457 (aref subs 1)))
14459 (eval-after-load "imenu"
14460 '(progn
14461 (add-hook 'imenu-after-jump-hook
14462 (lambda ()
14463 (if (eq major-mode 'org-mode)
14464 (org-show-context 'org-goto))))))
14466 (defun org-link-display-format (link)
14467 "Replace a link with either the description, or the link target
14468 if no description is present"
14469 (save-match-data
14470 (if (string-match org-bracket-link-analytic-regexp link)
14471 (replace-match (or (match-string 5 link)
14472 (concat (match-string 1 link)
14473 (match-string 3 link)))
14474 nil nil link)
14475 link)))
14477 ;; Speedbar support
14479 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14480 "Overlay marking the agenda restriction line in speedbar.")
14481 (org-overlay-put org-speedbar-restriction-lock-overlay
14482 'face 'org-agenda-restriction-lock)
14483 (org-overlay-put org-speedbar-restriction-lock-overlay
14484 'help-echo "Agendas are currently limited to this item.")
14485 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14487 (defun org-speedbar-set-agenda-restriction ()
14488 "Restrict future agenda commands to the location at point in speedbar.
14489 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14490 (interactive)
14491 (require 'org-agenda)
14492 (let (p m tp np dir txt w)
14493 (cond
14494 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14495 'org-imenu t))
14496 (setq m (get-text-property p 'org-imenu-marker))
14497 (save-excursion
14498 (save-restriction
14499 (set-buffer (marker-buffer m))
14500 (goto-char m)
14501 (org-agenda-set-restriction-lock 'subtree))))
14502 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14503 'speedbar-function 'speedbar-find-file))
14504 (setq tp (previous-single-property-change
14505 (1+ p) 'speedbar-function)
14506 np (next-single-property-change
14507 tp 'speedbar-function)
14508 dir (speedbar-line-directory)
14509 txt (buffer-substring-no-properties (or tp (point-min))
14510 (or np (point-max))))
14511 (save-excursion
14512 (save-restriction
14513 (set-buffer (find-file-noselect
14514 (let ((default-directory dir))
14515 (expand-file-name txt))))
14516 (unless (org-mode-p)
14517 (error "Cannot restrict to non-Org-mode file"))
14518 (org-agenda-set-restriction-lock 'file))))
14519 (t (error "Don't know how to restrict Org-mode's agenda")))
14520 (org-move-overlay org-speedbar-restriction-lock-overlay
14521 (point-at-bol) (point-at-eol))
14522 (setq current-prefix-arg nil)
14523 (org-agenda-maybe-redo)))
14525 (eval-after-load "speedbar"
14526 '(progn
14527 (speedbar-add-supported-extension ".org")
14528 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14529 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14530 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14531 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14532 (add-hook 'speedbar-visiting-tag-hook
14533 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14536 ;;; Fixes and Hacks for problems with other packages
14538 ;; Make flyspell not check words in links, to not mess up our keymap
14539 (defun org-mode-flyspell-verify ()
14540 "Don't let flyspell put overlays at active buttons."
14541 (not (get-text-property (point) 'keymap)))
14543 ;; Make `bookmark-jump' show the jump location if it was hidden.
14544 (eval-after-load "bookmark"
14545 '(if (boundp 'bookmark-after-jump-hook)
14546 ;; We can use the hook
14547 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14548 ;; Hook not available, use advice
14549 (defadvice bookmark-jump (after org-make-visible activate)
14550 "Make the position visible."
14551 (org-bookmark-jump-unhide))))
14553 ;; Make sure saveplace show the location if it was hidden
14554 (eval-after-load "saveplace"
14555 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14556 "Make the position visible."
14557 (org-bookmark-jump-unhide)))
14559 (defun org-bookmark-jump-unhide ()
14560 "Unhide the current position, to show the bookmark location."
14561 (and (org-mode-p)
14562 (or (org-invisible-p)
14563 (save-excursion (goto-char (max (point-min) (1- (point))))
14564 (org-invisible-p)))
14565 (org-show-context 'bookmark-jump)))
14567 ;; Make session.el ignore our circular variable
14568 (eval-after-load "session"
14569 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14571 ;;;; Experimental code
14573 (defun org-closed-in-range ()
14574 "Sparse tree of items closed in a certain time range.
14575 Still experimental, may disappear in the future."
14576 (interactive)
14577 ;; Get the time interval from the user.
14578 (let* ((time1 (time-to-seconds
14579 (org-read-date nil 'to-time nil "Starting date: ")))
14580 (time2 (time-to-seconds
14581 (org-read-date nil 'to-time nil "End date:")))
14582 ;; callback function
14583 (callback (lambda ()
14584 (let ((time
14585 (time-to-seconds
14586 (apply 'encode-time
14587 (org-parse-time-string
14588 (match-string 1))))))
14589 ;; check if time in interval
14590 (and (>= time time1) (<= time time2))))))
14591 ;; make tree, check each match with the callback
14592 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14595 ;;;; Finish up
14597 (provide 'org)
14599 (run-hooks 'org-load-hook)
14601 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14603 ;;; org.el ends here