Make drawer skipping for note insertion more sensible.
[org-mode.git] / lisp / org.el
blob91d2546d994c4fd514f6e2d90d76f39cdc3dd274
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.09a
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.09a"
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-default-extensions'."
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 expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-M-RET-may-split-line '((default . t))
645 "Non-nil means, M-RET will split the line at the cursor position.
646 When nil, it will go to the end of the line before making a
647 new line.
648 You may also set this option in a different way for different
649 contexts. Valid contexts are:
651 headline when creating a new headline
652 item when creating a new item
653 table in a table field
654 default the value to be used for all contexts not explicitly
655 customized"
656 :group 'org-structure
657 :group 'org-table
658 :type '(choice
659 (const :tag "Always" t)
660 (const :tag "Never" nil)
661 (repeat :greedy t :tag "Individual contexts"
662 (cons
663 (choice :tag "Context"
664 (const headline)
665 (const item)
666 (const table)
667 (const default))
668 (boolean)))))
671 (defcustom org-insert-heading-respect-content nil
672 "Non-nil means, insert new headings after the current subtree.
673 When nil, the new heading is created directly after the current line.
674 The commands \\[org-insert-heading-respect-content] and
675 \\[org-insert-todo-heading-respect-content] turn this variable on
676 for the duration of the command."
677 :group 'org-structure
678 :type 'boolean)
680 (defcustom org-blank-before-new-entry '((heading . nil)
681 (plain-list-item . nil))
682 "Should `org-insert-heading' leave a blank line before new heading/item?
683 The value is an alist, with `heading' and `plain-list-item' as car,
684 and a boolean flag as cdr."
685 :group 'org-edit-structure
686 :type '(list
687 (cons (const heading) (boolean))
688 (cons (const plain-list-item) (boolean))))
690 (defcustom org-insert-heading-hook nil
691 "Hook being run after inserting a new heading."
692 :group 'org-edit-structure
693 :type 'hook)
695 (defcustom org-enable-fixed-width-editor t
696 "Non-nil means, lines starting with \":\" are treated as fixed-width.
697 This currently only means, they are never auto-wrapped.
698 When nil, such lines will be treated like ordinary lines.
699 See also the QUOTE keyword."
700 :group 'org-edit-structure
701 :type 'boolean)
703 (defcustom org-edit-src-region-extra nil
704 "Additional regexps to identify regions for editing with `org-edit-src-code'.
705 For examples see the function `org-edit-src-find-region-and-lang'.
706 The regular expression identifying the begin marker should end with a newline,
707 and the regexp marking the end line should start with a newline, to make sure
708 there are kept outside the narrowed region."
709 :group 'org-edit-structure
710 :type '(repeat
711 (list
712 (regexp :tag "begin regexp")
713 (regexp :tag "end regexp")
714 (choice :tag "language"
715 (string :tag "specify")
716 (integer :tag "from match group")
717 (const :tag "from `lang' element")
718 (const :tag "from `style' element")))))
720 (defcustom org-edit-fixed-width-region-mode 'artist-mode
721 "The mode that should be used to edit fixed-width regions.
722 These are the regions where each line starts with a colon."
723 :group 'org-edit-structure
724 :type '(choice
725 (const artist-mode)
726 (const picture-mode)
727 (const fundamental-mode)
728 (function :tag "Other (specify)")))
730 (defcustom org-goto-auto-isearch t
731 "Non-nil means, typing characters in org-goto starts incremental search."
732 :group 'org-edit-structure
733 :type 'boolean)
735 (defgroup org-sparse-trees nil
736 "Options concerning sparse trees in Org-mode."
737 :tag "Org Sparse Trees"
738 :group 'org-structure)
740 (defcustom org-highlight-sparse-tree-matches t
741 "Non-nil means, highlight all matches that define a sparse tree.
742 The highlights will automatically disappear the next time the buffer is
743 changed by an edit command."
744 :group 'org-sparse-trees
745 :type 'boolean)
747 (defcustom org-remove-highlights-with-change t
748 "Non-nil means, any change to the buffer will remove temporary highlights.
749 Such highlights are created by `org-occur' and `org-clock-display'.
750 When nil, `C-c C-c needs to be used to get rid of the highlights.
751 The highlights created by `org-preview-latex-fragment' always need
752 `C-c C-c' to be removed."
753 :group 'org-sparse-trees
754 :group 'org-time
755 :type 'boolean)
758 (defcustom org-occur-hook '(org-first-headline-recenter)
759 "Hook that is run after `org-occur' has constructed a sparse tree.
760 This can be used to recenter the window to show as much of the structure
761 as possible."
762 :group 'org-sparse-trees
763 :type 'hook)
765 (defgroup org-imenu-and-speedbar nil
766 "Options concerning imenu and speedbar in Org-mode."
767 :tag "Org Imenu and Speedbar"
768 :group 'org-structure)
770 (defcustom org-imenu-depth 2
771 "The maximum level for Imenu access to Org-mode headlines.
772 This also applied for speedbar access."
773 :group 'org-imenu-and-speedbar
774 :type 'number)
776 (defgroup org-table nil
777 "Options concerning tables in Org-mode."
778 :tag "Org Table"
779 :group 'org)
781 (defcustom org-enable-table-editor 'optimized
782 "Non-nil means, lines starting with \"|\" are handled by the table editor.
783 When nil, such lines will be treated like ordinary lines.
785 When equal to the symbol `optimized', the table editor will be optimized to
786 do the following:
787 - Automatic overwrite mode in front of whitespace in table fields.
788 This makes the structure of the table stay in tact as long as the edited
789 field does not exceed the column width.
790 - Minimize the number of realigns. Normally, the table is aligned each time
791 TAB or RET are pressed to move to another field. With optimization this
792 happens only if changes to a field might have changed the column width.
793 Optimization requires replacing the functions `self-insert-command',
794 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
795 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
796 very good at guessing when a re-align will be necessary, but you can always
797 force one with \\[org-ctrl-c-ctrl-c].
799 If you would like to use the optimized version in Org-mode, but the
800 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
802 This variable can be used to turn on and off the table editor during a session,
803 but in order to toggle optimization, a restart is required.
805 See also the variable `org-table-auto-blank-field'."
806 :group 'org-table
807 :type '(choice
808 (const :tag "off" nil)
809 (const :tag "on" t)
810 (const :tag "on, optimized" optimized)))
812 (defcustom org-table-tab-recognizes-table.el t
813 "Non-nil means, TAB will automatically notice a table.el table.
814 When it sees such a table, it moves point into it and - if necessary -
815 calls `table-recognize-table'."
816 :group 'org-table-editing
817 :type 'boolean)
819 (defgroup org-link nil
820 "Options concerning links in Org-mode."
821 :tag "Org Link"
822 :group 'org)
824 (defvar org-link-abbrev-alist-local nil
825 "Buffer-local version of `org-link-abbrev-alist', which see.
826 The value of this is taken from the #+LINK lines.")
827 (make-variable-buffer-local 'org-link-abbrev-alist-local)
829 (defcustom org-link-abbrev-alist nil
830 "Alist of link abbreviations.
831 The car of each element is a string, to be replaced at the start of a link.
832 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
833 links in Org-mode buffers can have an optional tag after a double colon, e.g.
835 [[linkkey:tag][description]]
837 If REPLACE is a string, the tag will simply be appended to create the link.
838 If the string contains \"%s\", the tag will be inserted there.
840 REPLACE may also be a function that will be called with the tag as the
841 only argument to create the link, which should be returned as a string.
843 See the manual for examples."
844 :group 'org-link
845 :type 'alist)
847 (defcustom org-descriptive-links t
848 "Non-nil means, hide link part and only show description of bracket links.
849 Bracket links are like [[link][descritpion]]. This variable sets the initial
850 state in new org-mode buffers. The setting can then be toggled on a
851 per-buffer basis from the Org->Hyperlinks menu."
852 :group 'org-link
853 :type 'boolean)
855 (defcustom org-link-file-path-type 'adaptive
856 "How the path name in file links should be stored.
857 Valid values are:
859 relative Relative to the current directory, i.e. the directory of the file
860 into which the link is being inserted.
861 absolute Absolute path, if possible with ~ for home directory.
862 noabbrev Absolute path, no abbreviation of home directory.
863 adaptive Use relative path for files in the current directory and sub-
864 directories of it. For other files, use an absolute path."
865 :group 'org-link
866 :type '(choice
867 (const relative)
868 (const absolute)
869 (const noabbrev)
870 (const adaptive)))
872 (defcustom org-activate-links '(bracket angle plain radio tag date)
873 "Types of links that should be activated in Org-mode files.
874 This is a list of symbols, each leading to the activation of a certain link
875 type. In principle, it does not hurt to turn on most link types - there may
876 be a small gain when turning off unused link types. The types are:
878 bracket The recommended [[link][description]] or [[link]] links with hiding.
879 angular Links in angular brackes that may contain whitespace like
880 <bbdb:Carsten Dominik>.
881 plain Plain links in normal text, no whitespace, like http://google.com.
882 radio Text that is matched by a radio target, see manual for details.
883 tag Tag settings in a headline (link to tag search).
884 date Time stamps (link to calendar).
886 Changing this variable requires a restart of Emacs to become effective."
887 :group 'org-link
888 :type '(set (const :tag "Double bracket links (new style)" bracket)
889 (const :tag "Angular bracket links (old style)" angular)
890 (const :tag "Plain text links" plain)
891 (const :tag "Radio target matches" radio)
892 (const :tag "Tags" tag)
893 (const :tag "Timestamps" date)))
895 (defcustom org-make-link-description-function nil
896 "Function to use to generate link descriptions from links. If
897 nil the link location will be used. This function must take two
898 parameters; the first is the link and the second the description
899 org-insert-link has generated, and should return the description
900 to use."
901 :group 'org-link
902 :type 'function)
904 (defgroup org-link-store nil
905 "Options concerning storing links in Org-mode."
906 :tag "Org Store Link"
907 :group 'org-link)
909 (defcustom org-email-link-description-format "Email %c: %.30s"
910 "Format of the description part of a link to an email or usenet message.
911 The following %-excapes will be replaced by corresponding information:
913 %F full \"From\" field
914 %f name, taken from \"From\" field, address if no name
915 %T full \"To\" field
916 %t first name in \"To\" field, address if no name
917 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
918 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
919 %s subject
920 %m message-id.
922 You may use normal field width specification between the % and the letter.
923 This is for example useful to limit the length of the subject.
925 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
926 :group 'org-link-store
927 :type 'string)
929 (defcustom org-from-is-user-regexp
930 (let (r1 r2)
931 (when (and user-mail-address (not (string= user-mail-address "")))
932 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
933 (when (and user-full-name (not (string= user-full-name "")))
934 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
935 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
936 "Regexp mached against the \"From:\" header of an email or usenet message.
937 It should match if the message is from the user him/herself."
938 :group 'org-link-store
939 :type 'regexp)
941 (defcustom org-context-in-file-links t
942 "Non-nil means, file links from `org-store-link' contain context.
943 A search string will be added to the file name with :: as separator and
944 used to find the context when the link is activated by the command
945 `org-open-at-point'.
946 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
947 negates this setting for the duration of the command."
948 :group 'org-link-store
949 :type 'boolean)
951 (defcustom org-keep-stored-link-after-insertion nil
952 "Non-nil means, keep link in list for entire session.
954 The command `org-store-link' adds a link pointing to the current
955 location to an internal list. These links accumulate during a session.
956 The command `org-insert-link' can be used to insert links into any
957 Org-mode file (offering completion for all stored links). When this
958 option is nil, every link which has been inserted once using \\[org-insert-link]
959 will be removed from the list, to make completing the unused links
960 more efficient."
961 :group 'org-link-store
962 :type 'boolean)
964 (defgroup org-link-follow nil
965 "Options concerning following links in Org-mode."
966 :tag "Org Follow Link"
967 :group 'org-link)
969 (defcustom org-follow-link-hook nil
970 "Hook that is run after a link has been followed."
971 :group 'org-link-follow
972 :type 'hook)
974 (defcustom org-tab-follows-link nil
975 "Non-nil means, on links TAB will follow the link.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-return-follows-link nil
981 "Non-nil means, on links RET will follow the link.
982 Needs to be set before org.el is loaded."
983 :group 'org-link-follow
984 :type 'boolean)
986 (defcustom org-mouse-1-follows-link
987 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
988 "Non-nil means, mouse-1 on a link will follow the link.
989 A longer mouse click will still set point. Does not work on XEmacs.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
994 (defcustom org-mark-ring-length 4
995 "Number of different positions to be recorded in the ring
996 Changing this requires a restart of Emacs to work correctly."
997 :group 'org-link-follow
998 :type 'interger)
1000 (defcustom org-link-frame-setup
1001 '((vm . vm-visit-folder-other-frame)
1002 (gnus . gnus-other-frame)
1003 (file . find-file-other-window))
1004 "Setup the frame configuration for following links.
1005 When following a link with Emacs, it may often be useful to display
1006 this link in another window or frame. This variable can be used to
1007 set this up for the different types of links.
1008 For VM, use any of
1009 `vm-visit-folder'
1010 `vm-visit-folder-other-frame'
1011 For Gnus, use any of
1012 `gnus'
1013 `gnus-other-frame'
1014 For FILE, use any of
1015 `find-file'
1016 `find-file-other-window'
1017 `find-file-other-frame'
1018 For the calendar, use the variable `calendar-setup'.
1019 For BBDB, it is currently only possible to display the matches in
1020 another window."
1021 :group 'org-link-follow
1022 :type '(list
1023 (cons (const vm)
1024 (choice
1025 (const vm-visit-folder)
1026 (const vm-visit-folder-other-window)
1027 (const vm-visit-folder-other-frame)))
1028 (cons (const gnus)
1029 (choice
1030 (const gnus)
1031 (const gnus-other-frame)))
1032 (cons (const file)
1033 (choice
1034 (const find-file)
1035 (const find-file-other-window)
1036 (const find-file-other-frame)))))
1038 (defcustom org-display-internal-link-with-indirect-buffer nil
1039 "Non-nil means, use indirect buffer to display infile links.
1040 Activating internal links (from one location in a file to another location
1041 in the same file) normally just jumps to the location. When the link is
1042 activated with a C-u prefix (or with mouse-3), the link is displayed in
1043 another window. When this option is set, the other window actually displays
1044 an indirect buffer clone of the current buffer, to avoid any visibility
1045 changes to the current buffer."
1046 :group 'org-link-follow
1047 :type 'boolean)
1049 (defcustom org-open-non-existing-files nil
1050 "Non-nil means, `org-open-file' will open non-existing files.
1051 When nil, an error will be generated."
1052 :group 'org-link-follow
1053 :type 'boolean)
1055 (defcustom org-open-directory-means-index-dot-org nil
1056 "Non-nil means, a link to a directory really means to index.org.
1057 When nil, following a directory link will run dired or open a finder/explorer
1058 window on that directory."
1059 :group 'org-link-follow
1060 :type 'boolean)
1062 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1063 "Function and arguments to call for following mailto links.
1064 This is a list with the first element being a lisp function, and the
1065 remaining elements being arguments to the function. In string arguments,
1066 %a will be replaced by the address, and %s will be replaced by the subject
1067 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1068 :group 'org-link-follow
1069 :type '(choice
1070 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1071 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1072 (const :tag "message-mail" (message-mail "%a" "%s"))
1073 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1075 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1076 "Non-nil means, ask for confirmation before executing shell links.
1077 Shell links can be dangerous: just think about a link
1079 [[shell:rm -rf ~/*][Google Search]]
1081 This link would show up in your Org-mode document as \"Google Search\",
1082 but really it would remove your entire home directory.
1083 Therefore we advise against setting this variable to nil.
1084 Just change it to `y-or-n-p' of you want to confirm with a
1085 single keystroke rather than having to type \"yes\"."
1086 :group 'org-link-follow
1087 :type '(choice
1088 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1089 (const :tag "with y-or-n (faster)" y-or-n-p)
1090 (const :tag "no confirmation (dangerous)" nil)))
1092 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1093 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1094 Elisp links can be dangerous: just think about a link
1096 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1098 This link would show up in your Org-mode document as \"Google Search\",
1099 but really it would remove your entire home directory.
1100 Therefore we advise against setting this variable to nil.
1101 Just change it to `y-or-n-p' of you want to confirm with a
1102 single keystroke rather than having to type \"yes\"."
1103 :group 'org-link-follow
1104 :type '(choice
1105 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1106 (const :tag "with y-or-n (faster)" y-or-n-p)
1107 (const :tag "no confirmation (dangerous)" nil)))
1109 (defconst org-file-apps-defaults-gnu
1110 '((remote . emacs)
1111 (t . mailcap))
1112 "Default file applications on a UNIX or GNU/Linux system.
1113 See `org-file-apps'.")
1115 (defconst org-file-apps-defaults-macosx
1116 '((remote . emacs)
1117 (t . "open %s")
1118 ("ps.gz" . "gv %s")
1119 ("eps.gz" . "gv %s")
1120 ("dvi" . "xdvi %s")
1121 ("fig" . "xfig %s"))
1122 "Default file applications on a MacOS X system.
1123 The system \"open\" is known as a default, but we use X11 applications
1124 for some files for which the OS does not have a good default.
1125 See `org-file-apps'.")
1127 (defconst org-file-apps-defaults-windowsnt
1128 (list
1129 '(remote . emacs)
1130 (cons t
1131 (list (if (featurep 'xemacs)
1132 'mswindows-shell-execute
1133 'w32-shell-execute)
1134 "open" 'file)))
1135 "Default file applications on a Windows NT system.
1136 The system \"open\" is used for most files.
1137 See `org-file-apps'.")
1139 (defcustom org-file-apps
1141 (auto-mode . emacs)
1142 ("\\.x?html?\\'" . default)
1143 ("\\.pdf\\'" . default)
1145 "External applications for opening `file:path' items in a document.
1146 Org-mode uses system defaults for different file types, but
1147 you can use this variable to set the application for a given file
1148 extension. The entries in this list are cons cells where the car identifies
1149 files and the cdr the corresponding command. Possible values for the
1150 file identifier are
1151 \"regex\" Regular expression matched against the file name. For backward
1152 compatibility, this can also be a string with only alphanumeric
1153 characters, which is then interpreted as an extension.
1154 `directory' Matches a directory
1155 `remote' Matches a remote file, accessible through tramp or efs.
1156 Remote files most likely should be visited through Emacs
1157 because external applications cannot handle such paths.
1158 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1159 so all files Emacs knows how to handle. Useing this with
1160 command `emacs' will open most files in Emacs. Beware that this
1161 will also open html files insite Emacs, unless you add
1162 (\"html\" . default) to the list as well.
1163 t Default for files not matched by any of the other options.
1165 Possible values for the command are:
1166 `emacs' The file will be visited by the current Emacs process.
1167 `default' Use the default application for this file type, which is the
1168 association for t in the list, most likely in the system-specific
1169 part.
1170 This can be used to overrule an unwanted seting in the
1171 system-specific variable.
1172 string A command to be executed by a shell; %s will be replaced
1173 by the path to the file.
1174 sexp A Lisp form which will be evaluated. The file path will
1175 be available in the Lisp variable `file'.
1176 For more examples, see the system specific constants
1177 `org-file-apps-defaults-macosx'
1178 `org-file-apps-defaults-windowsnt'
1179 `org-file-apps-defaults-gnu'."
1180 :group 'org-link-follow
1181 :type '(repeat
1182 (cons (choice :value ""
1183 (string :tag "Extension")
1184 (const :tag "Default for unrecognized files" t)
1185 (const :tag "Remote file" remote)
1186 (const :tag "Links to a directory" directory)
1187 (const :tag "Any files that have Emacs modes"
1188 auto-mode))
1189 (choice :value ""
1190 (const :tag "Visit with Emacs" emacs)
1191 (const :tag "Use system default" default)
1192 (string :tag "Command")
1193 (sexp :tag "Lisp form")))))
1195 (defgroup org-refile nil
1196 "Options concerning refiling entries in Org-mode."
1197 :tag "Org Remember"
1198 :group 'org)
1200 (defcustom org-directory "~/org"
1201 "Directory with org files.
1202 This directory will be used as default to prompt for org files.
1203 Used by the hooks for remember.el."
1204 :group 'org-refile
1205 :group 'org-remember
1206 :type 'directory)
1208 (defcustom org-default-notes-file "~/.notes"
1209 "Default target for storing notes.
1210 Used by the hooks for remember.el. This can be a string, or nil to mean
1211 the value of `remember-data-file'.
1212 You can set this on a per-template basis with the variable
1213 `org-remember-templates'."
1214 :group 'org-refile
1215 :group 'org-remember
1216 :type '(choice
1217 (const :tag "Default from remember-data-file" nil)
1218 file))
1220 (defcustom org-goto-interface 'outline
1221 "The default interface to be used for `org-goto'.
1222 Allowed vaues are:
1223 outline The interface shows an outline of the relevant file
1224 and the correct heading is found by moving through
1225 the outline or by searching with incremental search.
1226 outline-path-completion Headlines in the current buffer are offered via
1227 completion."
1228 :group 'org-refile
1229 :type '(choice
1230 (const :tag "Outline" outline)
1231 (const :tag "Outline-path-completion" outline-path-completion)))
1233 (defcustom org-reverse-note-order nil
1234 "Non-nil means, store new notes at the beginning of a file or entry.
1235 When nil, new notes will be filed to the end of a file or entry.
1236 This can also be a list with cons cells of regular expressions that
1237 are matched against file names, and values."
1238 :group 'org-remember
1239 :type '(choice
1240 (const :tag "Reverse always" t)
1241 (const :tag "Reverse never" nil)
1242 (repeat :tag "By file name regexp"
1243 (cons regexp boolean))))
1245 (defcustom org-refile-targets nil
1246 "Targets for refiling entries with \\[org-refile].
1247 This is list of cons cells. Each cell contains:
1248 - a specification of the files to be considered, either a list of files,
1249 or a symbol whose function or variable value will be used to retrieve
1250 a file name or a list of file names. Nil means, refile to a different
1251 heading in the current buffer.
1252 - A specification of how to find candidate refile targets. This may be
1253 any of
1254 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1255 This tag has to be present in all target headlines, inheritance will
1256 not be considered.
1257 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1258 todo keyword.
1259 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1260 headlines that are refiling targets.
1261 - a cons cell (:level . N). Any headline of level N is considered a target.
1262 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1264 When this variable is nil, all top-level headlines in the current buffer
1265 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1266 :group 'org-remember
1267 :type '(repeat
1268 (cons
1269 (choice :value org-agenda-files
1270 (const :tag "All agenda files" org-agenda-files)
1271 (const :tag "Current buffer" nil)
1272 (function) (variable) (file))
1273 (choice :tag "Identify target headline by"
1274 (cons :tag "Specific tag" (const :tag) (string))
1275 (cons :tag "TODO keyword" (const :todo) (string))
1276 (cons :tag "Regular expression" (const :regexp) (regexp))
1277 (cons :tag "Level number" (const :level) (integer))
1278 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1280 (defcustom org-refile-use-outline-path nil
1281 "Non-nil means, provide refile targets as paths.
1282 So a level 3 headline will be available as level1/level2/level3.
1283 When the value is `file', also include the file name (without directory)
1284 into the path. When `full-file-path', include the full file path."
1285 :group 'org-remember
1286 :type '(choice
1287 (const :tag "Not" nil)
1288 (const :tag "Yes" t)
1289 (const :tag "Start with file name" file)
1290 (const :tag "Start with full file path" full-file-path)))
1292 (defgroup org-todo nil
1293 "Options concerning TODO items in Org-mode."
1294 :tag "Org TODO"
1295 :group 'org)
1297 (defgroup org-progress nil
1298 "Options concerning Progress logging in Org-mode."
1299 :tag "Org Progress"
1300 :group 'org-time)
1302 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1303 "List of TODO entry keyword sequences and their interpretation.
1304 \\<org-mode-map>This is a list of sequences.
1306 Each sequence starts with a symbol, either `sequence' or `type',
1307 indicating if the keywords should be interpreted as a sequence of
1308 action steps, or as different types of TODO items. The first
1309 keywords are states requiring action - these states will select a headline
1310 for inclusion into the global TODO list Org-mode produces. If one of
1311 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1312 signify that no further action is necessary. If \"|\" is not found,
1313 the last keyword is treated as the only DONE state of the sequence.
1315 The command \\[org-todo] cycles an entry through these states, and one
1316 additional state where no keyword is present. For details about this
1317 cycling, see the manual.
1319 TODO keywords and interpretation can also be set on a per-file basis with
1320 the special #+SEQ_TODO and #+TYP_TODO lines.
1322 Each keyword can optionally specify a character for fast state selection
1323 \(in combination with the variable `org-use-fast-todo-selection')
1324 and specifiers for state change logging, using the same syntax
1325 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1326 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1327 indicates to record a time stamp each time this state is selected.
1329 Each keyword may also specify if a timestamp or a note should be
1330 recorded when entering or leaving the state, by adding additional
1331 characters in the parenthesis after the keyword. This looks like this:
1332 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1333 record only the time of the state change. With X and Y being either
1334 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1335 Y when leaving the state if and only if the *target* state does not
1336 define X. You may omit any of the fast-selection key or X or /Y,
1337 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1339 For backward compatibility, this variable may also be just a list
1340 of keywords - in this case the interptetation (sequence or type) will be
1341 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1342 :group 'org-todo
1343 :group 'org-keywords
1344 :type '(choice
1345 (repeat :tag "Old syntax, just keywords"
1346 (string :tag "Keyword"))
1347 (repeat :tag "New syntax"
1348 (cons
1349 (choice
1350 :tag "Interpretation"
1351 (const :tag "Sequence (cycling hits every state)" sequence)
1352 (const :tag "Type (cycling directly to DONE)" type))
1353 (repeat
1354 (string :tag "Keyword"))))))
1356 (defvar org-todo-keywords-1 nil
1357 "All TODO and DONE keywords active in a buffer.")
1358 (make-variable-buffer-local 'org-todo-keywords-1)
1359 (defvar org-todo-keywords-for-agenda nil)
1360 (defvar org-done-keywords-for-agenda nil)
1361 (defvar org-todo-keyword-alist-for-agenda nil)
1362 (defvar org-tag-alist-for-agenda nil)
1363 (defvar org-agenda-contributing-files nil)
1364 (defvar org-not-done-keywords nil)
1365 (make-variable-buffer-local 'org-not-done-keywords)
1366 (defvar org-done-keywords nil)
1367 (make-variable-buffer-local 'org-done-keywords)
1368 (defvar org-todo-heads nil)
1369 (make-variable-buffer-local 'org-todo-heads)
1370 (defvar org-todo-sets nil)
1371 (make-variable-buffer-local 'org-todo-sets)
1372 (defvar org-todo-log-states nil)
1373 (make-variable-buffer-local 'org-todo-log-states)
1374 (defvar org-todo-kwd-alist nil)
1375 (make-variable-buffer-local 'org-todo-kwd-alist)
1376 (defvar org-todo-key-alist nil)
1377 (make-variable-buffer-local 'org-todo-key-alist)
1378 (defvar org-todo-key-trigger nil)
1379 (make-variable-buffer-local 'org-todo-key-trigger)
1381 (defcustom org-todo-interpretation 'sequence
1382 "Controls how TODO keywords are interpreted.
1383 This variable is in principle obsolete and is only used for
1384 backward compatibility, if the interpretation of todo keywords is
1385 not given already in `org-todo-keywords'. See that variable for
1386 more information."
1387 :group 'org-todo
1388 :group 'org-keywords
1389 :type '(choice (const sequence)
1390 (const type)))
1392 (defcustom org-use-fast-todo-selection 'prefix
1393 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1394 This variable describes if and under what circumstances the cycling
1395 mechanism for TODO keywords will be replaced by a single-key, direct
1396 selection scheme.
1398 When nil, fast selection is never used.
1400 When the symbol `prefix', it will be used when `org-todo' is called with
1401 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1402 in an agenda buffer.
1404 When t, fast selection is used by default. In this case, the prefix
1405 argument forces cycling instead.
1407 In all cases, the special interface is only used if access keys have actually
1408 been assigned by the user, i.e. if keywords in the configuration are followed
1409 by a letter in parenthesis, like TODO(t)."
1410 :group 'org-todo
1411 :type '(choice
1412 (const :tag "Never" nil)
1413 (const :tag "By default" t)
1414 (const :tag "Only with C-u C-c C-t" prefix)))
1416 (defcustom org-provide-todo-statistics t
1417 "Non-nil means, update todo statistics after insert and toggle.
1418 When this is set, todo statistics is updated in the parent of the current
1419 entry each time a todo state is changed."
1420 :group 'org-todo
1421 :type 'boolean)
1423 (defcustom org-after-todo-state-change-hook nil
1424 "Hook which is run after the state of a TODO item was changed.
1425 The new state (a string with a TODO keyword, or nil) is available in the
1426 Lisp variable `state'."
1427 :group 'org-todo
1428 :type 'hook)
1430 (defcustom org-todo-state-tags-triggers nil
1431 "Tag changes that should be triggered by TODO state changes.
1432 This is a list. Each entry is
1434 (state-change (tag . flag) .......)
1436 State-change can be a string with a state, and empty string to indicate the
1437 state that has no TODO keyword, or it can be one of the symbols `todo'
1438 or `done', meaning any not-done or done state, respectively."
1439 :group 'org-todo
1440 :group 'org-tags
1441 :type '(repeat
1442 (cons (choice :tag "When changing to"
1443 (const :tag "Not-done state" todo)
1444 (const :tag "Done state" done)
1445 (string :tag "State"))
1446 (repeat
1447 (cons :tag "Tag action"
1448 (string :tag "Tag")
1449 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1451 (defcustom org-log-done nil
1452 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1453 When equal to the list (done), also prompt for a closing note.
1454 This can also be configured on a per-file basis by adding one of
1455 the following lines anywhere in the buffer:
1457 #+STARTUP: logdone
1458 #+STARTUP: lognotedone
1459 #+STARTUP: nologdone"
1460 :group 'org-todo
1461 :group 'org-progress
1462 :type '(choice
1463 (const :tag "No logging" nil)
1464 (const :tag "Record CLOSED timestamp" time)
1465 (const :tag "Record CLOSED timestamp with closing note." note)))
1467 ;; Normalize old uses of org-log-done.
1468 (cond
1469 ((eq org-log-done t) (setq org-log-done 'time))
1470 ((and (listp org-log-done) (memq 'done org-log-done))
1471 (setq org-log-done 'note)))
1473 (defcustom org-log-note-clock-out nil
1474 "Non-nil means, record a note when clocking out of an item.
1475 This can also be configured on a per-file basis by adding one of
1476 the following lines anywhere in the buffer:
1478 #+STARTUP: lognoteclock-out
1479 #+STARTUP: nolognoteclock-out"
1480 :group 'org-todo
1481 :group 'org-progress
1482 :type 'boolean)
1484 (defcustom org-log-done-with-time t
1485 "Non-nil means, the CLOSED time stamp will contain date and time.
1486 When nil, only the date will be recorded."
1487 :group 'org-progress
1488 :type 'boolean)
1490 (defcustom org-log-note-headings
1491 '((done . "CLOSING NOTE %t")
1492 (state . "State %-12s %t")
1493 (note . "Note taken on %t")
1494 (clock-out . ""))
1495 "Headings for notes added to entries.
1496 The value is an alist, with the car being a symbol indicating the note
1497 context, and the cdr is the heading to be used. The heading may also be the
1498 empty string.
1499 %t in the heading will be replaced by a time stamp.
1500 %s will be replaced by the new TODO state, in double quotes.
1501 %u will be replaced by the user name.
1502 %U will be replaced by the full user name."
1503 :group 'org-todo
1504 :group 'org-progress
1505 :type '(list :greedy t
1506 (cons (const :tag "Heading when closing an item" done) string)
1507 (cons (const :tag
1508 "Heading when changing todo state (todo sequence only)"
1509 state) string)
1510 (cons (const :tag "Heading when just taking a note" note) string)
1511 (cons (const :tag "Heading when clocking out" clock-out) string)))
1513 (unless (assq 'note org-log-note-headings)
1514 (push '(note . "%t") org-log-note-headings))
1516 (defcustom org-log-state-notes-insert-after-drawers nil
1517 "Non-nil means, insert state change notes after any drawers in entry.
1518 Only the drawers that *immediately* follow the headline and the
1519 deadline/scheduled line are skipped.
1520 When nil, insert notes right after the heading and perhaps the line
1521 with deadline/scheduling if present."
1522 :group 'org-todo
1523 :group 'org-progress
1524 :type 'boolean)
1526 (defcustom org-log-states-order-reversed t
1527 "Non-nil means, the latest state change note will be directly after heading.
1528 When nil, the notes will be orderer according to time."
1529 :group 'org-todo
1530 :group 'org-progress
1531 :type 'boolean)
1533 (defcustom org-log-repeat 'time
1534 "Non-nil means, record moving through the DONE state when triggering repeat.
1535 An auto-repeating tasks is immediately switched back to TODO when marked
1536 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1537 the TODO keyword definition, or recording a closing note by setting
1538 `org-log-done', there will be no record of the task moving through DONE.
1539 This variable forces taking a note anyway. Possible values are:
1541 nil Don't force a record
1542 time Record a time stamp
1543 note Record a note
1545 This option can also be set with on a per-file-basis with
1547 #+STARTUP: logrepeat
1548 #+STARTUP: lognoterepeat
1549 #+STARTUP: nologrepeat
1551 You can have local logging settings for a subtree by setting the LOGGING
1552 property to one or more of these keywords."
1553 :group 'org-todo
1554 :group 'org-progress
1555 :type '(choice
1556 (const :tag "Don't force a record" nil)
1557 (const :tag "Force recording the DONE state" time)
1558 (const :tag "Force recording a note with the DONE state" note)))
1561 (defgroup org-priorities nil
1562 "Priorities in Org-mode."
1563 :tag "Org Priorities"
1564 :group 'org-todo)
1566 (defcustom org-highest-priority ?A
1567 "The highest priority of TODO items. A character like ?A, ?B etc.
1568 Must have a smaller ASCII number than `org-lowest-priority'."
1569 :group 'org-priorities
1570 :type 'character)
1572 (defcustom org-lowest-priority ?C
1573 "The lowest priority of TODO items. A character like ?A, ?B etc.
1574 Must have a larger ASCII number than `org-highest-priority'."
1575 :group 'org-priorities
1576 :type 'character)
1578 (defcustom org-default-priority ?B
1579 "The default priority of TODO items.
1580 This is the priority an item get if no explicit priority is given."
1581 :group 'org-priorities
1582 :type 'character)
1584 (defcustom org-priority-start-cycle-with-default t
1585 "Non-nil means, start with default priority when starting to cycle.
1586 When this is nil, the first step in the cycle will be (depending on the
1587 command used) one higher or lower that the default priority."
1588 :group 'org-priorities
1589 :type 'boolean)
1591 (defgroup org-time nil
1592 "Options concerning time stamps and deadlines in Org-mode."
1593 :tag "Org Time"
1594 :group 'org)
1596 (defcustom org-insert-labeled-timestamps-at-point nil
1597 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1598 When nil, these labeled time stamps are forces into the second line of an
1599 entry, just after the headline. When scheduling from the global TODO list,
1600 the time stamp will always be forced into the second line."
1601 :group 'org-time
1602 :type 'boolean)
1604 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1605 "Formats for `format-time-string' which are used for time stamps.
1606 It is not recommended to change this constant.")
1608 (defcustom org-time-stamp-rounding-minutes '(0 5)
1609 "Number of minutes to round time stamps to.
1610 These are two values, the first applies when first creating a time stamp.
1611 The second applies when changing it with the commands `S-up' and `S-down'.
1612 When changing the time stamp, this means that it will change in steps
1613 of N minutes, as given by the second value.
1615 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1616 numbers should be factors of 60, so for example 5, 10, 15.
1618 When this is larger than 1, you can still force an exact time-stamp by using
1619 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1620 and by using a prefix arg to `S-up/down' to specify the exact number
1621 of minutes to shift."
1622 :group 'org-time
1623 :get '(lambda (var) ; Make sure all entries have 5 elements
1624 (if (integerp (default-value var))
1625 (list (default-value var) 5)
1626 (default-value var)))
1627 :type '(list
1628 (integer :tag "when inserting times")
1629 (integer :tag "when modifying times")))
1631 ;; Normalize old customizations of this variable.
1632 (when (integerp org-time-stamp-rounding-minutes)
1633 (setq org-time-stamp-rounding-minutes
1634 (list org-time-stamp-rounding-minutes
1635 org-time-stamp-rounding-minutes)))
1637 (defcustom org-display-custom-times nil
1638 "Non-nil means, overlay custom formats over all time stamps.
1639 The formats are defined through the variable `org-time-stamp-custom-formats'.
1640 To turn this on on a per-file basis, insert anywhere in the file:
1641 #+STARTUP: customtime"
1642 :group 'org-time
1643 :set 'set-default
1644 :type 'sexp)
1645 (make-variable-buffer-local 'org-display-custom-times)
1647 (defcustom org-time-stamp-custom-formats
1648 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1649 "Custom formats for time stamps. See `format-time-string' for the syntax.
1650 These are overlayed over the default ISO format if the variable
1651 `org-display-custom-times' is set. Time like %H:%M should be at the
1652 end of the second format."
1653 :group 'org-time
1654 :type 'sexp)
1656 (defun org-time-stamp-format (&optional long inactive)
1657 "Get the right format for a time string."
1658 (let ((f (if long (cdr org-time-stamp-formats)
1659 (car org-time-stamp-formats))))
1660 (if inactive
1661 (concat "[" (substring f 1 -1) "]")
1662 f)))
1664 (defcustom org-time-clocksum-format "%d:%02d"
1665 "The format string used when creating CLOCKSUM lines, or when
1666 org-mode generates a time duration."
1667 :group 'org-time
1668 :type 'string)
1670 (defcustom org-deadline-warning-days 14
1671 "No. of days before expiration during which a deadline becomes active.
1672 This variable governs the display in sparse trees and in the agenda.
1673 When 0 or negative, it means use this number (the absolute value of it)
1674 even if a deadline has a different individual lead time specified."
1675 :group 'org-time
1676 :group 'org-agenda-daily/weekly
1677 :type 'number)
1679 (defcustom org-read-date-prefer-future t
1680 "Non-nil means, assume future for incomplete date input from user.
1681 This affects the following situations:
1682 1. The user gives a day, but no month.
1683 For example, if today is the 15th, and you enter \"3\", Org-mode will
1684 read this as the third of *next* month. However, if you enter \"17\",
1685 it will be considered as *this* month.
1686 2. The user gives a month but not a year.
1687 For example, if it is april and you enter \"feb 2\", this will be read
1688 as feb 2, *next* year. \"May 5\", however, will be this year.
1690 Currently this does not work for ISO week specifications.
1692 When this option is nil, the current month and year will always be used
1693 as defaults."
1694 :group 'org-time
1695 :type 'boolean)
1697 (defcustom org-read-date-display-live t
1698 "Non-nil means, display current interpretation of date prompt live.
1699 This display will be in an overlay, in the minibuffer."
1700 :group 'org-time
1701 :type 'boolean)
1703 (defcustom org-read-date-popup-calendar t
1704 "Non-nil means, pop up a calendar when prompting for a date.
1705 In the calendar, the date can be selected with mouse-1. However, the
1706 minibuffer will also be active, and you can simply enter the date as well.
1707 When nil, only the minibuffer will be available."
1708 :group 'org-time
1709 :type 'boolean)
1710 (if (fboundp 'defvaralias)
1711 (defvaralias 'org-popup-calendar-for-date-prompt
1712 'org-read-date-popup-calendar))
1714 (defcustom org-extend-today-until 0
1715 "The hour when your day really ends. Must be an integer.
1716 This has influence for the following applications:
1717 - When switching the agenda to \"today\". It it is still earlier than
1718 the time given here, the day recognized as TODAY is actually yesterday.
1719 - When a date is read from the user and it is still before the time given
1720 here, the current date and time will be assumed to be yesterday, 23:59.
1721 Also, timestamps inserted in remember templates follow this rule.
1723 IMPORTANT: This is a feature whose implementation is and likely will
1724 remain incomplete. Really, it is only here because past midnight seems to
1725 ne the favorite working time of John Wiegley :-)"
1726 :group 'org-time
1727 :type 'number)
1729 (defcustom org-edit-timestamp-down-means-later nil
1730 "Non-nil means, S-down will increase the time in a time stamp.
1731 When nil, S-up will increase."
1732 :group 'org-time
1733 :type 'boolean)
1735 (defcustom org-calendar-follow-timestamp-change t
1736 "Non-nil means, make the calendar window follow timestamp changes.
1737 When a timestamp is modified and the calendar window is visible, it will be
1738 moved to the new date."
1739 :group 'org-time
1740 :type 'boolean)
1742 (defgroup org-tags nil
1743 "Options concerning tags in Org-mode."
1744 :tag "Org Tags"
1745 :group 'org)
1747 (defcustom org-tag-alist nil
1748 "List of tags allowed in Org-mode files.
1749 When this list is nil, Org-mode will base TAG input on what is already in the
1750 buffer.
1751 The value of this variable is an alist, the car of each entry must be a
1752 keyword as a string, the cdr may be a character that is used to select
1753 that tag through the fast-tag-selection interface.
1754 See the manual for details."
1755 :group 'org-tags
1756 :type '(repeat
1757 (choice
1758 (cons (string :tag "Tag name")
1759 (character :tag "Access char"))
1760 (const :tag "Start radio group" (:startgroup))
1761 (const :tag "End radio group" (:endgroup)))))
1763 (defvar org-file-tags nil
1764 "List of tags that can be inherited by all entries in the file.
1765 The tags will be inherited if the variable `org-use-tag-inheritance'
1766 says they should be.
1767 This variable is populated from #+TAG lines.")
1769 (defcustom org-use-fast-tag-selection 'auto
1770 "Non-nil means, use fast tag selection scheme.
1771 This is a special interface to select and deselect tags with single keys.
1772 When nil, fast selection is never used.
1773 When the symbol `auto', fast selection is used if and only if selection
1774 characters for tags have been configured, either through the variable
1775 `org-tag-alist' or through a #+TAGS line in the buffer.
1776 When t, fast selection is always used and selection keys are assigned
1777 automatically if necessary."
1778 :group 'org-tags
1779 :type '(choice
1780 (const :tag "Always" t)
1781 (const :tag "Never" nil)
1782 (const :tag "When selection characters are configured" 'auto)))
1784 (defcustom org-fast-tag-selection-single-key nil
1785 "Non-nil means, fast tag selection exits after first change.
1786 When nil, you have to press RET to exit it.
1787 During fast tag selection, you can toggle this flag with `C-c'.
1788 This variable can also have the value `expert'. In this case, the window
1789 displaying the tags menu is not even shown, until you press C-c again."
1790 :group 'org-tags
1791 :type '(choice
1792 (const :tag "No" nil)
1793 (const :tag "Yes" t)
1794 (const :tag "Expert" expert)))
1796 (defvar org-fast-tag-selection-include-todo nil
1797 "Non-nil means, fast tags selection interface will also offer TODO states.
1798 This is an undocumented feature, you should not rely on it.")
1800 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1801 "The column to which tags should be indented in a headline.
1802 If this number is positive, it specifies the column. If it is negative,
1803 it means that the tags should be flushright to that column. For example,
1804 -80 works well for a normal 80 character screen."
1805 :group 'org-tags
1806 :type 'integer)
1808 (defcustom org-auto-align-tags t
1809 "Non-nil means, realign tags after pro/demotion of TODO state change.
1810 These operations change the length of a headline and therefore shift
1811 the tags around. With this options turned on, after each such operation
1812 the tags are again aligned to `org-tags-column'."
1813 :group 'org-tags
1814 :type 'boolean)
1816 (defcustom org-use-tag-inheritance t
1817 "Non-nil means, tags in levels apply also for sublevels.
1818 When nil, only the tags directly given in a specific line apply there.
1819 If this option is t, a match early-on in a tree can lead to a large
1820 number of matches in the subtree. If you only want to see the first
1821 match in a tree during a search, check out the variable
1822 `org-tags-match-list-sublevels'.
1824 This may also be a list of tags that should be inherited, or a regexp that
1825 matches tags that should be inherited."
1826 :group 'org-tags
1827 :type '(choice
1828 (const :tag "Not" nil)
1829 (const :tag "Always" t)
1830 (repeat :tag "Specific tags" (string :tag "Tag"))
1831 (regexp :tag "Tags matched by regexp")))
1833 (defun org-tag-inherit-p (tag)
1834 "Check if TAG is one that should be inherited."
1835 (cond
1836 ((eq org-use-tag-inheritance t) t)
1837 ((not org-use-tag-inheritance) nil)
1838 ((stringp org-use-tag-inheritance)
1839 (string-match org-use-tag-inheritance tag))
1840 ((listp org-use-tag-inheritance)
1841 (member tag org-use-tag-inheritance))
1842 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1844 (defcustom org-tags-match-list-sublevels t
1845 "Non-nil means list also sublevels of headlines matching tag search.
1846 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1847 the sublevels of a headline matching a tag search often also match
1848 the same search. Listing all of them can create very long lists.
1849 Setting this variable to nil causes subtrees of a match to be skipped.
1850 This option is off by default, because inheritance in on. If you turn
1851 inheritance off, you very likely want to turn this option on.
1853 As a special case, if the tag search is restricted to TODO items, the
1854 value of this variable is ignored and sublevels are always checked, to
1855 make sure all corresponding TODO items find their way into the list."
1856 :group 'org-tags
1857 :type 'boolean)
1859 (defvar org-tags-history nil
1860 "History of minibuffer reads for tags.")
1861 (defvar org-last-tags-completion-table nil
1862 "The last used completion table for tags.")
1863 (defvar org-after-tags-change-hook nil
1864 "Hook that is run after the tags in a line have changed.")
1866 (defgroup org-properties nil
1867 "Options concerning properties in Org-mode."
1868 :tag "Org Properties"
1869 :group 'org)
1871 (defcustom org-property-format "%-10s %s"
1872 "How property key/value pairs should be formatted by `indent-line'.
1873 When `indent-line' hits a property definition, it will format the line
1874 according to this format, mainly to make sure that the values are
1875 lined-up with respect to each other."
1876 :group 'org-properties
1877 :type 'string)
1879 (defcustom org-use-property-inheritance nil
1880 "Non-nil means, properties apply also for sublevels.
1882 This setting is chiefly used during property searches. Turning it on can
1883 cause significant overhead when doing a search, which is why it is not
1884 on by default.
1886 When nil, only the properties directly given in the current entry count.
1887 When t, every property is inherited. The value may also be a list of
1888 properties that should have inheritance, or a regular expression matching
1889 properties that should be inherited.
1891 However, note that some special properties use inheritance under special
1892 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1893 and the properties ending in \"_ALL\" when they are used as descriptor
1894 for valid values of a property.
1896 Note for programmers:
1897 When querying an entry with `org-entry-get', you can control if inheritance
1898 should be used. By default, `org-entry-get' looks only at the local
1899 properties. You can request inheritance by setting the inherit argument
1900 to t (to force inheritance) or to `selective' (to respect the setting
1901 in this variable)."
1902 :group 'org-properties
1903 :type '(choice
1904 (const :tag "Not" nil)
1905 (const :tag "Always" t)
1906 (repeat :tag "Specific properties" (string :tag "Property"))
1907 (regexp :tag "Properties matched by regexp")))
1909 (defun org-property-inherit-p (property)
1910 "Check if PROPERTY is one that should be inherited."
1911 (cond
1912 ((eq org-use-property-inheritance t) t)
1913 ((not org-use-property-inheritance) nil)
1914 ((stringp org-use-property-inheritance)
1915 (string-match org-use-property-inheritance property))
1916 ((listp org-use-property-inheritance)
1917 (member property org-use-property-inheritance))
1918 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1920 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1921 "The default column format, if no other format has been defined.
1922 This variable can be set on the per-file basis by inserting a line
1924 #+COLUMNS: %25ITEM ....."
1925 :group 'org-properties
1926 :type 'string)
1928 (defcustom org-columns-ellipses ".."
1929 "The ellipses to be used when a field in column view is truncated.
1930 When this is the empty string, as many characters as possible are shown,
1931 but then there will be no visual indication that the field has been truncated.
1932 When this is a string of length N, the last N characters of a truncated
1933 field are replaced by this string. If the column is narrower than the
1934 ellipses string, only part of the ellipses string will be shown."
1935 :group 'org-properties
1936 :type 'string)
1938 (defcustom org-columns-modify-value-for-display-function nil
1939 "Function that modifies values for display in column view.
1940 For example, it can be used to cut out a certain part from a time stamp.
1941 The function must take 2 argments:
1943 column-title The tite of the column (*not* the property name)
1944 value The value that should be modified.
1946 The function should return the value that should be displayed,
1947 or nil if the normal value should be used."
1948 :group 'org-properties
1949 :type 'function)
1951 (defcustom org-effort-property "Effort"
1952 "The property that is being used to keep track of effort estimates.
1953 Effort estimates given in this property need to have the format H:MM."
1954 :group 'org-properties
1955 :group 'org-progress
1956 :type '(string :tag "Property"))
1958 (defconst org-global-properties-fixed
1959 '(("VISIBILITY_ALL" . "folded children content all"))
1960 "List of property/value pairs that can be inherited by any entry.
1961 These are fixed values, for the preset properties.")
1964 (defcustom org-global-properties nil
1965 "List of property/value pairs that can be inherited by any entry.
1966 You can set buffer-local values for this by adding lines like
1968 #+PROPERTY: NAME VALUE"
1969 :group 'org-properties
1970 :type '(repeat
1971 (cons (string :tag "Property")
1972 (string :tag "Value"))))
1974 (defvar org-file-properties nil
1975 "List of property/value pairs that can be inherited by any entry.
1976 Valid for the current buffer.
1977 This variable is populated from #+PROPERTY lines.")
1978 (make-variable-buffer-local 'org-file-properties)
1980 (defgroup org-agenda nil
1981 "Options concerning agenda views in Org-mode."
1982 :tag "Org Agenda"
1983 :group 'org)
1985 (defvar org-category nil
1986 "Variable used by org files to set a category for agenda display.
1987 Such files should use a file variable to set it, for example
1989 # -*- mode: org; org-category: \"ELisp\"
1991 or contain a special line
1993 #+CATEGORY: ELisp
1995 If the file does not specify a category, then file's base name
1996 is used instead.")
1997 (make-variable-buffer-local 'org-category)
1998 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2000 (defcustom org-agenda-files nil
2001 "The files to be used for agenda display.
2002 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2003 \\[org-remove-file]. You can also use customize to edit the list.
2005 If an entry is a directory, all files in that directory that are matched by
2006 `org-agenda-file-regexp' will be part of the file list.
2008 If the value of the variable is not a list but a single file name, then
2009 the list of agenda files is actually stored and maintained in that file, one
2010 agenda file per line."
2011 :group 'org-agenda
2012 :type '(choice
2013 (repeat :tag "List of files and directories" file)
2014 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2016 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2017 "Regular expression to match files for `org-agenda-files'.
2018 If any element in the list in that variable contains a directory instead
2019 of a normal file, all files in that directory that are matched by this
2020 regular expression will be included."
2021 :group 'org-agenda
2022 :type 'regexp)
2024 (defcustom org-agenda-text-search-extra-files nil
2025 "List of extra files to be searched by text search commands.
2026 These files will be search in addition to the agenda files by the
2027 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2028 Note that these files will only be searched for text search commands,
2029 not for the other agenda views like todo lists, tag searches or the weekly
2030 agenda. This variable is intended to list notes and possibly archive files
2031 that should also be searched by these two commands.
2032 In fact, if the first element in the list is the symbol `agenda-archives',
2033 than all archive files of all agenda files will be added to the search
2034 scope."
2035 :group 'org-agenda
2036 :type '(set :greedy t
2037 (const :tag "Agenda Archives" agenda-archives)
2038 (repeat :inline t (file))))
2040 (if (fboundp 'defvaralias)
2041 (defvaralias 'org-agenda-multi-occur-extra-files
2042 'org-agenda-text-search-extra-files))
2044 (defcustom org-agenda-skip-unavailable-files nil
2045 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2046 A nil value means to remove them, after a query, from the list."
2047 :group 'org-agenda
2048 :type 'boolean)
2050 (defcustom org-calendar-to-agenda-key [?c]
2051 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2052 The command `org-calendar-goto-agenda' will be bound to this key. The
2053 default is the character `c' because then `c' can be used to switch back and
2054 forth between agenda and calendar."
2055 :group 'org-agenda
2056 :type 'sexp)
2058 (defcustom org-calendar-agenda-action-key [?k]
2059 "The key to be installed in `calendar-mode-map' for agenda-action.
2060 The command `org-agenda-action' will be bound to this key. The
2061 default is the character `k' because we use the same key in the agenda."
2062 :group 'org-agenda
2063 :type 'sexp)
2065 (eval-after-load "calendar"
2066 '(progn
2067 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2068 'org-calendar-goto-agenda)
2069 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2070 'org-agenda-action)))
2072 (defgroup org-latex nil
2073 "Options for embedding LaTeX code into Org-mode."
2074 :tag "Org LaTeX"
2075 :group 'org)
2077 (defcustom org-format-latex-options
2078 '(:foreground default :background default :scale 1.0
2079 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2080 :matchers ("begin" "$" "$$" "\\(" "\\["))
2081 "Options for creating images from LaTeX fragments.
2082 This is a property list with the following properties:
2083 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2084 `default' means use the foreground of the default face.
2085 :background the background color, or \"Transparent\".
2086 `default' means use the background of the default face.
2087 :scale a scaling factor for the size of the images.
2088 :html-foreground, :html-background, :html-scale
2089 the same numbers for HTML export.
2090 :matchers a list indicating which matchers should be used to
2091 find LaTeX fragments. Valid members of this list are:
2092 \"begin\" find environments
2093 \"$\" find math expressions surrounded by $...$
2094 \"$$\" find math expressions surrounded by $$....$$
2095 \"\\(\" find math expressions surrounded by \\(...\\)
2096 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2097 :group 'org-latex
2098 :type 'plist)
2100 (defcustom org-format-latex-header "\\documentclass{article}
2101 \\usepackage{fullpage} % do not remove
2102 \\usepackage{amssymb}
2103 \\usepackage[usenames]{color}
2104 \\usepackage{amsmath}
2105 \\usepackage{latexsym}
2106 \\usepackage[mathscr]{eucal}
2107 \\pagestyle{empty} % do not remove"
2108 "The document header used for processing LaTeX fragments."
2109 :group 'org-latex
2110 :type 'string)
2113 (defgroup org-font-lock nil
2114 "Font-lock settings for highlighting in Org-mode."
2115 :tag "Org Font Lock"
2116 :group 'org)
2118 (defcustom org-level-color-stars-only nil
2119 "Non-nil means fontify only the stars in each headline.
2120 When nil, the entire headline is fontified.
2121 Changing it requires restart of `font-lock-mode' to become effective
2122 also in regions already fontified."
2123 :group 'org-font-lock
2124 :type 'boolean)
2126 (defcustom org-hide-leading-stars nil
2127 "Non-nil means, hide the first N-1 stars in a headline.
2128 This works by using the face `org-hide' for these stars. This
2129 face is white for a light background, and black for a dark
2130 background. You may have to customize the face `org-hide' to
2131 make this work.
2132 Changing it requires restart of `font-lock-mode' to become effective
2133 also in regions already fontified.
2134 You may also set this on a per-file basis by adding one of the following
2135 lines to the buffer:
2137 #+STARTUP: hidestars
2138 #+STARTUP: showstars"
2139 :group 'org-font-lock
2140 :type 'boolean)
2142 (defcustom org-fontify-done-headline nil
2143 "Non-nil means, change the face of a headline if it is marked DONE.
2144 Normally, only the TODO/DONE keyword indicates the state of a headline.
2145 When this is non-nil, the headline after the keyword is set to the
2146 `org-headline-done' as an additional indication."
2147 :group 'org-font-lock
2148 :type 'boolean)
2150 (defcustom org-fontify-emphasized-text t
2151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2152 Changing this variable requires a restart of Emacs to take effect."
2153 :group 'org-font-lock
2154 :type 'boolean)
2156 (defcustom org-highlight-latex-fragments-and-specials nil
2157 "Non-nil means, fontify what is treated specially by the exporters."
2158 :group 'org-font-lock
2159 :type 'boolean)
2161 (defcustom org-hide-emphasis-markers nil
2162 "Non-nil mean font-lock should hide the emphasis marker characters."
2163 :group 'org-font-lock
2164 :type 'boolean)
2166 (defvar org-emph-re nil
2167 "Regular expression for matching emphasis.")
2168 (defvar org-verbatim-re nil
2169 "Regular expression for matching verbatim text.")
2170 (defvar org-emphasis-regexp-components) ; defined just below
2171 (defvar org-emphasis-alist) ; defined just below
2172 (defun org-set-emph-re (var val)
2173 "Set variable and compute the emphasis regular expression."
2174 (set var val)
2175 (when (and (boundp 'org-emphasis-alist)
2176 (boundp 'org-emphasis-regexp-components)
2177 org-emphasis-alist org-emphasis-regexp-components)
2178 (let* ((e org-emphasis-regexp-components)
2179 (pre (car e))
2180 (post (nth 1 e))
2181 (border (nth 2 e))
2182 (body (nth 3 e))
2183 (nl (nth 4 e))
2184 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2185 (body1 (concat body "*?"))
2186 (markers (mapconcat 'car org-emphasis-alist ""))
2187 (vmarkers (mapconcat
2188 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2189 org-emphasis-alist "")))
2190 ;; make sure special characters appear at the right position in the class
2191 (if (string-match "\\^" markers)
2192 (setq markers (concat (replace-match "" t t markers) "^")))
2193 (if (string-match "-" markers)
2194 (setq markers (concat (replace-match "" t t markers) "-")))
2195 (if (string-match "\\^" vmarkers)
2196 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2197 (if (string-match "-" vmarkers)
2198 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2199 (if (> nl 0)
2200 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2201 (int-to-string nl) "\\}")))
2202 ;; Make the regexp
2203 (setq org-emph-re
2204 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2205 "\\("
2206 "\\([" markers "]\\)"
2207 "\\("
2208 "[^" border "]\\|"
2209 "[^" border (if (and nil stacked) markers) "]"
2210 body1
2211 "[^" border (if (and nil stacked) markers) "]"
2212 "\\)"
2213 "\\3\\)"
2214 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2215 (setq org-verbatim-re
2216 (concat "\\([" pre "]\\|^\\)"
2217 "\\("
2218 "\\([" vmarkers "]\\)"
2219 "\\("
2220 "[^" border "]\\|"
2221 "[^" border "]"
2222 body1
2223 "[^" border "]"
2224 "\\)"
2225 "\\3\\)"
2226 "\\([" post "]\\|$\\)")))))
2228 (defcustom org-emphasis-regexp-components
2229 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2230 "Components used to build the regular expression for emphasis.
2231 This is a list with 6 entries. Terminology: In an emphasis string
2232 like \" *strong word* \", we call the initial space PREMATCH, the final
2233 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2234 and \"trong wor\" is the body. The different components in this variable
2235 specify what is allowed/forbidden in each part:
2237 pre Chars allowed as prematch. Beginning of line will be allowed too.
2238 post Chars allowed as postmatch. End of line will be allowed too.
2239 border The chars *forbidden* as border characters.
2240 body-regexp A regexp like \".\" to match a body character. Don't use
2241 non-shy groups here, and don't allow newline here.
2242 newline The maximum number of newlines allowed in an emphasis exp.
2244 Use customize to modify this, or restart Emacs after changing it."
2245 :group 'org-font-lock
2246 :set 'org-set-emph-re
2247 :type '(list
2248 (sexp :tag "Allowed chars in pre ")
2249 (sexp :tag "Allowed chars in post ")
2250 (sexp :tag "Forbidden chars in border ")
2251 (sexp :tag "Regexp for body ")
2252 (integer :tag "number of newlines allowed")
2253 (option (boolean :tag "Please ignore this button"))))
2255 (defcustom org-emphasis-alist
2256 `(("*" bold "<b>" "</b>")
2257 ("/" italic "<i>" "</i>")
2258 ("_" underline "<u>" "</u>")
2259 ("=" org-code "<code>" "</code>" verbatim)
2260 ("~" org-verbatim "" "" verbatim)
2261 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2262 "<del>" "</del>")
2264 "Special syntax for emphasized text.
2265 Text starting and ending with a special character will be emphasized, for
2266 example *bold*, _underlined_ and /italic/. This variable sets the marker
2267 characters, the face to be used by font-lock for highlighting in Org-mode
2268 Emacs buffers, and the HTML tags to be used for this.
2269 Use customize to modify this, or restart Emacs after changing it."
2270 :group 'org-font-lock
2271 :set 'org-set-emph-re
2272 :type '(repeat
2273 (list
2274 (string :tag "Marker character")
2275 (choice
2276 (face :tag "Font-lock-face")
2277 (plist :tag "Face property list"))
2278 (string :tag "HTML start tag")
2279 (string :tag "HTML end tag")
2280 (option (const verbatim)))))
2282 ;;; Miscellaneous options
2284 (defgroup org-completion nil
2285 "Completion in Org-mode."
2286 :tag "Org Completion"
2287 :group 'org)
2289 (defcustom org-completion-fallback-command 'hippie-expand
2290 "The expansion command called by \\[org-complete] in normal context.
2291 Normal means, no org-mode-specific context."
2292 :group 'org-completion
2293 :type 'function)
2295 ;;; Functions and variables from ther packages
2296 ;; Declared here to avoid compiler warnings
2298 ;; XEmacs only
2299 (defvar outline-mode-menu-heading)
2300 (defvar outline-mode-menu-show)
2301 (defvar outline-mode-menu-hide)
2302 (defvar zmacs-regions) ; XEmacs regions
2304 ;; Emacs only
2305 (defvar mark-active)
2307 ;; Various packages
2308 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2309 (declare-function calendar-forward-day "cal-move" (arg))
2310 (declare-function calendar-goto-date "cal-move" (date))
2311 (declare-function calendar-goto-today "cal-move" ())
2312 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2313 (defvar calc-embedded-close-formula)
2314 (defvar calc-embedded-open-formula)
2315 (declare-function cdlatex-tab "ext:cdlatex" ())
2316 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2317 (defvar font-lock-unfontify-region-function)
2318 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2319 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2320 (defvar iswitchb-temp-buflist)
2321 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2322 (declare-function org-agenda-skip "org-agenda" ())
2323 (declare-function org-format-agenda-item "org-agenda"
2324 (extra txt &optional category tags dotime noprefix remove-re))
2325 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2326 (declare-function org-agenda-change-all-lines "org-agenda"
2327 (newhead hdmarker &optional fixface))
2328 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2329 (declare-function org-agenda-maybe-redo "org-agenda" ())
2330 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2331 (beg end))
2332 (declare-function parse-time-string "parse-time" (string))
2333 (declare-function remember "remember" (&optional initial))
2334 (declare-function remember-buffer-desc "remember" ())
2335 (declare-function remember-finalize "remember" ())
2336 (defvar remember-save-after-remembering)
2337 (defvar remember-data-file)
2338 (defvar remember-register)
2339 (defvar remember-buffer)
2340 (defvar remember-handler-functions)
2341 (defvar remember-annotation-functions)
2342 (defvar texmathp-why)
2343 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2344 (declare-function table--at-cell-p "table" (position &optional object at-column))
2346 (defvar w3m-current-url)
2347 (defvar w3m-current-title)
2349 (defvar org-latex-regexps)
2351 ;;; Autoload and prepare some org modules
2353 ;; Some table stuff that needs to be defined here, because it is used
2354 ;; by the functions setting up org-mode or checking for table context.
2356 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2357 "Detects an org-type or table-type table.")
2358 (defconst org-table-line-regexp "^[ \t]*|"
2359 "Detects an org-type table line.")
2360 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2361 "Detects an org-type table line.")
2362 (defconst org-table-hline-regexp "^[ \t]*|-"
2363 "Detects an org-type table hline.")
2364 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2365 "Detects a table-type table hline.")
2366 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2367 "Searching from within a table (any type) this finds the first line
2368 outside the table.")
2370 ;; Autoload the functions in org-table.el that are needed by functions here.
2372 (eval-and-compile
2373 (org-autoload "org-table"
2374 '(org-table-align org-table-begin org-table-blank-field
2375 org-table-convert org-table-convert-region org-table-copy-down
2376 org-table-copy-region org-table-create
2377 org-table-create-or-convert-from-region
2378 org-table-create-with-table.el org-table-current-dline
2379 org-table-cut-region org-table-delete-column org-table-edit-field
2380 org-table-edit-formulas org-table-end org-table-eval-formula
2381 org-table-export org-table-field-info
2382 org-table-get-stored-formulas org-table-goto-column
2383 org-table-hline-and-move org-table-import org-table-insert-column
2384 org-table-insert-hline org-table-insert-row org-table-iterate
2385 org-table-justify-field-maybe org-table-kill-row
2386 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2387 org-table-move-column org-table-move-column-left
2388 org-table-move-column-right org-table-move-row
2389 org-table-move-row-down org-table-move-row-up
2390 org-table-next-field org-table-next-row org-table-paste-rectangle
2391 org-table-previous-field org-table-recalculate
2392 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2393 org-table-toggle-coordinate-overlays
2394 org-table-toggle-formula-debugger org-table-wrap-region
2395 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2397 (defun org-at-table-p (&optional table-type)
2398 "Return t if the cursor is inside an org-type table.
2399 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2400 (if org-enable-table-editor
2401 (save-excursion
2402 (beginning-of-line 1)
2403 (looking-at (if table-type org-table-any-line-regexp
2404 org-table-line-regexp)))
2405 nil))
2406 (defsubst org-table-p () (org-at-table-p))
2408 (defun org-at-table.el-p ()
2409 "Return t if and only if we are at a table.el table."
2410 (and (org-at-table-p 'any)
2411 (save-excursion
2412 (goto-char (org-table-begin 'any))
2413 (looking-at org-table1-hline-regexp))))
2414 (defun org-table-recognize-table.el ()
2415 "If there is a table.el table nearby, recognize it and move into it."
2416 (if org-table-tab-recognizes-table.el
2417 (if (org-at-table.el-p)
2418 (progn
2419 (beginning-of-line 1)
2420 (if (looking-at org-table-dataline-regexp)
2422 (if (looking-at org-table1-hline-regexp)
2423 (progn
2424 (beginning-of-line 2)
2425 (if (looking-at org-table-any-border-regexp)
2426 (beginning-of-line -1)))))
2427 (if (re-search-forward "|" (org-table-end t) t)
2428 (progn
2429 (require 'table)
2430 (if (table--at-cell-p (point))
2432 (message "recognizing table.el table...")
2433 (table-recognize-table)
2434 (message "recognizing table.el table...done")))
2435 (error "This should not happen..."))
2437 nil)
2438 nil))
2440 (defun org-at-table-hline-p ()
2441 "Return t if the cursor is inside a hline in a table."
2442 (if org-enable-table-editor
2443 (save-excursion
2444 (beginning-of-line 1)
2445 (looking-at org-table-hline-regexp))
2446 nil))
2448 (defvar org-table-clean-did-remove-column nil)
2450 (defun org-table-map-tables (function)
2451 "Apply FUNCTION to the start of all tables in the buffer."
2452 (save-excursion
2453 (save-restriction
2454 (widen)
2455 (goto-char (point-min))
2456 (while (re-search-forward org-table-any-line-regexp nil t)
2457 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2458 (beginning-of-line 1)
2459 (if (looking-at org-table-line-regexp)
2460 (save-excursion (funcall function)))
2461 (re-search-forward org-table-any-border-regexp nil 1))))
2462 (message "Mapping tables: done"))
2464 ;; Declare and autoload functions from org-exp.el
2466 (declare-function org-default-export-plist "org-exp")
2467 (declare-function org-infile-export-plist "org-exp")
2468 (declare-function org-get-current-options "org-exp")
2469 (eval-and-compile
2470 (org-autoload "org-exp"
2471 '(org-export org-export-as-ascii org-export-visible
2472 org-insert-export-options-template org-export-as-html-and-open
2473 org-export-as-html-batch org-export-as-html-to-buffer
2474 org-replace-region-by-html org-export-region-as-html
2475 org-export-as-html org-export-icalendar-this-file
2476 org-export-icalendar-all-agenda-files
2477 org-table-clean-before-export
2478 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2480 ;; Declare and autoload functions from org-agenda.el
2482 (eval-and-compile
2483 (org-autoload "org-agenda"
2484 '(org-agenda org-agenda-list org-search-view
2485 org-todo-list org-tags-view org-agenda-list-stuck-projects
2486 org-diary org-agenda-to-appt)))
2488 ;; Autoload org-remember
2490 (eval-and-compile
2491 (org-autoload "org-remember"
2492 '(org-remember-insinuate org-remember-annotation
2493 org-remember-apply-template org-remember org-remember-handler)))
2495 ;; Autoload org-clock.el
2498 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2499 (beg end))
2500 (declare-function org-update-mode-line "org-clock" ())
2501 (defvar org-clock-start-time)
2502 (defvar org-clock-marker (make-marker)
2503 "Marker recording the last clock-in.")
2505 (eval-and-compile
2506 (org-autoload
2507 "org-clock"
2508 '(org-clock-in org-clock-out org-clock-cancel
2509 org-clock-goto org-clock-sum org-clock-display
2510 org-remove-clock-overlays org-clock-report
2511 org-clocktable-shift org-dblock-write:clocktable
2512 org-get-clocktable)))
2514 (defun org-clock-update-time-maybe ()
2515 "If this is a CLOCK line, update it and return t.
2516 Otherwise, return nil."
2517 (interactive)
2518 (save-excursion
2519 (beginning-of-line 1)
2520 (skip-chars-forward " \t")
2521 (when (looking-at org-clock-string)
2522 (let ((re (concat "[ \t]*" org-clock-string
2523 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2524 "\\([ \t]*=>.*\\)?\\)?"))
2525 ts te h m s)
2526 (cond
2527 ((not (looking-at re))
2528 nil)
2529 ((not (match-end 2))
2530 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2531 (> org-clock-marker (point))
2532 (<= org-clock-marker (point-at-eol)))
2533 ;; The clock is running here
2534 (setq org-clock-start-time
2535 (apply 'encode-time
2536 (org-parse-time-string (match-string 1))))
2537 (org-update-mode-line)))
2539 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2540 (end-of-line 1)
2541 (setq ts (match-string 1)
2542 te (match-string 3))
2543 (setq s (- (time-to-seconds
2544 (apply 'encode-time (org-parse-time-string te)))
2545 (time-to-seconds
2546 (apply 'encode-time (org-parse-time-string ts))))
2547 h (floor (/ s 3600))
2548 s (- s (* 3600 h))
2549 m (floor (/ s 60))
2550 s (- s (* 60 s)))
2551 (insert " => " (format "%2d:%02d" h m))
2552 t))))))
2554 (defun org-check-running-clock ()
2555 "Check if the current buffer contains the running clock.
2556 If yes, offer to stop it and to save the buffer with the changes."
2557 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2558 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2559 (buffer-name))))
2560 (org-clock-out)
2561 (when (y-or-n-p "Save changed buffer?")
2562 (save-buffer))))
2564 (defun org-clocktable-try-shift (dir n)
2565 "Check if this line starts a clock table, if yes, shift the time block."
2566 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2567 (org-clocktable-shift dir n)))
2569 ;; Autoload archiving code
2570 ;; The stuff that is needed for cycling and tags has to be defined here.
2572 (defgroup org-archive nil
2573 "Options concerning archiving in Org-mode."
2574 :tag "Org Archive"
2575 :group 'org-structure)
2577 (defcustom org-archive-location "%s_archive::"
2578 "The location where subtrees should be archived.
2580 Otherwise, the value of this variable is a string, consisting of two
2581 parts, separated by a double-colon.
2583 The first part is a file name - when omitted, archiving happens in the same
2584 file. %s will be replaced by the current file name (without directory part).
2585 Archiving to a different file is useful to keep archived entries from
2586 contributing to the Org-mode Agenda.
2588 The part after the double colon is a headline. The archived entries will be
2589 filed under that headline. When omitted, the subtrees are simply filed away
2590 at the end of the file, as top-level entries.
2592 Here are a few examples:
2593 \"%s_archive::\"
2594 If the current file is Projects.org, archive in file
2595 Projects.org_archive, as top-level trees. This is the default.
2597 \"::* Archived Tasks\"
2598 Archive in the current file, under the top-level headline
2599 \"* Archived Tasks\".
2601 \"~/org/archive.org::\"
2602 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2604 \"basement::** Finished Tasks\"
2605 Archive in file ./basement (relative path), as level 3 trees
2606 below the level 2 heading \"** Finished Tasks\".
2608 You may set this option on a per-file basis by adding to the buffer a
2609 line like
2611 #+ARCHIVE: basement::** Finished Tasks
2613 You may also define it locally for a subtree by setting an ARCHIVE property
2614 in the entry. If such a property is found in an entry, or anywhere up
2615 the hierarchy, it will be used."
2616 :group 'org-archive
2617 :type 'string)
2619 (defcustom org-archive-tag "ARCHIVE"
2620 "The tag that marks a subtree as archived.
2621 An archived subtree does not open during visibility cycling, and does
2622 not contribute to the agenda listings.
2623 After changing this, font-lock must be restarted in the relevant buffers to
2624 get the proper fontification."
2625 :group 'org-archive
2626 :group 'org-keywords
2627 :type 'string)
2629 (defcustom org-agenda-skip-archived-trees t
2630 "Non-nil means, the agenda will skip any items located in archived trees.
2631 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2632 variable is no longer recommended, you should leave it at the value t.
2633 Instead, use the key `v' to cycle the archives-mode in the agenda."
2634 :group 'org-archive
2635 :group 'org-agenda-skip
2636 :type 'boolean)
2638 (defcustom org-cycle-open-archived-trees nil
2639 "Non-nil means, `org-cycle' will open archived trees.
2640 An archived tree is a tree marked with the tag ARCHIVE.
2641 When nil, archived trees will stay folded. You can still open them with
2642 normal outline commands like `show-all', but not with the cycling commands."
2643 :group 'org-archive
2644 :group 'org-cycle
2645 :type 'boolean)
2647 (defcustom org-sparse-tree-open-archived-trees nil
2648 "Non-nil means sparse tree construction shows matches in archived trees.
2649 When nil, matches in these trees are highlighted, but the trees are kept in
2650 collapsed state."
2651 :group 'org-archive
2652 :group 'org-sparse-trees
2653 :type 'boolean)
2655 (defun org-cycle-hide-archived-subtrees (state)
2656 "Re-hide all archived subtrees after a visibility state change."
2657 (when (and (not org-cycle-open-archived-trees)
2658 (not (memq state '(overview folded))))
2659 (save-excursion
2660 (let* ((globalp (memq state '(contents all)))
2661 (beg (if globalp (point-min) (point)))
2662 (end (if globalp (point-max) (org-end-of-subtree t))))
2663 (org-hide-archived-subtrees beg end)
2664 (goto-char beg)
2665 (if (looking-at (concat ".*:" org-archive-tag ":"))
2666 (message "%s" (substitute-command-keys
2667 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2669 (defun org-force-cycle-archived ()
2670 "Cycle subtree even if it is archived."
2671 (interactive)
2672 (setq this-command 'org-cycle)
2673 (let ((org-cycle-open-archived-trees t))
2674 (call-interactively 'org-cycle)))
2676 (defun org-hide-archived-subtrees (beg end)
2677 "Re-hide all archived subtrees after a visibility state change."
2678 (save-excursion
2679 (let* ((re (concat ":" org-archive-tag ":")))
2680 (goto-char beg)
2681 (while (re-search-forward re end t)
2682 (and (org-on-heading-p) (hide-subtree))
2683 (org-end-of-subtree t)))))
2685 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2687 (eval-and-compile
2688 (org-autoload "org-archive"
2689 '(org-add-archive-files org-archive-subtree
2690 org-archive-to-archive-sibling org-toggle-archive-tag)))
2692 ;; Autoload Column View Code
2694 (declare-function org-columns-number-to-string "org-colview")
2695 (declare-function org-columns-get-format-and-top-level "org-colview")
2696 (declare-function org-columns-compute "org-colview")
2698 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2699 '(org-columns-number-to-string org-columns-get-format-and-top-level
2700 org-columns-compute org-agenda-columns org-columns-remove-overlays
2701 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2703 ;; Autoload ID code
2705 (org-autoload "org-id"
2706 '(org-id-get-create org-id-new org-id-copy org-id-get
2707 org-id-get-with-outline-path-completion
2708 org-id-get-with-outline-drilling
2709 org-id-goto org-id-find))
2711 ;;; Variables for pre-computed regular expressions, all buffer local
2713 (defvar org-drawer-regexp nil
2714 "Matches first line of a hidden block.")
2715 (make-variable-buffer-local 'org-drawer-regexp)
2716 (defvar org-todo-regexp nil
2717 "Matches any of the TODO state keywords.")
2718 (make-variable-buffer-local 'org-todo-regexp)
2719 (defvar org-not-done-regexp nil
2720 "Matches any of the TODO state keywords except the last one.")
2721 (make-variable-buffer-local 'org-not-done-regexp)
2722 (defvar org-todo-line-regexp nil
2723 "Matches a headline and puts TODO state into group 2 if present.")
2724 (make-variable-buffer-local 'org-todo-line-regexp)
2725 (defvar org-complex-heading-regexp nil
2726 "Matches a headline and puts everything into groups:
2727 group 1: the stars
2728 group 2: The todo keyword, maybe
2729 group 3: Priority cookie
2730 group 4: True headline
2731 group 5: Tags")
2732 (make-variable-buffer-local 'org-complex-heading-regexp)
2733 (defvar org-todo-line-tags-regexp nil
2734 "Matches a headline and puts TODO state into group 2 if present.
2735 Also put tags into group 4 if tags are present.")
2736 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2737 (defvar org-nl-done-regexp nil
2738 "Matches newline followed by a headline with the DONE keyword.")
2739 (make-variable-buffer-local 'org-nl-done-regexp)
2740 (defvar org-looking-at-done-regexp nil
2741 "Matches the DONE keyword a point.")
2742 (make-variable-buffer-local 'org-looking-at-done-regexp)
2743 (defvar org-ds-keyword-length 12
2744 "Maximum length of the Deadline and SCHEDULED keywords.")
2745 (make-variable-buffer-local 'org-ds-keyword-length)
2746 (defvar org-deadline-regexp nil
2747 "Matches the DEADLINE keyword.")
2748 (make-variable-buffer-local 'org-deadline-regexp)
2749 (defvar org-deadline-time-regexp nil
2750 "Matches the DEADLINE keyword together with a time stamp.")
2751 (make-variable-buffer-local 'org-deadline-time-regexp)
2752 (defvar org-deadline-line-regexp nil
2753 "Matches the DEADLINE keyword and the rest of the line.")
2754 (make-variable-buffer-local 'org-deadline-line-regexp)
2755 (defvar org-scheduled-regexp nil
2756 "Matches the SCHEDULED keyword.")
2757 (make-variable-buffer-local 'org-scheduled-regexp)
2758 (defvar org-scheduled-time-regexp nil
2759 "Matches the SCHEDULED keyword together with a time stamp.")
2760 (make-variable-buffer-local 'org-scheduled-time-regexp)
2761 (defvar org-closed-time-regexp nil
2762 "Matches the CLOSED keyword together with a time stamp.")
2763 (make-variable-buffer-local 'org-closed-time-regexp)
2765 (defvar org-keyword-time-regexp nil
2766 "Matches any of the 4 keywords, together with the time stamp.")
2767 (make-variable-buffer-local 'org-keyword-time-regexp)
2768 (defvar org-keyword-time-not-clock-regexp nil
2769 "Matches any of the 3 keywords, together with the time stamp.")
2770 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2771 (defvar org-maybe-keyword-time-regexp nil
2772 "Matches a timestamp, possibly preceeded by a keyword.")
2773 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2774 (defvar org-planning-or-clock-line-re nil
2775 "Matches a line with planning or clock info.")
2776 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2778 (defconst org-plain-time-of-day-regexp
2779 (concat
2780 "\\(\\<[012]?[0-9]"
2781 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2782 "\\(--?"
2783 "\\(\\<[012]?[0-9]"
2784 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2785 "\\)?")
2786 "Regular expression to match a plain time or time range.
2787 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2788 groups carry important information:
2789 0 the full match
2790 1 the first time, range or not
2791 8 the second time, if it is a range.")
2793 (defconst org-plain-time-extension-regexp
2794 (concat
2795 "\\(\\<[012]?[0-9]"
2796 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2797 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2798 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2799 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2800 groups carry important information:
2801 0 the full match
2802 7 hours of duration
2803 9 minutes of duration")
2805 (defconst org-stamp-time-of-day-regexp
2806 (concat
2807 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2808 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2809 "\\(--?"
2810 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2811 "Regular expression to match a timestamp time or time range.
2812 After a match, the following groups carry important information:
2813 0 the full match
2814 1 date plus weekday, for backreferencing to make sure both times on same day
2815 2 the first time, range or not
2816 4 the second time, if it is a range.")
2818 (defconst org-startup-options
2819 '(("fold" org-startup-folded t)
2820 ("overview" org-startup-folded t)
2821 ("nofold" org-startup-folded nil)
2822 ("showall" org-startup-folded nil)
2823 ("content" org-startup-folded content)
2824 ("hidestars" org-hide-leading-stars t)
2825 ("showstars" org-hide-leading-stars nil)
2826 ("odd" org-odd-levels-only t)
2827 ("oddeven" org-odd-levels-only nil)
2828 ("align" org-startup-align-all-tables t)
2829 ("noalign" org-startup-align-all-tables nil)
2830 ("customtime" org-display-custom-times t)
2831 ("logdone" org-log-done time)
2832 ("lognotedone" org-log-done note)
2833 ("nologdone" org-log-done nil)
2834 ("lognoteclock-out" org-log-note-clock-out t)
2835 ("nolognoteclock-out" org-log-note-clock-out nil)
2836 ("logrepeat" org-log-repeat state)
2837 ("lognoterepeat" org-log-repeat note)
2838 ("nologrepeat" org-log-repeat nil)
2839 ("constcgs" constants-unit-system cgs)
2840 ("constSI" constants-unit-system SI))
2841 "Variable associated with STARTUP options for org-mode.
2842 Each element is a list of three items: The startup options as written
2843 in the #+STARTUP line, the corresponding variable, and the value to
2844 set this variable to if the option is found. An optional forth element PUSH
2845 means to push this value onto the list in the variable.")
2847 (defun org-set-regexps-and-options ()
2848 "Precompute regular expressions for current buffer."
2849 (when (org-mode-p)
2850 (org-set-local 'org-todo-kwd-alist nil)
2851 (org-set-local 'org-todo-key-alist nil)
2852 (org-set-local 'org-todo-key-trigger nil)
2853 (org-set-local 'org-todo-keywords-1 nil)
2854 (org-set-local 'org-done-keywords nil)
2855 (org-set-local 'org-todo-heads nil)
2856 (org-set-local 'org-todo-sets nil)
2857 (org-set-local 'org-todo-log-states nil)
2858 (org-set-local 'org-file-properties nil)
2859 (org-set-local 'org-file-tags nil)
2860 (let ((re (org-make-options-regexp
2861 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2862 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2863 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2864 (splitre "[ \t]+")
2865 kwds kws0 kwsa key log value cat arch tags const links hw dws
2866 tail sep kws1 prio props ftags drawers
2867 ext-setup-or-nil setup-contents (start 0))
2868 (save-excursion
2869 (save-restriction
2870 (widen)
2871 (goto-char (point-min))
2872 (while (or (and ext-setup-or-nil
2873 (string-match re ext-setup-or-nil start)
2874 (setq start (match-end 0)))
2875 (and (setq ext-setup-or-nil nil start 0)
2876 (re-search-forward re nil t)))
2877 (setq key (upcase (match-string 1 ext-setup-or-nil))
2878 value (org-match-string-no-properties 2 ext-setup-or-nil))
2879 (cond
2880 ((equal key "CATEGORY")
2881 (if (string-match "[ \t]+$" value)
2882 (setq value (replace-match "" t t value)))
2883 (setq cat value))
2884 ((member key '("SEQ_TODO" "TODO"))
2885 (push (cons 'sequence (org-split-string value splitre)) kwds))
2886 ((equal key "TYP_TODO")
2887 (push (cons 'type (org-split-string value splitre)) kwds))
2888 ((equal key "TAGS")
2889 (setq tags (append tags (org-split-string value splitre))))
2890 ((equal key "COLUMNS")
2891 (org-set-local 'org-columns-default-format value))
2892 ((equal key "LINK")
2893 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2894 (push (cons (match-string 1 value)
2895 (org-trim (match-string 2 value)))
2896 links)))
2897 ((equal key "PRIORITIES")
2898 (setq prio (org-split-string value " +")))
2899 ((equal key "PROPERTY")
2900 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2901 (push (cons (match-string 1 value) (match-string 2 value))
2902 props)))
2903 ((equal key "FILETAGS")
2904 (when (string-match "\\S-" value)
2905 (setq ftags
2906 (append
2907 ftags
2908 (apply 'append
2909 (mapcar (lambda (x) (org-split-string x ":"))
2910 (org-split-string value)))))))
2911 ((equal key "DRAWERS")
2912 (setq drawers (org-split-string value splitre)))
2913 ((equal key "CONSTANTS")
2914 (setq const (append const (org-split-string value splitre))))
2915 ((equal key "STARTUP")
2916 (let ((opts (org-split-string value splitre))
2917 l var val)
2918 (while (setq l (pop opts))
2919 (when (setq l (assoc l org-startup-options))
2920 (setq var (nth 1 l) val (nth 2 l))
2921 (if (not (nth 3 l))
2922 (set (make-local-variable var) val)
2923 (if (not (listp (symbol-value var)))
2924 (set (make-local-variable var) nil))
2925 (set (make-local-variable var) (symbol-value var))
2926 (add-to-list var val))))))
2927 ((equal key "ARCHIVE")
2928 (string-match " *$" value)
2929 (setq arch (replace-match "" t t value))
2930 (remove-text-properties 0 (length arch)
2931 '(face t fontified t) arch))
2932 ((equal key "SETUPFILE")
2933 (setq setup-contents (org-file-contents
2934 (expand-file-name
2935 (org-remove-double-quotes value))
2936 'noerror))
2937 (if (not ext-setup-or-nil)
2938 (setq ext-setup-or-nil setup-contents start 0)
2939 (setq ext-setup-or-nil
2940 (concat (substring ext-setup-or-nil 0 start)
2941 "\n" setup-contents "\n"
2942 (substring ext-setup-or-nil start)))))
2943 ))))
2944 (when cat
2945 (org-set-local 'org-category (intern cat))
2946 (push (cons "CATEGORY" cat) props))
2947 (when prio
2948 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2949 (setq prio (mapcar 'string-to-char prio))
2950 (org-set-local 'org-highest-priority (nth 0 prio))
2951 (org-set-local 'org-lowest-priority (nth 1 prio))
2952 (org-set-local 'org-default-priority (nth 2 prio)))
2953 (and props (org-set-local 'org-file-properties (nreverse props)))
2954 (and ftags (org-set-local 'org-file-tags ftags))
2955 (and drawers (org-set-local 'org-drawers drawers))
2956 (and arch (org-set-local 'org-archive-location arch))
2957 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2958 ;; Process the TODO keywords
2959 (unless kwds
2960 ;; Use the global values as if they had been given locally.
2961 (setq kwds (default-value 'org-todo-keywords))
2962 (if (stringp (car kwds))
2963 (setq kwds (list (cons org-todo-interpretation
2964 (default-value 'org-todo-keywords)))))
2965 (setq kwds (reverse kwds)))
2966 (setq kwds (nreverse kwds))
2967 (let (inter kws kw)
2968 (while (setq kws (pop kwds))
2969 (setq inter (pop kws) sep (member "|" kws)
2970 kws0 (delete "|" (copy-sequence kws))
2971 kwsa nil
2972 kws1 (mapcar
2973 (lambda (x)
2974 ;; 1 2
2975 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2976 (progn
2977 (setq kw (match-string 1 x)
2978 key (and (match-end 2) (match-string 2 x))
2979 log (org-extract-log-state-settings x))
2980 (push (cons kw (and key (string-to-char key))) kwsa)
2981 (and log (push log org-todo-log-states))
2983 (error "Invalid TODO keyword %s" x)))
2984 kws0)
2985 kwsa (if kwsa (append '((:startgroup))
2986 (nreverse kwsa)
2987 '((:endgroup))))
2988 hw (car kws1)
2989 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2990 tail (list inter hw (car dws) (org-last dws)))
2991 (add-to-list 'org-todo-heads hw 'append)
2992 (push kws1 org-todo-sets)
2993 (setq org-done-keywords (append org-done-keywords dws nil))
2994 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2995 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2996 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2997 (setq org-todo-sets (nreverse org-todo-sets)
2998 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2999 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3000 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3001 ;; Process the constants
3002 (when const
3003 (let (e cst)
3004 (while (setq e (pop const))
3005 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3006 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3007 (setq org-table-formula-constants-local cst)))
3009 ;; Process the tags.
3010 (when tags
3011 (let (e tgs)
3012 (while (setq e (pop tags))
3013 (cond
3014 ((equal e "{") (push '(:startgroup) tgs))
3015 ((equal e "}") (push '(:endgroup) tgs))
3016 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3017 (push (cons (match-string 1 e)
3018 (string-to-char (match-string 2 e)))
3019 tgs))
3020 (t (push (list e) tgs))))
3021 (org-set-local 'org-tag-alist nil)
3022 (while (setq e (pop tgs))
3023 (or (and (stringp (car e))
3024 (assoc (car e) org-tag-alist))
3025 (push e org-tag-alist)))))
3027 ;; Compute the regular expressions and other local variables
3028 (if (not org-done-keywords)
3029 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3030 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3031 (length org-scheduled-string)
3032 (length org-clock-string)
3033 (length org-closed-string)))
3034 org-drawer-regexp
3035 (concat "^[ \t]*:\\("
3036 (mapconcat 'regexp-quote org-drawers "\\|")
3037 "\\):[ \t]*$")
3038 org-not-done-keywords
3039 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3040 org-todo-regexp
3041 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3042 "\\|") "\\)\\>")
3043 org-not-done-regexp
3044 (concat "\\<\\("
3045 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3046 "\\)\\>")
3047 org-todo-line-regexp
3048 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3049 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3050 "\\)\\>\\)?[ \t]*\\(.*\\)")
3051 org-complex-heading-regexp
3052 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3053 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3054 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3055 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3056 org-nl-done-regexp
3057 (concat "\n\\*+[ \t]+"
3058 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3059 "\\)" "\\>")
3060 org-todo-line-tags-regexp
3061 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3062 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3063 (org-re
3064 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3065 org-looking-at-done-regexp
3066 (concat "^" "\\(?:"
3067 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3068 "\\>")
3069 org-deadline-regexp (concat "\\<" org-deadline-string)
3070 org-deadline-time-regexp
3071 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3072 org-deadline-line-regexp
3073 (concat "\\<\\(" org-deadline-string "\\).*")
3074 org-scheduled-regexp
3075 (concat "\\<" org-scheduled-string)
3076 org-scheduled-time-regexp
3077 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3078 org-closed-time-regexp
3079 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3080 org-keyword-time-regexp
3081 (concat "\\<\\(" org-scheduled-string
3082 "\\|" org-deadline-string
3083 "\\|" org-closed-string
3084 "\\|" org-clock-string "\\)"
3085 " *[[<]\\([^]>]+\\)[]>]")
3086 org-keyword-time-not-clock-regexp
3087 (concat "\\<\\(" org-scheduled-string
3088 "\\|" org-deadline-string
3089 "\\|" org-closed-string
3090 "\\)"
3091 " *[[<]\\([^]>]+\\)[]>]")
3092 org-maybe-keyword-time-regexp
3093 (concat "\\(\\<\\(" org-scheduled-string
3094 "\\|" org-deadline-string
3095 "\\|" org-closed-string
3096 "\\|" org-clock-string "\\)\\)?"
3097 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3098 org-planning-or-clock-line-re
3099 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3100 "\\|" org-deadline-string
3101 "\\|" org-closed-string "\\|" org-clock-string
3102 "\\)\\>\\)")
3104 (org-compute-latex-and-specials-regexp)
3105 (org-set-font-lock-defaults))))
3107 (defun org-file-contents (file &optional noerror)
3108 "Return the contents of FILE, as a string."
3109 (if (or (not file)
3110 (not (file-readable-p file)))
3111 (if noerror
3112 (progn
3113 (message "Cannot read file %s" file)
3114 (ding) (sit-for 2)
3116 (error "Cannot read file %s" file))
3117 (with-temp-buffer
3118 (insert-file-contents file)
3119 (buffer-string))))
3121 (defun org-extract-log-state-settings (x)
3122 "Extract the log state setting from a TODO keyword string.
3123 This will extract info from a string like \"WAIT(w@/!)\"."
3124 (let (kw key log1 log2)
3125 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3126 (setq kw (match-string 1 x)
3127 key (and (match-end 2) (match-string 2 x))
3128 log1 (and (match-end 3) (match-string 3 x))
3129 log2 (and (match-end 4) (match-string 4 x)))
3130 (and (or log1 log2)
3131 (list kw
3132 (and log1 (if (equal log1 "!") 'time 'note))
3133 (and log2 (if (equal log2 "!") 'time 'note)))))))
3135 (defun org-remove-keyword-keys (list)
3136 "Remove a pair of parenthesis at the end of each string in LIST."
3137 (mapcar (lambda (x)
3138 (if (string-match "(.*)$" x)
3139 (substring x 0 (match-beginning 0))
3141 list))
3143 ;; FIXME: this could be done much better, using second characters etc.
3144 (defun org-assign-fast-keys (alist)
3145 "Assign fast keys to a keyword-key alist.
3146 Respect keys that are already there."
3147 (let (new e k c c1 c2 (char ?a))
3148 (while (setq e (pop alist))
3149 (cond
3150 ((equal e '(:startgroup)) (push e new))
3151 ((equal e '(:endgroup)) (push e new))
3153 (setq k (car e) c2 nil)
3154 (if (cdr e)
3155 (setq c (cdr e))
3156 ;; automatically assign a character.
3157 (setq c1 (string-to-char
3158 (downcase (substring
3159 k (if (= (string-to-char k) ?@) 1 0)))))
3160 (if (or (rassoc c1 new) (rassoc c1 alist))
3161 (while (or (rassoc char new) (rassoc char alist))
3162 (setq char (1+ char)))
3163 (setq c2 c1))
3164 (setq c (or c2 char)))
3165 (push (cons k c) new))))
3166 (nreverse new)))
3168 ;;; Some variables used in various places
3170 (defvar org-window-configuration nil
3171 "Used in various places to store a window configuration.")
3172 (defvar org-finish-function nil
3173 "Function to be called when `C-c C-c' is used.
3174 This is for getting out of special buffers like remember.")
3177 ;; FIXME: Occasionally check by commenting these, to make sure
3178 ;; no other functions uses these, forgetting to let-bind them.
3179 (defvar entry)
3180 (defvar state)
3181 (defvar last-state)
3182 (defvar date)
3183 (defvar description)
3185 ;; Defined somewhere in this file, but used before definition.
3186 (defvar org-html-entities)
3187 (defvar org-struct-menu)
3188 (defvar org-org-menu)
3189 (defvar org-tbl-menu)
3190 (defvar org-agenda-keymap)
3192 ;;;; Define the Org-mode
3194 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3195 (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."))
3198 ;; We use a before-change function to check if a table might need
3199 ;; an update.
3200 (defvar org-table-may-need-update t
3201 "Indicates that a table might need an update.
3202 This variable is set by `org-before-change-function'.
3203 `org-table-align' sets it back to nil.")
3204 (defun org-before-change-function (beg end)
3205 "Every change indicates that a table might need an update."
3206 (setq org-table-may-need-update t))
3207 (defvar org-mode-map)
3208 (defvar org-mode-hook nil)
3209 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3210 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3211 (defvar org-table-buffer-is-an nil)
3212 (defconst org-outline-regexp "\\*+ ")
3214 ;;;###autoload
3215 (define-derived-mode org-mode outline-mode "Org"
3216 "Outline-based notes management and organizer, alias
3217 \"Carsten's outline-mode for keeping track of everything.\"
3219 Org-mode develops organizational tasks around a NOTES file which
3220 contains information about projects as plain text. Org-mode is
3221 implemented on top of outline-mode, which is ideal to keep the content
3222 of large files well structured. It supports ToDo items, deadlines and
3223 time stamps, which magically appear in the diary listing of the Emacs
3224 calendar. Tables are easily created with a built-in table editor.
3225 Plain text URL-like links connect to websites, emails (VM), Usenet
3226 messages (Gnus), BBDB entries, and any files related to the project.
3227 For printing and sharing of notes, an Org-mode file (or a part of it)
3228 can be exported as a structured ASCII or HTML file.
3230 The following commands are available:
3232 \\{org-mode-map}"
3234 ;; Get rid of Outline menus, they are not needed
3235 ;; Need to do this here because define-derived-mode sets up
3236 ;; the keymap so late. Still, it is a waste to call this each time
3237 ;; we switch another buffer into org-mode.
3238 (if (featurep 'xemacs)
3239 (when (boundp 'outline-mode-menu-heading)
3240 ;; Assume this is Greg's port, it used easymenu
3241 (easy-menu-remove outline-mode-menu-heading)
3242 (easy-menu-remove outline-mode-menu-show)
3243 (easy-menu-remove outline-mode-menu-hide))
3244 (define-key org-mode-map [menu-bar headings] 'undefined)
3245 (define-key org-mode-map [menu-bar hide] 'undefined)
3246 (define-key org-mode-map [menu-bar show] 'undefined))
3248 (org-load-modules-maybe)
3249 (easy-menu-add org-org-menu)
3250 (easy-menu-add org-tbl-menu)
3251 (org-install-agenda-files-menu)
3252 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3253 (org-add-to-invisibility-spec '(org-cwidth))
3254 (when (featurep 'xemacs)
3255 (org-set-local 'line-move-ignore-invisible t))
3256 (org-set-local 'outline-regexp org-outline-regexp)
3257 (org-set-local 'outline-level 'org-outline-level)
3258 (when (and org-ellipsis
3259 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3260 (fboundp 'make-glyph-code))
3261 (unless org-display-table
3262 (setq org-display-table (make-display-table)))
3263 (set-display-table-slot
3264 org-display-table 4
3265 (vconcat (mapcar
3266 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3267 org-ellipsis)))
3268 (if (stringp org-ellipsis) org-ellipsis "..."))))
3269 (setq buffer-display-table org-display-table))
3270 (org-set-regexps-and-options)
3271 ;; Calc embedded
3272 (org-set-local 'calc-embedded-open-mode "# ")
3273 (modify-syntax-entry ?# "<")
3274 (modify-syntax-entry ?@ "w")
3275 (if org-startup-truncated (setq truncate-lines t))
3276 (org-set-local 'font-lock-unfontify-region-function
3277 'org-unfontify-region)
3278 ;; Activate before-change-function
3279 (org-set-local 'org-table-may-need-update t)
3280 (org-add-hook 'before-change-functions 'org-before-change-function nil
3281 'local)
3282 ;; Check for running clock before killing a buffer
3283 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3284 ;; Paragraphs and auto-filling
3285 (org-set-autofill-regexps)
3286 (setq indent-line-function 'org-indent-line-function)
3287 (org-update-radio-target-regexp)
3289 ;; Comment characters
3290 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3291 (org-set-local 'comment-padding " ")
3293 ;; Align options lines
3294 (org-set-local
3295 'align-mode-rules-list
3296 '((org-in-buffer-settings
3297 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3298 (modes . '(org-mode)))))
3300 ;; Imenu
3301 (org-set-local 'imenu-create-index-function
3302 'org-imenu-get-tree)
3304 ;; Make isearch reveal context
3305 (if (or (featurep 'xemacs)
3306 (not (boundp 'outline-isearch-open-invisible-function)))
3307 ;; Emacs 21 and XEmacs make use of the hook
3308 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3309 ;; Emacs 22 deals with this through a special variable
3310 (org-set-local 'outline-isearch-open-invisible-function
3311 (lambda (&rest ignore) (org-show-context 'isearch))))
3313 ;; If empty file that did not turn on org-mode automatically, make it to.
3314 (if (and org-insert-mode-line-in-empty-file
3315 (interactive-p)
3316 (= (point-min) (point-max)))
3317 (insert "# -*- mode: org -*-\n\n"))
3319 (unless org-inhibit-startup
3320 (when org-startup-align-all-tables
3321 (let ((bmp (buffer-modified-p)))
3322 (org-table-map-tables 'org-table-align)
3323 (set-buffer-modified-p bmp)))
3324 (org-set-startup-visibility)))
3326 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3328 (defun org-current-time ()
3329 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3330 (if (> (car org-time-stamp-rounding-minutes) 1)
3331 (let ((r (car org-time-stamp-rounding-minutes))
3332 (time (decode-time)))
3333 (apply 'encode-time
3334 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3335 (nthcdr 2 time))))
3336 (current-time)))
3338 ;;;; Font-Lock stuff, including the activators
3340 (defvar org-mouse-map (make-sparse-keymap))
3341 (org-defkey org-mouse-map
3342 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3343 (org-defkey org-mouse-map
3344 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3345 (when org-mouse-1-follows-link
3346 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3347 (when org-tab-follows-link
3348 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3349 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3350 (when org-return-follows-link
3351 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3352 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3354 (require 'font-lock)
3356 (defconst org-non-link-chars "]\t\n\r<>")
3357 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3358 "shell" "elisp"))
3359 (defvar org-link-types-re nil
3360 "Matches a link that has a url-like prefix like \"http:\"")
3361 (defvar org-link-re-with-space nil
3362 "Matches a link with spaces, optional angular brackets around it.")
3363 (defvar org-link-re-with-space2 nil
3364 "Matches a link with spaces, optional angular brackets around it.")
3365 (defvar org-angle-link-re nil
3366 "Matches link with angular brackets, spaces are allowed.")
3367 (defvar org-plain-link-re nil
3368 "Matches plain link, without spaces.")
3369 (defvar org-bracket-link-regexp nil
3370 "Matches a link in double brackets.")
3371 (defvar org-bracket-link-analytic-regexp nil
3372 "Regular expression used to analyze links.
3373 Here is what the match groups contain after a match:
3374 1: http:
3375 2: http
3376 3: path
3377 4: [desc]
3378 5: desc")
3379 (defvar org-any-link-re nil
3380 "Regular expression matching any link.")
3382 (defun org-make-link-regexps ()
3383 "Update the link regular expressions.
3384 This should be called after the variable `org-link-types' has changed."
3385 (setq org-link-types-re
3386 (concat
3387 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3388 org-link-re-with-space
3389 (concat
3390 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3391 "\\([^" org-non-link-chars " ]"
3392 "[^" org-non-link-chars "]*"
3393 "[^" org-non-link-chars " ]\\)>?")
3394 org-link-re-with-space2
3395 (concat
3396 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3397 "\\([^" org-non-link-chars " ]"
3398 "[^]\t\n\r]*"
3399 "[^" org-non-link-chars " ]\\)>?")
3400 org-angle-link-re
3401 (concat
3402 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3403 "\\([^" org-non-link-chars " ]"
3404 "[^" org-non-link-chars "]*"
3405 "\\)>")
3406 org-plain-link-re
3407 (concat
3408 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3409 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3410 org-bracket-link-regexp
3411 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3412 org-bracket-link-analytic-regexp
3413 (concat
3414 "\\[\\["
3415 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3416 "\\([^]]+\\)"
3417 "\\]"
3418 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3419 "\\]")
3420 org-any-link-re
3421 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3422 org-angle-link-re "\\)\\|\\("
3423 org-plain-link-re "\\)")))
3425 (org-make-link-regexps)
3427 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3428 "Regular expression for fast time stamp matching.")
3429 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3430 "Regular expression for fast time stamp matching.")
3431 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3432 "Regular expression matching time strings for analysis.
3433 This one does not require the space after the date, so it can be used
3434 on a string that terminates immediately after the date.")
3435 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3436 "Regular expression matching time strings for analysis.")
3437 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3438 "Regular expression matching time stamps, with groups.")
3439 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3440 "Regular expression matching time stamps (also [..]), with groups.")
3441 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3442 "Regular expression matching a time stamp range.")
3443 (defconst org-tr-regexp-both
3444 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3445 "Regular expression matching a time stamp range.")
3446 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3447 org-ts-regexp "\\)?")
3448 "Regular expression matching a time stamp or time stamp range.")
3449 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3450 org-ts-regexp-both "\\)?")
3451 "Regular expression matching a time stamp or time stamp range.
3452 The time stamps may be either active or inactive.")
3454 (defvar org-emph-face nil)
3456 (defun org-do-emphasis-faces (limit)
3457 "Run through the buffer and add overlays to links."
3458 (let (rtn)
3459 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3460 (if (not (= (char-after (match-beginning 3))
3461 (char-after (match-beginning 4))))
3462 (progn
3463 (setq rtn t)
3464 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3465 'face
3466 (nth 1 (assoc (match-string 3)
3467 org-emphasis-alist)))
3468 (add-text-properties (match-beginning 2) (match-end 2)
3469 '(font-lock-multiline t))
3470 (when org-hide-emphasis-markers
3471 (add-text-properties (match-end 4) (match-beginning 5)
3472 '(invisible org-link))
3473 (add-text-properties (match-beginning 3) (match-end 3)
3474 '(invisible org-link)))))
3475 (backward-char 1))
3476 rtn))
3478 (defun org-emphasize (&optional char)
3479 "Insert or change an emphasis, i.e. a font like bold or italic.
3480 If there is an active region, change that region to a new emphasis.
3481 If there is no region, just insert the marker characters and position
3482 the cursor between them.
3483 CHAR should be either the marker character, or the first character of the
3484 HTML tag associated with that emphasis. If CHAR is a space, the means
3485 to remove the emphasis of the selected region.
3486 If char is not given (for example in an interactive call) it
3487 will be prompted for."
3488 (interactive)
3489 (let ((eal org-emphasis-alist) e det
3490 (erc org-emphasis-regexp-components)
3491 (prompt "")
3492 (string "") beg end move tag c s)
3493 (if (org-region-active-p)
3494 (setq beg (region-beginning) end (region-end)
3495 string (buffer-substring beg end))
3496 (setq move t))
3498 (while (setq e (pop eal))
3499 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3500 c (aref tag 0))
3501 (push (cons c (string-to-char (car e))) det)
3502 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3503 (substring tag 1)))))
3504 (unless char
3505 (message "%s" (concat "Emphasis marker or tag:" prompt))
3506 (setq char (read-char-exclusive)))
3507 (setq char (or (cdr (assoc char det)) char))
3508 (if (equal char ?\ )
3509 (setq s "" move nil)
3510 (unless (assoc (char-to-string char) org-emphasis-alist)
3511 (error "No such emphasis marker: \"%c\"" char))
3512 (setq s (char-to-string char)))
3513 (while (and (> (length string) 1)
3514 (equal (substring string 0 1) (substring string -1))
3515 (assoc (substring string 0 1) org-emphasis-alist))
3516 (setq string (substring string 1 -1)))
3517 (setq string (concat s string s))
3518 (if beg (delete-region beg end))
3519 (unless (or (bolp)
3520 (string-match (concat "[" (nth 0 erc) "\n]")
3521 (char-to-string (char-before (point)))))
3522 (insert " "))
3523 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3524 (char-to-string (char-after (point))))
3525 (insert " ") (backward-char 1))
3526 (insert string)
3527 (and move (backward-char 1))))
3529 (defconst org-nonsticky-props
3530 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3533 (defun org-activate-plain-links (limit)
3534 "Run through the buffer and add overlays to links."
3535 (catch 'exit
3536 (let (f)
3537 (while (re-search-forward org-plain-link-re limit t)
3538 (setq f (get-text-property (match-beginning 0) 'face))
3539 (if (or (eq f 'org-tag)
3540 (and (listp f) (memq 'org-tag f)))
3542 (add-text-properties (match-beginning 0) (match-end 0)
3543 (list 'mouse-face 'highlight
3544 'rear-nonsticky org-nonsticky-props
3545 'keymap org-mouse-map
3547 (throw 'exit t))))))
3549 (defun org-activate-code (limit)
3550 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3551 (progn
3552 (remove-text-properties (match-beginning 0) (match-end 0)
3553 '(display t invisible t intangible t))
3554 t)))
3556 (defun org-activate-angle-links (limit)
3557 "Run through the buffer and add overlays to links."
3558 (if (re-search-forward org-angle-link-re limit t)
3559 (progn
3560 (add-text-properties (match-beginning 0) (match-end 0)
3561 (list 'mouse-face 'highlight
3562 'rear-nonsticky org-nonsticky-props
3563 'keymap org-mouse-map
3565 t)))
3567 (defun org-activate-bracket-links (limit)
3568 "Run through the buffer and add overlays to bracketed links."
3569 (if (re-search-forward org-bracket-link-regexp limit t)
3570 (let* ((help (concat "LINK: "
3571 (org-match-string-no-properties 1)))
3572 ;; FIXME: above we should remove the escapes.
3573 ;; but that requires another match, protecting match data,
3574 ;; a lot of overhead for font-lock.
3575 (ip (org-maybe-intangible
3576 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3577 'keymap org-mouse-map 'mouse-face 'highlight
3578 'font-lock-multiline t 'help-echo help)))
3579 (vp (list 'rear-nonsticky org-nonsticky-props
3580 'keymap org-mouse-map 'mouse-face 'highlight
3581 ' font-lock-multiline t 'help-echo help)))
3582 ;; We need to remove the invisible property here. Table narrowing
3583 ;; may have made some of this invisible.
3584 (remove-text-properties (match-beginning 0) (match-end 0)
3585 '(invisible nil))
3586 (if (match-end 3)
3587 (progn
3588 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3589 (add-text-properties (match-beginning 3) (match-end 3) vp)
3590 (add-text-properties (match-end 3) (match-end 0) ip))
3591 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3592 (add-text-properties (match-beginning 1) (match-end 1) vp)
3593 (add-text-properties (match-end 1) (match-end 0) ip))
3594 t)))
3596 (defun org-activate-dates (limit)
3597 "Run through the buffer and add overlays to dates."
3598 (if (re-search-forward org-tsr-regexp-both limit t)
3599 (progn
3600 (add-text-properties (match-beginning 0) (match-end 0)
3601 (list 'mouse-face 'highlight
3602 'rear-nonsticky org-nonsticky-props
3603 'keymap org-mouse-map))
3604 (when org-display-custom-times
3605 (if (match-end 3)
3606 (org-display-custom-time (match-beginning 3) (match-end 3)))
3607 (org-display-custom-time (match-beginning 1) (match-end 1)))
3608 t)))
3610 (defvar org-target-link-regexp nil
3611 "Regular expression matching radio targets in plain text.")
3612 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3613 "Regular expression matching a link target.")
3614 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3615 "Regular expression matching a radio target.")
3616 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3617 "Regular expression matching any target.")
3619 (defun org-activate-target-links (limit)
3620 "Run through the buffer and add overlays to target matches."
3621 (when org-target-link-regexp
3622 (let ((case-fold-search t))
3623 (if (re-search-forward org-target-link-regexp limit t)
3624 (progn
3625 (add-text-properties (match-beginning 0) (match-end 0)
3626 (list 'mouse-face 'highlight
3627 'rear-nonsticky org-nonsticky-props
3628 'keymap org-mouse-map
3629 'help-echo "Radio target link"
3630 'org-linked-text t))
3631 t)))))
3633 (defun org-update-radio-target-regexp ()
3634 "Find all radio targets in this file and update the regular expression."
3635 (interactive)
3636 (when (memq 'radio org-activate-links)
3637 (setq org-target-link-regexp
3638 (org-make-target-link-regexp (org-all-targets 'radio)))
3639 (org-restart-font-lock)))
3641 (defun org-hide-wide-columns (limit)
3642 (let (s e)
3643 (setq s (text-property-any (point) (or limit (point-max))
3644 'org-cwidth t))
3645 (when s
3646 (setq e (next-single-property-change s 'org-cwidth))
3647 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3648 (goto-char e)
3649 t)))
3651 (defvar org-latex-and-specials-regexp nil
3652 "Regular expression for highlighting export special stuff.")
3653 (defvar org-match-substring-regexp)
3654 (defvar org-match-substring-with-braces-regexp)
3655 (defvar org-export-html-special-string-regexps)
3657 (defun org-compute-latex-and-specials-regexp ()
3658 "Compute regular expression for stuff treated specially by exporters."
3659 (if (not org-highlight-latex-fragments-and-specials)
3660 (org-set-local 'org-latex-and-specials-regexp nil)
3661 (require 'org-exp)
3662 (let*
3663 ((matchers (plist-get org-format-latex-options :matchers))
3664 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3665 org-latex-regexps)))
3666 (options (org-combine-plists (org-default-export-plist)
3667 (org-infile-export-plist)))
3668 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3669 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3670 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3671 (org-export-html-expand (plist-get options :expand-quoted-html))
3672 (org-export-with-special-strings (plist-get options :special-strings))
3673 (re-sub
3674 (cond
3675 ((equal org-export-with-sub-superscripts '{})
3676 (list org-match-substring-with-braces-regexp))
3677 (org-export-with-sub-superscripts
3678 (list org-match-substring-regexp))
3679 (t nil)))
3680 (re-latex
3681 (if org-export-with-LaTeX-fragments
3682 (mapcar (lambda (x) (nth 1 x)) latexs)))
3683 (re-macros
3684 (if org-export-with-TeX-macros
3685 (list (concat "\\\\"
3686 (regexp-opt
3687 (append (mapcar 'car org-html-entities)
3688 (if (boundp 'org-latex-entities)
3689 org-latex-entities nil))
3690 'words))) ; FIXME
3692 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3693 (re-special (if org-export-with-special-strings
3694 (mapcar (lambda (x) (car x))
3695 org-export-html-special-string-regexps)))
3696 (re-rest
3697 (delq nil
3698 (list
3699 (if org-export-html-expand "@<[^>\n]+>")
3700 ))))
3701 (org-set-local
3702 'org-latex-and-specials-regexp
3703 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3704 re-rest) "\\|")))))
3706 (defun org-do-latex-and-special-faces (limit)
3707 "Run through the buffer and add overlays to links."
3708 (when org-latex-and-specials-regexp
3709 (let (rtn d)
3710 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3711 limit t))
3712 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3713 'face))
3714 '(org-code org-verbatim underline)))
3715 (progn
3716 (setq rtn t
3717 d (cond ((member (char-after (1+ (match-beginning 0)))
3718 '(?_ ?^)) 1)
3719 (t 0)))
3720 (font-lock-prepend-text-property
3721 (+ d (match-beginning 0)) (match-end 0)
3722 'face 'org-latex-and-export-specials)
3723 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3724 '(font-lock-multiline t)))))
3725 rtn)))
3727 (defun org-restart-font-lock ()
3728 "Restart font-lock-mode, to force refontification."
3729 (when (and (boundp 'font-lock-mode) font-lock-mode)
3730 (font-lock-mode -1)
3731 (font-lock-mode 1)))
3733 (defun org-all-targets (&optional radio)
3734 "Return a list of all targets in this file.
3735 With optional argument RADIO, only find radio targets."
3736 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3737 rtn)
3738 (save-excursion
3739 (goto-char (point-min))
3740 (while (re-search-forward re nil t)
3741 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3742 rtn)))
3744 (defun org-make-target-link-regexp (targets)
3745 "Make regular expression matching all strings in TARGETS.
3746 The regular expression finds the targets also if there is a line break
3747 between words."
3748 (and targets
3749 (concat
3750 "\\<\\("
3751 (mapconcat
3752 (lambda (x)
3753 (while (string-match " +" x)
3754 (setq x (replace-match "\\s-+" t t x)))
3756 targets
3757 "\\|")
3758 "\\)\\>")))
3760 (defun org-activate-tags (limit)
3761 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3762 (progn
3763 (add-text-properties (match-beginning 1) (match-end 1)
3764 (list 'mouse-face 'highlight
3765 'rear-nonsticky org-nonsticky-props
3766 'keymap org-mouse-map))
3767 t)))
3769 (defun org-outline-level ()
3770 (save-excursion
3771 (looking-at outline-regexp)
3772 (if (match-beginning 1)
3773 (+ (org-get-string-indentation (match-string 1)) 1000)
3774 (1- (- (match-end 0) (match-beginning 0))))))
3776 (defvar org-font-lock-keywords nil)
3778 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3779 "Regular expression matching a property line.")
3781 (defvar org-font-lock-hook nil
3782 "Functions to be called for special font lock stuff.")
3784 (defun org-font-lock-hook (limit)
3785 (run-hook-with-args 'org-font-lock-hook limit))
3787 (defun org-set-font-lock-defaults ()
3788 (let* ((em org-fontify-emphasized-text)
3789 (lk org-activate-links)
3790 (org-font-lock-extra-keywords
3791 (list
3792 ;; Call the hook
3793 '(org-font-lock-hook)
3794 ;; Headlines
3795 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3796 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3797 ;; Table lines
3798 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3799 (1 'org-table t))
3800 ;; Table internals
3801 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3802 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3803 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3804 ;; Drawers
3805 (list org-drawer-regexp '(0 'org-special-keyword t))
3806 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3807 ;; Properties
3808 (list org-property-re
3809 '(1 'org-special-keyword t)
3810 '(3 'org-property-value t))
3811 (if org-format-transports-properties-p
3812 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3813 ;; Links
3814 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3815 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3816 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3817 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3818 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3819 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3820 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3821 '(org-hide-wide-columns (0 nil append))
3822 ;; TODO lines
3823 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3824 '(1 (org-get-todo-face 1) t))
3825 ;; DONE
3826 (if org-fontify-done-headline
3827 (list (concat "^[*]+ +\\<\\("
3828 (mapconcat 'regexp-quote org-done-keywords "\\|")
3829 "\\)\\(.*\\)")
3830 '(2 'org-headline-done t))
3831 nil)
3832 ;; Priorities
3833 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3834 ;; Special keywords
3835 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3836 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3837 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3838 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3839 ;; Emphasis
3840 (if em
3841 (if (featurep 'xemacs)
3842 '(org-do-emphasis-faces (0 nil append))
3843 '(org-do-emphasis-faces)))
3844 ;; Checkboxes
3845 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3846 2 'bold prepend)
3847 (if org-provide-checkbox-statistics
3848 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3849 (0 (org-get-checkbox-statistics-face) t)))
3850 ;; Description list items
3851 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3852 2 'bold prepend)
3853 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3854 '(1 'org-archived prepend))
3855 ;; Specials
3856 '(org-do-latex-and-special-faces)
3857 ;; Code
3858 '(org-activate-code (1 'org-code t))
3859 ;; COMMENT
3860 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3861 "\\|" org-quote-string "\\)\\>")
3862 '(1 'org-special-keyword t))
3863 '("^#.*" (0 'font-lock-comment-face t))
3865 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3866 ;; Now set the full font-lock-keywords
3867 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3868 (org-set-local 'font-lock-defaults
3869 '(org-font-lock-keywords t nil nil backward-paragraph))
3870 (kill-local-variable 'font-lock-keywords) nil))
3872 (defvar org-m nil)
3873 (defvar org-l nil)
3874 (defvar org-f nil)
3875 (defun org-get-level-face (n)
3876 "Get the right face for match N in font-lock matching of healdines."
3877 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3878 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3879 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3880 (cond
3881 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3882 ((eq n 2) org-f)
3883 (t (if org-level-color-stars-only nil org-f))))
3885 (defun org-get-todo-face (kwd)
3886 "Get the right face for a TODO keyword KWD.
3887 If KWD is a number, get the corresponding match group."
3888 (if (numberp kwd) (setq kwd (match-string kwd)))
3889 (or (cdr (assoc kwd org-todo-keyword-faces))
3890 (and (member kwd org-done-keywords) 'org-done)
3891 'org-todo))
3893 (defun org-unfontify-region (beg end &optional maybe_loudly)
3894 "Remove fontification and activation overlays from links."
3895 (font-lock-default-unfontify-region beg end)
3896 (let* ((buffer-undo-list t)
3897 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3898 (inhibit-modification-hooks t)
3899 deactivate-mark buffer-file-name buffer-file-truename)
3900 (remove-text-properties beg end
3901 '(mouse-face t keymap t org-linked-text t
3902 invisible t intangible t))))
3904 ;;;; Visibility cycling, including org-goto and indirect buffer
3906 ;;; Cycling
3908 (defvar org-cycle-global-status nil)
3909 (make-variable-buffer-local 'org-cycle-global-status)
3910 (defvar org-cycle-subtree-status nil)
3911 (make-variable-buffer-local 'org-cycle-subtree-status)
3913 ;;;###autoload
3914 (defun org-cycle (&optional arg)
3915 "Visibility cycling for Org-mode.
3917 - When this function is called with a prefix argument, rotate the entire
3918 buffer through 3 states (global cycling)
3919 1. OVERVIEW: Show only top-level headlines.
3920 2. CONTENTS: Show all headlines of all levels, but no body text.
3921 3. SHOW ALL: Show everything.
3922 When called with two C-u C-u prefixes, switch to the startup visibility,
3923 determined by the variable `org-startup-folded', and by any VISIBILITY
3924 properties in the buffer.
3925 When called with three C-u C-u C-u prefixed, show the entire buffer,
3926 including drawers.
3928 - When point is at the beginning of a headline, rotate the subtree started
3929 by this line through 3 different states (local cycling)
3930 1. FOLDED: Only the main headline is shown.
3931 2. CHILDREN: The main headline and the direct children are shown.
3932 From this state, you can move to one of the children
3933 and zoom in further.
3934 3. SUBTREE: Show the entire subtree, including body text.
3936 - When there is a numeric prefix, go up to a heading with level ARG, do
3937 a `show-subtree' and return to the previous cursor position. If ARG
3938 is negative, go up that many levels.
3940 - When point is not at the beginning of a headline, execute the global
3941 binding for TAB, which is re-indenting the line. See the option
3942 `org-cycle-emulate-tab' for details.
3944 - Special case: if point is at the beginning of the buffer and there is
3945 no headline in line 1, this function will act as if called with prefix arg.
3946 But only if also the variable `org-cycle-global-at-bob' is t."
3947 (interactive "P")
3948 (org-load-modules-maybe)
3949 (let* ((outline-regexp
3950 (if (and (org-mode-p) org-cycle-include-plain-lists)
3951 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3952 outline-regexp))
3953 (bob-special (and org-cycle-global-at-bob (bobp)
3954 (not (looking-at outline-regexp))))
3955 (org-cycle-hook
3956 (if bob-special
3957 (delq 'org-optimize-window-after-visibility-change
3958 (copy-sequence org-cycle-hook))
3959 org-cycle-hook))
3960 (pos (point)))
3962 (if (or bob-special (equal arg '(4)))
3963 ;; special case: use global cycling
3964 (setq arg t))
3966 (cond
3968 ((equal arg '(16))
3969 (org-set-startup-visibility)
3970 (message "Startup visibility, plus VISIBILITY properties"))
3972 ((equal arg '(64))
3973 (show-all)
3974 (message "Entire buffer visible, including drawers"))
3976 ((org-at-table-p 'any)
3977 ;; Enter the table or move to the next field in the table
3978 (or (org-table-recognize-table.el)
3979 (progn
3980 (if arg (org-table-edit-field t)
3981 (org-table-justify-field-maybe)
3982 (call-interactively 'org-table-next-field)))))
3984 ((eq arg t) ;; Global cycling
3986 (cond
3987 ((and (eq last-command this-command)
3988 (eq org-cycle-global-status 'overview))
3989 ;; We just created the overview - now do table of contents
3990 ;; This can be slow in very large buffers, so indicate action
3991 (message "CONTENTS...")
3992 (org-content)
3993 (message "CONTENTS...done")
3994 (setq org-cycle-global-status 'contents)
3995 (run-hook-with-args 'org-cycle-hook 'contents))
3997 ((and (eq last-command this-command)
3998 (eq org-cycle-global-status 'contents))
3999 ;; We just showed the table of contents - now show everything
4000 (show-all)
4001 (message "SHOW ALL")
4002 (setq org-cycle-global-status 'all)
4003 (run-hook-with-args 'org-cycle-hook 'all))
4006 ;; Default action: go to overview
4007 (org-overview)
4008 (message "OVERVIEW")
4009 (setq org-cycle-global-status 'overview)
4010 (run-hook-with-args 'org-cycle-hook 'overview))))
4012 ((and org-drawers org-drawer-regexp
4013 (save-excursion
4014 (beginning-of-line 1)
4015 (looking-at org-drawer-regexp)))
4016 ;; Toggle block visibility
4017 (org-flag-drawer
4018 (not (get-char-property (match-end 0) 'invisible))))
4020 ((integerp arg)
4021 ;; Show-subtree, ARG levels up from here.
4022 (save-excursion
4023 (org-back-to-heading)
4024 (outline-up-heading (if (< arg 0) (- arg)
4025 (- (funcall outline-level) arg)))
4026 (org-show-subtree)))
4028 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4029 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4030 ;; At a heading: rotate between three different views
4031 (org-back-to-heading)
4032 (let ((goal-column 0) eoh eol eos)
4033 ;; First, some boundaries
4034 (save-excursion
4035 (org-back-to-heading)
4036 (save-excursion
4037 (beginning-of-line 2)
4038 (while (and (not (eobp)) ;; this is like `next-line'
4039 (get-char-property (1- (point)) 'invisible))
4040 (beginning-of-line 2)) (setq eol (point)))
4041 (outline-end-of-heading) (setq eoh (point))
4042 (org-end-of-subtree t)
4043 (unless (eobp)
4044 (skip-chars-forward " \t\n")
4045 (beginning-of-line 1) ; in case this is an item
4047 (setq eos (1- (point))))
4048 ;; Find out what to do next and set `this-command'
4049 (cond
4050 ((= eos eoh)
4051 ;; Nothing is hidden behind this heading
4052 (message "EMPTY ENTRY")
4053 (setq org-cycle-subtree-status nil)
4054 (save-excursion
4055 (goto-char eos)
4056 (outline-next-heading)
4057 (if (org-invisible-p) (org-flag-heading nil))))
4058 ((or (>= eol eos)
4059 (not (string-match "\\S-" (buffer-substring eol eos))))
4060 ;; Entire subtree is hidden in one line: open it
4061 (org-show-entry)
4062 (show-children)
4063 (message "CHILDREN")
4064 (save-excursion
4065 (goto-char eos)
4066 (outline-next-heading)
4067 (if (org-invisible-p) (org-flag-heading nil)))
4068 (setq org-cycle-subtree-status 'children)
4069 (run-hook-with-args 'org-cycle-hook 'children))
4070 ((and (eq last-command this-command)
4071 (eq org-cycle-subtree-status 'children))
4072 ;; We just showed the children, now show everything.
4073 (org-show-subtree)
4074 (message "SUBTREE")
4075 (setq org-cycle-subtree-status 'subtree)
4076 (run-hook-with-args 'org-cycle-hook 'subtree))
4078 ;; Default action: hide the subtree.
4079 (hide-subtree)
4080 (message "FOLDED")
4081 (setq org-cycle-subtree-status 'folded)
4082 (run-hook-with-args 'org-cycle-hook 'folded)))))
4084 ;; TAB emulation and template completion
4085 (buffer-read-only (org-back-to-heading))
4087 ((org-try-structure-completion))
4089 ((org-try-cdlatex-tab))
4091 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4092 (or (not (bolp))
4093 (not (looking-at outline-regexp))))
4094 (call-interactively (global-key-binding "\t")))
4096 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4097 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4098 (or (and (eq org-cycle-emulate-tab 'white)
4099 (= (match-end 0) (point-at-eol)))
4100 (and (eq org-cycle-emulate-tab 'whitestart)
4101 (>= (match-end 0) pos))))
4103 (eq org-cycle-emulate-tab t))
4104 (call-interactively (global-key-binding "\t")))
4106 (t (save-excursion
4107 (org-back-to-heading)
4108 (org-cycle))))))
4110 ;;;###autoload
4111 (defun org-global-cycle (&optional arg)
4112 "Cycle the global visibility. For details see `org-cycle'.
4113 With C-u prefix arg, switch to startup visibility.
4114 With a numeric prefix, show all headlines up to that level."
4115 (interactive "P")
4116 (let ((org-cycle-include-plain-lists
4117 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4118 (cond
4119 ((integerp arg)
4120 (show-all)
4121 (hide-sublevels arg)
4122 (setq org-cycle-global-status 'contents))
4123 ((equal arg '(4))
4124 (org-set-startup-visibility)
4125 (message "Startup visibility, plus VISIBILITY properties."))
4127 (org-cycle '(4))))))
4129 (defun org-set-startup-visibility ()
4130 "Set the visibility required by startup options and properties."
4131 (cond
4132 ((eq org-startup-folded t)
4133 (org-cycle '(4)))
4134 ((eq org-startup-folded 'content)
4135 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4136 (org-cycle '(4)) (org-cycle '(4)))))
4137 (org-set-visibility-according-to-property 'no-cleanup)
4138 (org-cycle-hide-archived-subtrees 'all)
4139 (org-cycle-hide-drawers 'all)
4140 (org-cycle-show-empty-lines 'all))
4142 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4143 "Switch subtree visibilities according to :VISIBILITY: property."
4144 (interactive)
4145 (let (state)
4146 (save-excursion
4147 (goto-char (point-min))
4148 (while (re-search-forward
4149 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4150 nil t)
4151 (setq state (match-string 1))
4152 (save-excursion
4153 (org-back-to-heading t)
4154 (hide-subtree)
4155 (org-reveal)
4156 (cond
4157 ((equal state '("fold" "folded"))
4158 (hide-subtree))
4159 ((equal state "children")
4160 (org-show-hidden-entry)
4161 (show-children))
4162 ((equal state "content")
4163 (save-excursion
4164 (save-restriction
4165 (org-narrow-to-subtree)
4166 (org-content))))
4167 ((member state '("all" "showall"))
4168 (show-subtree)))))
4169 (unless no-cleanup
4170 (org-cycle-hide-archived-subtrees 'all)
4171 (org-cycle-hide-drawers 'all)
4172 (org-cycle-show-empty-lines 'all)))))
4174 (defun org-overview ()
4175 "Switch to overview mode, shoing only top-level headlines.
4176 Really, this shows all headlines with level equal or greater than the level
4177 of the first headline in the buffer. This is important, because if the
4178 first headline is not level one, then (hide-sublevels 1) gives confusing
4179 results."
4180 (interactive)
4181 (let ((level (save-excursion
4182 (goto-char (point-min))
4183 (if (re-search-forward (concat "^" outline-regexp) nil t)
4184 (progn
4185 (goto-char (match-beginning 0))
4186 (funcall outline-level))))))
4187 (and level (hide-sublevels level))))
4189 (defun org-content (&optional arg)
4190 "Show all headlines in the buffer, like a table of contents.
4191 With numerical argument N, show content up to level N."
4192 (interactive "P")
4193 (save-excursion
4194 ;; Visit all headings and show their offspring
4195 (and (integerp arg) (org-overview))
4196 (goto-char (point-max))
4197 (catch 'exit
4198 (while (and (progn (condition-case nil
4199 (outline-previous-visible-heading 1)
4200 (error (goto-char (point-min))))
4202 (looking-at outline-regexp))
4203 (if (integerp arg)
4204 (show-children (1- arg))
4205 (show-branches))
4206 (if (bobp) (throw 'exit nil))))))
4209 (defun org-optimize-window-after-visibility-change (state)
4210 "Adjust the window after a change in outline visibility.
4211 This function is the default value of the hook `org-cycle-hook'."
4212 (when (get-buffer-window (current-buffer))
4213 (cond
4214 ; ((eq state 'overview) (org-first-headline-recenter 1))
4215 ; ((eq state 'overview) (org-beginning-of-line))
4216 ((eq state 'content) nil)
4217 ((eq state 'all) nil)
4218 ((eq state 'folded) nil)
4219 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4220 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4222 (defun org-compact-display-after-subtree-move ()
4223 (let (beg end)
4224 (save-excursion
4225 (if (org-up-heading-safe)
4226 (progn
4227 (hide-subtree)
4228 (show-entry)
4229 (show-children)
4230 (org-cycle-show-empty-lines 'children)
4231 (org-cycle-hide-drawers 'children))
4232 (org-overview)))))
4234 (defun org-cycle-show-empty-lines (state)
4235 "Show empty lines above all visible headlines.
4236 The region to be covered depends on STATE when called through
4237 `org-cycle-hook'. Lisp program can use t for STATE to get the
4238 entire buffer covered. Note that an empty line is only shown if there
4239 are at least `org-cycle-separator-lines' empty lines before the headeline."
4240 (when (> org-cycle-separator-lines 0)
4241 (save-excursion
4242 (let* ((n org-cycle-separator-lines)
4243 (re (cond
4244 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4245 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4246 (t (let ((ns (number-to-string (- n 2))))
4247 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4248 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4249 beg end)
4250 (cond
4251 ((memq state '(overview contents t))
4252 (setq beg (point-min) end (point-max)))
4253 ((memq state '(children folded))
4254 (setq beg (point) end (progn (org-end-of-subtree t t)
4255 (beginning-of-line 2)
4256 (point)))))
4257 (when beg
4258 (goto-char beg)
4259 (while (re-search-forward re end t)
4260 (if (not (get-char-property (match-end 1) 'invisible))
4261 (outline-flag-region
4262 (match-beginning 1) (match-end 1) nil)))))))
4263 ;; Never hide empty lines at the end of the file.
4264 (save-excursion
4265 (goto-char (point-max))
4266 (outline-previous-heading)
4267 (outline-end-of-heading)
4268 (if (and (looking-at "[ \t\n]+")
4269 (= (match-end 0) (point-max)))
4270 (outline-flag-region (point) (match-end 0) nil))))
4272 (defun org-show-empty-lines-in-parent ()
4273 "Move to the parent and re-show empty lines before visible headlines."
4274 (save-excursion
4275 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4276 (org-cycle-show-empty-lines context))))
4278 (defun org-cycle-hide-drawers (state)
4279 "Re-hide all drawers after a visibility state change."
4280 (when (and (org-mode-p)
4281 (not (memq state '(overview folded))))
4282 (save-excursion
4283 (let* ((globalp (memq state '(contents all)))
4284 (beg (if globalp (point-min) (point)))
4285 (end (if globalp (point-max) (org-end-of-subtree t))))
4286 (goto-char beg)
4287 (while (re-search-forward org-drawer-regexp end t)
4288 (org-flag-drawer t))))))
4290 (defun org-flag-drawer (flag)
4291 (save-excursion
4292 (beginning-of-line 1)
4293 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4294 (let ((b (match-end 0))
4295 (outline-regexp org-outline-regexp))
4296 (if (re-search-forward
4297 "^[ \t]*:END:"
4298 (save-excursion (outline-next-heading) (point)) t)
4299 (outline-flag-region b (point-at-eol) flag)
4300 (error ":END: line missing"))))))
4302 (defun org-subtree-end-visible-p ()
4303 "Is the end of the current subtree visible?"
4304 (pos-visible-in-window-p
4305 (save-excursion (org-end-of-subtree t) (point))))
4307 (defun org-first-headline-recenter (&optional N)
4308 "Move cursor to the first headline and recenter the headline.
4309 Optional argument N means, put the headline into the Nth line of the window."
4310 (goto-char (point-min))
4311 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4312 (beginning-of-line)
4313 (recenter (prefix-numeric-value N))))
4315 ;;; Org-goto
4317 (defvar org-goto-window-configuration nil)
4318 (defvar org-goto-marker nil)
4319 (defvar org-goto-map
4320 (let ((map (make-sparse-keymap)))
4321 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4322 (while (setq cmd (pop cmds))
4323 (substitute-key-definition cmd cmd map global-map)))
4324 (suppress-keymap map)
4325 (org-defkey map "\C-m" 'org-goto-ret)
4326 (org-defkey map [(return)] 'org-goto-ret)
4327 (org-defkey map [(left)] 'org-goto-left)
4328 (org-defkey map [(right)] 'org-goto-right)
4329 (org-defkey map [(control ?g)] 'org-goto-quit)
4330 (org-defkey map "\C-i" 'org-cycle)
4331 (org-defkey map [(tab)] 'org-cycle)
4332 (org-defkey map [(down)] 'outline-next-visible-heading)
4333 (org-defkey map [(up)] 'outline-previous-visible-heading)
4334 (if org-goto-auto-isearch
4335 (if (fboundp 'define-key-after)
4336 (define-key-after map [t] 'org-goto-local-auto-isearch)
4337 nil)
4338 (org-defkey map "q" 'org-goto-quit)
4339 (org-defkey map "n" 'outline-next-visible-heading)
4340 (org-defkey map "p" 'outline-previous-visible-heading)
4341 (org-defkey map "f" 'outline-forward-same-level)
4342 (org-defkey map "b" 'outline-backward-same-level)
4343 (org-defkey map "u" 'outline-up-heading))
4344 (org-defkey map "/" 'org-occur)
4345 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4346 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4347 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4348 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4349 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4350 map))
4352 (defconst org-goto-help
4353 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4354 RET=jump to location [Q]uit and return to previous location
4355 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4357 (defvar org-goto-start-pos) ; dynamically scoped parameter
4359 ;; FIXME: Docstring doe not mention both interfaces
4360 (defun org-goto (&optional alternative-interface)
4361 "Look up a different location in the current file, keeping current visibility.
4363 When you want look-up or go to a different location in a document, the
4364 fastest way is often to fold the entire buffer and then dive into the tree.
4365 This method has the disadvantage, that the previous location will be folded,
4366 which may not be what you want.
4368 This command works around this by showing a copy of the current buffer
4369 in an indirect buffer, in overview mode. You can dive into the tree in
4370 that copy, use org-occur and incremental search to find a location.
4371 When pressing RET or `Q', the command returns to the original buffer in
4372 which the visibility is still unchanged. After RET is will also jump to
4373 the location selected in the indirect buffer and expose the
4374 the headline hierarchy above."
4375 (interactive "P")
4376 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4377 (org-refile-use-outline-path t)
4378 (interface
4379 (if (not alternative-interface)
4380 org-goto-interface
4381 (if (eq org-goto-interface 'outline)
4382 'outline-path-completion
4383 'outline)))
4384 (org-goto-start-pos (point))
4385 (selected-point
4386 (if (eq interface 'outline)
4387 (car (org-get-location (current-buffer) org-goto-help))
4388 (nth 3 (org-refile-get-location "Goto: ")))))
4389 (if selected-point
4390 (progn
4391 (org-mark-ring-push org-goto-start-pos)
4392 (goto-char selected-point)
4393 (if (or (org-invisible-p) (org-invisible-p2))
4394 (org-show-context 'org-goto)))
4395 (message "Quit"))))
4397 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4398 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4399 (defvar org-goto-local-auto-isearch-map) ; defined below
4401 (defun org-get-location (buf help)
4402 "Let the user select a location in the Org-mode buffer BUF.
4403 This function uses a recursive edit. It returns the selected position
4404 or nil."
4405 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4406 (isearch-hide-immediately nil)
4407 (isearch-search-fun-function
4408 (lambda () 'org-goto-local-search-headings))
4409 (org-goto-selected-point org-goto-exit-command))
4410 (save-excursion
4411 (save-window-excursion
4412 (delete-other-windows)
4413 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4414 (switch-to-buffer
4415 (condition-case nil
4416 (make-indirect-buffer (current-buffer) "*org-goto*")
4417 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4418 (with-output-to-temp-buffer "*Help*"
4419 (princ help))
4420 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4421 (setq buffer-read-only nil)
4422 (let ((org-startup-truncated t)
4423 (org-startup-folded nil)
4424 (org-startup-align-all-tables nil))
4425 (org-mode)
4426 (org-overview))
4427 (setq buffer-read-only t)
4428 (if (and (boundp 'org-goto-start-pos)
4429 (integer-or-marker-p org-goto-start-pos))
4430 (let ((org-show-hierarchy-above t)
4431 (org-show-siblings t)
4432 (org-show-following-heading t))
4433 (goto-char org-goto-start-pos)
4434 (and (org-invisible-p) (org-show-context)))
4435 (goto-char (point-min)))
4436 (org-beginning-of-line)
4437 (message "Select location and press RET")
4438 (use-local-map org-goto-map)
4439 (recursive-edit)
4441 (kill-buffer "*org-goto*")
4442 (cons org-goto-selected-point org-goto-exit-command)))
4444 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4445 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4446 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4447 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4449 (defun org-goto-local-search-headings (string bound noerror)
4450 "Search and make sure that any matches are in headlines."
4451 (catch 'return
4452 (while (if isearch-forward
4453 (search-forward string bound noerror)
4454 (search-backward string bound noerror))
4455 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4456 (and (member :headline context)
4457 (not (member :tags context))))
4458 (throw 'return (point))))))
4460 (defun org-goto-local-auto-isearch ()
4461 "Start isearch."
4462 (interactive)
4463 (goto-char (point-min))
4464 (let ((keys (this-command-keys)))
4465 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4466 (isearch-mode t)
4467 (isearch-process-search-char (string-to-char keys)))))
4469 (defun org-goto-ret (&optional arg)
4470 "Finish `org-goto' by going to the new location."
4471 (interactive "P")
4472 (setq org-goto-selected-point (point)
4473 org-goto-exit-command 'return)
4474 (throw 'exit nil))
4476 (defun org-goto-left ()
4477 "Finish `org-goto' by going to the new location."
4478 (interactive)
4479 (if (org-on-heading-p)
4480 (progn
4481 (beginning-of-line 1)
4482 (setq org-goto-selected-point (point)
4483 org-goto-exit-command 'left)
4484 (throw 'exit nil))
4485 (error "Not on a heading")))
4487 (defun org-goto-right ()
4488 "Finish `org-goto' by going to the new location."
4489 (interactive)
4490 (if (org-on-heading-p)
4491 (progn
4492 (setq org-goto-selected-point (point)
4493 org-goto-exit-command 'right)
4494 (throw 'exit nil))
4495 (error "Not on a heading")))
4497 (defun org-goto-quit ()
4498 "Finish `org-goto' without cursor motion."
4499 (interactive)
4500 (setq org-goto-selected-point nil)
4501 (setq org-goto-exit-command 'quit)
4502 (throw 'exit nil))
4504 ;;; Indirect buffer display of subtrees
4506 (defvar org-indirect-dedicated-frame nil
4507 "This is the frame being used for indirect tree display.")
4508 (defvar org-last-indirect-buffer nil)
4510 (defun org-tree-to-indirect-buffer (&optional arg)
4511 "Create indirect buffer and narrow it to current subtree.
4512 With numerical prefix ARG, go up to this level and then take that tree.
4513 If ARG is negative, go up that many levels.
4514 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4515 indirect buffer previously made with this command, to avoid proliferation of
4516 indirect buffers. However, when you call the command with a `C-u' prefix, or
4517 when `org-indirect-buffer-display' is `new-frame', the last buffer
4518 is kept so that you can work with several indirect buffers at the same time.
4519 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4520 requests that a new frame be made for the new buffer, so that the dedicated
4521 frame is not changed."
4522 (interactive "P")
4523 (let ((cbuf (current-buffer))
4524 (cwin (selected-window))
4525 (pos (point))
4526 beg end level heading ibuf)
4527 (save-excursion
4528 (org-back-to-heading t)
4529 (when (numberp arg)
4530 (setq level (org-outline-level))
4531 (if (< arg 0) (setq arg (+ level arg)))
4532 (while (> (setq level (org-outline-level)) arg)
4533 (outline-up-heading 1 t)))
4534 (setq beg (point)
4535 heading (org-get-heading))
4536 (org-end-of-subtree t) (setq end (point)))
4537 (if (and (buffer-live-p org-last-indirect-buffer)
4538 (not (eq org-indirect-buffer-display 'new-frame))
4539 (not arg))
4540 (kill-buffer org-last-indirect-buffer))
4541 (setq ibuf (org-get-indirect-buffer cbuf)
4542 org-last-indirect-buffer ibuf)
4543 (cond
4544 ((or (eq org-indirect-buffer-display 'new-frame)
4545 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4546 (select-frame (make-frame))
4547 (delete-other-windows)
4548 (switch-to-buffer ibuf)
4549 (org-set-frame-title heading))
4550 ((eq org-indirect-buffer-display 'dedicated-frame)
4551 (raise-frame
4552 (select-frame (or (and org-indirect-dedicated-frame
4553 (frame-live-p org-indirect-dedicated-frame)
4554 org-indirect-dedicated-frame)
4555 (setq org-indirect-dedicated-frame (make-frame)))))
4556 (delete-other-windows)
4557 (switch-to-buffer ibuf)
4558 (org-set-frame-title (concat "Indirect: " heading)))
4559 ((eq org-indirect-buffer-display 'current-window)
4560 (switch-to-buffer ibuf))
4561 ((eq org-indirect-buffer-display 'other-window)
4562 (pop-to-buffer ibuf))
4563 (t (error "Invalid value.")))
4564 (if (featurep 'xemacs)
4565 (save-excursion (org-mode) (turn-on-font-lock)))
4566 (narrow-to-region beg end)
4567 (show-all)
4568 (goto-char pos)
4569 (and (window-live-p cwin) (select-window cwin))))
4571 (defun org-get-indirect-buffer (&optional buffer)
4572 (setq buffer (or buffer (current-buffer)))
4573 (let ((n 1) (base (buffer-name buffer)) bname)
4574 (while (buffer-live-p
4575 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4576 (setq n (1+ n)))
4577 (condition-case nil
4578 (make-indirect-buffer buffer bname 'clone)
4579 (error (make-indirect-buffer buffer bname)))))
4581 (defun org-set-frame-title (title)
4582 "Set the title of the current frame to the string TITLE."
4583 ;; FIXME: how to name a single frame in XEmacs???
4584 (unless (featurep 'xemacs)
4585 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4587 ;;;; Structure editing
4589 ;;; Inserting headlines
4591 (defun org-insert-heading (&optional force-heading)
4592 "Insert a new heading or item with same depth at point.
4593 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4594 If point is at the beginning of a headline, insert a sibling before the
4595 current headline. If point is not at the beginning, do not split the line,
4596 but create the new hedline after the current line."
4597 (interactive "P")
4598 (if (= (buffer-size) 0)
4599 (insert "\n* ")
4600 (when (or force-heading (not (org-insert-item)))
4601 (let* ((head (save-excursion
4602 (condition-case nil
4603 (progn
4604 (org-back-to-heading)
4605 (match-string 0))
4606 (error "*"))))
4607 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4608 pos)
4609 (cond
4610 ((and (org-on-heading-p) (bolp)
4611 (or (bobp)
4612 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4613 ;; insert before the current line
4614 (open-line (if blank 2 1)))
4615 ((and (bolp)
4616 (or (bobp)
4617 (save-excursion
4618 (backward-char 1) (not (org-invisible-p)))))
4619 ;; insert right here
4620 nil)
4622 ;; in the middle of the line
4623 (org-show-entry)
4624 (let ((split
4625 (org-get-alist-option org-M-RET-may-split-line 'headline))
4626 tags pos)
4627 (cond
4628 (org-insert-heading-respect-content
4629 (org-end-of-subtree nil t)
4630 (open-line 1))
4631 ((org-on-heading-p)
4632 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4633 (setq tags (and (match-end 2) (match-string 2)))
4634 (and (match-end 1)
4635 (delete-region (match-beginning 1) (match-end 1)))
4636 (setq pos (point-at-bol))
4637 (or split (end-of-line 1))
4638 (delete-horizontal-space)
4639 (newline (if blank 2 1))
4640 (when tags
4641 (save-excursion
4642 (goto-char pos)
4643 (end-of-line 1)
4644 (insert " " tags)
4645 (org-set-tags nil 'align))))
4647 (or split (end-of-line 1))
4648 (newline (if blank 2 1)))))))
4649 (insert head) (just-one-space)
4650 (setq pos (point))
4651 (end-of-line 1)
4652 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4653 (run-hooks 'org-insert-heading-hook)))))
4655 (defun org-get-heading (&optional no-tags)
4656 "Return the heading of the current entry, without the stars."
4657 (save-excursion
4658 (org-back-to-heading t)
4659 (if (looking-at
4660 (if no-tags
4661 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4662 "\\*+[ \t]+\\([^\r\n]*\\)"))
4663 (match-string 1) "")))
4665 (defun org-insert-heading-after-current ()
4666 "Insert a new heading with same level as current, after current subtree."
4667 (interactive)
4668 (org-back-to-heading)
4669 (org-insert-heading)
4670 (org-move-subtree-down)
4671 (end-of-line 1))
4673 (defun org-insert-heading-respect-content ()
4674 (interactive)
4675 (let ((org-insert-heading-respect-content t))
4676 (call-interactively 'org-insert-heading)))
4678 (defun org-insert-todo-heading-respect-content ()
4679 (interactive)
4680 (let ((org-insert-heading-respect-content t))
4681 (call-interactively 'org-insert-todo-heading)))
4683 (defun org-insert-todo-heading (arg)
4684 "Insert a new heading with the same level and TODO state as current heading.
4685 If the heading has no TODO state, or if the state is DONE, use the first
4686 state (TODO by default). Also with prefix arg, force first state."
4687 (interactive "P")
4688 (when (not (org-insert-item 'checkbox))
4689 (org-insert-heading)
4690 (save-excursion
4691 (org-back-to-heading)
4692 (outline-previous-heading)
4693 (looking-at org-todo-line-regexp))
4694 (if (or arg
4695 (not (match-beginning 2))
4696 (member (match-string 2) org-done-keywords))
4697 (insert (car org-todo-keywords-1) " ")
4698 (insert (match-string 2) " "))
4699 (when org-provide-todo-statistics
4700 (org-update-parent-todo-statistics))))
4702 (defun org-insert-subheading (arg)
4703 "Insert a new subheading and demote it.
4704 Works for outline headings and for plain lists alike."
4705 (interactive "P")
4706 (org-insert-heading arg)
4707 (cond
4708 ((org-on-heading-p) (org-do-demote))
4709 ((org-at-item-p) (org-indent-item 1))))
4711 (defun org-insert-todo-subheading (arg)
4712 "Insert a new subheading with TODO keyword or checkbox and demote it.
4713 Works for outline headings and for plain lists alike."
4714 (interactive "P")
4715 (org-insert-todo-heading arg)
4716 (cond
4717 ((org-on-heading-p) (org-do-demote))
4718 ((org-at-item-p) (org-indent-item 1))))
4720 ;;; Promotion and Demotion
4722 (defun org-promote-subtree ()
4723 "Promote the entire subtree.
4724 See also `org-promote'."
4725 (interactive)
4726 (save-excursion
4727 (org-map-tree 'org-promote))
4728 (org-fix-position-after-promote))
4730 (defun org-demote-subtree ()
4731 "Demote the entire subtree. See `org-demote'.
4732 See also `org-promote'."
4733 (interactive)
4734 (save-excursion
4735 (org-map-tree 'org-demote))
4736 (org-fix-position-after-promote))
4739 (defun org-do-promote ()
4740 "Promote the current heading higher up the tree.
4741 If the region is active in `transient-mark-mode', promote all headings
4742 in the region."
4743 (interactive)
4744 (save-excursion
4745 (if (org-region-active-p)
4746 (org-map-region 'org-promote (region-beginning) (region-end))
4747 (org-promote)))
4748 (org-fix-position-after-promote))
4750 (defun org-do-demote ()
4751 "Demote the current heading lower down the tree.
4752 If the region is active in `transient-mark-mode', demote all headings
4753 in the region."
4754 (interactive)
4755 (save-excursion
4756 (if (org-region-active-p)
4757 (org-map-region 'org-demote (region-beginning) (region-end))
4758 (org-demote)))
4759 (org-fix-position-after-promote))
4761 (defun org-fix-position-after-promote ()
4762 "Make sure that after pro/demotion cursor position is right."
4763 (let ((pos (point)))
4764 (when (save-excursion
4765 (beginning-of-line 1)
4766 (looking-at org-todo-line-regexp)
4767 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4768 (cond ((eobp) (insert " "))
4769 ((eolp) (insert " "))
4770 ((equal (char-after) ?\ ) (forward-char 1))))))
4772 (defun org-reduced-level (l)
4773 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4775 (defun org-get-valid-level (level &optional change)
4776 "Rectify a level change under the influence of `org-odd-levels-only'
4777 LEVEL is a current level, CHANGE is by how much the level should be
4778 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4779 even level numbers will become the next higher odd number."
4780 (if org-odd-levels-only
4781 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4782 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4783 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4784 (max 1 (+ level change))))
4786 (if (boundp 'define-obsolete-function-alias)
4787 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4788 (define-obsolete-function-alias 'org-get-legal-level
4789 'org-get-valid-level)
4790 (define-obsolete-function-alias 'org-get-legal-level
4791 'org-get-valid-level "23.1")))
4793 (defun org-promote ()
4794 "Promote the current heading higher up the tree.
4795 If the region is active in `transient-mark-mode', promote all headings
4796 in the region."
4797 (org-back-to-heading t)
4798 (let* ((level (save-match-data (funcall outline-level)))
4799 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4800 (diff (abs (- level (length up-head) -1))))
4801 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4802 (replace-match up-head nil t)
4803 ;; Fixup tag positioning
4804 (and org-auto-align-tags (org-set-tags nil t))
4805 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4807 (defun org-demote ()
4808 "Demote the current heading lower down the tree.
4809 If the region is active in `transient-mark-mode', demote all headings
4810 in the region."
4811 (org-back-to-heading t)
4812 (let* ((level (save-match-data (funcall outline-level)))
4813 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4814 (diff (abs (- level (length down-head) -1))))
4815 (replace-match down-head nil t)
4816 ;; Fixup tag positioning
4817 (and org-auto-align-tags (org-set-tags nil t))
4818 (if org-adapt-indentation (org-fixup-indentation diff))))
4820 (defun org-map-tree (fun)
4821 "Call FUN for every heading underneath the current one."
4822 (org-back-to-heading)
4823 (let ((level (funcall outline-level)))
4824 (save-excursion
4825 (funcall fun)
4826 (while (and (progn
4827 (outline-next-heading)
4828 (> (funcall outline-level) level))
4829 (not (eobp)))
4830 (funcall fun)))))
4832 (defun org-map-region (fun beg end)
4833 "Call FUN for every heading between BEG and END."
4834 (let ((org-ignore-region t))
4835 (save-excursion
4836 (setq end (copy-marker end))
4837 (goto-char beg)
4838 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4839 (< (point) end))
4840 (funcall fun))
4841 (while (and (progn
4842 (outline-next-heading)
4843 (< (point) end))
4844 (not (eobp)))
4845 (funcall fun)))))
4847 (defun org-fixup-indentation (diff)
4848 "Change the indentation in the current entry by DIFF
4849 However, if any line in the current entry has no indentation, or if it
4850 would end up with no indentation after the change, nothing at all is done."
4851 (save-excursion
4852 (let ((end (save-excursion (outline-next-heading)
4853 (point-marker)))
4854 (prohibit (if (> diff 0)
4855 "^\\S-"
4856 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4857 col)
4858 (unless (save-excursion (end-of-line 1)
4859 (re-search-forward prohibit end t))
4860 (while (and (< (point) end)
4861 (re-search-forward "^[ \t]+" end t))
4862 (goto-char (match-end 0))
4863 (setq col (current-column))
4864 (if (< diff 0) (replace-match ""))
4865 (indent-to (+ diff col))))
4866 (move-marker end nil))))
4868 (defun org-convert-to-odd-levels ()
4869 "Convert an org-mode file with all levels allowed to one with odd levels.
4870 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4871 level 5 etc."
4872 (interactive)
4873 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4874 (let ((org-odd-levels-only nil) n)
4875 (save-excursion
4876 (goto-char (point-min))
4877 (while (re-search-forward "^\\*\\*+ " nil t)
4878 (setq n (- (length (match-string 0)) 2))
4879 (while (>= (setq n (1- n)) 0)
4880 (org-demote))
4881 (end-of-line 1))))))
4884 (defun org-convert-to-oddeven-levels ()
4885 "Convert an org-mode file with only odd levels to one with odd and even levels.
4886 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4887 section with an even level, conversion would destroy the structure of the file. An error
4888 is signaled in this case."
4889 (interactive)
4890 (goto-char (point-min))
4891 ;; First check if there are no even levels
4892 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4893 (org-show-context t)
4894 (error "Not all levels are odd in this file. Conversion not possible."))
4895 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4896 (let ((org-odd-levels-only nil) n)
4897 (save-excursion
4898 (goto-char (point-min))
4899 (while (re-search-forward "^\\*\\*+ " nil t)
4900 (setq n (/ (1- (length (match-string 0))) 2))
4901 (while (>= (setq n (1- n)) 0)
4902 (org-promote))
4903 (end-of-line 1))))))
4905 (defun org-tr-level (n)
4906 "Make N odd if required."
4907 (if org-odd-levels-only (1+ (/ n 2)) n))
4909 ;;; Vertical tree motion, cutting and pasting of subtrees
4911 (defun org-move-subtree-up (&optional arg)
4912 "Move the current subtree up past ARG headlines of the same level."
4913 (interactive "p")
4914 (org-move-subtree-down (- (prefix-numeric-value arg))))
4916 (defun org-move-subtree-down (&optional arg)
4917 "Move the current subtree down past ARG headlines of the same level."
4918 (interactive "p")
4919 (setq arg (prefix-numeric-value arg))
4920 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4921 'outline-get-last-sibling))
4922 (ins-point (make-marker))
4923 (cnt (abs arg))
4924 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4925 ;; Select the tree
4926 (org-back-to-heading)
4927 (setq beg0 (point))
4928 (save-excursion
4929 (setq ne-beg (org-back-over-empty-lines))
4930 (setq beg (point)))
4931 (save-match-data
4932 (save-excursion (outline-end-of-heading)
4933 (setq folded (org-invisible-p)))
4934 (outline-end-of-subtree))
4935 (outline-next-heading)
4936 (setq ne-end (org-back-over-empty-lines))
4937 (setq end (point))
4938 (goto-char beg0)
4939 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4940 ;; include less whitespace
4941 (save-excursion
4942 (goto-char beg)
4943 (forward-line (- ne-beg ne-end))
4944 (setq beg (point))))
4945 ;; Find insertion point, with error handling
4946 (while (> cnt 0)
4947 (or (and (funcall movfunc) (looking-at outline-regexp))
4948 (progn (goto-char beg0)
4949 (error "Cannot move past superior level or buffer limit")))
4950 (setq cnt (1- cnt)))
4951 (if (> arg 0)
4952 ;; Moving forward - still need to move over subtree
4953 (progn (org-end-of-subtree t t)
4954 (save-excursion
4955 (org-back-over-empty-lines)
4956 (or (bolp) (newline)))))
4957 (setq ne-ins (org-back-over-empty-lines))
4958 (move-marker ins-point (point))
4959 (setq txt (buffer-substring beg end))
4960 (org-save-markers-in-region beg end)
4961 (delete-region beg end)
4962 (outline-flag-region (1- beg) beg nil)
4963 (outline-flag-region (1- (point)) (point) nil)
4964 (let ((bbb (point)))
4965 (insert-before-markers txt)
4966 (org-reinstall-markers-in-region bbb)
4967 (move-marker ins-point bbb))
4968 (or (bolp) (insert "\n"))
4969 (setq ins-end (point))
4970 (goto-char ins-point)
4971 (org-skip-whitespace)
4972 (when (and (< arg 0)
4973 (org-first-sibling-p)
4974 (> ne-ins ne-beg))
4975 ;; Move whitespace back to beginning
4976 (save-excursion
4977 (goto-char ins-end)
4978 (let ((kill-whole-line t))
4979 (kill-line (- ne-ins ne-beg)) (point)))
4980 (insert (make-string (- ne-ins ne-beg) ?\n)))
4981 (move-marker ins-point nil)
4982 (org-compact-display-after-subtree-move)
4983 (org-show-empty-lines-in-parent)
4984 (unless folded
4985 (org-show-entry)
4986 (show-children)
4987 (org-cycle-hide-drawers 'children))))
4989 (defvar org-subtree-clip ""
4990 "Clipboard for cut and paste of subtrees.
4991 This is actually only a copy of the kill, because we use the normal kill
4992 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4994 (defvar org-subtree-clip-folded nil
4995 "Was the last copied subtree folded?
4996 This is used to fold the tree back after pasting.")
4998 (defun org-cut-subtree (&optional n)
4999 "Cut the current subtree into the clipboard.
5000 With prefix arg N, cut this many sequential subtrees.
5001 This is a short-hand for marking the subtree and then cutting it."
5002 (interactive "p")
5003 (org-copy-subtree n 'cut))
5005 (defun org-copy-subtree (&optional n cut force-store-markers)
5006 "Cut the current subtree into the clipboard.
5007 With prefix arg N, cut this many sequential subtrees.
5008 This is a short-hand for marking the subtree and then copying it.
5009 If CUT is non-nil, actually cut the subtree.
5010 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5011 of some markers in the region, even if CUT is non-nil. This is
5012 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5013 (interactive "p")
5014 (let (beg end folded (beg0 (point)))
5015 (if (interactive-p)
5016 (org-back-to-heading nil) ; take what looks like a subtree
5017 (org-back-to-heading t)) ; take what is really there
5018 (org-back-over-empty-lines)
5019 (setq beg (point))
5020 (skip-chars-forward " \t\r\n")
5021 (save-match-data
5022 (save-excursion (outline-end-of-heading)
5023 (setq folded (org-invisible-p)))
5024 (condition-case nil
5025 (outline-forward-same-level (1- n))
5026 (error nil))
5027 (org-end-of-subtree t t))
5028 (org-back-over-empty-lines)
5029 (setq end (point))
5030 (goto-char beg0)
5031 (when (> end beg)
5032 (setq org-subtree-clip-folded folded)
5033 (when (or cut force-store-markers)
5034 (org-save-markers-in-region beg end))
5035 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5036 (setq org-subtree-clip (current-kill 0))
5037 (message "%s: Subtree(s) with %d characters"
5038 (if cut "Cut" "Copied")
5039 (length org-subtree-clip)))))
5041 (defun org-paste-subtree (&optional level tree)
5042 "Paste the clipboard as a subtree, with modification of headline level.
5043 The entire subtree is promoted or demoted in order to match a new headline
5044 level. By default, the new level is derived from the visible headings
5045 before and after the insertion point, and taken to be the inferior headline
5046 level of the two. So if the previous visible heading is level 3 and the
5047 next is level 4 (or vice versa), level 4 will be used for insertion.
5048 This makes sure that the subtree remains an independent subtree and does
5049 not swallow low level entries.
5051 You can also force a different level, either by using a numeric prefix
5052 argument, or by inserting the heading marker by hand. For example, if the
5053 cursor is after \"*****\", then the tree will be shifted to level 5.
5055 If you want to insert the tree as is, just use \\[yank].
5057 If optional TREE is given, use this text instead of the kill ring."
5058 (interactive "P")
5059 (unless (org-kill-is-subtree-p tree)
5060 (error "%s"
5061 (substitute-command-keys
5062 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5063 (let* ((visp (not (org-invisible-p)))
5064 (txt (or tree (and kill-ring (current-kill 0))))
5065 (^re (concat "^\\(" outline-regexp "\\)"))
5066 (re (concat "\\(" outline-regexp "\\)"))
5067 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5069 (old-level (if (string-match ^re txt)
5070 (- (match-end 0) (match-beginning 0) 1)
5071 -1))
5072 (force-level (cond (level (prefix-numeric-value level))
5073 ((string-match
5074 ^re_ (buffer-substring (point-at-bol) (point)))
5075 (- (match-end 1) (match-beginning 1)))
5076 (t nil)))
5077 (previous-level (save-excursion
5078 (condition-case nil
5079 (progn
5080 (outline-previous-visible-heading 1)
5081 (if (looking-at re)
5082 (- (match-end 0) (match-beginning 0) 1)
5084 (error 1))))
5085 (next-level (save-excursion
5086 (condition-case nil
5087 (progn
5088 (or (looking-at outline-regexp)
5089 (outline-next-visible-heading 1))
5090 (if (looking-at re)
5091 (- (match-end 0) (match-beginning 0) 1)
5093 (error 1))))
5094 (new-level (or force-level (max previous-level next-level)))
5095 (shift (if (or (= old-level -1)
5096 (= new-level -1)
5097 (= old-level new-level))
5099 (- new-level old-level)))
5100 (delta (if (> shift 0) -1 1))
5101 (func (if (> shift 0) 'org-demote 'org-promote))
5102 (org-odd-levels-only nil)
5103 beg end)
5104 ;; Remove the forced level indicator
5105 (if force-level
5106 (delete-region (point-at-bol) (point)))
5107 ;; Paste
5108 (beginning-of-line 1)
5109 (org-back-over-empty-lines)
5110 (setq beg (point))
5111 (insert-before-markers txt)
5112 (unless (string-match "\n\\'" txt) (insert "\n"))
5113 (org-reinstall-markers-in-region beg)
5114 (setq end (point))
5115 (goto-char beg)
5116 (skip-chars-forward " \t\n\r")
5117 (setq beg (point))
5118 (if (and (org-invisible-p) visp)
5119 (save-excursion (outline-show-heading)))
5120 ;; Shift if necessary
5121 (unless (= shift 0)
5122 (save-restriction
5123 (narrow-to-region beg end)
5124 (while (not (= shift 0))
5125 (org-map-region func (point-min) (point-max))
5126 (setq shift (+ delta shift)))
5127 (goto-char (point-min))))
5128 (when (interactive-p)
5129 (message "Clipboard pasted as level %d subtree" new-level))
5130 (if (and kill-ring
5131 (eq org-subtree-clip (current-kill 0))
5132 org-subtree-clip-folded)
5133 ;; The tree was folded before it was killed/copied
5134 (hide-subtree))))
5136 (defun org-kill-is-subtree-p (&optional txt)
5137 "Check if the current kill is an outline subtree, or a set of trees.
5138 Returns nil if kill does not start with a headline, or if the first
5139 headline level is not the largest headline level in the tree.
5140 So this will actually accept several entries of equal levels as well,
5141 which is OK for `org-paste-subtree'.
5142 If optional TXT is given, check this string instead of the current kill."
5143 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5144 (start-level (and kill
5145 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5146 org-outline-regexp "\\)")
5147 kill)
5148 (- (match-end 2) (match-beginning 2) 1)))
5149 (re (concat "^" org-outline-regexp))
5150 (start (1+ (or (match-beginning 2) -1))))
5151 (if (not start-level)
5152 (progn
5153 nil) ;; does not even start with a heading
5154 (catch 'exit
5155 (while (setq start (string-match re kill (1+ start)))
5156 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5157 (throw 'exit nil)))
5158 t))))
5160 (defvar org-markers-to-move nil
5161 "Markers that should be moved with a cut-and-paste operation.
5162 Those markers are stored together with their positions relative to
5163 the start of the region.")
5165 (defun org-save-markers-in-region (beg end)
5166 "Check markers in region.
5167 If these markers are between BEG and END, record their position relative
5168 to BEG, so that after moving the block of text, we can put the markers back
5169 into place.
5170 This function gets called just before an entry or tree gets cut from the
5171 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5172 called immediately, to move the markers with the entries."
5173 (setq org-markers-to-move nil)
5174 (when (featurep 'org-clock)
5175 (org-clock-save-markers-for-cut-and-paste beg end))
5176 (when (featurep 'org-agenda)
5177 (org-agenda-save-markers-for-cut-and-paste beg end)))
5179 (defun org-check-and-save-marker (marker beg end)
5180 "Check if MARKER is between BEG and END.
5181 If yes, remember the marker and the distance to BEG."
5182 (when (and (marker-buffer marker)
5183 (equal (marker-buffer marker) (current-buffer)))
5184 (if (and (>= marker beg) (< marker end))
5185 (push (cons marker (- marker beg)) org-markers-to-move))))
5187 (defun org-reinstall-markers-in-region (beg)
5188 "Move all remembered markers to their position relative to BEG."
5189 (mapc (lambda (x)
5190 (move-marker (car x) (+ beg (cdr x))))
5191 org-markers-to-move)
5192 (setq org-markers-to-move nil))
5194 (defun org-narrow-to-subtree ()
5195 "Narrow buffer to the current subtree."
5196 (interactive)
5197 (save-excursion
5198 (save-match-data
5199 (narrow-to-region
5200 (progn (org-back-to-heading) (point))
5201 (progn (org-end-of-subtree t) (point))))))
5204 ;;; Outline Sorting
5206 (defun org-sort (with-case)
5207 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5208 Optional argument WITH-CASE means sort case-sensitively."
5209 (interactive "P")
5210 (if (org-at-table-p)
5211 (org-call-with-arg 'org-table-sort-lines with-case)
5212 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5214 (defun org-sort-remove-invisible (s)
5215 (remove-text-properties 0 (length s) org-rm-props s)
5216 (while (string-match org-bracket-link-regexp s)
5217 (setq s (replace-match (if (match-end 2)
5218 (match-string 3 s)
5219 (match-string 1 s)) t t s)))
5222 (defvar org-priority-regexp) ; defined later in the file
5224 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5225 "Sort entries on a certain level of an outline tree.
5226 If there is an active region, the entries in the region are sorted.
5227 Else, if the cursor is before the first entry, sort the top-level items.
5228 Else, the children of the entry at point are sorted.
5230 Sorting can be alphabetically, numerically, and by date/time as given by
5231 the first time stamp in the entry. The command prompts for the sorting
5232 type unless it has been given to the function through the SORTING-TYPE
5233 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5234 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5235 called with point at the beginning of the record. It must return either
5236 a string or a number that should serve as the sorting key for that record.
5238 Comparing entries ignores case by default. However, with an optional argument
5239 WITH-CASE, the sorting considers case as well."
5240 (interactive "P")
5241 (let ((case-func (if with-case 'identity 'downcase))
5242 start beg end stars re re2
5243 txt what tmp plain-list-p)
5244 ;; Find beginning and end of region to sort
5245 (cond
5246 ((org-region-active-p)
5247 ;; we will sort the region
5248 (setq end (region-end)
5249 what "region")
5250 (goto-char (region-beginning))
5251 (if (not (org-on-heading-p)) (outline-next-heading))
5252 (setq start (point)))
5253 ((org-at-item-p)
5254 ;; we will sort this plain list
5255 (org-beginning-of-item-list) (setq start (point))
5256 (org-end-of-item-list) (setq end (point))
5257 (goto-char start)
5258 (setq plain-list-p t
5259 what "plain list"))
5260 ((or (org-on-heading-p)
5261 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5262 ;; we will sort the children of the current headline
5263 (org-back-to-heading)
5264 (setq start (point)
5265 end (progn (org-end-of-subtree t t)
5266 (org-back-over-empty-lines)
5267 (point))
5268 what "children")
5269 (goto-char start)
5270 (show-subtree)
5271 (outline-next-heading))
5273 ;; we will sort the top-level entries in this file
5274 (goto-char (point-min))
5275 (or (org-on-heading-p) (outline-next-heading))
5276 (setq start (point) end (point-max) what "top-level")
5277 (goto-char start)
5278 (show-all)))
5280 (setq beg (point))
5281 (if (>= beg end) (error "Nothing to sort"))
5283 (unless plain-list-p
5284 (looking-at "\\(\\*+\\)")
5285 (setq stars (match-string 1)
5286 re (concat "^" (regexp-quote stars) " +")
5287 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5288 txt (buffer-substring beg end))
5289 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5290 (if (and (not (equal stars "*")) (string-match re2 txt))
5291 (error "Region to sort contains a level above the first entry")))
5293 (unless sorting-type
5294 (message
5295 (if plain-list-p
5296 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5297 "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:")
5298 what)
5299 (setq sorting-type (read-char-exclusive))
5301 (and (= (downcase sorting-type) ?f)
5302 (setq getkey-func
5303 (completing-read "Sort using function: "
5304 obarray 'fboundp t nil nil))
5305 (setq getkey-func (intern getkey-func)))
5307 (and (= (downcase sorting-type) ?r)
5308 (setq property
5309 (completing-read "Property: "
5310 (mapcar 'list (org-buffer-property-keys t))
5311 nil t))))
5313 (message "Sorting entries...")
5315 (save-restriction
5316 (narrow-to-region start end)
5318 (let ((dcst (downcase sorting-type))
5319 (now (current-time)))
5320 (sort-subr
5321 (/= dcst sorting-type)
5322 ;; This function moves to the beginning character of the "record" to
5323 ;; be sorted.
5324 (if plain-list-p
5325 (lambda nil
5326 (if (org-at-item-p) t (goto-char (point-max))))
5327 (lambda nil
5328 (if (re-search-forward re nil t)
5329 (goto-char (match-beginning 0))
5330 (goto-char (point-max)))))
5331 ;; This function moves to the last character of the "record" being
5332 ;; sorted.
5333 (if plain-list-p
5334 'org-end-of-item
5335 (lambda nil
5336 (save-match-data
5337 (condition-case nil
5338 (outline-forward-same-level 1)
5339 (error
5340 (goto-char (point-max)))))))
5342 ;; This function returns the value that gets sorted against.
5343 (if plain-list-p
5344 (lambda nil
5345 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5346 (cond
5347 ((= dcst ?n)
5348 (string-to-number (buffer-substring (match-end 0)
5349 (point-at-eol))))
5350 ((= dcst ?a)
5351 (buffer-substring (match-end 0) (point-at-eol)))
5352 ((= dcst ?t)
5353 (if (re-search-forward org-ts-regexp
5354 (point-at-eol) t)
5355 (org-time-string-to-time (match-string 0))
5356 now))
5357 ((= dcst ?f)
5358 (if getkey-func
5359 (progn
5360 (setq tmp (funcall getkey-func))
5361 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5362 tmp)
5363 (error "Invalid key function `%s'" getkey-func)))
5364 (t (error "Invalid sorting type `%c'" sorting-type)))))
5365 (lambda nil
5366 (cond
5367 ((= dcst ?n)
5368 (if (looking-at org-complex-heading-regexp)
5369 (string-to-number (match-string 4))
5370 nil))
5371 ((= dcst ?a)
5372 (if (looking-at org-complex-heading-regexp)
5373 (funcall case-func (match-string 4))
5374 nil))
5375 ((= dcst ?t)
5376 (if (re-search-forward org-ts-regexp
5377 (save-excursion
5378 (forward-line 2)
5379 (point)) t)
5380 (org-time-string-to-time (match-string 0))
5381 now))
5382 ((= dcst ?p)
5383 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5384 (string-to-char (match-string 2))
5385 org-default-priority))
5386 ((= dcst ?r)
5387 (or (org-entry-get nil property) ""))
5388 ((= dcst ?o)
5389 (if (looking-at org-complex-heading-regexp)
5390 (- 9999 (length (member (match-string 2)
5391 org-todo-keywords-1)))))
5392 ((= dcst ?f)
5393 (if getkey-func
5394 (progn
5395 (setq tmp (funcall getkey-func))
5396 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5397 tmp)
5398 (error "Invalid key function `%s'" getkey-func)))
5399 (t (error "Invalid sorting type `%c'" sorting-type)))))
5401 (cond
5402 ((= dcst ?a) 'string<)
5403 ((= dcst ?t) 'time-less-p)
5404 (t nil)))))
5405 (message "Sorting entries...done")))
5407 (defun org-do-sort (table what &optional with-case sorting-type)
5408 "Sort TABLE of WHAT according to SORTING-TYPE.
5409 The user will be prompted for the SORTING-TYPE if the call to this
5410 function does not specify it. WHAT is only for the prompt, to indicate
5411 what is being sorted. The sorting key will be extracted from
5412 the car of the elements of the table.
5413 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5414 (unless sorting-type
5415 (message
5416 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5417 what)
5418 (setq sorting-type (read-char-exclusive)))
5419 (let ((dcst (downcase sorting-type))
5420 extractfun comparefun)
5421 ;; Define the appropriate functions
5422 (cond
5423 ((= dcst ?n)
5424 (setq extractfun 'string-to-number
5425 comparefun (if (= dcst sorting-type) '< '>)))
5426 ((= dcst ?a)
5427 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5428 (lambda(x) (downcase (org-sort-remove-invisible x))))
5429 comparefun (if (= dcst sorting-type)
5430 'string<
5431 (lambda (a b) (and (not (string< a b))
5432 (not (string= a b)))))))
5433 ((= dcst ?t)
5434 (setq extractfun
5435 (lambda (x)
5436 (if (string-match org-ts-regexp x)
5437 (time-to-seconds
5438 (org-time-string-to-time (match-string 0 x)))
5440 comparefun (if (= dcst sorting-type) '< '>)))
5441 (t (error "Invalid sorting type `%c'" sorting-type)))
5443 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5444 table)
5445 (lambda (a b) (funcall comparefun (car a) (car b))))))
5447 ;;; Editing source examples
5449 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5450 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5451 (defvar org-edit-src-force-single-line nil)
5452 (defvar org-edit-src-from-org-mode nil)
5453 (defvar org-edit-src-picture nil)
5455 (define-minor-mode org-exit-edit-mode
5456 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5458 (defun org-edit-src-code ()
5459 "Edit the source code example at point.
5460 An indirect buffer is created, and that buffer is then narrowed to the
5461 example at point and switched to the correct language mode. When done,
5462 exit by killing the buffer with \\[org-edit-src-exit]."
5463 (interactive)
5464 (let ((line (org-current-line))
5465 (case-fold-search t)
5466 (msg (substitute-command-keys
5467 "Edit, then exit with C-c ' (C-c and single quote)"))
5468 (info (org-edit-src-find-region-and-lang))
5469 (org-mode-p (eq major-mode 'org-mode))
5470 beg end lang lang-f single)
5471 (if (not info)
5473 (setq beg (nth 0 info)
5474 end (nth 1 info)
5475 lang (nth 2 info)
5476 single (nth 3 info)
5477 lang-f (intern (concat lang "-mode")))
5478 (unless (functionp lang-f)
5479 (error "No such language mode: %s" lang-f))
5480 (goto-line line)
5481 (if (get-buffer "*Org Edit Src Example*")
5482 (kill-buffer "*Org Edit Src Example*"))
5483 (switch-to-buffer (make-indirect-buffer (current-buffer)
5484 "*Org Edit Src Example*"))
5485 (narrow-to-region beg end)
5486 (remove-text-properties beg end '(display nil invisible nil
5487 intangible nil))
5488 (let ((org-inhibit-startup t))
5489 (funcall lang-f))
5490 (set (make-local-variable 'org-edit-src-force-single-line) single)
5491 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5492 (when org-mode-p
5493 (goto-char (point-min))
5494 (while (re-search-forward "^," nil t)
5495 (replace-match "")))
5496 (goto-line line)
5497 (org-exit-edit-mode)
5498 (org-set-local 'header-line-format msg)
5499 (message "%s" msg)
5500 t)))
5502 (defun org-edit-fixed-width-region ()
5503 "Edit the fixed-width ascii drawing at point.
5504 This must be a region where each line starts with ca colon followed by
5505 a space character.
5506 An indirect buffer is created, and that buffer is then narrowed to the
5507 example at point and switched to artist-mode. When done,
5508 exit by killing the buffer with \\[org-edit-src-exit]."
5509 (interactive)
5510 (let ((line (org-current-line))
5511 (case-fold-search t)
5512 (msg (substitute-command-keys
5513 "Edit, then exit with C-c ' (C-c and single quote)"))
5514 (org-mode-p (eq major-mode 'org-mode))
5515 beg end lang lang-f)
5516 (beginning-of-line 1)
5517 (if (looking-at "[ \t]*[^:\n \t]")
5519 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5520 (setq beg (point) end (match-end 0))
5521 (save-excursion
5522 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5523 (setq beg (point-at-bol 2))
5524 (setq beg (point))))
5525 (save-excursion
5526 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5527 (setq end (1- (match-beginning 0)))
5528 (setq end (point))))
5529 (goto-line line)
5530 (if (get-buffer "*Org Edit Picture*")
5531 (kill-buffer "*Org Edit Picture*"))
5532 (switch-to-buffer (make-indirect-buffer (current-buffer)
5533 "*Org Edit Picture*"))
5534 (narrow-to-region beg end)
5535 (remove-text-properties beg end '(display nil invisible nil
5536 intangible nil))
5537 (when (fboundp 'font-lock-unfontify-region)
5538 (font-lock-unfontify-region (point-min) (point-max)))
5539 (cond
5540 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5541 (fundamental-mode)
5542 (artist-mode 1))
5543 (t (funcall org-edit-fixed-width-region-mode)))
5544 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5545 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5546 (set (make-local-variable 'org-edit-src-picture) t)
5547 (goto-char (point-min))
5548 (while (re-search-forward "^[ \t]*: " nil t)
5549 (replace-match ""))
5550 (goto-line line)
5551 (org-exit-edit-mode)
5552 (org-set-local 'header-line-format msg)
5553 (message "%s" msg)
5554 t))))
5557 (defun org-edit-src-find-region-and-lang ()
5558 "Find the region and language for a local edit.
5559 Return a list with beginning and end of the region, a string representing
5560 the language, a switch telling of the content should be in a single line."
5561 (let ((re-list
5562 (append
5563 org-edit-src-region-extra
5565 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5566 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5567 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5568 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5569 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5570 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5571 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5572 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5573 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5574 ("^#\\+html:" "\n" "html" single-line)
5575 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5576 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5577 ("^#\\+latex:" "\n" "latex" single-line)
5578 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5579 ("^#\\+ascii:" "\n" "ascii" single-line)
5581 (pos (point))
5582 re re1 re2 single beg end lang)
5583 (catch 'exit
5584 (while (setq entry (pop re-list))
5585 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5586 single (nth 3 entry))
5587 (save-excursion
5588 (if (or (looking-at re1)
5589 (re-search-backward re1 nil t))
5590 (progn
5591 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5592 (if (and (re-search-forward re2 nil t)
5593 (>= (match-end 0) pos))
5594 (throw 'exit (list beg (match-beginning 0) lang single))))
5595 (if (or (looking-at re2)
5596 (re-search-forward re2 nil t))
5597 (progn
5598 (setq end (match-beginning 0))
5599 (if (and (re-search-backward re1 nil t)
5600 (<= (match-beginning 0) pos))
5601 (throw 'exit
5602 (list (match-end 0) end
5603 (org-edit-src-get-lang lang) single)))))))))))
5605 (defun org-edit-src-get-lang (lang)
5606 "Extract the src language."
5607 (let ((m (match-string 0)))
5608 (cond
5609 ((stringp lang) lang)
5610 ((integerp lang) (match-string lang))
5611 ((and (eq lang 'lang)
5612 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5613 (match-string 1 m))
5614 ((and (eq lang 'style)
5615 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5616 (match-string 1 m))
5617 (t "fundamental"))))
5619 (defun org-edit-src-exit ()
5620 "Exit special edit and protect problematic lines."
5621 (interactive)
5622 (unless (buffer-base-buffer (current-buffer))
5623 (error "This is not an indirect buffer, something is wrong..."))
5624 (unless (> (point-min) 1)
5625 (error "This buffer is not narrowed, something is wrong..."))
5626 (goto-char (point-min))
5627 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5628 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5629 (when (org-bound-and-true-p org-edit-src-force-single-line)
5630 (goto-char (point-min))
5631 (while (re-search-forward "\n" nil t)
5632 (replace-match " "))
5633 (goto-char (point-min))
5634 (if (looking-at "\\s-*") (replace-match " "))
5635 (if (re-search-forward "\\s-+\\'" nil t)
5636 (replace-match "")))
5637 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5638 (goto-char (point-min))
5639 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5640 (replace-match ",\\1"))
5641 (when font-lock-mode
5642 (font-lock-unfontify-region (point-min) (point-max)))
5643 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5644 (when (org-bound-and-true-p org-edit-src-picture)
5645 (goto-char (point-min))
5646 (while (re-search-forward "^" nil t)
5647 (replace-match ": "))
5648 (when font-lock-mode
5649 (font-lock-unfontify-region (point-min) (point-max)))
5650 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5651 (kill-buffer (current-buffer))
5652 (and (org-mode-p) (org-restart-font-lock)))
5655 ;;; The orgstruct minor mode
5657 ;; Define a minor mode which can be used in other modes in order to
5658 ;; integrate the org-mode structure editing commands.
5660 ;; This is really a hack, because the org-mode structure commands use
5661 ;; keys which normally belong to the major mode. Here is how it
5662 ;; works: The minor mode defines all the keys necessary to operate the
5663 ;; structure commands, but wraps the commands into a function which
5664 ;; tests if the cursor is currently at a headline or a plain list
5665 ;; item. If that is the case, the structure command is used,
5666 ;; temporarily setting many Org-mode variables like regular
5667 ;; expressions for filling etc. However, when any of those keys is
5668 ;; used at a different location, function uses `key-binding' to look
5669 ;; up if the key has an associated command in another currently active
5670 ;; keymap (minor modes, major mode, global), and executes that
5671 ;; command. There might be problems if any of the keys is otherwise
5672 ;; used as a prefix key.
5674 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5675 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5676 ;; addresses this by checking explicitly for both bindings.
5678 (defvar orgstruct-mode-map (make-sparse-keymap)
5679 "Keymap for the minor `orgstruct-mode'.")
5681 (defvar org-local-vars nil
5682 "List of local variables, for use by `orgstruct-mode'")
5684 ;;;###autoload
5685 (define-minor-mode orgstruct-mode
5686 "Toggle the minor more `orgstruct-mode'.
5687 This mode is for using Org-mode structure commands in other modes.
5688 The following key behave as if Org-mode was active, if the cursor
5689 is on a headline, or on a plain list item (both in the definition
5690 of Org-mode).
5692 M-up Move entry/item up
5693 M-down Move entry/item down
5694 M-left Promote
5695 M-right Demote
5696 M-S-up Move entry/item up
5697 M-S-down Move entry/item down
5698 M-S-left Promote subtree
5699 M-S-right Demote subtree
5700 M-q Fill paragraph and items like in Org-mode
5701 C-c ^ Sort entries
5702 C-c - Cycle list bullet
5703 TAB Cycle item visibility
5704 M-RET Insert new heading/item
5705 S-M-RET Insert new TODO heading / Chekbox item
5706 C-c C-c Set tags / toggle checkbox"
5707 nil " OrgStruct" nil
5708 (org-load-modules-maybe)
5709 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5711 ;;;###autoload
5712 (defun turn-on-orgstruct ()
5713 "Unconditionally turn on `orgstruct-mode'."
5714 (orgstruct-mode 1))
5716 ;;;###autoload
5717 (defun turn-on-orgstruct++ ()
5718 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5719 In addition to setting orgstruct-mode, this also exports all indentation and
5720 autofilling variables from org-mode into the buffer. Note that turning
5721 off orgstruct-mode will *not* remove these additional settings."
5722 (orgstruct-mode 1)
5723 (let (var val)
5724 (mapc
5725 (lambda (x)
5726 (when (string-match
5727 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5728 (symbol-name (car x)))
5729 (setq var (car x) val (nth 1 x))
5730 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5731 org-local-vars)))
5733 (defun orgstruct-error ()
5734 "Error when there is no default binding for a structure key."
5735 (interactive)
5736 (error "This key has no function outside structure elements"))
5738 (defun orgstruct-setup ()
5739 "Setup orgstruct keymaps."
5740 (let ((nfunc 0)
5741 (bindings
5742 (list
5743 '([(meta up)] org-metaup)
5744 '([(meta down)] org-metadown)
5745 '([(meta left)] org-metaleft)
5746 '([(meta right)] org-metaright)
5747 '([(meta shift up)] org-shiftmetaup)
5748 '([(meta shift down)] org-shiftmetadown)
5749 '([(meta shift left)] org-shiftmetaleft)
5750 '([(meta shift right)] org-shiftmetaright)
5751 '([(shift up)] org-shiftup)
5752 '([(shift down)] org-shiftdown)
5753 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5754 '("\M-q" fill-paragraph)
5755 '("\C-c^" org-sort)
5756 '("\C-c-" org-cycle-list-bullet)))
5757 elt key fun cmd)
5758 (while (setq elt (pop bindings))
5759 (setq nfunc (1+ nfunc))
5760 (setq key (org-key (car elt))
5761 fun (nth 1 elt)
5762 cmd (orgstruct-make-binding fun nfunc key))
5763 (org-defkey orgstruct-mode-map key cmd))
5765 ;; Special treatment needed for TAB and RET
5766 (org-defkey orgstruct-mode-map [(tab)]
5767 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5768 (org-defkey orgstruct-mode-map "\C-i"
5769 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5771 (org-defkey orgstruct-mode-map "\M-\C-m"
5772 (orgstruct-make-binding 'org-insert-heading 105
5773 "\M-\C-m" [(meta return)]))
5774 (org-defkey orgstruct-mode-map [(meta return)]
5775 (orgstruct-make-binding 'org-insert-heading 106
5776 [(meta return)] "\M-\C-m"))
5778 (org-defkey orgstruct-mode-map [(shift meta return)]
5779 (orgstruct-make-binding 'org-insert-todo-heading 107
5780 [(meta return)] "\M-\C-m"))
5782 (unless org-local-vars
5783 (setq org-local-vars (org-get-local-variables)))
5787 (defun orgstruct-make-binding (fun n &rest keys)
5788 "Create a function for binding in the structure minor mode.
5789 FUN is the command to call inside a table. N is used to create a unique
5790 command name. KEYS are keys that should be checked in for a command
5791 to execute outside of tables."
5792 (eval
5793 (list 'defun
5794 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5795 '(arg)
5796 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5797 "Outside of structure, run the binding of `"
5798 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5799 "'.")
5800 '(interactive "p")
5801 (list 'if
5802 '(org-context-p 'headline 'item)
5803 (list 'org-run-like-in-org-mode (list 'quote fun))
5804 (list 'let '(orgstruct-mode)
5805 (list 'call-interactively
5806 (append '(or)
5807 (mapcar (lambda (k)
5808 (list 'key-binding k))
5809 keys)
5810 '('orgstruct-error))))))))
5812 (defun org-context-p (&rest contexts)
5813 "Check if local context is any of CONTEXTS.
5814 Possible values in the list of contexts are `table', `headline', and `item'."
5815 (let ((pos (point)))
5816 (goto-char (point-at-bol))
5817 (prog1 (or (and (memq 'table contexts)
5818 (looking-at "[ \t]*|"))
5819 (and (memq 'headline contexts)
5820 ;;????????? (looking-at "\\*+"))
5821 (looking-at outline-regexp))
5822 (and (memq 'item contexts)
5823 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5824 (goto-char pos))))
5826 (defun org-get-local-variables ()
5827 "Return a list of all local variables in an org-mode buffer."
5828 (let (varlist)
5829 (with-current-buffer (get-buffer-create "*Org tmp*")
5830 (erase-buffer)
5831 (org-mode)
5832 (setq varlist (buffer-local-variables)))
5833 (kill-buffer "*Org tmp*")
5834 (delq nil
5835 (mapcar
5836 (lambda (x)
5837 (setq x
5838 (if (symbolp x)
5839 (list x)
5840 (list (car x) (list 'quote (cdr x)))))
5841 (if (string-match
5842 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5843 (symbol-name (car x)))
5844 x nil))
5845 varlist))))
5847 ;;;###autoload
5848 (defun org-run-like-in-org-mode (cmd)
5849 (org-load-modules-maybe)
5850 (unless org-local-vars
5851 (setq org-local-vars (org-get-local-variables)))
5852 (eval (list 'let org-local-vars
5853 (list 'call-interactively (list 'quote cmd)))))
5855 ;;;; Archiving
5857 (defun org-get-category (&optional pos)
5858 "Get the category applying to position POS."
5859 (get-text-property (or pos (point)) 'org-category))
5861 (defun org-refresh-category-properties ()
5862 "Refresh category text properties in the buffer."
5863 (let ((def-cat (cond
5864 ((null org-category)
5865 (if buffer-file-name
5866 (file-name-sans-extension
5867 (file-name-nondirectory buffer-file-name))
5868 "???"))
5869 ((symbolp org-category) (symbol-name org-category))
5870 (t org-category)))
5871 beg end cat pos optionp)
5872 (org-unmodified
5873 (save-excursion
5874 (save-restriction
5875 (widen)
5876 (goto-char (point-min))
5877 (put-text-property (point) (point-max) 'org-category def-cat)
5878 (while (re-search-forward
5879 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5880 (setq pos (match-end 0)
5881 optionp (equal (char-after (match-beginning 0)) ?#)
5882 cat (org-trim (match-string 2)))
5883 (if optionp
5884 (setq beg (point-at-bol) end (point-max))
5885 (org-back-to-heading t)
5886 (setq beg (point) end (org-end-of-subtree t t)))
5887 (put-text-property beg end 'org-category cat)
5888 (goto-char pos)))))))
5891 ;;;; Link Stuff
5893 ;;; Link abbreviations
5895 (defun org-link-expand-abbrev (link)
5896 "Apply replacements as defined in `org-link-abbrev-alist."
5897 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5898 (let* ((key (match-string 1 link))
5899 (as (or (assoc key org-link-abbrev-alist-local)
5900 (assoc key org-link-abbrev-alist)))
5901 (tag (and (match-end 2) (match-string 3 link)))
5902 rpl)
5903 (if (not as)
5904 link
5905 (setq rpl (cdr as))
5906 (cond
5907 ((symbolp rpl) (funcall rpl tag))
5908 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5909 (t (concat rpl tag)))))
5910 link))
5912 ;;; Storing and inserting links
5914 (defvar org-insert-link-history nil
5915 "Minibuffer history for links inserted with `org-insert-link'.")
5917 (defvar org-stored-links nil
5918 "Contains the links stored with `org-store-link'.")
5920 (defvar org-store-link-plist nil
5921 "Plist with info about the most recently link created with `org-store-link'.")
5923 (defvar org-link-protocols nil
5924 "Link protocols added to Org-mode using `org-add-link-type'.")
5926 (defvar org-store-link-functions nil
5927 "List of functions that are called to create and store a link.
5928 Each function will be called in turn until one returns a non-nil
5929 value. Each function should check if it is responsible for creating
5930 this link (for example by looking at the major mode).
5931 If not, it must exit and return nil.
5932 If yes, it should return a non-nil value after a calling
5933 `org-store-link-props' with a list of properties and values.
5934 Special properties are:
5936 :type The link prefix. like \"http\". This must be given.
5937 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5938 This is obligatory as well.
5939 :description Optional default description for the second pair
5940 of brackets in an Org-mode link. The user can still change
5941 this when inserting this link into an Org-mode buffer.
5943 In addition to these, any additional properties can be specified
5944 and then used in remember templates.")
5946 (defun org-add-link-type (type &optional follow export)
5947 "Add TYPE to the list of `org-link-types'.
5948 Re-compute all regular expressions depending on `org-link-types'
5950 FOLLOW and EXPORT are two functions.
5952 FOLLOW should take the link path as the single argument and do whatever
5953 is necessary to follow the link, for example find a file or display
5954 a mail message.
5956 EXPORT should format the link path for export to one of the export formats.
5957 It should be a function accepting three arguments:
5959 path the path of the link, the text after the prefix (like \"http:\")
5960 desc the description of the link, if any, nil if there was no descripton
5961 format the export format, a symbol like `html' or `latex'.
5963 The function may use the FORMAT information to return different values
5964 depending on the format. The return value will be put literally into
5965 the exported file.
5966 Org-mode has a built-in default for exporting links. If you are happy with
5967 this default, there is no need to define an export function for the link
5968 type. For a simple example of an export function, see `org-bbdb.el'."
5969 (add-to-list 'org-link-types type t)
5970 (org-make-link-regexps)
5971 (if (assoc type org-link-protocols)
5972 (setcdr (assoc type org-link-protocols) (list follow export))
5973 (push (list type follow export) org-link-protocols)))
5976 ;;;###autoload
5977 (defun org-store-link (arg)
5978 "\\<org-mode-map>Store an org-link to the current location.
5979 This link is added to `org-stored-links' and can later be inserted
5980 into an org-buffer with \\[org-insert-link].
5982 For some link types, a prefix arg is interpreted:
5983 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5984 For file links, arg negates `org-context-in-file-links'."
5985 (interactive "P")
5986 (org-load-modules-maybe)
5987 (setq org-store-link-plist nil) ; reset
5988 (let (link cpltxt desc description search txt)
5989 (cond
5991 ((run-hook-with-args-until-success 'org-store-link-functions)
5992 (setq link (plist-get org-store-link-plist :link)
5993 desc (or (plist-get org-store-link-plist :description) link)))
5995 ((eq major-mode 'calendar-mode)
5996 (let ((cd (calendar-cursor-to-date)))
5997 (setq link
5998 (format-time-string
5999 (car org-time-stamp-formats)
6000 (apply 'encode-time
6001 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6002 nil nil nil))))
6003 (org-store-link-props :type "calendar" :date cd)))
6005 ((eq major-mode 'w3-mode)
6006 (setq cpltxt (url-view-url t)
6007 link (org-make-link cpltxt))
6008 (org-store-link-props :type "w3" :url (url-view-url t)))
6010 ((eq major-mode 'w3m-mode)
6011 (setq cpltxt (or w3m-current-title w3m-current-url)
6012 link (org-make-link w3m-current-url))
6013 (org-store-link-props :type "w3m" :url (url-view-url t)))
6015 ((setq search (run-hook-with-args-until-success
6016 'org-create-file-search-functions))
6017 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6018 "::" search))
6019 (setq cpltxt (or description link)))
6021 ((eq major-mode 'image-mode)
6022 (setq cpltxt (concat "file:"
6023 (abbreviate-file-name buffer-file-name))
6024 link (org-make-link cpltxt))
6025 (org-store-link-props :type "image" :file buffer-file-name))
6027 ((eq major-mode 'dired-mode)
6028 ;; link to the file in the current line
6029 (setq cpltxt (concat "file:"
6030 (abbreviate-file-name
6031 (expand-file-name
6032 (dired-get-filename nil t))))
6033 link (org-make-link cpltxt)))
6035 ((and buffer-file-name (org-mode-p))
6036 ;; Just link to current headline
6037 (setq cpltxt (concat "file:"
6038 (abbreviate-file-name buffer-file-name)))
6039 ;; Add a context search string
6040 (when (org-xor org-context-in-file-links arg)
6041 ;; Check if we are on a target
6042 (if (org-in-regexp "<<\\(.*?\\)>>")
6043 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6044 (setq txt (cond
6045 ((org-on-heading-p) nil)
6046 ((org-region-active-p)
6047 (buffer-substring (region-beginning) (region-end)))
6048 (t nil)))
6049 (when (or (null txt) (string-match "\\S-" txt))
6050 (setq cpltxt
6051 (concat cpltxt "::"
6052 (condition-case nil
6053 (org-make-org-heading-search-string txt)
6054 (error "")))
6055 desc "NONE"))))
6056 (if (string-match "::\\'" cpltxt)
6057 (setq cpltxt (substring cpltxt 0 -2)))
6058 (setq link (org-make-link cpltxt)))
6060 ((buffer-file-name (buffer-base-buffer))
6061 ;; Just link to this file here.
6062 (setq cpltxt (concat "file:"
6063 (abbreviate-file-name
6064 (buffer-file-name (buffer-base-buffer)))))
6065 ;; Add a context string
6066 (when (org-xor org-context-in-file-links arg)
6067 (setq txt (if (org-region-active-p)
6068 (buffer-substring (region-beginning) (region-end))
6069 (buffer-substring (point-at-bol) (point-at-eol))))
6070 ;; Only use search option if there is some text.
6071 (when (string-match "\\S-" txt)
6072 (setq cpltxt
6073 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6074 desc "NONE")))
6075 (setq link (org-make-link cpltxt)))
6077 ((interactive-p)
6078 (error "Cannot link to a buffer which is not visiting a file"))
6080 (t (setq link nil)))
6082 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6083 (setq link (or link cpltxt)
6084 desc (or desc cpltxt))
6085 (if (equal desc "NONE") (setq desc nil))
6087 (if (and (interactive-p) link)
6088 (progn
6089 (setq org-stored-links
6090 (cons (list link desc) org-stored-links))
6091 (message "Stored: %s" (or desc link)))
6092 (and link (org-make-link-string link desc)))))
6094 (defun org-store-link-props (&rest plist)
6095 "Store link properties, extract names and addresses."
6096 (let (x adr)
6097 (when (setq x (plist-get plist :from))
6098 (setq adr (mail-extract-address-components x))
6099 (plist-put plist :fromname (car adr))
6100 (plist-put plist :fromaddress (nth 1 adr)))
6101 (when (setq x (plist-get plist :to))
6102 (setq adr (mail-extract-address-components x))
6103 (plist-put plist :toname (car adr))
6104 (plist-put plist :toaddress (nth 1 adr))))
6105 (let ((from (plist-get plist :from))
6106 (to (plist-get plist :to)))
6107 (when (and from to org-from-is-user-regexp)
6108 (plist-put plist :fromto
6109 (if (string-match org-from-is-user-regexp from)
6110 (concat "to %t")
6111 (concat "from %f")))))
6112 (setq org-store-link-plist plist))
6114 (defun org-add-link-props (&rest plist)
6115 "Add these properties to the link property list."
6116 (let (key value)
6117 (while plist
6118 (setq key (pop plist) value (pop plist))
6119 (setq org-store-link-plist
6120 (plist-put org-store-link-plist key value)))))
6122 (defun org-email-link-description (&optional fmt)
6123 "Return the description part of an email link.
6124 This takes information from `org-store-link-plist' and formats it
6125 according to FMT (default from `org-email-link-description-format')."
6126 (setq fmt (or fmt org-email-link-description-format))
6127 (let* ((p org-store-link-plist)
6128 (to (plist-get p :toaddress))
6129 (from (plist-get p :fromaddress))
6130 (table
6131 (list
6132 (cons "%c" (plist-get p :fromto))
6133 (cons "%F" (plist-get p :from))
6134 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6135 (cons "%T" (plist-get p :to))
6136 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6137 (cons "%s" (plist-get p :subject))
6138 (cons "%m" (plist-get p :message-id)))))
6139 (when (string-match "%c" fmt)
6140 ;; Check if the user wrote this message
6141 (if (and org-from-is-user-regexp from to
6142 (save-match-data (string-match org-from-is-user-regexp from)))
6143 (setq fmt (replace-match "to %t" t t fmt))
6144 (setq fmt (replace-match "from %f" t t fmt))))
6145 (org-replace-escapes fmt table)))
6147 (defun org-make-org-heading-search-string (&optional string heading)
6148 "Make search string for STRING or current headline."
6149 (interactive)
6150 (let ((s (or string (org-get-heading))))
6151 (unless (and string (not heading))
6152 ;; We are using a headline, clean up garbage in there.
6153 (if (string-match org-todo-regexp s)
6154 (setq s (replace-match "" t t s)))
6155 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6156 (setq s (replace-match "" t t s)))
6157 (setq s (org-trim s))
6158 (if (string-match (concat "^\\(" org-quote-string "\\|"
6159 org-comment-string "\\)") s)
6160 (setq s (replace-match "" t t s)))
6161 (while (string-match org-ts-regexp s)
6162 (setq s (replace-match "" t t s))))
6163 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6164 (setq s (replace-match " " t t s)))
6165 (or string (setq s (concat "*" s))) ; Add * for headlines
6166 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6168 (defun org-make-link (&rest strings)
6169 "Concatenate STRINGS."
6170 (apply 'concat strings))
6172 (defun org-make-link-string (link &optional description)
6173 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6174 (unless (string-match "\\S-" link)
6175 (error "Empty link"))
6176 (when (stringp description)
6177 ;; Remove brackets from the description, they are fatal.
6178 (while (string-match "\\[" description)
6179 (setq description (replace-match "{" t t description)))
6180 (while (string-match "\\]" description)
6181 (setq description (replace-match "}" t t description))))
6182 (when (equal (org-link-escape link) description)
6183 ;; No description needed, it is identical
6184 (setq description nil))
6185 (when (and (not description)
6186 (not (equal link (org-link-escape link))))
6187 (setq description (org-extract-attributes link)))
6188 (concat "[[" (org-link-escape link) "]"
6189 (if description (concat "[" description "]") "")
6190 "]"))
6192 (defconst org-link-escape-chars
6193 '((?\ . "%20")
6194 (?\[ . "%5B")
6195 (?\] . "%5D")
6196 (?\340 . "%E0") ; `a
6197 (?\342 . "%E2") ; ^a
6198 (?\347 . "%E7") ; ,c
6199 (?\350 . "%E8") ; `e
6200 (?\351 . "%E9") ; 'e
6201 (?\352 . "%EA") ; ^e
6202 (?\356 . "%EE") ; ^i
6203 (?\364 . "%F4") ; ^o
6204 (?\371 . "%F9") ; `u
6205 (?\373 . "%FB") ; ^u
6206 (?\; . "%3B")
6207 (?? . "%3F")
6208 (?= . "%3D")
6209 (?+ . "%2B")
6211 "Association list of escapes for some characters problematic in links.
6212 This is the list that is used for internal purposes.")
6214 (defconst org-link-escape-chars-browser
6215 '((?\ . "%20")) ; 32 for the SPC char
6216 "Association list of escapes for some characters problematic in links.
6217 This is the list that is used before handing over to the browser.")
6219 (defun org-link-escape (text &optional table)
6220 "Escape charaters in TEXT that are problematic for links."
6221 (setq table (or table org-link-escape-chars))
6222 (when text
6223 (let ((re (mapconcat (lambda (x) (regexp-quote
6224 (char-to-string (car x))))
6225 table "\\|")))
6226 (while (string-match re text)
6227 (setq text
6228 (replace-match
6229 (cdr (assoc (string-to-char (match-string 0 text))
6230 table))
6231 t t text)))
6232 text)))
6234 (defun org-link-unescape (text &optional table)
6235 "Reverse the action of `org-link-escape'."
6236 (setq table (or table org-link-escape-chars))
6237 (when text
6238 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6239 table "\\|")))
6240 (while (string-match re text)
6241 (setq text
6242 (replace-match
6243 (char-to-string (car (rassoc (match-string 0 text) table)))
6244 t t text)))
6245 text)))
6247 (defun org-xor (a b)
6248 "Exclusive or."
6249 (if a (not b) b))
6251 (defun org-get-header (header)
6252 "Find a header field in the current buffer."
6253 (save-excursion
6254 (goto-char (point-min))
6255 (let ((case-fold-search t) s)
6256 (cond
6257 ((eq header 'from)
6258 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6259 (setq s (match-string 1)))
6260 (while (string-match "\"" s)
6261 (setq s (replace-match "" t t s)))
6262 (if (string-match "[<(].*" s)
6263 (setq s (replace-match "" t t s))))
6264 ((eq header 'message-id)
6265 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6266 (setq s (match-string 1))))
6267 ((eq header 'subject)
6268 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6269 (setq s (match-string 1)))))
6270 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6271 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6272 s)))
6275 (defun org-fixup-message-id-for-http (s)
6276 "Replace special characters in a message id, so it can be used in an http query."
6277 (while (string-match "<" s)
6278 (setq s (replace-match "%3C" t t s)))
6279 (while (string-match ">" s)
6280 (setq s (replace-match "%3E" t t s)))
6281 (while (string-match "@" s)
6282 (setq s (replace-match "%40" t t s)))
6285 ;;;###autoload
6286 (defun org-insert-link-global ()
6287 "Insert a link like Org-mode does.
6288 This command can be called in any mode to insert a link in Org-mode syntax."
6289 (interactive)
6290 (org-load-modules-maybe)
6291 (org-run-like-in-org-mode 'org-insert-link))
6293 (defun org-insert-link (&optional complete-file link-location)
6294 "Insert a link. At the prompt, enter the link.
6296 Completion can be used to select a link previously stored with
6297 `org-store-link'. When the empty string is entered (i.e. if you just
6298 press RET at the prompt), the link defaults to the most recently
6299 stored link. As SPC triggers completion in the minibuffer, you need to
6300 use M-SPC or C-q SPC to force the insertion of a space character.
6302 You will also be prompted for a description, and if one is given, it will
6303 be displayed in the buffer instead of the link.
6305 If there is already a link at point, this command will allow you to edit link
6306 and description parts.
6308 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6309 be selected using completion. The path to the file will be relative to the
6310 current directory if the file is in the current directory or a subdirectory.
6311 Otherwise, the link will be the absolute path as completed in the minibuffer
6312 \(i.e. normally ~/path/to/file).
6314 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6315 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6316 of `org-keep-stored-link-after-insertion'.
6318 If `org-make-link-description-function' is non-nil, this function will be
6319 called with the link target, and the result will be the default
6320 link description.
6322 If the LINK-LOCATION parameter is non-nil, this value will be
6323 used as the link location instead of reading one interactively."
6324 (interactive "P")
6325 (let* ((wcf (current-window-configuration))
6326 (region (if (org-region-active-p)
6327 (buffer-substring (region-beginning) (region-end))))
6328 (remove (and region (list (region-beginning) (region-end))))
6329 (desc region)
6330 tmphist ; byte-compile incorrectly complains about this
6331 (link link-location)
6332 entry file)
6333 (cond
6334 (link-location) ; specified by arg, just use it.
6335 ((org-in-regexp org-bracket-link-regexp 1)
6336 ;; We do have a link at point, and we are going to edit it.
6337 (setq remove (list (match-beginning 0) (match-end 0)))
6338 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6339 (setq link (read-string "Link: "
6340 (org-link-unescape
6341 (org-match-string-no-properties 1)))))
6342 ((or (org-in-regexp org-angle-link-re)
6343 (org-in-regexp org-plain-link-re))
6344 ;; Convert to bracket link
6345 (setq remove (list (match-beginning 0) (match-end 0))
6346 link (read-string "Link: "
6347 (org-remove-angle-brackets (match-string 0)))))
6348 ((equal complete-file '(4))
6349 ;; Completing read for file names.
6350 (setq file (read-file-name "File: "))
6351 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6352 (pwd1 (file-name-as-directory (abbreviate-file-name
6353 (expand-file-name ".")))))
6354 (cond
6355 ((equal complete-file '(16))
6356 (setq link (org-make-link
6357 "file:"
6358 (abbreviate-file-name (expand-file-name file)))))
6359 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6360 (setq link (org-make-link "file:" (match-string 1 file))))
6361 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6362 (expand-file-name file))
6363 (setq link (org-make-link
6364 "file:" (match-string 1 (expand-file-name file)))))
6365 (t (setq link (org-make-link "file:" file))))))
6367 ;; Read link, with completion for stored links.
6368 (with-output-to-temp-buffer "*Org Links*"
6369 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6370 (when org-stored-links
6371 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6372 (princ (mapconcat
6373 (lambda (x)
6374 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6375 (reverse org-stored-links) "\n"))))
6376 (let ((cw (selected-window)))
6377 (select-window (get-buffer-window "*Org Links*"))
6378 (shrink-window-if-larger-than-buffer)
6379 (setq truncate-lines t)
6380 (select-window cw))
6381 ;; Fake a link history, containing the stored links.
6382 (setq tmphist (append (mapcar 'car org-stored-links)
6383 org-insert-link-history))
6384 (unwind-protect
6385 (setq link (org-completing-read
6386 "Link: "
6387 (append
6388 (mapcar (lambda (x) (list (concat (car x) ":")))
6389 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6390 (mapcar (lambda (x) (list (concat x ":")))
6391 org-link-types))
6392 nil nil nil
6393 'tmphist
6394 (or (car (car org-stored-links)))))
6395 (set-window-configuration wcf)
6396 (kill-buffer "*Org Links*"))
6397 (setq entry (assoc link org-stored-links))
6398 (or entry (push link org-insert-link-history))
6399 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6400 (not org-keep-stored-link-after-insertion))
6401 (setq org-stored-links (delq (assoc link org-stored-links)
6402 org-stored-links)))
6403 (setq desc (or desc (nth 1 entry)))))
6405 (if (string-match org-plain-link-re link)
6406 ;; URL-like link, normalize the use of angular brackets.
6407 (setq link (org-make-link (org-remove-angle-brackets link))))
6409 ;; Check if we are linking to the current file with a search option
6410 ;; If yes, simplify the link by using only the search option.
6411 (when (and buffer-file-name
6412 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6413 (let* ((path (match-string 1 link))
6414 (case-fold-search nil)
6415 (search (match-string 2 link)))
6416 (save-match-data
6417 (if (equal (file-truename buffer-file-name) (file-truename path))
6418 ;; We are linking to this same file, with a search option
6419 (setq link search)))))
6421 ;; Check if we can/should use a relative path. If yes, simplify the link
6422 (when (string-match "\\<file:\\(.*\\)" link)
6423 (let* ((path (match-string 1 link))
6424 (origpath path)
6425 (case-fold-search nil))
6426 (cond
6427 ((eq org-link-file-path-type 'absolute)
6428 (setq path (abbreviate-file-name (expand-file-name path))))
6429 ((eq org-link-file-path-type 'noabbrev)
6430 (setq path (expand-file-name path)))
6431 ((eq org-link-file-path-type 'relative)
6432 (setq path (file-relative-name path)))
6434 (save-match-data
6435 (if (string-match (concat "^" (regexp-quote
6436 (file-name-as-directory
6437 (expand-file-name "."))))
6438 (expand-file-name path))
6439 ;; We are linking a file with relative path name.
6440 (setq path (substring (expand-file-name path)
6441 (match-end 0)))))))
6442 (setq link (concat "file:" path))
6443 (if (equal desc origpath)
6444 (setq desc path))))
6446 (if org-make-link-description-function
6447 (setq desc (funcall org-make-link-description-function link desc)))
6449 (setq desc (read-string "Description: " desc))
6450 (unless (string-match "\\S-" desc) (setq desc nil))
6451 (if remove (apply 'delete-region remove))
6452 (insert (org-make-link-string link desc))))
6454 (defun org-completing-read (&rest args)
6455 (let ((minibuffer-local-completion-map
6456 (copy-keymap minibuffer-local-completion-map)))
6457 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6458 (apply 'completing-read args)))
6460 (defun org-extract-attributes (s)
6461 "Extract the attributes cookie from a string and set as text property."
6462 (let (a attr (start 0) key value)
6463 (save-match-data
6464 (when (string-match "{{\\([^}]+\\)}}$" s)
6465 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6466 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6467 (setq key (match-string 1 a) value (match-string 2 a)
6468 start (match-end 0)
6469 attr (plist-put attr (intern key) value))))
6470 (org-add-props s nil 'org-attributes attr))
6473 (defun org-attributes-to-string (plist)
6474 "Format a property list into an HTML attribute list."
6475 (let ((s "") key value)
6476 (while plist
6477 (setq key (pop plist) value (pop plist))
6478 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6481 ;;; Opening/following a link
6483 (defvar org-link-search-failed nil)
6485 (defun org-next-link ()
6486 "Move forward to the next link.
6487 If the link is in hidden text, expose it."
6488 (interactive)
6489 (when (and org-link-search-failed (eq this-command last-command))
6490 (goto-char (point-min))
6491 (message "Link search wrapped back to beginning of buffer"))
6492 (setq org-link-search-failed nil)
6493 (let* ((pos (point))
6494 (ct (org-context))
6495 (a (assoc :link ct)))
6496 (if a (goto-char (nth 2 a)))
6497 (if (re-search-forward org-any-link-re nil t)
6498 (progn
6499 (goto-char (match-beginning 0))
6500 (if (org-invisible-p) (org-show-context)))
6501 (goto-char pos)
6502 (setq org-link-search-failed t)
6503 (error "No further link found"))))
6505 (defun org-previous-link ()
6506 "Move backward to the previous link.
6507 If the link is in hidden text, expose it."
6508 (interactive)
6509 (when (and org-link-search-failed (eq this-command last-command))
6510 (goto-char (point-max))
6511 (message "Link search wrapped back to end of buffer"))
6512 (setq org-link-search-failed nil)
6513 (let* ((pos (point))
6514 (ct (org-context))
6515 (a (assoc :link ct)))
6516 (if a (goto-char (nth 1 a)))
6517 (if (re-search-backward org-any-link-re nil t)
6518 (progn
6519 (goto-char (match-beginning 0))
6520 (if (org-invisible-p) (org-show-context)))
6521 (goto-char pos)
6522 (setq org-link-search-failed t)
6523 (error "No further link found"))))
6525 (defun org-find-file-at-mouse (ev)
6526 "Open file link or URL at mouse."
6527 (interactive "e")
6528 (mouse-set-point ev)
6529 (org-open-at-point 'in-emacs))
6531 (defun org-open-at-mouse (ev)
6532 "Open file link or URL at mouse."
6533 (interactive "e")
6534 (mouse-set-point ev)
6535 (org-open-at-point))
6537 (defvar org-window-config-before-follow-link nil
6538 "The window configuration before following a link.
6539 This is saved in case the need arises to restore it.")
6541 (defvar org-open-link-marker (make-marker)
6542 "Marker pointing to the location where `org-open-at-point; was called.")
6544 ;;;###autoload
6545 (defun org-open-at-point-global ()
6546 "Follow a link like Org-mode does.
6547 This command can be called in any mode to follow a link that has
6548 Org-mode syntax."
6549 (interactive)
6550 (org-run-like-in-org-mode 'org-open-at-point))
6552 ;;;###autoload
6553 (defun org-open-link-from-string (s &optional arg)
6554 "Open a link in the string S, as if it was in Org-mode."
6555 (interactive "sLink: \nP")
6556 (with-temp-buffer
6557 (let ((org-inhibit-startup t))
6558 (org-mode)
6559 (insert s)
6560 (goto-char (point-min))
6561 (org-open-at-point arg))))
6563 (defun org-open-at-point (&optional in-emacs)
6564 "Open link at or after point.
6565 If there is no link at point, this function will search forward up to
6566 the end of the current subtree.
6567 Normally, files will be opened by an appropriate application. If the
6568 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6569 (interactive "P")
6570 (org-load-modules-maybe)
6571 (move-marker org-open-link-marker (point))
6572 (setq org-window-config-before-follow-link (current-window-configuration))
6573 (org-remove-occur-highlights nil nil t)
6574 (if (org-at-timestamp-p t)
6575 (org-follow-timestamp-link)
6576 (let (type path link line search (pos (point)))
6577 (catch 'match
6578 (save-excursion
6579 (skip-chars-forward "^]\n\r")
6580 (when (org-in-regexp org-bracket-link-regexp)
6581 (setq link (org-extract-attributes
6582 (org-link-unescape (org-match-string-no-properties 1))))
6583 (while (string-match " *\n *" link)
6584 (setq link (replace-match " " t t link)))
6585 (setq link (org-link-expand-abbrev link))
6586 (cond
6587 ((or (file-name-absolute-p link)
6588 (string-match "^\\.\\.?/" link))
6589 (setq type "file" path link))
6590 ((string-match org-link-re-with-space2 link)
6591 (setq type (match-string 1 link) path (match-string 2 link)))
6592 (t (setq type "thisfile" path link)))
6593 (throw 'match t)))
6595 (when (get-text-property (point) 'org-linked-text)
6596 (setq type "thisfile"
6597 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6598 (1+ (point)) (point))
6599 path (buffer-substring
6600 (previous-single-property-change pos 'org-linked-text)
6601 (next-single-property-change pos 'org-linked-text)))
6602 (throw 'match t))
6604 (save-excursion
6605 (when (or (org-in-regexp org-angle-link-re)
6606 (org-in-regexp org-plain-link-re))
6607 (setq type (match-string 1) path (match-string 2))
6608 (throw 'match t)))
6609 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6610 (setq type "tree-match"
6611 path (match-string 1))
6612 (throw 'match t))
6613 (save-excursion
6614 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6615 (setq type "tags"
6616 path (match-string 1))
6617 (while (string-match ":" path)
6618 (setq path (replace-match "+" t t path)))
6619 (throw 'match t))))
6620 (unless path
6621 (error "No link found"))
6622 ;; Remove any trailing spaces in path
6623 (if (string-match " +\\'" path)
6624 (setq path (replace-match "" t t path)))
6626 (cond
6628 ((assoc type org-link-protocols)
6629 (funcall (nth 1 (assoc type org-link-protocols)) path))
6631 ((equal type "mailto")
6632 (let ((cmd (car org-link-mailto-program))
6633 (args (cdr org-link-mailto-program)) args1
6634 (address path) (subject "") a)
6635 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6636 (setq address (match-string 1 path)
6637 subject (org-link-escape (match-string 2 path))))
6638 (while args
6639 (cond
6640 ((not (stringp (car args))) (push (pop args) args1))
6641 (t (setq a (pop args))
6642 (if (string-match "%a" a)
6643 (setq a (replace-match address t t a)))
6644 (if (string-match "%s" a)
6645 (setq a (replace-match subject t t a)))
6646 (push a args1))))
6647 (apply cmd (nreverse args1))))
6649 ((member type '("http" "https" "ftp" "news"))
6650 (browse-url (concat type ":" (org-link-escape
6651 path org-link-escape-chars-browser))))
6653 ((member type '("message"))
6654 (browse-url (concat type ":" path)))
6656 ((string= type "tags")
6657 (org-tags-view in-emacs path))
6658 ((string= type "thisfile")
6659 (if in-emacs
6660 (switch-to-buffer-other-window
6661 (org-get-buffer-for-internal-link (current-buffer)))
6662 (org-mark-ring-push))
6663 (let ((cmd `(org-link-search
6664 ,path
6665 ,(cond ((equal in-emacs '(4)) 'occur)
6666 ((equal in-emacs '(16)) 'org-occur)
6667 (t nil))
6668 ,pos)))
6669 (condition-case nil (eval cmd)
6670 (error (progn (widen) (eval cmd))))))
6672 ((string= type "tree-match")
6673 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6675 ((string= type "file")
6676 (if (string-match "::\\([0-9]+\\)\\'" path)
6677 (setq line (string-to-number (match-string 1 path))
6678 path (substring path 0 (match-beginning 0)))
6679 (if (string-match "::\\(.+\\)\\'" path)
6680 (setq search (match-string 1 path)
6681 path (substring path 0 (match-beginning 0)))))
6682 (if (string-match "[*?{]" (file-name-nondirectory path))
6683 (dired path)
6684 (org-open-file path in-emacs line search)))
6686 ((string= type "news")
6687 (require 'org-gnus)
6688 (org-gnus-follow-link path))
6690 ((string= type "shell")
6691 (let ((cmd path))
6692 (if (or (not org-confirm-shell-link-function)
6693 (funcall org-confirm-shell-link-function
6694 (format "Execute \"%s\" in shell? "
6695 (org-add-props cmd nil
6696 'face 'org-warning))))
6697 (progn
6698 (message "Executing %s" cmd)
6699 (shell-command cmd))
6700 (error "Abort"))))
6702 ((string= type "elisp")
6703 (let ((cmd path))
6704 (if (or (not org-confirm-elisp-link-function)
6705 (funcall org-confirm-elisp-link-function
6706 (format "Execute \"%s\" as elisp? "
6707 (org-add-props cmd nil
6708 'face 'org-warning))))
6709 (message "%s => %s" cmd (eval (read cmd)))
6710 (error "Abort"))))
6713 (browse-url-at-point)))))
6714 (move-marker org-open-link-marker nil)
6715 (run-hook-with-args 'org-follow-link-hook))
6717 ;;;; Time estimates
6719 (defun org-get-effort (&optional pom)
6720 "Get the effort estimate for the current entry."
6721 (org-entry-get pom org-effort-property))
6723 ;;; File search
6725 (defvar org-create-file-search-functions nil
6726 "List of functions to construct the right search string for a file link.
6727 These functions are called in turn with point at the location to
6728 which the link should point.
6730 A function in the hook should first test if it would like to
6731 handle this file type, for example by checking the major-mode or
6732 the file extension. If it decides not to handle this file, it
6733 should just return nil to give other functions a chance. If it
6734 does handle the file, it must return the search string to be used
6735 when following the link. The search string will be part of the
6736 file link, given after a double colon, and `org-open-at-point'
6737 will automatically search for it. If special measures must be
6738 taken to make the search successful, another function should be
6739 added to the companion hook `org-execute-file-search-functions',
6740 which see.
6742 A function in this hook may also use `setq' to set the variable
6743 `description' to provide a suggestion for the descriptive text to
6744 be used for this link when it gets inserted into an Org-mode
6745 buffer with \\[org-insert-link].")
6747 (defvar org-execute-file-search-functions nil
6748 "List of functions to execute a file search triggered by a link.
6750 Functions added to this hook must accept a single argument, the
6751 search string that was part of the file link, the part after the
6752 double colon. The function must first check if it would like to
6753 handle this search, for example by checking the major-mode or the
6754 file extension. If it decides not to handle this search, it
6755 should just return nil to give other functions a chance. If it
6756 does handle the search, it must return a non-nil value to keep
6757 other functions from trying.
6759 Each function can access the current prefix argument through the
6760 variable `current-prefix-argument'. Note that a single prefix is
6761 used to force opening a link in Emacs, so it may be good to only
6762 use a numeric or double prefix to guide the search function.
6764 In case this is needed, a function in this hook can also restore
6765 the window configuration before `org-open-at-point' was called using:
6767 (set-window-configuration org-window-config-before-follow-link)")
6769 (defun org-link-search (s &optional type avoid-pos)
6770 "Search for a link search option.
6771 If S is surrounded by forward slashes, it is interpreted as a
6772 regular expression. In org-mode files, this will create an `org-occur'
6773 sparse tree. In ordinary files, `occur' will be used to list matches.
6774 If the current buffer is in `dired-mode', grep will be used to search
6775 in all files. If AVOID-POS is given, ignore matches near that position."
6776 (let ((case-fold-search t)
6777 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6778 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6779 (append '(("") (" ") ("\t") ("\n"))
6780 org-emphasis-alist)
6781 "\\|") "\\)"))
6782 (pos (point))
6783 (pre nil) (post nil)
6784 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6785 (cond
6786 ;; First check if there are any special
6787 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6788 ;; Now try the builtin stuff
6789 ((save-excursion
6790 (goto-char (point-min))
6791 (and
6792 (re-search-forward
6793 (concat "<<" (regexp-quote s0) ">>") nil t)
6794 (setq type 'dedicated
6795 pos (match-beginning 0))))
6796 ;; There is an exact target for this
6797 (goto-char pos))
6798 ((string-match "^/\\(.*\\)/$" s)
6799 ;; A regular expression
6800 (cond
6801 ((org-mode-p)
6802 (org-occur (match-string 1 s)))
6803 ;;((eq major-mode 'dired-mode)
6804 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6805 (t (org-do-occur (match-string 1 s)))))
6807 ;; A normal search strings
6808 (when (equal (string-to-char s) ?*)
6809 ;; Anchor on headlines, post may include tags.
6810 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6811 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6812 s (substring s 1)))
6813 (remove-text-properties
6814 0 (length s)
6815 '(face nil mouse-face nil keymap nil fontified nil) s)
6816 ;; Make a series of regular expressions to find a match
6817 (setq words (org-split-string s "[ \n\r\t]+")
6819 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6820 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6821 "\\)" markers)
6822 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6823 re2a (concat "[ \t\r\n]" re2a_)
6824 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6825 re4 (concat "[^a-zA-Z_]" re4_)
6827 re1 (concat pre re2 post)
6828 re3 (concat pre (if pre re4_ re4) post)
6829 re5 (concat pre ".*" re4)
6830 re2 (concat pre re2)
6831 re2a (concat pre (if pre re2a_ re2a))
6832 re4 (concat pre (if pre re4_ re4))
6833 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6834 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6835 re5 "\\)"
6837 (cond
6838 ((eq type 'org-occur) (org-occur reall))
6839 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6840 (t (goto-char (point-min))
6841 (setq type 'fuzzy)
6842 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6843 (org-search-not-self 1 re1 nil t)
6844 (org-search-not-self 1 re2 nil t)
6845 (org-search-not-self 1 re2a nil t)
6846 (org-search-not-self 1 re3 nil t)
6847 (org-search-not-self 1 re4 nil t)
6848 (org-search-not-self 1 re5 nil t)
6850 (goto-char (match-beginning 1))
6851 (goto-char pos)
6852 (error "No match")))))
6854 ;; Normal string-search
6855 (goto-char (point-min))
6856 (if (search-forward s nil t)
6857 (goto-char (match-beginning 0))
6858 (error "No match"))))
6859 (and (org-mode-p) (org-show-context 'link-search))
6860 type))
6862 (defun org-search-not-self (group &rest args)
6863 "Execute `re-search-forward', but only accept matches that do not
6864 enclose the position of `org-open-link-marker'."
6865 (let ((m org-open-link-marker))
6866 (catch 'exit
6867 (while (apply 're-search-forward args)
6868 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6869 (goto-char (match-end group))
6870 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6871 (> (match-beginning 0) (marker-position m))
6872 (< (match-end 0) (marker-position m)))
6873 (save-match-data
6874 (or (not (org-in-regexp
6875 org-bracket-link-analytic-regexp 1))
6876 (not (match-end 4)) ; no description
6877 (and (<= (match-beginning 4) (point))
6878 (>= (match-end 4) (point))))))
6879 (throw 'exit (point))))))))
6881 (defun org-get-buffer-for-internal-link (buffer)
6882 "Return a buffer to be used for displaying the link target of internal links."
6883 (cond
6884 ((not org-display-internal-link-with-indirect-buffer)
6885 buffer)
6886 ((string-match "(Clone)$" (buffer-name buffer))
6887 (message "Buffer is already a clone, not making another one")
6888 ;; we also do not modify visibility in this case
6889 buffer)
6890 (t ; make a new indirect buffer for displaying the link
6891 (let* ((bn (buffer-name buffer))
6892 (ibn (concat bn "(Clone)"))
6893 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6894 (with-current-buffer ib (org-overview))
6895 ib))))
6897 (defun org-do-occur (regexp &optional cleanup)
6898 "Call the Emacs command `occur'.
6899 If CLEANUP is non-nil, remove the printout of the regular expression
6900 in the *Occur* buffer. This is useful if the regex is long and not useful
6901 to read."
6902 (occur regexp)
6903 (when cleanup
6904 (let ((cwin (selected-window)) win beg end)
6905 (when (setq win (get-buffer-window "*Occur*"))
6906 (select-window win))
6907 (goto-char (point-min))
6908 (when (re-search-forward "match[a-z]+" nil t)
6909 (setq beg (match-end 0))
6910 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6911 (setq end (1- (match-beginning 0)))))
6912 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6913 (goto-char (point-min))
6914 (select-window cwin))))
6916 ;;; The mark ring for links jumps
6918 (defvar org-mark-ring nil
6919 "Mark ring for positions before jumps in Org-mode.")
6920 (defvar org-mark-ring-last-goto nil
6921 "Last position in the mark ring used to go back.")
6922 ;; Fill and close the ring
6923 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6924 (loop for i from 1 to org-mark-ring-length do
6925 (push (make-marker) org-mark-ring))
6926 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6927 org-mark-ring)
6929 (defun org-mark-ring-push (&optional pos buffer)
6930 "Put the current position or POS into the mark ring and rotate it."
6931 (interactive)
6932 (setq pos (or pos (point)))
6933 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6934 (move-marker (car org-mark-ring)
6935 (or pos (point))
6936 (or buffer (current-buffer)))
6937 (message "%s"
6938 (substitute-command-keys
6939 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6941 (defun org-mark-ring-goto (&optional n)
6942 "Jump to the previous position in the mark ring.
6943 With prefix arg N, jump back that many stored positions. When
6944 called several times in succession, walk through the entire ring.
6945 Org-mode commands jumping to a different position in the current file,
6946 or to another Org-mode file, automatically push the old position
6947 onto the ring."
6948 (interactive "p")
6949 (let (p m)
6950 (if (eq last-command this-command)
6951 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6952 (setq p org-mark-ring))
6953 (setq org-mark-ring-last-goto p)
6954 (setq m (car p))
6955 (switch-to-buffer (marker-buffer m))
6956 (goto-char m)
6957 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6959 (defun org-remove-angle-brackets (s)
6960 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6961 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6963 (defun org-add-angle-brackets (s)
6964 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6965 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6967 (defun org-remove-double-quotes (s)
6968 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
6969 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
6972 ;;; Following specific links
6974 (defun org-follow-timestamp-link ()
6975 (cond
6976 ((org-at-date-range-p t)
6977 (let ((org-agenda-start-on-weekday)
6978 (t1 (match-string 1))
6979 (t2 (match-string 2)))
6980 (setq t1 (time-to-days (org-time-string-to-time t1))
6981 t2 (time-to-days (org-time-string-to-time t2)))
6982 (org-agenda-list nil t1 (1+ (- t2 t1)))))
6983 ((org-at-timestamp-p t)
6984 (org-agenda-list nil (time-to-days (org-time-string-to-time
6985 (substring (match-string 1) 0 10)))
6987 (t (error "This should not happen"))))
6990 ;;; Following file links
6991 (defvar org-wait nil)
6992 (defun org-open-file (path &optional in-emacs line search)
6993 "Open the file at PATH.
6994 First, this expands any special file name abbreviations. Then the
6995 configuration variable `org-file-apps' is checked if it contains an
6996 entry for this file type, and if yes, the corresponding command is launched.
6997 If no application is found, Emacs simply visits the file.
6998 With optional argument IN-EMACS, Emacs will visit the file.
6999 Optional LINE specifies a line to go to, optional SEARCH a string to
7000 search for. If LINE or SEARCH is given, the file will always be
7001 opened in Emacs.
7002 If the file does not exist, an error is thrown."
7003 (setq in-emacs (or in-emacs line search))
7004 (let* ((file (if (equal path "")
7005 buffer-file-name
7006 (substitute-in-file-name (expand-file-name path))))
7007 (apps (append org-file-apps (org-default-apps)))
7008 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7009 (dirp (if remp nil (file-directory-p file)))
7010 (file (if (and dirp org-open-directory-means-index-dot-org)
7011 (concat (file-name-as-directory file) "index.org")
7012 file))
7013 (a-m-a-p (assq 'auto-mode apps))
7014 (dfile (downcase file))
7015 (old-buffer (current-buffer))
7016 (old-pos (point))
7017 (old-mode major-mode)
7018 ext cmd)
7019 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7020 (setq ext (match-string 1 dfile))
7021 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7022 (setq ext (match-string 1 dfile))))
7023 (if in-emacs
7024 (setq cmd 'emacs)
7025 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7026 (and dirp (cdr (assoc 'directory apps)))
7027 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7028 'string-match)
7029 (cdr (assoc ext apps))
7030 (cdr (assoc t apps)))))
7031 (when (eq cmd 'default)
7032 (setq cmd (cdr (assoc t apps))))
7033 (when (eq cmd 'mailcap)
7034 (require 'mailcap)
7035 (mailcap-parse-mailcaps)
7036 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7037 (command (mailcap-mime-info mime-type)))
7038 (if (stringp command)
7039 (setq cmd command)
7040 (setq cmd 'emacs))))
7041 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7042 (not (file-exists-p file))
7043 (not org-open-non-existing-files))
7044 (error "No such file: %s" file))
7045 (cond
7046 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7047 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7048 (while (string-match "['\"]%s['\"]" cmd)
7049 (setq cmd (replace-match "%s" t t cmd)))
7050 (while (string-match "%s" cmd)
7051 (setq cmd (replace-match
7052 (save-match-data
7053 (shell-quote-argument
7054 (convert-standard-filename file)))
7055 t t cmd)))
7056 (save-window-excursion
7057 (start-process-shell-command cmd nil cmd)
7058 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7060 ((or (stringp cmd)
7061 (eq cmd 'emacs))
7062 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7063 (widen)
7064 (if line (goto-line line)
7065 (if search (org-link-search search))))
7066 ((consp cmd)
7067 (let ((file (convert-standard-filename file)))
7068 (eval cmd)))
7069 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7070 (and (org-mode-p) (eq old-mode 'org-mode)
7071 (or (not (equal old-buffer (current-buffer)))
7072 (not (equal old-pos (point))))
7073 (org-mark-ring-push old-pos old-buffer))))
7075 (defun org-default-apps ()
7076 "Return the default applications for this operating system."
7077 (cond
7078 ((eq system-type 'darwin)
7079 org-file-apps-defaults-macosx)
7080 ((eq system-type 'windows-nt)
7081 org-file-apps-defaults-windowsnt)
7082 (t org-file-apps-defaults-gnu)))
7084 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7085 "Convert extensions to regular expressions in the cars of LIST.
7086 Also, weed out any non-string entries, because the return value is used
7087 only for regexp matching.
7088 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7089 point to the symbol `emacs', indicating that the file should
7090 be opened in Emacs."
7091 (append
7092 (delq nil
7093 (mapcar (lambda (x)
7094 (if (not (stringp (car x)))
7096 (if (string-match "\\W" (car x))
7098 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7099 list))
7100 (if add-auto-mode
7101 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7103 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7104 (defun org-file-remote-p (file)
7105 "Test whether FILE specifies a location on a remote system.
7106 Return non-nil if the location is indeed remote.
7108 For example, the filename \"/user@host:/foo\" specifies a location
7109 on the system \"/user@host:\"."
7110 (cond ((fboundp 'file-remote-p)
7111 (file-remote-p file))
7112 ((fboundp 'tramp-handle-file-remote-p)
7113 (tramp-handle-file-remote-p file))
7114 ((and (boundp 'ange-ftp-name-format)
7115 (string-match (car ange-ftp-name-format) file))
7117 (t nil)))
7120 ;;;; Refiling
7122 (defun org-get-org-file ()
7123 "Read a filename, with default directory `org-directory'."
7124 (let ((default (or org-default-notes-file remember-data-file)))
7125 (read-file-name (format "File name [%s]: " default)
7126 (file-name-as-directory org-directory)
7127 default)))
7129 (defun org-notes-order-reversed-p ()
7130 "Check if the current file should receive notes in reversed order."
7131 (cond
7132 ((not org-reverse-note-order) nil)
7133 ((eq t org-reverse-note-order) t)
7134 ((not (listp org-reverse-note-order)) nil)
7135 (t (catch 'exit
7136 (let ((all org-reverse-note-order)
7137 entry)
7138 (while (setq entry (pop all))
7139 (if (string-match (car entry) buffer-file-name)
7140 (throw 'exit (cdr entry))))
7141 nil)))))
7143 (defvar org-refile-target-table nil
7144 "The list of refile targets, created by `org-refile'.")
7146 (defvar org-agenda-new-buffers nil
7147 "Buffers created to visit agenda files.")
7149 (defun org-get-refile-targets (&optional default-buffer)
7150 "Produce a table with refile targets."
7151 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7152 targets txt re files f desc descre)
7153 (with-current-buffer (or default-buffer (current-buffer))
7154 (while (setq entry (pop entries))
7155 (setq files (car entry) desc (cdr entry))
7156 (cond
7157 ((null files) (setq files (list (current-buffer))))
7158 ((eq files 'org-agenda-files)
7159 (setq files (org-agenda-files 'unrestricted)))
7160 ((and (symbolp files) (fboundp files))
7161 (setq files (funcall files)))
7162 ((and (symbolp files) (boundp files))
7163 (setq files (symbol-value files))))
7164 (if (stringp files) (setq files (list files)))
7165 (cond
7166 ((eq (car desc) :tag)
7167 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7168 ((eq (car desc) :todo)
7169 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7170 ((eq (car desc) :regexp)
7171 (setq descre (cdr desc)))
7172 ((eq (car desc) :level)
7173 (setq descre (concat "^\\*\\{" (number-to-string
7174 (if org-odd-levels-only
7175 (1- (* 2 (cdr desc)))
7176 (cdr desc)))
7177 "\\}[ \t]")))
7178 ((eq (car desc) :maxlevel)
7179 (setq descre (concat "^\\*\\{1," (number-to-string
7180 (if org-odd-levels-only
7181 (1- (* 2 (cdr desc)))
7182 (cdr desc)))
7183 "\\}[ \t]")))
7184 (t (error "Bad refiling target description %s" desc)))
7185 (while (setq f (pop files))
7186 (save-excursion
7187 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7188 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7189 (save-excursion
7190 (save-restriction
7191 (widen)
7192 (goto-char (point-min))
7193 (while (re-search-forward descre nil t)
7194 (goto-char (point-at-bol))
7195 (when (looking-at org-complex-heading-regexp)
7196 (setq txt (org-link-display-format (match-string 4))
7197 re (concat "^" (regexp-quote
7198 (buffer-substring (match-beginning 1)
7199 (match-end 4)))))
7200 (if (match-end 5) (setq re (concat re "[ \t]+"
7201 (regexp-quote
7202 (match-string 5)))))
7203 (setq re (concat re "[ \t]*$"))
7204 (when org-refile-use-outline-path
7205 (setq txt (mapconcat 'org-protect-slash
7206 (append
7207 (if (eq org-refile-use-outline-path 'file)
7208 (list (file-name-nondirectory
7209 (buffer-file-name (buffer-base-buffer))))
7210 (if (eq org-refile-use-outline-path 'full-file-path)
7211 (list (buffer-file-name (buffer-base-buffer)))))
7212 (org-get-outline-path)
7213 (list txt))
7214 "/")))
7215 (push (list txt f re (point)) targets))
7216 (goto-char (point-at-eol))))))))
7217 (nreverse targets))))
7219 (defun org-protect-slash (s)
7220 (while (string-match "/" s)
7221 (setq s (replace-match "\\" t t s)))
7224 (defun org-get-outline-path ()
7225 "Return the outline path to the current entry, as a list."
7226 (let (rtn)
7227 (save-excursion
7228 (while (org-up-heading-safe)
7229 (when (looking-at org-complex-heading-regexp)
7230 (push (org-match-string-no-properties 4) rtn)))
7231 rtn)))
7233 (defvar org-refile-history nil
7234 "History for refiling operations.")
7236 (defun org-refile (&optional goto default-buffer)
7237 "Move the entry at point to another heading.
7238 The list of target headings is compiled using the information in
7239 `org-refile-targets', which see. This list is created before each use
7240 and will therefore always be up-to-date.
7242 At the target location, the entry is filed as a subitem of the target heading.
7243 Depending on `org-reverse-note-order', the new subitem will either be the
7244 first of the last subitem.
7246 With prefix arg GOTO, the command will only visit the target location,
7247 not actually move anything.
7248 With a double prefix `C-u C-u', go to the location where the last refiling
7249 operation has put the subtree."
7250 (interactive "P")
7251 (let* ((cbuf (current-buffer))
7252 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7253 pos it nbuf file re level reversed)
7254 (if (equal goto '(16))
7255 (org-refile-goto-last-stored)
7256 (when (setq it (org-refile-get-location
7257 (if goto "Goto: " "Refile to: ") default-buffer))
7258 (setq file (nth 1 it)
7259 re (nth 2 it)
7260 pos (nth 3 it))
7261 (setq nbuf (or (find-buffer-visiting file)
7262 (find-file-noselect file)))
7263 (if goto
7264 (progn
7265 (switch-to-buffer nbuf)
7266 (goto-char pos)
7267 (org-show-context 'org-goto))
7268 (org-copy-subtree 1 nil t)
7269 (save-excursion
7270 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7271 (find-file-noselect file))))
7272 (setq reversed (org-notes-order-reversed-p))
7273 (save-excursion
7274 (save-restriction
7275 (widen)
7276 (goto-char pos)
7277 (looking-at outline-regexp)
7278 (setq level (org-get-valid-level (funcall outline-level) 1))
7279 (goto-char
7280 (if reversed
7281 (or (outline-next-heading) (point-max))
7282 (or (save-excursion (outline-get-next-sibling))
7283 (org-end-of-subtree t t)
7284 (point-max))))
7285 (if (not (bolp)) (newline))
7286 (bookmark-set "org-refile-last-stored")
7287 (org-paste-subtree level))))
7288 (org-cut-subtree)
7289 (setq org-markers-to-move nil)
7290 (message "Entry refiled to \"%s\"" (car it)))))))
7292 (defun org-refile-goto-last-stored ()
7293 "Go to the location where the last refile was stored."
7294 (interactive)
7295 (bookmark-jump "org-refile-last-stored")
7296 (message "This is the location of the last refile"))
7298 (defun org-refile-get-location (&optional prompt default-buffer)
7299 "Prompt the user for a refile location, using PROMPT."
7300 (let ((org-refile-targets org-refile-targets)
7301 (org-refile-use-outline-path org-refile-use-outline-path))
7302 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7303 (unless org-refile-target-table
7304 (error "No refile targets"))
7305 (let* ((cbuf (current-buffer))
7306 (cfunc (if org-refile-use-outline-path
7307 'org-olpath-completing-read
7308 'completing-read))
7309 (extra (if org-refile-use-outline-path "/" ""))
7310 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7311 (fname (and filename (file-truename filename)))
7312 (tbl (mapcar
7313 (lambda (x)
7314 (if (not (equal fname (file-truename (nth 1 x))))
7315 (cons (concat (car x) extra " ("
7316 (file-name-nondirectory (nth 1 x)) ")")
7317 (cdr x))
7318 (cons (concat (car x) extra) (cdr x))))
7319 org-refile-target-table))
7320 (completion-ignore-case t))
7321 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7322 tbl)))
7324 (defun org-olpath-completing-read (prompt collection &rest args)
7325 "Read an outline path like a file name."
7326 (let ((thetable collection))
7327 (apply
7328 'completing-read prompt
7329 (lambda (string predicate &optional flag)
7330 (let (rtn r s f (l (length string)))
7331 (cond
7332 ((eq flag nil)
7333 ;; try completion
7334 (try-completion string thetable))
7335 ((eq flag t)
7336 ;; all-completions
7337 (setq rtn (all-completions string thetable predicate))
7338 (mapcar
7339 (lambda (x)
7340 (setq r (substring x l))
7341 (if (string-match " ([^)]*)$" x)
7342 (setq f (match-string 0 x))
7343 (setq f ""))
7344 (if (string-match "/" r)
7345 (concat string (substring r 0 (match-end 0)) f)
7347 rtn))
7348 ((eq flag 'lambda)
7349 ;; exact match?
7350 (assoc string thetable)))
7352 args)))
7354 ;;;; Dynamic blocks
7356 (defun org-find-dblock (name)
7357 "Find the first dynamic block with name NAME in the buffer.
7358 If not found, stay at current position and return nil."
7359 (let (pos)
7360 (save-excursion
7361 (goto-char (point-min))
7362 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7363 nil t)
7364 (match-beginning 0))))
7365 (if pos (goto-char pos))
7366 pos))
7368 (defconst org-dblock-start-re
7369 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7370 "Matches the startline of a dynamic block, with parameters.")
7372 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7373 "Matches the end of a dyhamic block.")
7375 (defun org-create-dblock (plist)
7376 "Create a dynamic block section, with parameters taken from PLIST.
7377 PLIST must containe a :name entry which is used as name of the block."
7378 (unless (bolp) (newline))
7379 (let ((name (plist-get plist :name)))
7380 (insert "#+BEGIN: " name)
7381 (while plist
7382 (if (eq (car plist) :name)
7383 (setq plist (cddr plist))
7384 (insert " " (prin1-to-string (pop plist)))))
7385 (insert "\n\n#+END:\n")
7386 (beginning-of-line -2)))
7388 (defun org-prepare-dblock ()
7389 "Prepare dynamic block for refresh.
7390 This empties the block, puts the cursor at the insert position and returns
7391 the property list including an extra property :name with the block name."
7392 (unless (looking-at org-dblock-start-re)
7393 (error "Not at a dynamic block"))
7394 (let* ((begdel (1+ (match-end 0)))
7395 (name (org-no-properties (match-string 1)))
7396 (params (append (list :name name)
7397 (read (concat "(" (match-string 3) ")")))))
7398 (unless (re-search-forward org-dblock-end-re nil t)
7399 (error "Dynamic block not terminated"))
7400 (setq params
7401 (append params
7402 (list :content (buffer-substring
7403 begdel (match-beginning 0)))))
7404 (delete-region begdel (match-beginning 0))
7405 (goto-char begdel)
7406 (open-line 1)
7407 params))
7409 (defun org-map-dblocks (&optional command)
7410 "Apply COMMAND to all dynamic blocks in the current buffer.
7411 If COMMAND is not given, use `org-update-dblock'."
7412 (let ((cmd (or command 'org-update-dblock))
7413 pos)
7414 (save-excursion
7415 (goto-char (point-min))
7416 (while (re-search-forward org-dblock-start-re nil t)
7417 (goto-char (setq pos (match-beginning 0)))
7418 (condition-case nil
7419 (funcall cmd)
7420 (error (message "Error during update of dynamic block")))
7421 (goto-char pos)
7422 (unless (re-search-forward org-dblock-end-re nil t)
7423 (error "Dynamic block not terminated"))))))
7425 (defun org-dblock-update (&optional arg)
7426 "User command for updating dynamic blocks.
7427 Update the dynamic block at point. With prefix ARG, update all dynamic
7428 blocks in the buffer."
7429 (interactive "P")
7430 (if arg
7431 (org-update-all-dblocks)
7432 (or (looking-at org-dblock-start-re)
7433 (org-beginning-of-dblock))
7434 (org-update-dblock)))
7436 (defun org-update-dblock ()
7437 "Update the dynamic block at point
7438 This means to empty the block, parse for parameters and then call
7439 the correct writing function."
7440 (save-window-excursion
7441 (let* ((pos (point))
7442 (line (org-current-line))
7443 (params (org-prepare-dblock))
7444 (name (plist-get params :name))
7445 (cmd (intern (concat "org-dblock-write:" name))))
7446 (message "Updating dynamic block `%s' at line %d..." name line)
7447 (funcall cmd params)
7448 (message "Updating dynamic block `%s' at line %d...done" name line)
7449 (goto-char pos))))
7451 (defun org-beginning-of-dblock ()
7452 "Find the beginning of the dynamic block at point.
7453 Error if there is no scuh block at point."
7454 (let ((pos (point))
7455 beg)
7456 (end-of-line 1)
7457 (if (and (re-search-backward org-dblock-start-re nil t)
7458 (setq beg (match-beginning 0))
7459 (re-search-forward org-dblock-end-re nil t)
7460 (> (match-end 0) pos))
7461 (goto-char beg)
7462 (goto-char pos)
7463 (error "Not in a dynamic block"))))
7465 (defun org-update-all-dblocks ()
7466 "Update all dynamic blocks in the buffer.
7467 This function can be used in a hook."
7468 (when (org-mode-p)
7469 (org-map-dblocks 'org-update-dblock)))
7472 ;;;; Completion
7474 (defconst org-additional-option-like-keywords
7475 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7476 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7477 "BEGIN_EXAMPLE" "END_EXAMPLE"
7478 "BEGIN_QUOTE" "END_QUOTE"
7479 "BEGIN_VERSE" "END_VERSE"
7480 "BEGIN_SRC" "END_SRC"))
7482 (defcustom org-structure-template-alist
7484 ("s" "#+begin_src ?\n\n#+end_src"
7485 "<src lang=\"?\">\n\n</src>")
7486 ("e" "#+begin_example\n?\n#+end_example"
7487 "<example>\n?\n</example>")
7488 ("q" "#+begin_quote\n?\n#+end_quote"
7489 "<quote>\n?\n</quote>")
7490 ("v" "#+begin_verse\n?\n#+end_verse"
7491 "<verse>\n?\n/verse>")
7492 ("l" "#+begin_latex\n?\n#+end_latex"
7493 "<literal style=\"latex\">\n?\n</literal>")
7494 ("L" "#+latex: "
7495 "<literal style=\"latex\">?</literal>")
7496 ("h" "#+begin_html\n?\n#+end_html"
7497 "<literal style=\"html\">\n?\n</literal>")
7498 ("H" "#+html: "
7499 "<literal style=\"html\">?</literal>")
7500 ("a" "#+begin_ascii\n?\n#+end_ascii")
7501 ("A" "#+ascii: ")
7502 ("i" "#+include %file ?"
7503 "<include file=%file markup=\"?\">")
7505 "Structure completion elements.
7506 This is a list of abbreviation keys and values. The value gets inserted
7507 it you type @samp{.} followed by the key and then the completion key,
7508 usually `M-TAB'. %file will be replaced by a file name after prompting
7509 for the file uning completion.
7510 There are two templates for each key, the first uses the original Org syntax,
7511 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7512 the default when the /org-mtags.el/ module has been loaded. See also the
7513 variable `org-mtags-prefere-muse-templates'.
7514 This is an experimental feature, it is undecided if it is going to stay in."
7515 :group 'org-completion
7516 :type '(repeat
7517 (string :tag "Key")
7518 (string :tag "Template")
7519 (string :tag "Muse Template")))
7521 (defun org-try-structure-completion ()
7522 "Try to complete a structure template before point.
7523 This looks for strings like \"<e\" on an otherwise empty line and
7524 expands them."
7525 (let ((l (buffer-substring (point-at-bol) (point)))
7527 (when (and (looking-at "[ \t]*$")
7528 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7529 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7530 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7531 (match-beginning 1)) a)
7532 t)))
7534 (defun org-complete-expand-structure-template (start cell)
7535 "Expand a structure template."
7536 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7537 (rpl (nth (if musep 2 1) cell)))
7538 (delete-region start (point))
7539 (when (string-match "\\`#\\+" rpl)
7540 (cond
7541 ((bolp))
7542 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7543 (delete-region (point-at-bol) (point)))
7544 (t (newline))))
7545 (setq start (point))
7546 (if (string-match "%file" rpl)
7547 (setq rpl (replace-match
7548 (concat
7549 "\""
7550 (save-match-data
7551 (abbreviate-file-name (read-file-name "Include file: ")))
7552 "\"")
7553 t t rpl)))
7554 (insert rpl)
7555 (if (re-search-backward "\\?" start t) (delete-char 1))))
7558 (defun org-complete (&optional arg)
7559 "Perform completion on word at point.
7560 At the beginning of a headline, this completes TODO keywords as given in
7561 `org-todo-keywords'.
7562 If the current word is preceded by a backslash, completes the TeX symbols
7563 that are supported for HTML support.
7564 If the current word is preceded by \"#+\", completes special words for
7565 setting file options.
7566 In the line after \"#+STARTUP:, complete valid keywords.\"
7567 At all other locations, this simply calls the value of
7568 `org-completion-fallback-command'."
7569 (interactive "P")
7570 (org-without-partial-completion
7571 (catch 'exit
7572 (let* ((a nil)
7573 (end (point))
7574 (beg1 (save-excursion
7575 (skip-chars-backward (org-re "[:alnum:]_@"))
7576 (point)))
7577 (beg (save-excursion
7578 (skip-chars-backward "a-zA-Z0-9_:$")
7579 (point)))
7580 (confirm (lambda (x) (stringp (car x))))
7581 (searchhead (equal (char-before beg) ?*))
7582 (struct
7583 (when (and (member (char-before beg1) '(?. ?<))
7584 (setq a (assoc (buffer-substring beg1 (point))
7585 org-structure-template-alist)))
7586 (org-complete-expand-structure-template (1- beg1) a)
7587 (throw 'exit t)))
7588 (tag (and (equal (char-before beg1) ?:)
7589 (equal (char-after (point-at-bol)) ?*)))
7590 (prop (and (equal (char-before beg1) ?:)
7591 (not (equal (char-after (point-at-bol)) ?*))))
7592 (texp (equal (char-before beg) ?\\))
7593 (link (equal (char-before beg) ?\[))
7594 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7595 beg)
7596 "#+"))
7597 (startup (string-match "^#\\+STARTUP:.*"
7598 (buffer-substring (point-at-bol) (point))))
7599 (completion-ignore-case opt)
7600 (type nil)
7601 (tbl nil)
7602 (table (cond
7603 (opt
7604 (setq type :opt)
7605 (require 'org-exp)
7606 (append
7607 (mapcar
7608 (lambda (x)
7609 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7610 (cons (match-string 2 x) (match-string 1 x)))
7611 (org-split-string (org-get-current-options) "\n"))
7612 (mapcar 'list org-additional-option-like-keywords)))
7613 (startup
7614 (setq type :startup)
7615 org-startup-options)
7616 (link (append org-link-abbrev-alist-local
7617 org-link-abbrev-alist))
7618 (texp
7619 (setq type :tex)
7620 org-html-entities)
7621 ((string-match "\\`\\*+[ \t]+\\'"
7622 (buffer-substring (point-at-bol) beg))
7623 (setq type :todo)
7624 (mapcar 'list org-todo-keywords-1))
7625 (searchhead
7626 (setq type :searchhead)
7627 (save-excursion
7628 (goto-char (point-min))
7629 (while (re-search-forward org-todo-line-regexp nil t)
7630 (push (list
7631 (org-make-org-heading-search-string
7632 (match-string 3) t))
7633 tbl)))
7634 tbl)
7635 (tag (setq type :tag beg beg1)
7636 (or org-tag-alist (org-get-buffer-tags)))
7637 (prop (setq type :prop beg beg1)
7638 (mapcar 'list (org-buffer-property-keys nil t t)))
7639 (t (progn
7640 (call-interactively org-completion-fallback-command)
7641 (throw 'exit nil)))))
7642 (pattern (buffer-substring-no-properties beg end))
7643 (completion (try-completion pattern table confirm)))
7644 (cond ((eq completion t)
7645 (if (not (assoc (upcase pattern) table))
7646 (message "Already complete")
7647 (if (and (equal type :opt)
7648 (not (member (car (assoc (upcase pattern) table))
7649 org-additional-option-like-keywords)))
7650 (insert (substring (cdr (assoc (upcase pattern) table))
7651 (length pattern)))
7652 (if (memq type '(:tag :prop)) (insert ":")))))
7653 ((null completion)
7654 (message "Can't find completion for \"%s\"" pattern)
7655 (ding))
7656 ((not (string= pattern completion))
7657 (delete-region beg end)
7658 (if (string-match " +$" completion)
7659 (setq completion (replace-match "" t t completion)))
7660 (insert completion)
7661 (if (get-buffer-window "*Completions*")
7662 (delete-window (get-buffer-window "*Completions*")))
7663 (if (assoc completion table)
7664 (if (eq type :todo) (insert " ")
7665 (if (memq type '(:tag :prop)) (insert ":"))))
7666 (if (and (equal type :opt) (assoc completion table))
7667 (message "%s" (substitute-command-keys
7668 "Press \\[org-complete] again to insert example settings"))))
7670 (message "Making completion list...")
7671 (let ((list (sort (all-completions pattern table confirm)
7672 'string<)))
7673 (with-output-to-temp-buffer "*Completions*"
7674 (condition-case nil
7675 ;; Protection needed for XEmacs and emacs 21
7676 (display-completion-list list pattern)
7677 (error (display-completion-list list)))))
7678 (message "Making completion list...%s" "done")))))))
7680 ;;;; TODO, DEADLINE, Comments
7682 (defun org-toggle-comment ()
7683 "Change the COMMENT state of an entry."
7684 (interactive)
7685 (save-excursion
7686 (org-back-to-heading)
7687 (let (case-fold-search)
7688 (if (looking-at (concat outline-regexp
7689 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7690 (replace-match "" t t nil 1)
7691 (if (looking-at outline-regexp)
7692 (progn
7693 (goto-char (match-end 0))
7694 (insert org-comment-string " ")))))))
7696 (defvar org-last-todo-state-is-todo nil
7697 "This is non-nil when the last TODO state change led to a TODO state.
7698 If the last change removed the TODO tag or switched to DONE, then
7699 this is nil.")
7701 (defvar org-setting-tags nil) ; dynamically skiped
7703 (defun org-parse-local-options (string var)
7704 "Parse STRING for startup setting relevant for variable VAR."
7705 (let ((rtn (symbol-value var))
7706 e opts)
7707 (save-match-data
7708 (if (or (not string) (not (string-match "\\S-" string)))
7710 (setq opts (delq nil (mapcar (lambda (x)
7711 (setq e (assoc x org-startup-options))
7712 (if (eq (nth 1 e) var) e nil))
7713 (org-split-string string "[ \t]+"))))
7714 (if (not opts)
7716 (setq rtn nil)
7717 (while (setq e (pop opts))
7718 (if (not (nth 3 e))
7719 (setq rtn (nth 2 e))
7720 (if (not (listp rtn)) (setq rtn nil))
7721 (push (nth 2 e) rtn)))
7722 rtn)))))
7724 (defvar org-blocker-hook nil
7725 "Hook for functions that are allowed to block a state change.
7727 Each function gets as its single argument a property list, see
7728 `org-trigger-hook' for more information about this list.
7730 If any of the functions in this hook returns nil, the state change
7731 is blocked.")
7733 (defvar org-trigger-hook nil
7734 "Hook for functions that are triggered by a state change.
7736 Each function gets as its single argument a property list with at least
7737 the following elements:
7739 (:type type-of-change :position pos-at-entry-start
7740 :from old-state :to new-state)
7742 Depending on the type, more properties may be present.
7744 This mechanism is currently implemented for:
7746 TODO state changes
7747 ------------------
7748 :type todo-state-change
7749 :from previous state (keyword as a string), or nil
7750 :to new state (keyword as a string), or nil")
7753 (defun org-todo (&optional arg)
7754 "Change the TODO state of an item.
7755 The state of an item is given by a keyword at the start of the heading,
7756 like
7757 *** TODO Write paper
7758 *** DONE Call mom
7760 The different keywords are specified in the variable `org-todo-keywords'.
7761 By default the available states are \"TODO\" and \"DONE\".
7762 So for this example: when the item starts with TODO, it is changed to DONE.
7763 When it starts with DONE, the DONE is removed. And when neither TODO nor
7764 DONE are present, add TODO at the beginning of the heading.
7766 With C-u prefix arg, use completion to determine the new state.
7767 With numeric prefix arg, switch to that state.
7769 For calling through lisp, arg is also interpreted in the following way:
7770 'none -> empty state
7771 \"\"(empty string) -> switch to empty state
7772 'done -> switch to DONE
7773 'nextset -> switch to the next set of keywords
7774 'previousset -> switch to the previous set of keywords
7775 \"WAITING\" -> switch to the specified keyword, but only if it
7776 really is a member of `org-todo-keywords'."
7777 (interactive "P")
7778 (save-excursion
7779 (catch 'exit
7780 (org-back-to-heading)
7781 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7782 (or (looking-at (concat " +" org-todo-regexp " *"))
7783 (looking-at " *"))
7784 (let* ((match-data (match-data))
7785 (startpos (point-at-bol))
7786 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7787 (org-log-done org-log-done)
7788 (org-log-repeat org-log-repeat)
7789 (org-todo-log-states org-todo-log-states)
7790 (this (match-string 1))
7791 (hl-pos (match-beginning 0))
7792 (head (org-get-todo-sequence-head this))
7793 (ass (assoc head org-todo-kwd-alist))
7794 (interpret (nth 1 ass))
7795 (done-word (nth 3 ass))
7796 (final-done-word (nth 4 ass))
7797 (last-state (or this ""))
7798 (completion-ignore-case t)
7799 (member (member this org-todo-keywords-1))
7800 (tail (cdr member))
7801 (state (cond
7802 ((and org-todo-key-trigger
7803 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7804 (and (not arg) org-use-fast-todo-selection
7805 (not (eq org-use-fast-todo-selection 'prefix)))))
7806 ;; Use fast selection
7807 (org-fast-todo-selection))
7808 ((and (equal arg '(4))
7809 (or (not org-use-fast-todo-selection)
7810 (not org-todo-key-trigger)))
7811 ;; Read a state with completion
7812 (completing-read "State: " (mapcar (lambda(x) (list x))
7813 org-todo-keywords-1)
7814 nil t))
7815 ((eq arg 'right)
7816 (if this
7817 (if tail (car tail) nil)
7818 (car org-todo-keywords-1)))
7819 ((eq arg 'left)
7820 (if (equal member org-todo-keywords-1)
7822 (if this
7823 (nth (- (length org-todo-keywords-1) (length tail) 2)
7824 org-todo-keywords-1)
7825 (org-last org-todo-keywords-1))))
7826 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7827 (setq arg nil))) ; hack to fall back to cycling
7828 (arg
7829 ;; user or caller requests a specific state
7830 (cond
7831 ((equal arg "") nil)
7832 ((eq arg 'none) nil)
7833 ((eq arg 'done) (or done-word (car org-done-keywords)))
7834 ((eq arg 'nextset)
7835 (or (car (cdr (member head org-todo-heads)))
7836 (car org-todo-heads)))
7837 ((eq arg 'previousset)
7838 (let ((org-todo-heads (reverse org-todo-heads)))
7839 (or (car (cdr (member head org-todo-heads)))
7840 (car org-todo-heads))))
7841 ((car (member arg org-todo-keywords-1)))
7842 ((nth (1- (prefix-numeric-value arg))
7843 org-todo-keywords-1))))
7844 ((null member) (or head (car org-todo-keywords-1)))
7845 ((equal this final-done-word) nil) ;; -> make empty
7846 ((null tail) nil) ;; -> first entry
7847 ((eq interpret 'sequence)
7848 (car tail))
7849 ((memq interpret '(type priority))
7850 (if (eq this-command last-command)
7851 (car tail)
7852 (if (> (length tail) 0)
7853 (or done-word (car org-done-keywords))
7854 nil)))
7855 (t nil)))
7856 (next (if state (concat " " state " ") " "))
7857 (change-plist (list :type 'todo-state-change :from this :to state
7858 :position startpos))
7859 dolog now-done-p)
7860 (when org-blocker-hook
7861 (unless (save-excursion
7862 (save-match-data
7863 (run-hook-with-args-until-failure
7864 'org-blocker-hook change-plist)))
7865 (if (interactive-p)
7866 (error "TODO state change from %s to %s blocked" this state)
7867 ;; fail silently
7868 (message "TODO state change from %s to %s blocked" this state)
7869 (throw 'exit nil))))
7870 (store-match-data match-data)
7871 (replace-match next t t)
7872 (unless (pos-visible-in-window-p hl-pos)
7873 (message "TODO state changed to %s" (org-trim next)))
7874 (unless head
7875 (setq head (org-get-todo-sequence-head state)
7876 ass (assoc head org-todo-kwd-alist)
7877 interpret (nth 1 ass)
7878 done-word (nth 3 ass)
7879 final-done-word (nth 4 ass)))
7880 (when (memq arg '(nextset previousset))
7881 (message "Keyword-Set %d/%d: %s"
7882 (- (length org-todo-sets) -1
7883 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7884 (length org-todo-sets)
7885 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7886 (setq org-last-todo-state-is-todo
7887 (not (member state org-done-keywords)))
7888 (setq now-done-p (and (member state org-done-keywords)
7889 (not (member this org-done-keywords))))
7890 (and logging (org-local-logging logging))
7891 (when (and (or org-todo-log-states org-log-done)
7892 (not (memq arg '(nextset previousset))))
7893 ;; we need to look at recording a time and note
7894 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7895 (nth 2 (assoc this org-todo-log-states))))
7896 (when (and state
7897 (member state org-not-done-keywords)
7898 (not (member this org-not-done-keywords)))
7899 ;; This is now a todo state and was not one before
7900 ;; If there was a CLOSED time stamp, get rid of it.
7901 (org-add-planning-info nil nil 'closed))
7902 (when (and now-done-p org-log-done)
7903 ;; It is now done, and it was not done before
7904 (org-add-planning-info 'closed (org-current-time))
7905 (if (and (not dolog) (eq 'note org-log-done))
7906 (org-add-log-setup 'done state 'findpos 'note)))
7907 (when (and state dolog)
7908 ;; This is a non-nil state, and we need to log it
7909 (org-add-log-setup 'state state 'findpos dolog)))
7910 ;; Fixup tag positioning
7911 (org-todo-trigger-tag-changes state)
7912 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7913 (when org-provide-todo-statistics
7914 (org-update-parent-todo-statistics))
7915 (run-hooks 'org-after-todo-state-change-hook)
7916 (if (and arg (not (member state org-done-keywords)))
7917 (setq head (org-get-todo-sequence-head state)))
7918 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7919 ;; Do we need to trigger a repeat?
7920 (when now-done-p (org-auto-repeat-maybe state))
7921 ;; Fixup cursor location if close to the keyword
7922 (if (and (outline-on-heading-p)
7923 (not (bolp))
7924 (save-excursion (beginning-of-line 1)
7925 (looking-at org-todo-line-regexp))
7926 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7927 (progn
7928 (goto-char (or (match-end 2) (match-end 1)))
7929 (just-one-space)))
7930 (when org-trigger-hook
7931 (save-excursion
7932 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7934 (defun org-update-parent-todo-statistics ()
7935 "Update any statistics cookie in the parent of the current headline."
7936 (interactive)
7937 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7938 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7939 (catch 'exit
7940 (save-excursion
7941 (setq level (org-up-heading-safe))
7942 (unless (and level
7943 (re-search-forward box-re (point-at-eol) t))
7944 (throw 'exit nil))
7945 (setq is-percent (match-end 2))
7946 (save-match-data
7947 (unless (outline-next-heading) (throw 'exit nil))
7948 (while (looking-at org-todo-line-regexp)
7949 (setq kwd (match-string 2))
7950 (and kwd (setq cnt-all (1+ cnt-all)))
7951 (and (member kwd org-done-keywords)
7952 (setq cnt-done (1+ cnt-done)))
7953 (condition-case nil
7954 (org-forward-same-level 1)
7955 (error (end-of-line 1)))))
7956 (replace-match
7957 (if is-percent
7958 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7959 (format "[%d/%d]" cnt-done cnt-all)))
7960 (run-hook-with-args 'org-after-todo-statistics-hook
7961 cnt-done (- cnt-all cnt-done))))))
7963 (defvar org-after-todo-statistics-hook nil
7964 "Hook that is called after a TODO statistics cookie has been updated.
7965 Each function is called with two arguments: the number of not-done entries
7966 and the number of done entries.
7968 For example, the following function, when added to this hook, will switch
7969 an entry to DONE when all children are done, and back to TODO when new
7970 entries are set to a TODO status. Note that this hook is only called
7971 when there is a statistics cookie in the headline!
7973 (defun org-summary-todo (n-done n-not-done)
7974 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
7975 (let (org-log-done org-log-states) ; turn off logging
7976 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
7979 (defun org-todo-trigger-tag-changes (state)
7980 "Apply the changes defined in `org-todo-state-tags-triggers'."
7981 (let ((l org-todo-state-tags-triggers)
7982 changes)
7983 (when (or (not state) (equal state ""))
7984 (setq changes (append changes (cdr (assoc "" l)))))
7985 (when (and (stringp state) (> (length state) 0))
7986 (setq changes (append changes (cdr (assoc state l)))))
7987 (when (member state org-not-done-keywords)
7988 (setq changes (append changes (cdr (assoc 'todo l)))))
7989 (when (member state org-done-keywords)
7990 (setq changes (append changes (cdr (assoc 'done l)))))
7991 (dolist (c changes)
7992 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
7994 (defun org-local-logging (value)
7995 "Get logging settings from a property VALUE."
7996 (let* (words w a)
7997 ;; directly set the variables, they are already local.
7998 (setq org-log-done nil
7999 org-log-repeat nil
8000 org-todo-log-states nil)
8001 (setq words (org-split-string value))
8002 (while (setq w (pop words))
8003 (cond
8004 ((setq a (assoc w org-startup-options))
8005 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8006 (set (nth 1 a) (nth 2 a))))
8007 ((setq a (org-extract-log-state-settings w))
8008 (and (member (car a) org-todo-keywords-1)
8009 (push a org-todo-log-states)))))))
8011 (defun org-get-todo-sequence-head (kwd)
8012 "Return the head of the TODO sequence to which KWD belongs.
8013 If KWD is not set, check if there is a text property remembering the
8014 right sequence."
8015 (let (p)
8016 (cond
8017 ((not kwd)
8018 (or (get-text-property (point-at-bol) 'org-todo-head)
8019 (progn
8020 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8021 nil (point-at-eol)))
8022 (get-text-property p 'org-todo-head))))
8023 ((not (member kwd org-todo-keywords-1))
8024 (car org-todo-keywords-1))
8025 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8027 (defun org-fast-todo-selection ()
8028 "Fast TODO keyword selection with single keys.
8029 Returns the new TODO keyword, or nil if no state change should occur."
8030 (let* ((fulltable org-todo-key-alist)
8031 (done-keywords org-done-keywords) ;; needed for the faces.
8032 (maxlen (apply 'max (mapcar
8033 (lambda (x)
8034 (if (stringp (car x)) (string-width (car x)) 0))
8035 fulltable)))
8036 (expert nil)
8037 (fwidth (+ maxlen 3 1 3))
8038 (ncol (/ (- (window-width) 4) fwidth))
8039 tg cnt e c tbl
8040 groups ingroup)
8041 (save-window-excursion
8042 (if expert
8043 (set-buffer (get-buffer-create " *Org todo*"))
8044 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8045 (erase-buffer)
8046 (org-set-local 'org-done-keywords done-keywords)
8047 (setq tbl fulltable cnt 0)
8048 (while (setq e (pop tbl))
8049 (cond
8050 ((equal e '(:startgroup))
8051 (push '() groups) (setq ingroup t)
8052 (when (not (= cnt 0))
8053 (setq cnt 0)
8054 (insert "\n"))
8055 (insert "{ "))
8056 ((equal e '(:endgroup))
8057 (setq ingroup nil cnt 0)
8058 (insert "}\n"))
8060 (setq tg (car e) c (cdr e))
8061 (if ingroup (push tg (car groups)))
8062 (setq tg (org-add-props tg nil 'face
8063 (org-get-todo-face tg)))
8064 (if (and (= cnt 0) (not ingroup)) (insert " "))
8065 (insert "[" c "] " tg (make-string
8066 (- fwidth 4 (length tg)) ?\ ))
8067 (when (= (setq cnt (1+ cnt)) ncol)
8068 (insert "\n")
8069 (if ingroup (insert " "))
8070 (setq cnt 0)))))
8071 (insert "\n")
8072 (goto-char (point-min))
8073 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8074 (fit-window-to-buffer))
8075 (message "[a-z..]:Set [SPC]:clear")
8076 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8077 (cond
8078 ((or (= c ?\C-g)
8079 (and (= c ?q) (not (rassoc c fulltable))))
8080 (setq quit-flag t))
8081 ((= c ?\ ) nil)
8082 ((setq e (rassoc c fulltable) tg (car e))
8084 (t (setq quit-flag t))))))
8086 (defun org-entry-is-todo-p ()
8087 (member (org-get-todo-state) org-not-done-keywords))
8089 (defun org-entry-is-done-p ()
8090 (member (org-get-todo-state) org-done-keywords))
8092 (defun org-get-todo-state ()
8093 (save-excursion
8094 (org-back-to-heading t)
8095 (and (looking-at org-todo-line-regexp)
8096 (match-end 2)
8097 (match-string 2))))
8099 (defun org-at-date-range-p (&optional inactive-ok)
8100 "Is the cursor inside a date range?"
8101 (interactive)
8102 (save-excursion
8103 (catch 'exit
8104 (let ((pos (point)))
8105 (skip-chars-backward "^[<\r\n")
8106 (skip-chars-backward "<[")
8107 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8108 (>= (match-end 0) pos)
8109 (throw 'exit t))
8110 (skip-chars-backward "^<[\r\n")
8111 (skip-chars-backward "<[")
8112 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8113 (>= (match-end 0) pos)
8114 (throw 'exit t)))
8115 nil)))
8117 (defun org-get-repeat ()
8118 "Check if there is a deadline/schedule with repeater in this entry."
8119 (save-match-data
8120 (save-excursion
8121 (org-back-to-heading t)
8122 (if (re-search-forward
8123 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8124 (match-string 1)))))
8126 (defvar org-last-changed-timestamp)
8127 (defvar org-last-inserted-timestamp)
8128 (defvar org-log-post-message)
8129 (defvar org-log-note-purpose)
8130 (defvar org-log-note-how)
8131 (defvar org-log-note-extra)
8132 (defun org-auto-repeat-maybe (done-word)
8133 "Check if the current headline contains a repeated deadline/schedule.
8134 If yes, set TODO state back to what it was and change the base date
8135 of repeating deadline/scheduled time stamps to new date.
8136 This function is run automatically after each state change to a DONE state."
8137 ;; last-state is dynamically scoped into this function
8138 (let* ((repeat (org-get-repeat))
8139 (aa (assoc last-state org-todo-kwd-alist))
8140 (interpret (nth 1 aa))
8141 (head (nth 2 aa))
8142 (whata '(("d" . day) ("m" . month) ("y" . year)))
8143 (msg "Entry repeats: ")
8144 (org-log-done nil)
8145 (org-todo-log-states nil)
8146 (nshiftmax 10) (nshift 0)
8147 re type n what ts mb0 time)
8148 (when repeat
8149 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8150 (org-todo (if (eq interpret 'type) last-state head))
8151 (when org-log-repeat
8152 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8153 (memq 'org-add-log-note post-command-hook))
8154 ;; OK, we are already setup for some record
8155 (if (eq org-log-repeat 'note)
8156 ;; make sure we take a note, not only a time stamp
8157 (setq org-log-note-how 'note))
8158 ;; Set up for taking a record
8159 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8160 'findpos org-log-repeat)))
8161 (org-back-to-heading t)
8162 (org-add-planning-info nil nil 'closed)
8163 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8164 org-deadline-time-regexp "\\)\\|\\("
8165 org-ts-regexp "\\)"))
8166 (while (re-search-forward
8167 re (save-excursion (outline-next-heading) (point)) t)
8168 (setq type (if (match-end 1) org-scheduled-string
8169 (if (match-end 3) org-deadline-string "Plain:"))
8170 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8171 mb0 (match-beginning 0))
8172 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8173 (setq n (string-to-number (match-string 2 ts))
8174 what (match-string 3 ts))
8175 (if (equal what "w") (setq n (* n 7) what "d"))
8176 ;; Preparation, see if we need to modify the start date for the change
8177 (when (match-end 1)
8178 (setq time (save-match-data (org-time-string-to-time ts)))
8179 (cond
8180 ((equal (match-string 1 ts) ".")
8181 ;; Shift starting date to today
8182 (org-timestamp-change
8183 (- (time-to-days (current-time)) (time-to-days time))
8184 'day))
8185 ((equal (match-string 1 ts) "+")
8186 (while (or (= nshift 0)
8187 (<= (time-to-days time) (time-to-days (current-time))))
8188 (when (= (incf nshift) nshiftmax)
8189 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8190 (error "Abort")))
8191 (org-timestamp-change n (cdr (assoc what whata)))
8192 (org-at-timestamp-p t)
8193 (setq ts (match-string 1))
8194 (setq time (save-match-data (org-time-string-to-time ts))))
8195 (org-timestamp-change (- n) (cdr (assoc what whata)))
8196 ;; rematch, so that we have everything in place for the real shift
8197 (org-at-timestamp-p t)
8198 (setq ts (match-string 1))
8199 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8200 (org-timestamp-change n (cdr (assoc what whata)))
8201 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8202 (setq org-log-post-message msg)
8203 (message "%s" msg))))
8205 (defun org-show-todo-tree (arg)
8206 "Make a compact tree which shows all headlines marked with TODO.
8207 The tree will show the lines where the regexp matches, and all higher
8208 headlines above the match.
8209 With a \\[universal-argument] prefix, also show the DONE entries.
8210 With a numeric prefix N, construct a sparse tree for the Nth element
8211 of `org-todo-keywords-1'."
8212 (interactive "P")
8213 (let ((case-fold-search nil)
8214 (kwd-re
8215 (cond ((null arg) org-not-done-regexp)
8216 ((equal arg '(4))
8217 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8218 (mapcar 'list org-todo-keywords-1))))
8219 (concat "\\("
8220 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8221 "\\)\\>")))
8222 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8223 (regexp-quote (nth (1- (prefix-numeric-value arg))
8224 org-todo-keywords-1)))
8225 (t (error "Invalid prefix argument: %s" arg)))))
8226 (message "%d TODO entries found"
8227 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8229 (defun org-deadline (&optional remove time)
8230 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8231 With argument REMOVE, remove any deadline from the item.
8232 When TIME is set, it should be an internal time specification, and the
8233 scheduling will use the corresponding date."
8234 (interactive "P")
8235 (if remove
8236 (progn
8237 (org-remove-timestamp-with-keyword org-deadline-string)
8238 (message "Item no longer has a deadline."))
8239 (if (org-get-repeat)
8240 (error "Cannot change deadline on task with repeater, please do that by hand")
8241 (org-add-planning-info 'deadline time 'closed)
8242 (message "Deadline on %s" org-last-inserted-timestamp))))
8244 (defun org-schedule (&optional remove time)
8245 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8246 With argument REMOVE, remove any scheduling date from the item.
8247 When TIME is set, it should be an internal time specification, and the
8248 scheduling will use the corresponding date."
8249 (interactive "P")
8250 (if remove
8251 (progn
8252 (org-remove-timestamp-with-keyword org-scheduled-string)
8253 (message "Item is no longer scheduled."))
8254 (if (org-get-repeat)
8255 (error "Cannot reschedule task with repeater, please do that by hand")
8256 (org-add-planning-info 'scheduled time 'closed)
8257 (message "Scheduled to %s" org-last-inserted-timestamp))))
8259 (defun org-remove-timestamp-with-keyword (keyword)
8260 "Remove all time stamps with KEYWORD in the current entry."
8261 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8262 beg)
8263 (save-excursion
8264 (org-back-to-heading t)
8265 (setq beg (point))
8266 (org-end-of-subtree t t)
8267 (while (re-search-backward re beg t)
8268 (replace-match "")
8269 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8270 (equal (char-before) ?\ ))
8271 (backward-delete-char 1)
8272 (if (string-match "^[ \t]*$" (buffer-substring
8273 (point-at-bol) (point-at-eol)))
8274 (delete-region (point-at-bol)
8275 (min (point-max) (1+ (point-at-eol))))))))))
8277 (defun org-add-planning-info (what &optional time &rest remove)
8278 "Insert new timestamp with keyword in the line directly after the headline.
8279 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8280 If non is given, the user is prompted for a date.
8281 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8282 be removed."
8283 (interactive)
8284 (let (org-time-was-given org-end-time-was-given ts
8285 end default-time default-input)
8287 (when (and (not time) (memq what '(scheduled deadline)))
8288 ;; Try to get a default date/time from existing timestamp
8289 (save-excursion
8290 (org-back-to-heading t)
8291 (setq end (save-excursion (outline-next-heading) (point)))
8292 (when (re-search-forward (if (eq what 'scheduled)
8293 org-scheduled-time-regexp
8294 org-deadline-time-regexp)
8295 end t)
8296 (setq ts (match-string 1)
8297 default-time
8298 (apply 'encode-time (org-parse-time-string ts))
8299 default-input (and ts (org-get-compact-tod ts))))))
8300 (when what
8301 ;; If necessary, get the time from the user
8302 (setq time (or time (org-read-date nil 'to-time nil nil
8303 default-time default-input))))
8305 (when (and org-insert-labeled-timestamps-at-point
8306 (member what '(scheduled deadline)))
8307 (insert
8308 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8309 (org-insert-time-stamp time org-time-was-given
8310 nil nil nil (list org-end-time-was-given))
8311 (setq what nil))
8312 (save-excursion
8313 (save-restriction
8314 (let (col list elt ts buffer-invisibility-spec)
8315 (org-back-to-heading t)
8316 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8317 (goto-char (match-end 1))
8318 (setq col (current-column))
8319 (goto-char (match-end 0))
8320 (if (eobp) (insert "\n") (forward-char 1))
8321 (if (and (not (looking-at outline-regexp))
8322 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8323 "[^\r\n]*"))
8324 (not (equal (match-string 1) org-clock-string)))
8325 (narrow-to-region (match-beginning 0) (match-end 0))
8326 (insert-before-markers "\n")
8327 (backward-char 1)
8328 (narrow-to-region (point) (point))
8329 (and org-adapt-indentation (org-indent-to-column col)))
8330 ;; Check if we have to remove something.
8331 (setq list (cons what remove))
8332 (while list
8333 (setq elt (pop list))
8334 (goto-char (point-min))
8335 (when (or (and (eq elt 'scheduled)
8336 (re-search-forward org-scheduled-time-regexp nil t))
8337 (and (eq elt 'deadline)
8338 (re-search-forward org-deadline-time-regexp nil t))
8339 (and (eq elt 'closed)
8340 (re-search-forward org-closed-time-regexp nil t)))
8341 (replace-match "")
8342 (if (looking-at "--+<[^>]+>") (replace-match ""))
8343 (if (looking-at " +") (replace-match ""))))
8344 (goto-char (point-max))
8345 (when what
8346 (insert
8347 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8348 (cond ((eq what 'scheduled) org-scheduled-string)
8349 ((eq what 'deadline) org-deadline-string)
8350 ((eq what 'closed) org-closed-string))
8351 " ")
8352 (setq ts (org-insert-time-stamp
8353 time
8354 (or org-time-was-given
8355 (and (eq what 'closed) org-log-done-with-time))
8356 (eq what 'closed)
8357 nil nil (list org-end-time-was-given)))
8358 (end-of-line 1))
8359 (goto-char (point-min))
8360 (widen)
8361 (if (and (looking-at "[ \t]+\n")
8362 (equal (char-before) ?\n))
8363 (delete-region (1- (point)) (point-at-eol)))
8364 ts)))))
8366 (defvar org-log-note-marker (make-marker))
8367 (defvar org-log-note-purpose nil)
8368 (defvar org-log-note-state nil)
8369 (defvar org-log-note-how nil)
8370 (defvar org-log-note-extra nil)
8371 (defvar org-log-note-window-configuration nil)
8372 (defvar org-log-note-return-to (make-marker))
8373 (defvar org-log-post-message nil
8374 "Message to be displayed after a log note has been stored.
8375 The auto-repeater uses this.")
8377 (defun org-add-note ()
8378 "Add a note to the current entry.
8379 This is done in the same way as adding a state change note."
8380 (interactive)
8381 (org-add-log-setup 'note nil 'findpos nil))
8383 (defvar org-property-end-re)
8384 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8385 "Set up the post command hook to take a note.
8386 If this is about to TODO state change, the new state is expected in STATE.
8387 When FINDPOS is non-nil, find the correct position for the note in
8388 the current entry. If not, assume that it can be inserted at point.
8389 HOW is an indicator what kind of note should be created.
8390 EXTRA is additional text that will be inserted into the notes buffer."
8391 (save-restriction
8392 (save-excursion
8393 (when findpos
8394 (org-back-to-heading t)
8395 (narrow-to-region (point) (save-excursion
8396 (outline-next-heading) (point)))
8397 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8398 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8399 "[^\r\n]*\\)?"))
8400 (goto-char (match-end 0))
8401 (when (and org-log-state-notes-insert-after-drawers
8402 (save-excursion
8403 (forward-line) (looking-at org-drawer-regexp)))
8404 (progn (forward-line)
8405 (while (looking-at org-drawer-regexp)
8406 (goto-char (match-end 0))
8407 (re-search-forward org-property-end-re (point-max) t)
8408 (forward-line))))
8409 (unless org-log-states-order-reversed
8410 (and (= (char-after) ?\n) (forward-char 1))
8411 (org-skip-over-state-notes)
8412 (skip-chars-backward " \t\n\r")))
8413 (move-marker org-log-note-marker (point))
8414 (setq org-log-note-purpose purpose
8415 org-log-note-state state
8416 org-log-note-how how
8417 org-log-note-extra extra)
8418 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8420 (defun org-skip-over-state-notes ()
8421 "Skip past the list of State notes in an entry."
8422 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8423 (while (looking-at "[ \t]*- State")
8424 (condition-case nil
8425 (org-next-item)
8426 (error (org-end-of-item)))))
8428 (defun org-add-log-note (&optional purpose)
8429 "Pop up a window for taking a note, and add this note later at point."
8430 (remove-hook 'post-command-hook 'org-add-log-note)
8431 (setq org-log-note-window-configuration (current-window-configuration))
8432 (delete-other-windows)
8433 (move-marker org-log-note-return-to (point))
8434 (switch-to-buffer (marker-buffer org-log-note-marker))
8435 (goto-char org-log-note-marker)
8436 (org-switch-to-buffer-other-window "*Org Note*")
8437 (erase-buffer)
8438 (if (memq org-log-note-how '(time state))
8439 (org-store-log-note)
8440 (let ((org-inhibit-startup t)) (org-mode))
8441 (insert (format "# Insert note for %s.
8442 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8443 (cond
8444 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8445 ((eq org-log-note-purpose 'done) "closed todo item")
8446 ((eq org-log-note-purpose 'state)
8447 (format "state change to \"%s\"" org-log-note-state))
8448 ((eq org-log-note-purpose 'note)
8449 "this entry")
8450 (t (error "This should not happen")))))
8451 (if org-log-note-extra (insert org-log-note-extra))
8452 (org-set-local 'org-finish-function 'org-store-log-note)))
8454 (defvar org-note-abort nil) ; dynamically scoped
8455 (defun org-store-log-note ()
8456 "Finish taking a log note, and insert it to where it belongs."
8457 (let ((txt (buffer-string))
8458 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8459 lines ind)
8460 (kill-buffer (current-buffer))
8461 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8462 (setq txt (replace-match "" t t txt)))
8463 (if (string-match "\\s-+\\'" txt)
8464 (setq txt (replace-match "" t t txt)))
8465 (setq lines (org-split-string txt "\n"))
8466 (when (and note (string-match "\\S-" note))
8467 (setq note
8468 (org-replace-escapes
8469 note
8470 (list (cons "%u" (user-login-name))
8471 (cons "%U" user-full-name)
8472 (cons "%t" (format-time-string
8473 (org-time-stamp-format 'long 'inactive)
8474 (current-time)))
8475 (cons "%s" (if org-log-note-state
8476 (concat "\"" org-log-note-state "\"")
8477 "")))))
8478 (if lines (setq note (concat note " \\\\")))
8479 (push note lines))
8480 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8481 (when lines
8482 (save-excursion
8483 (set-buffer (marker-buffer org-log-note-marker))
8484 (save-excursion
8485 (goto-char org-log-note-marker)
8486 (move-marker org-log-note-marker nil)
8487 (end-of-line 1)
8488 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8489 (indent-relative nil)
8490 (insert "- " (pop lines))
8491 (org-indent-line-function)
8492 (beginning-of-line 1)
8493 (looking-at "[ \t]*")
8494 (setq ind (concat (match-string 0) " "))
8495 (end-of-line 1)
8496 (while lines (insert "\n" ind (pop lines)))))))
8497 (set-window-configuration org-log-note-window-configuration)
8498 (with-current-buffer (marker-buffer org-log-note-return-to)
8499 (goto-char org-log-note-return-to))
8500 (move-marker org-log-note-return-to nil)
8501 (and org-log-post-message (message "%s" org-log-post-message)))
8503 (defun org-sparse-tree (&optional arg)
8504 "Create a sparse tree, prompt for the details.
8505 This command can create sparse trees. You first need to select the type
8506 of match used to create the tree:
8508 t Show entries with a specific TODO keyword.
8509 T Show entries selected by a tags match.
8510 p Enter a property name and its value (both with completion on existing
8511 names/values) and show entries with that property.
8512 r Show entries matching a regular expression
8513 d Show deadlines due within `org-deadline-warning-days'."
8514 (interactive "P")
8515 (let (ans kwd value)
8516 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8517 (setq ans (read-char-exclusive))
8518 (cond
8519 ((equal ans ?d)
8520 (call-interactively 'org-check-deadlines))
8521 ((equal ans ?b)
8522 (call-interactively 'org-check-before-date))
8523 ((equal ans ?t)
8524 (org-show-todo-tree '(4)))
8525 ((equal ans ?T)
8526 (call-interactively 'org-tags-sparse-tree))
8527 ((member ans '(?p ?P))
8528 (setq kwd (completing-read "Property: "
8529 (mapcar 'list (org-buffer-property-keys))))
8530 (setq value (completing-read "Value: "
8531 (mapcar 'list (org-property-values kwd))))
8532 (unless (string-match "\\`{.*}\\'" value)
8533 (setq value (concat "\"" value "\"")))
8534 (org-tags-sparse-tree arg (concat kwd "=" value)))
8535 ((member ans '(?r ?R ?/))
8536 (call-interactively 'org-occur))
8537 (t (error "No such sparse tree command \"%c\"" ans)))))
8539 (defvar org-occur-highlights nil
8540 "List of overlays used for occur matches.")
8541 (make-variable-buffer-local 'org-occur-highlights)
8542 (defvar org-occur-parameters nil
8543 "Parameters of the active org-occur calls.
8544 This is a list, each call to org-occur pushes as cons cell,
8545 containing the regular expression and the callback, onto the list.
8546 The list can contain several entries if `org-occur' has been called
8547 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8548 will only contain one set of parameters. When the highlights are
8549 removed (for example with `C-c C-c', or with the next edit (depending
8550 on `org-remove-highlights-with-change'), this variable is emptied
8551 as well.")
8552 (make-variable-buffer-local 'org-occur-parameters)
8554 (defun org-occur (regexp &optional keep-previous callback)
8555 "Make a compact tree which shows all matches of REGEXP.
8556 The tree will show the lines where the regexp matches, and all higher
8557 headlines above the match. It will also show the heading after the match,
8558 to make sure editing the matching entry is easy.
8559 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8560 call to `org-occur' will be kept, to allow stacking of calls to this
8561 command.
8562 If CALLBACK is non-nil, it is a function which is called to confirm
8563 that the match should indeed be shown."
8564 (interactive "sRegexp: \nP")
8565 (unless keep-previous
8566 (org-remove-occur-highlights nil nil t))
8567 (push (cons regexp callback) org-occur-parameters)
8568 (let ((cnt 0))
8569 (save-excursion
8570 (goto-char (point-min))
8571 (if (or (not keep-previous) ; do not want to keep
8572 (not org-occur-highlights)) ; no previous matches
8573 ;; hide everything
8574 (org-overview))
8575 (while (re-search-forward regexp nil t)
8576 (when (or (not callback)
8577 (save-match-data (funcall callback)))
8578 (setq cnt (1+ cnt))
8579 (when org-highlight-sparse-tree-matches
8580 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8581 (org-show-context 'occur-tree))))
8582 (when org-remove-highlights-with-change
8583 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8584 nil 'local))
8585 (unless org-sparse-tree-open-archived-trees
8586 (org-hide-archived-subtrees (point-min) (point-max)))
8587 (run-hooks 'org-occur-hook)
8588 (if (interactive-p)
8589 (message "%d match(es) for regexp %s" cnt regexp))
8590 cnt))
8592 (defun org-show-context (&optional key)
8593 "Make sure point and context and visible.
8594 How much context is shown depends upon the variables
8595 `org-show-hierarchy-above', `org-show-following-heading'. and
8596 `org-show-siblings'."
8597 (let ((heading-p (org-on-heading-p t))
8598 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8599 (following-p (org-get-alist-option org-show-following-heading key))
8600 (entry-p (org-get-alist-option org-show-entry-below key))
8601 (siblings-p (org-get-alist-option org-show-siblings key)))
8602 (catch 'exit
8603 ;; Show heading or entry text
8604 (if (and heading-p (not entry-p))
8605 (org-flag-heading nil) ; only show the heading
8606 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8607 (org-show-hidden-entry))) ; show entire entry
8608 (when following-p
8609 ;; Show next sibling, or heading below text
8610 (save-excursion
8611 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8612 (org-flag-heading nil))))
8613 (when siblings-p (org-show-siblings))
8614 (when hierarchy-p
8615 ;; show all higher headings, possibly with siblings
8616 (save-excursion
8617 (while (and (condition-case nil
8618 (progn (org-up-heading-all 1) t)
8619 (error nil))
8620 (not (bobp)))
8621 (org-flag-heading nil)
8622 (when siblings-p (org-show-siblings))))))))
8624 (defun org-reveal (&optional siblings)
8625 "Show current entry, hierarchy above it, and the following headline.
8626 This can be used to show a consistent set of context around locations
8627 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8628 not t for the search context.
8630 With optional argument SIBLINGS, on each level of the hierarchy all
8631 siblings are shown. This repairs the tree structure to what it would
8632 look like when opened with hierarchical calls to `org-cycle'."
8633 (interactive "P")
8634 (let ((org-show-hierarchy-above t)
8635 (org-show-following-heading t)
8636 (org-show-siblings (if siblings t org-show-siblings)))
8637 (org-show-context nil)))
8639 (defun org-highlight-new-match (beg end)
8640 "Highlight from BEG to END and mark the highlight is an occur headline."
8641 (let ((ov (org-make-overlay beg end)))
8642 (org-overlay-put ov 'face 'secondary-selection)
8643 (push ov org-occur-highlights)))
8645 (defun org-remove-occur-highlights (&optional beg end noremove)
8646 "Remove the occur highlights from the buffer.
8647 BEG and END are ignored. If NOREMOVE is nil, remove this function
8648 from the `before-change-functions' in the current buffer."
8649 (interactive)
8650 (unless org-inhibit-highlight-removal
8651 (mapc 'org-delete-overlay org-occur-highlights)
8652 (setq org-occur-highlights nil)
8653 (setq org-occur-parameters nil)
8654 (unless noremove
8655 (remove-hook 'before-change-functions
8656 'org-remove-occur-highlights 'local))))
8658 ;;;; Priorities
8660 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8661 "Regular expression matching the priority indicator.")
8663 (defvar org-remove-priority-next-time nil)
8665 (defun org-priority-up ()
8666 "Increase the priority of the current item."
8667 (interactive)
8668 (org-priority 'up))
8670 (defun org-priority-down ()
8671 "Decrease the priority of the current item."
8672 (interactive)
8673 (org-priority 'down))
8675 (defun org-priority (&optional action)
8676 "Change the priority of an item by ARG.
8677 ACTION can be `set', `up', `down', or a character."
8678 (interactive)
8679 (setq action (or action 'set))
8680 (let (current new news have remove)
8681 (save-excursion
8682 (org-back-to-heading)
8683 (if (looking-at org-priority-regexp)
8684 (setq current (string-to-char (match-string 2))
8685 have t)
8686 (setq current org-default-priority))
8687 (cond
8688 ((or (eq action 'set)
8689 (if (featurep 'xemacs) (characterp action) (integerp action)))
8690 (if (not (eq action 'set))
8691 (setq new action)
8692 (message "Priority %c-%c, SPC to remove: "
8693 org-highest-priority org-lowest-priority)
8694 (setq new (read-char-exclusive)))
8695 (if (and (= (upcase org-highest-priority) org-highest-priority)
8696 (= (upcase org-lowest-priority) org-lowest-priority))
8697 (setq new (upcase new)))
8698 (cond ((equal new ?\ ) (setq remove t))
8699 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8700 (error "Priority must be between `%c' and `%c'"
8701 org-highest-priority org-lowest-priority))))
8702 ((eq action 'up)
8703 (if (and (not have) (eq last-command this-command))
8704 (setq new org-lowest-priority)
8705 (setq new (if (and org-priority-start-cycle-with-default (not have))
8706 org-default-priority (1- current)))))
8707 ((eq action 'down)
8708 (if (and (not have) (eq last-command this-command))
8709 (setq new org-highest-priority)
8710 (setq new (if (and org-priority-start-cycle-with-default (not have))
8711 org-default-priority (1+ current)))))
8712 (t (error "Invalid action")))
8713 (if (or (< (upcase new) org-highest-priority)
8714 (> (upcase new) org-lowest-priority))
8715 (setq remove t))
8716 (setq news (format "%c" new))
8717 (if have
8718 (if remove
8719 (replace-match "" t t nil 1)
8720 (replace-match news t t nil 2))
8721 (if remove
8722 (error "No priority cookie found in line")
8723 (looking-at org-todo-line-regexp)
8724 (if (match-end 2)
8725 (progn
8726 (goto-char (match-end 2))
8727 (insert " [#" news "]"))
8728 (goto-char (match-beginning 3))
8729 (insert "[#" news "] ")))))
8730 (org-preserve-lc (org-set-tags nil 'align))
8731 (if remove
8732 (message "Priority removed")
8733 (message "Priority of current item set to %s" news))))
8736 (defun org-get-priority (s)
8737 "Find priority cookie and return priority."
8738 (save-match-data
8739 (if (not (string-match org-priority-regexp s))
8740 (* 1000 (- org-lowest-priority org-default-priority))
8741 (* 1000 (- org-lowest-priority
8742 (string-to-char (match-string 2 s)))))))
8744 ;;;; Tags
8746 (defvar org-agenda-archives-mode)
8747 (defun org-scan-tags (action matcher &optional todo-only)
8748 "Scan headline tags with inheritance and produce output ACTION.
8750 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8751 or `agenda' to produce an entry list for an agenda view. It can also be
8752 a Lisp form or a function that should be called at each matched headline, in
8753 this case the return value is a list of all return values from these calls.
8755 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8756 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8757 only lines with a TODO keyword are included in the output."
8758 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8759 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8760 (org-re
8761 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8762 (props (list 'face 'default
8763 'done-face 'org-done
8764 'undone-face 'default
8765 'mouse-face 'highlight
8766 'org-not-done-regexp org-not-done-regexp
8767 'org-todo-regexp org-todo-regexp
8768 'keymap org-agenda-keymap
8769 'help-echo
8770 (format "mouse-2 or RET jump to org file %s"
8771 (abbreviate-file-name
8772 (or (buffer-file-name (buffer-base-buffer))
8773 (buffer-name (buffer-base-buffer)))))))
8774 (case-fold-search nil)
8775 lspos tags tags-list
8776 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8777 (llast 0) rtn rtn1 level category i txt
8778 todo marker entry priority)
8779 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8780 (setq action (list 'lambda nil action)))
8781 (save-excursion
8782 (goto-char (point-min))
8783 (when (eq action 'sparse-tree)
8784 (org-overview)
8785 (org-remove-occur-highlights))
8786 (while (re-search-forward re nil t)
8787 (catch :skip
8788 (setq todo (if (match-end 1) (match-string 2))
8789 tags (if (match-end 4) (match-string 4)))
8790 (goto-char (setq lspos (1+ (match-beginning 0))))
8791 (setq level (org-reduced-level (funcall outline-level))
8792 category (org-get-category))
8793 (setq i llast llast level)
8794 ;; remove tag lists from same and sublevels
8795 (while (>= i level)
8796 (when (setq entry (assoc i tags-alist))
8797 (setq tags-alist (delete entry tags-alist)))
8798 (setq i (1- i)))
8799 ;; add the next tags
8800 (when tags
8801 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8802 tags-alist
8803 (cons (cons level tags) tags-alist)))
8804 ;; compile tags for current headline
8805 (setq tags-list
8806 (if org-use-tag-inheritance
8807 (apply 'append (mapcar 'cdr tags-alist))
8808 tags))
8809 (when (and tags org-use-tag-inheritance
8810 (not (eq t org-use-tag-inheritance)))
8811 ;; selective inheritance, remove uninherited ones
8812 (setcdr (car tags-alist)
8813 (org-remove-uniherited-tags (cdar tags-alist))))
8814 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8815 (let ((case-fold-search t)) (eval matcher))
8817 (not (member org-archive-tag tags-list))
8818 ;; we have an archive tag, should we use this anyway?
8819 (or (not org-agenda-skip-archived-trees)
8820 (and (eq action 'agenda) org-agenda-archives-mode))))
8821 (unless (eq action 'sparse-tree) (org-agenda-skip))
8823 ;; select this headline
8825 (cond
8826 ((eq action 'sparse-tree)
8827 (and org-highlight-sparse-tree-matches
8828 (org-get-heading) (match-end 0)
8829 (org-highlight-new-match
8830 (match-beginning 0) (match-beginning 1)))
8831 (org-show-context 'tags-tree))
8832 ((eq action 'agenda)
8833 (setq txt (org-format-agenda-item
8835 (concat
8836 (if org-tags-match-list-sublevels
8837 (make-string (1- level) ?.) "")
8838 (org-get-heading))
8839 category tags-list)
8840 priority (org-get-priority txt))
8841 (goto-char lspos)
8842 (setq marker (org-agenda-new-marker))
8843 (org-add-props txt props
8844 'org-marker marker 'org-hd-marker marker 'org-category category
8845 'priority priority 'type "tagsmatch")
8846 (push txt rtn))
8847 ((functionp action)
8848 (save-excursion
8849 (setq rtn1 (funcall action))
8850 (push rtn1 rtn))
8851 (goto-char (point-at-eol)))
8852 (t (error "Invalid action")))
8854 ;; if we are to skip sublevels, jump to end of subtree
8855 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8856 (when (and (eq action 'sparse-tree)
8857 (not org-sparse-tree-open-archived-trees))
8858 (org-hide-archived-subtrees (point-min) (point-max)))
8859 (nreverse rtn)))
8861 (defun org-remove-uniherited-tags (tags)
8862 "Remove all tags that are not inherited from the list TAGS."
8863 (cond
8864 ((eq org-use-tag-inheritance t) tags)
8865 ((not org-use-tag-inheritance) nil)
8866 ((stringp org-use-tag-inheritance)
8867 (delq nil (mapcar
8868 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8869 tags)))
8870 ((listp org-use-tag-inheritance)
8871 (delq nil (mapcar
8872 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8873 tags)))))
8875 (defvar todo-only) ;; dynamically scoped
8877 (defun org-tags-sparse-tree (&optional todo-only match)
8878 "Create a sparse tree according to tags string MATCH.
8879 MATCH can contain positive and negative selection of tags, like
8880 \"+WORK+URGENT-WITHBOSS\".
8881 If optional argument TODO_ONLY is non-nil, only select lines that are
8882 also TODO lines."
8883 (interactive "P")
8884 (org-prepare-agenda-buffers (list (current-buffer)))
8885 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8887 (defvar org-cached-props nil)
8888 (defun org-cached-entry-get (pom property)
8889 (if (or (eq t org-use-property-inheritance)
8890 (and (stringp org-use-property-inheritance)
8891 (string-match org-use-property-inheritance property))
8892 (and (listp org-use-property-inheritance)
8893 (member property org-use-property-inheritance)))
8894 ;; Caching is not possible, check it directly
8895 (org-entry-get pom property 'inherit)
8896 ;; Get all properties, so that we can do complicated checks easily
8897 (cdr (assoc property (or org-cached-props
8898 (setq org-cached-props
8899 (org-entry-properties pom)))))))
8901 (defun org-global-tags-completion-table (&optional files)
8902 "Return the list of all tags in all agenda buffer/files."
8903 (save-excursion
8904 (org-uniquify
8905 (delq nil
8906 (apply 'append
8907 (mapcar
8908 (lambda (file)
8909 (set-buffer (find-file-noselect file))
8910 (append (org-get-buffer-tags)
8911 (mapcar (lambda (x) (if (stringp (car-safe x))
8912 (list (car-safe x)) nil))
8913 org-tag-alist)))
8914 (if (and files (car files))
8915 files
8916 (org-agenda-files))))))))
8918 (defun org-make-tags-matcher (match)
8919 "Create the TAGS//TODO matcher form for the selection string MATCH."
8920 ;; todo-only is scoped dynamically into this function, and the function
8921 ;; may change it it the matcher asksk for it.
8922 (unless match
8923 ;; Get a new match request, with completion
8924 (let ((org-last-tags-completion-table
8925 (org-global-tags-completion-table)))
8926 (setq match (completing-read
8927 "Match: " 'org-tags-completion-function nil nil nil
8928 'org-tags-history))))
8930 ;; Parse the string and create a lisp form
8931 (let ((match0 match)
8932 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8933 minus tag mm
8934 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8935 orterms term orlist re-p str-p level-p level-op time-p
8936 prop-p pn pv po cat-p gv)
8937 (if (string-match "/+" match)
8938 ;; match contains also a todo-matching request
8939 (progn
8940 (setq tagsmatch (substring match 0 (match-beginning 0))
8941 todomatch (substring match (match-end 0)))
8942 (if (string-match "^!" todomatch)
8943 (setq todo-only t todomatch (substring todomatch 1)))
8944 (if (string-match "^\\s-*$" todomatch)
8945 (setq todomatch nil)))
8946 ;; only matching tags
8947 (setq tagsmatch match todomatch nil))
8949 ;; Make the tags matcher
8950 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8951 (setq tagsmatcher t)
8952 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8953 (while (setq term (pop orterms))
8954 (while (and (equal (substring term -1) "\\") orterms)
8955 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8956 (while (string-match re term)
8957 (setq minus (and (match-end 1)
8958 (equal (match-string 1 term) "-"))
8959 tag (match-string 2 term)
8960 re-p (equal (string-to-char tag) ?{)
8961 level-p (match-end 4)
8962 prop-p (match-end 5)
8963 mm (cond
8964 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8965 (level-p
8966 (setq level-op (org-op-to-function (match-string 3 term)))
8967 `(,level-op level ,(string-to-number
8968 (match-string 4 term))))
8969 (prop-p
8970 (setq pn (match-string 5 term)
8971 po (match-string 6 term)
8972 pv (match-string 7 term)
8973 cat-p (equal pn "CATEGORY")
8974 re-p (equal (string-to-char pv) ?{)
8975 str-p (equal (string-to-char pv) ?\")
8976 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
8977 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8978 (if time-p (setq pv (org-matcher-time pv)))
8979 (setq po (org-op-to-function po (if time-p 'time str-p)))
8980 (if (equal pn "CATEGORY")
8981 (setq gv '(get-text-property (point) 'org-category))
8982 (setq gv `(org-cached-entry-get nil ,pn)))
8983 (if re-p
8984 (if (eq po 'org<>)
8985 `(not (string-match ,pv (or ,gv "")))
8986 `(string-match ,pv (or ,gv "")))
8987 (if str-p
8988 `(,po (or ,gv "") ,pv)
8989 `(,po (string-to-number (or ,gv ""))
8990 ,(string-to-number pv) ))))
8991 (t `(member ,(downcase tag) tags-list)))
8992 mm (if minus (list 'not mm) mm)
8993 term (substring term (match-end 0)))
8994 (push mm tagsmatcher))
8995 (push (if (> (length tagsmatcher) 1)
8996 (cons 'and tagsmatcher)
8997 (car tagsmatcher))
8998 orlist)
8999 (setq tagsmatcher nil))
9000 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9001 (setq tagsmatcher
9002 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9003 ;; Make the todo matcher
9004 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9005 (setq todomatcher t)
9006 (setq orterms (org-split-string todomatch "|") orlist nil)
9007 (while (setq term (pop orterms))
9008 (while (string-match re term)
9009 (setq minus (and (match-end 1)
9010 (equal (match-string 1 term) "-"))
9011 kwd (match-string 2 term)
9012 re-p (equal (string-to-char kwd) ?{)
9013 term (substring term (match-end 0))
9014 mm (if re-p
9015 `(string-match ,(substring kwd 1 -1) todo)
9016 (list 'equal 'todo kwd))
9017 mm (if minus (list 'not mm) mm))
9018 (push mm todomatcher))
9019 (push (if (> (length todomatcher) 1)
9020 (cons 'and todomatcher)
9021 (car todomatcher))
9022 orlist)
9023 (setq todomatcher nil))
9024 (setq todomatcher (if (> (length orlist) 1)
9025 (cons 'or orlist) (car orlist))))
9027 ;; Return the string and lisp forms of the matcher
9028 (setq matcher (if todomatcher
9029 (list 'and tagsmatcher todomatcher)
9030 tagsmatcher))
9031 (cons match0 matcher)))
9033 (defun org-op-to-function (op &optional stringp)
9034 "Turn an operator into the appropriate function."
9035 (setq op
9036 (cond
9037 ((equal op "<" ) '(< string< org-time<))
9038 ((equal op ">" ) '(> org-string> org-time>))
9039 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9040 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9041 ((member op '("=" "==")) '(= string= org-time=))
9042 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9043 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9045 (defun org<> (a b) (not (= a b)))
9046 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9047 (defun org-string>= (a b) (not (string< a b)))
9048 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9049 (defun org-string<> (a b) (not (string= a b)))
9050 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9051 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9052 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9053 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9054 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9055 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9056 (defun org-2ft (s)
9057 "Convert S to a floating point time.
9058 If S is already a number, just return it. If it is a string, parse
9059 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9060 (cond
9061 ((numberp s) s)
9062 ((stringp s)
9063 (condition-case nil
9064 (float-time (apply 'encode-time (org-parse-time-string s)))
9065 (error 0.)))
9066 (t 0.)))
9068 (defun org-matcher-time (s)
9069 (cond
9070 ((equal s "<now>") (float-time))
9071 ((equal s "<today>")
9072 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9073 (t (org-2ft s))))
9075 (defun org-match-any-p (re list)
9076 "Does re match any element of list?"
9077 (setq list (mapcar (lambda (x) (string-match re x)) list))
9078 (delq nil list))
9080 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9081 (defvar org-tags-overlay (org-make-overlay 1 1))
9082 (org-detach-overlay org-tags-overlay)
9084 (defun org-get-local-tags-at (&optional pos)
9085 "Get a list of tags defined in the current headline."
9086 (org-get-tags-at pos 'local))
9088 (defun org-get-local-tags ()
9089 "Get a list of tags defined in the current headline."
9090 (org-get-tags-at nil 'local))
9092 (defun org-get-tags-at (&optional pos local)
9093 "Get a list of all headline tags applicable at POS.
9094 POS defaults to point. If tags are inherited, the list contains
9095 the targets in the same sequence as the headlines appear, i.e.
9096 the tags of the current headline come last.
9097 When LOCAL is non-nil, only return tags from the current headline,
9098 ignore inherited ones."
9099 (interactive)
9100 (let (tags ltags lastpos parent)
9101 (save-excursion
9102 (save-restriction
9103 (widen)
9104 (goto-char (or pos (point)))
9105 (save-match-data
9106 (catch 'done
9107 (condition-case nil
9108 (progn
9109 (org-back-to-heading t)
9110 (while (not (equal lastpos (point)))
9111 (setq lastpos (point))
9112 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9113 (setq ltags (org-split-string
9114 (org-match-string-no-properties 1) ":"))
9115 (setq tags (append
9116 (if parent
9117 (org-remove-uniherited-tags ltags)
9118 ltags)
9119 tags)))
9120 (or org-use-tag-inheritance (throw 'done t))
9121 (if local (throw 'done t))
9122 (org-up-heading-all 1)
9123 (setq parent t)))
9124 (error nil)))))
9125 (append (org-remove-uniherited-tags org-file-tags) tags))))
9127 (defun org-toggle-tag (tag &optional onoff)
9128 "Toggle the tag TAG for the current line.
9129 If ONOFF is `on' or `off', don't toggle but set to this state."
9130 (unless (org-on-heading-p t) (error "Not on headling"))
9131 (let (res current)
9132 (save-excursion
9133 (beginning-of-line)
9134 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9135 (point-at-eol) t)
9136 (progn
9137 (setq current (match-string 1))
9138 (replace-match ""))
9139 (setq current ""))
9140 (setq current (nreverse (org-split-string current ":")))
9141 (cond
9142 ((eq onoff 'on)
9143 (setq res t)
9144 (or (member tag current) (push tag current)))
9145 ((eq onoff 'off)
9146 (or (not (member tag current)) (setq current (delete tag current))))
9147 (t (if (member tag current)
9148 (setq current (delete tag current))
9149 (setq res t)
9150 (push tag current))))
9151 (end-of-line 1)
9152 (if current
9153 (progn
9154 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9155 (org-set-tags nil t))
9156 (delete-horizontal-space))
9157 (run-hooks 'org-after-tags-change-hook))
9158 res))
9160 (defun org-align-tags-here (to-col)
9161 ;; Assumes that this is a headline
9162 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9163 (beginning-of-line 1)
9164 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9165 (< pos (match-beginning 2)))
9166 (progn
9167 (setq tags-l (- (match-end 2) (match-beginning 2)))
9168 (goto-char (match-beginning 1))
9169 (insert " ")
9170 (delete-region (point) (1+ (match-beginning 2)))
9171 (setq ncol (max (1+ (current-column))
9172 (1+ col)
9173 (if (> to-col 0)
9174 to-col
9175 (- (abs to-col) tags-l))))
9176 (setq p (point))
9177 (insert (make-string (- ncol (current-column)) ?\ ))
9178 (setq ncol (current-column))
9179 (when indent-tabs-mode (tabify p (point-at-eol)))
9180 (org-move-to-column (min ncol col) t))
9181 (goto-char pos))))
9183 (defun org-set-tags-command (&optional arg just-align)
9184 "Call the set-tags command for the current entry."
9185 (interactive "P")
9186 (if (org-on-heading-p)
9187 (org-set-tags arg just-align)
9188 (save-excursion
9189 (org-back-to-heading t)
9190 (org-set-tags arg just-align))))
9192 (defun org-set-tags (&optional arg just-align)
9193 "Set the tags for the current headline.
9194 With prefix ARG, realign all tags in headings in the current buffer."
9195 (interactive "P")
9196 (let* ((re (concat "^" outline-regexp))
9197 (current (org-get-tags-string))
9198 (col (current-column))
9199 (org-setting-tags t)
9200 table current-tags inherited-tags ; computed below when needed
9201 tags p0 c0 c1 rpl)
9202 (if arg
9203 (save-excursion
9204 (goto-char (point-min))
9205 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9206 (while (re-search-forward re nil t)
9207 (org-set-tags nil t)
9208 (end-of-line 1)))
9209 (message "All tags realigned to column %d" org-tags-column))
9210 (if just-align
9211 (setq tags current)
9212 ;; Get a new set of tags from the user
9213 (save-excursion
9214 (setq table (or org-tag-alist (org-get-buffer-tags))
9215 org-last-tags-completion-table table
9216 current-tags (org-split-string current ":")
9217 inherited-tags (nreverse
9218 (nthcdr (length current-tags)
9219 (nreverse (org-get-tags-at))))
9220 tags
9221 (if (or (eq t org-use-fast-tag-selection)
9222 (and org-use-fast-tag-selection
9223 (delq nil (mapcar 'cdr table))))
9224 (org-fast-tag-selection
9225 current-tags inherited-tags table
9226 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9227 (let ((org-add-colon-after-tag-completion t))
9228 (org-trim
9229 (org-without-partial-completion
9230 (completing-read "Tags: " 'org-tags-completion-function
9231 nil nil current 'org-tags-history)))))))
9232 (while (string-match "[-+&]+" tags)
9233 ;; No boolean logic, just a list
9234 (setq tags (replace-match ":" t t tags))))
9236 (if (string-match "\\`[\t ]*\\'" tags)
9237 (setq tags "")
9238 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9239 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9241 ;; Insert new tags at the correct column
9242 (beginning-of-line 1)
9243 (cond
9244 ((and (equal current "") (equal tags "")))
9245 ((re-search-forward
9246 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9247 (point-at-eol) t)
9248 (if (equal tags "")
9249 (setq rpl "")
9250 (goto-char (match-beginning 0))
9251 (setq c0 (current-column) p0 (point)
9252 c1 (max (1+ c0) (if (> org-tags-column 0)
9253 org-tags-column
9254 (- (- org-tags-column) (length tags))))
9255 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9256 (replace-match rpl t t)
9257 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9258 tags)
9259 (t (error "Tags alignment failed")))
9260 (org-move-to-column col)
9261 (unless just-align
9262 (run-hooks 'org-after-tags-change-hook)))))
9264 (defun org-change-tag-in-region (beg end tag off)
9265 "Add or remove TAG for each entry in the region.
9266 This works in the agenda, and also in an org-mode buffer."
9267 (interactive
9268 (list (region-beginning) (region-end)
9269 (let ((org-last-tags-completion-table
9270 (if (org-mode-p)
9271 (org-get-buffer-tags)
9272 (org-global-tags-completion-table))))
9273 (completing-read
9274 "Tag: " 'org-tags-completion-function nil nil nil
9275 'org-tags-history))
9276 (progn
9277 (message "[s]et or [r]emove? ")
9278 (equal (read-char-exclusive) ?r))))
9279 (if (fboundp 'deactivate-mark) (deactivate-mark))
9280 (let ((agendap (equal major-mode 'org-agenda-mode))
9281 l1 l2 m buf pos newhead (cnt 0))
9282 (goto-char end)
9283 (setq l2 (1- (org-current-line)))
9284 (goto-char beg)
9285 (setq l1 (org-current-line))
9286 (loop for l from l1 to l2 do
9287 (goto-line l)
9288 (setq m (get-text-property (point) 'org-hd-marker))
9289 (when (or (and (org-mode-p) (org-on-heading-p))
9290 (and agendap m))
9291 (setq buf (if agendap (marker-buffer m) (current-buffer))
9292 pos (if agendap m (point)))
9293 (with-current-buffer buf
9294 (save-excursion
9295 (save-restriction
9296 (goto-char pos)
9297 (setq cnt (1+ cnt))
9298 (org-toggle-tag tag (if off 'off 'on))
9299 (setq newhead (org-get-heading)))))
9300 (and agendap (org-agenda-change-all-lines newhead m))))
9301 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9303 (defun org-tags-completion-function (string predicate &optional flag)
9304 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9305 (confirm (lambda (x) (stringp (car x)))))
9306 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9307 (setq s1 (match-string 1 string)
9308 s2 (match-string 2 string))
9309 (setq s1 "" s2 string))
9310 (cond
9311 ((eq flag nil)
9312 ;; try completion
9313 (setq rtn (try-completion s2 ctable confirm))
9314 (if (stringp rtn)
9315 (setq rtn
9316 (concat s1 s2 (substring rtn (length s2))
9317 (if (and org-add-colon-after-tag-completion
9318 (assoc rtn ctable))
9319 ":" ""))))
9320 rtn)
9321 ((eq flag t)
9322 ;; all-completions
9323 (all-completions s2 ctable confirm)
9325 ((eq flag 'lambda)
9326 ;; exact match?
9327 (assoc s2 ctable)))
9330 (defun org-fast-tag-insert (kwd tags face &optional end)
9331 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9332 (insert (format "%-12s" (concat kwd ":"))
9333 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9334 (or end "")))
9336 (defun org-fast-tag-show-exit (flag)
9337 (save-excursion
9338 (goto-line 3)
9339 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9340 (replace-match ""))
9341 (when flag
9342 (end-of-line 1)
9343 (org-move-to-column (- (window-width) 19) t)
9344 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9346 (defun org-set-current-tags-overlay (current prefix)
9347 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9348 (if (featurep 'xemacs)
9349 (org-overlay-display org-tags-overlay (concat prefix s)
9350 'secondary-selection)
9351 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9352 (org-overlay-display org-tags-overlay (concat prefix s)))))
9354 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9355 "Fast tag selection with single keys.
9356 CURRENT is the current list of tags in the headline, INHERITED is the
9357 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9358 possibly with grouping information. TODO-TABLE is a similar table with
9359 TODO keywords, should these have keys assigned to them.
9360 If the keys are nil, a-z are automatically assigned.
9361 Returns the new tags string, or nil to not change the current settings."
9362 (let* ((fulltable (append table todo-table))
9363 (maxlen (apply 'max (mapcar
9364 (lambda (x)
9365 (if (stringp (car x)) (string-width (car x)) 0))
9366 fulltable)))
9367 (buf (current-buffer))
9368 (expert (eq org-fast-tag-selection-single-key 'expert))
9369 (buffer-tags nil)
9370 (fwidth (+ maxlen 3 1 3))
9371 (ncol (/ (- (window-width) 4) fwidth))
9372 (i-face 'org-done)
9373 (c-face 'org-todo)
9374 tg cnt e c char c1 c2 ntable tbl rtn
9375 ov-start ov-end ov-prefix
9376 (exit-after-next org-fast-tag-selection-single-key)
9377 (done-keywords org-done-keywords)
9378 groups ingroup)
9379 (save-excursion
9380 (beginning-of-line 1)
9381 (if (looking-at
9382 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9383 (setq ov-start (match-beginning 1)
9384 ov-end (match-end 1)
9385 ov-prefix "")
9386 (setq ov-start (1- (point-at-eol))
9387 ov-end (1+ ov-start))
9388 (skip-chars-forward "^\n\r")
9389 (setq ov-prefix
9390 (concat
9391 (buffer-substring (1- (point)) (point))
9392 (if (> (current-column) org-tags-column)
9394 (make-string (- org-tags-column (current-column)) ?\ ))))))
9395 (org-move-overlay org-tags-overlay ov-start ov-end)
9396 (save-window-excursion
9397 (if expert
9398 (set-buffer (get-buffer-create " *Org tags*"))
9399 (delete-other-windows)
9400 (split-window-vertically)
9401 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9402 (erase-buffer)
9403 (org-set-local 'org-done-keywords done-keywords)
9404 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9405 (org-fast-tag-insert "Current" current c-face "\n\n")
9406 (org-fast-tag-show-exit exit-after-next)
9407 (org-set-current-tags-overlay current ov-prefix)
9408 (setq tbl fulltable char ?a cnt 0)
9409 (while (setq e (pop tbl))
9410 (cond
9411 ((equal e '(:startgroup))
9412 (push '() groups) (setq ingroup t)
9413 (when (not (= cnt 0))
9414 (setq cnt 0)
9415 (insert "\n"))
9416 (insert "{ "))
9417 ((equal e '(:endgroup))
9418 (setq ingroup nil cnt 0)
9419 (insert "}\n"))
9421 (setq tg (car e) c2 nil)
9422 (if (cdr e)
9423 (setq c (cdr e))
9424 ;; automatically assign a character.
9425 (setq c1 (string-to-char
9426 (downcase (substring
9427 tg (if (= (string-to-char tg) ?@) 1 0)))))
9428 (if (or (rassoc c1 ntable) (rassoc c1 table))
9429 (while (or (rassoc char ntable) (rassoc char table))
9430 (setq char (1+ char)))
9431 (setq c2 c1))
9432 (setq c (or c2 char)))
9433 (if ingroup (push tg (car groups)))
9434 (setq tg (org-add-props tg nil 'face
9435 (cond
9436 ((not (assoc tg table))
9437 (org-get-todo-face tg))
9438 ((member tg current) c-face)
9439 ((member tg inherited) i-face)
9440 (t nil))))
9441 (if (and (= cnt 0) (not ingroup)) (insert " "))
9442 (insert "[" c "] " tg (make-string
9443 (- fwidth 4 (length tg)) ?\ ))
9444 (push (cons tg c) ntable)
9445 (when (= (setq cnt (1+ cnt)) ncol)
9446 (insert "\n")
9447 (if ingroup (insert " "))
9448 (setq cnt 0)))))
9449 (setq ntable (nreverse ntable))
9450 (insert "\n")
9451 (goto-char (point-min))
9452 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9453 (fit-window-to-buffer))
9454 (setq rtn
9455 (catch 'exit
9456 (while t
9457 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9458 (if groups " [!] no groups" " [!]groups")
9459 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9460 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9461 (cond
9462 ((= c ?\r) (throw 'exit t))
9463 ((= c ?!)
9464 (setq groups (not groups))
9465 (goto-char (point-min))
9466 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9467 ((= c ?\C-c)
9468 (if (not expert)
9469 (org-fast-tag-show-exit
9470 (setq exit-after-next (not exit-after-next)))
9471 (setq expert nil)
9472 (delete-other-windows)
9473 (split-window-vertically)
9474 (org-switch-to-buffer-other-window " *Org tags*")
9475 (and (fboundp 'fit-window-to-buffer)
9476 (fit-window-to-buffer))))
9477 ((or (= c ?\C-g)
9478 (and (= c ?q) (not (rassoc c ntable))))
9479 (org-detach-overlay org-tags-overlay)
9480 (setq quit-flag t))
9481 ((= c ?\ )
9482 (setq current nil)
9483 (if exit-after-next (setq exit-after-next 'now)))
9484 ((= c ?\t)
9485 (condition-case nil
9486 (setq tg (completing-read
9487 "Tag: "
9488 (or buffer-tags
9489 (with-current-buffer buf
9490 (org-get-buffer-tags)))))
9491 (quit (setq tg "")))
9492 (when (string-match "\\S-" tg)
9493 (add-to-list 'buffer-tags (list tg))
9494 (if (member tg current)
9495 (setq current (delete tg current))
9496 (push tg current)))
9497 (if exit-after-next (setq exit-after-next 'now)))
9498 ((setq e (rassoc c todo-table) tg (car e))
9499 (with-current-buffer buf
9500 (save-excursion (org-todo tg)))
9501 (if exit-after-next (setq exit-after-next 'now)))
9502 ((setq e (rassoc c ntable) tg (car e))
9503 (if (member tg current)
9504 (setq current (delete tg current))
9505 (loop for g in groups do
9506 (if (member tg g)
9507 (mapc (lambda (x)
9508 (setq current (delete x current)))
9509 g)))
9510 (push tg current))
9511 (if exit-after-next (setq exit-after-next 'now))))
9513 ;; Create a sorted list
9514 (setq current
9515 (sort current
9516 (lambda (a b)
9517 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9518 (if (eq exit-after-next 'now) (throw 'exit t))
9519 (goto-char (point-min))
9520 (beginning-of-line 2)
9521 (delete-region (point) (point-at-eol))
9522 (org-fast-tag-insert "Current" current c-face)
9523 (org-set-current-tags-overlay current ov-prefix)
9524 (while (re-search-forward
9525 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9526 (setq tg (match-string 1))
9527 (add-text-properties
9528 (match-beginning 1) (match-end 1)
9529 (list 'face
9530 (cond
9531 ((member tg current) c-face)
9532 ((member tg inherited) i-face)
9533 (t (get-text-property (match-beginning 1) 'face))))))
9534 (goto-char (point-min)))))
9535 (org-detach-overlay org-tags-overlay)
9536 (if rtn
9537 (mapconcat 'identity current ":")
9538 nil))))
9540 (defun org-get-tags-string ()
9541 "Get the TAGS string in the current headline."
9542 (unless (org-on-heading-p t)
9543 (error "Not on a heading"))
9544 (save-excursion
9545 (beginning-of-line 1)
9546 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9547 (org-match-string-no-properties 1)
9548 "")))
9550 (defun org-get-tags ()
9551 "Get the list of tags specified in the current headline."
9552 (org-split-string (org-get-tags-string) ":"))
9554 (defun org-get-buffer-tags ()
9555 "Get a table of all tags used in the buffer, for completion."
9556 (let (tags)
9557 (save-excursion
9558 (goto-char (point-min))
9559 (while (re-search-forward
9560 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9561 (when (equal (char-after (point-at-bol 0)) ?*)
9562 (mapc (lambda (x) (add-to-list 'tags x))
9563 (org-split-string (org-match-string-no-properties 1) ":")))))
9564 (mapcar 'list tags)))
9566 ;;;; The mapping API
9568 ;;;###autoload
9569 (defun org-map-entries (func &optional match scope &rest skip)
9570 "Call FUNC at each headline selected by MATCH in SCOPE.
9572 FUNC is a function or a lisp form. The function will be called without
9573 arguments, with the cursor positioned at the beginning of the headline.
9574 The return values of all calls to the function will be collected and
9575 returned as a list.
9577 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9578 Only headlines that are matched by this query will be considered during
9579 the iteration. When MATCH is nil or t, all headlines will be
9580 visited by the iteration.
9582 SCOPE determines the scope of this command. It can be any of:
9584 nil The current buffer, respecting the restriction if any
9585 tree The subtree started with the entry at point
9586 file The current buffer, without restriction
9587 file-with-archives
9588 The current buffer, and any archives associated with it
9589 agenda All agenda files
9590 agenda-with-archives
9591 All agenda files with any archive files associated with them
9592 \(file1 file2 ...)
9593 If this is a list, all files in the list will be scanned
9595 The remaining args are treated as settings for the skipping facilities of
9596 the scanner. The following items can be given here:
9598 archive skip trees with the archive tag.
9599 comment skip trees with the COMMENT keyword
9600 function or Emacs Lisp form:
9601 will be used as value for `org-agenda-skip-function', so whenever
9602 the the function returns t, FUNC will not be called for that
9603 entry and search will continue from the point where the
9604 function leaves it."
9605 (let* ((org-agenda-archives-mode nil) ; just to make sure
9606 (org-agenda-skip-archived-trees (memq 'archive skip))
9607 (org-agenda-skip-comment-trees (memq 'comment skip))
9608 (org-agenda-skip-function
9609 (car (org-delete-all '(comment archive) skip)))
9610 (org-tags-match-list-sublevels t)
9611 matcher pos file
9612 org-todo-keywords-for-agenda
9613 org-done-keywords-for-agenda
9614 org-todo-keyword-alist-for-agenda
9615 org-tag-alist-for-agenda)
9617 (cond
9618 ((eq match t) (setq matcher t))
9619 ((eq match nil) (setq matcher t))
9620 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9622 (when (eq scope 'tree)
9623 (org-back-to-heading t)
9624 (org-narrow-to-subtree)
9625 (setq scope nil))
9627 (if (not scope)
9628 (progn
9629 (org-prepare-agenda-buffers
9630 (list (buffer-file-name (current-buffer))))
9631 (org-scan-tags func matcher))
9632 ;; Get the right scope
9633 (setq pos (point))
9634 (cond
9635 ((and scope (listp scope) (symbolp (car scope)))
9636 (setq scope (eval scope)))
9637 ((eq scope 'agenda)
9638 (setq scope (org-agenda-files t)))
9639 ((eq scope 'agenda-with-archives)
9640 (setq scope (org-agenda-files t))
9641 (setq scope (org-add-archive-files scope)))
9642 ((eq scope 'file)
9643 (setq scope (list (buffer-file-name))))
9644 ((eq scope 'file-with-archives)
9645 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9646 (org-prepare-agenda-buffers scope)
9647 (while (setq file (pop scope))
9648 (with-current-buffer (org-find-base-buffer-visiting file)
9649 (save-excursion
9650 (save-restriction
9651 (widen)
9652 (goto-char (point-min))
9653 (org-scan-tags func matcher))))))))
9655 ;;;; Properties
9657 ;;; Setting and retrieving properties
9659 (defconst org-special-properties
9660 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9661 "TIMESTAMP" "TIMESTAMP_IA")
9662 "The special properties valid in Org-mode.
9664 These are properties that are not defined in the property drawer,
9665 but in some other way.")
9667 (defconst org-default-properties
9668 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9669 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9670 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9671 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9672 "Some properties that are used by Org-mode for various purposes.
9673 Being in this list makes sure that they are offered for completion.")
9675 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9676 "Regular expression matching the first line of a property drawer.")
9678 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9679 "Regular expression matching the first line of a property drawer.")
9681 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9682 "Regular expression matching the first line of a property drawer.")
9684 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9685 "Regular expression matching the first line of a property drawer.")
9687 (defconst org-property-drawer-re
9688 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9689 org-property-end-re "\\)\n?")
9690 "Matches an entire property drawer.")
9692 (defconst org-clock-drawer-re
9693 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9694 org-property-end-re "\\)\n?")
9695 "Matches an entire clock drawer.")
9697 (defun org-property-action ()
9698 "Do an action on properties."
9699 (interactive)
9700 (let (c)
9701 (org-at-property-p)
9702 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9703 (setq c (read-char-exclusive))
9704 (cond
9705 ((equal c ?s)
9706 (call-interactively 'org-set-property))
9707 ((equal c ?d)
9708 (call-interactively 'org-delete-property))
9709 ((equal c ?D)
9710 (call-interactively 'org-delete-property-globally))
9711 ((equal c ?c)
9712 (call-interactively 'org-compute-property-at-point))
9713 (t (error "No such property action %c" c)))))
9715 (defun org-at-property-p ()
9716 "Is the cursor in a property line?"
9717 ;; FIXME: Does not check if we are actually in the drawer.
9718 ;; FIXME: also returns true on any drawers.....
9719 ;; This is used by C-c C-c for property action.
9720 (save-excursion
9721 (beginning-of-line 1)
9722 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9724 (defun org-get-property-block (&optional beg end force)
9725 "Return the (beg . end) range of the body of the property drawer.
9726 BEG and END can be beginning and end of subtree, if not given
9727 they will be found.
9728 If the drawer does not exist and FORCE is non-nil, create the drawer."
9729 (catch 'exit
9730 (save-excursion
9731 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9732 (end (or end (progn (outline-next-heading) (point)))))
9733 (goto-char beg)
9734 (if (re-search-forward org-property-start-re end t)
9735 (setq beg (1+ (match-end 0)))
9736 (if force
9737 (save-excursion
9738 (org-insert-property-drawer)
9739 (setq end (progn (outline-next-heading) (point))))
9740 (throw 'exit nil))
9741 (goto-char beg)
9742 (if (re-search-forward org-property-start-re end t)
9743 (setq beg (1+ (match-end 0)))))
9744 (if (re-search-forward org-property-end-re end t)
9745 (setq end (match-beginning 0))
9746 (or force (throw 'exit nil))
9747 (goto-char beg)
9748 (setq end beg)
9749 (org-indent-line-function)
9750 (insert ":END:\n"))
9751 (cons beg end)))))
9753 (defun org-entry-properties (&optional pom which)
9754 "Get all properties of the entry at point-or-marker POM.
9755 This includes the TODO keyword, the tags, time strings for deadline,
9756 scheduled, and clocking, and any additional properties defined in the
9757 entry. The return value is an alist, keys may occur multiple times
9758 if the property key was used several times.
9759 POM may also be nil, in which case the current entry is used.
9760 If WHICH is nil or `all', get all properties. If WHICH is
9761 `special' or `standard', only get that subclass."
9762 (setq which (or which 'all))
9763 (org-with-point-at pom
9764 (let ((clockstr (substring org-clock-string 0 -1))
9765 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9766 beg end range props sum-props key value string clocksum)
9767 (save-excursion
9768 (when (condition-case nil (org-back-to-heading t) (error nil))
9769 (setq beg (point))
9770 (setq sum-props (get-text-property (point) 'org-summaries))
9771 (setq clocksum (get-text-property (point) :org-clock-minutes))
9772 (outline-next-heading)
9773 (setq end (point))
9774 (when (memq which '(all special))
9775 ;; Get the special properties, like TODO and tags
9776 (goto-char beg)
9777 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9778 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9779 (when (looking-at org-priority-regexp)
9780 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9781 (when (and (setq value (org-get-tags-string))
9782 (string-match "\\S-" value))
9783 (push (cons "TAGS" value) props))
9784 (when (setq value (org-get-tags-at))
9785 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9786 props))
9787 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9788 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9789 string (if (equal key clockstr)
9790 (org-no-properties
9791 (org-trim
9792 (buffer-substring
9793 (match-beginning 3) (goto-char (point-at-eol)))))
9794 (substring (org-match-string-no-properties 3) 1 -1)))
9795 (unless key
9796 (if (= (char-after (match-beginning 3)) ?\[)
9797 (setq key "TIMESTAMP_IA")
9798 (setq key "TIMESTAMP")))
9799 (when (or (equal key clockstr) (not (assoc key props)))
9800 (push (cons key string) props)))
9804 (when (memq which '(all standard))
9805 ;; Get the standard properties, like :PORP: ...
9806 (setq range (org-get-property-block beg end))
9807 (when range
9808 (goto-char (car range))
9809 (while (re-search-forward
9810 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9811 (cdr range) t)
9812 (setq key (org-match-string-no-properties 1)
9813 value (org-trim (or (org-match-string-no-properties 2) "")))
9814 (unless (member key excluded)
9815 (push (cons key (or value "")) props)))))
9816 (if clocksum
9817 (push (cons "CLOCKSUM"
9818 (org-columns-number-to-string (/ (float clocksum) 60.)
9819 'add_times))
9820 props))
9821 (append sum-props (nreverse props)))))))
9823 (defun org-entry-get (pom property &optional inherit)
9824 "Get value of PROPERTY for entry at point-or-marker POM.
9825 If INHERIT is non-nil and the entry does not have the property,
9826 then also check higher levels of the hierarchy.
9827 If INHERIT is the symbol `selective', use inheritance only if the setting
9828 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9829 If the property is present but empty, the return value is the empty string.
9830 If the property is not present at all, nil is returned."
9831 (org-with-point-at pom
9832 (if (and inherit (if (eq inherit 'selective)
9833 (org-property-inherit-p property)
9835 (org-entry-get-with-inheritance property)
9836 (if (member property org-special-properties)
9837 ;; We need a special property. Use brute force, get all properties.
9838 (cdr (assoc property (org-entry-properties nil 'special)))
9839 (let ((range (org-get-property-block)))
9840 (if (and range
9841 (goto-char (car range))
9842 (re-search-forward
9843 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9844 (cdr range) t))
9845 ;; Found the property, return it.
9846 (if (match-end 1)
9847 (org-match-string-no-properties 1)
9848 "")))))))
9850 (defun org-property-or-variable-value (var &optional inherit)
9851 "Check if there is a property fixing the value of VAR.
9852 If yes, return this value. If not, return the current value of the variable."
9853 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9854 (if (and prop (stringp prop) (string-match "\\S-" prop))
9855 (read prop)
9856 (symbol-value var))))
9858 (defun org-entry-delete (pom property)
9859 "Delete the property PROPERTY from entry at point-or-marker POM."
9860 (org-with-point-at pom
9861 (if (member property org-special-properties)
9862 nil ; cannot delete these properties.
9863 (let ((range (org-get-property-block)))
9864 (if (and range
9865 (goto-char (car range))
9866 (re-search-forward
9867 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9868 (cdr range) t))
9869 (progn
9870 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9872 nil)))))
9874 ;; Multi-values properties are properties that contain multiple values
9875 ;; These values are assumed to be single words, separated by whitespace.
9876 (defun org-entry-add-to-multivalued-property (pom property value)
9877 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9878 (let* ((old (org-entry-get pom property))
9879 (values (and old (org-split-string old "[ \t]"))))
9880 (setq value (org-entry-protect-space value))
9881 (unless (member value values)
9882 (setq values (cons value values))
9883 (org-entry-put pom property
9884 (mapconcat 'identity values " ")))))
9886 (defun org-entry-remove-from-multivalued-property (pom property value)
9887 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9888 (let* ((old (org-entry-get pom property))
9889 (values (and old (org-split-string old "[ \t]"))))
9890 (setq value (org-entry-protect-space value))
9891 (when (member value values)
9892 (setq values (delete value values))
9893 (org-entry-put pom property
9894 (mapconcat 'identity values " ")))))
9896 (defun org-entry-member-in-multivalued-property (pom property value)
9897 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9898 (let* ((old (org-entry-get pom property))
9899 (values (and old (org-split-string old "[ \t]"))))
9900 (setq value (org-entry-protect-space value))
9901 (member value values)))
9903 (defun org-entry-get-multivalued-property (pom property)
9904 "Return a list of values in a multivalued property."
9905 (let* ((value (org-entry-get pom property))
9906 (values (and value (org-split-string value "[ \t]"))))
9907 (mapcar 'org-entry-restore-space values)))
9909 (defun org-entry-put-multivalued-property (pom property &rest values)
9910 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9911 VALUES should be a list of strings. Spaces will be protected."
9912 (org-entry-put pom property
9913 (mapconcat 'org-entry-protect-space values " "))
9914 (let* ((value (org-entry-get pom property))
9915 (values (and value (org-split-string value "[ \t]"))))
9916 (mapcar 'org-entry-restore-space values)))
9918 (defun org-entry-protect-space (s)
9919 "Protect spaces and newline in string S."
9920 (while (string-match " " s)
9921 (setq s (replace-match "%20" t t s)))
9922 (while (string-match "\n" s)
9923 (setq s (replace-match "%0A" t t s)))
9926 (defun org-entry-restore-space (s)
9927 "Restore spaces and newline in string S."
9928 (while (string-match "%20" s)
9929 (setq s (replace-match " " t t s)))
9930 (while (string-match "%0A" s)
9931 (setq s (replace-match "\n" t t s)))
9934 (defvar org-entry-property-inherited-from (make-marker)
9935 "Marker pointing to the entry from where a proerty was inherited.
9936 Each call to `org-entry-get-with-inheritance' will set this marker to the
9937 location of the entry where the inheriance search matched. If there was
9938 no match, the marker will point nowhere.
9939 Note that also `org-entry-get' calls this function, if the INHERIT flag
9940 is set.")
9942 (defun org-entry-get-with-inheritance (property)
9943 "Get entry property, and search higher levels if not present."
9944 (move-marker org-entry-property-inherited-from nil)
9945 (let (tmp)
9946 (save-excursion
9947 (save-restriction
9948 (widen)
9949 (catch 'ex
9950 (while t
9951 (when (setq tmp (org-entry-get nil property))
9952 (org-back-to-heading t)
9953 (move-marker org-entry-property-inherited-from (point))
9954 (throw 'ex tmp))
9955 (or (org-up-heading-safe) (throw 'ex nil)))))
9956 (or tmp
9957 (cdr (assoc property org-file-properties))
9958 (cdr (assoc property org-global-properties))
9959 (cdr (assoc property org-global-properties-fixed))))))
9961 (defun org-entry-put (pom property value)
9962 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9963 (org-with-point-at pom
9964 (org-back-to-heading t)
9965 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9966 range)
9967 (cond
9968 ((equal property "TODO")
9969 (when (and (stringp value) (string-match "\\S-" value)
9970 (not (member value org-todo-keywords-1)))
9971 (error "\"%s\" is not a valid TODO state" value))
9972 (if (or (not value)
9973 (not (string-match "\\S-" value)))
9974 (setq value 'none))
9975 (org-todo value)
9976 (org-set-tags nil 'align))
9977 ((equal property "PRIORITY")
9978 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9979 (string-to-char value) ?\ ))
9980 (org-set-tags nil 'align))
9981 ((equal property "SCHEDULED")
9982 (if (re-search-forward org-scheduled-time-regexp end t)
9983 (cond
9984 ((eq value 'earlier) (org-timestamp-change -1 'day))
9985 ((eq value 'later) (org-timestamp-change 1 'day))
9986 (t (call-interactively 'org-schedule)))
9987 (call-interactively 'org-schedule)))
9988 ((equal property "DEADLINE")
9989 (if (re-search-forward org-deadline-time-regexp end t)
9990 (cond
9991 ((eq value 'earlier) (org-timestamp-change -1 'day))
9992 ((eq value 'later) (org-timestamp-change 1 'day))
9993 (t (call-interactively 'org-deadline)))
9994 (call-interactively 'org-deadline)))
9995 ((member property org-special-properties)
9996 (error "The %s property can not yet be set with `org-entry-put'"
9997 property))
9998 (t ; a non-special property
9999 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10000 (setq range (org-get-property-block beg end 'force))
10001 (goto-char (car range))
10002 (if (re-search-forward
10003 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10004 (progn
10005 (delete-region (match-beginning 1) (match-end 1))
10006 (goto-char (match-beginning 1)))
10007 (goto-char (cdr range))
10008 (insert "\n")
10009 (backward-char 1)
10010 (org-indent-line-function)
10011 (insert ":" property ":"))
10012 (and value (insert " " value))
10013 (org-indent-line-function)))))))
10015 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10016 "Get all property keys in the current buffer.
10017 With INCLUDE-SPECIALS, also list the special properties that relect things
10018 like tags and TODO state.
10019 With INCLUDE-DEFAULTS, also include properties that has special meaning
10020 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10021 With INCLUDE-COLUMNS, also include property names given in COLUMN
10022 formats in the current buffer."
10023 (let (rtn range cfmt cols s p)
10024 (save-excursion
10025 (save-restriction
10026 (widen)
10027 (goto-char (point-min))
10028 (while (re-search-forward org-property-start-re nil t)
10029 (setq range (org-get-property-block))
10030 (goto-char (car range))
10031 (while (re-search-forward
10032 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10033 (cdr range) t)
10034 (add-to-list 'rtn (org-match-string-no-properties 1)))
10035 (outline-next-heading))))
10037 (when include-specials
10038 (setq rtn (append org-special-properties rtn)))
10040 (when include-defaults
10041 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10043 (when include-columns
10044 (save-excursion
10045 (save-restriction
10046 (widen)
10047 (goto-char (point-min))
10048 (while (re-search-forward
10049 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10050 nil t)
10051 (setq cfmt (match-string 2) s 0)
10052 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10053 cfmt s)
10054 (setq s (match-end 0)
10055 p (match-string 1 cfmt))
10056 (unless (or (equal p "ITEM")
10057 (member p org-special-properties))
10058 (add-to-list 'rtn (match-string 1 cfmt))))))))
10060 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10062 (defun org-property-values (key)
10063 "Return a list of all values of property KEY."
10064 (save-excursion
10065 (save-restriction
10066 (widen)
10067 (goto-char (point-min))
10068 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10069 values)
10070 (while (re-search-forward re nil t)
10071 (add-to-list 'values (org-trim (match-string 1))))
10072 (delete "" values)))))
10074 (defun org-insert-property-drawer ()
10075 "Insert a property drawer into the current entry."
10076 (interactive)
10077 (org-back-to-heading t)
10078 (looking-at outline-regexp)
10079 (let ((indent (- (match-end 0)(match-beginning 0)))
10080 (beg (point))
10081 (re (concat "^[ \t]*" org-keyword-time-regexp))
10082 end hiddenp)
10083 (outline-next-heading)
10084 (setq end (point))
10085 (goto-char beg)
10086 (while (re-search-forward re end t))
10087 (setq hiddenp (org-invisible-p))
10088 (end-of-line 1)
10089 (and (equal (char-after) ?\n) (forward-char 1))
10090 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10091 (beginning-of-line 2))
10092 (org-skip-over-state-notes)
10093 (skip-chars-backward " \t\n\r")
10094 (if (eq (char-before) ?*) (forward-char 1))
10095 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10096 (beginning-of-line 0)
10097 (org-indent-to-column indent)
10098 (beginning-of-line 2)
10099 (org-indent-to-column indent)
10100 (beginning-of-line 0)
10101 (if hiddenp
10102 (save-excursion
10103 (org-back-to-heading t)
10104 (hide-entry))
10105 (org-flag-drawer t))))
10107 (defun org-set-property (property value)
10108 "In the current entry, set PROPERTY to VALUE.
10109 When called interactively, this will prompt for a property name, offering
10110 completion on existing and default properties. And then it will prompt
10111 for a value, offering competion either on allowed values (via an inherited
10112 xxx_ALL property) or on existing values in other instances of this property
10113 in the current file."
10114 (interactive
10115 (let* ((completion-ignore-case t)
10116 (keys (org-buffer-property-keys nil t t))
10117 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10118 (prop (if (member prop0 keys)
10119 prop0
10120 (or (cdr (assoc (downcase prop0)
10121 (mapcar (lambda (x) (cons (downcase x) x))
10122 keys)))
10123 prop0)))
10124 (cur (org-entry-get nil prop))
10125 (allowed (org-property-get-allowed-values nil prop 'table))
10126 (existing (mapcar 'list (org-property-values prop)))
10127 (val (if allowed
10128 (org-completing-read "Value: " allowed nil 'req-match)
10129 (org-completing-read
10130 (concat "Value" (if (and cur (string-match "\\S-" cur))
10131 (concat "[" cur "]") "")
10132 ": ")
10133 existing nil nil "" nil cur))))
10134 (list prop (if (equal val "") cur val))))
10135 (unless (equal (org-entry-get nil property) value)
10136 (org-entry-put nil property value)))
10138 (defun org-delete-property (property)
10139 "In the current entry, delete PROPERTY."
10140 (interactive
10141 (let* ((completion-ignore-case t)
10142 (prop (completing-read
10143 "Property: " (org-entry-properties nil 'standard))))
10144 (list prop)))
10145 (message "Property %s %s" property
10146 (if (org-entry-delete nil property)
10147 "deleted"
10148 "was not present in the entry")))
10150 (defun org-delete-property-globally (property)
10151 "Remove PROPERTY globally, from all entries."
10152 (interactive
10153 (let* ((completion-ignore-case t)
10154 (prop (completing-read
10155 "Globally remove property: "
10156 (mapcar 'list (org-buffer-property-keys)))))
10157 (list prop)))
10158 (save-excursion
10159 (save-restriction
10160 (widen)
10161 (goto-char (point-min))
10162 (let ((cnt 0))
10163 (while (re-search-forward
10164 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10165 nil t)
10166 (setq cnt (1+ cnt))
10167 (replace-match ""))
10168 (message "Property \"%s\" removed from %d entries" property cnt)))))
10170 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10172 (defun org-compute-property-at-point ()
10173 "Compute the property at point.
10174 This looks for an enclosing column format, extracts the operator and
10175 then applies it to the proerty in the column format's scope."
10176 (interactive)
10177 (unless (org-at-property-p)
10178 (error "Not at a property"))
10179 (let ((prop (org-match-string-no-properties 2)))
10180 (org-columns-get-format-and-top-level)
10181 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10182 (error "No operator defined for property %s" prop))
10183 (org-columns-compute prop)))
10185 (defun org-property-get-allowed-values (pom property &optional table)
10186 "Get allowed values for the property PROPERTY.
10187 When TABLE is non-nil, return an alist that can directly be used for
10188 completion."
10189 (let (vals)
10190 (cond
10191 ((equal property "TODO")
10192 (setq vals (org-with-point-at pom
10193 (append org-todo-keywords-1 '("")))))
10194 ((equal property "PRIORITY")
10195 (let ((n org-lowest-priority))
10196 (while (>= n org-highest-priority)
10197 (push (char-to-string n) vals)
10198 (setq n (1- n)))))
10199 ((member property org-special-properties))
10201 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10203 (when (and vals (string-match "\\S-" vals))
10204 (setq vals (car (read-from-string (concat "(" vals ")"))))
10205 (setq vals (mapcar (lambda (x)
10206 (cond ((stringp x) x)
10207 ((numberp x) (number-to-string x))
10208 ((symbolp x) (symbol-name x))
10209 (t "???")))
10210 vals)))))
10211 (if table (mapcar 'list vals) vals)))
10213 (defun org-property-previous-allowed-value (&optional previous)
10214 "Switch to the next allowed value for this property."
10215 (interactive)
10216 (org-property-next-allowed-value t))
10218 (defun org-property-next-allowed-value (&optional previous)
10219 "Switch to the next allowed value for this property."
10220 (interactive)
10221 (unless (org-at-property-p)
10222 (error "Not at a property"))
10223 (let* ((key (match-string 2))
10224 (value (match-string 3))
10225 (allowed (or (org-property-get-allowed-values (point) key)
10226 (and (member value '("[ ]" "[-]" "[X]"))
10227 '("[ ]" "[X]"))))
10228 nval)
10229 (unless allowed
10230 (error "Allowed values for this property have not been defined"))
10231 (if previous (setq allowed (reverse allowed)))
10232 (if (member value allowed)
10233 (setq nval (car (cdr (member value allowed)))))
10234 (setq nval (or nval (car allowed)))
10235 (if (equal nval value)
10236 (error "Only one allowed value for this property"))
10237 (org-at-property-p)
10238 (replace-match (concat " :" key ": " nval) t t)
10239 (org-indent-line-function)
10240 (beginning-of-line 1)
10241 (skip-chars-forward " \t")))
10243 (defun org-find-entry-with-id (ident)
10244 "Locate the entry that contains the ID property with exact value IDENT.
10245 IDENT can be a string, a symbol or a number, this function will search for
10246 the string representation of it.
10247 Return the position where this entry starts, or nil if there is no such entry."
10248 (let ((id (cond
10249 ((stringp ident) ident)
10250 ((symbol-name ident) (symbol-name ident))
10251 ((numberp ident) (number-to-string ident))
10252 (t (error "IDENT %s must be a string, symbol or number" ident))))
10253 (case-fold-search nil))
10254 (save-excursion
10255 (save-restriction
10256 (widen)
10257 (goto-char (point-min))
10258 (when (re-search-forward
10259 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10260 nil t)
10261 (org-back-to-heading)
10262 (point))))))
10264 ;;;; Timestamps
10266 (defvar org-last-changed-timestamp nil)
10267 (defvar org-last-inserted-timestamp nil
10268 "The last time stamp inserted with `org-insert-time-stamp'.")
10269 (defvar org-time-was-given) ; dynamically scoped parameter
10270 (defvar org-end-time-was-given) ; dynamically scoped parameter
10271 (defvar org-ts-what) ; dynamically scoped parameter
10273 (defun org-time-stamp (arg &optional inactive)
10274 "Prompt for a date/time and insert a time stamp.
10275 If the user specifies a time like HH:MM, or if this command is called
10276 with a prefix argument, the time stamp will contain date and time.
10277 Otherwise, only the date will be included. All parts of a date not
10278 specified by the user will be filled in from the current date/time.
10279 So if you press just return without typing anything, the time stamp
10280 will represent the current date/time. If there is already a timestamp
10281 at the cursor, it will be modified."
10282 (interactive "P")
10283 (let* ((ts nil)
10284 (default-time
10285 ;; Default time is either today, or, when entering a range,
10286 ;; the range start.
10287 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10288 (save-excursion
10289 (re-search-backward
10290 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10291 (- (point) 20) t)))
10292 (apply 'encode-time (org-parse-time-string (match-string 1)))
10293 (current-time)))
10294 (default-input (and ts (org-get-compact-tod ts)))
10295 org-time-was-given org-end-time-was-given time)
10296 (cond
10297 ((and (org-at-timestamp-p t)
10298 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10299 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10300 (insert "--")
10301 (setq time (let ((this-command this-command))
10302 (org-read-date arg 'totime nil nil
10303 default-time default-input)))
10304 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10305 ((org-at-timestamp-p t)
10306 (setq time (let ((this-command this-command))
10307 (org-read-date arg 'totime nil nil default-time default-input)))
10308 (when (org-at-timestamp-p t) ; just to get the match data
10309 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10310 (replace-match "")
10311 (setq org-last-changed-timestamp
10312 (org-insert-time-stamp
10313 time (or org-time-was-given arg)
10314 inactive nil nil (list org-end-time-was-given))))
10315 (message "Timestamp updated"))
10317 (setq time (let ((this-command this-command))
10318 (org-read-date arg 'totime nil nil default-time default-input)))
10319 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10320 nil nil (list org-end-time-was-given))))))
10322 ;; FIXME: can we use this for something else, like computing time differences?
10323 (defun org-get-compact-tod (s)
10324 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10325 (let* ((t1 (match-string 1 s))
10326 (h1 (string-to-number (match-string 2 s)))
10327 (m1 (string-to-number (match-string 3 s)))
10328 (t2 (and (match-end 4) (match-string 5 s)))
10329 (h2 (and t2 (string-to-number (match-string 6 s))))
10330 (m2 (and t2 (string-to-number (match-string 7 s))))
10331 dh dm)
10332 (if (not t2)
10334 (setq dh (- h2 h1) dm (- m2 m1))
10335 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10336 (concat t1 "+" (number-to-string dh)
10337 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10339 (defun org-time-stamp-inactive (&optional arg)
10340 "Insert an inactive time stamp.
10341 An inactive time stamp is enclosed in square brackets instead of angle
10342 brackets. It is inactive in the sense that it does not trigger agenda entries,
10343 does not link to the calendar and cannot be changed with the S-cursor keys.
10344 So these are more for recording a certain time/date."
10345 (interactive "P")
10346 (org-time-stamp arg 'inactive))
10348 (defvar org-date-ovl (org-make-overlay 1 1))
10349 (org-overlay-put org-date-ovl 'face 'org-warning)
10350 (org-detach-overlay org-date-ovl)
10352 (defvar org-ans1) ; dynamically scoped parameter
10353 (defvar org-ans2) ; dynamically scoped parameter
10355 (defvar org-plain-time-of-day-regexp) ; defined below
10357 (defvar org-overriding-default-time nil) ; dynamically scoped
10358 (defvar org-read-date-overlay nil)
10359 (defvar org-dcst nil) ; dynamically scoped
10361 (defun org-read-date (&optional with-time to-time from-string prompt
10362 default-time default-input)
10363 "Read a date, possibly a time, and make things smooth for the user.
10364 The prompt will suggest to enter an ISO date, but you can also enter anything
10365 which will at least partially be understood by `parse-time-string'.
10366 Unrecognized parts of the date will default to the current day, month, year,
10367 hour and minute. If this command is called to replace a timestamp at point,
10368 of to enter the second timestamp of a range, the default time is taken from the
10369 existing stamp. For example,
10370 3-2-5 --> 2003-02-05
10371 feb 15 --> currentyear-02-15
10372 sep 12 9 --> 2009-09-12
10373 12:45 --> today 12:45
10374 22 sept 0:34 --> currentyear-09-22 0:34
10375 12 --> currentyear-currentmonth-12
10376 Fri --> nearest Friday (today or later)
10377 etc.
10379 Furthermore you can specify a relative date by giving, as the *first* thing
10380 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10381 change in days weeks, months, years.
10382 With a single plus or minus, the date is relative to today. With a double
10383 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10384 +4d --> four days from today
10385 +4 --> same as above
10386 +2w --> two weeks from today
10387 ++5 --> five days from default date
10389 The function understands only English month and weekday abbreviations,
10390 but this can be configured with the variables `parse-time-months' and
10391 `parse-time-weekdays'.
10393 While prompting, a calendar is popped up - you can also select the
10394 date with the mouse (button 1). The calendar shows a period of three
10395 months. To scroll it to other months, use the keys `>' and `<'.
10396 If you don't like the calendar, turn it off with
10397 \(setq org-read-date-popup-calendar nil)
10399 With optional argument TO-TIME, the date will immediately be converted
10400 to an internal time.
10401 With an optional argument WITH-TIME, the prompt will suggest to also
10402 insert a time. Note that when WITH-TIME is not set, you can still
10403 enter a time, and this function will inform the calling routine about
10404 this change. The calling routine may then choose to change the format
10405 used to insert the time stamp into the buffer to include the time.
10406 With optional argument FROM-STRING, read from this string instead from
10407 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10408 the time/date that is used for everything that is not specified by the
10409 user."
10410 (require 'parse-time)
10411 (let* ((org-time-stamp-rounding-minutes
10412 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10413 (org-dcst org-display-custom-times)
10414 (ct (org-current-time))
10415 (def (or org-overriding-default-time default-time ct))
10416 (defdecode (decode-time def))
10417 (dummy (progn
10418 (when (< (nth 2 defdecode) org-extend-today-until)
10419 (setcar (nthcdr 2 defdecode) -1)
10420 (setcar (nthcdr 1 defdecode) 59)
10421 (setq def (apply 'encode-time defdecode)
10422 defdecode (decode-time def)))))
10423 (calendar-move-hook nil)
10424 (calendar-view-diary-initially-flag nil)
10425 (view-diary-entries-initially nil)
10426 (calendar-view-holidays-initially-flag nil)
10427 (view-calendar-holidays-initially nil)
10428 (timestr (format-time-string
10429 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10430 (prompt (concat (if prompt (concat prompt " ") "")
10431 (format "Date+time [%s]: " timestr)))
10432 ans (org-ans0 "") org-ans1 org-ans2 final)
10434 (cond
10435 (from-string (setq ans from-string))
10436 (org-read-date-popup-calendar
10437 (save-excursion
10438 (save-window-excursion
10439 (calendar)
10440 (calendar-forward-day (- (time-to-days def)
10441 (calendar-absolute-from-gregorian
10442 (calendar-current-date))))
10443 (org-eval-in-calendar nil t)
10444 (let* ((old-map (current-local-map))
10445 (map (copy-keymap calendar-mode-map))
10446 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10447 (org-defkey map (kbd "RET") 'org-calendar-select)
10448 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10449 'org-calendar-select-mouse)
10450 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10451 'org-calendar-select-mouse)
10452 (org-defkey minibuffer-local-map [(meta shift left)]
10453 (lambda () (interactive)
10454 (org-eval-in-calendar '(calendar-backward-month 1))))
10455 (org-defkey minibuffer-local-map [(meta shift right)]
10456 (lambda () (interactive)
10457 (org-eval-in-calendar '(calendar-forward-month 1))))
10458 (org-defkey minibuffer-local-map [(meta shift up)]
10459 (lambda () (interactive)
10460 (org-eval-in-calendar '(calendar-backward-year 1))))
10461 (org-defkey minibuffer-local-map [(meta shift down)]
10462 (lambda () (interactive)
10463 (org-eval-in-calendar '(calendar-forward-year 1))))
10464 (org-defkey minibuffer-local-map [(shift up)]
10465 (lambda () (interactive)
10466 (org-eval-in-calendar '(calendar-backward-week 1))))
10467 (org-defkey minibuffer-local-map [(shift down)]
10468 (lambda () (interactive)
10469 (org-eval-in-calendar '(calendar-forward-week 1))))
10470 (org-defkey minibuffer-local-map [(shift left)]
10471 (lambda () (interactive)
10472 (org-eval-in-calendar '(calendar-backward-day 1))))
10473 (org-defkey minibuffer-local-map [(shift right)]
10474 (lambda () (interactive)
10475 (org-eval-in-calendar '(calendar-forward-day 1))))
10476 (org-defkey minibuffer-local-map ">"
10477 (lambda () (interactive)
10478 (org-eval-in-calendar '(scroll-calendar-left 1))))
10479 (org-defkey minibuffer-local-map "<"
10480 (lambda () (interactive)
10481 (org-eval-in-calendar '(scroll-calendar-right 1))))
10482 (unwind-protect
10483 (progn
10484 (use-local-map map)
10485 (add-hook 'post-command-hook 'org-read-date-display)
10486 (setq org-ans0 (read-string prompt default-input nil nil))
10487 ;; org-ans0: from prompt
10488 ;; org-ans1: from mouse click
10489 ;; org-ans2: from calendar motion
10490 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10491 (remove-hook 'post-command-hook 'org-read-date-display)
10492 (use-local-map old-map)
10493 (when org-read-date-overlay
10494 (org-delete-overlay org-read-date-overlay)
10495 (setq org-read-date-overlay nil)))))))
10497 (t ; Naked prompt only
10498 (unwind-protect
10499 (setq ans (read-string prompt default-input nil timestr))
10500 (when org-read-date-overlay
10501 (org-delete-overlay org-read-date-overlay)
10502 (setq org-read-date-overlay nil)))))
10504 (setq final (org-read-date-analyze ans def defdecode))
10506 (if to-time
10507 (apply 'encode-time final)
10508 (if (and (boundp 'org-time-was-given) org-time-was-given)
10509 (format "%04d-%02d-%02d %02d:%02d"
10510 (nth 5 final) (nth 4 final) (nth 3 final)
10511 (nth 2 final) (nth 1 final))
10512 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10513 (defvar def)
10514 (defvar defdecode)
10515 (defvar with-time)
10516 (defun org-read-date-display ()
10517 "Display the currrent date prompt interpretation in the minibuffer."
10518 (when org-read-date-display-live
10519 (when org-read-date-overlay
10520 (org-delete-overlay org-read-date-overlay))
10521 (let ((p (point)))
10522 (end-of-line 1)
10523 (while (not (equal (buffer-substring
10524 (max (point-min) (- (point) 4)) (point))
10525 " "))
10526 (insert " "))
10527 (goto-char p))
10528 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10529 " " (or org-ans1 org-ans2)))
10530 (org-end-time-was-given nil)
10531 (f (org-read-date-analyze ans def defdecode))
10532 (fmts (if org-dcst
10533 org-time-stamp-custom-formats
10534 org-time-stamp-formats))
10535 (fmt (if (or with-time
10536 (and (boundp 'org-time-was-given) org-time-was-given))
10537 (cdr fmts)
10538 (car fmts)))
10539 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10540 (when (and org-end-time-was-given
10541 (string-match org-plain-time-of-day-regexp txt))
10542 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10543 org-end-time-was-given
10544 (substring txt (match-end 0)))))
10545 (setq org-read-date-overlay
10546 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10547 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10549 (defun org-read-date-analyze (ans def defdecode)
10550 "Analyze the combined answer of the date prompt."
10551 ;; FIXME: cleanup and comment
10552 (let (delta deltan deltaw deltadef year month day
10553 hour minute second wday pm h2 m2 tl wday1
10554 iso-year iso-weekday iso-week iso-year iso-date)
10556 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10557 (setq ans "+0"))
10559 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10560 (setq ans (replace-match "" t t ans)
10561 deltan (car delta)
10562 deltaw (nth 1 delta)
10563 deltadef (nth 2 delta)))
10565 ;; Check if there is an iso week date in there
10566 ;; If yes, sore the info and ostpone interpreting it until the rest
10567 ;; of the parsing is done
10568 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10569 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10570 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10571 iso-week (string-to-number (match-string 2 ans)))
10572 (setq ans (replace-match "" t t ans)))
10574 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10575 (when (string-match
10576 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10577 (setq year (if (match-end 2)
10578 (string-to-number (match-string 2 ans))
10579 (string-to-number (format-time-string "%Y")))
10580 month (string-to-number (match-string 3 ans))
10581 day (string-to-number (match-string 4 ans)))
10582 (if (< year 100) (setq year (+ 2000 year)))
10583 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10584 t nil ans)))
10585 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10586 ;; If there is a time with am/pm, and *no* time without it, we convert
10587 ;; so that matching will be successful.
10588 (loop for i from 1 to 2 do ; twice, for end time as well
10589 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10590 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10591 (setq hour (string-to-number (match-string 1 ans))
10592 minute (if (match-end 3)
10593 (string-to-number (match-string 3 ans))
10595 pm (equal ?p
10596 (string-to-char (downcase (match-string 4 ans)))))
10597 (if (and (= hour 12) (not pm))
10598 (setq hour 0)
10599 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10600 (setq ans (replace-match (format "%02d:%02d" hour minute)
10601 t t ans))))
10603 ;; Check if a time range is given as a duration
10604 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10605 (setq hour (string-to-number (match-string 1 ans))
10606 h2 (+ hour (string-to-number (match-string 3 ans)))
10607 minute (string-to-number (match-string 2 ans))
10608 m2 (+ minute (if (match-end 5) (string-to-number
10609 (match-string 5 ans))0)))
10610 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10611 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10612 t t ans)))
10614 ;; Check if there is a time range
10615 (when (boundp 'org-end-time-was-given)
10616 (setq org-time-was-given nil)
10617 (when (and (string-match org-plain-time-of-day-regexp ans)
10618 (match-end 8))
10619 (setq org-end-time-was-given (match-string 8 ans))
10620 (setq ans (concat (substring ans 0 (match-beginning 7))
10621 (substring ans (match-end 7))))))
10623 (setq tl (parse-time-string ans)
10624 day (or (nth 3 tl) (nth 3 defdecode))
10625 month (or (nth 4 tl)
10626 (if (and org-read-date-prefer-future
10627 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10628 (1+ (nth 4 defdecode))
10629 (nth 4 defdecode)))
10630 year (or (nth 5 tl)
10631 (if (and org-read-date-prefer-future
10632 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10633 (1+ (nth 5 defdecode))
10634 (nth 5 defdecode)))
10635 hour (or (nth 2 tl) (nth 2 defdecode))
10636 minute (or (nth 1 tl) (nth 1 defdecode))
10637 second (or (nth 0 tl) 0)
10638 wday (nth 6 tl))
10640 ;; Special date definitions below
10641 (cond
10642 (iso-week
10643 ;; There was an iso week
10644 (setq year (or iso-year year)
10645 day (or iso-weekday wday 1)
10646 wday nil ; to make sure that the trigger below does not match
10647 iso-date (calendar-gregorian-from-absolute
10648 (calendar-absolute-from-iso
10649 (list iso-week day year))))
10650 ; FIXME: Should we also push ISO weeks into the future?
10651 ; (when (and org-read-date-prefer-future
10652 ; (not iso-year)
10653 ; (< (calendar-absolute-from-gregorian iso-date)
10654 ; (time-to-days (current-time))))
10655 ; (setq year (1+ year)
10656 ; iso-date (calendar-gregorian-from-absolute
10657 ; (calendar-absolute-from-iso
10658 ; (list iso-week day year)))))
10659 (setq month (car iso-date)
10660 year (nth 2 iso-date)
10661 day (nth 1 iso-date)))
10662 (deltan
10663 (unless deltadef
10664 (let ((now (decode-time (current-time))))
10665 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10666 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10667 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10668 ((equal deltaw "m") (setq month (+ month deltan)))
10669 ((equal deltaw "y") (setq year (+ year deltan)))))
10670 ((and wday (not (nth 3 tl)))
10671 ;; Weekday was given, but no day, so pick that day in the week
10672 ;; on or after the derived date.
10673 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10674 (unless (equal wday wday1)
10675 (setq day (+ day (% (- wday wday1 -7) 7))))))
10676 (if (and (boundp 'org-time-was-given)
10677 (nth 2 tl))
10678 (setq org-time-was-given t))
10679 (if (< year 100) (setq year (+ 2000 year)))
10680 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10681 (list second minute hour day month year)))
10683 (defvar parse-time-weekdays)
10685 (defun org-read-date-get-relative (s today default)
10686 "Check string S for special relative date string.
10687 TODAY and DEFAULT are internal times, for today and for a default.
10688 Return shift list (N what def-flag)
10689 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10690 N is the number of WHATs to shift.
10691 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10692 the DEFAULT date rather than TODAY."
10693 (when (and
10694 (string-match
10695 (concat
10696 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10697 "\\([0-9]+\\)?"
10698 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10699 "\\([ \t]\\|$\\)") s)
10700 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10701 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10702 (string-to-char (substring (match-string 1 s) -1))
10703 ?+))
10704 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10705 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10706 (what (if (match-end 3) (match-string 3 s) "d"))
10707 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10708 (date (if rel default today))
10709 (wday (nth 6 (decode-time date)))
10710 delta)
10711 (if wday1
10712 (progn
10713 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10714 (if (= dir ?-) (setq delta (- delta 7)))
10715 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10716 (list delta "d" rel))
10717 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10719 (defun org-eval-in-calendar (form &optional keepdate)
10720 "Eval FORM in the calendar window and return to current window.
10721 Also, store the cursor date in variable org-ans2."
10722 (let ((sw (selected-window)))
10723 (select-window (get-buffer-window "*Calendar*"))
10724 (eval form)
10725 (when (and (not keepdate) (calendar-cursor-to-date))
10726 (let* ((date (calendar-cursor-to-date))
10727 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10728 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10729 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10730 (select-window sw)))
10732 (defun org-calendar-select ()
10733 "Return to `org-read-date' with the date currently selected.
10734 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10735 (interactive)
10736 (when (calendar-cursor-to-date)
10737 (let* ((date (calendar-cursor-to-date))
10738 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10739 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10740 (if (active-minibuffer-window) (exit-minibuffer))))
10742 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10743 "Insert a date stamp for the date given by the internal TIME.
10744 WITH-HM means, use the stamp format that includes the time of the day.
10745 INACTIVE means use square brackets instead of angular ones, so that the
10746 stamp will not contribute to the agenda.
10747 PRE and POST are optional strings to be inserted before and after the
10748 stamp.
10749 The command returns the inserted time stamp."
10750 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10751 stamp)
10752 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10753 (insert-before-markers (or pre ""))
10754 (insert-before-markers (setq stamp (format-time-string fmt time)))
10755 (when (listp extra)
10756 (setq extra (car extra))
10757 (if (and (stringp extra)
10758 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10759 (setq extra (format "-%02d:%02d"
10760 (string-to-number (match-string 1 extra))
10761 (string-to-number (match-string 2 extra))))
10762 (setq extra nil)))
10763 (when extra
10764 (backward-char 1)
10765 (insert-before-markers extra)
10766 (forward-char 1))
10767 (insert-before-markers (or post ""))
10768 (setq org-last-inserted-timestamp stamp)))
10770 (defun org-toggle-time-stamp-overlays ()
10771 "Toggle the use of custom time stamp formats."
10772 (interactive)
10773 (setq org-display-custom-times (not org-display-custom-times))
10774 (unless org-display-custom-times
10775 (let ((p (point-min)) (bmp (buffer-modified-p)))
10776 (while (setq p (next-single-property-change p 'display))
10777 (if (and (get-text-property p 'display)
10778 (eq (get-text-property p 'face) 'org-date))
10779 (remove-text-properties
10780 p (setq p (next-single-property-change p 'display))
10781 '(display t))))
10782 (set-buffer-modified-p bmp)))
10783 (if (featurep 'xemacs)
10784 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10785 (org-restart-font-lock)
10786 (setq org-table-may-need-update t)
10787 (if org-display-custom-times
10788 (message "Time stamps are overlayed with custom format")
10789 (message "Time stamp overlays removed")))
10791 (defun org-display-custom-time (beg end)
10792 "Overlay modified time stamp format over timestamp between BEG and END."
10793 (let* ((ts (buffer-substring beg end))
10794 t1 w1 with-hm tf time str w2 (off 0))
10795 (save-match-data
10796 (setq t1 (org-parse-time-string ts t))
10797 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10798 (setq off (- (match-end 0) (match-beginning 0)))))
10799 (setq end (- end off))
10800 (setq w1 (- end beg)
10801 with-hm (and (nth 1 t1) (nth 2 t1))
10802 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10803 time (org-fix-decoded-time t1)
10804 str (org-add-props
10805 (format-time-string
10806 (substring tf 1 -1) (apply 'encode-time time))
10807 nil 'mouse-face 'highlight)
10808 w2 (length str))
10809 (if (not (= w2 w1))
10810 (add-text-properties (1+ beg) (+ 2 beg)
10811 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10812 (if (featurep 'xemacs)
10813 (progn
10814 (put-text-property beg end 'invisible t)
10815 (put-text-property beg end 'end-glyph (make-glyph str)))
10816 (put-text-property beg end 'display str))))
10818 (defun org-translate-time (string)
10819 "Translate all timestamps in STRING to custom format.
10820 But do this only if the variable `org-display-custom-times' is set."
10821 (when org-display-custom-times
10822 (save-match-data
10823 (let* ((start 0)
10824 (re org-ts-regexp-both)
10825 t1 with-hm inactive tf time str beg end)
10826 (while (setq start (string-match re string start))
10827 (setq beg (match-beginning 0)
10828 end (match-end 0)
10829 t1 (save-match-data
10830 (org-parse-time-string (substring string beg end) t))
10831 with-hm (and (nth 1 t1) (nth 2 t1))
10832 inactive (equal (substring string beg (1+ beg)) "[")
10833 tf (funcall (if with-hm 'cdr 'car)
10834 org-time-stamp-custom-formats)
10835 time (org-fix-decoded-time t1)
10836 str (format-time-string
10837 (concat
10838 (if inactive "[" "<") (substring tf 1 -1)
10839 (if inactive "]" ">"))
10840 (apply 'encode-time time))
10841 string (replace-match str t t string)
10842 start (+ start (length str)))))))
10843 string)
10845 (defun org-fix-decoded-time (time)
10846 "Set 0 instead of nil for the first 6 elements of time.
10847 Don't touch the rest."
10848 (let ((n 0))
10849 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10851 (defun org-days-to-time (timestamp-string)
10852 "Difference between TIMESTAMP-STRING and now in days."
10853 (- (time-to-days (org-time-string-to-time timestamp-string))
10854 (time-to-days (current-time))))
10856 (defun org-deadline-close (timestamp-string &optional ndays)
10857 "Is the time in TIMESTAMP-STRING close to the current date?"
10858 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10859 (and (< (org-days-to-time timestamp-string) ndays)
10860 (not (org-entry-is-done-p))))
10862 (defun org-get-wdays (ts)
10863 "Get the deadline lead time appropriate for timestring TS."
10864 (cond
10865 ((<= org-deadline-warning-days 0)
10866 ;; 0 or negative, enforce this value no matter what
10867 (- org-deadline-warning-days))
10868 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10869 ;; lead time is specified.
10870 (floor (* (string-to-number (match-string 1 ts))
10871 (cdr (assoc (match-string 2 ts)
10872 '(("d" . 1) ("w" . 7)
10873 ("m" . 30.4) ("y" . 365.25)))))))
10874 ;; go for the default.
10875 (t org-deadline-warning-days)))
10877 (defun org-calendar-select-mouse (ev)
10878 "Return to `org-read-date' with the date currently selected.
10879 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10880 (interactive "e")
10881 (mouse-set-point ev)
10882 (when (calendar-cursor-to-date)
10883 (let* ((date (calendar-cursor-to-date))
10884 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10885 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10886 (if (active-minibuffer-window) (exit-minibuffer))))
10888 (defun org-check-deadlines (ndays)
10889 "Check if there are any deadlines due or past due.
10890 A deadline is considered due if it happens within `org-deadline-warning-days'
10891 days from today's date. If the deadline appears in an entry marked DONE,
10892 it is not shown. The prefix arg NDAYS can be used to test that many
10893 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10894 (interactive "P")
10895 (let* ((org-warn-days
10896 (cond
10897 ((equal ndays '(4)) 100000)
10898 (ndays (prefix-numeric-value ndays))
10899 (t (abs org-deadline-warning-days))))
10900 (case-fold-search nil)
10901 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10902 (callback
10903 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10905 (message "%d deadlines past-due or due within %d days"
10906 (org-occur regexp nil callback)
10907 org-warn-days)))
10909 (defun org-check-before-date (date)
10910 "Check if there are deadlines or scheduled entries before DATE."
10911 (interactive (list (org-read-date)))
10912 (let ((case-fold-search nil)
10913 (regexp (concat "\\<\\(" org-deadline-string
10914 "\\|" org-scheduled-string
10915 "\\) *<\\([^>]+\\)>"))
10916 (callback
10917 (lambda () (time-less-p
10918 (org-time-string-to-time (match-string 2))
10919 (org-time-string-to-time date)))))
10920 (message "%d entries before %s"
10921 (org-occur regexp nil callback) date)))
10923 (defun org-evaluate-time-range (&optional to-buffer)
10924 "Evaluate a time range by computing the difference between start and end.
10925 Normally the result is just printed in the echo area, but with prefix arg
10926 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10927 If the time range is actually in a table, the result is inserted into the
10928 next column.
10929 For time difference computation, a year is assumed to be exactly 365
10930 days in order to avoid rounding problems."
10931 (interactive "P")
10933 (org-clock-update-time-maybe)
10934 (save-excursion
10935 (unless (org-at-date-range-p t)
10936 (goto-char (point-at-bol))
10937 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10938 (if (not (org-at-date-range-p t))
10939 (error "Not at a time-stamp range, and none found in current line")))
10940 (let* ((ts1 (match-string 1))
10941 (ts2 (match-string 2))
10942 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10943 (match-end (match-end 0))
10944 (time1 (org-time-string-to-time ts1))
10945 (time2 (org-time-string-to-time ts2))
10946 (t1 (time-to-seconds time1))
10947 (t2 (time-to-seconds time2))
10948 (diff (abs (- t2 t1)))
10949 (negative (< (- t2 t1) 0))
10950 ;; (ys (floor (* 365 24 60 60)))
10951 (ds (* 24 60 60))
10952 (hs (* 60 60))
10953 (fy "%dy %dd %02d:%02d")
10954 (fy1 "%dy %dd")
10955 (fd "%dd %02d:%02d")
10956 (fd1 "%dd")
10957 (fh "%02d:%02d")
10958 y d h m align)
10959 (if havetime
10960 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10962 d (floor (/ diff ds)) diff (mod diff ds)
10963 h (floor (/ diff hs)) diff (mod diff hs)
10964 m (floor (/ diff 60)))
10965 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10967 d (floor (+ (/ diff ds) 0.5))
10968 h 0 m 0))
10969 (if (not to-buffer)
10970 (message "%s" (org-make-tdiff-string y d h m))
10971 (if (org-at-table-p)
10972 (progn
10973 (goto-char match-end)
10974 (setq align t)
10975 (and (looking-at " *|") (goto-char (match-end 0))))
10976 (goto-char match-end))
10977 (if (looking-at
10978 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10979 (replace-match ""))
10980 (if negative (insert " -"))
10981 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10982 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10983 (insert " " (format fh h m))))
10984 (if align (org-table-align))
10985 (message "Time difference inserted")))))
10987 (defun org-make-tdiff-string (y d h m)
10988 (let ((fmt "")
10989 (l nil))
10990 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10991 l (push y l)))
10992 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10993 l (push d l)))
10994 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10995 l (push h l)))
10996 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10997 l (push m l)))
10998 (apply 'format fmt (nreverse l))))
11000 (defun org-time-string-to-time (s)
11001 (apply 'encode-time (org-parse-time-string s)))
11003 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11004 "Convert a time stamp to an absolute day number.
11005 If there is a specifyer for a cyclic time stamp, get the closest date to
11006 DAYNR.
11007 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11008 (cond
11009 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11010 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11011 daynr
11012 (+ daynr 1000)))
11013 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11014 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11015 (time-to-days (current-time))) (match-string 0 s)
11016 prefer show-all))
11017 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11019 (defun org-days-to-iso-week (days)
11020 "Return the iso week number."
11021 (require 'cal-iso)
11022 (car (calendar-iso-from-absolute days)))
11024 (defun org-small-year-to-year (year)
11025 "Convert 2-digit years into 4-digit years.
11026 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11027 The year 2000 cannot be abbreviated. Any year lager than 99
11028 is retrned unchanged."
11029 (if (< year 38)
11030 (setq year (+ 2000 year))
11031 (if (< year 100)
11032 (setq year (+ 1900 year))))
11033 year)
11035 (defun org-time-from-absolute (d)
11036 "Return the time corresponding to date D.
11037 D may be an absolute day number, or a calendar-type list (month day year)."
11038 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11039 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11041 (defun org-calendar-holiday ()
11042 "List of holidays, for Diary display in Org-mode."
11043 (require 'holidays)
11044 (let ((hl (funcall
11045 (if (fboundp 'calendar-check-holidays)
11046 'calendar-check-holidays 'check-calendar-holidays) date)))
11047 (if hl (mapconcat 'identity hl "; "))))
11049 (defun org-diary-sexp-entry (sexp entry date)
11050 "Process a SEXP diary ENTRY for DATE."
11051 (require 'diary-lib)
11052 (let ((result (if calendar-debug-sexp
11053 (let ((stack-trace-on-error t))
11054 (eval (car (read-from-string sexp))))
11055 (condition-case nil
11056 (eval (car (read-from-string sexp)))
11057 (error
11058 (beep)
11059 (message "Bad sexp at line %d in %s: %s"
11060 (org-current-line)
11061 (buffer-file-name) sexp)
11062 (sleep-for 2))))))
11063 (cond ((stringp result) result)
11064 ((and (consp result)
11065 (stringp (cdr result))) (cdr result))
11066 (result entry)
11067 (t nil))))
11069 (defun org-diary-to-ical-string (frombuf)
11070 "Get iCalendar entries from diary entries in buffer FROMBUF.
11071 This uses the icalendar.el library."
11072 (let* ((tmpdir (if (featurep 'xemacs)
11073 (temp-directory)
11074 temporary-file-directory))
11075 (tmpfile (make-temp-name
11076 (expand-file-name "orgics" tmpdir)))
11077 buf rtn b e)
11078 (save-excursion
11079 (set-buffer frombuf)
11080 (icalendar-export-region (point-min) (point-max) tmpfile)
11081 (setq buf (find-buffer-visiting tmpfile))
11082 (set-buffer buf)
11083 (goto-char (point-min))
11084 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11085 (setq b (match-beginning 0)))
11086 (goto-char (point-max))
11087 (if (re-search-backward "^END:VEVENT" nil t)
11088 (setq e (match-end 0)))
11089 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11090 (kill-buffer buf)
11091 (delete-file tmpfile)
11092 rtn))
11094 (defun org-closest-date (start current change prefer show-all)
11095 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11096 When PREFER is `past' return a date that is either CURRENT or past.
11097 When PREFER is `future', return a date that is either CURRENT or future.
11098 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11099 ;; Make the proper lists from the dates
11100 (catch 'exit
11101 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11102 dn dw sday cday n1 n2
11103 d m y y1 y2 date1 date2 nmonths nm ny m2)
11105 (setq start (org-date-to-gregorian start)
11106 current (org-date-to-gregorian
11107 (if show-all
11108 current
11109 (time-to-days (current-time))))
11110 sday (calendar-absolute-from-gregorian start)
11111 cday (calendar-absolute-from-gregorian current))
11113 (if (<= cday sday) (throw 'exit sday))
11115 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11116 (setq dn (string-to-number (match-string 1 change))
11117 dw (cdr (assoc (match-string 2 change) a1)))
11118 (error "Invalid change specifyer: %s" change))
11119 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11120 (cond
11121 ((eq dw 'day)
11122 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11123 n2 (+ n1 dn)))
11124 ((eq dw 'year)
11125 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11126 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11127 (setq date1 (list m d y1)
11128 n1 (calendar-absolute-from-gregorian date1)
11129 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11130 n2 (calendar-absolute-from-gregorian date2)))
11131 ((eq dw 'month)
11132 ;; approx number of month between the two dates
11133 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11134 ;; How often does dn fit in there?
11135 (setq d (nth 1 start) m (car start) y (nth 2 start)
11136 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11137 m (+ m nm)
11138 ny (floor (/ m 12))
11139 y (+ y ny)
11140 m (- m (* ny 12)))
11141 (while (> m 12) (setq m (- m 12) y (1+ y)))
11142 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11143 (setq m2 (+ m dn) y2 y)
11144 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11145 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11146 (while (<= n2 cday)
11147 (setq n1 n2 m m2 y y2)
11148 (setq m2 (+ m dn) y2 y)
11149 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11150 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11151 (if show-all
11152 (cond
11153 ((eq prefer 'past) n1)
11154 ((eq prefer 'future) (if (= cday n1) n1 n2))
11155 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11156 (cond
11157 ((eq prefer 'past) n1)
11158 ((eq prefer 'future) (if (= cday n1) n1 n2))
11159 (t (if (= cday n1) n1 n2)))))))
11161 (defun org-date-to-gregorian (date)
11162 "Turn any specification of DATE into a gregorian date for the calendar."
11163 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11164 ((and (listp date) (= (length date) 3)) date)
11165 ((stringp date)
11166 (setq date (org-parse-time-string date))
11167 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11168 ((listp date)
11169 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11171 (defun org-parse-time-string (s &optional nodefault)
11172 "Parse the standard Org-mode time string.
11173 This should be a lot faster than the normal `parse-time-string'.
11174 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11175 hour and minute fields will be nil if not given."
11176 (if (string-match org-ts-regexp0 s)
11177 (list 0
11178 (if (or (match-beginning 8) (not nodefault))
11179 (string-to-number (or (match-string 8 s) "0")))
11180 (if (or (match-beginning 7) (not nodefault))
11181 (string-to-number (or (match-string 7 s) "0")))
11182 (string-to-number (match-string 4 s))
11183 (string-to-number (match-string 3 s))
11184 (string-to-number (match-string 2 s))
11185 nil nil nil)
11186 (make-list 9 0)))
11188 (defun org-timestamp-up (&optional arg)
11189 "Increase the date item at the cursor by one.
11190 If the cursor is on the year, change the year. If it is on the month or
11191 the day, change that.
11192 With prefix ARG, change by that many units."
11193 (interactive "p")
11194 (org-timestamp-change (prefix-numeric-value arg)))
11196 (defun org-timestamp-down (&optional arg)
11197 "Decrease the date item at the cursor by one.
11198 If the cursor is on the year, change the year. If it is on the month or
11199 the day, change that.
11200 With prefix ARG, change by that many units."
11201 (interactive "p")
11202 (org-timestamp-change (- (prefix-numeric-value arg))))
11204 (defun org-timestamp-up-day (&optional arg)
11205 "Increase the date in the time stamp by one day.
11206 With prefix ARG, change that many days."
11207 (interactive "p")
11208 (if (and (not (org-at-timestamp-p t))
11209 (org-on-heading-p))
11210 (org-todo 'up)
11211 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11213 (defun org-timestamp-down-day (&optional arg)
11214 "Decrease the date in the time stamp by one day.
11215 With prefix ARG, change that many days."
11216 (interactive "p")
11217 (if (and (not (org-at-timestamp-p t))
11218 (org-on-heading-p))
11219 (org-todo 'down)
11220 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11222 (defun org-at-timestamp-p (&optional inactive-ok)
11223 "Determine if the cursor is in or at a timestamp."
11224 (interactive)
11225 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11226 (pos (point))
11227 (ans (or (looking-at tsr)
11228 (save-excursion
11229 (skip-chars-backward "^[<\n\r\t")
11230 (if (> (point) (point-min)) (backward-char 1))
11231 (and (looking-at tsr)
11232 (> (- (match-end 0) pos) -1))))))
11233 (and ans
11234 (boundp 'org-ts-what)
11235 (setq org-ts-what
11236 (cond
11237 ((= pos (match-beginning 0)) 'bracket)
11238 ((= pos (1- (match-end 0))) 'bracket)
11239 ((org-pos-in-match-range pos 2) 'year)
11240 ((org-pos-in-match-range pos 3) 'month)
11241 ((org-pos-in-match-range pos 7) 'hour)
11242 ((org-pos-in-match-range pos 8) 'minute)
11243 ((or (org-pos-in-match-range pos 4)
11244 (org-pos-in-match-range pos 5)) 'day)
11245 ((and (> pos (or (match-end 8) (match-end 5)))
11246 (< pos (match-end 0)))
11247 (- pos (or (match-end 8) (match-end 5))))
11248 (t 'day))))
11249 ans))
11251 (defun org-toggle-timestamp-type ()
11252 "Toggle the type (<active> or [inactive]) of a time stamp."
11253 (interactive)
11254 (when (org-at-timestamp-p t)
11255 (save-excursion
11256 (goto-char (match-beginning 0))
11257 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11258 (goto-char (1- (match-end 0)))
11259 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11260 (message "Timestamp is now %sactive"
11261 (if (equal (char-before) ?>) "in" ""))))
11263 (defun org-timestamp-change (n &optional what)
11264 "Change the date in the time stamp at point.
11265 The date will be changed by N times WHAT. WHAT can be `day', `month',
11266 `year', `minute', `second'. If WHAT is not given, the cursor position
11267 in the timestamp determines what will be changed."
11268 (let ((pos (point))
11269 with-hm inactive
11270 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11271 org-ts-what
11272 extra rem
11273 ts time time0)
11274 (if (not (org-at-timestamp-p t))
11275 (error "Not at a timestamp"))
11276 (if (and (not what) (eq org-ts-what 'bracket))
11277 (org-toggle-timestamp-type)
11278 (if (and (not what) (not (eq org-ts-what 'day))
11279 org-display-custom-times
11280 (get-text-property (point) 'display)
11281 (not (get-text-property (1- (point)) 'display)))
11282 (setq org-ts-what 'day))
11283 (setq org-ts-what (or what org-ts-what)
11284 inactive (= (char-after (match-beginning 0)) ?\[)
11285 ts (match-string 0))
11286 (replace-match "")
11287 (if (string-match
11288 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11290 (setq extra (match-string 1 ts)))
11291 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11292 (setq with-hm t))
11293 (setq time0 (org-parse-time-string ts))
11294 (when (and (eq org-ts-what 'minute)
11295 (eq current-prefix-arg nil))
11296 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11297 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11298 (setcar (cdr time0) (+ (nth 1 time0)
11299 (if (> n 0) (- rem) (- dm rem))))))
11300 (setq time
11301 (encode-time (or (car time0) 0)
11302 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11303 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11304 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11305 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11306 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11307 (nthcdr 6 time0)))
11308 (when (integerp org-ts-what)
11309 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11310 (if (eq what 'calendar)
11311 (let ((cal-date (org-get-date-from-calendar)))
11312 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11313 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11314 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11315 (setcar time0 (or (car time0) 0))
11316 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11317 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11318 (setq time (apply 'encode-time time0))))
11319 (setq org-last-changed-timestamp
11320 (org-insert-time-stamp time with-hm inactive nil nil extra))
11321 (org-clock-update-time-maybe)
11322 (goto-char pos)
11323 ;; Try to recenter the calendar window, if any
11324 (if (and org-calendar-follow-timestamp-change
11325 (get-buffer-window "*Calendar*" t)
11326 (memq org-ts-what '(day month year)))
11327 (org-recenter-calendar (time-to-days time))))))
11329 (defun org-modify-ts-extra (s pos n dm)
11330 "Change the different parts of the lead-time and repeat fields in timestamp."
11331 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11332 ng h m new rem)
11333 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11334 (cond
11335 ((or (org-pos-in-match-range pos 2)
11336 (org-pos-in-match-range pos 3))
11337 (setq m (string-to-number (match-string 3 s))
11338 h (string-to-number (match-string 2 s)))
11339 (if (org-pos-in-match-range pos 2)
11340 (setq h (+ h n))
11341 (setq n (* dm (org-no-warnings (signum n))))
11342 (when (not (= 0 (setq rem (% m dm))))
11343 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11344 (setq m (+ m n)))
11345 (if (< m 0) (setq m (+ m 60) h (1- h)))
11346 (if (> m 59) (setq m (- m 60) h (1+ h)))
11347 (setq h (min 24 (max 0 h)))
11348 (setq ng 1 new (format "-%02d:%02d" h m)))
11349 ((org-pos-in-match-range pos 6)
11350 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11351 ((org-pos-in-match-range pos 5)
11352 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11354 ((org-pos-in-match-range pos 9)
11355 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11356 ((org-pos-in-match-range pos 8)
11357 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11359 (when ng
11360 (setq s (concat
11361 (substring s 0 (match-beginning ng))
11363 (substring s (match-end ng))))))
11366 (defun org-recenter-calendar (date)
11367 "If the calendar is visible, recenter it to DATE."
11368 (let* ((win (selected-window))
11369 (cwin (get-buffer-window "*Calendar*" t))
11370 (calendar-move-hook nil))
11371 (when cwin
11372 (select-window cwin)
11373 (calendar-goto-date (if (listp date) date
11374 (calendar-gregorian-from-absolute date)))
11375 (select-window win))))
11377 (defun org-goto-calendar (&optional arg)
11378 "Go to the Emacs calendar at the current date.
11379 If there is a time stamp in the current line, go to that date.
11380 A prefix ARG can be used to force the current date."
11381 (interactive "P")
11382 (let ((tsr org-ts-regexp) diff
11383 (calendar-move-hook nil)
11384 (calendar-view-holidays-initially-flag nil)
11385 (view-calendar-holidays-initially nil)
11386 (calendar-view-diary-initially-flag nil)
11387 (view-diary-entries-initially nil))
11388 (if (or (org-at-timestamp-p)
11389 (save-excursion
11390 (beginning-of-line 1)
11391 (looking-at (concat ".*" tsr))))
11392 (let ((d1 (time-to-days (current-time)))
11393 (d2 (time-to-days
11394 (org-time-string-to-time (match-string 1)))))
11395 (setq diff (- d2 d1))))
11396 (calendar)
11397 (calendar-goto-today)
11398 (if (and diff (not arg)) (calendar-forward-day diff))))
11400 (defun org-get-date-from-calendar ()
11401 "Return a list (month day year) of date at point in calendar."
11402 (with-current-buffer "*Calendar*"
11403 (save-match-data
11404 (calendar-cursor-to-date))))
11406 (defun org-date-from-calendar ()
11407 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11408 If there is already a time stamp at the cursor position, update it."
11409 (interactive)
11410 (if (org-at-timestamp-p t)
11411 (org-timestamp-change 0 'calendar)
11412 (let ((cal-date (org-get-date-from-calendar)))
11413 (org-insert-time-stamp
11414 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11416 (defun org-minutes-to-hh:mm-string (m)
11417 "Compute H:MM from a number of minutes."
11418 (let ((h (/ m 60)))
11419 (setq m (- m (* 60 h)))
11420 (format org-time-clocksum-format h m)))
11422 (defun org-hh:mm-string-to-minutes (s)
11423 "Convert a string H:MM to a number of minutes."
11424 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11425 (+ (* (string-to-number (match-string 1 s)) 60)
11426 (string-to-number (match-string 2 s)))
11429 ;;;; Agenda files
11431 ;;;###autoload
11432 (defun org-iswitchb (&optional arg)
11433 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11434 With a prefix argument, restrict available to files.
11435 With two prefix arguments, restrict available buffers to agenda files.
11437 Due to some yet unresolved reason, the global function
11438 `iswitchb-mode' needs to be active for this function to work."
11439 (interactive "P")
11440 (require 'iswitchb)
11441 (let ((enabled iswitchb-mode) blist)
11442 (or enabled (iswitchb-mode 1))
11443 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11444 ((equal arg '(16)) (org-buffer-list 'agenda))
11445 (t (org-buffer-list))))
11446 (unwind-protect
11447 (let ((iswitchb-make-buflist-hook
11448 (lambda ()
11449 (setq iswitchb-temp-buflist
11450 (mapcar 'buffer-name blist)))))
11451 (switch-to-buffer
11452 (iswitchb-read-buffer
11453 "Switch-to: " nil t))
11454 (or enabled (iswitchb-mode -1))))))
11456 (defun org-buffer-list (&optional predicate exclude-tmp)
11457 "Return a list of Org buffers.
11458 PREDICATE can be `export', `files' or `agenda'.
11460 export restrict the list to Export buffers.
11461 files restrict the list to buffers visiting Org files.
11462 agenda restrict the list to buffers visiting agenda files.
11464 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11465 (let* ((bfn nil)
11466 (agenda-files (and (eq predicate 'agenda)
11467 (mapcar 'file-truename (org-agenda-files t))))
11468 (filter
11469 (cond
11470 ((eq predicate 'files)
11471 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11472 ((eq predicate 'export)
11473 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11474 ((eq predicate 'agenda)
11475 (lambda (b)
11476 (with-current-buffer b
11477 (and (eq major-mode 'org-mode)
11478 (setq bfn (buffer-file-name b))
11479 (member (file-truename bfn) agenda-files)))))
11480 (t (lambda (b) (with-current-buffer b
11481 (or (eq major-mode 'org-mode)
11482 (string-match "\*Org .*Export"
11483 (buffer-name b)))))))))
11484 (delq nil
11485 (mapcar
11486 (lambda(b)
11487 (if (and (funcall filter b)
11488 (or (not exclude-tmp)
11489 (not (string-match "tmp" (buffer-name b)))))
11491 nil))
11492 (buffer-list)))))
11494 (defun org-agenda-files (&optional unrestricted archives)
11495 "Get the list of agenda files.
11496 Optional UNRESTRICTED means return the full list even if a restriction
11497 is currently in place.
11498 When ARCHIVES is t, include all archive files hat are really being
11499 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11500 `org-agenda-archives-mode' is t."
11501 (let ((files
11502 (cond
11503 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11504 ((stringp org-agenda-files) (org-read-agenda-file-list))
11505 ((listp org-agenda-files) org-agenda-files)
11506 (t (error "Invalid value of `org-agenda-files'")))))
11507 (setq files (apply 'append
11508 (mapcar (lambda (f)
11509 (if (file-directory-p f)
11510 (directory-files
11511 f t org-agenda-file-regexp)
11512 (list f)))
11513 files)))
11514 (when org-agenda-skip-unavailable-files
11515 (setq files (delq nil
11516 (mapcar (function
11517 (lambda (file)
11518 (and (file-readable-p file) file)))
11519 files))))
11520 (when (or (eq archives t)
11521 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11522 (setq files (org-add-archive-files files)))
11523 files))
11525 (defun org-edit-agenda-file-list ()
11526 "Edit the list of agenda files.
11527 Depending on setup, this either uses customize to edit the variable
11528 `org-agenda-files', or it visits the file that is holding the list. In the
11529 latter case, the buffer is set up in a way that saving it automatically kills
11530 the buffer and restores the previous window configuration."
11531 (interactive)
11532 (if (stringp org-agenda-files)
11533 (let ((cw (current-window-configuration)))
11534 (find-file org-agenda-files)
11535 (org-set-local 'org-window-configuration cw)
11536 (org-add-hook 'after-save-hook
11537 (lambda ()
11538 (set-window-configuration
11539 (prog1 org-window-configuration
11540 (kill-buffer (current-buffer))))
11541 (org-install-agenda-files-menu)
11542 (message "New agenda file list installed"))
11543 nil 'local)
11544 (message "%s" (substitute-command-keys
11545 "Edit list and finish with \\[save-buffer]")))
11546 (customize-variable 'org-agenda-files)))
11548 (defun org-store-new-agenda-file-list (list)
11549 "Set new value for the agenda file list and save it correcly."
11550 (if (stringp org-agenda-files)
11551 (let ((f org-agenda-files) b)
11552 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11553 (with-temp-file f
11554 (insert (mapconcat 'identity list "\n") "\n")))
11555 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11556 (setq org-agenda-files list)
11557 (customize-save-variable 'org-agenda-files org-agenda-files))))
11559 (defun org-read-agenda-file-list ()
11560 "Read the list of agenda files from a file."
11561 (when (file-directory-p org-agenda-files)
11562 (error "`org-agenda-files' cannot be a single directory"))
11563 (when (stringp org-agenda-files)
11564 (with-temp-buffer
11565 (insert-file-contents org-agenda-files)
11566 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11569 ;;;###autoload
11570 (defun org-cycle-agenda-files ()
11571 "Cycle through the files in `org-agenda-files'.
11572 If the current buffer visits an agenda file, find the next one in the list.
11573 If the current buffer does not, find the first agenda file."
11574 (interactive)
11575 (let* ((fs (org-agenda-files t))
11576 (files (append fs (list (car fs))))
11577 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11578 file)
11579 (unless files (error "No agenda files"))
11580 (catch 'exit
11581 (while (setq file (pop files))
11582 (if (equal (file-truename file) tcf)
11583 (when (car files)
11584 (find-file (car files))
11585 (throw 'exit t))))
11586 (find-file (car fs)))
11587 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11589 (defun org-agenda-file-to-front (&optional to-end)
11590 "Move/add the current file to the top of the agenda file list.
11591 If the file is not present in the list, it is added to the front. If it is
11592 present, it is moved there. With optional argument TO-END, add/move to the
11593 end of the list."
11594 (interactive "P")
11595 (let ((org-agenda-skip-unavailable-files nil)
11596 (file-alist (mapcar (lambda (x)
11597 (cons (file-truename x) x))
11598 (org-agenda-files t)))
11599 (ctf (file-truename buffer-file-name))
11600 x had)
11601 (setq x (assoc ctf file-alist) had x)
11603 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11604 (if to-end
11605 (setq file-alist (append (delq x file-alist) (list x)))
11606 (setq file-alist (cons x (delq x file-alist))))
11607 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11608 (org-install-agenda-files-menu)
11609 (message "File %s to %s of agenda file list"
11610 (if had "moved" "added") (if to-end "end" "front"))))
11612 (defun org-remove-file (&optional file)
11613 "Remove current file from the list of files in variable `org-agenda-files'.
11614 These are the files which are being checked for agenda entries.
11615 Optional argument FILE means, use this file instead of the current."
11616 (interactive)
11617 (let* ((org-agenda-skip-unavailable-files nil)
11618 (file (or file buffer-file-name))
11619 (true-file (file-truename file))
11620 (afile (abbreviate-file-name file))
11621 (files (delq nil (mapcar
11622 (lambda (x)
11623 (if (equal true-file
11624 (file-truename x))
11625 nil x))
11626 (org-agenda-files t)))))
11627 (if (not (= (length files) (length (org-agenda-files t))))
11628 (progn
11629 (org-store-new-agenda-file-list files)
11630 (org-install-agenda-files-menu)
11631 (message "Removed file: %s" afile))
11632 (message "File was not in list: %s (not removed)" afile))))
11634 (defun org-file-menu-entry (file)
11635 (vector file (list 'find-file file) t))
11637 (defun org-check-agenda-file (file)
11638 "Make sure FILE exists. If not, ask user what to do."
11639 (when (not (file-exists-p file))
11640 (message "non-existent file %s. [R]emove from list or [A]bort?"
11641 (abbreviate-file-name file))
11642 (let ((r (downcase (read-char-exclusive))))
11643 (cond
11644 ((equal r ?r)
11645 (org-remove-file file)
11646 (throw 'nextfile t))
11647 (t (error "Abort"))))))
11649 (defun org-get-agenda-file-buffer (file)
11650 "Get a buffer visiting FILE. If the buffer needs to be created, add
11651 it to the list of buffers which might be released later."
11652 (let ((buf (org-find-base-buffer-visiting file)))
11653 (if buf
11654 buf ; just return it
11655 ;; Make a new buffer and remember it
11656 (setq buf (find-file-noselect file))
11657 (if buf (push buf org-agenda-new-buffers))
11658 buf)))
11660 (defun org-release-buffers (blist)
11661 "Release all buffers in list, asking the user for confirmation when needed.
11662 When a buffer is unmodified, it is just killed. When modified, it is saved
11663 \(if the user agrees) and then killed."
11664 (let (buf file)
11665 (while (setq buf (pop blist))
11666 (setq file (buffer-file-name buf))
11667 (when (and (buffer-modified-p buf)
11668 file
11669 (y-or-n-p (format "Save file %s? " file)))
11670 (with-current-buffer buf (save-buffer)))
11671 (kill-buffer buf))))
11673 (defun org-prepare-agenda-buffers (files)
11674 "Create buffers for all agenda files, protect archived trees and comments."
11675 (interactive)
11676 (let ((pa '(:org-archived t))
11677 (pc '(:org-comment t))
11678 (pall '(:org-archived t :org-comment t))
11679 (inhibit-read-only t)
11680 (rea (concat ":" org-archive-tag ":"))
11681 bmp file re)
11682 (save-excursion
11683 (save-restriction
11684 (while (setq file (pop files))
11685 (if (bufferp file)
11686 (set-buffer file)
11687 (org-check-agenda-file file)
11688 (set-buffer (org-get-agenda-file-buffer file)))
11689 (widen)
11690 (setq bmp (buffer-modified-p))
11691 (org-refresh-category-properties)
11692 (setq org-todo-keywords-for-agenda
11693 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11694 (setq org-done-keywords-for-agenda
11695 (append org-done-keywords-for-agenda org-done-keywords))
11696 (setq org-todo-keyword-alist-for-agenda
11697 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11698 (setq org-tag-alist-for-agenda
11699 (append org-tag-alist-for-agenda org-tag-alist))
11701 (save-excursion
11702 (remove-text-properties (point-min) (point-max) pall)
11703 (when org-agenda-skip-archived-trees
11704 (goto-char (point-min))
11705 (while (re-search-forward rea nil t)
11706 (if (org-on-heading-p t)
11707 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11708 (goto-char (point-min))
11709 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11710 (while (re-search-forward re nil t)
11711 (add-text-properties
11712 (match-beginning 0) (org-end-of-subtree t) pc)))
11713 (set-buffer-modified-p bmp))))
11714 (setq org-todo-keyword-alist-for-agenda
11715 (org-uniquify org-todo-keyword-alist-for-agenda)
11716 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11718 ;;;; Embedded LaTeX
11720 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11721 "Keymap for the minor `org-cdlatex-mode'.")
11723 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11724 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11725 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11726 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11727 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11729 (defvar org-cdlatex-texmathp-advice-is-done nil
11730 "Flag remembering if we have applied the advice to texmathp already.")
11732 (define-minor-mode org-cdlatex-mode
11733 "Toggle the minor `org-cdlatex-mode'.
11734 This mode supports entering LaTeX environment and math in LaTeX fragments
11735 in Org-mode.
11736 \\{org-cdlatex-mode-map}"
11737 nil " OCDL" nil
11738 (when org-cdlatex-mode (require 'cdlatex))
11739 (unless org-cdlatex-texmathp-advice-is-done
11740 (setq org-cdlatex-texmathp-advice-is-done t)
11741 (defadvice texmathp (around org-math-always-on activate)
11742 "Always return t in org-mode buffers.
11743 This is because we want to insert math symbols without dollars even outside
11744 the LaTeX math segments. If Orgmode thinks that point is actually inside
11745 en embedded LaTeX fragement, let texmathp do its job.
11746 \\[org-cdlatex-mode-map]"
11747 (interactive)
11748 (let (p)
11749 (cond
11750 ((not (org-mode-p)) ad-do-it)
11751 ((eq this-command 'cdlatex-math-symbol)
11752 (setq ad-return-value t
11753 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11755 (let ((p (org-inside-LaTeX-fragment-p)))
11756 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11757 (setq ad-return-value t
11758 texmathp-why '("Org-mode embedded math" . 0))
11759 (if p ad-do-it)))))))))
11761 (defun turn-on-org-cdlatex ()
11762 "Unconditionally turn on `org-cdlatex-mode'."
11763 (org-cdlatex-mode 1))
11765 (defun org-inside-LaTeX-fragment-p ()
11766 "Test if point is inside a LaTeX fragment.
11767 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11768 sequence appearing also before point.
11769 Even though the matchers for math are configurable, this function assumes
11770 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11771 delimiters are skipped when they have been removed by customization.
11772 The return value is nil, or a cons cell with the delimiter and
11773 and the position of this delimiter.
11775 This function does a reasonably good job, but can locally be fooled by
11776 for example currency specifications. For example it will assume being in
11777 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11778 fragments that are properly closed, but during editing, we have to live
11779 with the uncertainty caused by missing closing delimiters. This function
11780 looks only before point, not after."
11781 (catch 'exit
11782 (let ((pos (point))
11783 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11784 (lim (progn
11785 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11786 (point)))
11787 dd-on str (start 0) m re)
11788 (goto-char pos)
11789 (when dodollar
11790 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11791 re (nth 1 (assoc "$" org-latex-regexps)))
11792 (while (string-match re str start)
11793 (cond
11794 ((= (match-end 0) (length str))
11795 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11796 ((= (match-end 0) (- (length str) 5))
11797 (throw 'exit nil))
11798 (t (setq start (match-end 0))))))
11799 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11800 (goto-char pos)
11801 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11802 (and (match-beginning 2) (throw 'exit nil))
11803 ;; count $$
11804 (while (re-search-backward "\\$\\$" lim t)
11805 (setq dd-on (not dd-on)))
11806 (goto-char pos)
11807 (if dd-on (cons "$$" m))))))
11810 (defun org-try-cdlatex-tab ()
11811 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11812 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11813 - inside a LaTeX fragment, or
11814 - after the first word in a line, where an abbreviation expansion could
11815 insert a LaTeX environment."
11816 (when org-cdlatex-mode
11817 (cond
11818 ((save-excursion
11819 (skip-chars-backward "a-zA-Z0-9*")
11820 (skip-chars-backward " \t")
11821 (bolp))
11822 (cdlatex-tab) t)
11823 ((org-inside-LaTeX-fragment-p)
11824 (cdlatex-tab) t)
11825 (t nil))))
11827 (defun org-cdlatex-underscore-caret (&optional arg)
11828 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11829 Revert to the normal definition outside of these fragments."
11830 (interactive "P")
11831 (if (org-inside-LaTeX-fragment-p)
11832 (call-interactively 'cdlatex-sub-superscript)
11833 (let (org-cdlatex-mode)
11834 (call-interactively (key-binding (vector last-input-event))))))
11836 (defun org-cdlatex-math-modify (&optional arg)
11837 "Execute `cdlatex-math-modify' in LaTeX fragments.
11838 Revert to the normal definition outside of these fragments."
11839 (interactive "P")
11840 (if (org-inside-LaTeX-fragment-p)
11841 (call-interactively 'cdlatex-math-modify)
11842 (let (org-cdlatex-mode)
11843 (call-interactively (key-binding (vector last-input-event))))))
11845 (defvar org-latex-fragment-image-overlays nil
11846 "List of overlays carrying the images of latex fragments.")
11847 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11849 (defun org-remove-latex-fragment-image-overlays ()
11850 "Remove all overlays with LaTeX fragment images in current buffer."
11851 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11852 (setq org-latex-fragment-image-overlays nil))
11854 (defun org-preview-latex-fragment (&optional subtree)
11855 "Preview the LaTeX fragment at point, or all locally or globally.
11856 If the cursor is in a LaTeX fragment, create the image and overlay
11857 it over the source code. If there is no fragment at point, display
11858 all fragments in the current text, from one headline to the next. With
11859 prefix SUBTREE, display all fragments in the current subtree. With a
11860 double prefix `C-u C-u', or when the cursor is before the first headline,
11861 display all fragments in the buffer.
11862 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11863 (interactive "P")
11864 (org-remove-latex-fragment-image-overlays)
11865 (save-excursion
11866 (save-restriction
11867 (let (beg end at msg)
11868 (cond
11869 ((or (equal subtree '(16))
11870 (not (save-excursion
11871 (re-search-backward (concat "^" outline-regexp) nil t))))
11872 (setq beg (point-min) end (point-max)
11873 msg "Creating images for buffer...%s"))
11874 ((equal subtree '(4))
11875 (org-back-to-heading)
11876 (setq beg (point) end (org-end-of-subtree t)
11877 msg "Creating images for subtree...%s"))
11879 (if (setq at (org-inside-LaTeX-fragment-p))
11880 (goto-char (max (point-min) (- (cdr at) 2)))
11881 (org-back-to-heading))
11882 (setq beg (point) end (progn (outline-next-heading) (point))
11883 msg (if at "Creating image...%s"
11884 "Creating images for entry...%s"))))
11885 (message msg "")
11886 (narrow-to-region beg end)
11887 (goto-char beg)
11888 (org-format-latex
11889 (concat "ltxpng/" (file-name-sans-extension
11890 (file-name-nondirectory
11891 buffer-file-name)))
11892 default-directory 'overlays msg at 'forbuffer)
11893 (message msg "done. Use `C-c C-c' to remove images.")))))
11895 (defvar org-latex-regexps
11896 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11897 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11898 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11899 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11900 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11901 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11902 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11903 "Regular expressions for matching embedded LaTeX.")
11905 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11906 "Replace LaTeX fragments with links to an image, and produce images."
11907 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11908 (let* ((prefixnodir (file-name-nondirectory prefix))
11909 (absprefix (expand-file-name prefix dir))
11910 (todir (file-name-directory absprefix))
11911 (opt org-format-latex-options)
11912 (matchers (plist-get opt :matchers))
11913 (re-list org-latex-regexps)
11914 (cnt 0) txt link beg end re e checkdir
11915 m n block linkfile movefile ov)
11916 ;; Check if there are old images files with this prefix, and remove them
11917 (when (file-directory-p todir)
11918 (mapc 'delete-file
11919 (directory-files
11920 todir 'full
11921 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11922 ;; Check the different regular expressions
11923 (while (setq e (pop re-list))
11924 (setq m (car e) re (nth 1 e) n (nth 2 e)
11925 block (if (nth 3 e) "\n\n" ""))
11926 (when (member m matchers)
11927 (goto-char (point-min))
11928 (while (re-search-forward re nil t)
11929 (when (or (not at) (equal (cdr at) (match-beginning n)))
11930 (setq txt (match-string n)
11931 beg (match-beginning n) end (match-end n)
11932 cnt (1+ cnt)
11933 linkfile (format "%s_%04d.png" prefix cnt)
11934 movefile (format "%s_%04d.png" absprefix cnt)
11935 link (concat block "[[file:" linkfile "]]" block))
11936 (if msg (message msg cnt))
11937 (goto-char beg)
11938 (unless checkdir ; make sure the directory exists
11939 (setq checkdir t)
11940 (or (file-directory-p todir) (make-directory todir)))
11941 (org-create-formula-image
11942 txt movefile opt forbuffer)
11943 (if overlays
11944 (progn
11945 (setq ov (org-make-overlay beg end))
11946 (if (featurep 'xemacs)
11947 (progn
11948 (org-overlay-put ov 'invisible t)
11949 (org-overlay-put
11950 ov 'end-glyph
11951 (make-glyph (vector 'png :file movefile))))
11952 (org-overlay-put
11953 ov 'display
11954 (list 'image :type 'png :file movefile :ascent 'center)))
11955 (push ov org-latex-fragment-image-overlays)
11956 (goto-char end))
11957 (delete-region beg end)
11958 (insert link))))))))
11960 ;; This function borrows from Ganesh Swami's latex2png.el
11961 (defun org-create-formula-image (string tofile options buffer)
11962 (let* ((tmpdir (if (featurep 'xemacs)
11963 (temp-directory)
11964 temporary-file-directory))
11965 (texfilebase (make-temp-name
11966 (expand-file-name "orgtex" tmpdir)))
11967 (texfile (concat texfilebase ".tex"))
11968 (dvifile (concat texfilebase ".dvi"))
11969 (pngfile (concat texfilebase ".png"))
11970 (fnh (if (featurep 'xemacs)
11971 (font-height (get-face-font 'default))
11972 (face-attribute 'default :height nil)))
11973 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11974 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11975 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11976 "Black"))
11977 (bg (or (plist-get options (if buffer :background :html-background))
11978 "Transparent")))
11979 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11980 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11981 (with-temp-file texfile
11982 (insert org-format-latex-header
11983 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11984 (let ((dir default-directory))
11985 (condition-case nil
11986 (progn
11987 (cd tmpdir)
11988 (call-process "latex" nil nil nil texfile))
11989 (error nil))
11990 (cd dir))
11991 (if (not (file-exists-p dvifile))
11992 (progn (message "Failed to create dvi file from %s" texfile) nil)
11993 (condition-case nil
11994 (call-process "dvipng" nil nil nil
11995 "-E" "-fg" fg "-bg" bg
11996 "-D" dpi
11997 ;;"-x" scale "-y" scale
11998 "-T" "tight"
11999 "-o" pngfile
12000 dvifile)
12001 (error nil))
12002 (if (not (file-exists-p pngfile))
12003 (progn (message "Failed to create png file from %s" texfile) nil)
12004 ;; Use the requested file name and clean up
12005 (copy-file pngfile tofile 'replace)
12006 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12007 (delete-file (concat texfilebase e)))
12008 pngfile))))
12010 (defun org-dvipng-color (attr)
12011 "Return an rgb color specification for dvipng."
12012 (apply 'format "rgb %s %s %s"
12013 (mapcar 'org-normalize-color
12014 (color-values (face-attribute 'default attr nil)))))
12016 (defun org-normalize-color (value)
12017 "Return string to be used as color value for an RGB component."
12018 (format "%g" (/ value 65535.0)))
12021 ;;;; Key bindings
12023 ;; Make `C-c C-x' a prefix key
12024 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12026 ;; TAB key with modifiers
12027 (org-defkey org-mode-map "\C-i" 'org-cycle)
12028 (org-defkey org-mode-map [(tab)] 'org-cycle)
12029 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12030 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12031 (org-defkey org-mode-map "\M-\t" 'org-complete)
12032 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12033 ;; The following line is necessary under Suse GNU/Linux
12034 (unless (featurep 'xemacs)
12035 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12036 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12037 (define-key org-mode-map [backtab] 'org-shifttab)
12039 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12040 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12041 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12043 ;; Cursor keys with modifiers
12044 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12045 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12046 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12047 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12049 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12050 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12051 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12052 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12054 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12055 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12056 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12057 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12059 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12060 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12062 ;;; Extra keys for tty access.
12063 ;; We only set them when really needed because otherwise the
12064 ;; menus don't show the simple keys
12066 (when (or org-use-extra-keys
12067 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12068 (not window-system))
12069 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12070 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12071 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12072 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12073 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12074 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12075 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12076 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12077 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12078 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12079 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12080 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12081 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12082 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12083 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12084 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12085 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12086 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12087 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12088 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12089 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12090 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12092 ;; All the other keys
12094 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12095 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12096 (if (boundp 'narrow-map)
12097 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12098 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12099 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12100 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12101 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12102 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12103 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12104 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12105 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12106 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12107 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12108 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12109 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12110 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12111 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12112 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12113 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12114 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12115 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12116 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12117 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12118 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12119 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12120 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12121 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12122 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12123 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12124 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12125 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12126 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12127 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12128 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12129 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12130 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12131 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12132 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12133 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12134 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12135 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12136 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12137 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12138 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12139 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12140 (org-defkey org-mode-map "\C-c^" 'org-sort)
12141 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12142 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12143 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12144 (org-defkey org-mode-map "\C-m" 'org-return)
12145 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12146 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12147 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12148 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12149 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12150 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12151 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12152 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12153 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12154 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12155 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12156 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12157 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12158 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12159 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12160 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12162 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12163 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12164 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12165 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12167 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12168 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12169 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12170 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12171 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12172 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12173 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12174 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12175 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12176 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12177 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12178 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12180 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12182 (when (featurep 'xemacs)
12183 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12185 (defvar org-table-auto-blank-field) ; defined in org-table.el
12186 (defun org-self-insert-command (N)
12187 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12188 If the cursor is in a table looking at whitespace, the whitespace is
12189 overwritten, and the table is not marked as requiring realignment."
12190 (interactive "p")
12191 (if (and (org-table-p)
12192 (progn
12193 ;; check if we blank the field, and if that triggers align
12194 (and (featurep 'org-table) org-table-auto-blank-field
12195 (member last-command
12196 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12197 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12198 ;; got extra space, this field does not determine column width
12199 (let (org-table-may-need-update) (org-table-blank-field))
12200 ;; no extra space, this field may determine column width
12201 (org-table-blank-field)))
12203 (eq N 1)
12204 (looking-at "[^|\n]* |"))
12205 (let (org-table-may-need-update)
12206 (goto-char (1- (match-end 0)))
12207 (delete-backward-char 1)
12208 (goto-char (match-beginning 0))
12209 (self-insert-command N))
12210 (setq org-table-may-need-update t)
12211 (self-insert-command N)
12212 (org-fix-tags-on-the-fly)))
12214 (defun org-fix-tags-on-the-fly ()
12215 (when (and (equal (char-after (point-at-bol)) ?*)
12216 (org-on-heading-p))
12217 (org-align-tags-here org-tags-column)))
12219 (defun org-delete-backward-char (N)
12220 "Like `delete-backward-char', insert whitespace at field end in tables.
12221 When deleting backwards, in tables this function will insert whitespace in
12222 front of the next \"|\" separator, to keep the table aligned. The table will
12223 still be marked for re-alignment if the field did fill the entire column,
12224 because, in this case the deletion might narrow the column."
12225 (interactive "p")
12226 (if (and (org-table-p)
12227 (eq N 1)
12228 (string-match "|" (buffer-substring (point-at-bol) (point)))
12229 (looking-at ".*?|"))
12230 (let ((pos (point))
12231 (noalign (looking-at "[^|\n\r]* |"))
12232 (c org-table-may-need-update))
12233 (backward-delete-char N)
12234 (skip-chars-forward "^|")
12235 (insert " ")
12236 (goto-char (1- pos))
12237 ;; noalign: if there were two spaces at the end, this field
12238 ;; does not determine the width of the column.
12239 (if noalign (setq org-table-may-need-update c)))
12240 (backward-delete-char N)
12241 (org-fix-tags-on-the-fly)))
12243 (defun org-delete-char (N)
12244 "Like `delete-char', but insert whitespace at field end in tables.
12245 When deleting characters, in tables this function will insert whitespace in
12246 front of the next \"|\" separator, to keep the table aligned. The table will
12247 still be marked for re-alignment if the field did fill the entire column,
12248 because, in this case the deletion might narrow the column."
12249 (interactive "p")
12250 (if (and (org-table-p)
12251 (not (bolp))
12252 (not (= (char-after) ?|))
12253 (eq N 1))
12254 (if (looking-at ".*?|")
12255 (let ((pos (point))
12256 (noalign (looking-at "[^|\n\r]* |"))
12257 (c org-table-may-need-update))
12258 (replace-match (concat
12259 (substring (match-string 0) 1 -1)
12260 " |"))
12261 (goto-char pos)
12262 ;; noalign: if there were two spaces at the end, this field
12263 ;; does not determine the width of the column.
12264 (if noalign (setq org-table-may-need-update c)))
12265 (delete-char N))
12266 (delete-char N)
12267 (org-fix-tags-on-the-fly)))
12269 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12270 (put 'org-self-insert-command 'delete-selection t)
12271 (put 'orgtbl-self-insert-command 'delete-selection t)
12272 (put 'org-delete-char 'delete-selection 'supersede)
12273 (put 'org-delete-backward-char 'delete-selection 'supersede)
12275 ;; Make `flyspell-mode' delay after some commands
12276 (put 'org-self-insert-command 'flyspell-delayed t)
12277 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12278 (put 'org-delete-char 'flyspell-delayed t)
12279 (put 'org-delete-backward-char 'flyspell-delayed t)
12281 ;; Make pabbrev-mode expand after org-mode commands
12282 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12283 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12285 ;; How to do this: Measure non-white length of current string
12286 ;; If equal to column width, we should realign.
12288 (defun org-remap (map &rest commands)
12289 "In MAP, remap the functions given in COMMANDS.
12290 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12291 (let (new old)
12292 (while commands
12293 (setq old (pop commands) new (pop commands))
12294 (if (fboundp 'command-remapping)
12295 (org-defkey map (vector 'remap old) new)
12296 (substitute-key-definition old new map global-map)))))
12298 (when (eq org-enable-table-editor 'optimized)
12299 ;; If the user wants maximum table support, we need to hijack
12300 ;; some standard editing functions
12301 (org-remap org-mode-map
12302 'self-insert-command 'org-self-insert-command
12303 'delete-char 'org-delete-char
12304 'delete-backward-char 'org-delete-backward-char)
12305 (org-defkey org-mode-map "|" 'org-force-self-insert))
12307 (defun org-shiftcursor-error ()
12308 "Throw an error because Shift-Cursor command was applied in wrong context."
12309 (error "This command is active in special context like tables, headlines or timestamps"))
12311 (defun org-shifttab (&optional arg)
12312 "Global visibility cycling or move to previous table field.
12313 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12314 on context.
12315 See the individual commands for more information."
12316 (interactive "P")
12317 (cond
12318 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12319 ((integerp arg)
12320 (message "Content view to level: %d" arg)
12321 (org-content (prefix-numeric-value arg))
12322 (setq org-cycle-global-status 'overview))
12323 (t (call-interactively 'org-global-cycle))))
12325 (defun org-shiftmetaleft ()
12326 "Promote subtree or delete table column.
12327 Calls `org-promote-subtree', `org-outdent-item',
12328 or `org-table-delete-column', depending on context.
12329 See the individual commands for more information."
12330 (interactive)
12331 (cond
12332 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12333 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12334 ((org-at-item-p) (call-interactively 'org-outdent-item))
12335 (t (org-shiftcursor-error))))
12337 (defun org-shiftmetaright ()
12338 "Demote subtree or insert table column.
12339 Calls `org-demote-subtree', `org-indent-item',
12340 or `org-table-insert-column', depending on context.
12341 See the individual commands for more information."
12342 (interactive)
12343 (cond
12344 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12345 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12346 ((org-at-item-p) (call-interactively 'org-indent-item))
12347 (t (org-shiftcursor-error))))
12349 (defun org-shiftmetaup (&optional arg)
12350 "Move subtree up or kill table row.
12351 Calls `org-move-subtree-up' or `org-table-kill-row' or
12352 `org-move-item-up' depending on context. See the individual commands
12353 for more information."
12354 (interactive "P")
12355 (cond
12356 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12357 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12358 ((org-at-item-p) (call-interactively 'org-move-item-up))
12359 (t (org-shiftcursor-error))))
12360 (defun org-shiftmetadown (&optional arg)
12361 "Move subtree down or insert table row.
12362 Calls `org-move-subtree-down' or `org-table-insert-row' or
12363 `org-move-item-down', depending on context. See the individual
12364 commands for more information."
12365 (interactive "P")
12366 (cond
12367 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12368 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12369 ((org-at-item-p) (call-interactively 'org-move-item-down))
12370 (t (org-shiftcursor-error))))
12372 (defun org-metaleft (&optional arg)
12373 "Promote heading or move table column to left.
12374 Calls `org-do-promote' or `org-table-move-column', depending on context.
12375 With no specific context, calls the Emacs default `backward-word'.
12376 See the individual commands for more information."
12377 (interactive "P")
12378 (cond
12379 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12380 ((or (org-on-heading-p) (org-region-active-p))
12381 (call-interactively 'org-do-promote))
12382 ((org-at-item-p) (call-interactively 'org-outdent-item))
12383 (t (call-interactively 'backward-word))))
12385 (defun org-metaright (&optional arg)
12386 "Demote subtree or move table column to right.
12387 Calls `org-do-demote' or `org-table-move-column', depending on context.
12388 With no specific context, calls the Emacs default `forward-word'.
12389 See the individual commands for more information."
12390 (interactive "P")
12391 (cond
12392 ((org-at-table-p) (call-interactively 'org-table-move-column))
12393 ((or (org-on-heading-p) (org-region-active-p))
12394 (call-interactively 'org-do-demote))
12395 ((org-at-item-p) (call-interactively 'org-indent-item))
12396 (t (call-interactively 'forward-word))))
12398 (defun org-metaup (&optional arg)
12399 "Move subtree up or move table row up.
12400 Calls `org-move-subtree-up' or `org-table-move-row' or
12401 `org-move-item-up', depending on context. See the individual commands
12402 for more information."
12403 (interactive "P")
12404 (cond
12405 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12406 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12407 ((org-at-item-p) (call-interactively 'org-move-item-up))
12408 (t (transpose-lines 1) (beginning-of-line -1))))
12410 (defun org-metadown (&optional arg)
12411 "Move subtree down or move table row down.
12412 Calls `org-move-subtree-down' or `org-table-move-row' or
12413 `org-move-item-down', depending on context. See the individual
12414 commands for more information."
12415 (interactive "P")
12416 (cond
12417 ((org-at-table-p) (call-interactively 'org-table-move-row))
12418 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12419 ((org-at-item-p) (call-interactively 'org-move-item-down))
12420 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12422 (defun org-shiftup (&optional arg)
12423 "Increase item in timestamp or increase priority of current headline.
12424 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12425 depending on context. See the individual commands for more information."
12426 (interactive "P")
12427 (cond
12428 ((org-at-timestamp-p t)
12429 (call-interactively (if org-edit-timestamp-down-means-later
12430 'org-timestamp-down 'org-timestamp-up)))
12431 ((org-on-heading-p) (call-interactively 'org-priority-up))
12432 ((org-at-item-p) (call-interactively 'org-previous-item))
12433 ((org-clocktable-try-shift 'up arg))
12434 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12436 (defun org-shiftdown (&optional arg)
12437 "Decrease item in timestamp or decrease priority of current headline.
12438 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12439 depending on context. See the individual commands for more information."
12440 (interactive "P")
12441 (cond
12442 ((org-at-timestamp-p t)
12443 (call-interactively (if org-edit-timestamp-down-means-later
12444 'org-timestamp-up 'org-timestamp-down)))
12445 ((org-on-heading-p) (call-interactively 'org-priority-down))
12446 ((org-clocktable-try-shift 'down arg))
12447 (t (call-interactively 'org-next-item))))
12449 (defun org-shiftright (&optional arg)
12450 "Next TODO keyword or timestamp one day later, depending on context."
12451 (interactive "P")
12452 (cond
12453 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12454 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12455 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12456 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12457 ((org-clocktable-try-shift 'right arg))
12458 (t (org-shiftcursor-error))))
12460 (defun org-shiftleft (&optional arg)
12461 "Previous TODO keyword or timestamp one day earlier, depending on context."
12462 (interactive "P")
12463 (cond
12464 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12465 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12466 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12467 ((org-at-property-p)
12468 (call-interactively 'org-property-previous-allowed-value))
12469 ((org-clocktable-try-shift 'left arg))
12470 (t (org-shiftcursor-error))))
12472 (defun org-shiftcontrolright ()
12473 "Switch to next TODO set."
12474 (interactive)
12475 (cond
12476 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12477 (t (org-shiftcursor-error))))
12479 (defun org-shiftcontrolleft ()
12480 "Switch to previous TODO set."
12481 (interactive)
12482 (cond
12483 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12484 (t (org-shiftcursor-error))))
12486 (defun org-ctrl-c-ret ()
12487 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12488 (interactive)
12489 (cond
12490 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12491 (t (call-interactively 'org-insert-heading))))
12493 (defun org-copy-special ()
12494 "Copy region in table or copy current subtree.
12495 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12496 See the individual commands for more information."
12497 (interactive)
12498 (call-interactively
12499 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12501 (defun org-cut-special ()
12502 "Cut region in table or cut current subtree.
12503 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12504 See the individual commands for more information."
12505 (interactive)
12506 (call-interactively
12507 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12509 (defun org-paste-special (arg)
12510 "Paste rectangular region into table, or past subtree relative to level.
12511 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12512 See the individual commands for more information."
12513 (interactive "P")
12514 (if (org-at-table-p)
12515 (org-table-paste-rectangle)
12516 (org-paste-subtree arg)))
12518 (defun org-edit-special ()
12519 "Call a special editor for the stuff at point.
12520 When at a table, call the formula editor with `org-table-edit-formulas'.
12521 When at the first line of an src example, call `org-edit-src-code'.
12522 When in an #+include line, visit the include file. Otherwise call
12523 `ffap' to visit the file at point."
12524 (interactive)
12525 (cond
12526 ((org-at-table-p)
12527 (call-interactively 'org-table-edit-formulas))
12528 ((save-excursion
12529 (beginning-of-line 1)
12530 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12531 (find-file (org-trim (match-string 1))))
12532 ((org-edit-src-code))
12533 ((org-edit-fixed-width-region))
12534 (t (call-interactively 'ffap))))
12536 (defun org-ctrl-c-ctrl-c (&optional arg)
12537 "Set tags in headline, or update according to changed information at point.
12539 This command does many different things, depending on context:
12541 - If the cursor is in a headline, prompt for tags and insert them
12542 into the current line, aligned to `org-tags-column'. When called
12543 with prefix arg, realign all tags in the current buffer.
12545 - If the cursor is in one of the special #+KEYWORD lines, this
12546 triggers scanning the buffer for these lines and updating the
12547 information.
12549 - If the cursor is inside a table, realign the table. This command
12550 works even if the automatic table editor has been turned off.
12552 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12553 the entire table.
12555 - If the cursor is a the beginning of a dynamic block, update it.
12557 - If the cursor is inside a table created by the table.el package,
12558 activate that table.
12560 - If the current buffer is a remember buffer, close note and file it.
12561 with a prefix argument, file it without further interaction to the default
12562 location.
12564 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12565 links in this buffer.
12567 - If the cursor is on a numbered item in a plain list, renumber the
12568 ordered list.
12570 - If the cursor is on a checkbox, toggle it."
12571 (interactive "P")
12572 (let ((org-enable-table-editor t))
12573 (cond
12574 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12575 org-occur-highlights
12576 org-latex-fragment-image-overlays)
12577 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12578 (org-remove-occur-highlights)
12579 (org-remove-latex-fragment-image-overlays)
12580 (message "Temporary highlights/overlays removed from current buffer"))
12581 ((and (local-variable-p 'org-finish-function (current-buffer))
12582 (fboundp org-finish-function))
12583 (funcall org-finish-function))
12584 ((org-at-property-p)
12585 (call-interactively 'org-property-action))
12586 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12587 ((org-on-heading-p) (call-interactively 'org-set-tags))
12588 ((org-at-table.el-p)
12589 (require 'table)
12590 (beginning-of-line 1)
12591 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12592 (call-interactively 'table-recognize-table))
12593 ((org-at-table-p)
12594 (org-table-maybe-eval-formula)
12595 (if arg
12596 (call-interactively 'org-table-recalculate)
12597 (org-table-maybe-recalculate-line))
12598 (call-interactively 'org-table-align))
12599 ((org-at-item-checkbox-p)
12600 (call-interactively 'org-toggle-checkbox))
12601 ((org-at-item-p)
12602 (call-interactively 'org-maybe-renumber-ordered-list))
12603 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12604 ;; Dynamic block
12605 (beginning-of-line 1)
12606 (save-excursion (org-update-dblock)))
12607 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12608 (cond
12609 ((equal (match-string 1) "TBLFM")
12610 ;; Recalculate the table before this line
12611 (save-excursion
12612 (beginning-of-line 1)
12613 (skip-chars-backward " \r\n\t")
12614 (if (org-at-table-p)
12615 (org-call-with-arg 'org-table-recalculate t))))
12617 ; (org-set-regexps-and-options)
12618 ; (org-restart-font-lock)
12619 (let ((org-inhibit-startup t)) (org-mode-restart))
12620 (message "Local setup has been refreshed"))))
12621 (t (error "C-c C-c can do nothing useful at this location.")))))
12623 (defun org-mode-restart ()
12624 "Restart Org-mode, to scan again for special lines.
12625 Also updates the keyword regular expressions."
12626 (interactive)
12627 (org-mode)
12628 (message "Org-mode restarted"))
12630 (defun org-kill-note-or-show-branches ()
12631 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12632 (interactive)
12633 (if (not org-finish-function)
12634 (call-interactively 'show-branches)
12635 (let ((org-note-abort t))
12636 (funcall org-finish-function))))
12638 (defun org-return (&optional indent)
12639 "Goto next table row or insert a newline.
12640 Calls `org-table-next-row' or `newline', depending on context.
12641 See the individual commands for more information."
12642 (interactive)
12643 (cond
12644 ((bobp) (if indent (newline-and-indent) (newline)))
12645 ((and (org-at-heading-p)
12646 (looking-at
12647 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12648 (org-show-entry)
12649 (end-of-line 1)
12650 (newline))
12651 ((org-at-table-p)
12652 (org-table-justify-field-maybe)
12653 (call-interactively 'org-table-next-row))
12654 (t (if indent (newline-and-indent) (newline)))))
12656 (defun org-return-indent ()
12657 "Goto next table row or insert a newline and indent.
12658 Calls `org-table-next-row' or `newline-and-indent', depending on
12659 context. See the individual commands for more information."
12660 (interactive)
12661 (org-return t))
12663 (defun org-ctrl-c-star ()
12664 "Compute table, or change heading status of lines.
12665 Calls `org-table-recalculate' or `org-toggle-region-headings',
12666 depending on context. This will also turn a plain list item or a normal
12667 line into a subheading."
12668 (interactive)
12669 (cond
12670 ((org-at-table-p)
12671 (call-interactively 'org-table-recalculate))
12672 ((org-region-active-p)
12673 ;; Convert all lines in region to list items
12674 (call-interactively 'org-toggle-region-headings))
12675 ((org-on-heading-p)
12676 (org-toggle-region-headings (point-at-bol)
12677 (min (1+ (point-at-eol)) (point-max))))
12678 ((org-at-item-p)
12679 ;; Convert to heading
12680 (let ((level (save-match-data
12681 (save-excursion
12682 (condition-case nil
12683 (progn
12684 (org-back-to-heading t)
12685 (funcall outline-level))
12686 (error 0))))))
12687 (replace-match
12688 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12689 (t (org-toggle-region-headings (point-at-bol)
12690 (min (1+ (point-at-eol)) (point-max))))))
12692 (defun org-ctrl-c-minus ()
12693 "Insert separator line in table or modify bullet status of line.
12694 Also turns a plain line or a region of lines into list items.
12695 Calls `org-table-insert-hline', `org-toggle-region-items', or
12696 `org-cycle-list-bullet', depending on context."
12697 (interactive)
12698 (cond
12699 ((org-at-table-p)
12700 (call-interactively 'org-table-insert-hline))
12701 ((org-on-heading-p)
12702 ;; Convert to item
12703 (save-excursion
12704 (beginning-of-line 1)
12705 (if (looking-at "\\*+ ")
12706 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12707 ((org-region-active-p)
12708 ;; Convert all lines in region to list items
12709 (call-interactively 'org-toggle-region-items))
12710 ((org-in-item-p)
12711 (call-interactively 'org-cycle-list-bullet))
12712 (t (org-toggle-region-items (point-at-bol)
12713 (min (1+ (point-at-eol)) (point-max))))))
12715 (defun org-toggle-region-items (beg end)
12716 "Convert all lines in region to list items.
12717 If the first line is already an item, convert all list items in the region
12718 to normal lines."
12719 (interactive "r")
12720 (let (l2 l)
12721 (save-excursion
12722 (goto-char end)
12723 (setq l2 (org-current-line))
12724 (goto-char beg)
12725 (beginning-of-line 1)
12726 (setq l (1- (org-current-line)))
12727 (if (org-at-item-p)
12728 ;; We already have items, de-itemize
12729 (while (< (setq l (1+ l)) l2)
12730 (when (org-at-item-p)
12731 (goto-char (match-beginning 2))
12732 (delete-region (match-beginning 2) (match-end 2))
12733 (and (looking-at "[ \t]+") (replace-match "")))
12734 (beginning-of-line 2))
12735 (while (< (setq l (1+ l)) l2)
12736 (unless (org-at-item-p)
12737 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12738 (replace-match "\\1- \\2")))
12739 (beginning-of-line 2))))))
12741 (defun org-toggle-region-headings (beg end)
12742 "Convert all lines in region to list items.
12743 If the first line is already an item, convert all list items in the region
12744 to normal lines."
12745 (interactive "r")
12746 (let (l2 l)
12747 (save-excursion
12748 (goto-char end)
12749 (setq l2 (org-current-line))
12750 (goto-char beg)
12751 (beginning-of-line 1)
12752 (setq l (1- (org-current-line)))
12753 (if (org-on-heading-p)
12754 ;; We already have headlines, de-star them
12755 (while (< (setq l (1+ l)) l2)
12756 (when (org-on-heading-p t)
12757 (and (looking-at outline-regexp) (replace-match "")))
12758 (beginning-of-line 2))
12759 (let* ((stars (save-excursion
12760 (re-search-backward org-complex-heading-regexp nil t)
12761 (or (match-string 1) "*")))
12762 (add-stars (if org-odd-levels-only "**" "*"))
12763 (rpl (concat stars add-stars " \\2")))
12764 (while (< (setq l (1+ l)) l2)
12765 (unless (org-on-heading-p)
12766 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12767 (replace-match rpl)))
12768 (beginning-of-line 2)))))))
12770 (defun org-meta-return (&optional arg)
12771 "Insert a new heading or wrap a region in a table.
12772 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12773 See the individual commands for more information."
12774 (interactive "P")
12775 (cond
12776 ((org-at-table-p)
12777 (call-interactively 'org-table-wrap-region))
12778 (t (call-interactively 'org-insert-heading))))
12780 ;;; Menu entries
12782 ;; Define the Org-mode menus
12783 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12784 '("Tbl"
12785 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12786 ["Next Field" org-cycle (org-at-table-p)]
12787 ["Previous Field" org-shifttab (org-at-table-p)]
12788 ["Next Row" org-return (org-at-table-p)]
12789 "--"
12790 ["Blank Field" org-table-blank-field (org-at-table-p)]
12791 ["Edit Field" org-table-edit-field (org-at-table-p)]
12792 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12793 "--"
12794 ("Column"
12795 ["Move Column Left" org-metaleft (org-at-table-p)]
12796 ["Move Column Right" org-metaright (org-at-table-p)]
12797 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12798 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12799 ("Row"
12800 ["Move Row Up" org-metaup (org-at-table-p)]
12801 ["Move Row Down" org-metadown (org-at-table-p)]
12802 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12803 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12804 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12805 "--"
12806 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12807 ("Rectangle"
12808 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12809 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12810 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12811 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12812 "--"
12813 ("Calculate"
12814 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12815 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12816 ["Edit Formulas" org-edit-special (org-at-table-p)]
12817 "--"
12818 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12819 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12820 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12821 "--"
12822 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12823 "--"
12824 ["Sum Column/Rectangle" org-table-sum
12825 (or (org-at-table-p) (org-region-active-p))]
12826 ["Which Column?" org-table-current-column (org-at-table-p)])
12827 ["Debug Formulas"
12828 org-table-toggle-formula-debugger
12829 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12830 ["Show Col/Row Numbers"
12831 org-table-toggle-coordinate-overlays
12832 :style toggle
12833 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12834 "--"
12835 ["Create" org-table-create (and (not (org-at-table-p))
12836 org-enable-table-editor)]
12837 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12838 ["Import from File" org-table-import (not (org-at-table-p))]
12839 ["Export to File" org-table-export (org-at-table-p)]
12840 "--"
12841 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12843 (easy-menu-define org-org-menu org-mode-map "Org menu"
12844 '("Org"
12845 ("Show/Hide"
12846 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12847 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12848 ["Sparse Tree..." org-sparse-tree t]
12849 ["Reveal Context" org-reveal t]
12850 ["Show All" show-all t]
12851 "--"
12852 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12853 "--"
12854 ["New Heading" org-insert-heading t]
12855 ("Navigate Headings"
12856 ["Up" outline-up-heading t]
12857 ["Next" outline-next-visible-heading t]
12858 ["Previous" outline-previous-visible-heading t]
12859 ["Next Same Level" outline-forward-same-level t]
12860 ["Previous Same Level" outline-backward-same-level t]
12861 "--"
12862 ["Jump" org-goto t])
12863 ("Edit Structure"
12864 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12865 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12866 "--"
12867 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12868 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12869 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12870 "--"
12871 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12872 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12873 ["Demote Heading" org-metaright (not (org-at-table-p))]
12874 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12875 "--"
12876 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12877 "--"
12878 ["Convert to odd levels" org-convert-to-odd-levels t]
12879 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12880 ("Editing"
12881 ["Emphasis..." org-emphasize t]
12882 ["Edit Source Example" org-edit-special t])
12883 ("Archive"
12884 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12885 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12886 ; :active t :keys "C-u C-c C-x C-a"]
12887 ["Sparse trees open ARCHIVE trees"
12888 (setq org-sparse-tree-open-archived-trees
12889 (not org-sparse-tree-open-archived-trees))
12890 :style toggle :selected org-sparse-tree-open-archived-trees]
12891 ["Cycling opens ARCHIVE trees"
12892 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12893 :style toggle :selected org-cycle-open-archived-trees]
12894 "--"
12895 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12896 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12897 ; ["Check and Move Children" (org-archive-subtree '(4))
12898 ; :active t :keys "C-u C-c C-x C-s"]
12900 "--"
12901 ("TODO Lists"
12902 ["TODO/DONE/-" org-todo t]
12903 ("Select keyword"
12904 ["Next keyword" org-shiftright (org-on-heading-p)]
12905 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12906 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12907 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12908 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12909 ["Show TODO Tree" org-show-todo-tree t]
12910 ["Global TODO list" org-todo-list t]
12911 "--"
12912 ["Set Priority" org-priority t]
12913 ["Priority Up" org-shiftup t]
12914 ["Priority Down" org-shiftdown t])
12915 ("TAGS and Properties"
12916 ["Set Tags" 'org-set-tags-command t]
12917 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12918 "--"
12919 ["Set property" 'org-set-property t]
12920 ["Column view of properties" org-columns t]
12921 ["Insert Column View DBlock" org-insert-columns-dblock t])
12922 ("Dates and Scheduling"
12923 ["Timestamp" org-time-stamp t]
12924 ["Timestamp (inactive)" org-time-stamp-inactive t]
12925 ("Change Date"
12926 ["1 Day Later" org-shiftright t]
12927 ["1 Day Earlier" org-shiftleft t]
12928 ["1 ... Later" org-shiftup t]
12929 ["1 ... Earlier" org-shiftdown t])
12930 ["Compute Time Range" org-evaluate-time-range t]
12931 ["Schedule Item" org-schedule t]
12932 ["Deadline" org-deadline t]
12933 "--"
12934 ["Custom time format" org-toggle-time-stamp-overlays
12935 :style radio :selected org-display-custom-times]
12936 "--"
12937 ["Goto Calendar" org-goto-calendar t]
12938 ["Date from Calendar" org-date-from-calendar t])
12939 ("Logging work"
12940 ["Clock in" org-clock-in t]
12941 ["Clock out" org-clock-out t]
12942 ["Clock cancel" org-clock-cancel t]
12943 ["Goto running clock" org-clock-goto t]
12944 ["Display times" org-clock-display t]
12945 ["Create clock table" org-clock-report t]
12946 "--"
12947 ["Record DONE time"
12948 (progn (setq org-log-done (not org-log-done))
12949 (message "Switching to %s will %s record a timestamp"
12950 (car org-done-keywords)
12951 (if org-log-done "automatically" "not")))
12952 :style toggle :selected org-log-done])
12953 "--"
12954 ["Agenda Command..." org-agenda t]
12955 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12956 ("File List for Agenda")
12957 ("Special views current file"
12958 ["TODO Tree" org-show-todo-tree t]
12959 ["Check Deadlines" org-check-deadlines t]
12960 ["Timeline" org-timeline t]
12961 ["Tags Tree" org-tags-sparse-tree t])
12962 "--"
12963 ("Hyperlinks"
12964 ["Store Link (Global)" org-store-link t]
12965 ["Insert Link" org-insert-link t]
12966 ["Follow Link" org-open-at-point t]
12967 "--"
12968 ["Next link" org-next-link t]
12969 ["Previous link" org-previous-link t]
12970 "--"
12971 ["Descriptive Links"
12972 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12973 :style radio
12974 :selected (member '(org-link) buffer-invisibility-spec)]
12975 ["Literal Links"
12976 (progn
12977 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12978 :style radio
12979 :selected (not (member '(org-link) buffer-invisibility-spec))])
12980 "--"
12981 ["Export/Publish..." org-export t]
12982 ("LaTeX"
12983 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12984 :selected org-cdlatex-mode]
12985 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12986 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12987 ["Modify math symbol" org-cdlatex-math-modify
12988 (org-inside-LaTeX-fragment-p)]
12989 ["Export LaTeX fragments as images"
12990 (if (featurep 'org-exp)
12991 (setq org-export-with-LaTeX-fragments
12992 (not org-export-with-LaTeX-fragments))
12993 (require 'org-exp))
12994 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12995 org-export-with-LaTeX-fragments)])
12996 "--"
12997 ("Documentation"
12998 ["Show Version" org-version t]
12999 ["Info Documentation" org-info t])
13000 ("Customize"
13001 ["Browse Org Group" org-customize t]
13002 "--"
13003 ["Expand This Menu" org-create-customize-menu
13004 (fboundp 'customize-menu-create)])
13005 "--"
13006 ["Refresh setup" org-mode-restart t]
13009 (defun org-info (&optional node)
13010 "Read documentation for Org-mode in the info system.
13011 With optional NODE, go directly to that node."
13012 (interactive)
13013 (info (format "(org)%s" (or node ""))))
13015 (defun org-install-agenda-files-menu ()
13016 (let ((bl (buffer-list)))
13017 (save-excursion
13018 (while bl
13019 (set-buffer (pop bl))
13020 (if (org-mode-p) (setq bl nil)))
13021 (when (org-mode-p)
13022 (easy-menu-change
13023 '("Org") "File List for Agenda"
13024 (append
13025 (list
13026 ["Edit File List" (org-edit-agenda-file-list) t]
13027 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13028 ["Remove Current File from List" org-remove-file t]
13029 ["Cycle through agenda files" org-cycle-agenda-files t]
13030 ["Occur in all agenda files" org-occur-in-agenda-files t]
13031 "--")
13032 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13034 ;;;; Documentation
13036 ;;;###autoload
13037 (defun org-require-autoloaded-modules ()
13038 (interactive)
13039 (mapc 'require
13040 '(org-agenda org-archive org-clock org-colview
13041 org-exp org-id org-export-latex org-publish
13042 org-remember org-table)))
13044 ;;;###autoload
13045 (defun org-customize ()
13046 "Call the customize function with org as argument."
13047 (interactive)
13048 (org-load-modules-maybe)
13049 (org-require-autoloaded-modules)
13050 (customize-browse 'org))
13052 (defun org-create-customize-menu ()
13053 "Create a full customization menu for Org-mode, insert it into the menu."
13054 (interactive)
13055 (org-load-modules-maybe)
13056 (org-require-autoloaded-modules)
13057 (if (fboundp 'customize-menu-create)
13058 (progn
13059 (easy-menu-change
13060 '("Org") "Customize"
13061 `(["Browse Org group" org-customize t]
13062 "--"
13063 ,(customize-menu-create 'org)
13064 ["Set" Custom-set t]
13065 ["Save" Custom-save t]
13066 ["Reset to Current" Custom-reset-current t]
13067 ["Reset to Saved" Custom-reset-saved t]
13068 ["Reset to Standard Settings" Custom-reset-standard t]))
13069 (message "\"Org\"-menu now contains full customization menu"))
13070 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13072 ;;;; Miscellaneous stuff
13074 ;;; Generally useful functions
13076 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13077 "Display the given MESSAGE as a warning."
13078 (if (fboundp 'display-warning)
13079 (display-warning 'org message
13080 (if (featurep 'xemacs)
13081 'warning
13082 :warning))
13083 (let ((buf (get-buffer-create "*Org warnings*")))
13084 (with-current-buffer buf
13085 (goto-char (point-max))
13086 (insert "Warning (Org): " message)
13087 (unless (bolp)
13088 (newline)))
13089 (display-buffer buf)
13090 (sit-for 0))))
13092 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13093 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13094 (if (and marker (marker-buffer marker)
13095 (buffer-live-p (marker-buffer marker)))
13096 (progn
13097 (switch-to-buffer (marker-buffer marker))
13098 (if (or (> marker (point-max)) (< marker (point-min)))
13099 (widen))
13100 (goto-char marker))
13101 (if bookmark
13102 (bookmark-jump bookmark)
13103 (error "Cannot find location"))))
13105 (defun org-quote-csv-field (s)
13106 "Quote field for inclusion in CSV material."
13107 (if (string-match "[\",]" s)
13108 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13111 (defun org-plist-delete (plist property)
13112 "Delete PROPERTY from PLIST.
13113 This is in contrast to merely setting it to 0."
13114 (let (p)
13115 (while plist
13116 (if (not (eq property (car plist)))
13117 (setq p (plist-put p (car plist) (nth 1 plist))))
13118 (setq plist (cddr plist)))
13121 (defun org-force-self-insert (N)
13122 "Needed to enforce self-insert under remapping."
13123 (interactive "p")
13124 (self-insert-command N))
13126 (defun org-string-width (s)
13127 "Compute width of string, ignoring invisible characters.
13128 This ignores character with invisibility property `org-link', and also
13129 characters with property `org-cwidth', because these will become invisible
13130 upon the next fontification round."
13131 (let (b l)
13132 (when (or (eq t buffer-invisibility-spec)
13133 (assq 'org-link buffer-invisibility-spec))
13134 (while (setq b (text-property-any 0 (length s)
13135 'invisible 'org-link s))
13136 (setq s (concat (substring s 0 b)
13137 (substring s (or (next-single-property-change
13138 b 'invisible s) (length s)))))))
13139 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13140 (setq s (concat (substring s 0 b)
13141 (substring s (or (next-single-property-change
13142 b 'org-cwidth s) (length s))))))
13143 (setq l (string-width s) b -1)
13144 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13145 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13148 (defun org-get-indentation (&optional line)
13149 "Get the indentation of the current line, interpreting tabs.
13150 When LINE is given, assume it represents a line and compute its indentation."
13151 (if line
13152 (if (string-match "^ *" (org-remove-tabs line))
13153 (match-end 0))
13154 (save-excursion
13155 (beginning-of-line 1)
13156 (skip-chars-forward " \t")
13157 (current-column))))
13159 (defun org-remove-tabs (s &optional width)
13160 "Replace tabulators in S with spaces.
13161 Assumes that s is a single line, starting in column 0."
13162 (setq width (or width tab-width))
13163 (while (string-match "\t" s)
13164 (setq s (replace-match
13165 (make-string
13166 (- (* width (/ (+ (match-beginning 0) width) width))
13167 (match-beginning 0)) ?\ )
13168 t t s)))
13171 (defun org-fix-indentation (line ind)
13172 "Fix indentation in LINE.
13173 IND is a cons cell with target and minimum indentation.
13174 If the current indenation in LINE is smaller than the minimum,
13175 leave it alone. If it is larger than ind, set it to the target."
13176 (let* ((l (org-remove-tabs line))
13177 (i (org-get-indentation l))
13178 (i1 (car ind)) (i2 (cdr ind)))
13179 (if (>= i i2) (setq l (substring line i2)))
13180 (if (> i1 0)
13181 (concat (make-string i1 ?\ ) l)
13182 l)))
13184 (defun org-base-buffer (buffer)
13185 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13186 (if (not buffer)
13187 buffer
13188 (or (buffer-base-buffer buffer)
13189 buffer)))
13191 (defun org-trim (s)
13192 "Remove whitespace at beginning and end of string."
13193 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13194 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13197 (defun org-wrap (string &optional width lines)
13198 "Wrap string to either a number of lines, or a width in characters.
13199 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13200 that costs. If there is a word longer than WIDTH, the text is actually
13201 wrapped to the length of that word.
13202 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13203 many lines, whatever width that takes.
13204 The return value is a list of lines, without newlines at the end."
13205 (let* ((words (org-split-string string "[ \t\n]+"))
13206 (maxword (apply 'max (mapcar 'org-string-width words)))
13207 w ll)
13208 (cond (width
13209 (org-do-wrap words (max maxword width)))
13210 (lines
13211 (setq w maxword)
13212 (setq ll (org-do-wrap words maxword))
13213 (if (<= (length ll) lines)
13215 (setq ll words)
13216 (while (> (length ll) lines)
13217 (setq w (1+ w))
13218 (setq ll (org-do-wrap words w)))
13219 ll))
13220 (t (error "Cannot wrap this")))))
13222 (defun org-do-wrap (words width)
13223 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13224 (let (lines line)
13225 (while words
13226 (setq line (pop words))
13227 (while (and words (< (+ (length line) (length (car words))) width))
13228 (setq line (concat line " " (pop words))))
13229 (setq lines (push line lines)))
13230 (nreverse lines)))
13232 (defun org-split-string (string &optional separators)
13233 "Splits STRING into substrings at SEPARATORS.
13234 No empty strings are returned if there are matches at the beginning
13235 and end of string."
13236 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13237 (start 0)
13238 notfirst
13239 (list nil))
13240 (while (and (string-match rexp string
13241 (if (and notfirst
13242 (= start (match-beginning 0))
13243 (< start (length string)))
13244 (1+ start) start))
13245 (< (match-beginning 0) (length string)))
13246 (setq notfirst t)
13247 (or (eq (match-beginning 0) 0)
13248 (and (eq (match-beginning 0) (match-end 0))
13249 (eq (match-beginning 0) start))
13250 (setq list
13251 (cons (substring string start (match-beginning 0))
13252 list)))
13253 (setq start (match-end 0)))
13254 (or (eq start (length string))
13255 (setq list
13256 (cons (substring string start)
13257 list)))
13258 (nreverse list)))
13260 (defun org-context ()
13261 "Return a list of contexts of the current cursor position.
13262 If several contexts apply, all are returned.
13263 Each context entry is a list with a symbol naming the context, and
13264 two positions indicating start and end of the context. Possible
13265 contexts are:
13267 :headline anywhere in a headline
13268 :headline-stars on the leading stars in a headline
13269 :todo-keyword on a TODO keyword (including DONE) in a headline
13270 :tags on the TAGS in a headline
13271 :priority on the priority cookie in a headline
13272 :item on the first line of a plain list item
13273 :item-bullet on the bullet/number of a plain list item
13274 :checkbox on the checkbox in a plain list item
13275 :table in an org-mode table
13276 :table-special on a special filed in a table
13277 :table-table in a table.el table
13278 :link on a hyperlink
13279 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13280 :target on a <<target>>
13281 :radio-target on a <<<radio-target>>>
13282 :latex-fragment on a LaTeX fragment
13283 :latex-preview on a LaTeX fragment with overlayed preview image
13285 This function expects the position to be visible because it uses font-lock
13286 faces as a help to recognize the following contexts: :table-special, :link,
13287 and :keyword."
13288 (let* ((f (get-text-property (point) 'face))
13289 (faces (if (listp f) f (list f)))
13290 (p (point)) clist o)
13291 ;; First the large context
13292 (cond
13293 ((org-on-heading-p t)
13294 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13295 (when (progn
13296 (beginning-of-line 1)
13297 (looking-at org-todo-line-tags-regexp))
13298 (push (org-point-in-group p 1 :headline-stars) clist)
13299 (push (org-point-in-group p 2 :todo-keyword) clist)
13300 (push (org-point-in-group p 4 :tags) clist))
13301 (goto-char p)
13302 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13303 (if (looking-at "\\[#[A-Z0-9]\\]")
13304 (push (org-point-in-group p 0 :priority) clist)))
13306 ((org-at-item-p)
13307 (push (org-point-in-group p 2 :item-bullet) clist)
13308 (push (list :item (point-at-bol)
13309 (save-excursion (org-end-of-item) (point)))
13310 clist)
13311 (and (org-at-item-checkbox-p)
13312 (push (org-point-in-group p 0 :checkbox) clist)))
13314 ((org-at-table-p)
13315 (push (list :table (org-table-begin) (org-table-end)) clist)
13316 (if (memq 'org-formula faces)
13317 (push (list :table-special
13318 (previous-single-property-change p 'face)
13319 (next-single-property-change p 'face)) clist)))
13320 ((org-at-table-p 'any)
13321 (push (list :table-table) clist)))
13322 (goto-char p)
13324 ;; Now the small context
13325 (cond
13326 ((org-at-timestamp-p)
13327 (push (org-point-in-group p 0 :timestamp) clist))
13328 ((memq 'org-link faces)
13329 (push (list :link
13330 (previous-single-property-change p 'face)
13331 (next-single-property-change p 'face)) clist))
13332 ((memq 'org-special-keyword faces)
13333 (push (list :keyword
13334 (previous-single-property-change p 'face)
13335 (next-single-property-change p 'face)) clist))
13336 ((org-on-target-p)
13337 (push (org-point-in-group p 0 :target) clist)
13338 (goto-char (1- (match-beginning 0)))
13339 (if (looking-at org-radio-target-regexp)
13340 (push (org-point-in-group p 0 :radio-target) clist))
13341 (goto-char p))
13342 ((setq o (car (delq nil
13343 (mapcar
13344 (lambda (x)
13345 (if (memq x org-latex-fragment-image-overlays) x))
13346 (org-overlays-at (point))))))
13347 (push (list :latex-fragment
13348 (org-overlay-start o) (org-overlay-end o)) clist)
13349 (push (list :latex-preview
13350 (org-overlay-start o) (org-overlay-end o)) clist))
13351 ((org-inside-LaTeX-fragment-p)
13352 ;; FIXME: positions wrong.
13353 (push (list :latex-fragment (point) (point)) clist)))
13355 (setq clist (nreverse (delq nil clist)))
13356 clist))
13358 ;; FIXME: Compare with at-regexp-p Do we need both?
13359 (defun org-in-regexp (re &optional nlines visually)
13360 "Check if point is inside a match of regexp.
13361 Normally only the current line is checked, but you can include NLINES extra
13362 lines both before and after point into the search.
13363 If VISUALLY is set, require that the cursor is not after the match but
13364 really on, so that the block visually is on the match."
13365 (catch 'exit
13366 (let ((pos (point))
13367 (eol (point-at-eol (+ 1 (or nlines 0))))
13368 (inc (if visually 1 0)))
13369 (save-excursion
13370 (beginning-of-line (- 1 (or nlines 0)))
13371 (while (re-search-forward re eol t)
13372 (if (and (<= (match-beginning 0) pos)
13373 (>= (+ inc (match-end 0)) pos))
13374 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13376 (defun org-at-regexp-p (regexp)
13377 "Is point inside a match of REGEXP in the current line?"
13378 (catch 'exit
13379 (save-excursion
13380 (let ((pos (point)) (end (point-at-eol)))
13381 (beginning-of-line 1)
13382 (while (re-search-forward regexp end t)
13383 (if (and (<= (match-beginning 0) pos)
13384 (>= (match-end 0) pos))
13385 (throw 'exit t)))
13386 nil))))
13388 (defun org-occur-in-agenda-files (regexp &optional nlines)
13389 "Call `multi-occur' with buffers for all agenda files."
13390 (interactive "sOrg-files matching: \np")
13391 (let* ((files (org-agenda-files))
13392 (tnames (mapcar 'file-truename files))
13393 (extra org-agenda-text-search-extra-files)
13395 (when (eq (car extra) 'agenda-archives)
13396 (setq extra (cdr extra))
13397 (setq files (org-add-archive-files files)))
13398 (while (setq f (pop extra))
13399 (unless (member (file-truename f) tnames)
13400 (add-to-list 'files f 'append)
13401 (add-to-list 'tnames (file-truename f) 'append)))
13402 (multi-occur
13403 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13404 regexp)))
13406 (if (boundp 'occur-mode-find-occurrence-hook)
13407 ;; Emacs 23
13408 (add-hook 'occur-mode-find-occurrence-hook
13409 (lambda ()
13410 (when (org-mode-p)
13411 (org-reveal))))
13412 ;; Emacs 22
13413 (defadvice occur-mode-goto-occurrence
13414 (after org-occur-reveal activate)
13415 (and (org-mode-p) (org-reveal)))
13416 (defadvice occur-mode-goto-occurrence-other-window
13417 (after org-occur-reveal activate)
13418 (and (org-mode-p) (org-reveal)))
13419 (defadvice occur-mode-display-occurrence
13420 (after org-occur-reveal activate)
13421 (when (org-mode-p)
13422 (let ((pos (occur-mode-find-occurrence)))
13423 (with-current-buffer (marker-buffer pos)
13424 (save-excursion
13425 (goto-char pos)
13426 (org-reveal)))))))
13428 (defun org-uniquify (list)
13429 "Remove duplicate elements from LIST."
13430 (let (res)
13431 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13432 res))
13434 (defun org-delete-all (elts list)
13435 "Remove all elements in ELTS from LIST."
13436 (while elts
13437 (setq list (delete (pop elts) list)))
13438 list)
13440 (defun org-back-over-empty-lines ()
13441 "Move backwards over witespace, to the beginning of the first empty line.
13442 Returns the number of empty lines passed."
13443 (let ((pos (point)))
13444 (skip-chars-backward " \t\n\r")
13445 (beginning-of-line 2)
13446 (goto-char (min (point) pos))
13447 (count-lines (point) pos)))
13449 (defun org-skip-whitespace ()
13450 (skip-chars-forward " \t\n\r"))
13452 (defun org-point-in-group (point group &optional context)
13453 "Check if POINT is in match-group GROUP.
13454 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13455 match. If the match group does ot exist or point is not inside it,
13456 return nil."
13457 (and (match-beginning group)
13458 (>= point (match-beginning group))
13459 (<= point (match-end group))
13460 (if context
13461 (list context (match-beginning group) (match-end group))
13462 t)))
13464 (defun org-switch-to-buffer-other-window (&rest args)
13465 "Switch to buffer in a second window on the current frame.
13466 In particular, do not allow pop-up frames."
13467 (let (pop-up-frames special-display-buffer-names special-display-regexps
13468 special-display-function)
13469 (apply 'switch-to-buffer-other-window args)))
13471 (defun org-combine-plists (&rest plists)
13472 "Create a single property list from all plists in PLISTS.
13473 The process starts by copying the first list, and then setting properties
13474 from the other lists. Settings in the last list are the most significant
13475 ones and overrule settings in the other lists."
13476 (let ((rtn (copy-sequence (pop plists)))
13477 p v ls)
13478 (while plists
13479 (setq ls (pop plists))
13480 (while ls
13481 (setq p (pop ls) v (pop ls))
13482 (setq rtn (plist-put rtn p v))))
13483 rtn))
13485 (defun org-move-line-down (arg)
13486 "Move the current line down. With prefix argument, move it past ARG lines."
13487 (interactive "p")
13488 (let ((col (current-column))
13489 beg end pos)
13490 (beginning-of-line 1) (setq beg (point))
13491 (beginning-of-line 2) (setq end (point))
13492 (beginning-of-line (+ 1 arg))
13493 (setq pos (move-marker (make-marker) (point)))
13494 (insert (delete-and-extract-region beg end))
13495 (goto-char pos)
13496 (org-move-to-column col)))
13498 (defun org-move-line-up (arg)
13499 "Move the current line up. With prefix argument, move it past ARG lines."
13500 (interactive "p")
13501 (let ((col (current-column))
13502 beg end pos)
13503 (beginning-of-line 1) (setq beg (point))
13504 (beginning-of-line 2) (setq end (point))
13505 (beginning-of-line (- arg))
13506 (setq pos (move-marker (make-marker) (point)))
13507 (insert (delete-and-extract-region beg end))
13508 (goto-char pos)
13509 (org-move-to-column col)))
13511 (defun org-replace-escapes (string table)
13512 "Replace %-escapes in STRING with values in TABLE.
13513 TABLE is an association list with keys like \"%a\" and string values.
13514 The sequences in STRING may contain normal field width and padding information,
13515 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13516 so values can contain further %-escapes if they are define later in TABLE."
13517 (let ((case-fold-search nil)
13518 e re rpl)
13519 (while (setq e (pop table))
13520 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13521 (while (string-match re string)
13522 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13523 (cdr e)))
13524 (setq string (replace-match rpl t t string))))
13525 string))
13528 (defun org-sublist (list start end)
13529 "Return a section of LIST, from START to END.
13530 Counting starts at 1."
13531 (let (rtn (c start))
13532 (setq list (nthcdr (1- start) list))
13533 (while (and list (<= c end))
13534 (push (pop list) rtn)
13535 (setq c (1+ c)))
13536 (nreverse rtn)))
13538 (defun org-find-base-buffer-visiting (file)
13539 "Like `find-buffer-visiting' but alway return the base buffer and
13540 not an indirect buffer."
13541 (let ((buf (find-buffer-visiting file)))
13542 (if buf
13543 (or (buffer-base-buffer buf) buf)
13544 nil)))
13546 (defun org-image-file-name-regexp ()
13547 "Return regexp matching the file names of images."
13548 (if (fboundp 'image-file-name-regexp)
13549 (image-file-name-regexp)
13550 (let ((image-file-name-extensions
13551 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13552 "xbm" "xpm" "pbm" "pgm" "ppm")))
13553 (concat "\\."
13554 (regexp-opt (nconc (mapcar 'upcase
13555 image-file-name-extensions)
13556 image-file-name-extensions)
13558 "\\'"))))
13560 (defun org-file-image-p (file)
13561 "Return non-nil if FILE is an image."
13562 (save-match-data
13563 (string-match (org-image-file-name-regexp) file)))
13565 (defun org-get-cursor-date ()
13566 "Return the date at cursor in as a time.
13567 This works in the calendar and in the agenda, anywhere else it just
13568 returns the current time."
13569 (let (date day defd)
13570 (cond
13571 ((eq major-mode 'calendar-mode)
13572 (setq date (calendar-cursor-to-date)
13573 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13574 ((eq major-mode 'org-agenda-mode)
13575 (setq day (get-text-property (point) 'day))
13576 (if day
13577 (setq date (calendar-gregorian-from-absolute day)
13578 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13579 (nth 2 date))))))
13580 (or defd (current-time))))
13582 (defvar org-agenda-action-marker (make-marker)
13583 "Marker pointing to the entry for the next agenda action.")
13585 (defun org-mark-entry-for-agenda-action ()
13586 "Mark the current entry as target of an agenda action.
13587 Agenda actions are actions executed from the agenda with the key `k',
13588 which make use of the date at the cursor."
13589 (interactive)
13590 (move-marker org-agenda-action-marker
13591 (save-excursion (org-back-to-heading t) (point))
13592 (current-buffer))
13593 (message
13594 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13596 ;;; Paragraph filling stuff.
13597 ;; We want this to be just right, so use the full arsenal.
13599 (defun org-indent-line-function ()
13600 "Indent line like previous, but further if previous was headline or item."
13601 (interactive)
13602 (let* ((pos (point))
13603 (itemp (org-at-item-p))
13604 column bpos bcol tpos tcol bullet btype bullet-type)
13605 ;; Find the previous relevant line
13606 (beginning-of-line 1)
13607 (cond
13608 ((looking-at "#") (setq column 0))
13609 ((looking-at "\\*+ ") (setq column 0))
13611 (beginning-of-line 0)
13612 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13613 (beginning-of-line 0))
13614 (cond
13615 ((looking-at "\\*+[ \t]+")
13616 (if (not org-adapt-indentation)
13617 (setq column 0)
13618 (goto-char (match-end 0))
13619 (setq column (current-column))))
13620 ((org-in-item-p)
13621 (org-beginning-of-item)
13622 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13623 (setq bpos (match-beginning 1) tpos (match-end 0)
13624 bcol (progn (goto-char bpos) (current-column))
13625 tcol (progn (goto-char tpos) (current-column))
13626 bullet (match-string 1)
13627 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13628 (if (> tcol (+ bcol org-description-max-indent))
13629 (setq tcol (+ bcol 5)))
13630 (if (not itemp)
13631 (setq column tcol)
13632 (goto-char pos)
13633 (beginning-of-line 1)
13634 (if (looking-at "\\S-")
13635 (progn
13636 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13637 (setq bullet (match-string 1)
13638 btype (if (string-match "[0-9]" bullet) "n" bullet))
13639 (setq column (if (equal btype bullet-type) bcol tcol)))
13640 (setq column (org-get-indentation)))))
13641 (t (setq column (org-get-indentation))))))
13642 (goto-char pos)
13643 (if (<= (current-column) (current-indentation))
13644 (org-indent-line-to column)
13645 (save-excursion (org-indent-line-to column)))
13646 (setq column (current-column))
13647 (beginning-of-line 1)
13648 (if (looking-at
13649 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13650 (replace-match (concat "\\1" (format org-property-format
13651 (match-string 2) (match-string 3)))
13652 t nil))
13653 (org-move-to-column column)))
13655 (defun org-set-autofill-regexps ()
13656 (interactive)
13657 ;; In the paragraph separator we include headlines, because filling
13658 ;; text in a line directly attached to a headline would otherwise
13659 ;; fill the headline as well.
13660 (org-set-local 'comment-start-skip "^#+[ \t]*")
13661 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13662 ;; The paragraph starter includes hand-formatted lists.
13663 (org-set-local 'paragraph-start
13664 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13665 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13666 ;; But only if the user has not turned off tables or fixed-width regions
13667 (org-set-local
13668 'auto-fill-inhibit-regexp
13669 (concat "\\*+ \\|#\\+"
13670 "\\|[ \t]*" org-keyword-time-regexp
13671 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13672 (concat
13673 "\\|[ \t]*["
13674 (if org-enable-table-editor "|" "")
13675 (if org-enable-fixed-width-editor ":" "")
13676 "]"))))
13677 ;; We use our own fill-paragraph function, to make sure that tables
13678 ;; and fixed-width regions are not wrapped. That function will pass
13679 ;; through to `fill-paragraph' when appropriate.
13680 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13681 ; Adaptive filling: To get full control, first make sure that
13682 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13683 (org-set-local 'adaptive-fill-regexp "\000")
13684 (org-set-local 'adaptive-fill-function
13685 'org-adaptive-fill-function)
13686 (org-set-local
13687 'align-mode-rules-list
13688 '((org-in-buffer-settings
13689 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13690 (modes . '(org-mode))))))
13692 (defun org-fill-paragraph (&optional justify)
13693 "Re-align a table, pass through to fill-paragraph if no table."
13694 (let ((table-p (org-at-table-p))
13695 (table.el-p (org-at-table.el-p)))
13696 (cond ((and (equal (char-after (point-at-bol)) ?*)
13697 (save-excursion (goto-char (point-at-bol))
13698 (looking-at outline-regexp)))
13699 t) ; skip headlines
13700 (table.el-p t) ; skip table.el tables
13701 (table-p (org-table-align) t) ; align org-mode tables
13702 (t nil)))) ; call paragraph-fill
13704 ;; For reference, this is the default value of adaptive-fill-regexp
13705 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13707 (defun org-adaptive-fill-function ()
13708 "Return a fill prefix for org-mode files.
13709 In particular, this makes sure hanging paragraphs for hand-formatted lists
13710 work correctly."
13711 (cond ((looking-at "#[ \t]+")
13712 (match-string 0))
13713 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13714 (save-excursion
13715 (if (> (match-end 1) (+ (match-beginning 1)
13716 org-description-max-indent))
13717 (goto-char (+ (match-beginning 1) 5))
13718 (goto-char (match-end 0)))
13719 (make-string (current-column) ?\ )))
13720 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13721 (save-excursion
13722 (goto-char (match-end 0))
13723 (make-string (current-column) ?\ )))
13724 (t nil)))
13726 ;;; Other stuff.
13728 (defun org-toggle-fixed-width-section (arg)
13729 "Toggle the fixed-width export.
13730 If there is no active region, the QUOTE keyword at the current headline is
13731 inserted or removed. When present, it causes the text between this headline
13732 and the next to be exported as fixed-width text, and unmodified.
13733 If there is an active region, this command adds or removes a colon as the
13734 first character of this line. If the first character of a line is a colon,
13735 this line is also exported in fixed-width font."
13736 (interactive "P")
13737 (let* ((cc 0)
13738 (regionp (org-region-active-p))
13739 (beg (if regionp (region-beginning) (point)))
13740 (end (if regionp (region-end)))
13741 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13742 (case-fold-search nil)
13743 (re "[ \t]*\\(:\\)")
13744 off)
13745 (if regionp
13746 (save-excursion
13747 (goto-char beg)
13748 (setq cc (current-column))
13749 (beginning-of-line 1)
13750 (setq off (looking-at re))
13751 (while (> nlines 0)
13752 (setq nlines (1- nlines))
13753 (beginning-of-line 1)
13754 (cond
13755 (arg
13756 (org-move-to-column cc t)
13757 (insert ":\n")
13758 (forward-line -1))
13759 ((and off (looking-at re))
13760 (replace-match "" t t nil 1))
13761 ((not off) (org-move-to-column cc t) (insert ":")))
13762 (forward-line 1)))
13763 (save-excursion
13764 (org-back-to-heading)
13765 (if (looking-at (concat outline-regexp
13766 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13767 (replace-match "" t t nil 1)
13768 (if (looking-at outline-regexp)
13769 (progn
13770 (goto-char (match-end 0))
13771 (insert org-quote-string " "))))))))
13773 ;;;; Functions extending outline functionality
13775 (defun org-beginning-of-line (&optional arg)
13776 "Go to the beginning of the current line. If that is invisible, continue
13777 to a visible line beginning. This makes the function of C-a more intuitive.
13778 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13779 first attempt, and only move to after the tags when the cursor is already
13780 beyond the end of the headline."
13781 (interactive "P")
13782 (let ((pos (point)) refpos)
13783 (beginning-of-line 1)
13784 (if (bobp)
13786 (backward-char 1)
13787 (if (org-invisible-p)
13788 (while (and (not (bobp)) (org-invisible-p))
13789 (backward-char 1)
13790 (beginning-of-line 1))
13791 (forward-char 1)))
13792 (when org-special-ctrl-a/e
13793 (cond
13794 ((and (looking-at org-complex-heading-regexp)
13795 (= (char-after (match-end 1)) ?\ ))
13796 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13797 (point-at-eol)))
13798 (goto-char
13799 (if (eq org-special-ctrl-a/e t)
13800 (cond ((> pos refpos) refpos)
13801 ((= pos (point)) refpos)
13802 (t (point)))
13803 (cond ((> pos (point)) (point))
13804 ((not (eq last-command this-command)) (point))
13805 (t refpos)))))
13806 ((org-at-item-p)
13807 (goto-char
13808 (if (eq org-special-ctrl-a/e t)
13809 (cond ((> pos (match-end 4)) (match-end 4))
13810 ((= pos (point)) (match-end 4))
13811 (t (point)))
13812 (cond ((> pos (point)) (point))
13813 ((not (eq last-command this-command)) (point))
13814 (t (match-end 4))))))))
13815 (org-no-warnings
13816 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13818 (defun org-end-of-line (&optional arg)
13819 "Go to the end of the line.
13820 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13821 first attempt, and only move to after the tags when the cursor is already
13822 beyond the end of the headline."
13823 (interactive "P")
13824 (if (or (not org-special-ctrl-a/e)
13825 (not (org-on-heading-p)))
13826 (end-of-line arg)
13827 (let ((pos (point)))
13828 (beginning-of-line 1)
13829 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13830 (if (eq org-special-ctrl-a/e t)
13831 (if (or (< pos (match-beginning 1))
13832 (= pos (match-end 0)))
13833 (goto-char (match-beginning 1))
13834 (goto-char (match-end 0)))
13835 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13836 (goto-char (match-end 0))
13837 (goto-char (match-beginning 1))))
13838 (end-of-line arg))))
13839 (org-no-warnings
13840 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13843 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13844 (define-key org-mode-map "\C-e" 'org-end-of-line)
13846 (defun org-kill-line (&optional arg)
13847 "Kill line, to tags or end of line."
13848 (interactive "P")
13849 (cond
13850 ((or (not org-special-ctrl-k)
13851 (bolp)
13852 (not (org-on-heading-p)))
13853 (call-interactively 'kill-line))
13854 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13855 (kill-region (point) (match-beginning 1))
13856 (org-set-tags nil t))
13857 (t (kill-region (point) (point-at-eol)))))
13860 (define-key org-mode-map "\C-k" 'org-kill-line)
13862 (defun org-yank ()
13863 "Yank, and if the yanked text is a single subtree, fold it.
13864 In fact, if the yanked text is a sequence of subtrees, fold all of them."
13865 (interactive)
13866 (if org-yank-folded-subtrees
13867 (let ((beg (point)) end)
13868 (call-interactively 'yank)
13869 (setq end (point))
13870 (goto-char beg)
13871 (when (and (bolp)
13872 (org-kill-is-subtree-p))
13873 (or (looking-at outline-regexp)
13874 (re-search-forward (concat "^" outline-regexp) end t))
13875 (while (and (< (point) end) (looking-at outline-regexp))
13876 (hide-subtree)
13877 (org-cycle-show-empty-lines 'folded)
13878 (condition-case nil
13879 (outline-forward-same-level 1)
13880 (error (goto-char end)))))
13881 (goto-char end)
13882 (skip-chars-forward " \t\n\r"))
13883 (call-interactively 'yank)))
13885 (define-key org-mode-map "\C-y" 'org-yank)
13887 (defun org-invisible-p ()
13888 "Check if point is at a character currently not visible."
13889 ;; Early versions of noutline don't have `outline-invisible-p'.
13890 (if (fboundp 'outline-invisible-p)
13891 (outline-invisible-p)
13892 (get-char-property (point) 'invisible)))
13894 (defun org-invisible-p2 ()
13895 "Check if point is at a character currently not visible."
13896 (save-excursion
13897 (if (and (eolp) (not (bobp))) (backward-char 1))
13898 ;; Early versions of noutline don't have `outline-invisible-p'.
13899 (if (fboundp 'outline-invisible-p)
13900 (outline-invisible-p)
13901 (get-char-property (point) 'invisible))))
13903 (defalias 'org-back-to-heading 'outline-back-to-heading)
13904 (defalias 'org-on-heading-p 'outline-on-heading-p)
13905 (defalias 'org-at-heading-p 'outline-on-heading-p)
13906 (defun org-at-heading-or-item-p ()
13907 (or (org-on-heading-p) (org-at-item-p)))
13909 (defun org-on-target-p ()
13910 (or (org-in-regexp org-radio-target-regexp)
13911 (org-in-regexp org-target-regexp)))
13913 (defun org-up-heading-all (arg)
13914 "Move to the heading line of which the present line is a subheading.
13915 This function considers both visible and invisible heading lines.
13916 With argument, move up ARG levels."
13917 (if (fboundp 'outline-up-heading-all)
13918 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13919 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13921 (defun org-up-heading-safe ()
13922 "Move to the heading line of which the present line is a subheading.
13923 This version will not throw an error. It will return the level of the
13924 headline found, or nil if no higher level is found."
13925 (let ((pos (point)) start-level level
13926 (re (concat "^" outline-regexp)))
13927 (catch 'exit
13928 (outline-back-to-heading t)
13929 (setq start-level (funcall outline-level))
13930 (if (equal start-level 1) (throw 'exit nil))
13931 (while (re-search-backward re nil t)
13932 (setq level (funcall outline-level))
13933 (if (< level start-level) (throw 'exit level)))
13934 nil)))
13936 (defun org-first-sibling-p ()
13937 "Is this heading the first child of its parents?"
13938 (interactive)
13939 (let ((re (concat "^" outline-regexp))
13940 level l)
13941 (unless (org-at-heading-p t)
13942 (error "Not at a heading"))
13943 (setq level (funcall outline-level))
13944 (save-excursion
13945 (if (not (re-search-backward re nil t))
13947 (setq l (funcall outline-level))
13948 (< l level)))))
13950 (defun org-goto-sibling (&optional previous)
13951 "Goto the next sibling, even if it is invisible.
13952 When PREVIOUS is set, go to the previous sibling instead. Returns t
13953 when a sibling was found. When none is found, return nil and don't
13954 move point."
13955 (let ((fun (if previous 're-search-backward 're-search-forward))
13956 (pos (point))
13957 (re (concat "^" outline-regexp))
13958 level l)
13959 (when (condition-case nil (org-back-to-heading t) (error nil))
13960 (setq level (funcall outline-level))
13961 (catch 'exit
13962 (or previous (forward-char 1))
13963 (while (funcall fun re nil t)
13964 (setq l (funcall outline-level))
13965 (when (< l level) (goto-char pos) (throw 'exit nil))
13966 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13967 (goto-char pos)
13968 nil))))
13970 (defun org-show-siblings ()
13971 "Show all siblings of the current headline."
13972 (save-excursion
13973 (while (org-goto-sibling) (org-flag-heading nil)))
13974 (save-excursion
13975 (while (org-goto-sibling 'previous)
13976 (org-flag-heading nil))))
13978 (defun org-show-hidden-entry ()
13979 "Show an entry where even the heading is hidden."
13980 (save-excursion
13981 (org-show-entry)))
13983 (defun org-flag-heading (flag &optional entry)
13984 "Flag the current heading. FLAG non-nil means make invisible.
13985 When ENTRY is non-nil, show the entire entry."
13986 (save-excursion
13987 (org-back-to-heading t)
13988 ;; Check if we should show the entire entry
13989 (if entry
13990 (progn
13991 (org-show-entry)
13992 (save-excursion
13993 (and (outline-next-heading)
13994 (org-flag-heading nil))))
13995 (outline-flag-region (max (point-min) (1- (point)))
13996 (save-excursion (outline-end-of-heading) (point))
13997 flag))))
13999 (defun org-forward-same-level (arg)
14000 "Move forward to the ARG'th subheading at same level as this one.
14001 Stop at the first and last subheadings of a superior heading.
14002 This is like outline-forward-same-level, but invisible headings are ok."
14003 (interactive "p")
14004 (outline-back-to-heading t)
14005 (while (> arg 0)
14006 (let ((point-to-move-to (save-excursion
14007 (org-get-next-sibling))))
14008 (if point-to-move-to
14009 (progn
14010 (goto-char point-to-move-to)
14011 (setq arg (1- arg)))
14012 (progn
14013 (setq arg 0)
14014 (error "No following same-level heading"))))))
14016 (defun org-get-next-sibling ()
14017 "Move to next heading of the same level, and return point.
14018 If there is no such heading, return nil.
14019 This is like outline-next-sibling, but invisible headings are ok."
14020 (let ((level (funcall outline-level)))
14021 (outline-next-heading)
14022 (while (and (not (eobp)) (> (funcall outline-level) level))
14023 (outline-next-heading))
14024 (if (or (eobp) (< (funcall outline-level) level))
14026 (point))))
14028 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14029 ;; This is an exact copy of the original function, but it uses
14030 ;; `org-back-to-heading', to make it work also in invisible
14031 ;; trees. And is uses an invisible-OK argument.
14032 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14033 (org-back-to-heading invisible-OK)
14034 (let ((first t)
14035 (level (funcall outline-level)))
14036 (while (and (not (eobp))
14037 (or first (> (funcall outline-level) level)))
14038 (setq first nil)
14039 (outline-next-heading))
14040 (unless to-heading
14041 (if (memq (preceding-char) '(?\n ?\^M))
14042 (progn
14043 ;; Go to end of line before heading
14044 (forward-char -1)
14045 (if (memq (preceding-char) '(?\n ?\^M))
14046 ;; leave blank line before heading
14047 (forward-char -1))))))
14048 (point))
14050 (defun org-show-subtree ()
14051 "Show everything after this heading at deeper levels."
14052 (outline-flag-region
14053 (point)
14054 (save-excursion
14055 (outline-end-of-subtree) (outline-next-heading) (point))
14056 nil))
14058 (defun org-show-entry ()
14059 "Show the body directly following this heading.
14060 Show the heading too, if it is currently invisible."
14061 (interactive)
14062 (save-excursion
14063 (condition-case nil
14064 (progn
14065 (org-back-to-heading t)
14066 (outline-flag-region
14067 (max (point-min) (1- (point)))
14068 (save-excursion
14069 (re-search-forward
14070 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14071 (or (match-beginning 1) (point-max)))
14072 nil))
14073 (error nil))))
14075 (defun org-make-options-regexp (kwds)
14076 "Make a regular expression for keyword lines."
14077 (concat
14079 "#?[ \t]*\\+\\("
14080 (mapconcat 'regexp-quote kwds "\\|")
14081 "\\):[ \t]*"
14082 "\\(.+\\)"))
14084 ;; Make isearch reveal the necessary context
14085 (defun org-isearch-end ()
14086 "Reveal context after isearch exits."
14087 (when isearch-success ; only if search was successful
14088 (if (featurep 'xemacs)
14089 ;; Under XEmacs, the hook is run in the correct place,
14090 ;; we directly show the context.
14091 (org-show-context 'isearch)
14092 ;; In Emacs the hook runs *before* restoring the overlays.
14093 ;; So we have to use a one-time post-command-hook to do this.
14094 ;; (Emacs 22 has a special variable, see function `org-mode')
14095 (unless (and (boundp 'isearch-mode-end-hook-quit)
14096 isearch-mode-end-hook-quit)
14097 ;; Only when the isearch was not quitted.
14098 (org-add-hook 'post-command-hook 'org-isearch-post-command
14099 'append 'local)))))
14101 (defun org-isearch-post-command ()
14102 "Remove self from hook, and show context."
14103 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14104 (org-show-context 'isearch))
14107 ;;;; Integration with and fixes for other packages
14109 ;;; Imenu support
14111 (defvar org-imenu-markers nil
14112 "All markers currently used by Imenu.")
14113 (make-variable-buffer-local 'org-imenu-markers)
14115 (defun org-imenu-new-marker (&optional pos)
14116 "Return a new marker for use by Imenu, and remember the marker."
14117 (let ((m (make-marker)))
14118 (move-marker m (or pos (point)))
14119 (push m org-imenu-markers)
14122 (defun org-imenu-get-tree ()
14123 "Produce the index for Imenu."
14124 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14125 (setq org-imenu-markers nil)
14126 (let* ((n org-imenu-depth)
14127 (re (concat "^" outline-regexp))
14128 (subs (make-vector (1+ n) nil))
14129 (last-level 0)
14130 m tree level head)
14131 (save-excursion
14132 (save-restriction
14133 (widen)
14134 (goto-char (point-max))
14135 (while (re-search-backward re nil t)
14136 (setq level (org-reduced-level (funcall outline-level)))
14137 (when (<= level n)
14138 (looking-at org-complex-heading-regexp)
14139 (setq head (org-link-display-format
14140 (org-match-string-no-properties 4))
14141 m (org-imenu-new-marker))
14142 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14143 (if (>= level last-level)
14144 (push (cons head m) (aref subs level))
14145 (push (cons head (aref subs (1+ level))) (aref subs level))
14146 (loop for i from (1+ level) to n do (aset subs i nil)))
14147 (setq last-level level)))))
14148 (aref subs 1)))
14150 (eval-after-load "imenu"
14151 '(progn
14152 (add-hook 'imenu-after-jump-hook
14153 (lambda ()
14154 (if (eq major-mode 'org-mode)
14155 (org-show-context 'org-goto))))))
14157 (defun org-link-display-format (link)
14158 "Replace a link with either the description, or the link target
14159 if no description is present"
14160 (save-match-data
14161 (if (string-match org-bracket-link-analytic-regexp link)
14162 (replace-match (or (match-string 5 link)
14163 (concat (match-string 1 link)
14164 (match-string 3 link)))
14165 nil nil link)
14166 link)))
14168 ;; Speedbar support
14170 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14171 "Overlay marking the agenda restriction line in speedbar.")
14172 (org-overlay-put org-speedbar-restriction-lock-overlay
14173 'face 'org-agenda-restriction-lock)
14174 (org-overlay-put org-speedbar-restriction-lock-overlay
14175 'help-echo "Agendas are currently limited to this item.")
14176 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14178 (defun org-speedbar-set-agenda-restriction ()
14179 "Restrict future agenda commands to the location at point in speedbar.
14180 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14181 (interactive)
14182 (require 'org-agenda)
14183 (let (p m tp np dir txt w)
14184 (cond
14185 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14186 'org-imenu t))
14187 (setq m (get-text-property p 'org-imenu-marker))
14188 (save-excursion
14189 (save-restriction
14190 (set-buffer (marker-buffer m))
14191 (goto-char m)
14192 (org-agenda-set-restriction-lock 'subtree))))
14193 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14194 'speedbar-function 'speedbar-find-file))
14195 (setq tp (previous-single-property-change
14196 (1+ p) 'speedbar-function)
14197 np (next-single-property-change
14198 tp 'speedbar-function)
14199 dir (speedbar-line-directory)
14200 txt (buffer-substring-no-properties (or tp (point-min))
14201 (or np (point-max))))
14202 (save-excursion
14203 (save-restriction
14204 (set-buffer (find-file-noselect
14205 (let ((default-directory dir))
14206 (expand-file-name txt))))
14207 (unless (org-mode-p)
14208 (error "Cannot restrict to non-Org-mode file"))
14209 (org-agenda-set-restriction-lock 'file))))
14210 (t (error "Don't know how to restrict Org-mode's agenda")))
14211 (org-move-overlay org-speedbar-restriction-lock-overlay
14212 (point-at-bol) (point-at-eol))
14213 (setq current-prefix-arg nil)
14214 (org-agenda-maybe-redo)))
14216 (eval-after-load "speedbar"
14217 '(progn
14218 (speedbar-add-supported-extension ".org")
14219 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14220 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14221 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14222 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14223 (add-hook 'speedbar-visiting-tag-hook
14224 (lambda () (org-show-context 'org-goto)))))
14227 ;;; Fixes and Hacks for problems with other packages
14229 ;; Make flyspell not check words in links, to not mess up our keymap
14230 (defun org-mode-flyspell-verify ()
14231 "Don't let flyspell put overlays at active buttons."
14232 (not (get-text-property (point) 'keymap)))
14234 ;; Make `bookmark-jump' show the jump location if it was hidden.
14235 (eval-after-load "bookmark"
14236 '(if (boundp 'bookmark-after-jump-hook)
14237 ;; We can use the hook
14238 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14239 ;; Hook not available, use advice
14240 (defadvice bookmark-jump (after org-make-visible activate)
14241 "Make the position visible."
14242 (org-bookmark-jump-unhide))))
14244 (defun org-bookmark-jump-unhide ()
14245 "Unhide the current position, to show the bookmark location."
14246 (and (org-mode-p)
14247 (or (org-invisible-p)
14248 (save-excursion (goto-char (max (point-min) (1- (point))))
14249 (org-invisible-p)))
14250 (org-show-context 'bookmark-jump)))
14252 ;; Make session.el ignore our circular variable
14253 (eval-after-load "session"
14254 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14256 ;;;; Experimental code
14258 (defun org-closed-in-range ()
14259 "Sparse tree of items closed in a certain time range.
14260 Still experimental, may disappear in the future."
14261 (interactive)
14262 ;; Get the time interval from the user.
14263 (let* ((time1 (time-to-seconds
14264 (org-read-date nil 'to-time nil "Starting date: ")))
14265 (time2 (time-to-seconds
14266 (org-read-date nil 'to-time nil "End date:")))
14267 ;; callback function
14268 (callback (lambda ()
14269 (let ((time
14270 (time-to-seconds
14271 (apply 'encode-time
14272 (org-parse-time-string
14273 (match-string 1))))))
14274 ;; check if time in interval
14275 (and (>= time time1) (<= time time2))))))
14276 ;; make tree, check each match with the callback
14277 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14280 ;;;; Finish up
14282 (provide 'org)
14284 (run-hooks 'org-load-hook)
14286 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14288 ;;; org.el ends here