Small bug fixes for inserting tabulators and for cursor positioning.
[org-mode.git] / lisp / org.el
blob8b18a020cab9ac3ae00102a4e9fa132663fb97e3
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.04c
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)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.04c"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (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)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " id: Global id's for identifying entries" org-id)
165 (const :tag " info: Links to Info nodes" org-info)
166 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
167 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
168 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
169 (const :tag " mew Links to Mew folders/messages" org-mew)
170 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
171 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
172 (const :tag " vm: Links to VM folders/messages" org-vm)
173 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
174 (const :tag " mouse: Additional mouse support" org-mouse)
176 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
177 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
178 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
179 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
180 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
181 (const :tag "C eval: Include command output as text" org-eval)
182 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
183 (const :tag "C id: Global id's for identifying entries" org-id)
184 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
185 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
186 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
187 (const :tag "C mtags: Support for muse-like tags" org-mtags)
188 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
189 (const :tag "C registry: A registry for Org links" org-registry)
190 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
191 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
192 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
193 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
194 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
197 (defgroup org-startup nil
198 "Options concerning startup of Org-mode."
199 :tag "Org Startup"
200 :group 'org)
202 (defcustom org-startup-folded t
203 "Non-nil means, entering Org-mode will switch to OVERVIEW.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
207 #+STARTUP: fold
208 #+STARTUP: nofold
209 #+STARTUP: content"
210 :group 'org-startup
211 :type '(choice
212 (const :tag "nofold: show all" nil)
213 (const :tag "fold: overview" t)
214 (const :tag "content: all headlines" content)))
216 (defcustom org-startup-truncated t
217 "Non-nil means, entering Org-mode will set `truncate-lines'.
218 This is useful since some lines containing links can be very long and
219 uninteresting. Also tables look terrible when wrapped."
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-startup-indented nil
224 "Non-nil means, turn on `org-indent-mode' on startup.
225 This can also be configured on a per-file basis by adding one of
226 the following lines anywhere in the buffer:
228 #+STARTUP: localindent
229 #+STARTUP: indent
230 #+STARTUP: noindent"
231 :group 'org-structure
232 :type '(choice
233 (const :tag "Not" nil)
234 (const :tag "Locally" local)
235 (const :tag "Globally (slow on startup in large files)" t)))
237 (defcustom org-startup-align-all-tables nil
238 "Non-nil means, align all tables when visiting a file.
239 This is useful when the column width in tables is forced with <N> cookies
240 in table fields. Such tables will look correct only after the first re-align.
241 This can also be configured on a per-file basis by adding one of
242 the following lines anywhere in the buffer:
243 #+STARTUP: align
244 #+STARTUP: noalign"
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-insert-mode-line-in-empty-file nil
249 "Non-nil means insert the first line setting Org-mode in empty files.
250 When the function `org-mode' is called interactively in an empty file, this
251 normally means that the file name does not automatically trigger Org-mode.
252 To ensure that the file will always be in Org-mode in the future, a
253 line enforcing Org-mode will be inserted into the buffer, if this option
254 has been set."
255 :group 'org-startup
256 :type 'boolean)
258 (defcustom org-replace-disputed-keys nil
259 "Non-nil means use alternative key bindings for some keys.
260 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
261 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
262 If you want to use Org-mode together with one of these other modes,
263 or more generally if you would like to move some Org-mode commands to
264 other keys, set this variable and configure the keys with the variable
265 `org-disputed-keys'.
267 This option is only relevant at load-time of Org-mode, and must be set
268 *before* org.el is loaded. Changing it requires a restart of Emacs to
269 become effective."
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)
558 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
559 org-cycle-hide-drawers
560 org-cycle-show-empty-lines
561 org-optimize-window-after-visibility-change)
562 "Hook that is run after `org-cycle' has changed the buffer visibility.
563 The function(s) in this hook must accept a single argument which indicates
564 the new state that was set by the most recent `org-cycle' command. The
565 argument is a symbol. After a global state change, it can have the values
566 `overview', `content', or `all'. After a local state change, it can have
567 the values `folded', `children', or `subtree'."
568 :group 'org-cycle
569 :type 'hook)
571 (defgroup org-edit-structure nil
572 "Options concerning structure editing in Org-mode."
573 :tag "Org Edit Structure"
574 :group 'org-structure)
576 (defcustom org-odd-levels-only nil
577 "Non-nil means, skip even levels and only use odd levels for the outline.
578 This has the effect that two stars are being added/taken away in
579 promotion/demotion commands. It also influences how levels are
580 handled by the exporters.
581 Changing it requires restart of `font-lock-mode' to become effective
582 for fontification also in regions already fontified.
583 You may also set this on a per-file basis by adding one of the following
584 lines to the buffer:
586 #+STARTUP: odd
587 #+STARTUP: oddeven"
588 :group 'org-edit-structure
589 :group 'org-font-lock
590 :type 'boolean)
592 (defcustom org-adapt-indentation t
593 "Non-nil means, adapt indentation when promoting and demoting.
594 When this is set and the *entire* text in an entry is indented, the
595 indentation is increased by one space in a demotion command, and
596 decreased by one in a promotion command. If any line in the entry
597 body starts at column 0, indentation is not changed at all."
598 :group 'org-edit-structure
599 :type 'boolean)
601 (defcustom org-special-ctrl-a/e nil
602 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
603 When t, `C-a' will bring back the cursor to the beginning of the
604 headline text, i.e. after the stars and after a possible TODO keyword.
605 In an item, this will be the position after the bullet.
606 When the cursor is already at that position, another `C-a' will bring
607 it to the beginning of the line.
608 `C-e' will jump to the end of the headline, ignoring the presence of tags
609 in the headline. A second `C-e' will then jump to the true end of the
610 line, after any tags.
611 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
612 and only a directly following, identical keypress will bring the cursor
613 to the special positions."
614 :group 'org-edit-structure
615 :type '(choice
616 (const :tag "off" nil)
617 (const :tag "after bullet first" t)
618 (const :tag "border first" reversed)))
620 (if (fboundp 'defvaralias)
621 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
623 (defcustom org-special-ctrl-k nil
624 "Non-nil means `C-k' will behave specially in headlines.
625 When nil, `C-k' will call the default `kill-line' command.
626 When t, the following will happen while the cursor is in the headline:
628 - When the cursor is at the beginning of a headline, kill the entire
629 line and possible the folded subtree below the line.
630 - When in the middle of the headline text, kill the headline up to the tags.
631 - When after the headline text, kill the tags."
632 :group 'org-edit-structure
633 :type 'boolean)
635 (defcustom org-M-RET-may-split-line '((default . t))
636 "Non-nil means, M-RET will split the line at the cursor position.
637 When nil, it will go to the end of the line before making a
638 new line.
639 You may also set this option in a different way for different
640 contexts. Valid contexts are:
642 headline when creating a new headline
643 item when creating a new item
644 table in a table field
645 default the value to be used for all contexts not explicitly
646 customized"
647 :group 'org-structure
648 :group 'org-table
649 :type '(choice
650 (const :tag "Always" t)
651 (const :tag "Never" nil)
652 (repeat :greedy t :tag "Individual contexts"
653 (cons
654 (choice :tag "Context"
655 (const headline)
656 (const item)
657 (const table)
658 (const default))
659 (boolean)))))
662 (defcustom org-blank-before-new-entry '((heading . nil)
663 (plain-list-item . nil))
664 "Should `org-insert-heading' leave a blank line before new heading/item?
665 The value is an alist, with `heading' and `plain-list-item' as car,
666 and a boolean flag as cdr."
667 :group 'org-edit-structure
668 :type '(list
669 (cons (const heading) (boolean))
670 (cons (const plain-list-item) (boolean))))
672 (defcustom org-insert-heading-hook nil
673 "Hook being run after inserting a new heading."
674 :group 'org-edit-structure
675 :type 'hook)
677 (defcustom org-enable-fixed-width-editor t
678 "Non-nil means, lines starting with \":\" are treated as fixed-width.
679 This currently only means, they are never auto-wrapped.
680 When nil, such lines will be treated like ordinary lines.
681 See also the QUOTE keyword."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-goto-auto-isearch t
686 "Non-nil means, typing characters in org-goto starts incremental search."
687 :group 'org-edit-structure
688 :type 'boolean)
690 (defgroup org-sparse-trees nil
691 "Options concerning sparse trees in Org-mode."
692 :tag "Org Sparse Trees"
693 :group 'org-structure)
695 (defcustom org-highlight-sparse-tree-matches t
696 "Non-nil means, highlight all matches that define a sparse tree.
697 The highlights will automatically disappear the next time the buffer is
698 changed by an edit command."
699 :group 'org-sparse-trees
700 :type 'boolean)
702 (defcustom org-remove-highlights-with-change t
703 "Non-nil means, any change to the buffer will remove temporary highlights.
704 Such highlights are created by `org-occur' and `org-clock-display'.
705 When nil, `C-c C-c needs to be used to get rid of the highlights.
706 The highlights created by `org-preview-latex-fragment' always need
707 `C-c C-c' to be removed."
708 :group 'org-sparse-trees
709 :group 'org-time
710 :type 'boolean)
713 (defcustom org-occur-hook '(org-first-headline-recenter)
714 "Hook that is run after `org-occur' has constructed a sparse tree.
715 This can be used to recenter the window to show as much of the structure
716 as possible."
717 :group 'org-sparse-trees
718 :type 'hook)
720 (defgroup org-plain-lists nil
721 "Options concerning plain lists in Org-mode."
722 :tag "Org Plain lists"
723 :group 'org-structure)
725 (defcustom org-cycle-include-plain-lists nil
726 "Non-nil means, include plain lists into visibility cycling.
727 This means that during cycling, plain list items will *temporarily* be
728 interpreted as outline headlines with a level given by 1000+i where i is the
729 indentation of the bullet. In all other operations, plain list items are
730 not seen as headlines. For example, you cannot assign a TODO keyword to
731 such an item."
732 :group 'org-plain-lists
733 :type 'boolean)
735 (defcustom org-plain-list-ordered-item-terminator t
736 "The character that makes a line with leading number an ordered list item.
737 Valid values are ?. and ?\). To get both terminators, use t. While
738 ?. may look nicer, it creates the danger that a line with leading
739 number may be incorrectly interpreted as an item. ?\) therefore is
740 the safe choice."
741 :group 'org-plain-lists
742 :type '(choice (const :tag "dot like in \"2.\"" ?.)
743 (const :tag "paren like in \"2)\"" ?\))
744 (const :tab "both" t)))
746 (defcustom org-empty-line-terminates-plain-lists nil
747 "Non-nil means, an empty line ends all plain list levels.
748 When nil, empty lines are part of the preceeding item."
749 :group 'org-plain-lists
750 :type 'boolean)
752 (defcustom org-auto-renumber-ordered-lists t
753 "Non-nil means, automatically renumber ordered plain lists.
754 Renumbering happens when the sequence have been changed with
755 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
756 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
757 :group 'org-plain-lists
758 :type 'boolean)
760 (defcustom org-provide-checkbox-statistics t
761 "Non-nil means, update checkbox statistics after insert and toggle.
762 When this is set, checkbox statistics is updated each time you either insert
763 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
764 with \\[org-ctrl-c-ctrl-c\\]."
765 :group 'org-plain-lists
766 :type 'boolean)
768 (defcustom org-description-max-indent 20
769 "Maximum indentation for the second line of a description list.
770 When the indentation would be larger than this, it will become
771 5 characters instead."
772 :group 'org-plain-lists
773 :type 'integer)
775 (defgroup org-imenu-and-speedbar nil
776 "Options concerning imenu and speedbar in Org-mode."
777 :tag "Org Imenu and Speedbar"
778 :group 'org-structure)
780 (defcustom org-imenu-depth 2
781 "The maximum level for Imenu access to Org-mode headlines.
782 This also applied for speedbar access."
783 :group 'org-imenu-and-speedbar
784 :type 'number)
786 (defgroup org-table nil
787 "Options concerning tables in Org-mode."
788 :tag "Org Table"
789 :group 'org)
791 (defcustom org-enable-table-editor 'optimized
792 "Non-nil means, lines starting with \"|\" are handled by the table editor.
793 When nil, such lines will be treated like ordinary lines.
795 When equal to the symbol `optimized', the table editor will be optimized to
796 do the following:
797 - Automatic overwrite mode in front of whitespace in table fields.
798 This makes the structure of the table stay in tact as long as the edited
799 field does not exceed the column width.
800 - Minimize the number of realigns. Normally, the table is aligned each time
801 TAB or RET are pressed to move to another field. With optimization this
802 happens only if changes to a field might have changed the column width.
803 Optimization requires replacing the functions `self-insert-command',
804 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
805 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
806 very good at guessing when a re-align will be necessary, but you can always
807 force one with \\[org-ctrl-c-ctrl-c].
809 If you would like to use the optimized version in Org-mode, but the
810 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
812 This variable can be used to turn on and off the table editor during a session,
813 but in order to toggle optimization, a restart is required.
815 See also the variable `org-table-auto-blank-field'."
816 :group 'org-table
817 :type '(choice
818 (const :tag "off" nil)
819 (const :tag "on" t)
820 (const :tag "on, optimized" optimized)))
822 (defcustom org-table-tab-recognizes-table.el t
823 "Non-nil means, TAB will automatically notice a table.el table.
824 When it sees such a table, it moves point into it and - if necessary -
825 calls `table-recognize-table'."
826 :group 'org-table-editing
827 :type 'boolean)
829 (defgroup org-link nil
830 "Options concerning links in Org-mode."
831 :tag "Org Link"
832 :group 'org)
834 (defvar org-link-abbrev-alist-local nil
835 "Buffer-local version of `org-link-abbrev-alist', which see.
836 The value of this is taken from the #+LINK lines.")
837 (make-variable-buffer-local 'org-link-abbrev-alist-local)
839 (defcustom org-link-abbrev-alist nil
840 "Alist of link abbreviations.
841 The car of each element is a string, to be replaced at the start of a link.
842 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
843 links in Org-mode buffers can have an optional tag after a double colon, e.g.
845 [[linkkey:tag][description]]
847 If REPLACE is a string, the tag will simply be appended to create the link.
848 If the string contains \"%s\", the tag will be inserted there.
850 REPLACE may also be a function that will be called with the tag as the
851 only argument to create the link, which should be returned as a string.
853 See the manual for examples."
854 :group 'org-link
855 :type 'alist)
857 (defcustom org-descriptive-links t
858 "Non-nil means, hide link part and only show description of bracket links.
859 Bracket links are like [[link][descritpion]]. This variable sets the initial
860 state in new org-mode buffers. The setting can then be toggled on a
861 per-buffer basis from the Org->Hyperlinks menu."
862 :group 'org-link
863 :type 'boolean)
865 (defcustom org-link-file-path-type 'adaptive
866 "How the path name in file links should be stored.
867 Valid values are:
869 relative Relative to the current directory, i.e. the directory of the file
870 into which the link is being inserted.
871 absolute Absolute path, if possible with ~ for home directory.
872 noabbrev Absolute path, no abbreviation of home directory.
873 adaptive Use relative path for files in the current directory and sub-
874 directories of it. For other files, use an absolute path."
875 :group 'org-link
876 :type '(choice
877 (const relative)
878 (const absolute)
879 (const noabbrev)
880 (const adaptive)))
882 (defcustom org-activate-links '(bracket angle plain radio tag date)
883 "Types of links that should be activated in Org-mode files.
884 This is a list of symbols, each leading to the activation of a certain link
885 type. In principle, it does not hurt to turn on most link types - there may
886 be a small gain when turning off unused link types. The types are:
888 bracket The recommended [[link][description]] or [[link]] links with hiding.
889 angular Links in angular brackes that may contain whitespace like
890 <bbdb:Carsten Dominik>.
891 plain Plain links in normal text, no whitespace, like http://google.com.
892 radio Text that is matched by a radio target, see manual for details.
893 tag Tag settings in a headline (link to tag search).
894 date Time stamps (link to calendar).
896 Changing this variable requires a restart of Emacs to become effective."
897 :group 'org-link
898 :type '(set (const :tag "Double bracket links (new style)" bracket)
899 (const :tag "Angular bracket links (old style)" angular)
900 (const :tag "Plain text links" plain)
901 (const :tag "Radio target matches" radio)
902 (const :tag "Tags" tag)
903 (const :tag "Timestamps" date)))
905 (defcustom org-make-link-description-function nil
906 "Function to use to generate link descriptions from links. If
907 nil the link location will be used. This function must take two
908 parameters; the first is the link and the second the description
909 org-insert-link has generated, and should return the description
910 to use."
911 :group 'org-link
912 :type 'function)
914 (defgroup org-link-store nil
915 "Options concerning storing links in Org-mode."
916 :tag "Org Store Link"
917 :group 'org-link)
919 (defcustom org-email-link-description-format "Email %c: %.30s"
920 "Format of the description part of a link to an email or usenet message.
921 The following %-excapes will be replaced by corresponding information:
923 %F full \"From\" field
924 %f name, taken from \"From\" field, address if no name
925 %T full \"To\" field
926 %t first name in \"To\" field, address if no name
927 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
928 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
929 %s subject
930 %m message-id.
932 You may use normal field width specification between the % and the letter.
933 This is for example useful to limit the length of the subject.
935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
936 :group 'org-link-store
937 :type 'string)
939 (defcustom org-from-is-user-regexp
940 (let (r1 r2)
941 (when (and user-mail-address (not (string= user-mail-address "")))
942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
943 (when (and user-full-name (not (string= user-full-name "")))
944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
946 "Regexp mached against the \"From:\" header of an email or usenet message.
947 It should match if the message is from the user him/herself."
948 :group 'org-link-store
949 :type 'regexp)
951 (defcustom org-context-in-file-links t
952 "Non-nil means, file links from `org-store-link' contain context.
953 A search string will be added to the file name with :: as separator and
954 used to find the context when the link is activated by the command
955 `org-open-at-point'.
956 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
957 negates this setting for the duration of the command."
958 :group 'org-link-store
959 :type 'boolean)
961 (defcustom org-keep-stored-link-after-insertion nil
962 "Non-nil means, keep link in list for entire session.
964 The command `org-store-link' adds a link pointing to the current
965 location to an internal list. These links accumulate during a session.
966 The command `org-insert-link' can be used to insert links into any
967 Org-mode file (offering completion for all stored links). When this
968 option is nil, every link which has been inserted once using \\[org-insert-link]
969 will be removed from the list, to make completing the unused links
970 more efficient."
971 :group 'org-link-store
972 :type 'boolean)
974 (defgroup org-link-follow nil
975 "Options concerning following links in Org-mode."
976 :tag "Org Follow Link"
977 :group 'org-link)
979 (defcustom org-follow-link-hook nil
980 "Hook that is run after a link has been followed."
981 :group 'org-link-follow
982 :type 'hook)
984 (defcustom org-tab-follows-link nil
985 "Non-nil means, on links TAB will follow the link.
986 Needs to be set before org.el is loaded."
987 :group 'org-link-follow
988 :type 'boolean)
990 (defcustom org-return-follows-link nil
991 "Non-nil means, on links RET will follow the link.
992 Needs to be set before org.el is loaded."
993 :group 'org-link-follow
994 :type 'boolean)
996 (defcustom org-mouse-1-follows-link
997 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
998 "Non-nil means, mouse-1 on a link will follow the link.
999 A longer mouse click will still set point. Does not work on XEmacs.
1000 Needs to be set before org.el is loaded."
1001 :group 'org-link-follow
1002 :type 'boolean)
1004 (defcustom org-mark-ring-length 4
1005 "Number of different positions to be recorded in the ring
1006 Changing this requires a restart of Emacs to work correctly."
1007 :group 'org-link-follow
1008 :type 'interger)
1010 (defcustom org-link-frame-setup
1011 '((vm . vm-visit-folder-other-frame)
1012 (gnus . gnus-other-frame)
1013 (file . find-file-other-window))
1014 "Setup the frame configuration for following links.
1015 When following a link with Emacs, it may often be useful to display
1016 this link in another window or frame. This variable can be used to
1017 set this up for the different types of links.
1018 For VM, use any of
1019 `vm-visit-folder'
1020 `vm-visit-folder-other-frame'
1021 For Gnus, use any of
1022 `gnus'
1023 `gnus-other-frame'
1024 For FILE, use any of
1025 `find-file'
1026 `find-file-other-window'
1027 `find-file-other-frame'
1028 For the calendar, use the variable `calendar-setup'.
1029 For BBDB, it is currently only possible to display the matches in
1030 another window."
1031 :group 'org-link-follow
1032 :type '(list
1033 (cons (const vm)
1034 (choice
1035 (const vm-visit-folder)
1036 (const vm-visit-folder-other-window)
1037 (const vm-visit-folder-other-frame)))
1038 (cons (const gnus)
1039 (choice
1040 (const gnus)
1041 (const gnus-other-frame)))
1042 (cons (const file)
1043 (choice
1044 (const find-file)
1045 (const find-file-other-window)
1046 (const find-file-other-frame)))))
1048 (defcustom org-display-internal-link-with-indirect-buffer nil
1049 "Non-nil means, use indirect buffer to display infile links.
1050 Activating internal links (from one location in a file to another location
1051 in the same file) normally just jumps to the location. When the link is
1052 activated with a C-u prefix (or with mouse-3), the link is displayed in
1053 another window. When this option is set, the other window actually displays
1054 an indirect buffer clone of the current buffer, to avoid any visibility
1055 changes to the current buffer."
1056 :group 'org-link-follow
1057 :type 'boolean)
1059 (defcustom org-open-non-existing-files nil
1060 "Non-nil means, `org-open-file' will open non-existing files.
1061 When nil, an error will be generated."
1062 :group 'org-link-follow
1063 :type 'boolean)
1065 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1066 "Function and arguments to call for following mailto links.
1067 This is a list with the first element being a lisp function, and the
1068 remaining elements being arguments to the function. In string arguments,
1069 %a will be replaced by the address, and %s will be replaced by the subject
1070 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1071 :group 'org-link-follow
1072 :type '(choice
1073 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1074 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1075 (const :tag "message-mail" (message-mail "%a" "%s"))
1076 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1078 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1079 "Non-nil means, ask for confirmation before executing shell links.
1080 Shell links can be dangerous: just think about a link
1082 [[shell:rm -rf ~/*][Google Search]]
1084 This link would show up in your Org-mode document as \"Google Search\",
1085 but really it would remove your entire home directory.
1086 Therefore we advise against setting this variable to nil.
1087 Just change it to `y-or-n-p' of you want to confirm with a
1088 single keystroke rather than having to type \"yes\"."
1089 :group 'org-link-follow
1090 :type '(choice
1091 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1092 (const :tag "with y-or-n (faster)" y-or-n-p)
1093 (const :tag "no confirmation (dangerous)" nil)))
1095 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1096 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1097 Elisp links can be dangerous: just think about a link
1099 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1101 This link would show up in your Org-mode document as \"Google Search\",
1102 but really it would remove your entire home directory.
1103 Therefore we advise against setting this variable to nil.
1104 Just change it to `y-or-n-p' of you want to confirm with a
1105 single keystroke rather than having to type \"yes\"."
1106 :group 'org-link-follow
1107 :type '(choice
1108 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1109 (const :tag "with y-or-n (faster)" y-or-n-p)
1110 (const :tag "no confirmation (dangerous)" nil)))
1112 (defconst org-file-apps-defaults-gnu
1113 '((remote . emacs)
1114 (t . mailcap))
1115 "Default file applications on a UNIX or GNU/Linux system.
1116 See `org-file-apps'.")
1118 (defconst org-file-apps-defaults-macosx
1119 '((remote . emacs)
1120 (t . "open %s")
1121 ("ps" . "gv %s")
1122 ("ps.gz" . "gv %s")
1123 ("eps" . "gv %s")
1124 ("eps.gz" . "gv %s")
1125 ("dvi" . "xdvi %s")
1126 ("fig" . "xfig %s"))
1127 "Default file applications on a MacOS X system.
1128 The system \"open\" is known as a default, but we use X11 applications
1129 for some files for which the OS does not have a good default.
1130 See `org-file-apps'.")
1132 (defconst org-file-apps-defaults-windowsnt
1133 (list
1134 '(remote . emacs)
1135 (cons t
1136 (list (if (featurep 'xemacs)
1137 'mswindows-shell-execute
1138 'w32-shell-execute)
1139 "open" 'file)))
1140 "Default file applications on a Windows NT system.
1141 The system \"open\" is used for most files.
1142 See `org-file-apps'.")
1144 (defcustom org-file-apps
1146 ("txt" . emacs)
1147 ("tex" . emacs)
1148 ("ltx" . emacs)
1149 ("org" . emacs)
1150 ("el" . emacs)
1151 ("bib" . emacs)
1153 "External applications for opening `file:path' items in a document.
1154 Org-mode uses system defaults for different file types, but
1155 you can use this variable to set the application for a given file
1156 extension. The entries in this list are cons cells where the car identifies
1157 files and the cdr the corresponding command. Possible values for the
1158 file identifier are
1159 \"ext\" A string identifying an extension
1160 `directory' Matches a directory
1161 `remote' Matches a remote file, accessible through tramp or efs.
1162 Remote files most likely should be visited through Emacs
1163 because external applications cannot handle such paths.
1164 t Default for all remaining files
1166 Possible values for the command are:
1167 `emacs' The file will be visited by the current Emacs process.
1168 `default' Use the default application for this file type.
1169 string A command to be executed by a shell; %s will be replaced
1170 by the path to the file.
1171 sexp A Lisp form which will be evaluated. The file path will
1172 be available in the Lisp variable `file'.
1173 For more examples, see the system specific constants
1174 `org-file-apps-defaults-macosx'
1175 `org-file-apps-defaults-windowsnt'
1176 `org-file-apps-defaults-gnu'."
1177 :group 'org-link-follow
1178 :type '(repeat
1179 (cons (choice :value ""
1180 (string :tag "Extension")
1181 (const :tag "Default for unrecognized files" t)
1182 (const :tag "Remote file" remote)
1183 (const :tag "Links to a directory" directory))
1184 (choice :value ""
1185 (const :tag "Visit with Emacs" emacs)
1186 (const :tag "Use system default" default)
1187 (string :tag "Command")
1188 (sexp :tag "Lisp form")))))
1190 (defgroup org-refile nil
1191 "Options concerning refiling entries in Org-mode."
1192 :tag "Org Remember"
1193 :group 'org)
1195 (defcustom org-directory "~/org"
1196 "Directory with org files.
1197 This directory will be used as default to prompt for org files.
1198 Used by the hooks for remember.el."
1199 :group 'org-refile
1200 :group 'org-remember
1201 :type 'directory)
1203 (defcustom org-default-notes-file "~/.notes"
1204 "Default target for storing notes.
1205 Used by the hooks for remember.el. This can be a string, or nil to mean
1206 the value of `remember-data-file'.
1207 You can set this on a per-template basis with the variable
1208 `org-remember-templates'."
1209 :group 'org-refile
1210 :group 'org-remember
1211 :type '(choice
1212 (const :tag "Default from remember-data-file" nil)
1213 file))
1215 (defcustom org-goto-interface 'outline
1216 "The default interface to be used for `org-goto'.
1217 Allowed vaues are:
1218 outline The interface shows an outline of the relevant file
1219 and the correct heading is found by moving through
1220 the outline or by searching with incremental search.
1221 outline-path-completion Headlines in the current buffer are offered via
1222 completion."
1223 :group 'org-refile
1224 :type '(choice
1225 (const :tag "Outline" outline)
1226 (const :tag "Outline-path-completion" outline-path-completion)))
1228 (defcustom org-reverse-note-order nil
1229 "Non-nil means, store new notes at the beginning of a file or entry.
1230 When nil, new notes will be filed to the end of a file or entry.
1231 This can also be a list with cons cells of regular expressions that
1232 are matched against file names, and values."
1233 :group 'org-remember
1234 :type '(choice
1235 (const :tag "Reverse always" t)
1236 (const :tag "Reverse never" nil)
1237 (repeat :tag "By file name regexp"
1238 (cons regexp boolean))))
1240 (defcustom org-refile-targets nil
1241 "Targets for refiling entries with \\[org-refile].
1242 This is list of cons cells. Each cell contains:
1243 - a specification of the files to be considered, either a list of files,
1244 or a symbol whose function or variable value will be used to retrieve
1245 a file name or a list of file names. Nil means, refile to a different
1246 heading in the current buffer.
1247 - A specification of how to find candidate refile targets. This may be
1248 any of
1249 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1250 This tag has to be present in all target headlines, inheritance will
1251 not be considered.
1252 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1253 todo keyword.
1254 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1255 headlines that are refiling targets.
1256 - a cons cell (:level . N). Any headline of level N is considered a target.
1257 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1258 :group 'org-remember
1259 :type '(repeat
1260 (cons
1261 (choice :value org-agenda-files
1262 (const :tag "All agenda files" org-agenda-files)
1263 (const :tag "Current buffer" nil)
1264 (function) (variable) (file))
1265 (choice :tag "Identify target headline by"
1266 (cons :tag "Specific tag" (const :tag) (string))
1267 (cons :tag "TODO keyword" (const :todo) (string))
1268 (cons :tag "Regular expression" (const :regexp) (regexp))
1269 (cons :tag "Level number" (const :level) (integer))
1270 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1272 (defcustom org-refile-use-outline-path nil
1273 "Non-nil means, provide refile targets as paths.
1274 So a level 3 headline will be available as level1/level2/level3.
1275 When the value is `file', also include the file name (without directory)
1276 into the path. When `full-file-path', include the full file path."
1277 :group 'org-remember
1278 :type '(choice
1279 (const :tag "Not" nil)
1280 (const :tag "Yes" t)
1281 (const :tag "Start with file name" file)
1282 (const :tag "Start with full file path" full-file-path)))
1284 (defgroup org-todo nil
1285 "Options concerning TODO items in Org-mode."
1286 :tag "Org TODO"
1287 :group 'org)
1289 (defgroup org-progress nil
1290 "Options concerning Progress logging in Org-mode."
1291 :tag "Org Progress"
1292 :group 'org-time)
1294 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1295 "List of TODO entry keyword sequences and their interpretation.
1296 \\<org-mode-map>This is a list of sequences.
1298 Each sequence starts with a symbol, either `sequence' or `type',
1299 indicating if the keywords should be interpreted as a sequence of
1300 action steps, or as different types of TODO items. The first
1301 keywords are states requiring action - these states will select a headline
1302 for inclusion into the global TODO list Org-mode produces. If one of
1303 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1304 signify that no further action is necessary. If \"|\" is not found,
1305 the last keyword is treated as the only DONE state of the sequence.
1307 The command \\[org-todo] cycles an entry through these states, and one
1308 additional state where no keyword is present. For details about this
1309 cycling, see the manual.
1311 TODO keywords and interpretation can also be set on a per-file basis with
1312 the special #+SEQ_TODO and #+TYP_TODO lines.
1314 Each keyword can optionally specify a character for fast state selection
1315 \(in combination with the variable `org-use-fast-todo-selection')
1316 and specifiers for state change logging, using the same syntax
1317 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1318 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1319 indicates to record a time stamp each time this state is selected.
1321 Each keyword may also specify if a timestamp or a note should be
1322 recorded when entering or leaving the state, by adding additional
1323 characters in the parenthesis after the keyword. This looks like this:
1324 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1325 record only the time of the state change. With X and Y being either
1326 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1327 Y when leaving the state if and only if the *target* state does not
1328 define X. You may omit any of the fast-selection key or X or /Y,
1329 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1331 For backward compatibility, this variable may also be just a list
1332 of keywords - in this case the interptetation (sequence or type) will be
1333 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1334 :group 'org-todo
1335 :group 'org-keywords
1336 :type '(choice
1337 (repeat :tag "Old syntax, just keywords"
1338 (string :tag "Keyword"))
1339 (repeat :tag "New syntax"
1340 (cons
1341 (choice
1342 :tag "Interpretation"
1343 (const :tag "Sequence (cycling hits every state)" sequence)
1344 (const :tag "Type (cycling directly to DONE)" type))
1345 (repeat
1346 (string :tag "Keyword"))))))
1348 (defvar org-todo-keywords-1 nil
1349 "All TODO and DONE keywords active in a buffer.")
1350 (make-variable-buffer-local 'org-todo-keywords-1)
1351 (defvar org-todo-keywords-for-agenda nil)
1352 (defvar org-done-keywords-for-agenda nil)
1353 (defvar org-agenda-contributing-files nil)
1354 (defvar org-not-done-keywords nil)
1355 (make-variable-buffer-local 'org-not-done-keywords)
1356 (defvar org-done-keywords nil)
1357 (make-variable-buffer-local 'org-done-keywords)
1358 (defvar org-todo-heads nil)
1359 (make-variable-buffer-local 'org-todo-heads)
1360 (defvar org-todo-sets nil)
1361 (make-variable-buffer-local 'org-todo-sets)
1362 (defvar org-todo-log-states nil)
1363 (make-variable-buffer-local 'org-todo-log-states)
1364 (defvar org-todo-kwd-alist nil)
1365 (make-variable-buffer-local 'org-todo-kwd-alist)
1366 (defvar org-todo-key-alist nil)
1367 (make-variable-buffer-local 'org-todo-key-alist)
1368 (defvar org-todo-key-trigger nil)
1369 (make-variable-buffer-local 'org-todo-key-trigger)
1371 (defcustom org-todo-interpretation 'sequence
1372 "Controls how TODO keywords are interpreted.
1373 This variable is in principle obsolete and is only used for
1374 backward compatibility, if the interpretation of todo keywords is
1375 not given already in `org-todo-keywords'. See that variable for
1376 more information."
1377 :group 'org-todo
1378 :group 'org-keywords
1379 :type '(choice (const sequence)
1380 (const type)))
1382 (defcustom org-use-fast-todo-selection 'prefix
1383 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1384 This variable describes if and under what circumstances the cycling
1385 mechanism for TODO keywords will be replaced by a single-key, direct
1386 selection scheme.
1388 When nil, fast selection is never used.
1390 When the symbol `prefix', it will be used when `org-todo' is called with
1391 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1392 in an agenda buffer.
1394 When t, fast selection is used by default. In this case, the prefix
1395 argument forces cycling instead.
1397 In all cases, the special interface is only used if access keys have actually
1398 been assigned by the user, i.e. if keywords in the configuration are followed
1399 by a letter in parenthesis, like TODO(t)."
1400 :group 'org-todo
1401 :type '(choice
1402 (const :tag "Never" nil)
1403 (const :tag "By default" t)
1404 (const :tag "Only with C-u C-c C-t" prefix)))
1406 (defcustom org-provide-todo-statistics t
1407 "Non-nil means, update todo statistics after insert and toggle.
1408 When this is set, todo statistics is updated in the parent of the current
1409 entry each time a todo state is changed."
1410 :group 'org-todo
1411 :type 'boolean)
1413 (defcustom org-after-todo-state-change-hook nil
1414 "Hook which is run after the state of a TODO item was changed.
1415 The new state (a string with a TODO keyword, or nil) is available in the
1416 Lisp variable `state'."
1417 :group 'org-todo
1418 :type 'hook)
1420 (defcustom org-log-done nil
1421 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1422 When equal to the list (done), also prompt for a closing note.
1423 This can also be configured on a per-file basis by adding one of
1424 the following lines anywhere in the buffer:
1426 #+STARTUP: logdone
1427 #+STARTUP: lognotedone
1428 #+STARTUP: nologdone"
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(choice
1432 (const :tag "No logging" nil)
1433 (const :tag "Record CLOSED timestamp" time)
1434 (const :tag "Record CLOSED timestamp with closing note." note)))
1436 ;; Normalize old uses of org-log-done.
1437 (cond
1438 ((eq org-log-done t) (setq org-log-done 'time))
1439 ((and (listp org-log-done) (memq 'done org-log-done))
1440 (setq org-log-done 'note)))
1442 (defcustom org-log-note-clock-out nil
1443 "Non-nil means, recored a note when clocking out of an item.
1444 This can also be configured on a per-file basis by adding one of
1445 the following lines anywhere in the buffer:
1447 #+STARTUP: lognoteclock-out
1448 #+STARTUP: nolognoteclock-out"
1449 :group 'org-todo
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-done-with-time t
1454 "Non-nil means, the CLOSED time stamp will contain date and time.
1455 When nil, only the date will be recorded."
1456 :group 'org-progress
1457 :type 'boolean)
1459 (defcustom org-log-note-headings
1460 '((done . "CLOSING NOTE %t")
1461 (state . "State %-12s %t")
1462 (note . "Note taken on %t")
1463 (clock-out . ""))
1464 "Headings for notes added to entries.
1465 The value is an alist, with the car being a symbol indicating the note
1466 context, and the cdr is the heading to be used. The heading may also be the
1467 empty string.
1468 %t in the heading will be replaced by a time stamp.
1469 %s will be replaced by the new TODO state, in double quotes.
1470 %u will be replaced by the user name.
1471 %U will be replaced by the full user name."
1472 :group 'org-todo
1473 :group 'org-progress
1474 :type '(list :greedy t
1475 (cons (const :tag "Heading when closing an item" done) string)
1476 (cons (const :tag
1477 "Heading when changing todo state (todo sequence only)"
1478 state) string)
1479 (cons (const :tag "Heading when just taking a note" note) string)
1480 (cons (const :tag "Heading when clocking out" clock-out) string)))
1482 (unless (assq 'note org-log-note-headings)
1483 (push '(note . "%t") org-log-note-headings))
1485 (defcustom org-log-states-order-reversed t
1486 "Non-nil means, the latest state change note will be directly after heading.
1487 When nil, the notes will be orderer according to time."
1488 :group 'org-todo
1489 :group 'org-progress
1490 :type 'boolean)
1492 (defcustom org-log-repeat 'time
1493 "Non-nil means, record moving through the DONE state when triggering repeat.
1494 An auto-repeating tasks is immediately switched back to TODO when marked
1495 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1496 the TODO keyword definition, or recording a closing note by setting
1497 `org-log-done', there will be no record of the task moving through DONE.
1498 This variable forces taking a note anyway. Possible values are:
1500 nil Don't force a record
1501 time Record a time stamp
1502 note Record a note
1504 This option can also be set with on a per-file-basis with
1506 #+STARTUP: logrepeat
1507 #+STARTUP: lognoterepeat
1508 #+STARTUP: nologrepeat
1510 You can have local logging settings for a subtree by setting the LOGGING
1511 property to one or more of these keywords."
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type '(choice
1515 (const :tag "Don't force a record" nil)
1516 (const :tag "Force recording the DONE state" time)
1517 (const :tag "Force recording a note with the DONE state" note)))
1520 (defgroup org-priorities nil
1521 "Priorities in Org-mode."
1522 :tag "Org Priorities"
1523 :group 'org-todo)
1525 (defcustom org-highest-priority ?A
1526 "The highest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a smaller ASCII number than `org-lowest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-lowest-priority ?C
1532 "The lowest priority of TODO items. A character like ?A, ?B etc.
1533 Must have a larger ASCII number than `org-highest-priority'."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-default-priority ?B
1538 "The default priority of TODO items.
1539 This is the priority an item get if no explicit priority is given."
1540 :group 'org-priorities
1541 :type 'character)
1543 (defcustom org-priority-start-cycle-with-default t
1544 "Non-nil means, start with default priority when starting to cycle.
1545 When this is nil, the first step in the cycle will be (depending on the
1546 command used) one higher or lower that the default priority."
1547 :group 'org-priorities
1548 :type 'boolean)
1550 (defgroup org-time nil
1551 "Options concerning time stamps and deadlines in Org-mode."
1552 :tag "Org Time"
1553 :group 'org)
1555 (defcustom org-insert-labeled-timestamps-at-point nil
1556 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1557 When nil, these labeled time stamps are forces into the second line of an
1558 entry, just after the headline. When scheduling from the global TODO list,
1559 the time stamp will always be forced into the second line."
1560 :group 'org-time
1561 :type 'boolean)
1563 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1564 "Formats for `format-time-string' which are used for time stamps.
1565 It is not recommended to change this constant.")
1567 (defcustom org-time-stamp-rounding-minutes '(0 5)
1568 "Number of minutes to round time stamps to.
1569 These are two values, the first applies when first creating a time stamp.
1570 The second applies when changing it with the commands `S-up' and `S-down'.
1571 When changing the time stamp, this means that it will change in steps
1572 of N minutes, as given by the second value.
1574 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1575 numbers should be factors of 60, so for example 5, 10, 15.
1577 When this is larger than 1, you can still force an exact time-stamp by using
1578 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1579 and by using a prefix arg to `S-up/down' to specify the exact number
1580 of minutes to shift."
1581 :group 'org-time
1582 :get '(lambda (var) ; Make sure all entries have 5 elements
1583 (if (integerp (default-value var))
1584 (list (default-value var) 5)
1585 (default-value var)))
1586 :type '(list
1587 (integer :tag "when inserting times")
1588 (integer :tag "when modifying times")))
1590 ;; Normalize old customizations of this variable.
1591 (when (integerp org-time-stamp-rounding-minutes)
1592 (setq org-time-stamp-rounding-minutes
1593 (list org-time-stamp-rounding-minutes
1594 org-time-stamp-rounding-minutes)))
1596 (defcustom org-display-custom-times nil
1597 "Non-nil means, overlay custom formats over all time stamps.
1598 The formats are defined through the variable `org-time-stamp-custom-formats'.
1599 To turn this on on a per-file basis, insert anywhere in the file:
1600 #+STARTUP: customtime"
1601 :group 'org-time
1602 :set 'set-default
1603 :type 'sexp)
1604 (make-variable-buffer-local 'org-display-custom-times)
1606 (defcustom org-time-stamp-custom-formats
1607 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1608 "Custom formats for time stamps. See `format-time-string' for the syntax.
1609 These are overlayed over the default ISO format if the variable
1610 `org-display-custom-times' is set. Time like %H:%M should be at the
1611 end of the second format."
1612 :group 'org-time
1613 :type 'sexp)
1615 (defun org-time-stamp-format (&optional long inactive)
1616 "Get the right format for a time string."
1617 (let ((f (if long (cdr org-time-stamp-formats)
1618 (car org-time-stamp-formats))))
1619 (if inactive
1620 (concat "[" (substring f 1 -1) "]")
1621 f)))
1623 (defcustom org-time-clocksum-format "%d:%02d"
1624 "The format string used when creating CLOCKSUM lines, or when
1625 org-mode generates a time duration."
1626 :group 'org-time
1627 :type 'string)
1629 (defcustom org-deadline-warning-days 14
1630 "No. of days before expiration during which a deadline becomes active.
1631 This variable governs the display in sparse trees and in the agenda.
1632 When 0 or negative, it means use this number (the absolute value of it)
1633 even if a deadline has a different individual lead time specified."
1634 :group 'org-time
1635 :group 'org-agenda-daily/weekly
1636 :type 'number)
1638 (defcustom org-read-date-prefer-future t
1639 "Non-nil means, assume future for incomplete date input from user.
1640 This affects the following situations:
1641 1. The user gives a day, but no month.
1642 For example, if today is the 15th, and you enter \"3\", Org-mode will
1643 read this as the third of *next* month. However, if you enter \"17\",
1644 it will be considered as *this* month.
1645 2. The user gives a month but not a year.
1646 For example, if it is april and you enter \"feb 2\", this will be read
1647 as feb 2, *next* year. \"May 5\", however, will be this year.
1649 Currently this does not work for ISO week specifications.
1651 When this option is nil, the current month and year will always be used
1652 as defaults."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-display-live t
1657 "Non-nil means, display current interpretation of date prompt live.
1658 This display will be in an overlay, in the minibuffer."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defcustom org-read-date-popup-calendar t
1663 "Non-nil means, pop up a calendar when prompting for a date.
1664 In the calendar, the date can be selected with mouse-1. However, the
1665 minibuffer will also be active, and you can simply enter the date as well.
1666 When nil, only the minibuffer will be available."
1667 :group 'org-time
1668 :type 'boolean)
1669 (if (fboundp 'defvaralias)
1670 (defvaralias 'org-popup-calendar-for-date-prompt
1671 'org-read-date-popup-calendar))
1673 (defcustom org-extend-today-until 0
1674 "The hour when your day really ends.
1675 This has influence for the following applications:
1676 - When switching the agenda to \"today\". It it is still earlier than
1677 the time given here, the day recognized as TODAY is actually yesterday.
1678 - When a date is read from the user and it is still before the time given
1679 here, the current date and time will be assumed to be yesterday, 23:59.
1681 FIXME:
1682 IMPORTANT: This is still a very experimental feature, it may disappear
1683 again or it may be extended to mean more things."
1684 :group 'org-time
1685 :type 'number)
1687 (defcustom org-edit-timestamp-down-means-later nil
1688 "Non-nil means, S-down will increase the time in a time stamp.
1689 When nil, S-up will increase."
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-calendar-follow-timestamp-change t
1694 "Non-nil means, make the calendar window follow timestamp changes.
1695 When a timestamp is modified and the calendar window is visible, it will be
1696 moved to the new date."
1697 :group 'org-time
1698 :type 'boolean)
1700 (defgroup org-tags nil
1701 "Options concerning tags in Org-mode."
1702 :tag "Org Tags"
1703 :group 'org)
1705 (defcustom org-tag-alist nil
1706 "List of tags allowed in Org-mode files.
1707 When this list is nil, Org-mode will base TAG input on what is already in the
1708 buffer.
1709 The value of this variable is an alist, the car of each entry must be a
1710 keyword as a string, the cdr may be a character that is used to select
1711 that tag through the fast-tag-selection interface.
1712 See the manual for details."
1713 :group 'org-tags
1714 :type '(repeat
1715 (choice
1716 (cons (string :tag "Tag name")
1717 (character :tag "Access char"))
1718 (const :tag "Start radio group" (:startgroup))
1719 (const :tag "End radio group" (:endgroup)))))
1721 (defvar org-file-tags nil
1722 "List of tags that can be inherited by all entries in the file.
1723 The tags will be inherited if the variable `org-use-tag-inheritance'
1724 says they should be.
1725 This variable is populated from #+TAG lines.")
1727 (defcustom org-use-fast-tag-selection 'auto
1728 "Non-nil means, use fast tag selection scheme.
1729 This is a special interface to select and deselect tags with single keys.
1730 When nil, fast selection is never used.
1731 When the symbol `auto', fast selection is used if and only if selection
1732 characters for tags have been configured, either through the variable
1733 `org-tag-alist' or through a #+TAGS line in the buffer.
1734 When t, fast selection is always used and selection keys are assigned
1735 automatically if necessary."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Always" t)
1739 (const :tag "Never" nil)
1740 (const :tag "When selection characters are configured" 'auto)))
1742 (defcustom org-fast-tag-selection-single-key nil
1743 "Non-nil means, fast tag selection exits after first change.
1744 When nil, you have to press RET to exit it.
1745 During fast tag selection, you can toggle this flag with `C-c'.
1746 This variable can also have the value `expert'. In this case, the window
1747 displaying the tags menu is not even shown, until you press C-c again."
1748 :group 'org-tags
1749 :type '(choice
1750 (const :tag "No" nil)
1751 (const :tag "Yes" t)
1752 (const :tag "Expert" expert)))
1754 (defvar org-fast-tag-selection-include-todo nil
1755 "Non-nil means, fast tags selection interface will also offer TODO states.
1756 This is an undocumented feature, you should not rely on it.")
1758 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1759 "The column to which tags should be indented in a headline.
1760 If this number is positive, it specifies the column. If it is negative,
1761 it means that the tags should be flushright to that column. For example,
1762 -80 works well for a normal 80 character screen."
1763 :group 'org-tags
1764 :type 'integer)
1766 (defcustom org-auto-align-tags t
1767 "Non-nil means, realign tags after pro/demotion of TODO state change.
1768 These operations change the length of a headline and therefore shift
1769 the tags around. With this options turned on, after each such operation
1770 the tags are again aligned to `org-tags-column'."
1771 :group 'org-tags
1772 :type 'boolean)
1774 (defcustom org-use-tag-inheritance t
1775 "Non-nil means, tags in levels apply also for sublevels.
1776 When nil, only the tags directly given in a specific line apply there.
1777 If this option is t, a match early-on in a tree can lead to a large
1778 number of matches in the subtree. If you only want to see the first
1779 match in a tree during a search, check out the variable
1780 `org-tags-match-list-sublevels'.
1782 This may also be a list of tags that should be inherited, or a regexp that
1783 matches tags that should be inherited."
1784 :group 'org-tags
1785 :type '(choice
1786 (const :tag "Not" nil)
1787 (const :tag "Always" t)
1788 (repeat :tag "Specific tags" (string :tag "Tag"))
1789 (regexp :tag "Tags matched by regexp")))
1791 (defun org-tag-inherit-p (tag)
1792 "Check if TAG is one that should be inherited."
1793 (cond
1794 ((eq org-use-tag-inheritance t) t)
1795 ((not org-use-tag-inheritance) nil)
1796 ((stringp org-use-tag-inheritance)
1797 (string-match org-use-tag-inheritance tag))
1798 ((listp org-use-tag-inheritance)
1799 (member tag org-use-tag-inheritance))
1800 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1802 (defcustom org-tags-match-list-sublevels t
1803 "Non-nil means list also sublevels of headlines matching tag search.
1804 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1805 the sublevels of a headline matching a tag search often also match
1806 the same search. Listing all of them can create very long lists.
1807 Setting this variable to nil causes subtrees of a match to be skipped.
1808 This option is off by default, because inheritance in on. If you turn
1809 inheritance off, you very likely want to turn this option on.
1811 As a special case, if the tag search is restricted to TODO items, the
1812 value of this variable is ignored and sublevels are always checked, to
1813 make sure all corresponding TODO items find their way into the list."
1814 :group 'org-tags
1815 :type 'boolean)
1817 (defvar org-tags-history nil
1818 "History of minibuffer reads for tags.")
1819 (defvar org-last-tags-completion-table nil
1820 "The last used completion table for tags.")
1821 (defvar org-after-tags-change-hook nil
1822 "Hook that is run after the tags in a line have changed.")
1824 (defgroup org-properties nil
1825 "Options concerning properties in Org-mode."
1826 :tag "Org Properties"
1827 :group 'org)
1829 (defcustom org-property-format "%-10s %s"
1830 "How property key/value pairs should be formatted by `indent-line'.
1831 When `indent-line' hits a property definition, it will format the line
1832 according to this format, mainly to make sure that the values are
1833 lined-up with respect to each other."
1834 :group 'org-properties
1835 :type 'string)
1837 (defcustom org-use-property-inheritance nil
1838 "Non-nil means, properties apply also for sublevels.
1840 This setting is chiefly used during property searches. Turning it on can
1841 cause significant overhead when doing a search, which is why it is not
1842 on by default.
1844 When nil, only the properties directly given in the current entry count.
1845 When t, every property is inherited. The value may also be a list of
1846 properties that should have inheritance, or a regular expression matching
1847 properties that should be inherited.
1849 However, note that some special properties use inheritance under special
1850 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1851 and the properties ending in \"_ALL\" when they are used as descriptor
1852 for valid values of a property.
1854 Note for programmers:
1855 When querying an entry with `org-entry-get', you can control if inheritance
1856 should be used. By default, `org-entry-get' looks only at the local
1857 properties. You can request inheritance by setting the inherit argument
1858 to t (to force inheritance) or to `selective' (to respect the setting
1859 in this variable)."
1860 :group 'org-properties
1861 :type '(choice
1862 (const :tag "Not" nil)
1863 (const :tag "Always" t)
1864 (repeat :tag "Specific properties" (string :tag "Property"))
1865 (regexp :tag "Properties matched by regexp")))
1867 (defun org-property-inherit-p (property)
1868 "Check if PROPERTY is one that should be inherited."
1869 (cond
1870 ((eq org-use-property-inheritance t) t)
1871 ((not org-use-property-inheritance) nil)
1872 ((stringp org-use-property-inheritance)
1873 (string-match org-use-property-inheritance property))
1874 ((listp org-use-property-inheritance)
1875 (member property org-use-property-inheritance))
1876 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1878 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1879 "The default column format, if no other format has been defined.
1880 This variable can be set on the per-file basis by inserting a line
1882 #+COLUMNS: %25ITEM ....."
1883 :group 'org-properties
1884 :type 'string)
1886 (defcustom org-columns-ellipses ".."
1887 "The ellipses to be used when a field in column view is truncated.
1888 When this is the empty string, as many characters as possible are shown,
1889 but then there will be no visual indication that the field has been truncated.
1890 When this is a string of length N, the last N characters of a truncated
1891 field are replaced by this string. If the column is narrower than the
1892 ellipses string, only part of the ellipses string will be shown."
1893 :group 'org-properties
1894 :type 'string)
1897 (defcustom org-effort-property "Effort"
1898 "The property that is being used to keep track of effort estimates.
1899 Effort estimates given in this property need to have the format H:MM."
1900 :group 'org-properties
1901 :group 'org-progress
1902 :type '(string :tag "Property"))
1904 (defconst org-global-properties-fixed
1905 '(("VISIBILITY_ALL" . "folded children content all"))
1906 "List of property/value pairs that can be inherited by any entry.
1907 These are fixed values, for the preset properties.")
1910 (defcustom org-global-properties nil
1911 "List of property/value pairs that can be inherited by any entry.
1912 You can set buffer-local values for this by adding lines like
1914 #+PROPERTY: NAME VALUE"
1915 :group 'org-properties
1916 :type '(repeat
1917 (cons (string :tag "Property")
1918 (string :tag "Value"))))
1920 (defvar org-file-properties nil
1921 "List of property/value pairs that can be inherited by any entry.
1922 Valid for the current buffer.
1923 This variable is populated from #+PROPERTY lines.")
1924 (make-variable-buffer-local 'org-file-properties)
1926 (defgroup org-agenda nil
1927 "Options concerning agenda views in Org-mode."
1928 :tag "Org Agenda"
1929 :group 'org)
1931 (defvar org-category nil
1932 "Variable used by org files to set a category for agenda display.
1933 Such files should use a file variable to set it, for example
1935 # -*- mode: org; org-category: \"ELisp\"
1937 or contain a special line
1939 #+CATEGORY: ELisp
1941 If the file does not specify a category, then file's base name
1942 is used instead.")
1943 (make-variable-buffer-local 'org-category)
1945 (defcustom org-agenda-files nil
1946 "The files to be used for agenda display.
1947 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1948 \\[org-remove-file]. You can also use customize to edit the list.
1950 If an entry is a directory, all files in that directory that are matched by
1951 `org-agenda-file-regexp' will be part of the file list.
1953 If the value of the variable is not a list but a single file name, then
1954 the list of agenda files is actually stored and maintained in that file, one
1955 agenda file per line."
1956 :group 'org-agenda
1957 :type '(choice
1958 (repeat :tag "List of files and directories" file)
1959 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1961 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1962 "Regular expression to match files for `org-agenda-files'.
1963 If any element in the list in that variable contains a directory instead
1964 of a normal file, all files in that directory that are matched by this
1965 regular expression will be included."
1966 :group 'org-agenda
1967 :type 'regexp)
1969 (defcustom org-agenda-text-search-extra-files nil
1970 "List of extra files to be searched by text search commands.
1971 These files will be search in addition to the agenda files by the
1972 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1973 Note that these files will only be searched for text search commands,
1974 not for the other agenda views like todo lists, tag searches or the weekly
1975 agenda. This variable is intended to list notes and possibly archive files
1976 that should also be searched by these two commands.
1977 In fact, if the first element in the list is the symbol `agenda-archives',
1978 than all archive files of all agenda files will be added to the search
1979 scope."
1980 :group 'org-agenda
1981 :type '(set :greedy t
1982 (const :tag "Agenda Archives" agenda-archives)
1983 (repeat :inline t (file))))
1985 (if (fboundp 'defvaralias)
1986 (defvaralias 'org-agenda-multi-occur-extra-files
1987 'org-agenda-text-search-extra-files))
1989 (defcustom org-agenda-skip-unavailable-files nil
1990 "t means to just skip non-reachable files in `org-agenda-files'.
1991 Nil means to remove them, after a query, from the list."
1992 :group 'org-agenda
1993 :type 'boolean)
1995 (defcustom org-calendar-to-agenda-key [?c]
1996 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1997 The command `org-calendar-goto-agenda' will be bound to this key. The
1998 default is the character `c' because then `c' can be used to switch back and
1999 forth between agenda and calendar."
2000 :group 'org-agenda
2001 :type 'sexp)
2003 (eval-after-load "calendar"
2004 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
2005 'org-calendar-goto-agenda))
2007 (defgroup org-latex nil
2008 "Options for embedding LaTeX code into Org-mode."
2009 :tag "Org LaTeX"
2010 :group 'org)
2012 (defcustom org-format-latex-options
2013 '(:foreground default :background default :scale 1.0
2014 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2015 :matchers ("begin" "$" "$$" "\\(" "\\["))
2016 "Options for creating images from LaTeX fragments.
2017 This is a property list with the following properties:
2018 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2019 `default' means use the foreground of the default face.
2020 :background the background color, or \"Transparent\".
2021 `default' means use the background of the default face.
2022 :scale a scaling factor for the size of the images.
2023 :html-foreground, :html-background, :html-scale
2024 the same numbers for HTML export.
2025 :matchers a list indicating which matchers should be used to
2026 find LaTeX fragments. Valid members of this list are:
2027 \"begin\" find environments
2028 \"$\" find math expressions surrounded by $...$
2029 \"$$\" find math expressions surrounded by $$....$$
2030 \"\\(\" find math expressions surrounded by \\(...\\)
2031 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2032 :group 'org-latex
2033 :type 'plist)
2035 (defcustom org-format-latex-header "\\documentclass{article}
2036 \\usepackage{fullpage} % do not remove
2037 \\usepackage{amssymb}
2038 \\usepackage[usenames]{color}
2039 \\usepackage{amsmath}
2040 \\usepackage{latexsym}
2041 \\usepackage[mathscr]{eucal}
2042 \\pagestyle{empty} % do not remove"
2043 "The document header used for processing LaTeX fragments."
2044 :group 'org-latex
2045 :type 'string)
2048 (defgroup org-font-lock nil
2049 "Font-lock settings for highlighting in Org-mode."
2050 :tag "Org Font Lock"
2051 :group 'org)
2053 (defcustom org-level-color-stars-only nil
2054 "Non-nil means fontify only the stars in each headline.
2055 When nil, the entire headline is fontified.
2056 Changing it requires restart of `font-lock-mode' to become effective
2057 also in regions already fontified."
2058 :group 'org-font-lock
2059 :type 'boolean)
2061 (defcustom org-hide-leading-stars nil
2062 "Non-nil means, hide the first N-1 stars in a headline.
2063 This works by using the face `org-hide' for these stars. This
2064 face is white for a light background, and black for a dark
2065 background. You may have to customize the face `org-hide' to
2066 make this work.
2067 Changing it requires restart of `font-lock-mode' to become effective
2068 also in regions already fontified.
2069 You may also set this on a per-file basis by adding one of the following
2070 lines to the buffer:
2072 #+STARTUP: hidestars
2073 #+STARTUP: showstars"
2074 :group 'org-font-lock
2075 :type 'boolean)
2077 (defcustom org-fontify-done-headline nil
2078 "Non-nil means, change the face of a headline if it is marked DONE.
2079 Normally, only the TODO/DONE keyword indicates the state of a headline.
2080 When this is non-nil, the headline after the keyword is set to the
2081 `org-headline-done' as an additional indication."
2082 :group 'org-font-lock
2083 :type 'boolean)
2085 (defcustom org-fontify-emphasized-text t
2086 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2087 Changing this variable requires a restart of Emacs to take effect."
2088 :group 'org-font-lock
2089 :type 'boolean)
2091 (defcustom org-highlight-latex-fragments-and-specials nil
2092 "Non-nil means, fontify what is treated specially by the exporters."
2093 :group 'org-font-lock
2094 :type 'boolean)
2096 (defcustom org-hide-emphasis-markers nil
2097 "Non-nil mean font-lock should hide the emphasis marker characters."
2098 :group 'org-font-lock
2099 :type 'boolean)
2101 (defvar org-emph-re nil
2102 "Regular expression for matching emphasis.")
2103 (defvar org-verbatim-re nil
2104 "Regular expression for matching verbatim text.")
2105 (defvar org-emphasis-regexp-components) ; defined just below
2106 (defvar org-emphasis-alist) ; defined just below
2107 (defun org-set-emph-re (var val)
2108 "Set variable and compute the emphasis regular expression."
2109 (set var val)
2110 (when (and (boundp 'org-emphasis-alist)
2111 (boundp 'org-emphasis-regexp-components)
2112 org-emphasis-alist org-emphasis-regexp-components)
2113 (let* ((e org-emphasis-regexp-components)
2114 (pre (car e))
2115 (post (nth 1 e))
2116 (border (nth 2 e))
2117 (body (nth 3 e))
2118 (nl (nth 4 e))
2119 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2120 (body1 (concat body "*?"))
2121 (markers (mapconcat 'car org-emphasis-alist ""))
2122 (vmarkers (mapconcat
2123 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2124 org-emphasis-alist "")))
2125 ;; make sure special characters appear at the right position in the class
2126 (if (string-match "\\^" markers)
2127 (setq markers (concat (replace-match "" t t markers) "^")))
2128 (if (string-match "-" markers)
2129 (setq markers (concat (replace-match "" t t markers) "-")))
2130 (if (string-match "\\^" vmarkers)
2131 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2132 (if (string-match "-" vmarkers)
2133 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2134 (if (> nl 0)
2135 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2136 (int-to-string nl) "\\}")))
2137 ;; Make the regexp
2138 (setq org-emph-re
2139 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2140 "\\("
2141 "\\([" markers "]\\)"
2142 "\\("
2143 "[^" border "]\\|"
2144 "[^" border (if (and nil stacked) markers) "]"
2145 body1
2146 "[^" border (if (and nil stacked) markers) "]"
2147 "\\)"
2148 "\\3\\)"
2149 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2150 (setq org-verbatim-re
2151 (concat "\\([" pre "]\\|^\\)"
2152 "\\("
2153 "\\([" vmarkers "]\\)"
2154 "\\("
2155 "[^" border "]\\|"
2156 "[^" border "]"
2157 body1
2158 "[^" border "]"
2159 "\\)"
2160 "\\3\\)"
2161 "\\([" post "]\\|$\\)")))))
2163 (defcustom org-emphasis-regexp-components
2164 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2165 "Components used to build the regular expression for emphasis.
2166 This is a list with 6 entries. Terminology: In an emphasis string
2167 like \" *strong word* \", we call the initial space PREMATCH, the final
2168 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2169 and \"trong wor\" is the body. The different components in this variable
2170 specify what is allowed/forbidden in each part:
2172 pre Chars allowed as prematch. Beginning of line will be allowed too.
2173 post Chars allowed as postmatch. End of line will be allowed too.
2174 border The chars *forbidden* as border characters.
2175 body-regexp A regexp like \".\" to match a body character. Don't use
2176 non-shy groups here, and don't allow newline here.
2177 newline The maximum number of newlines allowed in an emphasis exp.
2179 Use customize to modify this, or restart Emacs after changing it."
2180 :group 'org-font-lock
2181 :set 'org-set-emph-re
2182 :type '(list
2183 (sexp :tag "Allowed chars in pre ")
2184 (sexp :tag "Allowed chars in post ")
2185 (sexp :tag "Forbidden chars in border ")
2186 (sexp :tag "Regexp for body ")
2187 (integer :tag "number of newlines allowed")
2188 (option (boolean :tag "Please ignore this button"))))
2190 (defcustom org-emphasis-alist
2191 `(("*" bold "<b>" "</b>")
2192 ("/" italic "<i>" "</i>")
2193 ("_" underline "<u>" "</u>")
2194 ("=" org-code "<code>" "</code>" verbatim)
2195 ("~" org-verbatim "" "" verbatim)
2196 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2197 "<del>" "</del>")
2199 "Special syntax for emphasized text.
2200 Text starting and ending with a special character will be emphasized, for
2201 example *bold*, _underlined_ and /italic/. This variable sets the marker
2202 characters, the face to be used by font-lock for highlighting in Org-mode
2203 Emacs buffers, and the HTML tags to be used for this.
2204 Use customize to modify this, or restart Emacs after changing it."
2205 :group 'org-font-lock
2206 :set 'org-set-emph-re
2207 :type '(repeat
2208 (list
2209 (string :tag "Marker character")
2210 (choice
2211 (face :tag "Font-lock-face")
2212 (plist :tag "Face property list"))
2213 (string :tag "HTML start tag")
2214 (string :tag "HTML end tag")
2215 (option (const verbatim)))))
2217 ;;; Miscellaneous options
2219 (defgroup org-completion nil
2220 "Completion in Org-mode."
2221 :tag "Org Completion"
2222 :group 'org)
2224 (defcustom org-completion-fallback-command 'hippie-expand
2225 "The expansion command called by \\[org-complete] in normal context.
2226 Normal means, no org-mode-specific context."
2227 :group 'org-completion
2228 :type 'function)
2230 ;;; Functions and variables from ther packages
2231 ;; Declared here to avoid compiler warnings
2233 ;; XEmacs only
2234 (defvar outline-mode-menu-heading)
2235 (defvar outline-mode-menu-show)
2236 (defvar outline-mode-menu-hide)
2237 (defvar zmacs-regions) ; XEmacs regions
2239 ;; Emacs only
2240 (defvar mark-active)
2242 ;; Various packages
2243 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2244 (declare-function calendar-forward-day "cal-move" (arg))
2245 (declare-function calendar-goto-date "cal-move" (date))
2246 (declare-function calendar-goto-today "cal-move" ())
2247 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2248 (defvar calc-embedded-close-formula)
2249 (defvar calc-embedded-open-formula)
2250 (declare-function cdlatex-tab "ext:cdlatex" ())
2251 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2252 (defvar font-lock-unfontify-region-function)
2253 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2254 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2255 (defvar iswitchb-temp-buflist)
2256 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2257 (declare-function org-agenda-skip "org-agenda" ())
2258 (declare-function org-format-agenda-item "org-agenda"
2259 (extra txt &optional category tags dotime noprefix remove-re))
2260 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2261 (declare-function org-agenda-change-all-lines "org-agenda"
2262 (newhead hdmarker &optional fixface))
2263 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2264 (declare-function org-agenda-maybe-redo "org-agenda" ())
2265 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2266 (beg end))
2267 (declare-function parse-time-string "parse-time" (string))
2268 (declare-function remember "remember" (&optional initial))
2269 (declare-function remember-buffer-desc "remember" ())
2270 (declare-function remember-finalize "remember" ())
2271 (defvar remember-save-after-remembering)
2272 (defvar remember-data-file)
2273 (defvar remember-register)
2274 (defvar remember-buffer)
2275 (defvar remember-handler-functions)
2276 (defvar remember-annotation-functions)
2277 (defvar texmathp-why)
2278 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2279 (declare-function table--at-cell-p "table" (position &optional object at-column))
2281 (defvar w3m-current-url)
2282 (defvar w3m-current-title)
2284 (defvar org-latex-regexps)
2286 ;;; Autoload and prepare some org modules
2288 ;; Some table stuff that needs to be defined here, because it is used
2289 ;; by the functions setting up org-mode or checking for table context.
2291 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2292 "Detects an org-type or table-type table.")
2293 (defconst org-table-line-regexp "^[ \t]*|"
2294 "Detects an org-type table line.")
2295 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2296 "Detects an org-type table line.")
2297 (defconst org-table-hline-regexp "^[ \t]*|-"
2298 "Detects an org-type table hline.")
2299 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2300 "Detects a table-type table hline.")
2301 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2302 "Searching from within a table (any type) this finds the first line
2303 outside the table.")
2305 ;; Autoload the functions in org-table.el that are needed by functions here.
2307 (eval-and-compile
2308 (org-autoload "org-table"
2309 '(org-table-align org-table-begin org-table-blank-field
2310 org-table-convert org-table-convert-region org-table-copy-down
2311 org-table-copy-region org-table-create
2312 org-table-create-or-convert-from-region
2313 org-table-create-with-table.el org-table-current-dline
2314 org-table-cut-region org-table-delete-column org-table-edit-field
2315 org-table-edit-formulas org-table-end org-table-eval-formula
2316 org-table-export org-table-field-info
2317 org-table-get-stored-formulas org-table-goto-column
2318 org-table-hline-and-move org-table-import org-table-insert-column
2319 org-table-insert-hline org-table-insert-row org-table-iterate
2320 org-table-justify-field-maybe org-table-kill-row
2321 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2322 org-table-move-column org-table-move-column-left
2323 org-table-move-column-right org-table-move-row
2324 org-table-move-row-down org-table-move-row-up
2325 org-table-next-field org-table-next-row org-table-paste-rectangle
2326 org-table-previous-field org-table-recalculate
2327 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2328 org-table-toggle-coordinate-overlays
2329 org-table-toggle-formula-debugger org-table-wrap-region
2330 orgtbl-mode turn-on-orgtbl)))
2332 (defun org-at-table-p (&optional table-type)
2333 "Return t if the cursor is inside an org-type table.
2334 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2335 (if org-enable-table-editor
2336 (save-excursion
2337 (beginning-of-line 1)
2338 (looking-at (if table-type org-table-any-line-regexp
2339 org-table-line-regexp)))
2340 nil))
2341 (defsubst org-table-p () (org-at-table-p))
2343 (defun org-at-table.el-p ()
2344 "Return t if and only if we are at a table.el table."
2345 (and (org-at-table-p 'any)
2346 (save-excursion
2347 (goto-char (org-table-begin 'any))
2348 (looking-at org-table1-hline-regexp))))
2349 (defun org-table-recognize-table.el ()
2350 "If there is a table.el table nearby, recognize it and move into it."
2351 (if org-table-tab-recognizes-table.el
2352 (if (org-at-table.el-p)
2353 (progn
2354 (beginning-of-line 1)
2355 (if (looking-at org-table-dataline-regexp)
2357 (if (looking-at org-table1-hline-regexp)
2358 (progn
2359 (beginning-of-line 2)
2360 (if (looking-at org-table-any-border-regexp)
2361 (beginning-of-line -1)))))
2362 (if (re-search-forward "|" (org-table-end t) t)
2363 (progn
2364 (require 'table)
2365 (if (table--at-cell-p (point))
2367 (message "recognizing table.el table...")
2368 (table-recognize-table)
2369 (message "recognizing table.el table...done")))
2370 (error "This should not happen..."))
2372 nil)
2373 nil))
2375 (defun org-at-table-hline-p ()
2376 "Return t if the cursor is inside a hline in a table."
2377 (if org-enable-table-editor
2378 (save-excursion
2379 (beginning-of-line 1)
2380 (looking-at org-table-hline-regexp))
2381 nil))
2383 (defvar org-table-clean-did-remove-column nil)
2385 (defun org-table-map-tables (function)
2386 "Apply FUNCTION to the start of all tables in the buffer."
2387 (save-excursion
2388 (save-restriction
2389 (widen)
2390 (goto-char (point-min))
2391 (while (re-search-forward org-table-any-line-regexp nil t)
2392 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2393 (beginning-of-line 1)
2394 (if (looking-at org-table-line-regexp)
2395 (save-excursion (funcall function)))
2396 (re-search-forward org-table-any-border-regexp nil 1))))
2397 (message "Mapping tables: done"))
2399 ;; Declare and autoload functions from org-exp.el
2401 (declare-function org-default-export-plist "org-exp")
2402 (declare-function org-infile-export-plist "org-exp")
2403 (declare-function org-get-current-options "org-exp")
2404 (eval-and-compile
2405 (org-autoload "org-exp"
2406 '(org-export org-export-as-ascii org-export-visible
2407 org-insert-export-options-template org-export-as-html-and-open
2408 org-export-as-html-batch org-export-as-html-to-buffer
2409 org-replace-region-by-html org-export-region-as-html
2410 org-export-as-html org-export-icalendar-this-file
2411 org-export-icalendar-all-agenda-files
2412 org-table-clean-before-export
2413 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2415 ;; Declare and autoload functions from org-exp.el
2417 (eval-and-compile
2418 (org-autoload "org-exp"
2419 '(org-agenda org-agenda-list org-search-view
2420 org-todo-list org-tags-view org-agenda-list-stuck-projects
2421 org-diary org-agenda-to-appt)))
2423 ;; Autoload org-remember
2425 (eval-and-compile
2426 (org-autoload "org-remember"
2427 '(org-remember-insinuate org-remember-annotation
2428 org-remember-apply-template org-remember org-remember-handler)))
2430 ;; Autoload org-clock.el
2433 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2434 (beg end))
2435 (declare-function org-update-mode-line "org-clock" ())
2436 (defvar org-clock-start-time)
2437 (defvar org-clock-marker (make-marker)
2438 "Marker recording the last clock-in.")
2440 (eval-and-compile
2441 (org-autoload
2442 "org-clock"
2443 '(org-clock-in org-clock-out org-clock-cancel
2444 org-clock-goto org-clock-sum org-clock-display
2445 org-remove-clock-overlays org-clock-report
2446 org-clocktable-shift org-dblock-write:clocktable
2447 org-get-clocktable)))
2449 (defun org-clock-update-time-maybe ()
2450 "If this is a CLOCK line, update it and return t.
2451 Otherwise, return nil."
2452 (interactive)
2453 (save-excursion
2454 (beginning-of-line 1)
2455 (skip-chars-forward " \t")
2456 (when (looking-at org-clock-string)
2457 (let ((re (concat "[ \t]*" org-clock-string
2458 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2459 "\\([ \t]*=>.*\\)?\\)?"))
2460 ts te h m s)
2461 (cond
2462 ((not (looking-at re))
2463 nil)
2464 ((not (match-end 2))
2465 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2466 (> org-clock-marker (point))
2467 (<= org-clock-marker (point-at-eol)))
2468 ;; The clock is running here
2469 (setq org-clock-start-time
2470 (apply 'encode-time
2471 (org-parse-time-string (match-string 1))))
2472 (org-update-mode-line)))
2474 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2475 (end-of-line 1)
2476 (setq ts (match-string 1)
2477 te (match-string 3))
2478 (setq s (- (time-to-seconds
2479 (apply 'encode-time (org-parse-time-string te)))
2480 (time-to-seconds
2481 (apply 'encode-time (org-parse-time-string ts))))
2482 h (floor (/ s 3600))
2483 s (- s (* 3600 h))
2484 m (floor (/ s 60))
2485 s (- s (* 60 s)))
2486 (insert " => " (format "%2d:%02d" h m))
2487 t))))))
2489 (defun org-check-running-clock ()
2490 "Check if the current buffer contains the running clock.
2491 If yes, offer to stop it and to save the buffer with the changes."
2492 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2493 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2494 (buffer-name))))
2495 (org-clock-out)
2496 (when (y-or-n-p "Save changed buffer?")
2497 (save-buffer))))
2499 (defun org-clocktable-try-shift (dir n)
2500 "Check if this line starts a clock table, if yes, shift the time block."
2501 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2502 (org-clocktable-shift dir n)))
2504 ;; Autoload archiving code
2505 ;; The stuff that is needed for cycling and tags has to be defined here.
2507 (defgroup org-archive nil
2508 "Options concerning archiving in Org-mode."
2509 :tag "Org Archive"
2510 :group 'org-structure)
2512 (defcustom org-archive-location "%s_archive::"
2513 "The location where subtrees should be archived.
2515 Otherwise, the value of this variable is a string, consisting of two
2516 parts, separated by a double-colon.
2518 The first part is a file name - when omitted, archiving happens in the same
2519 file. %s will be replaced by the current file name (without directory part).
2520 Archiving to a different file is useful to keep archived entries from
2521 contributing to the Org-mode Agenda.
2523 The part after the double colon is a headline. The archived entries will be
2524 filed under that headline. When omitted, the subtrees are simply filed away
2525 at the end of the file, as top-level entries.
2527 Here are a few examples:
2528 \"%s_archive::\"
2529 If the current file is Projects.org, archive in file
2530 Projects.org_archive, as top-level trees. This is the default.
2532 \"::* Archived Tasks\"
2533 Archive in the current file, under the top-level headline
2534 \"* Archived Tasks\".
2536 \"~/org/archive.org::\"
2537 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2539 \"basement::** Finished Tasks\"
2540 Archive in file ./basement (relative path), as level 3 trees
2541 below the level 2 heading \"** Finished Tasks\".
2543 You may set this option on a per-file basis by adding to the buffer a
2544 line like
2546 #+ARCHIVE: basement::** Finished Tasks
2548 You may also define it locally for a subtree by setting an ARCHIVE property
2549 in the entry. If such a property is found in an entry, or anywhere up
2550 the hierarchy, it will be used."
2551 :group 'org-archive
2552 :type 'string)
2554 (defcustom org-archive-tag "ARCHIVE"
2555 "The tag that marks a subtree as archived.
2556 An archived subtree does not open during visibility cycling, and does
2557 not contribute to the agenda listings.
2558 After changing this, font-lock must be restarted in the relevant buffers to
2559 get the proper fontification."
2560 :group 'org-archive
2561 :group 'org-keywords
2562 :type 'string)
2564 (defcustom org-agenda-skip-archived-trees t
2565 "Non-nil means, the agenda will skip any items located in archived trees.
2566 An archived tree is a tree marked with the tag ARCHIVE."
2567 :group 'org-archive
2568 :group 'org-agenda-skip
2569 :type 'boolean)
2571 (defcustom org-cycle-open-archived-trees nil
2572 "Non-nil means, `org-cycle' will open archived trees.
2573 An archived tree is a tree marked with the tag ARCHIVE.
2574 When nil, archived trees will stay folded. You can still open them with
2575 normal outline commands like `show-all', but not with the cycling commands."
2576 :group 'org-archive
2577 :group 'org-cycle
2578 :type 'boolean)
2580 (defcustom org-sparse-tree-open-archived-trees nil
2581 "Non-nil means sparse tree construction shows matches in archived trees.
2582 When nil, matches in these trees are highlighted, but the trees are kept in
2583 collapsed state."
2584 :group 'org-archive
2585 :group 'org-sparse-trees
2586 :type 'boolean)
2588 (defun org-cycle-hide-archived-subtrees (state)
2589 "Re-hide all archived subtrees after a visibility state change."
2590 (when (and (not org-cycle-open-archived-trees)
2591 (not (memq state '(overview folded))))
2592 (save-excursion
2593 (let* ((globalp (memq state '(contents all)))
2594 (beg (if globalp (point-min) (point)))
2595 (end (if globalp (point-max) (org-end-of-subtree t))))
2596 (org-hide-archived-subtrees beg end)
2597 (goto-char beg)
2598 (if (looking-at (concat ".*:" org-archive-tag ":"))
2599 (message "%s" (substitute-command-keys
2600 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2602 (defun org-force-cycle-archived ()
2603 "Cycle subtree even if it is archived."
2604 (interactive)
2605 (setq this-command 'org-cycle)
2606 (let ((org-cycle-open-archived-trees t))
2607 (call-interactively 'org-cycle)))
2609 (defun org-hide-archived-subtrees (beg end)
2610 "Re-hide all archived subtrees after a visibility state change."
2611 (save-excursion
2612 (let* ((re (concat ":" org-archive-tag ":")))
2613 (goto-char beg)
2614 (while (re-search-forward re end t)
2615 (and (org-on-heading-p) (hide-subtree))
2616 (org-end-of-subtree t)))))
2618 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2620 (eval-and-compile
2621 (org-autoload "org-archive"
2622 '(org-add-archive-files org-archive-subtree
2623 org-archive-to-archive-sibling org-toggle-archive-tag)))
2625 ;; Autoload Column View Code
2627 (declare-function org-columns-number-to-string "org-colview")
2628 (declare-function org-columns-get-format-and-top-level "org-colview")
2629 (declare-function org-columns-compute "org-colview")
2631 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2632 '(org-columns-number-to-string org-columns-get-format-and-top-level
2633 org-columns-compute org-agenda-columns org-columns-remove-overlays
2634 org-columns org-insert-columns-dblock))
2636 ;; Autoload ID code
2638 (org-autoload "org-id"
2639 '(org-id-get-create org-id-new org-id-copy org-id-get
2640 org-id-get-with-outline-path-completion
2641 org-id-get-with-outline-drilling
2642 org-id-goto org-id-find))
2644 ;;; Variables for pre-computed regular expressions, all buffer local
2646 (defvar org-drawer-regexp nil
2647 "Matches first line of a hidden block.")
2648 (make-variable-buffer-local 'org-drawer-regexp)
2649 (defvar org-todo-regexp nil
2650 "Matches any of the TODO state keywords.")
2651 (make-variable-buffer-local 'org-todo-regexp)
2652 (defvar org-not-done-regexp nil
2653 "Matches any of the TODO state keywords except the last one.")
2654 (make-variable-buffer-local 'org-not-done-regexp)
2655 (defvar org-todo-line-regexp nil
2656 "Matches a headline and puts TODO state into group 2 if present.")
2657 (make-variable-buffer-local 'org-todo-line-regexp)
2658 (defvar org-complex-heading-regexp nil
2659 "Matches a headline and puts everything into groups:
2660 group 1: the stars
2661 group 2: The todo keyword, maybe
2662 group 3: Priority cookie
2663 group 4: True headline
2664 group 5: Tags")
2665 (make-variable-buffer-local 'org-complex-heading-regexp)
2666 (defvar org-todo-line-tags-regexp nil
2667 "Matches a headline and puts TODO state into group 2 if present.
2668 Also put tags into group 4 if tags are present.")
2669 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2670 (defvar org-nl-done-regexp nil
2671 "Matches newline followed by a headline with the DONE keyword.")
2672 (make-variable-buffer-local 'org-nl-done-regexp)
2673 (defvar org-looking-at-done-regexp nil
2674 "Matches the DONE keyword a point.")
2675 (make-variable-buffer-local 'org-looking-at-done-regexp)
2676 (defvar org-ds-keyword-length 12
2677 "Maximum length of the Deadline and SCHEDULED keywords.")
2678 (make-variable-buffer-local 'org-ds-keyword-length)
2679 (defvar org-deadline-regexp nil
2680 "Matches the DEADLINE keyword.")
2681 (make-variable-buffer-local 'org-deadline-regexp)
2682 (defvar org-deadline-time-regexp nil
2683 "Matches the DEADLINE keyword together with a time stamp.")
2684 (make-variable-buffer-local 'org-deadline-time-regexp)
2685 (defvar org-deadline-line-regexp nil
2686 "Matches the DEADLINE keyword and the rest of the line.")
2687 (make-variable-buffer-local 'org-deadline-line-regexp)
2688 (defvar org-scheduled-regexp nil
2689 "Matches the SCHEDULED keyword.")
2690 (make-variable-buffer-local 'org-scheduled-regexp)
2691 (defvar org-scheduled-time-regexp nil
2692 "Matches the SCHEDULED keyword together with a time stamp.")
2693 (make-variable-buffer-local 'org-scheduled-time-regexp)
2694 (defvar org-closed-time-regexp nil
2695 "Matches the CLOSED keyword together with a time stamp.")
2696 (make-variable-buffer-local 'org-closed-time-regexp)
2698 (defvar org-keyword-time-regexp nil
2699 "Matches any of the 4 keywords, together with the time stamp.")
2700 (make-variable-buffer-local 'org-keyword-time-regexp)
2701 (defvar org-keyword-time-not-clock-regexp nil
2702 "Matches any of the 3 keywords, together with the time stamp.")
2703 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2704 (defvar org-maybe-keyword-time-regexp nil
2705 "Matches a timestamp, possibly preceeded by a keyword.")
2706 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2707 (defvar org-planning-or-clock-line-re nil
2708 "Matches a line with planning or clock info.")
2709 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2711 (defconst org-plain-time-of-day-regexp
2712 (concat
2713 "\\(\\<[012]?[0-9]"
2714 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2715 "\\(--?"
2716 "\\(\\<[012]?[0-9]"
2717 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2718 "\\)?")
2719 "Regular expression to match a plain time or time range.
2720 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2721 groups carry important information:
2722 0 the full match
2723 1 the first time, range or not
2724 8 the second time, if it is a range.")
2726 (defconst org-plain-time-extension-regexp
2727 (concat
2728 "\\(\\<[012]?[0-9]"
2729 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2730 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2731 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2732 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2733 groups carry important information:
2734 0 the full match
2735 7 hours of duration
2736 9 minutes of duration")
2738 (defconst org-stamp-time-of-day-regexp
2739 (concat
2740 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2741 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2742 "\\(--?"
2743 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2744 "Regular expression to match a timestamp time or time range.
2745 After a match, the following groups carry important information:
2746 0 the full match
2747 1 date plus weekday, for backreferencing to make sure both times on same day
2748 2 the first time, range or not
2749 4 the second time, if it is a range.")
2751 (defconst org-startup-options
2752 '(("fold" org-startup-folded t)
2753 ("overview" org-startup-folded t)
2754 ("nofold" org-startup-folded nil)
2755 ("showall" org-startup-folded nil)
2756 ("content" org-startup-folded content)
2757 ("hidestars" org-hide-leading-stars t)
2758 ("showstars" org-hide-leading-stars nil)
2759 ("odd" org-odd-levels-only t)
2760 ("oddeven" org-odd-levels-only nil)
2761 ("align" org-startup-align-all-tables t)
2762 ("noalign" org-startup-align-all-tables nil)
2763 ("customtime" org-display-custom-times t)
2764 ("logdone" org-log-done time)
2765 ("lognotedone" org-log-done note)
2766 ("nologdone" org-log-done nil)
2767 ("lognoteclock-out" org-log-note-clock-out t)
2768 ("nolognoteclock-out" org-log-note-clock-out nil)
2769 ("logrepeat" org-log-repeat state)
2770 ("lognoterepeat" org-log-repeat note)
2771 ("nologrepeat" org-log-repeat nil)
2772 ("constcgs" constants-unit-system cgs)
2773 ("constSI" constants-unit-system SI))
2774 "Variable associated with STARTUP options for org-mode.
2775 Each element is a list of three items: The startup options as written
2776 in the #+STARTUP line, the corresponding variable, and the value to
2777 set this variable to if the option is found. An optional forth element PUSH
2778 means to push this value onto the list in the variable.")
2780 (defun org-set-regexps-and-options ()
2781 "Precompute regular expressions for current buffer."
2782 (when (org-mode-p)
2783 (org-set-local 'org-todo-kwd-alist nil)
2784 (org-set-local 'org-todo-key-alist nil)
2785 (org-set-local 'org-todo-key-trigger nil)
2786 (org-set-local 'org-todo-keywords-1 nil)
2787 (org-set-local 'org-done-keywords nil)
2788 (org-set-local 'org-todo-heads nil)
2789 (org-set-local 'org-todo-sets nil)
2790 (org-set-local 'org-todo-log-states nil)
2791 (org-set-local 'org-file-properties nil)
2792 (org-set-local 'org-file-tags nil)
2793 (let ((re (org-make-options-regexp
2794 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2795 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2796 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2797 (splitre "[ \t]+")
2798 kwds kws0 kwsa key log value cat arch tags const links hw dws
2799 tail sep kws1 prio props ftags drawers
2800 ext-setup-or-nil setup-contents (start 0))
2801 (save-excursion
2802 (save-restriction
2803 (widen)
2804 (goto-char (point-min))
2805 (while (or (and ext-setup-or-nil
2806 (string-match re ext-setup-or-nil start)
2807 (setq start (match-end 0)))
2808 (and (setq ext-setup-or-nil nil start 0)
2809 (re-search-forward re nil t)))
2810 (setq key (upcase (match-string 1 ext-setup-or-nil))
2811 value (org-match-string-no-properties 2 ext-setup-or-nil))
2812 (cond
2813 ((equal key "CATEGORY")
2814 (if (string-match "[ \t]+$" value)
2815 (setq value (replace-match "" t t value)))
2816 (setq cat value))
2817 ((member key '("SEQ_TODO" "TODO"))
2818 (push (cons 'sequence (org-split-string value splitre)) kwds))
2819 ((equal key "TYP_TODO")
2820 (push (cons 'type (org-split-string value splitre)) kwds))
2821 ((equal key "TAGS")
2822 (setq tags (append tags (org-split-string value splitre))))
2823 ((equal key "COLUMNS")
2824 (org-set-local 'org-columns-default-format value))
2825 ((equal key "LINK")
2826 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2827 (push (cons (match-string 1 value)
2828 (org-trim (match-string 2 value)))
2829 links)))
2830 ((equal key "PRIORITIES")
2831 (setq prio (org-split-string value " +")))
2832 ((equal key "PROPERTY")
2833 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2834 (push (cons (match-string 1 value) (match-string 2 value))
2835 props)))
2836 ((equal key "FILETAGS")
2837 (when (string-match "\\S-" value)
2838 (setq ftags
2839 (append
2840 ftags
2841 (apply 'append
2842 (mapcar (lambda (x) (org-split-string x ":"))
2843 (org-split-string value)))))))
2844 ((equal key "DRAWERS")
2845 (setq drawers (org-split-string value splitre)))
2846 ((equal key "CONSTANTS")
2847 (setq const (append const (org-split-string value splitre))))
2848 ((equal key "STARTUP")
2849 (let ((opts (org-split-string value splitre))
2850 l var val)
2851 (while (setq l (pop opts))
2852 (when (setq l (assoc l org-startup-options))
2853 (setq var (nth 1 l) val (nth 2 l))
2854 (if (not (nth 3 l))
2855 (set (make-local-variable var) val)
2856 (if (not (listp (symbol-value var)))
2857 (set (make-local-variable var) nil))
2858 (set (make-local-variable var) (symbol-value var))
2859 (add-to-list var val))))))
2860 ((equal key "ARCHIVE")
2861 (string-match " *$" value)
2862 (setq arch (replace-match "" t t value))
2863 (remove-text-properties 0 (length arch)
2864 '(face t fontified t) arch))
2865 ((equal key "SETUPFILE")
2866 (setq setup-contents (org-file-contents
2867 (expand-file-name
2868 (org-remove-double-quotes value))
2869 'noerror))
2870 (if (not ext-setup-or-nil)
2871 (setq ext-setup-or-nil setup-contents start 0)
2872 (setq ext-setup-or-nil
2873 (concat (substring ext-setup-or-nil 0 start)
2874 "\n" setup-contents "\n"
2875 (substring ext-setup-or-nil start)))))
2876 ))))
2877 (when cat
2878 (org-set-local 'org-category (intern cat))
2879 (push (cons "CATEGORY" cat) props))
2880 (when prio
2881 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2882 (setq prio (mapcar 'string-to-char prio))
2883 (org-set-local 'org-highest-priority (nth 0 prio))
2884 (org-set-local 'org-lowest-priority (nth 1 prio))
2885 (org-set-local 'org-default-priority (nth 2 prio)))
2886 (and props (org-set-local 'org-file-properties (nreverse props)))
2887 (and ftags (org-set-local 'org-file-tags ftags))
2888 (and drawers (org-set-local 'org-drawers drawers))
2889 (and arch (org-set-local 'org-archive-location arch))
2890 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2891 ;; Process the TODO keywords
2892 (unless kwds
2893 ;; Use the global values as if they had been given locally.
2894 (setq kwds (default-value 'org-todo-keywords))
2895 (if (stringp (car kwds))
2896 (setq kwds (list (cons org-todo-interpretation
2897 (default-value 'org-todo-keywords)))))
2898 (setq kwds (reverse kwds)))
2899 (setq kwds (nreverse kwds))
2900 (let (inter kws kw)
2901 (while (setq kws (pop kwds))
2902 (setq inter (pop kws) sep (member "|" kws)
2903 kws0 (delete "|" (copy-sequence kws))
2904 kwsa nil
2905 kws1 (mapcar
2906 (lambda (x)
2907 ;; 1 2
2908 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2909 (progn
2910 (setq kw (match-string 1 x)
2911 key (and (match-end 2) (match-string 2 x))
2912 log (org-extract-log-state-settings x))
2913 (push (cons kw (and key (string-to-char key))) kwsa)
2914 (and log (push log org-todo-log-states))
2916 (error "Invalid TODO keyword %s" x)))
2917 kws0)
2918 kwsa (if kwsa (append '((:startgroup))
2919 (nreverse kwsa)
2920 '((:endgroup))))
2921 hw (car kws1)
2922 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2923 tail (list inter hw (car dws) (org-last dws)))
2924 (add-to-list 'org-todo-heads hw 'append)
2925 (push kws1 org-todo-sets)
2926 (setq org-done-keywords (append org-done-keywords dws nil))
2927 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2928 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2929 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2930 (setq org-todo-sets (nreverse org-todo-sets)
2931 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2932 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2933 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2934 ;; Process the constants
2935 (when const
2936 (let (e cst)
2937 (while (setq e (pop const))
2938 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2939 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2940 (setq org-table-formula-constants-local cst)))
2942 ;; Process the tags.
2943 (when tags
2944 (let (e tgs)
2945 (while (setq e (pop tags))
2946 (cond
2947 ((equal e "{") (push '(:startgroup) tgs))
2948 ((equal e "}") (push '(:endgroup) tgs))
2949 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2950 (push (cons (match-string 1 e)
2951 (string-to-char (match-string 2 e)))
2952 tgs))
2953 (t (push (list e) tgs))))
2954 (org-set-local 'org-tag-alist nil)
2955 (while (setq e (pop tgs))
2956 (or (and (stringp (car e))
2957 (assoc (car e) org-tag-alist))
2958 (push e org-tag-alist)))))
2960 ;; Compute the regular expressions and other local variables
2961 (if (not org-done-keywords)
2962 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2963 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2964 (length org-scheduled-string)
2965 (length org-clock-string)
2966 (length org-closed-string)))
2967 org-drawer-regexp
2968 (concat "^[ \t]*:\\("
2969 (mapconcat 'regexp-quote org-drawers "\\|")
2970 "\\):[ \t]*$")
2971 org-not-done-keywords
2972 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2973 org-todo-regexp
2974 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2975 "\\|") "\\)\\>")
2976 org-not-done-regexp
2977 (concat "\\<\\("
2978 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2979 "\\)\\>")
2980 org-todo-line-regexp
2981 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2982 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2983 "\\)\\>\\)?[ \t]*\\(.*\\)")
2984 org-complex-heading-regexp
2985 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2986 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2987 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2988 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2989 org-nl-done-regexp
2990 (concat "\n\\*+[ \t]+"
2991 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2992 "\\)" "\\>")
2993 org-todo-line-tags-regexp
2994 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2995 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2996 (org-re
2997 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2998 org-looking-at-done-regexp
2999 (concat "^" "\\(?:"
3000 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3001 "\\>")
3002 org-deadline-regexp (concat "\\<" org-deadline-string)
3003 org-deadline-time-regexp
3004 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3005 org-deadline-line-regexp
3006 (concat "\\<\\(" org-deadline-string "\\).*")
3007 org-scheduled-regexp
3008 (concat "\\<" org-scheduled-string)
3009 org-scheduled-time-regexp
3010 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3011 org-closed-time-regexp
3012 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3013 org-keyword-time-regexp
3014 (concat "\\<\\(" org-scheduled-string
3015 "\\|" org-deadline-string
3016 "\\|" org-closed-string
3017 "\\|" org-clock-string "\\)"
3018 " *[[<]\\([^]>]+\\)[]>]")
3019 org-keyword-time-not-clock-regexp
3020 (concat "\\<\\(" org-scheduled-string
3021 "\\|" org-deadline-string
3022 "\\|" org-closed-string
3023 "\\)"
3024 " *[[<]\\([^]>]+\\)[]>]")
3025 org-maybe-keyword-time-regexp
3026 (concat "\\(\\<\\(" org-scheduled-string
3027 "\\|" org-deadline-string
3028 "\\|" org-closed-string
3029 "\\|" org-clock-string "\\)\\)?"
3030 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3031 org-planning-or-clock-line-re
3032 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3033 "\\|" org-deadline-string
3034 "\\|" org-closed-string "\\|" org-clock-string
3035 "\\)\\>\\)")
3037 (org-compute-latex-and-specials-regexp)
3038 (org-set-font-lock-defaults))))
3040 (defun org-file-contents (file &optional noerror)
3041 "Return the contents of FILE, as a string."
3042 (if (or (not file)
3043 (not (file-readable-p file)))
3044 (if noerror
3045 (progn
3046 (message "Cannot read file %s" file)
3047 (ding) (sit-for 2)
3049 (error "Cannot read file %s" file))
3050 (with-temp-buffer
3051 (insert-file-contents file)
3052 (buffer-string))))
3054 (defun org-extract-log-state-settings (x)
3055 "Extract the log state setting from a TODO keyword string.
3056 This will extract info from a string like \"WAIT(w@/!)\"."
3057 (let (kw key log1 log2)
3058 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3059 (setq kw (match-string 1 x)
3060 key (and (match-end 2) (match-string 2 x))
3061 log1 (and (match-end 3) (match-string 3 x))
3062 log2 (and (match-end 4) (match-string 4 x)))
3063 (and (or log1 log2)
3064 (list kw
3065 (and log1 (if (equal log1 "!") 'time 'note))
3066 (and log2 (if (equal log2 "!") 'time 'note)))))))
3068 (defun org-remove-keyword-keys (list)
3069 "Remove a pair of parenthesis at the end of each string in LIST."
3070 (mapcar (lambda (x)
3071 (if (string-match "(.*)$" x)
3072 (substring x 0 (match-beginning 0))
3074 list))
3076 ;; FIXME: this could be done much better, using second characters etc.
3077 (defun org-assign-fast-keys (alist)
3078 "Assign fast keys to a keyword-key alist.
3079 Respect keys that are already there."
3080 (let (new e k c c1 c2 (char ?a))
3081 (while (setq e (pop alist))
3082 (cond
3083 ((equal e '(:startgroup)) (push e new))
3084 ((equal e '(:endgroup)) (push e new))
3086 (setq k (car e) c2 nil)
3087 (if (cdr e)
3088 (setq c (cdr e))
3089 ;; automatically assign a character.
3090 (setq c1 (string-to-char
3091 (downcase (substring
3092 k (if (= (string-to-char k) ?@) 1 0)))))
3093 (if (or (rassoc c1 new) (rassoc c1 alist))
3094 (while (or (rassoc char new) (rassoc char alist))
3095 (setq char (1+ char)))
3096 (setq c2 c1))
3097 (setq c (or c2 char)))
3098 (push (cons k c) new))))
3099 (nreverse new)))
3101 ;;; Some variables used in various places
3103 (defvar org-window-configuration nil
3104 "Used in various places to store a window configuration.")
3105 (defvar org-finish-function nil
3106 "Function to be called when `C-c C-c' is used.
3107 This is for getting out of special buffers like remember.")
3110 ;; FIXME: Occasionally check by commenting these, to make sure
3111 ;; no other functions uses these, forgetting to let-bind them.
3112 (defvar entry)
3113 (defvar state)
3114 (defvar last-state)
3115 (defvar date)
3116 (defvar description)
3118 ;; Defined somewhere in this file, but used before definition.
3119 (defvar org-html-entities)
3120 (defvar org-struct-menu)
3121 (defvar org-org-menu)
3122 (defvar org-tbl-menu)
3123 (defvar org-agenda-keymap)
3125 ;;;; Define the Org-mode
3127 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3128 (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."))
3131 ;; We use a before-change function to check if a table might need
3132 ;; an update.
3133 (defvar org-table-may-need-update t
3134 "Indicates that a table might need an update.
3135 This variable is set by `org-before-change-function'.
3136 `org-table-align' sets it back to nil.")
3137 (defun org-before-change-function (beg end)
3138 "Every change indicates that a table might need an update."
3139 (setq org-table-may-need-update t))
3140 (defvar org-mode-map)
3141 (defvar org-mode-hook nil)
3142 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3143 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3144 (defvar org-table-buffer-is-an nil)
3145 (defconst org-outline-regexp "\\*+ ")
3147 ;;;###autoload
3148 (define-derived-mode org-mode outline-mode "Org"
3149 "Outline-based notes management and organizer, alias
3150 \"Carsten's outline-mode for keeping track of everything.\"
3152 Org-mode develops organizational tasks around a NOTES file which
3153 contains information about projects as plain text. Org-mode is
3154 implemented on top of outline-mode, which is ideal to keep the content
3155 of large files well structured. It supports ToDo items, deadlines and
3156 time stamps, which magically appear in the diary listing of the Emacs
3157 calendar. Tables are easily created with a built-in table editor.
3158 Plain text URL-like links connect to websites, emails (VM), Usenet
3159 messages (Gnus), BBDB entries, and any files related to the project.
3160 For printing and sharing of notes, an Org-mode file (or a part of it)
3161 can be exported as a structured ASCII or HTML file.
3163 The following commands are available:
3165 \\{org-mode-map}"
3167 ;; Get rid of Outline menus, they are not needed
3168 ;; Need to do this here because define-derived-mode sets up
3169 ;; the keymap so late. Still, it is a waste to call this each time
3170 ;; we switch another buffer into org-mode.
3171 (if (featurep 'xemacs)
3172 (when (boundp 'outline-mode-menu-heading)
3173 ;; Assume this is Greg's port, it used easymenu
3174 (easy-menu-remove outline-mode-menu-heading)
3175 (easy-menu-remove outline-mode-menu-show)
3176 (easy-menu-remove outline-mode-menu-hide))
3177 (define-key org-mode-map [menu-bar headings] 'undefined)
3178 (define-key org-mode-map [menu-bar hide] 'undefined)
3179 (define-key org-mode-map [menu-bar show] 'undefined))
3181 (org-load-modules-maybe)
3182 (easy-menu-add org-org-menu)
3183 (easy-menu-add org-tbl-menu)
3184 (org-install-agenda-files-menu)
3185 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3186 (org-add-to-invisibility-spec '(org-cwidth))
3187 (when (featurep 'xemacs)
3188 (org-set-local 'line-move-ignore-invisible t))
3189 (org-set-local 'outline-regexp org-outline-regexp)
3190 (org-set-local 'outline-level 'org-outline-level)
3191 (when (and org-ellipsis
3192 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3193 (fboundp 'make-glyph-code))
3194 (unless org-display-table
3195 (setq org-display-table (make-display-table)))
3196 (set-display-table-slot
3197 org-display-table 4
3198 (vconcat (mapcar
3199 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3200 org-ellipsis)))
3201 (if (stringp org-ellipsis) org-ellipsis "..."))))
3202 (setq buffer-display-table org-display-table))
3203 (org-set-regexps-and-options)
3204 ;; Calc embedded
3205 (org-set-local 'calc-embedded-open-mode "# ")
3206 (modify-syntax-entry ?# "<")
3207 (modify-syntax-entry ?@ "w")
3208 (if org-startup-truncated (setq truncate-lines t))
3209 (org-set-local 'font-lock-unfontify-region-function
3210 'org-unfontify-region)
3211 ;; Activate before-change-function
3212 (org-set-local 'org-table-may-need-update t)
3213 (org-add-hook 'before-change-functions 'org-before-change-function nil
3214 'local)
3215 ;; Check for running clock before killing a buffer
3216 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3217 ;; Paragraphs and auto-filling
3218 (org-set-autofill-regexps)
3219 (setq indent-line-function 'org-indent-line-function)
3220 (org-update-radio-target-regexp)
3222 ;; Comment characters
3223 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3224 (org-set-local 'comment-padding " ")
3226 ;; Align options lines
3227 (org-set-local
3228 'align-mode-rules-list
3229 '((org-in-buffer-settings
3230 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3231 (modes . '(org-mode)))))
3233 ;; Imenu
3234 (org-set-local 'imenu-create-index-function
3235 'org-imenu-get-tree)
3237 ;; Make isearch reveal context
3238 (if (or (featurep 'xemacs)
3239 (not (boundp 'outline-isearch-open-invisible-function)))
3240 ;; Emacs 21 and XEmacs make use of the hook
3241 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3242 ;; Emacs 22 deals with this through a special variable
3243 (org-set-local 'outline-isearch-open-invisible-function
3244 (lambda (&rest ignore) (org-show-context 'isearch))))
3246 ;; If empty file that did not turn on org-mode automatically, make it to.
3247 (if (and org-insert-mode-line-in-empty-file
3248 (interactive-p)
3249 (= (point-min) (point-max)))
3250 (insert "# -*- mode: org -*-\n\n"))
3252 (unless org-inhibit-startup
3253 (when org-startup-align-all-tables
3254 (let ((bmp (buffer-modified-p)))
3255 (org-table-map-tables 'org-table-align)
3256 (set-buffer-modified-p bmp)))
3257 (org-set-startup-visibility)))
3259 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3261 (defun org-current-time ()
3262 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3263 (if (> (car org-time-stamp-rounding-minutes) 1)
3264 (let ((r (car org-time-stamp-rounding-minutes))
3265 (time (decode-time)))
3266 (apply 'encode-time
3267 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3268 (nthcdr 2 time))))
3269 (current-time)))
3271 ;;;; Font-Lock stuff, including the activators
3273 (defvar org-mouse-map (make-sparse-keymap))
3274 (org-defkey org-mouse-map
3275 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3276 (org-defkey org-mouse-map
3277 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3278 (when org-mouse-1-follows-link
3279 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3280 (when org-tab-follows-link
3281 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3282 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3283 (when org-return-follows-link
3284 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3285 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3287 (require 'font-lock)
3289 (defconst org-non-link-chars "]\t\n\r<>")
3290 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3291 "shell" "elisp"))
3292 (defvar org-link-types-re nil
3293 "Matches a link that has a url-like prefix like \"http:\"")
3294 (defvar org-link-re-with-space nil
3295 "Matches a link with spaces, optional angular brackets around it.")
3296 (defvar org-link-re-with-space2 nil
3297 "Matches a link with spaces, optional angular brackets around it.")
3298 (defvar org-angle-link-re nil
3299 "Matches link with angular brackets, spaces are allowed.")
3300 (defvar org-plain-link-re nil
3301 "Matches plain link, without spaces.")
3302 (defvar org-bracket-link-regexp nil
3303 "Matches a link in double brackets.")
3304 (defvar org-bracket-link-analytic-regexp nil
3305 "Regular expression used to analyze links.
3306 Here is what the match groups contain after a match:
3307 1: http:
3308 2: http
3309 3: path
3310 4: [desc]
3311 5: desc")
3312 (defvar org-any-link-re nil
3313 "Regular expression matching any link.")
3315 (defun org-make-link-regexps ()
3316 "Update the link regular expressions.
3317 This should be called after the variable `org-link-types' has changed."
3318 (setq org-link-types-re
3319 (concat
3320 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3321 org-link-re-with-space
3322 (concat
3323 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3324 "\\([^" org-non-link-chars " ]"
3325 "[^" org-non-link-chars "]*"
3326 "[^" org-non-link-chars " ]\\)>?")
3327 org-link-re-with-space2
3328 (concat
3329 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3330 "\\([^" org-non-link-chars " ]"
3331 "[^]\t\n\r]*"
3332 "[^" org-non-link-chars " ]\\)>?")
3333 org-angle-link-re
3334 (concat
3335 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3336 "\\([^" org-non-link-chars " ]"
3337 "[^" org-non-link-chars "]*"
3338 "\\)>")
3339 org-plain-link-re
3340 (concat
3341 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3342 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3343 org-bracket-link-regexp
3344 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3345 org-bracket-link-analytic-regexp
3346 (concat
3347 "\\[\\["
3348 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3349 "\\([^]]+\\)"
3350 "\\]"
3351 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3352 "\\]")
3353 org-any-link-re
3354 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3355 org-angle-link-re "\\)\\|\\("
3356 org-plain-link-re "\\)")))
3358 (org-make-link-regexps)
3360 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3361 "Regular expression for fast time stamp matching.")
3362 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3363 "Regular expression for fast time stamp matching.")
3364 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3365 "Regular expression matching time strings for analysis.
3366 This one does not require the space after the date, so it can be used
3367 on a string that terminates immediately after the date.")
3368 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3369 "Regular expression matching time strings for analysis.")
3370 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3371 "Regular expression matching time stamps, with groups.")
3372 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3373 "Regular expression matching time stamps (also [..]), with groups.")
3374 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3375 "Regular expression matching a time stamp range.")
3376 (defconst org-tr-regexp-both
3377 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3378 "Regular expression matching a time stamp range.")
3379 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3380 org-ts-regexp "\\)?")
3381 "Regular expression matching a time stamp or time stamp range.")
3382 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3383 org-ts-regexp-both "\\)?")
3384 "Regular expression matching a time stamp or time stamp range.
3385 The time stamps may be either active or inactive.")
3387 (defvar org-emph-face nil)
3389 (defun org-do-emphasis-faces (limit)
3390 "Run through the buffer and add overlays to links."
3391 (let (rtn)
3392 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3393 (if (not (= (char-after (match-beginning 3))
3394 (char-after (match-beginning 4))))
3395 (progn
3396 (setq rtn t)
3397 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3398 'face
3399 (nth 1 (assoc (match-string 3)
3400 org-emphasis-alist)))
3401 (add-text-properties (match-beginning 2) (match-end 2)
3402 '(font-lock-multiline t))
3403 (when org-hide-emphasis-markers
3404 (add-text-properties (match-end 4) (match-beginning 5)
3405 '(invisible org-link))
3406 (add-text-properties (match-beginning 3) (match-end 3)
3407 '(invisible org-link)))))
3408 (backward-char 1))
3409 rtn))
3411 (defun org-emphasize (&optional char)
3412 "Insert or change an emphasis, i.e. a font like bold or italic.
3413 If there is an active region, change that region to a new emphasis.
3414 If there is no region, just insert the marker characters and position
3415 the cursor between them.
3416 CHAR should be either the marker character, or the first character of the
3417 HTML tag associated with that emphasis. If CHAR is a space, the means
3418 to remove the emphasis of the selected region.
3419 If char is not given (for example in an interactive call) it
3420 will be prompted for."
3421 (interactive)
3422 (let ((eal org-emphasis-alist) e det
3423 (erc org-emphasis-regexp-components)
3424 (prompt "")
3425 (string "") beg end move tag c s)
3426 (if (org-region-active-p)
3427 (setq beg (region-beginning) end (region-end)
3428 string (buffer-substring beg end))
3429 (setq move t))
3431 (while (setq e (pop eal))
3432 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3433 c (aref tag 0))
3434 (push (cons c (string-to-char (car e))) det)
3435 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3436 (substring tag 1)))))
3437 (unless char
3438 (message "%s" (concat "Emphasis marker or tag:" prompt))
3439 (setq char (read-char-exclusive)))
3440 (setq char (or (cdr (assoc char det)) char))
3441 (if (equal char ?\ )
3442 (setq s "" move nil)
3443 (unless (assoc (char-to-string char) org-emphasis-alist)
3444 (error "No such emphasis marker: \"%c\"" char))
3445 (setq s (char-to-string char)))
3446 (while (and (> (length string) 1)
3447 (equal (substring string 0 1) (substring string -1))
3448 (assoc (substring string 0 1) org-emphasis-alist))
3449 (setq string (substring string 1 -1)))
3450 (setq string (concat s string s))
3451 (if beg (delete-region beg end))
3452 (unless (or (bolp)
3453 (string-match (concat "[" (nth 0 erc) "\n]")
3454 (char-to-string (char-before (point)))))
3455 (insert " "))
3456 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3457 (char-to-string (char-after (point))))
3458 (insert " ") (backward-char 1))
3459 (insert string)
3460 (and move (backward-char 1))))
3462 (defconst org-nonsticky-props
3463 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3466 (defun org-activate-plain-links (limit)
3467 "Run through the buffer and add overlays to links."
3468 (catch 'exit
3469 (let (f)
3470 (while (re-search-forward org-plain-link-re limit t)
3471 (setq f (get-text-property (match-beginning 0) 'face))
3472 (if (or (eq f 'org-tag)
3473 (and (listp f) (memq 'org-tag f)))
3475 (add-text-properties (match-beginning 0) (match-end 0)
3476 (list 'mouse-face 'highlight
3477 'rear-nonsticky org-nonsticky-props
3478 'keymap org-mouse-map
3480 (throw 'exit t))))))
3482 (defun org-activate-code (limit)
3483 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3484 (unless (get-text-property (match-beginning 1) 'face)
3485 (remove-text-properties (match-beginning 0) (match-end 0)
3486 '(display t invisible t intangible t))
3487 t)))
3489 (defun org-activate-angle-links (limit)
3490 "Run through the buffer and add overlays to links."
3491 (if (re-search-forward org-angle-link-re limit t)
3492 (progn
3493 (add-text-properties (match-beginning 0) (match-end 0)
3494 (list 'mouse-face 'highlight
3495 'rear-nonsticky org-nonsticky-props
3496 'keymap org-mouse-map
3498 t)))
3500 (defun org-activate-bracket-links (limit)
3501 "Run through the buffer and add overlays to bracketed links."
3502 (if (re-search-forward org-bracket-link-regexp limit t)
3503 (let* ((help (concat "LINK: "
3504 (org-match-string-no-properties 1)))
3505 ;; FIXME: above we should remove the escapes.
3506 ;; but that requires another match, protecting match data,
3507 ;; a lot of overhead for font-lock.
3508 (ip (org-maybe-intangible
3509 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3510 'keymap org-mouse-map 'mouse-face 'highlight
3511 'font-lock-multiline t 'help-echo help)))
3512 (vp (list 'rear-nonsticky org-nonsticky-props
3513 'keymap org-mouse-map 'mouse-face 'highlight
3514 ' font-lock-multiline t 'help-echo help)))
3515 ;; We need to remove the invisible property here. Table narrowing
3516 ;; may have made some of this invisible.
3517 (remove-text-properties (match-beginning 0) (match-end 0)
3518 '(invisible nil))
3519 (if (match-end 3)
3520 (progn
3521 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3522 (add-text-properties (match-beginning 3) (match-end 3) vp)
3523 (add-text-properties (match-end 3) (match-end 0) ip))
3524 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3525 (add-text-properties (match-beginning 1) (match-end 1) vp)
3526 (add-text-properties (match-end 1) (match-end 0) ip))
3527 t)))
3529 (defun org-activate-dates (limit)
3530 "Run through the buffer and add overlays to dates."
3531 (if (re-search-forward org-tsr-regexp-both limit t)
3532 (progn
3533 (add-text-properties (match-beginning 0) (match-end 0)
3534 (list 'mouse-face 'highlight
3535 'rear-nonsticky org-nonsticky-props
3536 'keymap org-mouse-map))
3537 (when org-display-custom-times
3538 (if (match-end 3)
3539 (org-display-custom-time (match-beginning 3) (match-end 3)))
3540 (org-display-custom-time (match-beginning 1) (match-end 1)))
3541 t)))
3543 (defvar org-target-link-regexp nil
3544 "Regular expression matching radio targets in plain text.")
3545 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3546 "Regular expression matching a link target.")
3547 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3548 "Regular expression matching a radio target.")
3549 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3550 "Regular expression matching any target.")
3552 (defun org-activate-target-links (limit)
3553 "Run through the buffer and add overlays to target matches."
3554 (when org-target-link-regexp
3555 (let ((case-fold-search t))
3556 (if (re-search-forward org-target-link-regexp limit t)
3557 (progn
3558 (add-text-properties (match-beginning 0) (match-end 0)
3559 (list 'mouse-face 'highlight
3560 'rear-nonsticky org-nonsticky-props
3561 'keymap org-mouse-map
3562 'help-echo "Radio target link"
3563 'org-linked-text t))
3564 t)))))
3566 (defun org-update-radio-target-regexp ()
3567 "Find all radio targets in this file and update the regular expression."
3568 (interactive)
3569 (when (memq 'radio org-activate-links)
3570 (setq org-target-link-regexp
3571 (org-make-target-link-regexp (org-all-targets 'radio)))
3572 (org-restart-font-lock)))
3574 (defun org-hide-wide-columns (limit)
3575 (let (s e)
3576 (setq s (text-property-any (point) (or limit (point-max))
3577 'org-cwidth t))
3578 (when s
3579 (setq e (next-single-property-change s 'org-cwidth))
3580 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3581 (goto-char e)
3582 t)))
3584 (defvar org-latex-and-specials-regexp nil
3585 "Regular expression for highlighting export special stuff.")
3586 (defvar org-match-substring-regexp)
3587 (defvar org-match-substring-with-braces-regexp)
3588 (defvar org-export-html-special-string-regexps)
3590 (defun org-compute-latex-and-specials-regexp ()
3591 "Compute regular expression for stuff treated specially by exporters."
3592 (if (not org-highlight-latex-fragments-and-specials)
3593 (org-set-local 'org-latex-and-specials-regexp nil)
3594 (require 'org-exp)
3595 (let*
3596 ((matchers (plist-get org-format-latex-options :matchers))
3597 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3598 org-latex-regexps)))
3599 (options (org-combine-plists (org-default-export-plist)
3600 (org-infile-export-plist)))
3601 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3602 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3603 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3604 (org-export-html-expand (plist-get options :expand-quoted-html))
3605 (org-export-with-special-strings (plist-get options :special-strings))
3606 (re-sub
3607 (cond
3608 ((equal org-export-with-sub-superscripts '{})
3609 (list org-match-substring-with-braces-regexp))
3610 (org-export-with-sub-superscripts
3611 (list org-match-substring-regexp))
3612 (t nil)))
3613 (re-latex
3614 (if org-export-with-LaTeX-fragments
3615 (mapcar (lambda (x) (nth 1 x)) latexs)))
3616 (re-macros
3617 (if org-export-with-TeX-macros
3618 (list (concat "\\\\"
3619 (regexp-opt
3620 (append (mapcar 'car org-html-entities)
3621 (if (boundp 'org-latex-entities)
3622 org-latex-entities nil))
3623 'words))) ; FIXME
3625 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3626 (re-special (if org-export-with-special-strings
3627 (mapcar (lambda (x) (car x))
3628 org-export-html-special-string-regexps)))
3629 (re-rest
3630 (delq nil
3631 (list
3632 (if org-export-html-expand "@<[^>\n]+>")
3633 ))))
3634 (org-set-local
3635 'org-latex-and-specials-regexp
3636 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3637 re-rest) "\\|")))))
3639 (defun org-do-latex-and-special-faces (limit)
3640 "Run through the buffer and add overlays to links."
3641 (when org-latex-and-specials-regexp
3642 (let (rtn d)
3643 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3644 limit t))
3645 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3646 'face))
3647 '(org-code org-verbatim underline)))
3648 (progn
3649 (setq rtn t
3650 d (cond ((member (char-after (1+ (match-beginning 0)))
3651 '(?_ ?^)) 1)
3652 (t 0)))
3653 (font-lock-prepend-text-property
3654 (+ d (match-beginning 0)) (match-end 0)
3655 'face 'org-latex-and-export-specials)
3656 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3657 '(font-lock-multiline t)))))
3658 rtn)))
3660 (defun org-restart-font-lock ()
3661 "Restart font-lock-mode, to force refontification."
3662 (when (and (boundp 'font-lock-mode) font-lock-mode)
3663 (font-lock-mode -1)
3664 (font-lock-mode 1)))
3666 (defun org-all-targets (&optional radio)
3667 "Return a list of all targets in this file.
3668 With optional argument RADIO, only find radio targets."
3669 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3670 rtn)
3671 (save-excursion
3672 (goto-char (point-min))
3673 (while (re-search-forward re nil t)
3674 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3675 rtn)))
3677 (defun org-make-target-link-regexp (targets)
3678 "Make regular expression matching all strings in TARGETS.
3679 The regular expression finds the targets also if there is a line break
3680 between words."
3681 (and targets
3682 (concat
3683 "\\<\\("
3684 (mapconcat
3685 (lambda (x)
3686 (while (string-match " +" x)
3687 (setq x (replace-match "\\s-+" t t x)))
3689 targets
3690 "\\|")
3691 "\\)\\>")))
3693 (defun org-activate-tags (limit)
3694 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3695 (progn
3696 (add-text-properties (match-beginning 1) (match-end 1)
3697 (list 'mouse-face 'highlight
3698 'rear-nonsticky org-nonsticky-props
3699 'keymap org-mouse-map))
3700 t)))
3702 (defun org-outline-level ()
3703 (save-excursion
3704 (looking-at outline-regexp)
3705 (if (match-beginning 1)
3706 (+ (org-get-string-indentation (match-string 1)) 1000)
3707 (1- (- (match-end 0) (match-beginning 0))))))
3709 (defvar org-font-lock-keywords nil)
3711 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3712 "Regular expression matching a property line.")
3714 (defvar org-font-lock-hook nil
3715 "Functions to be called for special font lock stuff.")
3717 (defun org-font-lock-hook (limit)
3718 (run-hook-with-args 'org-font-lock-hook limit))
3720 (defun org-set-font-lock-defaults ()
3721 (let* ((em org-fontify-emphasized-text)
3722 (lk org-activate-links)
3723 (org-font-lock-extra-keywords
3724 (list
3725 ;; Call the hook
3726 '(org-font-lock-hook)
3727 ;; Headlines
3728 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3729 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3730 ;; Table lines
3731 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3732 (1 'org-table t))
3733 ;; Table internals
3734 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3735 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3736 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3737 ;; Drawers
3738 (list org-drawer-regexp '(0 'org-special-keyword t))
3739 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3740 ;; Properties
3741 (list org-property-re
3742 '(1 'org-special-keyword t)
3743 '(3 'org-property-value t))
3744 (if org-format-transports-properties-p
3745 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3746 ;; Links
3747 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3748 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3749 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3750 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3751 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3752 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3753 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3754 '(org-hide-wide-columns (0 nil append))
3755 ;; TODO lines
3756 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3757 '(1 (org-get-todo-face 1) t))
3758 ;; DONE
3759 (if org-fontify-done-headline
3760 (list (concat "^[*]+ +\\<\\("
3761 (mapconcat 'regexp-quote org-done-keywords "\\|")
3762 "\\)\\(.*\\)")
3763 '(2 'org-headline-done t))
3764 nil)
3765 ;; Priorities
3766 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3767 ;; Special keywords
3768 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3769 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3770 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3771 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3772 ;; Emphasis
3773 (if em
3774 (if (featurep 'xemacs)
3775 '(org-do-emphasis-faces (0 nil append))
3776 '(org-do-emphasis-faces)))
3777 ;; Checkboxes
3778 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3779 2 'bold prepend)
3780 (if org-provide-checkbox-statistics
3781 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3782 (0 (org-get-checkbox-statistics-face) t)))
3783 ;; Description list items
3784 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3785 2 'bold prepend)
3786 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3787 '(1 'org-archived prepend))
3788 ;; Specials
3789 '(org-do-latex-and-special-faces)
3790 ;; Code
3791 '(org-activate-code (1 'org-code t))
3792 ;; COMMENT
3793 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3794 "\\|" org-quote-string "\\)\\>")
3795 '(1 'org-special-keyword t))
3796 '("^#.*" (0 'font-lock-comment-face t))
3798 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3799 ;; Now set the full font-lock-keywords
3800 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3801 (org-set-local 'font-lock-defaults
3802 '(org-font-lock-keywords t nil nil backward-paragraph))
3803 (kill-local-variable 'font-lock-keywords) nil))
3805 (defvar org-m nil)
3806 (defvar org-l nil)
3807 (defvar org-f nil)
3808 (defun org-get-level-face (n)
3809 "Get the right face for match N in font-lock matching of healdines."
3810 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3811 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3812 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3813 (cond
3814 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3815 ((eq n 2) org-f)
3816 (t (if org-level-color-stars-only nil org-f))))
3818 (defun org-get-todo-face (kwd)
3819 "Get the right face for a TODO keyword KWD.
3820 If KWD is a number, get the corresponding match group."
3821 (if (numberp kwd) (setq kwd (match-string kwd)))
3822 (or (cdr (assoc kwd org-todo-keyword-faces))
3823 (and (member kwd org-done-keywords) 'org-done)
3824 'org-todo))
3826 (defun org-unfontify-region (beg end &optional maybe_loudly)
3827 "Remove fontification and activation overlays from links."
3828 (font-lock-default-unfontify-region beg end)
3829 (let* ((buffer-undo-list t)
3830 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3831 (inhibit-modification-hooks t)
3832 deactivate-mark buffer-file-name buffer-file-truename)
3833 (remove-text-properties beg end
3834 '(mouse-face t keymap t org-linked-text t
3835 invisible t intangible t))))
3837 ;;;; Visibility cycling, including org-goto and indirect buffer
3839 ;;; Cycling
3841 (defvar org-cycle-global-status nil)
3842 (make-variable-buffer-local 'org-cycle-global-status)
3843 (defvar org-cycle-subtree-status nil)
3844 (make-variable-buffer-local 'org-cycle-subtree-status)
3846 ;;;###autoload
3847 (defun org-cycle (&optional arg)
3848 "Visibility cycling for Org-mode.
3850 - When this function is called with a prefix argument, rotate the entire
3851 buffer through 3 states (global cycling)
3852 1. OVERVIEW: Show only top-level headlines.
3853 2. CONTENTS: Show all headlines of all levels, but no body text.
3854 3. SHOW ALL: Show everything.
3855 When called with two C-c C-u prefixes, switch to the startup visibility,
3856 determined by the variable `org-startup-folded', and by any VISIBILITY
3857 properties in the buffer.
3859 - When point is at the beginning of a headline, rotate the subtree started
3860 by this line through 3 different states (local cycling)
3861 1. FOLDED: Only the main headline is shown.
3862 2. CHILDREN: The main headline and the direct children are shown.
3863 From this state, you can move to one of the children
3864 and zoom in further.
3865 3. SUBTREE: Show the entire subtree, including body text.
3867 - When there is a numeric prefix, go up to a heading with level ARG, do
3868 a `show-subtree' and return to the previous cursor position. If ARG
3869 is negative, go up that many levels.
3871 - When point is not at the beginning of a headline, execute the global
3872 binding for TAB, which is re-indenting the line. See the option
3873 `org-cycle-emulate-tab' for details.
3875 - Special case: if point is at the beginning of the buffer and there is
3876 no headline in line 1, this function will act as if called with prefix arg.
3877 But only if also the variable `org-cycle-global-at-bob' is t."
3878 (interactive "P")
3879 (org-load-modules-maybe)
3880 (let* ((outline-regexp
3881 (if (and (org-mode-p) org-cycle-include-plain-lists)
3882 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3883 outline-regexp))
3884 (bob-special (and org-cycle-global-at-bob (bobp)
3885 (not (looking-at outline-regexp))))
3886 (org-cycle-hook
3887 (if bob-special
3888 (delq 'org-optimize-window-after-visibility-change
3889 (copy-sequence org-cycle-hook))
3890 org-cycle-hook))
3891 (pos (point)))
3893 (if (or bob-special (equal arg '(4)))
3894 ;; special case: use global cycling
3895 (setq arg t))
3897 (cond
3899 ((equal arg '(16))
3900 (org-set-startup-visibility)
3901 (message "Startup visibility, plus VISIBILITY properties."))
3903 ((org-at-table-p 'any)
3904 ;; Enter the table or move to the next field in the table
3905 (or (org-table-recognize-table.el)
3906 (progn
3907 (if arg (org-table-edit-field t)
3908 (org-table-justify-field-maybe)
3909 (call-interactively 'org-table-next-field)))))
3911 ((eq arg t) ;; Global cycling
3913 (cond
3914 ((and (eq last-command this-command)
3915 (eq org-cycle-global-status 'overview))
3916 ;; We just created the overview - now do table of contents
3917 ;; This can be slow in very large buffers, so indicate action
3918 (message "CONTENTS...")
3919 (org-content)
3920 (message "CONTENTS...done")
3921 (setq org-cycle-global-status 'contents)
3922 (run-hook-with-args 'org-cycle-hook 'contents))
3924 ((and (eq last-command this-command)
3925 (eq org-cycle-global-status 'contents))
3926 ;; We just showed the table of contents - now show everything
3927 (show-all)
3928 (message "SHOW ALL")
3929 (setq org-cycle-global-status 'all)
3930 (run-hook-with-args 'org-cycle-hook 'all))
3933 ;; Default action: go to overview
3934 (org-overview)
3935 (message "OVERVIEW")
3936 (setq org-cycle-global-status 'overview)
3937 (run-hook-with-args 'org-cycle-hook 'overview))))
3939 ((and org-drawers org-drawer-regexp
3940 (save-excursion
3941 (beginning-of-line 1)
3942 (looking-at org-drawer-regexp)))
3943 ;; Toggle block visibility
3944 (org-flag-drawer
3945 (not (get-char-property (match-end 0) 'invisible))))
3947 ((integerp arg)
3948 ;; Show-subtree, ARG levels up from here.
3949 (save-excursion
3950 (org-back-to-heading)
3951 (outline-up-heading (if (< arg 0) (- arg)
3952 (- (funcall outline-level) arg)))
3953 (org-show-subtree)))
3955 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3956 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3957 ;; At a heading: rotate between three different views
3958 (org-back-to-heading)
3959 (let ((goal-column 0) eoh eol eos)
3960 ;; First, some boundaries
3961 (save-excursion
3962 (org-back-to-heading)
3963 (save-excursion
3964 (beginning-of-line 2)
3965 (while (and (not (eobp)) ;; this is like `next-line'
3966 (get-char-property (1- (point)) 'invisible))
3967 (beginning-of-line 2)) (setq eol (point)))
3968 (outline-end-of-heading) (setq eoh (point))
3969 (org-end-of-subtree t)
3970 (unless (eobp)
3971 (skip-chars-forward " \t\n")
3972 (beginning-of-line 1) ; in case this is an item
3974 (setq eos (1- (point))))
3975 ;; Find out what to do next and set `this-command'
3976 (cond
3977 ((= eos eoh)
3978 ;; Nothing is hidden behind this heading
3979 (message "EMPTY ENTRY")
3980 (setq org-cycle-subtree-status nil)
3981 (save-excursion
3982 (goto-char eos)
3983 (outline-next-heading)
3984 (if (org-invisible-p) (org-flag-heading nil))))
3985 ((or (>= eol eos)
3986 (not (string-match "\\S-" (buffer-substring eol eos))))
3987 ;; Entire subtree is hidden in one line: open it
3988 (org-show-entry)
3989 (show-children)
3990 (message "CHILDREN")
3991 (save-excursion
3992 (goto-char eos)
3993 (outline-next-heading)
3994 (if (org-invisible-p) (org-flag-heading nil)))
3995 (setq org-cycle-subtree-status 'children)
3996 (run-hook-with-args 'org-cycle-hook 'children))
3997 ((and (eq last-command this-command)
3998 (eq org-cycle-subtree-status 'children))
3999 ;; We just showed the children, now show everything.
4000 (org-show-subtree)
4001 (message "SUBTREE")
4002 (setq org-cycle-subtree-status 'subtree)
4003 (run-hook-with-args 'org-cycle-hook 'subtree))
4005 ;; Default action: hide the subtree.
4006 (hide-subtree)
4007 (message "FOLDED")
4008 (setq org-cycle-subtree-status 'folded)
4009 (run-hook-with-args 'org-cycle-hook 'folded)))))
4011 ;; TAB emulation and template completion
4012 (buffer-read-only (org-back-to-heading))
4014 ((org-try-structure-completion))
4016 ((org-try-cdlatex-tab))
4018 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4019 (or (not (bolp))
4020 (not (looking-at outline-regexp))))
4021 (call-interactively (global-key-binding "\t")))
4023 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4024 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4025 (or (and (eq org-cycle-emulate-tab 'white)
4026 (= (match-end 0) (point-at-eol)))
4027 (and (eq org-cycle-emulate-tab 'whitestart)
4028 (>= (match-end 0) pos))))
4030 (eq org-cycle-emulate-tab t))
4031 (call-interactively (global-key-binding "\t")))
4033 (t (save-excursion
4034 (org-back-to-heading)
4035 (org-cycle))))))
4037 ;;;###autoload
4038 (defun org-global-cycle (&optional arg)
4039 "Cycle the global visibility. For details see `org-cycle'.
4040 With C-u prefix arg, switch to startup visibility.
4041 With a numeric prefix, show all headlines up to that level."
4042 (interactive "P")
4043 (let ((org-cycle-include-plain-lists
4044 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4045 (cond
4046 ((integerp arg)
4047 (show-all)
4048 (hide-sublevels arg)
4049 (setq org-cycle-global-status 'contents))
4050 ((equal arg '(4))
4051 (org-set-startup-visibility)
4052 (message "Startup visibility, plus VISIBILITY properties."))
4054 (org-cycle '(4))))))
4056 (defun org-set-startup-visibility ()
4057 "Set the visibility required by startup options and properties."
4058 (cond
4059 ((eq org-startup-folded t)
4060 (org-cycle '(4)))
4061 ((eq org-startup-folded 'content)
4062 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4063 (org-cycle '(4)) (org-cycle '(4)))))
4064 (org-set-visibility-according-to-property 'no-cleanup)
4065 (org-cycle-hide-archived-subtrees 'all)
4066 (org-cycle-hide-drawers 'all)
4067 (org-cycle-show-empty-lines 'all))
4069 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4070 "Switch subtree visibilities according to :VISIBILITY: property."
4071 (interactive)
4072 (let (state)
4073 (save-excursion
4074 (goto-char (point-min))
4075 (while (re-search-forward
4076 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4077 nil t)
4078 (setq state (match-string 1))
4079 (save-excursion
4080 (org-back-to-heading t)
4081 (hide-subtree)
4082 (org-reveal)
4083 (cond
4084 ((equal state '("fold" "folded"))
4085 (hide-subtree))
4086 ((equal state "children")
4087 (org-show-hidden-entry)
4088 (show-children))
4089 ((equal state "content")
4090 (save-excursion
4091 (save-restriction
4092 (org-narrow-to-subtree)
4093 (org-content))))
4094 ((member state '("all" "showall"))
4095 (show-subtree)))))
4096 (unless no-cleanup
4097 (org-cycle-hide-archived-subtrees 'all)
4098 (org-cycle-hide-drawers 'all)
4099 (org-cycle-show-empty-lines 'all)))))
4101 (defun org-overview ()
4102 "Switch to overview mode, shoing only top-level headlines.
4103 Really, this shows all headlines with level equal or greater than the level
4104 of the first headline in the buffer. This is important, because if the
4105 first headline is not level one, then (hide-sublevels 1) gives confusing
4106 results."
4107 (interactive)
4108 (let ((level (save-excursion
4109 (goto-char (point-min))
4110 (if (re-search-forward (concat "^" outline-regexp) nil t)
4111 (progn
4112 (goto-char (match-beginning 0))
4113 (funcall outline-level))))))
4114 (and level (hide-sublevels level))))
4116 (defun org-content (&optional arg)
4117 "Show all headlines in the buffer, like a table of contents.
4118 With numerical argument N, show content up to level N."
4119 (interactive "P")
4120 (save-excursion
4121 ;; Visit all headings and show their offspring
4122 (and (integerp arg) (org-overview))
4123 (goto-char (point-max))
4124 (catch 'exit
4125 (while (and (progn (condition-case nil
4126 (outline-previous-visible-heading 1)
4127 (error (goto-char (point-min))))
4129 (looking-at outline-regexp))
4130 (if (integerp arg)
4131 (show-children (1- arg))
4132 (show-branches))
4133 (if (bobp) (throw 'exit nil))))))
4136 (defun org-optimize-window-after-visibility-change (state)
4137 "Adjust the window after a change in outline visibility.
4138 This function is the default value of the hook `org-cycle-hook'."
4139 (when (get-buffer-window (current-buffer))
4140 (cond
4141 ; ((eq state 'overview) (org-first-headline-recenter 1))
4142 ; ((eq state 'overview) (org-beginning-of-line))
4143 ((eq state 'content) nil)
4144 ((eq state 'all) nil)
4145 ((eq state 'folded) nil)
4146 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4147 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4149 (defun org-compact-display-after-subtree-move ()
4150 (let (beg end)
4151 (save-excursion
4152 (if (org-up-heading-safe)
4153 (progn
4154 (hide-subtree)
4155 (show-entry)
4156 (show-children)
4157 (org-cycle-show-empty-lines 'children)
4158 (org-cycle-hide-drawers 'children))
4159 (org-overview)))))
4161 (defun org-cycle-show-empty-lines (state)
4162 "Show empty lines above all visible headlines.
4163 The region to be covered depends on STATE when called through
4164 `org-cycle-hook'. Lisp program can use t for STATE to get the
4165 entire buffer covered. Note that an empty line is only shown if there
4166 are at least `org-cycle-separator-lines' empty lines before the headeline."
4167 (when (> org-cycle-separator-lines 0)
4168 (save-excursion
4169 (let* ((n org-cycle-separator-lines)
4170 (re (cond
4171 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4172 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4173 (t (let ((ns (number-to-string (- n 2))))
4174 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4175 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4176 beg end)
4177 (cond
4178 ((memq state '(overview contents t))
4179 (setq beg (point-min) end (point-max)))
4180 ((memq state '(children folded))
4181 (setq beg (point) end (progn (org-end-of-subtree t t)
4182 (beginning-of-line 2)
4183 (point)))))
4184 (when beg
4185 (goto-char beg)
4186 (while (re-search-forward re end t)
4187 (if (not (get-char-property (match-end 1) 'invisible))
4188 (outline-flag-region
4189 (match-beginning 1) (match-end 1) nil)))))))
4190 ;; Never hide empty lines at the end of the file.
4191 (save-excursion
4192 (goto-char (point-max))
4193 (outline-previous-heading)
4194 (outline-end-of-heading)
4195 (if (and (looking-at "[ \t\n]+")
4196 (= (match-end 0) (point-max)))
4197 (outline-flag-region (point) (match-end 0) nil))))
4199 (defun org-cycle-hide-drawers (state)
4200 "Re-hide all drawers after a visibility state change."
4201 (when (and (org-mode-p)
4202 (not (memq state '(overview folded))))
4203 (save-excursion
4204 (let* ((globalp (memq state '(contents all)))
4205 (beg (if globalp (point-min) (point)))
4206 (end (if globalp (point-max) (org-end-of-subtree t))))
4207 (goto-char beg)
4208 (while (re-search-forward org-drawer-regexp end t)
4209 (org-flag-drawer t))))))
4211 (defun org-flag-drawer (flag)
4212 (save-excursion
4213 (beginning-of-line 1)
4214 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4215 (let ((b (match-end 0))
4216 (outline-regexp org-outline-regexp))
4217 (if (re-search-forward
4218 "^[ \t]*:END:"
4219 (save-excursion (outline-next-heading) (point)) t)
4220 (outline-flag-region b (point-at-eol) flag)
4221 (error ":END: line missing"))))))
4223 (defun org-subtree-end-visible-p ()
4224 "Is the end of the current subtree visible?"
4225 (pos-visible-in-window-p
4226 (save-excursion (org-end-of-subtree t) (point))))
4228 (defun org-first-headline-recenter (&optional N)
4229 "Move cursor to the first headline and recenter the headline.
4230 Optional argument N means, put the headline into the Nth line of the window."
4231 (goto-char (point-min))
4232 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4233 (beginning-of-line)
4234 (recenter (prefix-numeric-value N))))
4236 ;;; Org-goto
4238 (defvar org-goto-window-configuration nil)
4239 (defvar org-goto-marker nil)
4240 (defvar org-goto-map
4241 (let ((map (make-sparse-keymap)))
4242 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4243 (while (setq cmd (pop cmds))
4244 (substitute-key-definition cmd cmd map global-map)))
4245 (suppress-keymap map)
4246 (org-defkey map "\C-m" 'org-goto-ret)
4247 (org-defkey map [(return)] 'org-goto-ret)
4248 (org-defkey map [(left)] 'org-goto-left)
4249 (org-defkey map [(right)] 'org-goto-right)
4250 (org-defkey map [(control ?g)] 'org-goto-quit)
4251 (org-defkey map "\C-i" 'org-cycle)
4252 (org-defkey map [(tab)] 'org-cycle)
4253 (org-defkey map [(down)] 'outline-next-visible-heading)
4254 (org-defkey map [(up)] 'outline-previous-visible-heading)
4255 (if org-goto-auto-isearch
4256 (if (fboundp 'define-key-after)
4257 (define-key-after map [t] 'org-goto-local-auto-isearch)
4258 nil)
4259 (org-defkey map "q" 'org-goto-quit)
4260 (org-defkey map "n" 'outline-next-visible-heading)
4261 (org-defkey map "p" 'outline-previous-visible-heading)
4262 (org-defkey map "f" 'outline-forward-same-level)
4263 (org-defkey map "b" 'outline-backward-same-level)
4264 (org-defkey map "u" 'outline-up-heading))
4265 (org-defkey map "/" 'org-occur)
4266 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4267 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4268 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4269 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4270 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4271 map))
4273 (defconst org-goto-help
4274 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4275 RET=jump to location [Q]uit and return to previous location
4276 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4278 (defvar org-goto-start-pos) ; dynamically scoped parameter
4280 ;; FIXME: Docstring doe not mention both interfaces
4281 (defun org-goto (&optional alternative-interface)
4282 "Look up a different location in the current file, keeping current visibility.
4284 When you want look-up or go to a different location in a document, the
4285 fastest way is often to fold the entire buffer and then dive into the tree.
4286 This method has the disadvantage, that the previous location will be folded,
4287 which may not be what you want.
4289 This command works around this by showing a copy of the current buffer
4290 in an indirect buffer, in overview mode. You can dive into the tree in
4291 that copy, use org-occur and incremental search to find a location.
4292 When pressing RET or `Q', the command returns to the original buffer in
4293 which the visibility is still unchanged. After RET is will also jump to
4294 the location selected in the indirect buffer and expose the
4295 the headline hierarchy above."
4296 (interactive "P")
4297 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4298 (org-refile-use-outline-path t)
4299 (interface
4300 (if (not alternative-interface)
4301 org-goto-interface
4302 (if (eq org-goto-interface 'outline)
4303 'outline-path-completion
4304 'outline)))
4305 (org-goto-start-pos (point))
4306 (selected-point
4307 (if (eq interface 'outline)
4308 (car (org-get-location (current-buffer) org-goto-help))
4309 (nth 3 (org-refile-get-location "Goto: ")))))
4310 (if selected-point
4311 (progn
4312 (org-mark-ring-push org-goto-start-pos)
4313 (goto-char selected-point)
4314 (if (or (org-invisible-p) (org-invisible-p2))
4315 (org-show-context 'org-goto)))
4316 (message "Quit"))))
4318 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4319 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4320 (defvar org-goto-local-auto-isearch-map) ; defined below
4322 (defun org-get-location (buf help)
4323 "Let the user select a location in the Org-mode buffer BUF.
4324 This function uses a recursive edit. It returns the selected position
4325 or nil."
4326 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4327 (isearch-hide-immediately nil)
4328 (isearch-search-fun-function
4329 (lambda () 'org-goto-local-search-forward-headings))
4330 (org-goto-selected-point org-goto-exit-command))
4331 (save-excursion
4332 (save-window-excursion
4333 (delete-other-windows)
4334 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4335 (switch-to-buffer
4336 (condition-case nil
4337 (make-indirect-buffer (current-buffer) "*org-goto*")
4338 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4339 (with-output-to-temp-buffer "*Help*"
4340 (princ help))
4341 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4342 (setq buffer-read-only nil)
4343 (let ((org-startup-truncated t)
4344 (org-startup-folded nil)
4345 (org-startup-align-all-tables nil))
4346 (org-mode)
4347 (org-overview))
4348 (setq buffer-read-only t)
4349 (if (and (boundp 'org-goto-start-pos)
4350 (integer-or-marker-p org-goto-start-pos))
4351 (let ((org-show-hierarchy-above t)
4352 (org-show-siblings t)
4353 (org-show-following-heading t))
4354 (goto-char org-goto-start-pos)
4355 (and (org-invisible-p) (org-show-context)))
4356 (goto-char (point-min)))
4357 (org-beginning-of-line)
4358 (message "Select location and press RET")
4359 (use-local-map org-goto-map)
4360 (recursive-edit)
4362 (kill-buffer "*org-goto*")
4363 (cons org-goto-selected-point org-goto-exit-command)))
4365 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4366 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4367 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4368 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4370 (defun org-goto-local-search-forward-headings (string bound noerror)
4371 "Search and make sure that anu matches are in headlines."
4372 (catch 'return
4373 (while (search-forward string bound noerror)
4374 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4375 (and (member :headline context)
4376 (not (member :tags context))))
4377 (throw 'return (point))))))
4379 (defun org-goto-local-auto-isearch ()
4380 "Start isearch."
4381 (interactive)
4382 (goto-char (point-min))
4383 (let ((keys (this-command-keys)))
4384 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4385 (isearch-mode t)
4386 (isearch-process-search-char (string-to-char keys)))))
4388 (defun org-goto-ret (&optional arg)
4389 "Finish `org-goto' by going to the new location."
4390 (interactive "P")
4391 (setq org-goto-selected-point (point)
4392 org-goto-exit-command 'return)
4393 (throw 'exit nil))
4395 (defun org-goto-left ()
4396 "Finish `org-goto' by going to the new location."
4397 (interactive)
4398 (if (org-on-heading-p)
4399 (progn
4400 (beginning-of-line 1)
4401 (setq org-goto-selected-point (point)
4402 org-goto-exit-command 'left)
4403 (throw 'exit nil))
4404 (error "Not on a heading")))
4406 (defun org-goto-right ()
4407 "Finish `org-goto' by going to the new location."
4408 (interactive)
4409 (if (org-on-heading-p)
4410 (progn
4411 (setq org-goto-selected-point (point)
4412 org-goto-exit-command 'right)
4413 (throw 'exit nil))
4414 (error "Not on a heading")))
4416 (defun org-goto-quit ()
4417 "Finish `org-goto' without cursor motion."
4418 (interactive)
4419 (setq org-goto-selected-point nil)
4420 (setq org-goto-exit-command 'quit)
4421 (throw 'exit nil))
4423 ;;; Indirect buffer display of subtrees
4425 (defvar org-indirect-dedicated-frame nil
4426 "This is the frame being used for indirect tree display.")
4427 (defvar org-last-indirect-buffer nil)
4429 (defun org-tree-to-indirect-buffer (&optional arg)
4430 "Create indirect buffer and narrow it to current subtree.
4431 With numerical prefix ARG, go up to this level and then take that tree.
4432 If ARG is negative, go up that many levels.
4433 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4434 indirect buffer previously made with this command, to avoid proliferation of
4435 indirect buffers. However, when you call the command with a `C-u' prefix, or
4436 when `org-indirect-buffer-display' is `new-frame', the last buffer
4437 is kept so that you can work with several indirect buffers at the same time.
4438 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4439 requests that a new frame be made for the new buffer, so that the dedicated
4440 frame is not changed."
4441 (interactive "P")
4442 (let ((cbuf (current-buffer))
4443 (cwin (selected-window))
4444 (pos (point))
4445 beg end level heading ibuf)
4446 (save-excursion
4447 (org-back-to-heading t)
4448 (when (numberp arg)
4449 (setq level (org-outline-level))
4450 (if (< arg 0) (setq arg (+ level arg)))
4451 (while (> (setq level (org-outline-level)) arg)
4452 (outline-up-heading 1 t)))
4453 (setq beg (point)
4454 heading (org-get-heading))
4455 (org-end-of-subtree t) (setq end (point)))
4456 (if (and (buffer-live-p org-last-indirect-buffer)
4457 (not (eq org-indirect-buffer-display 'new-frame))
4458 (not arg))
4459 (kill-buffer org-last-indirect-buffer))
4460 (setq ibuf (org-get-indirect-buffer cbuf)
4461 org-last-indirect-buffer ibuf)
4462 (cond
4463 ((or (eq org-indirect-buffer-display 'new-frame)
4464 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4465 (select-frame (make-frame))
4466 (delete-other-windows)
4467 (switch-to-buffer ibuf)
4468 (org-set-frame-title heading))
4469 ((eq org-indirect-buffer-display 'dedicated-frame)
4470 (raise-frame
4471 (select-frame (or (and org-indirect-dedicated-frame
4472 (frame-live-p org-indirect-dedicated-frame)
4473 org-indirect-dedicated-frame)
4474 (setq org-indirect-dedicated-frame (make-frame)))))
4475 (delete-other-windows)
4476 (switch-to-buffer ibuf)
4477 (org-set-frame-title (concat "Indirect: " heading)))
4478 ((eq org-indirect-buffer-display 'current-window)
4479 (switch-to-buffer ibuf))
4480 ((eq org-indirect-buffer-display 'other-window)
4481 (pop-to-buffer ibuf))
4482 (t (error "Invalid value.")))
4483 (if (featurep 'xemacs)
4484 (save-excursion (org-mode) (turn-on-font-lock)))
4485 (narrow-to-region beg end)
4486 (show-all)
4487 (goto-char pos)
4488 (and (window-live-p cwin) (select-window cwin))))
4490 (defun org-get-indirect-buffer (&optional buffer)
4491 (setq buffer (or buffer (current-buffer)))
4492 (let ((n 1) (base (buffer-name buffer)) bname)
4493 (while (buffer-live-p
4494 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4495 (setq n (1+ n)))
4496 (condition-case nil
4497 (make-indirect-buffer buffer bname 'clone)
4498 (error (make-indirect-buffer buffer bname)))))
4500 (defun org-set-frame-title (title)
4501 "Set the title of the current frame to the string TITLE."
4502 ;; FIXME: how to name a single frame in XEmacs???
4503 (unless (featurep 'xemacs)
4504 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4506 ;;;; Structure editing
4508 ;;; Inserting headlines
4510 (defun org-insert-heading (&optional force-heading)
4511 "Insert a new heading or item with same depth at point.
4512 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4513 If point is at the beginning of a headline, insert a sibling before the
4514 current headline. If point is not at the beginning, do not split the line,
4515 but create the new hedline after the current line."
4516 (interactive "P")
4517 (if (= (buffer-size) 0)
4518 (insert "\n* ")
4519 (when (or force-heading (not (org-insert-item)))
4520 (let* ((head (save-excursion
4521 (condition-case nil
4522 (progn
4523 (org-back-to-heading)
4524 (match-string 0))
4525 (error "*"))))
4526 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4527 pos)
4528 (cond
4529 ((and (org-on-heading-p) (bolp)
4530 (or (bobp)
4531 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4532 ;; insert before the current line
4533 (open-line (if blank 2 1)))
4534 ((and (bolp)
4535 (or (bobp)
4536 (save-excursion
4537 (backward-char 1) (not (org-invisible-p)))))
4538 ;; insert right here
4539 nil)
4541 ;; in the middle of the line
4542 (org-show-entry)
4543 (let ((split
4544 (org-get-alist-option org-M-RET-may-split-line 'headline))
4545 tags pos)
4546 (if (org-on-heading-p)
4547 (progn
4548 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4549 (setq tags (and (match-end 2) (match-string 2)))
4550 (and (match-end 1)
4551 (delete-region (match-beginning 1) (match-end 1)))
4552 (setq pos (point-at-bol))
4553 (or split (end-of-line 1))
4554 (delete-horizontal-space)
4555 (newline (if blank 2 1))
4556 (when tags
4557 (save-excursion
4558 (goto-char pos)
4559 (end-of-line 1)
4560 (insert " " tags)
4561 (org-set-tags nil 'align))))
4562 (or split (end-of-line 1))
4563 (newline (if blank 2 1))))))
4564 (insert head) (just-one-space)
4565 (setq pos (point))
4566 (end-of-line 1)
4567 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4568 (run-hooks 'org-insert-heading-hook)))))
4570 (defun org-get-heading (&optional no-tags)
4571 "Return the heading of the current entry, without the stars."
4572 (save-excursion
4573 (org-back-to-heading t)
4574 (if (looking-at
4575 (if no-tags
4576 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4577 "\\*+[ \t]+\\([^\r\n]*\\)"))
4578 (match-string 1) "")))
4580 (defun org-insert-heading-after-current ()
4581 "Insert a new heading with same level as current, after current subtree."
4582 (interactive)
4583 (org-back-to-heading)
4584 (org-insert-heading)
4585 (org-move-subtree-down)
4586 (end-of-line 1))
4588 (defun org-insert-todo-heading (arg)
4589 "Insert a new heading with the same level and TODO state as current heading.
4590 If the heading has no TODO state, or if the state is DONE, use the first
4591 state (TODO by default). Also with prefix arg, force first state."
4592 (interactive "P")
4593 (when (not (org-insert-item 'checkbox))
4594 (org-insert-heading)
4595 (save-excursion
4596 (org-back-to-heading)
4597 (outline-previous-heading)
4598 (looking-at org-todo-line-regexp))
4599 (if (or arg
4600 (not (match-beginning 2))
4601 (member (match-string 2) org-done-keywords))
4602 (insert (car org-todo-keywords-1) " ")
4603 (insert (match-string 2) " "))
4604 (when org-provide-todo-statistics
4605 (org-update-parent-todo-statistics))))
4607 (defun org-insert-subheading (arg)
4608 "Insert a new subheading and demote it.
4609 Works for outline headings and for plain lists alike."
4610 (interactive "P")
4611 (org-insert-heading arg)
4612 (cond
4613 ((org-on-heading-p) (org-do-demote))
4614 ((org-at-item-p) (org-indent-item 1))))
4616 (defun org-insert-todo-subheading (arg)
4617 "Insert a new subheading with TODO keyword or checkbox and demote it.
4618 Works for outline headings and for plain lists alike."
4619 (interactive "P")
4620 (org-insert-todo-heading arg)
4621 (cond
4622 ((org-on-heading-p) (org-do-demote))
4623 ((org-at-item-p) (org-indent-item 1))))
4625 ;;; Promotion and Demotion
4627 (defun org-promote-subtree ()
4628 "Promote the entire subtree.
4629 See also `org-promote'."
4630 (interactive)
4631 (save-excursion
4632 (org-map-tree 'org-promote))
4633 (org-fix-position-after-promote))
4635 (defun org-demote-subtree ()
4636 "Demote the entire subtree. See `org-demote'.
4637 See also `org-promote'."
4638 (interactive)
4639 (save-excursion
4640 (org-map-tree 'org-demote))
4641 (org-fix-position-after-promote))
4644 (defun org-do-promote ()
4645 "Promote the current heading higher up the tree.
4646 If the region is active in `transient-mark-mode', promote all headings
4647 in the region."
4648 (interactive)
4649 (save-excursion
4650 (if (org-region-active-p)
4651 (org-map-region 'org-promote (region-beginning) (region-end))
4652 (org-promote)))
4653 (org-fix-position-after-promote))
4655 (defun org-do-demote ()
4656 "Demote the current heading lower down the tree.
4657 If the region is active in `transient-mark-mode', demote all headings
4658 in the region."
4659 (interactive)
4660 (save-excursion
4661 (if (org-region-active-p)
4662 (org-map-region 'org-demote (region-beginning) (region-end))
4663 (org-demote)))
4664 (org-fix-position-after-promote))
4666 (defun org-fix-position-after-promote ()
4667 "Make sure that after pro/demotion cursor position is right."
4668 (let ((pos (point)))
4669 (when (save-excursion
4670 (beginning-of-line 1)
4671 (looking-at org-todo-line-regexp)
4672 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4673 (cond ((eobp) (insert " "))
4674 ((eolp) (insert " "))
4675 ((equal (char-after) ?\ ) (forward-char 1))))))
4677 (defun org-reduced-level (l)
4678 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4680 (defun org-get-valid-level (level &optional change)
4681 "Rectify a level change under the influence of `org-odd-levels-only'
4682 LEVEL is a current level, CHANGE is by how much the level should be
4683 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4684 even level numbers will become the next higher odd number."
4685 (if org-odd-levels-only
4686 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4687 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4688 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4689 (max 1 (+ level change))))
4691 (if (boundp 'define-obsolete-function-alias)
4692 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4693 (define-obsolete-function-alias 'org-get-legal-level
4694 'org-get-valid-level)
4695 (define-obsolete-function-alias 'org-get-legal-level
4696 'org-get-valid-level "23.1")))
4698 (defun org-promote ()
4699 "Promote the current heading higher up the tree.
4700 If the region is active in `transient-mark-mode', promote all headings
4701 in the region."
4702 (org-back-to-heading t)
4703 (let* ((level (save-match-data (funcall outline-level)))
4704 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4705 (diff (abs (- level (length up-head) -1))))
4706 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4707 (replace-match up-head nil t)
4708 ;; Fixup tag positioning
4709 (and org-auto-align-tags (org-set-tags nil t))
4710 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4712 (defun org-demote ()
4713 "Demote the current heading lower down the tree.
4714 If the region is active in `transient-mark-mode', demote all headings
4715 in the region."
4716 (org-back-to-heading t)
4717 (let* ((level (save-match-data (funcall outline-level)))
4718 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4719 (diff (abs (- level (length down-head) -1))))
4720 (replace-match down-head nil t)
4721 ;; Fixup tag positioning
4722 (and org-auto-align-tags (org-set-tags nil t))
4723 (if org-adapt-indentation (org-fixup-indentation diff))))
4725 (defun org-map-tree (fun)
4726 "Call FUN for every heading underneath the current one."
4727 (org-back-to-heading)
4728 (let ((level (funcall outline-level)))
4729 (save-excursion
4730 (funcall fun)
4731 (while (and (progn
4732 (outline-next-heading)
4733 (> (funcall outline-level) level))
4734 (not (eobp)))
4735 (funcall fun)))))
4737 (defun org-map-region (fun beg end)
4738 "Call FUN for every heading between BEG and END."
4739 (let ((org-ignore-region t))
4740 (save-excursion
4741 (setq end (copy-marker end))
4742 (goto-char beg)
4743 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4744 (< (point) end))
4745 (funcall fun))
4746 (while (and (progn
4747 (outline-next-heading)
4748 (< (point) end))
4749 (not (eobp)))
4750 (funcall fun)))))
4752 (defun org-fixup-indentation (diff)
4753 "Change the indentation in the current entry by DIFF
4754 However, if any line in the current entry has no indentation, or if it
4755 would end up with no indentation after the change, nothing at all is done."
4756 (save-excursion
4757 (let ((end (save-excursion (outline-next-heading)
4758 (point-marker)))
4759 (prohibit (if (> diff 0)
4760 "^\\S-"
4761 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4762 col)
4763 (unless (save-excursion (end-of-line 1)
4764 (re-search-forward prohibit end t))
4765 (while (and (< (point) end)
4766 (re-search-forward "^[ \t]+" end t))
4767 (goto-char (match-end 0))
4768 (setq col (current-column))
4769 (if (< diff 0) (replace-match ""))
4770 (indent-to (+ diff col))))
4771 (move-marker end nil))))
4773 (defun org-convert-to-odd-levels ()
4774 "Convert an org-mode file with all levels allowed to one with odd levels.
4775 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4776 level 5 etc."
4777 (interactive)
4778 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4779 (let ((org-odd-levels-only nil) n)
4780 (save-excursion
4781 (goto-char (point-min))
4782 (while (re-search-forward "^\\*\\*+ " nil t)
4783 (setq n (- (length (match-string 0)) 2))
4784 (while (>= (setq n (1- n)) 0)
4785 (org-demote))
4786 (end-of-line 1))))))
4789 (defun org-convert-to-oddeven-levels ()
4790 "Convert an org-mode file with only odd levels to one with odd and even levels.
4791 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4792 section with an even level, conversion would destroy the structure of the file. An error
4793 is signaled in this case."
4794 (interactive)
4795 (goto-char (point-min))
4796 ;; First check if there are no even levels
4797 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4798 (org-show-context t)
4799 (error "Not all levels are odd in this file. Conversion not possible."))
4800 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4801 (let ((org-odd-levels-only nil) n)
4802 (save-excursion
4803 (goto-char (point-min))
4804 (while (re-search-forward "^\\*\\*+ " nil t)
4805 (setq n (/ (1- (length (match-string 0))) 2))
4806 (while (>= (setq n (1- n)) 0)
4807 (org-promote))
4808 (end-of-line 1))))))
4810 (defun org-tr-level (n)
4811 "Make N odd if required."
4812 (if org-odd-levels-only (1+ (/ n 2)) n))
4814 ;;; Vertical tree motion, cutting and pasting of subtrees
4816 (defun org-move-subtree-up (&optional arg)
4817 "Move the current subtree up past ARG headlines of the same level."
4818 (interactive "p")
4819 (org-move-subtree-down (- (prefix-numeric-value arg))))
4821 (defun org-move-subtree-down (&optional arg)
4822 "Move the current subtree down past ARG headlines of the same level."
4823 (interactive "p")
4824 (setq arg (prefix-numeric-value arg))
4825 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4826 'outline-get-last-sibling))
4827 (ins-point (make-marker))
4828 (cnt (abs arg))
4829 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4830 ;; Select the tree
4831 (org-back-to-heading)
4832 (setq beg0 (point))
4833 (save-excursion
4834 (setq ne-beg (org-back-over-empty-lines))
4835 (setq beg (point)))
4836 (save-match-data
4837 (save-excursion (outline-end-of-heading)
4838 (setq folded (org-invisible-p)))
4839 (outline-end-of-subtree))
4840 (outline-next-heading)
4841 (setq ne-end (org-back-over-empty-lines))
4842 (setq end (point))
4843 (goto-char beg0)
4844 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4845 ;; include less whitespace
4846 (save-excursion
4847 (goto-char beg)
4848 (forward-line (- ne-beg ne-end))
4849 (setq beg (point))))
4850 ;; Find insertion point, with error handling
4851 (while (> cnt 0)
4852 (or (and (funcall movfunc) (looking-at outline-regexp))
4853 (progn (goto-char beg0)
4854 (error "Cannot move past superior level or buffer limit")))
4855 (setq cnt (1- cnt)))
4856 (if (> arg 0)
4857 ;; Moving forward - still need to move over subtree
4858 (progn (org-end-of-subtree t t)
4859 (save-excursion
4860 (org-back-over-empty-lines)
4861 (or (bolp) (newline)))))
4862 (setq ne-ins (org-back-over-empty-lines))
4863 (move-marker ins-point (point))
4864 (setq txt (buffer-substring beg end))
4865 (org-save-markers-in-region beg end)
4866 (delete-region beg end)
4867 (outline-flag-region (1- beg) beg nil)
4868 (outline-flag-region (1- (point)) (point) nil)
4869 (let ((bbb (point)))
4870 (insert-before-markers txt)
4871 (org-reinstall-markers-in-region bbb)
4872 (move-marker ins-point bbb))
4873 (or (bolp) (insert "\n"))
4874 (setq ins-end (point))
4875 (goto-char ins-point)
4876 (org-skip-whitespace)
4877 (when (and (< arg 0)
4878 (org-first-sibling-p)
4879 (> ne-ins ne-beg))
4880 ;; Move whitespace back to beginning
4881 (save-excursion
4882 (goto-char ins-end)
4883 (let ((kill-whole-line t))
4884 (kill-line (- ne-ins ne-beg)) (point)))
4885 (insert (make-string (- ne-ins ne-beg) ?\n)))
4886 (move-marker ins-point nil)
4887 (org-compact-display-after-subtree-move)
4888 (unless folded
4889 (org-show-entry)
4890 (show-children)
4891 (org-cycle-hide-drawers 'children))))
4893 (defvar org-subtree-clip ""
4894 "Clipboard for cut and paste of subtrees.
4895 This is actually only a copy of the kill, because we use the normal kill
4896 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4898 (defvar org-subtree-clip-folded nil
4899 "Was the last copied subtree folded?
4900 This is used to fold the tree back after pasting.")
4902 (defun org-cut-subtree (&optional n)
4903 "Cut the current subtree into the clipboard.
4904 With prefix arg N, cut this many sequential subtrees.
4905 This is a short-hand for marking the subtree and then cutting it."
4906 (interactive "p")
4907 (org-copy-subtree n 'cut))
4909 (defun org-copy-subtree (&optional n cut force-store-markers)
4910 "Cut the current subtree into the clipboard.
4911 With prefix arg N, cut this many sequential subtrees.
4912 This is a short-hand for marking the subtree and then copying it.
4913 If CUT is non-nil, actually cut the subtree.
4914 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4915 of some markers in the region, even if CUT is non-nil. This is
4916 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4917 (interactive "p")
4918 (let (beg end folded (beg0 (point)))
4919 (if (interactive-p)
4920 (org-back-to-heading nil) ; take what looks like a subtree
4921 (org-back-to-heading t)) ; take what is really there
4922 (org-back-over-empty-lines)
4923 (setq beg (point))
4924 (skip-chars-forward " \t\r\n")
4925 (save-match-data
4926 (save-excursion (outline-end-of-heading)
4927 (setq folded (org-invisible-p)))
4928 (condition-case nil
4929 (outline-forward-same-level (1- n))
4930 (error nil))
4931 (org-end-of-subtree t t))
4932 (org-back-over-empty-lines)
4933 (setq end (point))
4934 (goto-char beg0)
4935 (when (> end beg)
4936 (setq org-subtree-clip-folded folded)
4937 (when (or cut force-store-markers)
4938 (org-save-markers-in-region beg end))
4939 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4940 (setq org-subtree-clip (current-kill 0))
4941 (message "%s: Subtree(s) with %d characters"
4942 (if cut "Cut" "Copied")
4943 (length org-subtree-clip)))))
4945 (defun org-paste-subtree (&optional level tree)
4946 "Paste the clipboard as a subtree, with modification of headline level.
4947 The entire subtree is promoted or demoted in order to match a new headline
4948 level. By default, the new level is derived from the visible headings
4949 before and after the insertion point, and taken to be the inferior headline
4950 level of the two. So if the previous visible heading is level 3 and the
4951 next is level 4 (or vice versa), level 4 will be used for insertion.
4952 This makes sure that the subtree remains an independent subtree and does
4953 not swallow low level entries.
4955 You can also force a different level, either by using a numeric prefix
4956 argument, or by inserting the heading marker by hand. For example, if the
4957 cursor is after \"*****\", then the tree will be shifted to level 5.
4959 If you want to insert the tree as is, just use \\[yank].
4961 If optional TREE is given, use this text instead of the kill ring."
4962 (interactive "P")
4963 (unless (org-kill-is-subtree-p tree)
4964 (error "%s"
4965 (substitute-command-keys
4966 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4967 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4968 (^re (concat "^\\(" outline-regexp "\\)"))
4969 (re (concat "\\(" outline-regexp "\\)"))
4970 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4972 (old-level (if (string-match ^re txt)
4973 (- (match-end 0) (match-beginning 0) 1)
4974 -1))
4975 (force-level (cond (level (prefix-numeric-value level))
4976 ((string-match
4977 ^re_ (buffer-substring (point-at-bol) (point)))
4978 (- (match-end 1) (match-beginning 1)))
4979 (t nil)))
4980 (previous-level (save-excursion
4981 (condition-case nil
4982 (progn
4983 (outline-previous-visible-heading 1)
4984 (if (looking-at re)
4985 (- (match-end 0) (match-beginning 0) 1)
4987 (error 1))))
4988 (next-level (save-excursion
4989 (condition-case nil
4990 (progn
4991 (or (looking-at outline-regexp)
4992 (outline-next-visible-heading 1))
4993 (if (looking-at re)
4994 (- (match-end 0) (match-beginning 0) 1)
4996 (error 1))))
4997 (new-level (or force-level (max previous-level next-level)))
4998 (shift (if (or (= old-level -1)
4999 (= new-level -1)
5000 (= old-level new-level))
5002 (- new-level old-level)))
5003 (delta (if (> shift 0) -1 1))
5004 (func (if (> shift 0) 'org-demote 'org-promote))
5005 (org-odd-levels-only nil)
5006 beg end)
5007 ;; Remove the forced level indicator
5008 (if force-level
5009 (delete-region (point-at-bol) (point)))
5010 ;; Paste
5011 (beginning-of-line 1)
5012 (org-back-over-empty-lines)
5013 (setq beg (point))
5014 (insert-before-markers txt)
5015 (unless (string-match "\n\\'" txt) (insert "\n"))
5016 (org-reinstall-markers-in-region beg)
5017 (setq end (point))
5018 (goto-char beg)
5019 (skip-chars-forward " \t\n\r")
5020 (setq beg (point))
5021 ;; Shift if necessary
5022 (unless (= shift 0)
5023 (save-restriction
5024 (narrow-to-region beg end)
5025 (while (not (= shift 0))
5026 (org-map-region func (point-min) (point-max))
5027 (setq shift (+ delta shift)))
5028 (goto-char (point-min))))
5029 (when (interactive-p)
5030 (message "Clipboard pasted as level %d subtree" new-level))
5031 (if (and kill-ring
5032 (eq org-subtree-clip (current-kill 0))
5033 org-subtree-clip-folded)
5034 ;; The tree was folded before it was killed/copied
5035 (hide-subtree))))
5037 (defun org-kill-is-subtree-p (&optional txt)
5038 "Check if the current kill is an outline subtree, or a set of trees.
5039 Returns nil if kill does not start with a headline, or if the first
5040 headline level is not the largest headline level in the tree.
5041 So this will actually accept several entries of equal levels as well,
5042 which is OK for `org-paste-subtree'.
5043 If optional TXT is given, check this string instead of the current kill."
5044 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5045 (start-level (and kill
5046 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5047 org-outline-regexp "\\)")
5048 kill)
5049 (- (match-end 2) (match-beginning 2) 1)))
5050 (re (concat "^" org-outline-regexp))
5051 (start (1+ (match-beginning 2))))
5052 (if (not start-level)
5053 (progn
5054 nil) ;; does not even start with a heading
5055 (catch 'exit
5056 (while (setq start (string-match re kill (1+ start)))
5057 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5058 (throw 'exit nil)))
5059 t))))
5061 (defvar org-markers-to-move nil
5062 "Markers that should be moved with a cut-and-paste operation.
5063 Those markers are stored together with their positions relative to
5064 the start of the region.")
5066 (defun org-save-markers-in-region (beg end)
5067 "Check markers in region.
5068 If these markers are between BEG and END, record their position relative
5069 to BEG, so that after moving the block of text, we can put the markers back
5070 into place.
5071 This function gets called just before an entry or tree gets cut from the
5072 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5073 called immediately, to move the markers with the entries."
5074 (setq org-markers-to-move nil)
5075 (when (featurep 'org-clock)
5076 (org-clock-save-markers-for-cut-and-paste beg end))
5077 (when (featurep 'org-agenda)
5078 (org-agenda-save-markers-for-cut-and-paste beg end)))
5080 (defun org-check-and-save-marker (marker beg end)
5081 "Check if MARKER is between BEG and END.
5082 If yes, remember the marker and the distance to BEG."
5083 (when (and (marker-buffer marker)
5084 (equal (marker-buffer marker) (current-buffer)))
5085 (if (and (>= marker beg) (< marker end))
5086 (push (cons marker (- marker beg)) org-markers-to-move))))
5088 (defun org-reinstall-markers-in-region (beg)
5089 "Move all remembered markers to their position relative to BEG."
5090 (mapc (lambda (x)
5091 (move-marker (car x) (+ beg (cdr x))))
5092 org-markers-to-move)
5093 (setq org-markers-to-move nil))
5095 (defun org-narrow-to-subtree ()
5096 "Narrow buffer to the current subtree."
5097 (interactive)
5098 (save-excursion
5099 (save-match-data
5100 (narrow-to-region
5101 (progn (org-back-to-heading) (point))
5102 (progn (org-end-of-subtree t t) (point))))))
5105 ;;; Outline Sorting
5107 (defun org-sort (with-case)
5108 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5109 Optional argument WITH-CASE means sort case-sensitively."
5110 (interactive "P")
5111 (if (org-at-table-p)
5112 (org-call-with-arg 'org-table-sort-lines with-case)
5113 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5115 (defun org-sort-remove-invisible (s)
5116 (remove-text-properties 0 (length s) org-rm-props s)
5117 (while (string-match org-bracket-link-regexp s)
5118 (setq s (replace-match (if (match-end 2)
5119 (match-string 3 s)
5120 (match-string 1 s)) t t s)))
5123 (defvar org-priority-regexp) ; defined later in the file
5125 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5126 "Sort entries on a certain level of an outline tree.
5127 If there is an active region, the entries in the region are sorted.
5128 Else, if the cursor is before the first entry, sort the top-level items.
5129 Else, the children of the entry at point are sorted.
5131 Sorting can be alphabetically, numerically, and by date/time as given by
5132 the first time stamp in the entry. The command prompts for the sorting
5133 type unless it has been given to the function through the SORTING-TYPE
5134 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5135 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5136 called with point at the beginning of the record. It must return either
5137 a string or a number that should serve as the sorting key for that record.
5139 Comparing entries ignores case by default. However, with an optional argument
5140 WITH-CASE, the sorting considers case as well."
5141 (interactive "P")
5142 (let ((case-func (if with-case 'identity 'downcase))
5143 start beg end stars re re2
5144 txt what tmp plain-list-p)
5145 ;; Find beginning and end of region to sort
5146 (cond
5147 ((org-region-active-p)
5148 ;; we will sort the region
5149 (setq end (region-end)
5150 what "region")
5151 (goto-char (region-beginning))
5152 (if (not (org-on-heading-p)) (outline-next-heading))
5153 (setq start (point)))
5154 ((org-at-item-p)
5155 ;; we will sort this plain list
5156 (org-beginning-of-item-list) (setq start (point))
5157 (org-end-of-item-list) (setq end (point))
5158 (goto-char start)
5159 (setq plain-list-p t
5160 what "plain list"))
5161 ((or (org-on-heading-p)
5162 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5163 ;; we will sort the children of the current headline
5164 (org-back-to-heading)
5165 (setq start (point)
5166 end (progn (org-end-of-subtree t t)
5167 (org-back-over-empty-lines)
5168 (point))
5169 what "children")
5170 (goto-char start)
5171 (show-subtree)
5172 (outline-next-heading))
5174 ;; we will sort the top-level entries in this file
5175 (goto-char (point-min))
5176 (or (org-on-heading-p) (outline-next-heading))
5177 (setq start (point) end (point-max) what "top-level")
5178 (goto-char start)
5179 (show-all)))
5181 (setq beg (point))
5182 (if (>= beg end) (error "Nothing to sort"))
5184 (unless plain-list-p
5185 (looking-at "\\(\\*+\\)")
5186 (setq stars (match-string 1)
5187 re (concat "^" (regexp-quote stars) " +")
5188 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5189 txt (buffer-substring beg end))
5190 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5191 (if (and (not (equal stars "*")) (string-match re2 txt))
5192 (error "Region to sort contains a level above the first entry")))
5194 (unless sorting-type
5195 (message
5196 (if plain-list-p
5197 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5198 "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:")
5199 what)
5200 (setq sorting-type (read-char-exclusive))
5202 (and (= (downcase sorting-type) ?f)
5203 (setq getkey-func
5204 (completing-read "Sort using function: "
5205 obarray 'fboundp t nil nil))
5206 (setq getkey-func (intern getkey-func)))
5208 (and (= (downcase sorting-type) ?r)
5209 (setq property
5210 (completing-read "Property: "
5211 (mapcar 'list (org-buffer-property-keys t))
5212 nil t))))
5214 (message "Sorting entries...")
5216 (save-restriction
5217 (narrow-to-region start end)
5219 (let ((dcst (downcase sorting-type))
5220 (now (current-time)))
5221 (sort-subr
5222 (/= dcst sorting-type)
5223 ;; This function moves to the beginning character of the "record" to
5224 ;; be sorted.
5225 (if plain-list-p
5226 (lambda nil
5227 (if (org-at-item-p) t (goto-char (point-max))))
5228 (lambda nil
5229 (if (re-search-forward re nil t)
5230 (goto-char (match-beginning 0))
5231 (goto-char (point-max)))))
5232 ;; This function moves to the last character of the "record" being
5233 ;; sorted.
5234 (if plain-list-p
5235 'org-end-of-item
5236 (lambda nil
5237 (save-match-data
5238 (condition-case nil
5239 (outline-forward-same-level 1)
5240 (error
5241 (goto-char (point-max)))))))
5243 ;; This function returns the value that gets sorted against.
5244 (if plain-list-p
5245 (lambda nil
5246 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5247 (cond
5248 ((= dcst ?n)
5249 (string-to-number (buffer-substring (match-end 0)
5250 (point-at-eol))))
5251 ((= dcst ?a)
5252 (buffer-substring (match-end 0) (point-at-eol)))
5253 ((= dcst ?t)
5254 (if (re-search-forward org-ts-regexp
5255 (point-at-eol) t)
5256 (org-time-string-to-time (match-string 0))
5257 now))
5258 ((= dcst ?f)
5259 (if getkey-func
5260 (progn
5261 (setq tmp (funcall getkey-func))
5262 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5263 tmp)
5264 (error "Invalid key function `%s'" getkey-func)))
5265 (t (error "Invalid sorting type `%c'" sorting-type)))))
5266 (lambda nil
5267 (cond
5268 ((= dcst ?n)
5269 (if (looking-at outline-regexp)
5270 (string-to-number (buffer-substring (match-end 0)
5271 (point-at-eol)))
5272 nil))
5273 ((= dcst ?a)
5274 (funcall case-func (buffer-substring (point-at-bol)
5275 (point-at-eol))))
5276 ((= dcst ?t)
5277 (if (re-search-forward org-ts-regexp
5278 (save-excursion
5279 (forward-line 2)
5280 (point)) t)
5281 (org-time-string-to-time (match-string 0))
5282 now))
5283 ((= dcst ?p)
5284 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5285 (string-to-char (match-string 2))
5286 org-default-priority))
5287 ((= dcst ?r)
5288 (or (org-entry-get nil property) ""))
5289 ((= dcst ?o)
5290 (if (looking-at org-complex-heading-regexp)
5291 (- 9999 (length (member (match-string 2)
5292 org-todo-keywords-1)))))
5293 ((= dcst ?f)
5294 (if getkey-func
5295 (progn
5296 (setq tmp (funcall getkey-func))
5297 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5298 tmp)
5299 (error "Invalid key function `%s'" getkey-func)))
5300 (t (error "Invalid sorting type `%c'" sorting-type)))))
5302 (cond
5303 ((= dcst ?a) 'string<)
5304 ((= dcst ?t) 'time-less-p)
5305 (t nil)))))
5306 (message "Sorting entries...done")))
5308 (defun org-do-sort (table what &optional with-case sorting-type)
5309 "Sort TABLE of WHAT according to SORTING-TYPE.
5310 The user will be prompted for the SORTING-TYPE if the call to this
5311 function does not specify it. WHAT is only for the prompt, to indicate
5312 what is being sorted. The sorting key will be extracted from
5313 the car of the elements of the table.
5314 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5315 (unless sorting-type
5316 (message
5317 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5318 what)
5319 (setq sorting-type (read-char-exclusive)))
5320 (let ((dcst (downcase sorting-type))
5321 extractfun comparefun)
5322 ;; Define the appropriate functions
5323 (cond
5324 ((= dcst ?n)
5325 (setq extractfun 'string-to-number
5326 comparefun (if (= dcst sorting-type) '< '>)))
5327 ((= dcst ?a)
5328 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5329 (lambda(x) (downcase (org-sort-remove-invisible x))))
5330 comparefun (if (= dcst sorting-type)
5331 'string<
5332 (lambda (a b) (and (not (string< a b))
5333 (not (string= a b)))))))
5334 ((= dcst ?t)
5335 (setq extractfun
5336 (lambda (x)
5337 (if (string-match org-ts-regexp x)
5338 (time-to-seconds
5339 (org-time-string-to-time (match-string 0 x)))
5341 comparefun (if (= dcst sorting-type) '< '>)))
5342 (t (error "Invalid sorting type `%c'" sorting-type)))
5344 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5345 table)
5346 (lambda (a b) (funcall comparefun (car a) (car b))))))
5348 ;;; Editing source examples
5350 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5351 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5352 (defvar org-edit-src-force-single-line nil)
5353 (defvar org-edit-src-from-org-mode nil)
5355 (define-minor-mode org-exit-edit-mode
5356 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5358 (defun org-edit-src-code ()
5359 "Edit the source code example at point.
5360 An indirect buffer is created, and that buffer is then narrowed to the
5361 example at point and switched to the correct language mode. When done,
5362 exit by killing the buffer with \\[org-edit-src-exit]."
5363 (interactive)
5364 (let ((line (org-current-line))
5365 (case-fold-search t)
5366 (msg (substitute-command-keys
5367 "Edit, then exit with C-c ' (C-c and single quote)"))
5368 (info (org-edit-src-find-region-and-lang))
5369 (org-mode-p (eq major-mode 'org-mode))
5370 beg end lang lang-f single)
5371 (if (not info)
5373 (setq beg (nth 0 info)
5374 end (nth 1 info)
5375 lang (nth 2 info)
5376 single (nth 3 info)
5377 lang-f (intern (concat lang "-mode")))
5378 (unless (functionp lang-f)
5379 (error "No such language mode: %s" lang-f))
5380 (goto-line line)
5381 (if (get-buffer "*Org Edit Src Example*")
5382 (kill-buffer "*Org Edit Src Example*"))
5383 (switch-to-buffer (make-indirect-buffer (current-buffer)
5384 "*Org Edit Src Example*"))
5385 (narrow-to-region beg end)
5386 (remove-text-properties beg end '(display nil invisible nil
5387 intangible nil))
5388 (let ((org-inhibit-startup t))
5389 (funcall lang-f))
5390 (set (make-local-variable 'org-edit-src-force-single-line) single)
5391 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5392 (when org-mode-p
5393 (goto-char (point-min))
5394 (while (re-search-forward "^," nil t)
5395 (replace-match "")))
5396 (goto-line line)
5397 (org-exit-edit-mode)
5398 (org-set-local 'header-line-format msg)
5399 (message "%s" msg)
5400 t)))
5402 (defun org-edit-src-find-region-and-lang ()
5403 "Find the region and language for a local edit.
5404 Return a list with beginning and end of the region, a string representing
5405 the language, a switch telling of the content should be in a single line."
5406 (let ((re-list
5408 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5409 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5410 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5411 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5412 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5413 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5414 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5415 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5416 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5417 ("^#\\+html:" "\n" "html" single-line)
5418 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5419 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5420 ("^#\\+latex:" "\n" "latex" single-line)
5421 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5422 ("^#\\+ascii:" "\n" "ascii" single-line)
5424 (pos (point))
5425 re re1 re2 single beg end lang)
5426 (catch 'exit
5427 (while (setq entry (pop re-list))
5428 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5429 single (nth 3 entry))
5430 (save-excursion
5431 (if (or (looking-at re1)
5432 (re-search-backward re1 nil t))
5433 (progn
5434 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5435 (if (and (re-search-forward re2 nil t)
5436 (>= (match-end 0) pos))
5437 (throw 'exit (list beg (match-beginning 0) lang single))))
5438 (if (or (looking-at re2)
5439 (re-search-forward re2 nil t))
5440 (progn
5441 (setq end (match-beginning 0))
5442 (if (and (re-search-backward re1 nil t)
5443 (<= (match-beginning 0) pos))
5444 (throw 'exit
5445 (list (match-end 0) end
5446 (org-edit-src-get-lang lang) single)))))))))))
5448 (defun org-edit-src-get-lang (lang)
5449 "Extract the src language."
5450 (let ((m (match-string 0)))
5451 (cond
5452 ((stringp lang) lang)
5453 ((integerp lang) (match-string lang))
5454 ((and (eq lang lang)
5455 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5456 (match-string 1 m))
5457 ((and (eq lang lang)
5458 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5459 (match-string 1 m))
5460 (t "fundamental"))))
5462 (defun org-edit-src-exit ()
5463 "Exit special edit and protect problematic lines."
5464 (interactive)
5465 (unless (buffer-base-buffer (current-buffer))
5466 (error "This is not an indirect buffer, something is wrong..."))
5467 (unless (> (point-min) 1)
5468 (error "This buffer is not narrowed, something is wrong..."))
5469 (goto-char (point-min))
5470 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5471 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5472 (when (org-bound-and-true-p org-edit-src-force-single-line)
5473 (goto-char (point-min))
5474 (while (re-search-forward "\n" nil t)
5475 (replace-match " "))
5476 (goto-char (point-min))
5477 (if (looking-at "\\s-*") (replace-match " "))
5478 (if (re-search-forward "\\s-+\\'" nil t)
5479 (replace-match "")))
5480 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5481 (goto-char (point-min))
5482 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5483 (replace-match ",\\1"))
5484 (when font-lock-mode
5485 (font-lock-unfontify-region (point-min) (point-max)))
5486 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5487 (kill-buffer (current-buffer)))
5489 ;;;; Plain list items, including checkboxes
5491 ;;; Plain list items
5493 (defun org-at-item-p ()
5494 "Is point in a line starting a hand-formatted item?"
5495 (let ((llt org-plain-list-ordered-item-terminator))
5496 (save-excursion
5497 (goto-char (point-at-bol))
5498 (looking-at
5499 (cond
5500 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5501 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5502 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5503 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5505 (defun org-in-item-p ()
5506 "It the cursor inside a plain list item.
5507 Does not have to be the first line."
5508 (save-excursion
5509 (condition-case nil
5510 (progn
5511 (org-beginning-of-item)
5512 (org-at-item-p)
5514 (error nil))))
5516 (defun org-insert-item (&optional checkbox)
5517 "Insert a new item at the current level.
5518 Return t when things worked, nil when we are not in an item."
5519 (when (save-excursion
5520 (condition-case nil
5521 (progn
5522 (org-beginning-of-item)
5523 (org-at-item-p)
5524 (if (org-invisible-p) (error "Invisible item"))
5526 (error nil)))
5527 (let* ((bul (match-string 0))
5528 (descp (save-excursion (goto-char (match-beginning 0))
5529 (beginning-of-line 1)
5530 (save-match-data
5531 (looking-at "[ \t]*.*? ::"))))
5532 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5533 (match-end 0)))
5534 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5535 pos)
5536 (if descp (setq checkbox nil))
5537 (cond
5538 ((and (org-at-item-p) (<= (point) eow))
5539 ;; before the bullet
5540 (beginning-of-line 1)
5541 (open-line (if blank 2 1)))
5542 ((<= (point) eow)
5543 (beginning-of-line 1))
5545 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5546 (end-of-line 1)
5547 (delete-horizontal-space))
5548 (newline (if blank 2 1))))
5549 (insert bul
5550 (if checkbox "[ ]" "")
5551 (if descp (concat (if checkbox " " "")
5552 (read-string "Term: ") " :: ") ""))
5553 (just-one-space)
5554 (setq pos (point))
5555 (end-of-line 1)
5556 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5557 (org-maybe-renumber-ordered-list)
5558 (and checkbox (org-update-checkbox-count-maybe))
5561 ;;; Checkboxes
5563 (defun org-at-item-checkbox-p ()
5564 "Is point at a line starting a plain-list item with a checklet?"
5565 (and (org-at-item-p)
5566 (save-excursion
5567 (goto-char (match-end 0))
5568 (skip-chars-forward " \t")
5569 (looking-at "\\[[- X]\\]"))))
5571 (defun org-toggle-checkbox (&optional arg)
5572 "Toggle the checkbox in the current line."
5573 (interactive "P")
5574 (catch 'exit
5575 (let (beg end status (firstnew 'unknown))
5576 (cond
5577 ((org-region-active-p)
5578 (setq beg (region-beginning) end (region-end)))
5579 ((org-on-heading-p)
5580 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5581 ((org-at-item-checkbox-p)
5582 (let ((pos (point)))
5583 (replace-match
5584 (cond (arg "[-]")
5585 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5586 (t "[ ]"))
5587 t t)
5588 (goto-char pos))
5589 (throw 'exit t))
5590 (t (error "Not at a checkbox or heading, and no active region")))
5591 (save-excursion
5592 (goto-char beg)
5593 (while (< (point) end)
5594 (when (org-at-item-checkbox-p)
5595 (setq status (equal (match-string 0) "[X]"))
5596 (when (eq firstnew 'unknown)
5597 (setq firstnew (not status)))
5598 (replace-match
5599 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5600 (beginning-of-line 2)))))
5601 (org-update-checkbox-count-maybe))
5603 (defun org-update-checkbox-count-maybe ()
5604 "Update checkbox statistics unless turned off by user."
5605 (when org-provide-checkbox-statistics
5606 (org-update-checkbox-count)))
5608 (defun org-update-checkbox-count (&optional all)
5609 "Update the checkbox statistics in the current section.
5610 This will find all statistic cookies like [57%] and [6/12] and update them
5611 with the current numbers. With optional prefix argument ALL, do this for
5612 the whole buffer."
5613 (interactive "P")
5614 (save-excursion
5615 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5616 (beg (condition-case nil
5617 (progn (outline-back-to-heading) (point))
5618 (error (point-min))))
5619 (end (move-marker (make-marker)
5620 (progn (outline-next-heading) (point))))
5621 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5622 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5623 (re-find (concat re "\\|" re-box))
5624 beg-cookie end-cookie is-percent c-on c-off lim
5625 eline curr-ind next-ind continue-from startsearch
5626 (cstat 0)
5628 (when all
5629 (goto-char (point-min))
5630 (outline-next-heading)
5631 (setq beg (point) end (point-max)))
5632 (goto-char end)
5633 ;; find each statistic cookie
5634 (while (re-search-backward re-find beg t)
5635 (setq beg-cookie (match-beginning 1)
5636 end-cookie (match-end 1)
5637 cstat (+ cstat (if end-cookie 1 0))
5638 startsearch (point-at-eol)
5639 continue-from (point-at-bol)
5640 is-percent (match-beginning 2)
5641 lim (cond
5642 ((org-on-heading-p) (outline-next-heading) (point))
5643 ((org-at-item-p) (org-end-of-item) (point))
5644 (t nil))
5645 c-on 0
5646 c-off 0)
5647 (when lim
5648 ;; find first checkbox for this cookie and gather
5649 ;; statistics from all that are at this indentation level
5650 (goto-char startsearch)
5651 (if (re-search-forward re-box lim t)
5652 (progn
5653 (org-beginning-of-item)
5654 (setq curr-ind (org-get-indentation))
5655 (setq next-ind curr-ind)
5656 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5657 (save-excursion (end-of-line) (setq eline (point)))
5658 (if (re-search-forward re-box eline t)
5659 (if (member (match-string 2) '("[ ]" "[-]"))
5660 (setq c-off (1+ c-off))
5661 (setq c-on (1+ c-on))
5664 (org-end-of-item)
5665 (setq next-ind (org-get-indentation))
5667 (goto-char continue-from)
5668 ;; update cookie
5669 (when end-cookie
5670 (delete-region beg-cookie end-cookie)
5671 (goto-char beg-cookie)
5672 (insert
5673 (if is-percent
5674 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5675 (format "[%d/%d]" c-on (+ c-on c-off)))))
5676 ;; update items checkbox if it has one
5677 (when (org-at-item-p)
5678 (org-beginning-of-item)
5679 (when (and (> (+ c-on c-off) 0)
5680 (re-search-forward re-box (point-at-eol) t))
5681 (setq beg-cookie (match-beginning 2)
5682 end-cookie (match-end 2))
5683 (delete-region beg-cookie end-cookie)
5684 (goto-char beg-cookie)
5685 (cond ((= c-off 0) (insert "[X]"))
5686 ((= c-on 0) (insert "[ ]"))
5687 (t (insert "[-]")))
5689 (goto-char continue-from))
5690 (when (interactive-p)
5691 (message "Checkbox satistics updated %s (%d places)"
5692 (if all "in entire file" "in current outline entry") cstat)))))
5694 (defun org-get-checkbox-statistics-face ()
5695 "Select the face for checkbox statistics.
5696 The face will be `org-done' when all relevant boxes are checked. Otherwise
5697 it will be `org-todo'."
5698 (if (match-end 1)
5699 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5700 (if (and (> (match-end 2) (match-beginning 2))
5701 (equal (match-string 2) (match-string 3)))
5702 'org-done
5703 'org-todo)))
5705 (defun org-get-indentation (&optional line)
5706 "Get the indentation of the current line, interpreting tabs.
5707 When LINE is given, assume it represents a line and compute its indentation."
5708 (if line
5709 (if (string-match "^ *" (org-remove-tabs line))
5710 (match-end 0))
5711 (save-excursion
5712 (beginning-of-line 1)
5713 (skip-chars-forward " \t")
5714 (current-column))))
5716 (defun org-remove-tabs (s &optional width)
5717 "Replace tabulators in S with spaces.
5718 Assumes that s is a single line, starting in column 0."
5719 (setq width (or width tab-width))
5720 (while (string-match "\t" s)
5721 (setq s (replace-match
5722 (make-string
5723 (- (* width (/ (+ (match-beginning 0) width) width))
5724 (match-beginning 0)) ?\ )
5725 t t s)))
5728 (defun org-fix-indentation (line ind)
5729 "Fix indentation in LINE.
5730 IND is a cons cell with target and minimum indentation.
5731 If the current indenation in LINE is smaller than the minimum,
5732 leave it alone. If it is larger than ind, set it to the target."
5733 (let* ((l (org-remove-tabs line))
5734 (i (org-get-indentation l))
5735 (i1 (car ind)) (i2 (cdr ind)))
5736 (if (>= i i2) (setq l (substring line i2)))
5737 (if (> i1 0)
5738 (concat (make-string i1 ?\ ) l)
5739 l)))
5741 (defun org-beginning-of-item ()
5742 "Go to the beginning of the current hand-formatted item.
5743 If the cursor is not in an item, throw an error."
5744 (interactive)
5745 (let ((pos (point))
5746 (limit (save-excursion
5747 (condition-case nil
5748 (progn
5749 (org-back-to-heading)
5750 (beginning-of-line 2) (point))
5751 (error (point-min)))))
5752 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5753 ind ind1)
5754 (if (org-at-item-p)
5755 (beginning-of-line 1)
5756 (beginning-of-line 1)
5757 (skip-chars-forward " \t")
5758 (setq ind (current-column))
5759 (if (catch 'exit
5760 (while t
5761 (beginning-of-line 0)
5762 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5764 (if (looking-at "[ \t]*$")
5765 (setq ind1 ind-empty)
5766 (skip-chars-forward " \t")
5767 (setq ind1 (current-column)))
5768 (if (< ind1 ind)
5769 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5771 (goto-char pos)
5772 (error "Not in an item")))))
5774 (defun org-end-of-item ()
5775 "Go to the end of the current hand-formatted item.
5776 If the cursor is not in an item, throw an error."
5777 (interactive)
5778 (let* ((pos (point))
5779 ind1
5780 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5781 (limit (save-excursion (outline-next-heading) (point)))
5782 (ind (save-excursion
5783 (org-beginning-of-item)
5784 (skip-chars-forward " \t")
5785 (current-column)))
5786 (end (catch 'exit
5787 (while t
5788 (beginning-of-line 2)
5789 (if (eobp) (throw 'exit (point)))
5790 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5791 (if (looking-at "[ \t]*$")
5792 (setq ind1 ind-empty)
5793 (skip-chars-forward " \t")
5794 (setq ind1 (current-column)))
5795 (if (<= ind1 ind)
5796 (throw 'exit (point-at-bol)))))))
5797 (if end
5798 (goto-char end)
5799 (goto-char pos)
5800 (error "Not in an item"))))
5802 (defun org-next-item ()
5803 "Move to the beginning of the next item in the current plain list.
5804 Error if not at a plain list, or if this is the last item in the list."
5805 (interactive)
5806 (let (ind ind1 (pos (point)))
5807 (org-beginning-of-item)
5808 (setq ind (org-get-indentation))
5809 (org-end-of-item)
5810 (setq ind1 (org-get-indentation))
5811 (unless (and (org-at-item-p) (= ind ind1))
5812 (goto-char pos)
5813 (error "On last item"))))
5815 (defun org-previous-item ()
5816 "Move to the beginning of the previous item in the current plain list.
5817 Error if not at a plain list, or if this is the first item in the list."
5818 (interactive)
5819 (let (beg ind ind1 (pos (point)))
5820 (org-beginning-of-item)
5821 (setq beg (point))
5822 (setq ind (org-get-indentation))
5823 (goto-char beg)
5824 (catch 'exit
5825 (while t
5826 (beginning-of-line 0)
5827 (if (looking-at "[ \t]*$")
5829 (if (<= (setq ind1 (org-get-indentation)) ind)
5830 (throw 'exit t)))))
5831 (condition-case nil
5832 (if (or (not (org-at-item-p))
5833 (< ind1 (1- ind)))
5834 (error "")
5835 (org-beginning-of-item))
5836 (error (goto-char pos)
5837 (error "On first item")))))
5839 (defun org-first-list-item-p ()
5840 "Is this heading the item in a plain list?"
5841 (unless (org-at-item-p)
5842 (error "Not at a plain list item"))
5843 (org-beginning-of-item)
5844 (= (point) (save-excursion (org-beginning-of-item-list))))
5846 (defun org-move-item-down ()
5847 "Move the plain list item at point down, i.e. swap with following item.
5848 Subitems (items with larger indentation) are considered part of the item,
5849 so this really moves item trees."
5850 (interactive)
5851 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5852 (org-beginning-of-item)
5853 (setq beg0 (point))
5854 (save-excursion
5855 (setq ne-beg (org-back-over-empty-lines))
5856 (setq beg (point)))
5857 (goto-char beg0)
5858 (setq ind (org-get-indentation))
5859 (org-end-of-item)
5860 (setq end0 (point))
5861 (setq ind1 (org-get-indentation))
5862 (setq ne-end (org-back-over-empty-lines))
5863 (setq end (point))
5864 (goto-char beg0)
5865 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5866 ;; include less whitespace
5867 (save-excursion
5868 (goto-char beg)
5869 (forward-line (- ne-beg ne-end))
5870 (setq beg (point))))
5871 (goto-char end0)
5872 (if (and (org-at-item-p) (= ind ind1))
5873 (progn
5874 (org-end-of-item)
5875 (org-back-over-empty-lines)
5876 (setq txt (buffer-substring beg end))
5877 (save-excursion
5878 (delete-region beg end))
5879 (setq pos (point))
5880 (insert txt)
5881 (goto-char pos) (org-skip-whitespace)
5882 (org-maybe-renumber-ordered-list))
5883 (goto-char pos)
5884 (error "Cannot move this item further down"))))
5886 (defun org-move-item-up (arg)
5887 "Move the plain list item at point up, i.e. swap with previous item.
5888 Subitems (items with larger indentation) are considered part of the item,
5889 so this really moves item trees."
5890 (interactive "p")
5891 (let (beg beg0 end ind ind1 (pos (point)) txt
5892 ne-beg ne-ins ins-end)
5893 (org-beginning-of-item)
5894 (setq beg0 (point))
5895 (setq ind (org-get-indentation))
5896 (save-excursion
5897 (setq ne-beg (org-back-over-empty-lines))
5898 (setq beg (point)))
5899 (goto-char beg0)
5900 (org-end-of-item)
5901 (setq end (point))
5902 (goto-char beg0)
5903 (catch 'exit
5904 (while t
5905 (beginning-of-line 0)
5906 (if (looking-at "[ \t]*$")
5907 (if org-empty-line-terminates-plain-lists
5908 (progn
5909 (goto-char pos)
5910 (error "Cannot move this item further up"))
5911 nil)
5912 (if (<= (setq ind1 (org-get-indentation)) ind)
5913 (throw 'exit t)))))
5914 (condition-case nil
5915 (org-beginning-of-item)
5916 (error (goto-char beg)
5917 (error "Cannot move this item further up")))
5918 (setq ind1 (org-get-indentation))
5919 (if (and (org-at-item-p) (= ind ind1))
5920 (progn
5921 (setq ne-ins (org-back-over-empty-lines))
5922 (setq txt (buffer-substring beg end))
5923 (save-excursion
5924 (delete-region beg end))
5925 (setq pos (point))
5926 (insert txt)
5927 (setq ins-end (point))
5928 (goto-char pos) (org-skip-whitespace)
5930 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5931 ;; Move whitespace back to beginning
5932 (save-excursion
5933 (goto-char ins-end)
5934 (let ((kill-whole-line t))
5935 (kill-line (- ne-ins ne-beg)) (point)))
5936 (insert (make-string (- ne-ins ne-beg) ?\n)))
5938 (org-maybe-renumber-ordered-list))
5939 (goto-char pos)
5940 (error "Cannot move this item further up"))))
5942 (defun org-maybe-renumber-ordered-list ()
5943 "Renumber the ordered list at point if setup allows it.
5944 This tests the user option `org-auto-renumber-ordered-lists' before
5945 doing the renumbering."
5946 (interactive)
5947 (when (and org-auto-renumber-ordered-lists
5948 (org-at-item-p))
5949 (if (match-beginning 3)
5950 (org-renumber-ordered-list 1)
5951 (org-fix-bullet-type))))
5953 (defun org-maybe-renumber-ordered-list-safe ()
5954 (condition-case nil
5955 (save-excursion
5956 (org-maybe-renumber-ordered-list))
5957 (error nil)))
5959 (defun org-cycle-list-bullet (&optional which)
5960 "Cycle through the different itemize/enumerate bullets.
5961 This cycle the entire list level through the sequence:
5963 `-' -> `+' -> `*' -> `1.' -> `1)'
5965 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5966 0 meand `-', 1 means `+' etc."
5967 (interactive "P")
5968 (org-preserve-lc
5969 (org-beginning-of-item-list)
5970 (org-at-item-p)
5971 (beginning-of-line 1)
5972 (let ((current (match-string 0))
5973 (prevp (eq which 'previous))
5974 new)
5975 (setq new (cond
5976 ((and (numberp which)
5977 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5978 ((string-match "-" current) (if prevp "1)" "+"))
5979 ((string-match "\\+" current)
5980 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5981 ((string-match "\\*" current) (if prevp "+" "1."))
5982 ((string-match "\\." current) (if prevp "*" "1)"))
5983 ((string-match ")" current) (if prevp "1." "-"))
5984 (t (error "This should not happen"))))
5985 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5986 (org-fix-bullet-type)
5987 (org-maybe-renumber-ordered-list))))
5989 (defun org-get-string-indentation (s)
5990 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5991 (let ((n -1) (i 0) (w tab-width) c)
5992 (catch 'exit
5993 (while (< (setq n (1+ n)) (length s))
5994 (setq c (aref s n))
5995 (cond ((= c ?\ ) (setq i (1+ i)))
5996 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5997 (t (throw 'exit t)))))
6000 (defun org-renumber-ordered-list (arg)
6001 "Renumber an ordered plain list.
6002 Cursor needs to be in the first line of an item, the line that starts
6003 with something like \"1.\" or \"2)\"."
6004 (interactive "p")
6005 (unless (and (org-at-item-p)
6006 (match-beginning 3))
6007 (error "This is not an ordered list"))
6008 (let ((line (org-current-line))
6009 (col (current-column))
6010 (ind (org-get-string-indentation
6011 (buffer-substring (point-at-bol) (match-beginning 3))))
6012 ;; (term (substring (match-string 3) -1))
6013 ind1 (n (1- arg))
6014 fmt)
6015 ;; find where this list begins
6016 (org-beginning-of-item-list)
6017 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6018 (setq fmt (concat "%d" (match-string 1)))
6019 (beginning-of-line 0)
6020 ;; walk forward and replace these numbers
6021 (catch 'exit
6022 (while t
6023 (catch 'next
6024 (beginning-of-line 2)
6025 (if (eobp) (throw 'exit nil))
6026 (if (looking-at "[ \t]*$") (throw 'next nil))
6027 (skip-chars-forward " \t") (setq ind1 (current-column))
6028 (if (> ind1 ind) (throw 'next t))
6029 (if (< ind1 ind) (throw 'exit t))
6030 (if (not (org-at-item-p)) (throw 'exit nil))
6031 (delete-region (match-beginning 2) (match-end 2))
6032 (goto-char (match-beginning 2))
6033 (insert (format fmt (setq n (1+ n)))))))
6034 (goto-line line)
6035 (org-move-to-column col)))
6037 (defun org-fix-bullet-type ()
6038 "Make sure all items in this list have the same bullet as the firsst item."
6039 (interactive)
6040 (unless (org-at-item-p) (error "This is not a list"))
6041 (let ((line (org-current-line))
6042 (col (current-column))
6043 (ind (current-indentation))
6044 ind1 bullet)
6045 ;; find where this list begins
6046 (org-beginning-of-item-list)
6047 (beginning-of-line 1)
6048 ;; find out what the bullet type is
6049 (looking-at "[ \t]*\\(\\S-+\\)")
6050 (setq bullet (match-string 1))
6051 ;; walk forward and replace these numbers
6052 (beginning-of-line 0)
6053 (catch 'exit
6054 (while t
6055 (catch 'next
6056 (beginning-of-line 2)
6057 (if (eobp) (throw 'exit nil))
6058 (if (looking-at "[ \t]*$") (throw 'next nil))
6059 (skip-chars-forward " \t") (setq ind1 (current-column))
6060 (if (> ind1 ind) (throw 'next t))
6061 (if (< ind1 ind) (throw 'exit t))
6062 (if (not (org-at-item-p)) (throw 'exit nil))
6063 (skip-chars-forward " \t")
6064 (looking-at "\\S-+")
6065 (replace-match bullet))))
6066 (goto-line line)
6067 (org-move-to-column col)
6068 (if (string-match "[0-9]" bullet)
6069 (org-renumber-ordered-list 1))))
6071 (defun org-beginning-of-item-list ()
6072 "Go to the beginning of the current item list.
6073 I.e. to the first item in this list."
6074 (interactive)
6075 (org-beginning-of-item)
6076 (let ((pos (point-at-bol))
6077 (ind (org-get-indentation))
6078 ind1)
6079 ;; find where this list begins
6080 (catch 'exit
6081 (while t
6082 (catch 'next
6083 (beginning-of-line 0)
6084 (if (looking-at "[ \t]*$")
6085 (throw (if (bobp) 'exit 'next) t))
6086 (skip-chars-forward " \t") (setq ind1 (current-column))
6087 (if (or (< ind1 ind)
6088 (and (= ind1 ind)
6089 (not (org-at-item-p)))
6090 (bobp))
6091 (throw 'exit t)
6092 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6093 (goto-char pos)))
6096 (defun org-end-of-item-list ()
6097 "Go to the end of the current item list.
6098 I.e. to the text after the last item."
6099 (interactive)
6100 (org-beginning-of-item)
6101 (let ((pos (point-at-bol))
6102 (ind (org-get-indentation))
6103 ind1)
6104 ;; find where this list begins
6105 (catch 'exit
6106 (while t
6107 (catch 'next
6108 (beginning-of-line 2)
6109 (if (looking-at "[ \t]*$")
6110 (throw (if (eobp) 'exit 'next) t))
6111 (skip-chars-forward " \t") (setq ind1 (current-column))
6112 (if (or (< ind1 ind)
6113 (and (= ind1 ind)
6114 (not (org-at-item-p)))
6115 (eobp))
6116 (progn
6117 (setq pos (point-at-bol))
6118 (throw 'exit t))))))
6119 (goto-char pos)))
6122 (defvar org-last-indent-begin-marker (make-marker))
6123 (defvar org-last-indent-end-marker (make-marker))
6125 (defun org-outdent-item (arg)
6126 "Outdent a local list item."
6127 (interactive "p")
6128 (org-indent-item (- arg)))
6130 (defun org-indent-item (arg)
6131 "Indent a local list item."
6132 (interactive "p")
6133 (unless (org-at-item-p)
6134 (error "Not on an item"))
6135 (save-excursion
6136 (let (beg end ind ind1 tmp delta ind-down ind-up)
6137 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6138 (setq beg org-last-indent-begin-marker
6139 end org-last-indent-end-marker)
6140 (org-beginning-of-item)
6141 (setq beg (move-marker org-last-indent-begin-marker (point)))
6142 (org-end-of-item)
6143 (setq end (move-marker org-last-indent-end-marker (point))))
6144 (goto-char beg)
6145 (setq tmp (org-item-indent-positions)
6146 ind (car tmp)
6147 ind-down (nth 2 tmp)
6148 ind-up (nth 1 tmp)
6149 delta (if (> arg 0)
6150 (if ind-down (- ind-down ind) 2)
6151 (if ind-up (- ind-up ind) -2)))
6152 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6153 (while (< (point) end)
6154 (beginning-of-line 1)
6155 (skip-chars-forward " \t") (setq ind1 (current-column))
6156 (delete-region (point-at-bol) (point))
6157 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6158 (beginning-of-line 2))))
6159 (org-fix-bullet-type)
6160 (org-maybe-renumber-ordered-list-safe)
6161 (save-excursion
6162 (beginning-of-line 0)
6163 (condition-case nil (org-beginning-of-item) (error nil))
6164 (org-maybe-renumber-ordered-list-safe)))
6166 (defun org-item-indent-positions ()
6167 "Return indentation for plain list items.
6168 This returns a list with three values: The current indentation, the
6169 parent indentation and the indentation a child should habe.
6170 Assumes cursor in item line."
6171 (let* ((bolpos (point-at-bol))
6172 (ind (org-get-indentation))
6173 ind-down ind-up pos)
6174 (save-excursion
6175 (org-beginning-of-item-list)
6176 (skip-chars-backward "\n\r \t")
6177 (when (org-in-item-p)
6178 (org-beginning-of-item)
6179 (setq ind-up (org-get-indentation))))
6180 (setq pos (point))
6181 (save-excursion
6182 (cond
6183 ((and (condition-case nil (progn (org-previous-item) t)
6184 (error nil))
6185 (or (forward-char 1) t)
6186 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6187 (setq ind-down (org-get-indentation)))
6188 ((and (goto-char pos)
6189 (org-at-item-p))
6190 (goto-char (match-end 0))
6191 (skip-chars-forward " \t")
6192 (setq ind-down (current-column)))))
6193 (list ind ind-up ind-down)))
6195 ;;; The orgstruct minor mode
6197 ;; Define a minor mode which can be used in other modes in order to
6198 ;; integrate the org-mode structure editing commands.
6200 ;; This is really a hack, because the org-mode structure commands use
6201 ;; keys which normally belong to the major mode. Here is how it
6202 ;; works: The minor mode defines all the keys necessary to operate the
6203 ;; structure commands, but wraps the commands into a function which
6204 ;; tests if the cursor is currently at a headline or a plain list
6205 ;; item. If that is the case, the structure command is used,
6206 ;; temporarily setting many Org-mode variables like regular
6207 ;; expressions for filling etc. However, when any of those keys is
6208 ;; used at a different location, function uses `key-binding' to look
6209 ;; up if the key has an associated command in another currently active
6210 ;; keymap (minor modes, major mode, global), and executes that
6211 ;; command. There might be problems if any of the keys is otherwise
6212 ;; used as a prefix key.
6214 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6215 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6216 ;; addresses this by checking explicitly for both bindings.
6218 (defvar orgstruct-mode-map (make-sparse-keymap)
6219 "Keymap for the minor `orgstruct-mode'.")
6221 (defvar org-local-vars nil
6222 "List of local variables, for use by `orgstruct-mode'")
6224 ;;;###autoload
6225 (define-minor-mode orgstruct-mode
6226 "Toggle the minor more `orgstruct-mode'.
6227 This mode is for using Org-mode structure commands in other modes.
6228 The following key behave as if Org-mode was active, if the cursor
6229 is on a headline, or on a plain list item (both in the definition
6230 of Org-mode).
6232 M-up Move entry/item up
6233 M-down Move entry/item down
6234 M-left Promote
6235 M-right Demote
6236 M-S-up Move entry/item up
6237 M-S-down Move entry/item down
6238 M-S-left Promote subtree
6239 M-S-right Demote subtree
6240 M-q Fill paragraph and items like in Org-mode
6241 C-c ^ Sort entries
6242 C-c - Cycle list bullet
6243 TAB Cycle item visibility
6244 M-RET Insert new heading/item
6245 S-M-RET Insert new TODO heading / Chekbox item
6246 C-c C-c Set tags / toggle checkbox"
6247 nil " OrgStruct" nil
6248 (org-load-modules-maybe)
6249 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6251 ;;;###autoload
6252 (defun turn-on-orgstruct ()
6253 "Unconditionally turn on `orgstruct-mode'."
6254 (orgstruct-mode 1))
6256 ;;;###autoload
6257 (defun turn-on-orgstruct++ ()
6258 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6259 In addition to setting orgstruct-mode, this also exports all indentation and
6260 autofilling variables from org-mode into the buffer. Note that turning
6261 off orgstruct-mode will *not* remove these additional settings."
6262 (orgstruct-mode 1)
6263 (let (var val)
6264 (mapc
6265 (lambda (x)
6266 (when (string-match
6267 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6268 (symbol-name (car x)))
6269 (setq var (car x) val (nth 1 x))
6270 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6271 org-local-vars)))
6273 (defun orgstruct-error ()
6274 "Error when there is no default binding for a structure key."
6275 (interactive)
6276 (error "This key has no function outside structure elements"))
6278 (defun orgstruct-setup ()
6279 "Setup orgstruct keymaps."
6280 (let ((nfunc 0)
6281 (bindings
6282 (list
6283 '([(meta up)] org-metaup)
6284 '([(meta down)] org-metadown)
6285 '([(meta left)] org-metaleft)
6286 '([(meta right)] org-metaright)
6287 '([(meta shift up)] org-shiftmetaup)
6288 '([(meta shift down)] org-shiftmetadown)
6289 '([(meta shift left)] org-shiftmetaleft)
6290 '([(meta shift right)] org-shiftmetaright)
6291 '([(shift up)] org-shiftup)
6292 '([(shift down)] org-shiftdown)
6293 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6294 '("\M-q" fill-paragraph)
6295 '("\C-c^" org-sort)
6296 '("\C-c-" org-cycle-list-bullet)))
6297 elt key fun cmd)
6298 (while (setq elt (pop bindings))
6299 (setq nfunc (1+ nfunc))
6300 (setq key (org-key (car elt))
6301 fun (nth 1 elt)
6302 cmd (orgstruct-make-binding fun nfunc key))
6303 (org-defkey orgstruct-mode-map key cmd))
6305 ;; Special treatment needed for TAB and RET
6306 (org-defkey orgstruct-mode-map [(tab)]
6307 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6308 (org-defkey orgstruct-mode-map "\C-i"
6309 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6311 (org-defkey orgstruct-mode-map "\M-\C-m"
6312 (orgstruct-make-binding 'org-insert-heading 105
6313 "\M-\C-m" [(meta return)]))
6314 (org-defkey orgstruct-mode-map [(meta return)]
6315 (orgstruct-make-binding 'org-insert-heading 106
6316 [(meta return)] "\M-\C-m"))
6318 (org-defkey orgstruct-mode-map [(shift meta return)]
6319 (orgstruct-make-binding 'org-insert-todo-heading 107
6320 [(meta return)] "\M-\C-m"))
6322 (unless org-local-vars
6323 (setq org-local-vars (org-get-local-variables)))
6327 (defun orgstruct-make-binding (fun n &rest keys)
6328 "Create a function for binding in the structure minor mode.
6329 FUN is the command to call inside a table. N is used to create a unique
6330 command name. KEYS are keys that should be checked in for a command
6331 to execute outside of tables."
6332 (eval
6333 (list 'defun
6334 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6335 '(arg)
6336 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6337 "Outside of structure, run the binding of `"
6338 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6339 "'.")
6340 '(interactive "p")
6341 (list 'if
6342 '(org-context-p 'headline 'item)
6343 (list 'org-run-like-in-org-mode (list 'quote fun))
6344 (list 'let '(orgstruct-mode)
6345 (list 'call-interactively
6346 (append '(or)
6347 (mapcar (lambda (k)
6348 (list 'key-binding k))
6349 keys)
6350 '('orgstruct-error))))))))
6352 (defun org-context-p (&rest contexts)
6353 "Check if local context is and of CONTEXTS.
6354 Possible values in the list of contexts are `table', `headline', and `item'."
6355 (let ((pos (point)))
6356 (goto-char (point-at-bol))
6357 (prog1 (or (and (memq 'table contexts)
6358 (looking-at "[ \t]*|"))
6359 (and (memq 'headline contexts)
6360 (looking-at "\\*+"))
6361 (and (memq 'item contexts)
6362 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6363 (goto-char pos))))
6365 (defun org-get-local-variables ()
6366 "Return a list of all local variables in an org-mode buffer."
6367 (let (varlist)
6368 (with-current-buffer (get-buffer-create "*Org tmp*")
6369 (erase-buffer)
6370 (org-mode)
6371 (setq varlist (buffer-local-variables)))
6372 (kill-buffer "*Org tmp*")
6373 (delq nil
6374 (mapcar
6375 (lambda (x)
6376 (setq x
6377 (if (symbolp x)
6378 (list x)
6379 (list (car x) (list 'quote (cdr x)))))
6380 (if (string-match
6381 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6382 (symbol-name (car x)))
6383 x nil))
6384 varlist))))
6386 ;;;###autoload
6387 (defun org-run-like-in-org-mode (cmd)
6388 (org-load-modules-maybe)
6389 (unless org-local-vars
6390 (setq org-local-vars (org-get-local-variables)))
6391 (eval (list 'let org-local-vars
6392 (list 'call-interactively (list 'quote cmd)))))
6394 ;;;; Archiving
6396 (defun org-get-category (&optional pos)
6397 "Get the category applying to position POS."
6398 (get-text-property (or pos (point)) 'org-category))
6400 (defun org-refresh-category-properties ()
6401 "Refresh category text properties in the buffer."
6402 (let ((def-cat (cond
6403 ((null org-category)
6404 (if buffer-file-name
6405 (file-name-sans-extension
6406 (file-name-nondirectory buffer-file-name))
6407 "???"))
6408 ((symbolp org-category) (symbol-name org-category))
6409 (t org-category)))
6410 beg end cat pos optionp)
6411 (org-unmodified
6412 (save-excursion
6413 (save-restriction
6414 (widen)
6415 (goto-char (point-min))
6416 (put-text-property (point) (point-max) 'org-category def-cat)
6417 (while (re-search-forward
6418 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6419 (setq pos (match-end 0)
6420 optionp (equal (char-after (match-beginning 0)) ?#)
6421 cat (org-trim (match-string 2)))
6422 (if optionp
6423 (setq beg (point-at-bol) end (point-max))
6424 (org-back-to-heading t)
6425 (setq beg (point) end (org-end-of-subtree t t)))
6426 (put-text-property beg end 'org-category cat)
6427 (goto-char pos)))))))
6430 ;;;; Link Stuff
6432 ;;; Link abbreviations
6434 (defun org-link-expand-abbrev (link)
6435 "Apply replacements as defined in `org-link-abbrev-alist."
6436 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6437 (let* ((key (match-string 1 link))
6438 (as (or (assoc key org-link-abbrev-alist-local)
6439 (assoc key org-link-abbrev-alist)))
6440 (tag (and (match-end 2) (match-string 3 link)))
6441 rpl)
6442 (if (not as)
6443 link
6444 (setq rpl (cdr as))
6445 (cond
6446 ((symbolp rpl) (funcall rpl tag))
6447 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6448 (t (concat rpl tag)))))
6449 link))
6451 ;;; Storing and inserting links
6453 (defvar org-insert-link-history nil
6454 "Minibuffer history for links inserted with `org-insert-link'.")
6456 (defvar org-stored-links nil
6457 "Contains the links stored with `org-store-link'.")
6459 (defvar org-store-link-plist nil
6460 "Plist with info about the most recently link created with `org-store-link'.")
6462 (defvar org-link-protocols nil
6463 "Link protocols added to Org-mode using `org-add-link-type'.")
6465 (defvar org-store-link-functions nil
6466 "List of functions that are called to create and store a link.
6467 Each function will be called in turn until one returns a non-nil
6468 value. Each function should check if it is responsible for creating
6469 this link (for example by looking at the major mode).
6470 If not, it must exit and return nil.
6471 If yes, it should return a non-nil value after a calling
6472 `org-store-link-props' with a list of properties and values.
6473 Special properties are:
6475 :type The link prefix. like \"http\". This must be given.
6476 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6477 This is obligatory as well.
6478 :description Optional default description for the second pair
6479 of brackets in an Org-mode link. The user can still change
6480 this when inserting this link into an Org-mode buffer.
6482 In addition to these, any additional properties can be specified
6483 and then used in remember templates.")
6485 (defun org-add-link-type (type &optional follow export)
6486 "Add TYPE to the list of `org-link-types'.
6487 Re-compute all regular expressions depending on `org-link-types'
6489 FOLLOW and EXPORT are two functions.
6491 FOLLOW should take the link path as the single argument and do whatever
6492 is necessary to follow the link, for example find a file or display
6493 a mail message.
6495 EXPORT should format the link path for export to one of the export formats.
6496 It should be a function accepting three arguments:
6498 path the path of the link, the text after the prefix (like \"http:\")
6499 desc the description of the link, if any, nil if there was no descripton
6500 format the export format, a symbol like `html' or `latex'.
6502 The function may use the FORMAT information to return different values
6503 depending on the format. The return value will be put literally into
6504 the exported file.
6505 Org-mode has a built-in default for exporting links. If you are happy with
6506 this default, there is no need to define an export function for the link
6507 type. For a simple example of an export function, see `org-bbdb.el'."
6508 (add-to-list 'org-link-types type t)
6509 (org-make-link-regexps)
6510 (if (assoc type org-link-protocols)
6511 (setcdr (assoc type org-link-protocols) (list follow export))
6512 (push (list type follow export) org-link-protocols)))
6515 ;;;###autoload
6516 (defun org-store-link (arg)
6517 "\\<org-mode-map>Store an org-link to the current location.
6518 This link is added to `org-stored-links' and can later be inserted
6519 into an org-buffer with \\[org-insert-link].
6521 For some link types, a prefix arg is interpreted:
6522 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6523 For file links, arg negates `org-context-in-file-links'."
6524 (interactive "P")
6525 (org-load-modules-maybe)
6526 (setq org-store-link-plist nil) ; reset
6527 (let (link cpltxt desc description search txt)
6528 (cond
6530 ((run-hook-with-args-until-success 'org-store-link-functions)
6531 (setq link (plist-get org-store-link-plist :link)
6532 desc (or (plist-get org-store-link-plist :description) link)))
6534 ((eq major-mode 'calendar-mode)
6535 (let ((cd (calendar-cursor-to-date)))
6536 (setq link
6537 (format-time-string
6538 (car org-time-stamp-formats)
6539 (apply 'encode-time
6540 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6541 nil nil nil))))
6542 (org-store-link-props :type "calendar" :date cd)))
6544 ((eq major-mode 'w3-mode)
6545 (setq cpltxt (url-view-url t)
6546 link (org-make-link cpltxt))
6547 (org-store-link-props :type "w3" :url (url-view-url t)))
6549 ((eq major-mode 'w3m-mode)
6550 (setq cpltxt (or w3m-current-title w3m-current-url)
6551 link (org-make-link w3m-current-url))
6552 (org-store-link-props :type "w3m" :url (url-view-url t)))
6554 ((setq search (run-hook-with-args-until-success
6555 'org-create-file-search-functions))
6556 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6557 "::" search))
6558 (setq cpltxt (or description link)))
6560 ((eq major-mode 'image-mode)
6561 (setq cpltxt (concat "file:"
6562 (abbreviate-file-name buffer-file-name))
6563 link (org-make-link cpltxt))
6564 (org-store-link-props :type "image" :file buffer-file-name))
6566 ((eq major-mode 'dired-mode)
6567 ;; link to the file in the current line
6568 (setq cpltxt (concat "file:"
6569 (abbreviate-file-name
6570 (expand-file-name
6571 (dired-get-filename nil t))))
6572 link (org-make-link cpltxt)))
6574 ((and buffer-file-name (org-mode-p))
6575 ;; Just link to current headline
6576 (setq cpltxt (concat "file:"
6577 (abbreviate-file-name buffer-file-name)))
6578 ;; Add a context search string
6579 (when (org-xor org-context-in-file-links arg)
6580 ;; Check if we are on a target
6581 (if (org-in-regexp "<<\\(.*?\\)>>")
6582 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6583 (setq txt (cond
6584 ((org-on-heading-p) nil)
6585 ((org-region-active-p)
6586 (buffer-substring (region-beginning) (region-end)))
6587 (t nil)))
6588 (when (or (null txt) (string-match "\\S-" txt))
6589 (setq cpltxt
6590 (concat cpltxt "::"
6591 (condition-case nil
6592 (org-make-org-heading-search-string txt)
6593 (error "")))
6594 desc "NONE"))))
6595 (if (string-match "::\\'" cpltxt)
6596 (setq cpltxt (substring cpltxt 0 -2)))
6597 (setq link (org-make-link cpltxt)))
6599 ((buffer-file-name (buffer-base-buffer))
6600 ;; Just link to this file here.
6601 (setq cpltxt (concat "file:"
6602 (abbreviate-file-name
6603 (buffer-file-name (buffer-base-buffer)))))
6604 ;; Add a context string
6605 (when (org-xor org-context-in-file-links arg)
6606 (setq txt (if (org-region-active-p)
6607 (buffer-substring (region-beginning) (region-end))
6608 (buffer-substring (point-at-bol) (point-at-eol))))
6609 ;; Only use search option if there is some text.
6610 (when (string-match "\\S-" txt)
6611 (setq cpltxt
6612 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6613 desc "NONE")))
6614 (setq link (org-make-link cpltxt)))
6616 ((interactive-p)
6617 (error "Cannot link to a buffer which is not visiting a file"))
6619 (t (setq link nil)))
6621 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6622 (setq link (or link cpltxt)
6623 desc (or desc cpltxt))
6624 (if (equal desc "NONE") (setq desc nil))
6626 (if (and (interactive-p) link)
6627 (progn
6628 (setq org-stored-links
6629 (cons (list link desc) org-stored-links))
6630 (message "Stored: %s" (or desc link)))
6631 (and link (org-make-link-string link desc)))))
6633 (defun org-store-link-props (&rest plist)
6634 "Store link properties, extract names and addresses."
6635 (let (x adr)
6636 (when (setq x (plist-get plist :from))
6637 (setq adr (mail-extract-address-components x))
6638 (plist-put plist :fromname (car adr))
6639 (plist-put plist :fromaddress (nth 1 adr)))
6640 (when (setq x (plist-get plist :to))
6641 (setq adr (mail-extract-address-components x))
6642 (plist-put plist :toname (car adr))
6643 (plist-put plist :toaddress (nth 1 adr))))
6644 (let ((from (plist-get plist :from))
6645 (to (plist-get plist :to)))
6646 (when (and from to org-from-is-user-regexp)
6647 (plist-put plist :fromto
6648 (if (string-match org-from-is-user-regexp from)
6649 (concat "to %t")
6650 (concat "from %f")))))
6651 (setq org-store-link-plist plist))
6653 (defun org-add-link-props (&rest plist)
6654 "Add these properties to the link property list."
6655 (let (key value)
6656 (while plist
6657 (setq key (pop plist) value (pop plist))
6658 (setq org-store-link-plist
6659 (plist-put org-store-link-plist key value)))))
6661 (defun org-email-link-description (&optional fmt)
6662 "Return the description part of an email link.
6663 This takes information from `org-store-link-plist' and formats it
6664 according to FMT (default from `org-email-link-description-format')."
6665 (setq fmt (or fmt org-email-link-description-format))
6666 (let* ((p org-store-link-plist)
6667 (to (plist-get p :toaddress))
6668 (from (plist-get p :fromaddress))
6669 (table
6670 (list
6671 (cons "%c" (plist-get p :fromto))
6672 (cons "%F" (plist-get p :from))
6673 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6674 (cons "%T" (plist-get p :to))
6675 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6676 (cons "%s" (plist-get p :subject))
6677 (cons "%m" (plist-get p :message-id)))))
6678 (when (string-match "%c" fmt)
6679 ;; Check if the user wrote this message
6680 (if (and org-from-is-user-regexp from to
6681 (save-match-data (string-match org-from-is-user-regexp from)))
6682 (setq fmt (replace-match "to %t" t t fmt))
6683 (setq fmt (replace-match "from %f" t t fmt))))
6684 (org-replace-escapes fmt table)))
6686 (defun org-make-org-heading-search-string (&optional string heading)
6687 "Make search string for STRING or current headline."
6688 (interactive)
6689 (let ((s (or string (org-get-heading))))
6690 (unless (and string (not heading))
6691 ;; We are using a headline, clean up garbage in there.
6692 (if (string-match org-todo-regexp s)
6693 (setq s (replace-match "" t t s)))
6694 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6695 (setq s (replace-match "" t t s)))
6696 (setq s (org-trim s))
6697 (if (string-match (concat "^\\(" org-quote-string "\\|"
6698 org-comment-string "\\)") s)
6699 (setq s (replace-match "" t t s)))
6700 (while (string-match org-ts-regexp s)
6701 (setq s (replace-match "" t t s))))
6702 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6703 (setq s (replace-match " " t t s)))
6704 (or string (setq s (concat "*" s))) ; Add * for headlines
6705 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6707 (defun org-make-link (&rest strings)
6708 "Concatenate STRINGS."
6709 (apply 'concat strings))
6711 (defun org-make-link-string (link &optional description)
6712 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6713 (unless (string-match "\\S-" link)
6714 (error "Empty link"))
6715 (when (stringp description)
6716 ;; Remove brackets from the description, they are fatal.
6717 (while (string-match "\\[" description)
6718 (setq description (replace-match "{" t t description)))
6719 (while (string-match "\\]" description)
6720 (setq description (replace-match "}" t t description))))
6721 (when (equal (org-link-escape link) description)
6722 ;; No description needed, it is identical
6723 (setq description nil))
6724 (when (and (not description)
6725 (not (equal link (org-link-escape link))))
6726 (setq description link))
6727 (concat "[[" (org-link-escape link) "]"
6728 (if description (concat "[" description "]") "")
6729 "]"))
6731 (defconst org-link-escape-chars
6732 '((?\ . "%20")
6733 (?\[ . "%5B")
6734 (?\] . "%5D")
6735 (?\340 . "%E0") ; `a
6736 (?\342 . "%E2") ; ^a
6737 (?\347 . "%E7") ; ,c
6738 (?\350 . "%E8") ; `e
6739 (?\351 . "%E9") ; 'e
6740 (?\352 . "%EA") ; ^e
6741 (?\356 . "%EE") ; ^i
6742 (?\364 . "%F4") ; ^o
6743 (?\371 . "%F9") ; `u
6744 (?\373 . "%FB") ; ^u
6745 (?\; . "%3B")
6746 (?? . "%3F")
6747 (?= . "%3D")
6748 (?+ . "%2B")
6750 "Association list of escapes for some characters problematic in links.
6751 This is the list that is used for internal purposes.")
6753 (defconst org-link-escape-chars-browser
6754 '((?\ . "%20")) ; 32 for the SPC char
6755 "Association list of escapes for some characters problematic in links.
6756 This is the list that is used before handing over to the browser.")
6758 (defun org-link-escape (text &optional table)
6759 "Escape charaters in TEXT that are problematic for links."
6760 (setq table (or table org-link-escape-chars))
6761 (when text
6762 (let ((re (mapconcat (lambda (x) (regexp-quote
6763 (char-to-string (car x))))
6764 table "\\|")))
6765 (while (string-match re text)
6766 (setq text
6767 (replace-match
6768 (cdr (assoc (string-to-char (match-string 0 text))
6769 table))
6770 t t text)))
6771 text)))
6773 (defun org-link-unescape (text &optional table)
6774 "Reverse the action of `org-link-escape'."
6775 (setq table (or table org-link-escape-chars))
6776 (when text
6777 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6778 table "\\|")))
6779 (while (string-match re text)
6780 (setq text
6781 (replace-match
6782 (char-to-string (car (rassoc (match-string 0 text) table)))
6783 t t text)))
6784 text)))
6786 (defun org-xor (a b)
6787 "Exclusive or."
6788 (if a (not b) b))
6790 (defun org-get-header (header)
6791 "Find a header field in the current buffer."
6792 (save-excursion
6793 (goto-char (point-min))
6794 (let ((case-fold-search t) s)
6795 (cond
6796 ((eq header 'from)
6797 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6798 (setq s (match-string 1)))
6799 (while (string-match "\"" s)
6800 (setq s (replace-match "" t t s)))
6801 (if (string-match "[<(].*" s)
6802 (setq s (replace-match "" t t s))))
6803 ((eq header 'message-id)
6804 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6805 (setq s (match-string 1))))
6806 ((eq header 'subject)
6807 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6808 (setq s (match-string 1)))))
6809 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6810 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6811 s)))
6814 (defun org-fixup-message-id-for-http (s)
6815 "Replace special characters in a message id, so it can be used in an http query."
6816 (while (string-match "<" s)
6817 (setq s (replace-match "%3C" t t s)))
6818 (while (string-match ">" s)
6819 (setq s (replace-match "%3E" t t s)))
6820 (while (string-match "@" s)
6821 (setq s (replace-match "%40" t t s)))
6824 ;;;###autoload
6825 (defun org-insert-link-global ()
6826 "Insert a link like Org-mode does.
6827 This command can be called in any mode to insert a link in Org-mode syntax."
6828 (interactive)
6829 (org-load-modules-maybe)
6830 (org-run-like-in-org-mode 'org-insert-link))
6832 (defun org-insert-link (&optional complete-file link-location)
6833 "Insert a link. At the prompt, enter the link.
6835 Completion can be used to select a link previously stored with
6836 `org-store-link'. When the empty string is entered (i.e. if you just
6837 press RET at the prompt), the link defaults to the most recently
6838 stored link. As SPC triggers completion in the minibuffer, you need to
6839 use M-SPC or C-q SPC to force the insertion of a space character.
6841 You will also be prompted for a description, and if one is given, it will
6842 be displayed in the buffer instead of the link.
6844 If there is already a link at point, this command will allow you to edit link
6845 and description parts.
6847 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6848 be selected using completion. The path to the file will be relative to the
6849 current directory if the file is in the current directory or a subdirectory.
6850 Otherwise, the link will be the absolute path as completed in the minibuffer
6851 \(i.e. normally ~/path/to/file).
6853 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6854 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6855 of `org-keep-stored-link-after-insertion'.
6857 If `org-make-link-description-function' is non-nil, this function will be
6858 called with the link target, and the result will be the default
6859 link description.
6861 If the LINK-LOCATION parameter is non-nil, this value will be
6862 used as the link location instead of reading one interactively."
6863 (interactive "P")
6864 (let* ((wcf (current-window-configuration))
6865 (region (if (org-region-active-p)
6866 (buffer-substring (region-beginning) (region-end))))
6867 (remove (and region (list (region-beginning) (region-end))))
6868 (desc region)
6869 tmphist ; byte-compile incorrectly complains about this
6870 (link link-location)
6871 entry file)
6872 (cond
6873 (link-location) ; specified by arg, just use it.
6874 ((org-in-regexp org-bracket-link-regexp 1)
6875 ;; We do have a link at point, and we are going to edit it.
6876 (setq remove (list (match-beginning 0) (match-end 0)))
6877 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6878 (setq link (read-string "Link: "
6879 (org-link-unescape
6880 (org-match-string-no-properties 1)))))
6881 ((or (org-in-regexp org-angle-link-re)
6882 (org-in-regexp org-plain-link-re))
6883 ;; Convert to bracket link
6884 (setq remove (list (match-beginning 0) (match-end 0))
6885 link (read-string "Link: "
6886 (org-remove-angle-brackets (match-string 0)))))
6887 ((equal complete-file '(4))
6888 ;; Completing read for file names.
6889 (setq file (read-file-name "File: "))
6890 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6891 (pwd1 (file-name-as-directory (abbreviate-file-name
6892 (expand-file-name ".")))))
6893 (cond
6894 ((equal complete-file '(16))
6895 (setq link (org-make-link
6896 "file:"
6897 (abbreviate-file-name (expand-file-name file)))))
6898 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6899 (setq link (org-make-link "file:" (match-string 1 file))))
6900 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6901 (expand-file-name file))
6902 (setq link (org-make-link
6903 "file:" (match-string 1 (expand-file-name file)))))
6904 (t (setq link (org-make-link "file:" file))))))
6906 ;; Read link, with completion for stored links.
6907 (with-output-to-temp-buffer "*Org Links*"
6908 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6909 (when org-stored-links
6910 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6911 (princ (mapconcat
6912 (lambda (x)
6913 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6914 (reverse org-stored-links) "\n"))))
6915 (let ((cw (selected-window)))
6916 (select-window (get-buffer-window "*Org Links*"))
6917 (shrink-window-if-larger-than-buffer)
6918 (setq truncate-lines t)
6919 (select-window cw))
6920 ;; Fake a link history, containing the stored links.
6921 (setq tmphist (append (mapcar 'car org-stored-links)
6922 org-insert-link-history))
6923 (unwind-protect
6924 (setq link (org-completing-read
6925 "Link: "
6926 (append
6927 (mapcar (lambda (x) (list (concat (car x) ":")))
6928 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6929 (mapcar (lambda (x) (list (concat x ":")))
6930 org-link-types))
6931 nil nil nil
6932 'tmphist
6933 (or (car (car org-stored-links)))))
6934 (set-window-configuration wcf)
6935 (kill-buffer "*Org Links*"))
6936 (setq entry (assoc link org-stored-links))
6937 (or entry (push link org-insert-link-history))
6938 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6939 (not org-keep-stored-link-after-insertion))
6940 (setq org-stored-links (delq (assoc link org-stored-links)
6941 org-stored-links)))
6942 (setq desc (or desc (nth 1 entry)))))
6944 (if (string-match org-plain-link-re link)
6945 ;; URL-like link, normalize the use of angular brackets.
6946 (setq link (org-make-link (org-remove-angle-brackets link))))
6948 ;; Check if we are linking to the current file with a search option
6949 ;; If yes, simplify the link by using only the search option.
6950 (when (and buffer-file-name
6951 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6952 (let* ((path (match-string 1 link))
6953 (case-fold-search nil)
6954 (search (match-string 2 link)))
6955 (save-match-data
6956 (if (equal (file-truename buffer-file-name) (file-truename path))
6957 ;; We are linking to this same file, with a search option
6958 (setq link search)))))
6960 ;; Check if we can/should use a relative path. If yes, simplify the link
6961 (when (string-match "\\<file:\\(.*\\)" link)
6962 (let* ((path (match-string 1 link))
6963 (origpath path)
6964 (case-fold-search nil))
6965 (cond
6966 ((eq org-link-file-path-type 'absolute)
6967 (setq path (abbreviate-file-name (expand-file-name path))))
6968 ((eq org-link-file-path-type 'noabbrev)
6969 (setq path (expand-file-name path)))
6970 ((eq org-link-file-path-type 'relative)
6971 (setq path (file-relative-name path)))
6973 (save-match-data
6974 (if (string-match (concat "^" (regexp-quote
6975 (file-name-as-directory
6976 (expand-file-name "."))))
6977 (expand-file-name path))
6978 ;; We are linking a file with relative path name.
6979 (setq path (substring (expand-file-name path)
6980 (match-end 0)))))))
6981 (setq link (concat "file:" path))
6982 (if (equal desc origpath)
6983 (setq desc path))))
6985 (if org-make-link-description-function
6986 (setq desc (funcall org-make-link-description-function link desc)))
6988 (setq desc (read-string "Description: " desc))
6989 (unless (string-match "\\S-" desc) (setq desc nil))
6990 (if remove (apply 'delete-region remove))
6991 (insert (org-make-link-string link desc))))
6993 (defun org-completing-read (&rest args)
6994 (let ((minibuffer-local-completion-map
6995 (copy-keymap minibuffer-local-completion-map)))
6996 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6997 (apply 'completing-read args)))
6999 ;;; Opening/following a link
7001 (defvar org-link-search-failed nil)
7003 (defun org-next-link ()
7004 "Move forward to the next link.
7005 If the link is in hidden text, expose it."
7006 (interactive)
7007 (when (and org-link-search-failed (eq this-command last-command))
7008 (goto-char (point-min))
7009 (message "Link search wrapped back to beginning of buffer"))
7010 (setq org-link-search-failed nil)
7011 (let* ((pos (point))
7012 (ct (org-context))
7013 (a (assoc :link ct)))
7014 (if a (goto-char (nth 2 a)))
7015 (if (re-search-forward org-any-link-re nil t)
7016 (progn
7017 (goto-char (match-beginning 0))
7018 (if (org-invisible-p) (org-show-context)))
7019 (goto-char pos)
7020 (setq org-link-search-failed t)
7021 (error "No further link found"))))
7023 (defun org-previous-link ()
7024 "Move backward to the previous link.
7025 If the link is in hidden text, expose it."
7026 (interactive)
7027 (when (and org-link-search-failed (eq this-command last-command))
7028 (goto-char (point-max))
7029 (message "Link search wrapped back to end of buffer"))
7030 (setq org-link-search-failed nil)
7031 (let* ((pos (point))
7032 (ct (org-context))
7033 (a (assoc :link ct)))
7034 (if a (goto-char (nth 1 a)))
7035 (if (re-search-backward org-any-link-re nil t)
7036 (progn
7037 (goto-char (match-beginning 0))
7038 (if (org-invisible-p) (org-show-context)))
7039 (goto-char pos)
7040 (setq org-link-search-failed t)
7041 (error "No further link found"))))
7043 (defun org-find-file-at-mouse (ev)
7044 "Open file link or URL at mouse."
7045 (interactive "e")
7046 (mouse-set-point ev)
7047 (org-open-at-point 'in-emacs))
7049 (defun org-open-at-mouse (ev)
7050 "Open file link or URL at mouse."
7051 (interactive "e")
7052 (mouse-set-point ev)
7053 (org-open-at-point))
7055 (defvar org-window-config-before-follow-link nil
7056 "The window configuration before following a link.
7057 This is saved in case the need arises to restore it.")
7059 (defvar org-open-link-marker (make-marker)
7060 "Marker pointing to the location where `org-open-at-point; was called.")
7062 ;;;###autoload
7063 (defun org-open-at-point-global ()
7064 "Follow a link like Org-mode does.
7065 This command can be called in any mode to follow a link that has
7066 Org-mode syntax."
7067 (interactive)
7068 (org-run-like-in-org-mode 'org-open-at-point))
7070 ;;;###autoload
7071 (defun org-open-link-from-string (s &optional arg)
7072 "Open a link in the string S, as if it was in Org-mode."
7073 (interactive "sLink: \nP")
7074 (with-temp-buffer
7075 (let ((org-inhibit-startup t))
7076 (org-mode)
7077 (insert s)
7078 (goto-char (point-min))
7079 (org-open-at-point arg))))
7081 (defun org-open-at-point (&optional in-emacs)
7082 "Open link at or after point.
7083 If there is no link at point, this function will search forward up to
7084 the end of the current subtree.
7085 Normally, files will be opened by an appropriate application. If the
7086 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7087 (interactive "P")
7088 (org-load-modules-maybe)
7089 (move-marker org-open-link-marker (point))
7090 (setq org-window-config-before-follow-link (current-window-configuration))
7091 (org-remove-occur-highlights nil nil t)
7092 (if (org-at-timestamp-p t)
7093 (org-follow-timestamp-link)
7094 (let (type path link line search (pos (point)))
7095 (catch 'match
7096 (save-excursion
7097 (skip-chars-forward "^]\n\r")
7098 (when (org-in-regexp org-bracket-link-regexp)
7099 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7100 (while (string-match " *\n *" link)
7101 (setq link (replace-match " " t t link)))
7102 (setq link (org-link-expand-abbrev link))
7103 (if (string-match org-link-re-with-space2 link)
7104 (setq type (match-string 1 link) path (match-string 2 link))
7105 (setq type "thisfile" path link))
7106 (throw 'match t)))
7108 (when (get-text-property (point) 'org-linked-text)
7109 (setq type "thisfile"
7110 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7111 (1+ (point)) (point))
7112 path (buffer-substring
7113 (previous-single-property-change pos 'org-linked-text)
7114 (next-single-property-change pos 'org-linked-text)))
7115 (throw 'match t))
7117 (save-excursion
7118 (when (or (org-in-regexp org-angle-link-re)
7119 (org-in-regexp org-plain-link-re))
7120 (setq type (match-string 1) path (match-string 2))
7121 (throw 'match t)))
7122 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7123 (setq type "tree-match"
7124 path (match-string 1))
7125 (throw 'match t))
7126 (save-excursion
7127 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7128 (setq type "tags"
7129 path (match-string 1))
7130 (while (string-match ":" path)
7131 (setq path (replace-match "+" t t path)))
7132 (throw 'match t))))
7133 (unless path
7134 (error "No link found"))
7135 ;; Remove any trailing spaces in path
7136 (if (string-match " +\\'" path)
7137 (setq path (replace-match "" t t path)))
7139 (cond
7141 ((assoc type org-link-protocols)
7142 (funcall (nth 1 (assoc type org-link-protocols)) path))
7144 ((equal type "mailto")
7145 (let ((cmd (car org-link-mailto-program))
7146 (args (cdr org-link-mailto-program)) args1
7147 (address path) (subject "") a)
7148 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7149 (setq address (match-string 1 path)
7150 subject (org-link-escape (match-string 2 path))))
7151 (while args
7152 (cond
7153 ((not (stringp (car args))) (push (pop args) args1))
7154 (t (setq a (pop args))
7155 (if (string-match "%a" a)
7156 (setq a (replace-match address t t a)))
7157 (if (string-match "%s" a)
7158 (setq a (replace-match subject t t a)))
7159 (push a args1))))
7160 (apply cmd (nreverse args1))))
7162 ((member type '("http" "https" "ftp" "news"))
7163 (browse-url (concat type ":" (org-link-escape
7164 path org-link-escape-chars-browser))))
7166 ((member type '("message"))
7167 (browse-url (concat type ":" path)))
7169 ((string= type "tags")
7170 (org-tags-view in-emacs path))
7171 ((string= type "thisfile")
7172 (if in-emacs
7173 (switch-to-buffer-other-window
7174 (org-get-buffer-for-internal-link (current-buffer)))
7175 (org-mark-ring-push))
7176 (let ((cmd `(org-link-search
7177 ,path
7178 ,(cond ((equal in-emacs '(4)) 'occur)
7179 ((equal in-emacs '(16)) 'org-occur)
7180 (t nil))
7181 ,pos)))
7182 (condition-case nil (eval cmd)
7183 (error (progn (widen) (eval cmd))))))
7185 ((string= type "tree-match")
7186 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7188 ((string= type "file")
7189 (if (string-match "::\\([0-9]+\\)\\'" path)
7190 (setq line (string-to-number (match-string 1 path))
7191 path (substring path 0 (match-beginning 0)))
7192 (if (string-match "::\\(.+\\)\\'" path)
7193 (setq search (match-string 1 path)
7194 path (substring path 0 (match-beginning 0)))))
7195 (if (string-match "[*?{]" (file-name-nondirectory path))
7196 (dired path)
7197 (org-open-file path in-emacs line search)))
7199 ((string= type "news")
7200 (require 'org-gnus)
7201 (org-gnus-follow-link path))
7203 ((string= type "shell")
7204 (let ((cmd path))
7205 (if (or (not org-confirm-shell-link-function)
7206 (funcall org-confirm-shell-link-function
7207 (format "Execute \"%s\" in shell? "
7208 (org-add-props cmd nil
7209 'face 'org-warning))))
7210 (progn
7211 (message "Executing %s" cmd)
7212 (shell-command cmd))
7213 (error "Abort"))))
7215 ((string= type "elisp")
7216 (let ((cmd path))
7217 (if (or (not org-confirm-elisp-link-function)
7218 (funcall org-confirm-elisp-link-function
7219 (format "Execute \"%s\" as elisp? "
7220 (org-add-props cmd nil
7221 'face 'org-warning))))
7222 (message "%s => %s" cmd (eval (read cmd)))
7223 (error "Abort"))))
7226 (browse-url-at-point)))))
7227 (move-marker org-open-link-marker nil)
7228 (run-hook-with-args 'org-follow-link-hook))
7230 ;;;; Time estimates
7232 (defun org-get-effort (&optional pom)
7233 "Get the effort estimate for the current entry."
7234 (org-entry-get pom org-effort-property))
7236 ;;; File search
7238 (defvar org-create-file-search-functions nil
7239 "List of functions to construct the right search string for a file link.
7240 These functions are called in turn with point at the location to
7241 which the link should point.
7243 A function in the hook should first test if it would like to
7244 handle this file type, for example by checking the major-mode or
7245 the file extension. If it decides not to handle this file, it
7246 should just return nil to give other functions a chance. If it
7247 does handle the file, it must return the search string to be used
7248 when following the link. The search string will be part of the
7249 file link, given after a double colon, and `org-open-at-point'
7250 will automatically search for it. If special measures must be
7251 taken to make the search successful, another function should be
7252 added to the companion hook `org-execute-file-search-functions',
7253 which see.
7255 A function in this hook may also use `setq' to set the variable
7256 `description' to provide a suggestion for the descriptive text to
7257 be used for this link when it gets inserted into an Org-mode
7258 buffer with \\[org-insert-link].")
7260 (defvar org-execute-file-search-functions nil
7261 "List of functions to execute a file search triggered by a link.
7263 Functions added to this hook must accept a single argument, the
7264 search string that was part of the file link, the part after the
7265 double colon. The function must first check if it would like to
7266 handle this search, for example by checking the major-mode or the
7267 file extension. If it decides not to handle this search, it
7268 should just return nil to give other functions a chance. If it
7269 does handle the search, it must return a non-nil value to keep
7270 other functions from trying.
7272 Each function can access the current prefix argument through the
7273 variable `current-prefix-argument'. Note that a single prefix is
7274 used to force opening a link in Emacs, so it may be good to only
7275 use a numeric or double prefix to guide the search function.
7277 In case this is needed, a function in this hook can also restore
7278 the window configuration before `org-open-at-point' was called using:
7280 (set-window-configuration org-window-config-before-follow-link)")
7282 (defun org-link-search (s &optional type avoid-pos)
7283 "Search for a link search option.
7284 If S is surrounded by forward slashes, it is interpreted as a
7285 regular expression. In org-mode files, this will create an `org-occur'
7286 sparse tree. In ordinary files, `occur' will be used to list matches.
7287 If the current buffer is in `dired-mode', grep will be used to search
7288 in all files. If AVOID-POS is given, ignore matches near that position."
7289 (let ((case-fold-search t)
7290 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7291 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7292 (append '(("") (" ") ("\t") ("\n"))
7293 org-emphasis-alist)
7294 "\\|") "\\)"))
7295 (pos (point))
7296 (pre nil) (post nil)
7297 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7298 (cond
7299 ;; First check if there are any special
7300 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7301 ;; Now try the builtin stuff
7302 ((save-excursion
7303 (goto-char (point-min))
7304 (and
7305 (re-search-forward
7306 (concat "<<" (regexp-quote s0) ">>") nil t)
7307 (setq type 'dedicated
7308 pos (match-beginning 0))))
7309 ;; There is an exact target for this
7310 (goto-char pos))
7311 ((string-match "^/\\(.*\\)/$" s)
7312 ;; A regular expression
7313 (cond
7314 ((org-mode-p)
7315 (org-occur (match-string 1 s)))
7316 ;;((eq major-mode 'dired-mode)
7317 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7318 (t (org-do-occur (match-string 1 s)))))
7320 ;; A normal search strings
7321 (when (equal (string-to-char s) ?*)
7322 ;; Anchor on headlines, post may include tags.
7323 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7324 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7325 s (substring s 1)))
7326 (remove-text-properties
7327 0 (length s)
7328 '(face nil mouse-face nil keymap nil fontified nil) s)
7329 ;; Make a series of regular expressions to find a match
7330 (setq words (org-split-string s "[ \n\r\t]+")
7332 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7333 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7334 "\\)" markers)
7335 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7336 re2a (concat "[ \t\r\n]" re2a_)
7337 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7338 re4 (concat "[^a-zA-Z_]" re4_)
7340 re1 (concat pre re2 post)
7341 re3 (concat pre (if pre re4_ re4) post)
7342 re5 (concat pre ".*" re4)
7343 re2 (concat pre re2)
7344 re2a (concat pre (if pre re2a_ re2a))
7345 re4 (concat pre (if pre re4_ re4))
7346 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7347 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7348 re5 "\\)"
7350 (cond
7351 ((eq type 'org-occur) (org-occur reall))
7352 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7353 (t (goto-char (point-min))
7354 (setq type 'fuzzy)
7355 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7356 (org-search-not-self 1 re1 nil t)
7357 (org-search-not-self 1 re2 nil t)
7358 (org-search-not-self 1 re2a nil t)
7359 (org-search-not-self 1 re3 nil t)
7360 (org-search-not-self 1 re4 nil t)
7361 (org-search-not-self 1 re5 nil t)
7363 (goto-char (match-beginning 1))
7364 (goto-char pos)
7365 (error "No match")))))
7367 ;; Normal string-search
7368 (goto-char (point-min))
7369 (if (search-forward s nil t)
7370 (goto-char (match-beginning 0))
7371 (error "No match"))))
7372 (and (org-mode-p) (org-show-context 'link-search))
7373 type))
7375 (defun org-search-not-self (group &rest args)
7376 "Execute `re-search-forward', but only accept matches that do not
7377 enclose the position of `org-open-link-marker'."
7378 (let ((m org-open-link-marker))
7379 (catch 'exit
7380 (while (apply 're-search-forward args)
7381 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7382 (goto-char (match-end group))
7383 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7384 (> (match-beginning 0) (marker-position m))
7385 (< (match-end 0) (marker-position m)))
7386 (save-match-data
7387 (or (not (org-in-regexp
7388 org-bracket-link-analytic-regexp 1))
7389 (not (match-end 4)) ; no description
7390 (and (<= (match-beginning 4) (point))
7391 (>= (match-end 4) (point))))))
7392 (throw 'exit (point))))))))
7394 (defun org-get-buffer-for-internal-link (buffer)
7395 "Return a buffer to be used for displaying the link target of internal links."
7396 (cond
7397 ((not org-display-internal-link-with-indirect-buffer)
7398 buffer)
7399 ((string-match "(Clone)$" (buffer-name buffer))
7400 (message "Buffer is already a clone, not making another one")
7401 ;; we also do not modify visibility in this case
7402 buffer)
7403 (t ; make a new indirect buffer for displaying the link
7404 (let* ((bn (buffer-name buffer))
7405 (ibn (concat bn "(Clone)"))
7406 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7407 (with-current-buffer ib (org-overview))
7408 ib))))
7410 (defun org-do-occur (regexp &optional cleanup)
7411 "Call the Emacs command `occur'.
7412 If CLEANUP is non-nil, remove the printout of the regular expression
7413 in the *Occur* buffer. This is useful if the regex is long and not useful
7414 to read."
7415 (occur regexp)
7416 (when cleanup
7417 (let ((cwin (selected-window)) win beg end)
7418 (when (setq win (get-buffer-window "*Occur*"))
7419 (select-window win))
7420 (goto-char (point-min))
7421 (when (re-search-forward "match[a-z]+" nil t)
7422 (setq beg (match-end 0))
7423 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7424 (setq end (1- (match-beginning 0)))))
7425 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7426 (goto-char (point-min))
7427 (select-window cwin))))
7429 ;;; The mark ring for links jumps
7431 (defvar org-mark-ring nil
7432 "Mark ring for positions before jumps in Org-mode.")
7433 (defvar org-mark-ring-last-goto nil
7434 "Last position in the mark ring used to go back.")
7435 ;; Fill and close the ring
7436 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7437 (loop for i from 1 to org-mark-ring-length do
7438 (push (make-marker) org-mark-ring))
7439 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7440 org-mark-ring)
7442 (defun org-mark-ring-push (&optional pos buffer)
7443 "Put the current position or POS into the mark ring and rotate it."
7444 (interactive)
7445 (setq pos (or pos (point)))
7446 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7447 (move-marker (car org-mark-ring)
7448 (or pos (point))
7449 (or buffer (current-buffer)))
7450 (message "%s"
7451 (substitute-command-keys
7452 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7454 (defun org-mark-ring-goto (&optional n)
7455 "Jump to the previous position in the mark ring.
7456 With prefix arg N, jump back that many stored positions. When
7457 called several times in succession, walk through the entire ring.
7458 Org-mode commands jumping to a different position in the current file,
7459 or to another Org-mode file, automatically push the old position
7460 onto the ring."
7461 (interactive "p")
7462 (let (p m)
7463 (if (eq last-command this-command)
7464 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7465 (setq p org-mark-ring))
7466 (setq org-mark-ring-last-goto p)
7467 (setq m (car p))
7468 (switch-to-buffer (marker-buffer m))
7469 (goto-char m)
7470 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7472 (defun org-remove-angle-brackets (s)
7473 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7474 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7476 (defun org-add-angle-brackets (s)
7477 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7478 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7480 (defun org-remove-double-quotes (s)
7481 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7482 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7485 ;;; Following specific links
7487 (defun org-follow-timestamp-link ()
7488 (cond
7489 ((org-at-date-range-p t)
7490 (let ((org-agenda-start-on-weekday)
7491 (t1 (match-string 1))
7492 (t2 (match-string 2)))
7493 (setq t1 (time-to-days (org-time-string-to-time t1))
7494 t2 (time-to-days (org-time-string-to-time t2)))
7495 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7496 ((org-at-timestamp-p t)
7497 (org-agenda-list nil (time-to-days (org-time-string-to-time
7498 (substring (match-string 1) 0 10)))
7500 (t (error "This should not happen"))))
7503 ;;; Following file links
7504 (defvar org-wait nil)
7505 (defun org-open-file (path &optional in-emacs line search)
7506 "Open the file at PATH.
7507 First, this expands any special file name abbreviations. Then the
7508 configuration variable `org-file-apps' is checked if it contains an
7509 entry for this file type, and if yes, the corresponding command is launched.
7510 If no application is found, Emacs simply visits the file.
7511 With optional argument IN-EMACS, Emacs will visit the file.
7512 Optional LINE specifies a line to go to, optional SEARCH a string to
7513 search for. If LINE or SEARCH is given, the file will always be
7514 opened in Emacs.
7515 If the file does not exist, an error is thrown."
7516 (setq in-emacs (or in-emacs line search))
7517 (let* ((file (if (equal path "")
7518 buffer-file-name
7519 (substitute-in-file-name (expand-file-name path))))
7520 (apps (append org-file-apps (org-default-apps)))
7521 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7522 (dirp (if remp nil (file-directory-p file)))
7523 (dfile (downcase file))
7524 (old-buffer (current-buffer))
7525 (old-pos (point))
7526 (old-mode major-mode)
7527 ext cmd)
7528 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7529 (setq ext (match-string 1 dfile))
7530 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7531 (setq ext (match-string 1 dfile))))
7532 (if in-emacs
7533 (setq cmd 'emacs)
7534 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7535 (and dirp (cdr (assoc 'directory apps)))
7536 (cdr (assoc ext apps))
7537 (cdr (assoc t apps)))))
7538 (when (eq cmd 'mailcap)
7539 (require 'mailcap)
7540 (mailcap-parse-mailcaps)
7541 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7542 (command (mailcap-mime-info mime-type)))
7543 (if (stringp command)
7544 (setq cmd command)
7545 (setq cmd 'emacs))))
7546 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7547 (not (file-exists-p file))
7548 (not org-open-non-existing-files))
7549 (error "No such file: %s" file))
7550 (cond
7551 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7552 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7553 (while (string-match "['\"]%s['\"]" cmd)
7554 (setq cmd (replace-match "%s" t t cmd)))
7555 (while (string-match "%s" cmd)
7556 (setq cmd (replace-match
7557 (save-match-data
7558 (shell-quote-argument
7559 (convert-standard-filename file)))
7560 t t cmd)))
7561 (save-window-excursion
7562 (start-process-shell-command cmd nil cmd)
7563 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7565 ((or (stringp cmd)
7566 (eq cmd 'emacs))
7567 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7568 (widen)
7569 (if line (goto-line line)
7570 (if search (org-link-search search))))
7571 ((consp cmd)
7572 (let ((file (convert-standard-filename file)))
7573 (eval cmd)))
7574 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7575 (and (org-mode-p) (eq old-mode 'org-mode)
7576 (or (not (equal old-buffer (current-buffer)))
7577 (not (equal old-pos (point))))
7578 (org-mark-ring-push old-pos old-buffer))))
7580 (defun org-default-apps ()
7581 "Return the default applications for this operating system."
7582 (cond
7583 ((eq system-type 'darwin)
7584 org-file-apps-defaults-macosx)
7585 ((eq system-type 'windows-nt)
7586 org-file-apps-defaults-windowsnt)
7587 (t org-file-apps-defaults-gnu)))
7589 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7590 (defun org-file-remote-p (file)
7591 "Test whether FILE specifies a location on a remote system.
7592 Return non-nil if the location is indeed remote.
7594 For example, the filename \"/user@host:/foo\" specifies a location
7595 on the system \"/user@host:\"."
7596 (cond ((fboundp 'file-remote-p)
7597 (file-remote-p file))
7598 ((fboundp 'tramp-handle-file-remote-p)
7599 (tramp-handle-file-remote-p file))
7600 ((and (boundp 'ange-ftp-name-format)
7601 (string-match (car ange-ftp-name-format) file))
7603 (t nil)))
7606 ;;;; Refiling
7608 (defun org-get-org-file ()
7609 "Read a filename, with default directory `org-directory'."
7610 (let ((default (or org-default-notes-file remember-data-file)))
7611 (read-file-name (format "File name [%s]: " default)
7612 (file-name-as-directory org-directory)
7613 default)))
7615 (defun org-notes-order-reversed-p ()
7616 "Check if the current file should receive notes in reversed order."
7617 (cond
7618 ((not org-reverse-note-order) nil)
7619 ((eq t org-reverse-note-order) t)
7620 ((not (listp org-reverse-note-order)) nil)
7621 (t (catch 'exit
7622 (let ((all org-reverse-note-order)
7623 entry)
7624 (while (setq entry (pop all))
7625 (if (string-match (car entry) buffer-file-name)
7626 (throw 'exit (cdr entry))))
7627 nil)))))
7629 (defvar org-refile-target-table nil
7630 "The list of refile targets, created by `org-refile'.")
7632 (defvar org-agenda-new-buffers nil
7633 "Buffers created to visit agenda files.")
7635 (defun org-get-refile-targets (&optional default-buffer)
7636 "Produce a table with refile targets."
7637 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7638 targets txt re files f desc descre)
7639 (with-current-buffer (or default-buffer (current-buffer))
7640 (while (setq entry (pop entries))
7641 (setq files (car entry) desc (cdr entry))
7642 (cond
7643 ((null files) (setq files (list (current-buffer))))
7644 ((eq files 'org-agenda-files)
7645 (setq files (org-agenda-files 'unrestricted)))
7646 ((and (symbolp files) (fboundp files))
7647 (setq files (funcall files)))
7648 ((and (symbolp files) (boundp files))
7649 (setq files (symbol-value files))))
7650 (if (stringp files) (setq files (list files)))
7651 (cond
7652 ((eq (car desc) :tag)
7653 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7654 ((eq (car desc) :todo)
7655 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7656 ((eq (car desc) :regexp)
7657 (setq descre (cdr desc)))
7658 ((eq (car desc) :level)
7659 (setq descre (concat "^\\*\\{" (number-to-string
7660 (if org-odd-levels-only
7661 (1- (* 2 (cdr desc)))
7662 (cdr desc)))
7663 "\\}[ \t]")))
7664 ((eq (car desc) :maxlevel)
7665 (setq descre (concat "^\\*\\{1," (number-to-string
7666 (if org-odd-levels-only
7667 (1- (* 2 (cdr desc)))
7668 (cdr desc)))
7669 "\\}[ \t]")))
7670 (t (error "Bad refiling target description %s" desc)))
7671 (while (setq f (pop files))
7672 (save-excursion
7673 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7674 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7675 (save-excursion
7676 (save-restriction
7677 (widen)
7678 (goto-char (point-min))
7679 (while (re-search-forward descre nil t)
7680 (goto-char (point-at-bol))
7681 (when (looking-at org-complex-heading-regexp)
7682 (setq txt (match-string 4)
7683 re (concat "^" (regexp-quote
7684 (buffer-substring (match-beginning 1)
7685 (match-end 4)))))
7686 (if (match-end 5) (setq re (concat re "[ \t]+"
7687 (regexp-quote
7688 (match-string 5)))))
7689 (setq re (concat re "[ \t]*$"))
7690 (when org-refile-use-outline-path
7691 (setq txt (mapconcat 'identity
7692 (append
7693 (if (eq org-refile-use-outline-path 'file)
7694 (list (file-name-nondirectory
7695 (buffer-file-name (buffer-base-buffer))))
7696 (if (eq org-refile-use-outline-path 'full-file-path)
7697 (list (buffer-file-name (buffer-base-buffer)))))
7698 (org-get-outline-path)
7699 (list txt))
7700 "/")))
7701 (push (list txt f re (point)) targets))
7702 (goto-char (point-at-eol))))))))
7703 (nreverse targets))))
7705 (defun org-get-outline-path ()
7706 "Return the outline path to the current entry, as a list."
7707 (let (rtn)
7708 (save-excursion
7709 (while (org-up-heading-safe)
7710 (when (looking-at org-complex-heading-regexp)
7711 (push (org-match-string-no-properties 4) rtn)))
7712 rtn)))
7714 (defvar org-refile-history nil
7715 "History for refiling operations.")
7717 (defun org-refile (&optional goto default-buffer)
7718 "Move the entry at point to another heading.
7719 The list of target headings is compiled using the information in
7720 `org-refile-targets', which see. This list is created before each use
7721 and will therefore always be up-to-date.
7723 At the target location, the entry is filed as a subitem of the target heading.
7724 Depending on `org-reverse-note-order', the new subitem will either be the
7725 first of the last subitem.
7727 With prefix arg GOTO, the command will only visit the target location,
7728 not actually move anything.
7729 With a double prefix `C-c C-c', go to the location where the last refiling
7730 operation has put the subtree."
7731 (interactive "P")
7732 (let* ((cbuf (current-buffer))
7733 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7734 pos it nbuf file re level reversed)
7735 (if (equal goto '(16))
7736 (org-refile-goto-last-stored)
7737 (when (setq it (org-refile-get-location
7738 (if goto "Goto: " "Refile to: ") default-buffer))
7739 (setq file (nth 1 it)
7740 re (nth 2 it)
7741 pos (nth 3 it))
7742 (setq nbuf (or (find-buffer-visiting file)
7743 (find-file-noselect file)))
7744 (if goto
7745 (progn
7746 (switch-to-buffer nbuf)
7747 (goto-char pos)
7748 (org-show-context 'org-goto))
7749 (org-copy-subtree 1 nil t)
7750 (save-excursion
7751 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7752 (find-file-noselect file))))
7753 (setq reversed (org-notes-order-reversed-p))
7754 (save-excursion
7755 (save-restriction
7756 (widen)
7757 (goto-char pos)
7758 (looking-at outline-regexp)
7759 (setq level (org-get-valid-level (funcall outline-level) 1))
7760 (goto-char
7761 (if reversed
7762 (outline-next-heading)
7763 (or (save-excursion (outline-get-next-sibling))
7764 (org-end-of-subtree t t)
7765 (point-max))))
7766 (bookmark-set "org-refile-last-stored")
7767 (org-paste-subtree level))))
7768 (org-cut-subtree)
7769 (setq org-markers-to-move nil)
7770 (message "Entry refiled to \"%s\"" (car it)))))))
7772 (defun org-refile-goto-last-stored ()
7773 "Go to the location where the last refile was stored."
7774 (interactive)
7775 (bookmark-jump "org-refile-last-stored")
7776 (message "This is the location of the last refile"))
7778 (defun org-refile-get-location (&optional prompt default-buffer)
7779 "Prompt the user for a refile location, using PROMPT."
7780 (let ((org-refile-targets org-refile-targets)
7781 (org-refile-use-outline-path org-refile-use-outline-path))
7782 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7783 (unless org-refile-target-table
7784 (error "No refile targets"))
7785 (let* ((cbuf (current-buffer))
7786 (cfunc (if org-refile-use-outline-path
7787 'org-olpath-completing-read
7788 'completing-read))
7789 (extra (if org-refile-use-outline-path "/" ""))
7790 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7791 (fname (and filename (file-truename filename)))
7792 (tbl (mapcar
7793 (lambda (x)
7794 (if (not (equal fname (file-truename (nth 1 x))))
7795 (cons (concat (car x) extra " ("
7796 (file-name-nondirectory (nth 1 x)) ")")
7797 (cdr x))
7798 (cons (concat (car x) extra) (cdr x))))
7799 org-refile-target-table))
7800 (completion-ignore-case t))
7801 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7802 tbl)))
7804 (defun org-olpath-completing-read (prompt collection &rest args)
7805 "Read an outline path like a file name."
7806 (let ((thetable collection))
7807 (apply
7808 'completing-read prompt
7809 (lambda (string predicate &optional flag)
7810 (let (rtn r s f (l (length string)))
7811 (cond
7812 ((eq flag nil)
7813 ;; try completion
7814 (try-completion string thetable))
7815 ((eq flag t)
7816 ;; all-completions
7817 (setq rtn (all-completions string thetable predicate))
7818 (mapcar
7819 (lambda (x)
7820 (setq r (substring x l))
7821 (if (string-match " ([^)]*)$" x)
7822 (setq f (match-string 0 x))
7823 (setq f ""))
7824 (if (string-match "/" r)
7825 (concat string (substring r 0 (match-end 0)) f)
7827 rtn))
7828 ((eq flag 'lambda)
7829 ;; exact match?
7830 (assoc string thetable)))
7832 args)))
7834 ;;;; Dynamic blocks
7836 (defun org-find-dblock (name)
7837 "Find the first dynamic block with name NAME in the buffer.
7838 If not found, stay at current position and return nil."
7839 (let (pos)
7840 (save-excursion
7841 (goto-char (point-min))
7842 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7843 nil t)
7844 (match-beginning 0))))
7845 (if pos (goto-char pos))
7846 pos))
7848 (defconst org-dblock-start-re
7849 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7850 "Matches the startline of a dynamic block, with parameters.")
7852 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7853 "Matches the end of a dyhamic block.")
7855 (defun org-create-dblock (plist)
7856 "Create a dynamic block section, with parameters taken from PLIST.
7857 PLIST must containe a :name entry which is used as name of the block."
7858 (unless (bolp) (newline))
7859 (let ((name (plist-get plist :name)))
7860 (insert "#+BEGIN: " name)
7861 (while plist
7862 (if (eq (car plist) :name)
7863 (setq plist (cddr plist))
7864 (insert " " (prin1-to-string (pop plist)))))
7865 (insert "\n\n#+END:\n")
7866 (beginning-of-line -2)))
7868 (defun org-prepare-dblock ()
7869 "Prepare dynamic block for refresh.
7870 This empties the block, puts the cursor at the insert position and returns
7871 the property list including an extra property :name with the block name."
7872 (unless (looking-at org-dblock-start-re)
7873 (error "Not at a dynamic block"))
7874 (let* ((begdel (1+ (match-end 0)))
7875 (name (org-no-properties (match-string 1)))
7876 (params (append (list :name name)
7877 (read (concat "(" (match-string 3) ")")))))
7878 (unless (re-search-forward org-dblock-end-re nil t)
7879 (error "Dynamic block not terminated"))
7880 (setq params
7881 (append params
7882 (list :content (buffer-substring
7883 begdel (match-beginning 0)))))
7884 (delete-region begdel (match-beginning 0))
7885 (goto-char begdel)
7886 (open-line 1)
7887 params))
7889 (defun org-map-dblocks (&optional command)
7890 "Apply COMMAND to all dynamic blocks in the current buffer.
7891 If COMMAND is not given, use `org-update-dblock'."
7892 (let ((cmd (or command 'org-update-dblock))
7893 pos)
7894 (save-excursion
7895 (goto-char (point-min))
7896 (while (re-search-forward org-dblock-start-re nil t)
7897 (goto-char (setq pos (match-beginning 0)))
7898 (condition-case nil
7899 (funcall cmd)
7900 (error (message "Error during update of dynamic block")))
7901 (goto-char pos)
7902 (unless (re-search-forward org-dblock-end-re nil t)
7903 (error "Dynamic block not terminated"))))))
7905 (defun org-dblock-update (&optional arg)
7906 "User command for updating dynamic blocks.
7907 Update the dynamic block at point. With prefix ARG, update all dynamic
7908 blocks in the buffer."
7909 (interactive "P")
7910 (if arg
7911 (org-update-all-dblocks)
7912 (or (looking-at org-dblock-start-re)
7913 (org-beginning-of-dblock))
7914 (org-update-dblock)))
7916 (defun org-update-dblock ()
7917 "Update the dynamic block at point
7918 This means to empty the block, parse for parameters and then call
7919 the correct writing function."
7920 (save-window-excursion
7921 (let* ((pos (point))
7922 (line (org-current-line))
7923 (params (org-prepare-dblock))
7924 (name (plist-get params :name))
7925 (cmd (intern (concat "org-dblock-write:" name))))
7926 (message "Updating dynamic block `%s' at line %d..." name line)
7927 (funcall cmd params)
7928 (message "Updating dynamic block `%s' at line %d...done" name line)
7929 (goto-char pos))))
7931 (defun org-beginning-of-dblock ()
7932 "Find the beginning of the dynamic block at point.
7933 Error if there is no scuh block at point."
7934 (let ((pos (point))
7935 beg)
7936 (end-of-line 1)
7937 (if (and (re-search-backward org-dblock-start-re nil t)
7938 (setq beg (match-beginning 0))
7939 (re-search-forward org-dblock-end-re nil t)
7940 (> (match-end 0) pos))
7941 (goto-char beg)
7942 (goto-char pos)
7943 (error "Not in a dynamic block"))))
7945 (defun org-update-all-dblocks ()
7946 "Update all dynamic blocks in the buffer.
7947 This function can be used in a hook."
7948 (when (org-mode-p)
7949 (org-map-dblocks 'org-update-dblock)))
7952 ;;;; Completion
7954 (defconst org-additional-option-like-keywords
7955 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7956 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7957 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7959 (defcustom org-structure-template-alist
7961 ("s" "#+begin_src ?\n\n#+end_src"
7962 "<src lang=\"?\">\n\n</src>")
7963 ("e" "#+begin_example\n?\n#+end_example"
7964 "<example>\n?\n</example>")
7965 ("q" "#+begin_quote\n?\n#+end_quote"
7966 "<quote>\n?\n</quote>")
7967 ("v" "#+begin_verse\n?\n#+end_verse"
7968 "<verse>\n?\n/verse>")
7969 ("l" "#+begin_latex\n?\n#+end_latex"
7970 "<literal style=\"latex\">\n?\n</literal>")
7971 ("L" "#+latex: "
7972 "<literal style=\"latex\">?</literal>")
7973 ("h" "#+begin_html\n?\n#+end_html"
7974 "<literal style=\"html\">\n?\n</literal>")
7975 ("H" "#+html: "
7976 "<literal style=\"html\">?</literal>")
7977 ("a" "#+begin_ascii\n?\n#+end_ascii")
7978 ("A" "#+ascii: ")
7979 ("i" "#+include %file ?"
7980 "<include file=%file markup=\"?\">")
7982 "Structure completion elements.
7983 This is a list of abbreviation keys and values. The value gets inserted
7984 it you type @samp{.} followed by the key and then the completion key,
7985 usually `M-TAB'. %file will be replaced by a file name after prompting
7986 for the file uning completion.
7987 There are two templates for each key, the first uses the original Org syntax,
7988 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7989 the default when the /org-mtags.el/ module has been loaded. See also the
7990 variable `org-mtags-prefere-muse-templates'.
7991 This is an experimental feature, it is undecided if it is going to stay in."
7992 :group 'org-completion
7993 :type '(repeat
7994 (string :tag "Key")
7995 (string :tag "Template")
7996 (string :tag "Muse Template")))
7998 (defun org-try-structure-completion ()
7999 "Try to complete a structure template before point.
8000 This looks for strings like \"<e\" on an otherwise empty line and
8001 expands them."
8002 (let ((l (buffer-substring (point-at-bol) (point)))
8004 (when (and (looking-at "[ \t]*$")
8005 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8006 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8007 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8008 (match-beginning 1)) a)
8009 t)))
8011 (defun org-complete-expand-structure-template (start cell)
8012 "Expand a structure template."
8013 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8014 (rpl (nth (if musep 2 1) cell)))
8015 (delete-region start (point))
8016 (when (string-match "\\`#\\+" rpl)
8017 (cond
8018 ((bolp))
8019 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8020 (delete-region (point-at-bol) (point)))
8021 (t (newline))))
8022 (setq start (point))
8023 (if (string-match "%file" rpl)
8024 (setq rpl (replace-match
8025 (concat
8026 "\""
8027 (save-match-data
8028 (abbreviate-file-name (read-file-name "Include file: ")))
8029 "\"")
8030 t t rpl)))
8031 (insert rpl)
8032 (if (re-search-backward "\\?" start t) (delete-char 1))))
8035 (defun org-complete (&optional arg)
8036 "Perform completion on word at point.
8037 At the beginning of a headline, this completes TODO keywords as given in
8038 `org-todo-keywords'.
8039 If the current word is preceded by a backslash, completes the TeX symbols
8040 that are supported for HTML support.
8041 If the current word is preceded by \"#+\", completes special words for
8042 setting file options.
8043 In the line after \"#+STARTUP:, complete valid keywords.\"
8044 At all other locations, this simply calls the value of
8045 `org-completion-fallback-command'."
8046 (interactive "P")
8047 (org-without-partial-completion
8048 (catch 'exit
8049 (let* ((a nil)
8050 (end (point))
8051 (beg1 (save-excursion
8052 (skip-chars-backward (org-re "[:alnum:]_@"))
8053 (point)))
8054 (beg (save-excursion
8055 (skip-chars-backward "a-zA-Z0-9_:$")
8056 (point)))
8057 (confirm (lambda (x) (stringp (car x))))
8058 (searchhead (equal (char-before beg) ?*))
8059 (struct
8060 (when (and (member (char-before beg1) '(?. ?<))
8061 (setq a (assoc (buffer-substring beg1 (point))
8062 org-structure-template-alist)))
8063 (org-complete-expand-structure-template (1- beg1) a)
8064 (throw 'exit t)))
8065 (tag (and (equal (char-before beg1) ?:)
8066 (equal (char-after (point-at-bol)) ?*)))
8067 (prop (and (equal (char-before beg1) ?:)
8068 (not (equal (char-after (point-at-bol)) ?*))))
8069 (texp (equal (char-before beg) ?\\))
8070 (link (equal (char-before beg) ?\[))
8071 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8072 beg)
8073 "#+"))
8074 (startup (string-match "^#\\+STARTUP:.*"
8075 (buffer-substring (point-at-bol) (point))))
8076 (completion-ignore-case opt)
8077 (type nil)
8078 (tbl nil)
8079 (table (cond
8080 (opt
8081 (setq type :opt)
8082 (require 'org-exp)
8083 (append
8084 (mapcar
8085 (lambda (x)
8086 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8087 (cons (match-string 2 x) (match-string 1 x)))
8088 (org-split-string (org-get-current-options) "\n"))
8089 (mapcar 'list org-additional-option-like-keywords)))
8090 (startup
8091 (setq type :startup)
8092 org-startup-options)
8093 (link (append org-link-abbrev-alist-local
8094 org-link-abbrev-alist))
8095 (texp
8096 (setq type :tex)
8097 org-html-entities)
8098 ((string-match "\\`\\*+[ \t]+\\'"
8099 (buffer-substring (point-at-bol) beg))
8100 (setq type :todo)
8101 (mapcar 'list org-todo-keywords-1))
8102 (searchhead
8103 (setq type :searchhead)
8104 (save-excursion
8105 (goto-char (point-min))
8106 (while (re-search-forward org-todo-line-regexp nil t)
8107 (push (list
8108 (org-make-org-heading-search-string
8109 (match-string 3) t))
8110 tbl)))
8111 tbl)
8112 (tag (setq type :tag beg beg1)
8113 (or org-tag-alist (org-get-buffer-tags)))
8114 (prop (setq type :prop beg beg1)
8115 (mapcar 'list (org-buffer-property-keys nil t t)))
8116 (t (progn
8117 (call-interactively org-completion-fallback-command)
8118 (throw 'exit nil)))))
8119 (pattern (buffer-substring-no-properties beg end))
8120 (completion (try-completion pattern table confirm)))
8121 (cond ((eq completion t)
8122 (if (not (assoc (upcase pattern) table))
8123 (message "Already complete")
8124 (if (and (equal type :opt)
8125 (not (member (car (assoc (upcase pattern) table))
8126 org-additional-option-like-keywords)))
8127 (insert (substring (cdr (assoc (upcase pattern) table))
8128 (length pattern)))
8129 (if (memq type '(:tag :prop)) (insert ":")))))
8130 ((null completion)
8131 (message "Can't find completion for \"%s\"" pattern)
8132 (ding))
8133 ((not (string= pattern completion))
8134 (delete-region beg end)
8135 (if (string-match " +$" completion)
8136 (setq completion (replace-match "" t t completion)))
8137 (insert completion)
8138 (if (get-buffer-window "*Completions*")
8139 (delete-window (get-buffer-window "*Completions*")))
8140 (if (assoc completion table)
8141 (if (eq type :todo) (insert " ")
8142 (if (memq type '(:tag :prop)) (insert ":"))))
8143 (if (and (equal type :opt) (assoc completion table))
8144 (message "%s" (substitute-command-keys
8145 "Press \\[org-complete] again to insert example settings"))))
8147 (message "Making completion list...")
8148 (let ((list (sort (all-completions pattern table confirm)
8149 'string<)))
8150 (with-output-to-temp-buffer "*Completions*"
8151 (condition-case nil
8152 ;; Protection needed for XEmacs and emacs 21
8153 (display-completion-list list pattern)
8154 (error (display-completion-list list)))))
8155 (message "Making completion list...%s" "done")))))))
8157 ;;;; TODO, DEADLINE, Comments
8159 (defun org-toggle-comment ()
8160 "Change the COMMENT state of an entry."
8161 (interactive)
8162 (save-excursion
8163 (org-back-to-heading)
8164 (let (case-fold-search)
8165 (if (looking-at (concat outline-regexp
8166 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8167 (replace-match "" t t nil 1)
8168 (if (looking-at outline-regexp)
8169 (progn
8170 (goto-char (match-end 0))
8171 (insert org-comment-string " ")))))))
8173 (defvar org-last-todo-state-is-todo nil
8174 "This is non-nil when the last TODO state change led to a TODO state.
8175 If the last change removed the TODO tag or switched to DONE, then
8176 this is nil.")
8178 (defvar org-setting-tags nil) ; dynamically skiped
8180 (defun org-parse-local-options (string var)
8181 "Parse STRING for startup setting relevant for variable VAR."
8182 (let ((rtn (symbol-value var))
8183 e opts)
8184 (save-match-data
8185 (if (or (not string) (not (string-match "\\S-" string)))
8187 (setq opts (delq nil (mapcar (lambda (x)
8188 (setq e (assoc x org-startup-options))
8189 (if (eq (nth 1 e) var) e nil))
8190 (org-split-string string "[ \t]+"))))
8191 (if (not opts)
8193 (setq rtn nil)
8194 (while (setq e (pop opts))
8195 (if (not (nth 3 e))
8196 (setq rtn (nth 2 e))
8197 (if (not (listp rtn)) (setq rtn nil))
8198 (push (nth 2 e) rtn)))
8199 rtn)))))
8201 (defvar org-blocker-hook nil
8202 "Hook for functions that are allowed to block a state change.
8204 Each function gets as its single argument a property list, see
8205 `org-trigger-hook' for more information about this list.
8207 If any of the functions in this hook returns nil, the state change
8208 is blocked.")
8210 (defvar org-trigger-hook nil
8211 "Hook for functions that are triggered by a state change.
8213 Each function gets as its single argument a property list with at least
8214 the following elements:
8216 (:type type-of-change :position pos-at-entry-start
8217 :from old-state :to new-state)
8219 Depending on the type, more properties may be present.
8221 This mechanism is currently implemented for:
8223 TODO state changes
8224 ------------------
8225 :type todo-state-change
8226 :from previous state (keyword as a string), or nil
8227 :to new state (keyword as a string), or nil")
8230 (defun org-todo (&optional arg)
8231 "Change the TODO state of an item.
8232 The state of an item is given by a keyword at the start of the heading,
8233 like
8234 *** TODO Write paper
8235 *** DONE Call mom
8237 The different keywords are specified in the variable `org-todo-keywords'.
8238 By default the available states are \"TODO\" and \"DONE\".
8239 So for this example: when the item starts with TODO, it is changed to DONE.
8240 When it starts with DONE, the DONE is removed. And when neither TODO nor
8241 DONE are present, add TODO at the beginning of the heading.
8243 With C-u prefix arg, use completion to determine the new state.
8244 With numeric prefix arg, switch to that state.
8246 For calling through lisp, arg is also interpreted in the following way:
8247 'none -> empty state
8248 \"\"(empty string) -> switch to empty state
8249 'done -> switch to DONE
8250 'nextset -> switch to the next set of keywords
8251 'previousset -> switch to the previous set of keywords
8252 \"WAITING\" -> switch to the specified keyword, but only if it
8253 really is a member of `org-todo-keywords'."
8254 (interactive "P")
8255 (save-excursion
8256 (catch 'exit
8257 (org-back-to-heading)
8258 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8259 (or (looking-at (concat " +" org-todo-regexp " *"))
8260 (looking-at " *"))
8261 (let* ((match-data (match-data))
8262 (startpos (point-at-bol))
8263 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8264 (org-log-done org-log-done)
8265 (org-log-repeat org-log-repeat)
8266 (org-todo-log-states org-todo-log-states)
8267 (this (match-string 1))
8268 (hl-pos (match-beginning 0))
8269 (head (org-get-todo-sequence-head this))
8270 (ass (assoc head org-todo-kwd-alist))
8271 (interpret (nth 1 ass))
8272 (done-word (nth 3 ass))
8273 (final-done-word (nth 4 ass))
8274 (last-state (or this ""))
8275 (completion-ignore-case t)
8276 (member (member this org-todo-keywords-1))
8277 (tail (cdr member))
8278 (state (cond
8279 ((and org-todo-key-trigger
8280 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8281 (and (not arg) org-use-fast-todo-selection
8282 (not (eq org-use-fast-todo-selection 'prefix)))))
8283 ;; Use fast selection
8284 (org-fast-todo-selection))
8285 ((and (equal arg '(4))
8286 (or (not org-use-fast-todo-selection)
8287 (not org-todo-key-trigger)))
8288 ;; Read a state with completion
8289 (completing-read "State: " (mapcar (lambda(x) (list x))
8290 org-todo-keywords-1)
8291 nil t))
8292 ((eq arg 'right)
8293 (if this
8294 (if tail (car tail) nil)
8295 (car org-todo-keywords-1)))
8296 ((eq arg 'left)
8297 (if (equal member org-todo-keywords-1)
8299 (if this
8300 (nth (- (length org-todo-keywords-1) (length tail) 2)
8301 org-todo-keywords-1)
8302 (org-last org-todo-keywords-1))))
8303 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8304 (setq arg nil))) ; hack to fall back to cycling
8305 (arg
8306 ;; user or caller requests a specific state
8307 (cond
8308 ((equal arg "") nil)
8309 ((eq arg 'none) nil)
8310 ((eq arg 'done) (or done-word (car org-done-keywords)))
8311 ((eq arg 'nextset)
8312 (or (car (cdr (member head org-todo-heads)))
8313 (car org-todo-heads)))
8314 ((eq arg 'previousset)
8315 (let ((org-todo-heads (reverse org-todo-heads)))
8316 (or (car (cdr (member head org-todo-heads)))
8317 (car org-todo-heads))))
8318 ((car (member arg org-todo-keywords-1)))
8319 ((nth (1- (prefix-numeric-value arg))
8320 org-todo-keywords-1))))
8321 ((null member) (or head (car org-todo-keywords-1)))
8322 ((equal this final-done-word) nil) ;; -> make empty
8323 ((null tail) nil) ;; -> first entry
8324 ((eq interpret 'sequence)
8325 (car tail))
8326 ((memq interpret '(type priority))
8327 (if (eq this-command last-command)
8328 (car tail)
8329 (if (> (length tail) 0)
8330 (or done-word (car org-done-keywords))
8331 nil)))
8332 (t nil)))
8333 (next (if state (concat " " state " ") " "))
8334 (change-plist (list :type 'todo-state-change :from this :to state
8335 :position startpos))
8336 dolog now-done-p)
8337 (when org-blocker-hook
8338 (unless (save-excursion
8339 (save-match-data
8340 (run-hook-with-args-until-failure
8341 'org-blocker-hook change-plist)))
8342 (if (interactive-p)
8343 (error "TODO state change from %s to %s blocked" this state)
8344 ;; fail silently
8345 (message "TODO state change from %s to %s blocked" this state)
8346 (throw 'exit nil))))
8347 (store-match-data match-data)
8348 (replace-match next t t)
8349 (unless (pos-visible-in-window-p hl-pos)
8350 (message "TODO state changed to %s" (org-trim next)))
8351 (unless head
8352 (setq head (org-get-todo-sequence-head state)
8353 ass (assoc head org-todo-kwd-alist)
8354 interpret (nth 1 ass)
8355 done-word (nth 3 ass)
8356 final-done-word (nth 4 ass)))
8357 (when (memq arg '(nextset previousset))
8358 (message "Keyword-Set %d/%d: %s"
8359 (- (length org-todo-sets) -1
8360 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8361 (length org-todo-sets)
8362 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8363 (setq org-last-todo-state-is-todo
8364 (not (member state org-done-keywords)))
8365 (setq now-done-p (and (member state org-done-keywords)
8366 (not (member this org-done-keywords))))
8367 (and logging (org-local-logging logging))
8368 (when (and (or org-todo-log-states org-log-done)
8369 (not (memq arg '(nextset previousset))))
8370 ;; we need to look at recording a time and note
8371 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8372 (nth 2 (assoc this org-todo-log-states))))
8373 (when (and state
8374 (member state org-not-done-keywords)
8375 (not (member this org-not-done-keywords)))
8376 ;; This is now a todo state and was not one before
8377 ;; If there was a CLOSED time stamp, get rid of it.
8378 (org-add-planning-info nil nil 'closed))
8379 (when (and now-done-p org-log-done)
8380 ;; It is now done, and it was not done before
8381 (org-add-planning-info 'closed (org-current-time))
8382 (if (and (not dolog) (eq 'note org-log-done))
8383 (org-add-log-setup 'done state 'findpos 'note)))
8384 (when (and state dolog)
8385 ;; This is a non-nil state, and we need to log it
8386 (org-add-log-setup 'state state 'findpos dolog)))
8387 ;; Fixup tag positioning
8388 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8389 (when org-provide-todo-statistics
8390 (org-update-parent-todo-statistics))
8391 (run-hooks 'org-after-todo-state-change-hook)
8392 (if (and arg (not (member state org-done-keywords)))
8393 (setq head (org-get-todo-sequence-head state)))
8394 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8395 ;; Do we need to trigger a repeat?
8396 (when now-done-p (org-auto-repeat-maybe state))
8397 ;; Fixup cursor location if close to the keyword
8398 (if (and (outline-on-heading-p)
8399 (not (bolp))
8400 (save-excursion (beginning-of-line 1)
8401 (looking-at org-todo-line-regexp))
8402 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8403 (progn
8404 (goto-char (or (match-end 2) (match-end 1)))
8405 (just-one-space)))
8406 (when org-trigger-hook
8407 (save-excursion
8408 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8410 (defun org-update-parent-todo-statistics ()
8411 "Update any statistics cookie in the parent of the current headline."
8412 (interactive)
8413 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8414 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8415 (catch 'exit
8416 (save-excursion
8417 (setq level (org-up-heading-safe))
8418 (unless (and level
8419 (re-search-forward box-re (point-at-eol) t))
8420 (throw 'exit nil))
8421 (setq is-percent (match-end 2))
8422 (save-match-data
8423 (unless (outline-next-heading) (throw 'exit nil))
8424 (while (looking-at org-todo-line-regexp)
8425 (setq kwd (match-string 2))
8426 (and kwd (setq cnt-all (1+ cnt-all)))
8427 (and (member kwd org-done-keywords)
8428 (setq cnt-done (1+ cnt-done)))
8429 (condition-case nil
8430 (outline-forward-same-level 1)
8431 (error (end-of-line 1)))))
8432 (replace-match
8433 (if is-percent
8434 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8435 (format "[%d/%d]" cnt-done cnt-all)))
8436 (run-hook-with-args 'org-after-todo-statistics-hook
8437 cnt-done (- cnt-all cnt-done))))))
8439 (defvar org-after-todo-statistics-hook nil
8440 "Hook that is called after a TODO statistics cookie has been updated.
8441 Each function is called with two arguments: the number of not-done entries
8442 and the number of done entries.
8444 For example, the following function, when added to this hook, will switch
8445 an entry to DONE when all children are done, and back to TODO when new
8446 entries are set to a TODO status. Note that this hook is only called
8447 when there is a statistics cookie in the headline!
8449 (defun org-summary-todo (n-done n-not-done)
8450 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8451 (let (org-log-done org-log-states) ; turn off logging
8452 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8455 (defun org-local-logging (value)
8456 "Get logging settings from a property VALUE."
8457 (let* (words w a)
8458 ;; directly set the variables, they are already local.
8459 (setq org-log-done nil
8460 org-log-repeat nil
8461 org-todo-log-states nil)
8462 (setq words (org-split-string value))
8463 (while (setq w (pop words))
8464 (cond
8465 ((setq a (assoc w org-startup-options))
8466 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8467 (set (nth 1 a) (nth 2 a))))
8468 ((setq a (org-extract-log-state-settings w))
8469 (and (member (car a) org-todo-keywords-1)
8470 (push a org-todo-log-states)))))))
8472 (defun org-get-todo-sequence-head (kwd)
8473 "Return the head of the TODO sequence to which KWD belongs.
8474 If KWD is not set, check if there is a text property remembering the
8475 right sequence."
8476 (let (p)
8477 (cond
8478 ((not kwd)
8479 (or (get-text-property (point-at-bol) 'org-todo-head)
8480 (progn
8481 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8482 nil (point-at-eol)))
8483 (get-text-property p 'org-todo-head))))
8484 ((not (member kwd org-todo-keywords-1))
8485 (car org-todo-keywords-1))
8486 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8488 (defun org-fast-todo-selection ()
8489 "Fast TODO keyword selection with single keys.
8490 Returns the new TODO keyword, or nil if no state change should occur."
8491 (let* ((fulltable org-todo-key-alist)
8492 (done-keywords org-done-keywords) ;; needed for the faces.
8493 (maxlen (apply 'max (mapcar
8494 (lambda (x)
8495 (if (stringp (car x)) (string-width (car x)) 0))
8496 fulltable)))
8497 (expert nil)
8498 (fwidth (+ maxlen 3 1 3))
8499 (ncol (/ (- (window-width) 4) fwidth))
8500 tg cnt e c tbl
8501 groups ingroup)
8502 (save-window-excursion
8503 (if expert
8504 (set-buffer (get-buffer-create " *Org todo*"))
8505 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8506 (erase-buffer)
8507 (org-set-local 'org-done-keywords done-keywords)
8508 (setq tbl fulltable cnt 0)
8509 (while (setq e (pop tbl))
8510 (cond
8511 ((equal e '(:startgroup))
8512 (push '() groups) (setq ingroup t)
8513 (when (not (= cnt 0))
8514 (setq cnt 0)
8515 (insert "\n"))
8516 (insert "{ "))
8517 ((equal e '(:endgroup))
8518 (setq ingroup nil cnt 0)
8519 (insert "}\n"))
8521 (setq tg (car e) c (cdr e))
8522 (if ingroup (push tg (car groups)))
8523 (setq tg (org-add-props tg nil 'face
8524 (org-get-todo-face tg)))
8525 (if (and (= cnt 0) (not ingroup)) (insert " "))
8526 (insert "[" c "] " tg (make-string
8527 (- fwidth 4 (length tg)) ?\ ))
8528 (when (= (setq cnt (1+ cnt)) ncol)
8529 (insert "\n")
8530 (if ingroup (insert " "))
8531 (setq cnt 0)))))
8532 (insert "\n")
8533 (goto-char (point-min))
8534 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8535 (fit-window-to-buffer))
8536 (message "[a-z..]:Set [SPC]:clear")
8537 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8538 (cond
8539 ((or (= c ?\C-g)
8540 (and (= c ?q) (not (rassoc c fulltable))))
8541 (setq quit-flag t))
8542 ((= c ?\ ) nil)
8543 ((setq e (rassoc c fulltable) tg (car e))
8545 (t (setq quit-flag t))))))
8547 (defun org-entry-is-todo-p ()
8548 (member (org-get-todo-state) org-not-done-keywords))
8550 (defun org-entry-is-done-p ()
8551 (member (org-get-todo-state) org-done-keywords))
8553 (defun org-get-todo-state ()
8554 (save-excursion
8555 (org-back-to-heading t)
8556 (and (looking-at org-todo-line-regexp)
8557 (match-end 2)
8558 (match-string 2))))
8560 (defun org-at-date-range-p (&optional inactive-ok)
8561 "Is the cursor inside a date range?"
8562 (interactive)
8563 (save-excursion
8564 (catch 'exit
8565 (let ((pos (point)))
8566 (skip-chars-backward "^[<\r\n")
8567 (skip-chars-backward "<[")
8568 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8569 (>= (match-end 0) pos)
8570 (throw 'exit t))
8571 (skip-chars-backward "^<[\r\n")
8572 (skip-chars-backward "<[")
8573 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8574 (>= (match-end 0) pos)
8575 (throw 'exit t)))
8576 nil)))
8578 (defun org-get-repeat ()
8579 "Check if tere is a deadline/schedule with repeater in this entry."
8580 (save-match-data
8581 (save-excursion
8582 (org-back-to-heading t)
8583 (if (re-search-forward
8584 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8585 (match-string 1)))))
8587 (defvar org-last-changed-timestamp)
8588 (defvar org-log-post-message)
8589 (defvar org-log-note-purpose)
8590 (defvar org-log-note-how)
8591 (defun org-auto-repeat-maybe (done-word)
8592 "Check if the current headline contains a repeated deadline/schedule.
8593 If yes, set TODO state back to what it was and change the base date
8594 of repeating deadline/scheduled time stamps to new date.
8595 This function is run automatically after each state change to a DONE state."
8596 ;; last-state is dynamically scoped into this function
8597 (let* ((repeat (org-get-repeat))
8598 (aa (assoc last-state org-todo-kwd-alist))
8599 (interpret (nth 1 aa))
8600 (head (nth 2 aa))
8601 (whata '(("d" . day) ("m" . month) ("y" . year)))
8602 (msg "Entry repeats: ")
8603 (org-log-done nil)
8604 (org-todo-log-states nil)
8605 (nshiftmax 10) (nshift 0)
8606 re type n what ts mb0 time)
8607 (when repeat
8608 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8609 (org-todo (if (eq interpret 'type) last-state head))
8610 (when org-log-repeat
8611 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8612 (memq 'org-add-log-note post-command-hook))
8613 ;; OK, we are already setup for some record
8614 (if (eq org-log-repeat 'note)
8615 ;; make sure we take a note, not only a time stamp
8616 (setq org-log-note-how 'note))
8617 ;; Set up for taking a record
8618 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8619 'findpos org-log-repeat)))
8620 (org-back-to-heading t)
8621 (org-add-planning-info nil nil 'closed)
8622 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8623 org-deadline-time-regexp "\\)\\|\\("
8624 org-ts-regexp "\\)"))
8625 (while (re-search-forward
8626 re (save-excursion (outline-next-heading) (point)) t)
8627 (setq type (if (match-end 1) org-scheduled-string
8628 (if (match-end 3) org-deadline-string "Plain:"))
8629 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8630 mb0 (match-beginning 0))
8631 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8632 (setq n (string-to-number (match-string 2 ts))
8633 what (match-string 3 ts))
8634 (if (equal what "w") (setq n (* n 7) what "d"))
8635 ;; Preparation, see if we need to modify the start date for the change
8636 (when (match-end 1)
8637 (setq time (save-match-data (org-time-string-to-time ts)))
8638 (cond
8639 ((equal (match-string 1 ts) ".")
8640 ;; Shift starting date to today
8641 (org-timestamp-change
8642 (- (time-to-days (current-time)) (time-to-days time))
8643 'day))
8644 ((equal (match-string 1 ts) "+")
8645 (while (or (= nshift 0)
8646 (<= (time-to-days time) (time-to-days (current-time))))
8647 (when (= (incf nshift) nshiftmax)
8648 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8649 (error "Abort")))
8650 (org-timestamp-change n (cdr (assoc what whata)))
8651 (org-at-timestamp-p t)
8652 (setq ts (match-string 1))
8653 (setq time (save-match-data (org-time-string-to-time ts))))
8654 (org-timestamp-change (- n) (cdr (assoc what whata)))
8655 ;; rematch, so that we have everything in place for the real shift
8656 (org-at-timestamp-p t)
8657 (setq ts (match-string 1))
8658 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8659 (org-timestamp-change n (cdr (assoc what whata)))
8660 (setq msg (concat msg type org-last-changed-timestamp " "))))
8661 (setq org-log-post-message msg)
8662 (message "%s" msg))))
8664 (defun org-show-todo-tree (arg)
8665 "Make a compact tree which shows all headlines marked with TODO.
8666 The tree will show the lines where the regexp matches, and all higher
8667 headlines above the match.
8668 With a \\[universal-argument] prefix, also show the DONE entries.
8669 With a numeric prefix N, construct a sparse tree for the Nth element
8670 of `org-todo-keywords-1'."
8671 (interactive "P")
8672 (let ((case-fold-search nil)
8673 (kwd-re
8674 (cond ((null arg) org-not-done-regexp)
8675 ((equal arg '(4))
8676 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8677 (mapcar 'list org-todo-keywords-1))))
8678 (concat "\\("
8679 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8680 "\\)\\>")))
8681 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8682 (regexp-quote (nth (1- (prefix-numeric-value arg))
8683 org-todo-keywords-1)))
8684 (t (error "Invalid prefix argument: %s" arg)))))
8685 (message "%d TODO entries found"
8686 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8688 (defun org-deadline (&optional remove)
8689 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8690 With argument REMOVE, remove any deadline from the item."
8691 (interactive "P")
8692 (if remove
8693 (progn
8694 (org-remove-timestamp-with-keyword org-deadline-string)
8695 (message "Item no longer has a deadline."))
8696 (org-add-planning-info 'deadline nil 'closed)))
8698 (defun org-schedule (&optional remove)
8699 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8700 With argument REMOVE, remove any scheduling date from the item."
8701 (interactive "P")
8702 (if remove
8703 (progn
8704 (org-remove-timestamp-with-keyword org-scheduled-string)
8705 (message "Item is no longer scheduled."))
8706 (org-add-planning-info 'scheduled nil 'closed)))
8708 (defun org-remove-timestamp-with-keyword (keyword)
8709 "Remove all time stamps with KEYWORD in the current entry."
8710 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8711 beg)
8712 (save-excursion
8713 (org-back-to-heading t)
8714 (setq beg (point))
8715 (org-end-of-subtree t t)
8716 (while (re-search-backward re beg t)
8717 (replace-match "")
8718 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8719 (equal (char-before) ?\ ))
8720 (backward-delete-char 1)
8721 (if (string-match "^[ \t]*$" (buffer-substring
8722 (point-at-bol) (point-at-eol)))
8723 (delete-region (point-at-bol)
8724 (min (point-max) (1+ (point-at-eol))))))))))
8726 (defun org-add-planning-info (what &optional time &rest remove)
8727 "Insert new timestamp with keyword in the line directly after the headline.
8728 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8729 If non is given, the user is prompted for a date.
8730 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8731 be removed."
8732 (interactive)
8733 (let (org-time-was-given org-end-time-was-given ts
8734 end default-time default-input)
8736 (when (and (not time) (memq what '(scheduled deadline)))
8737 ;; Try to get a default date/time from existing timestamp
8738 (save-excursion
8739 (org-back-to-heading t)
8740 (setq end (save-excursion (outline-next-heading) (point)))
8741 (when (re-search-forward (if (eq what 'scheduled)
8742 org-scheduled-time-regexp
8743 org-deadline-time-regexp)
8744 end t)
8745 (setq ts (match-string 1)
8746 default-time
8747 (apply 'encode-time (org-parse-time-string ts))
8748 default-input (and ts (org-get-compact-tod ts))))))
8749 (when what
8750 ;; If necessary, get the time from the user
8751 (setq time (or time (org-read-date nil 'to-time nil nil
8752 default-time default-input))))
8754 (when (and org-insert-labeled-timestamps-at-point
8755 (member what '(scheduled deadline)))
8756 (insert
8757 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8758 (org-insert-time-stamp time org-time-was-given
8759 nil nil nil (list org-end-time-was-given))
8760 (setq what nil))
8761 (save-excursion
8762 (save-restriction
8763 (let (col list elt ts buffer-invisibility-spec)
8764 (org-back-to-heading t)
8765 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8766 (goto-char (match-end 1))
8767 (setq col (current-column))
8768 (goto-char (match-end 0))
8769 (if (eobp) (insert "\n") (forward-char 1))
8770 (if (and (not (looking-at outline-regexp))
8771 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8772 "[^\r\n]*"))
8773 (not (equal (match-string 1) org-clock-string)))
8774 (narrow-to-region (match-beginning 0) (match-end 0))
8775 (insert-before-markers "\n")
8776 (backward-char 1)
8777 (narrow-to-region (point) (point))
8778 (and org-adapt-indentation (org-indent-to-column col)))
8779 ;; Check if we have to remove something.
8780 (setq list (cons what remove))
8781 (while list
8782 (setq elt (pop list))
8783 (goto-char (point-min))
8784 (when (or (and (eq elt 'scheduled)
8785 (re-search-forward org-scheduled-time-regexp nil t))
8786 (and (eq elt 'deadline)
8787 (re-search-forward org-deadline-time-regexp nil t))
8788 (and (eq elt 'closed)
8789 (re-search-forward org-closed-time-regexp nil t)))
8790 (replace-match "")
8791 (if (looking-at "--+<[^>]+>") (replace-match ""))
8792 (if (looking-at " +") (replace-match ""))))
8793 (goto-char (point-max))
8794 (when what
8795 (insert
8796 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8797 (cond ((eq what 'scheduled) org-scheduled-string)
8798 ((eq what 'deadline) org-deadline-string)
8799 ((eq what 'closed) org-closed-string))
8800 " ")
8801 (setq ts (org-insert-time-stamp
8802 time
8803 (or org-time-was-given
8804 (and (eq what 'closed) org-log-done-with-time))
8805 (eq what 'closed)
8806 nil nil (list org-end-time-was-given)))
8807 (end-of-line 1))
8808 (goto-char (point-min))
8809 (widen)
8810 (if (and (looking-at "[ \t]+\n")
8811 (equal (char-before) ?\n))
8812 (delete-region (1- (point)) (point-at-eol)))
8813 ts)))))
8815 (defvar org-log-note-marker (make-marker))
8816 (defvar org-log-note-purpose nil)
8817 (defvar org-log-note-state nil)
8818 (defvar org-log-note-how nil)
8819 (defvar org-log-note-window-configuration nil)
8820 (defvar org-log-note-return-to (make-marker))
8821 (defvar org-log-post-message nil
8822 "Message to be displayed after a log note has been stored.
8823 The auto-repeater uses this.")
8825 (defun org-add-note ()
8826 "Add a note to the current entry.
8827 This is done in the same way as adding a state change note."
8828 (interactive)
8829 (org-add-log-setup 'note nil t nil))
8831 (defun org-add-log-setup (&optional purpose state findpos how)
8832 "Set up the post command hook to take a note.
8833 If this is about to TODO state change, the new state is expected in STATE.
8834 When FINDPOS is non-nil, find the correct position for the note in
8835 the current entry. If not, assume that it can be inserted at point."
8836 (save-excursion
8837 (when findpos
8838 (org-back-to-heading t)
8839 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8840 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8841 "[^\r\n]*\\)?"))
8842 (goto-char (match-end 0))
8843 (unless org-log-states-order-reversed
8844 (and (= (char-after) ?\n) (forward-char 1))
8845 (org-skip-over-state-notes)
8846 (skip-chars-backward " \t\n\r")))
8847 (move-marker org-log-note-marker (point))
8848 (setq org-log-note-purpose purpose
8849 org-log-note-state state
8850 org-log-note-how how)
8851 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8853 (defun org-skip-over-state-notes ()
8854 "Skip past the list of State notes in an entry."
8855 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8856 (while (looking-at "[ \t]*- State")
8857 (condition-case nil
8858 (org-next-item)
8859 (error (org-end-of-item)))))
8861 (defun org-add-log-note (&optional purpose)
8862 "Pop up a window for taking a note, and add this note later at point."
8863 (remove-hook 'post-command-hook 'org-add-log-note)
8864 (setq org-log-note-window-configuration (current-window-configuration))
8865 (delete-other-windows)
8866 (move-marker org-log-note-return-to (point))
8867 (switch-to-buffer (marker-buffer org-log-note-marker))
8868 (goto-char org-log-note-marker)
8869 (org-switch-to-buffer-other-window "*Org Note*")
8870 (erase-buffer)
8871 (if (memq org-log-note-how '(time state))
8872 (org-store-log-note)
8873 (let ((org-inhibit-startup t)) (org-mode))
8874 (insert (format "# Insert note for %s.
8875 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8876 (cond
8877 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8878 ((eq org-log-note-purpose 'done) "closed todo item")
8879 ((eq org-log-note-purpose 'state)
8880 (format "state change to \"%s\"" org-log-note-state))
8881 ((eq org-log-note-purpose 'note)
8882 "this entry")
8883 (t (error "This should not happen")))))
8884 (org-set-local 'org-finish-function 'org-store-log-note)))
8886 (defvar org-note-abort nil) ; dynamically scoped
8887 (defun org-store-log-note ()
8888 "Finish taking a log note, and insert it to where it belongs."
8889 (let ((txt (buffer-string))
8890 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8891 lines ind)
8892 (kill-buffer (current-buffer))
8893 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8894 (setq txt (replace-match "" t t txt)))
8895 (if (string-match "\\s-+\\'" txt)
8896 (setq txt (replace-match "" t t txt)))
8897 (setq lines (org-split-string txt "\n"))
8898 (when (and note (string-match "\\S-" note))
8899 (setq note
8900 (org-replace-escapes
8901 note
8902 (list (cons "%u" (user-login-name))
8903 (cons "%U" user-full-name)
8904 (cons "%t" (format-time-string
8905 (org-time-stamp-format 'long 'inactive)
8906 (current-time)))
8907 (cons "%s" (if org-log-note-state
8908 (concat "\"" org-log-note-state "\"")
8909 "")))))
8910 (if lines (setq note (concat note " \\\\")))
8911 (push note lines))
8912 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8913 (when lines
8914 (save-excursion
8915 (set-buffer (marker-buffer org-log-note-marker))
8916 (save-excursion
8917 (goto-char org-log-note-marker)
8918 (move-marker org-log-note-marker nil)
8919 (end-of-line 1)
8920 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8921 (indent-relative nil)
8922 (insert "- " (pop lines))
8923 (org-indent-line-function)
8924 (beginning-of-line 1)
8925 (looking-at "[ \t]*")
8926 (setq ind (concat (match-string 0) " "))
8927 (end-of-line 1)
8928 (while lines (insert "\n" ind (pop lines)))))))
8929 (set-window-configuration org-log-note-window-configuration)
8930 (with-current-buffer (marker-buffer org-log-note-return-to)
8931 (goto-char org-log-note-return-to))
8932 (move-marker org-log-note-return-to nil)
8933 (and org-log-post-message (message "%s" org-log-post-message)))
8935 (defun org-sparse-tree (&optional arg)
8936 "Create a sparse tree, prompt for the details.
8937 This command can create sparse trees. You first need to select the type
8938 of match used to create the tree:
8940 t Show entries with a specific TODO keyword.
8941 T Show entries selected by a tags match.
8942 p Enter a property name and its value (both with completion on existing
8943 names/values) and show entries with that property.
8944 r Show entries matching a regular expression
8945 d Show deadlines due within `org-deadline-warning-days'."
8946 (interactive "P")
8947 (let (ans kwd value)
8948 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8949 (setq ans (read-char-exclusive))
8950 (cond
8951 ((equal ans ?d)
8952 (call-interactively 'org-check-deadlines))
8953 ((equal ans ?b)
8954 (call-interactively 'org-check-before-date))
8955 ((equal ans ?t)
8956 (org-show-todo-tree '(4)))
8957 ((equal ans ?T)
8958 (call-interactively 'org-tags-sparse-tree))
8959 ((member ans '(?p ?P))
8960 (setq kwd (completing-read "Property: "
8961 (mapcar 'list (org-buffer-property-keys))))
8962 (setq value (completing-read "Value: "
8963 (mapcar 'list (org-property-values kwd))))
8964 (unless (string-match "\\`{.*}\\'" value)
8965 (setq value (concat "\"" value "\"")))
8966 (org-tags-sparse-tree arg (concat kwd "=" value)))
8967 ((member ans '(?r ?R ?/))
8968 (call-interactively 'org-occur))
8969 (t (error "No such sparse tree command \"%c\"" ans)))))
8971 (defvar org-occur-highlights nil
8972 "List of overlays used for occur matches.")
8973 (make-variable-buffer-local 'org-occur-highlights)
8974 (defvar org-occur-parameters nil
8975 "Parameters of the active org-occur calls.
8976 This is a list, each call to org-occur pushes as cons cell,
8977 containing the regular expression and the callback, onto the list.
8978 The list can contain several entries if `org-occur' has been called
8979 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8980 will only contain one set of parameters. When the highlights are
8981 removed (for example with `C-c C-c', or with the next edit (depending
8982 on `org-remove-highlights-with-change'), this variable is emptied
8983 as well.")
8984 (make-variable-buffer-local 'org-occur-parameters)
8986 (defun org-occur (regexp &optional keep-previous callback)
8987 "Make a compact tree which shows all matches of REGEXP.
8988 The tree will show the lines where the regexp matches, and all higher
8989 headlines above the match. It will also show the heading after the match,
8990 to make sure editing the matching entry is easy.
8991 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8992 call to `org-occur' will be kept, to allow stacking of calls to this
8993 command.
8994 If CALLBACK is non-nil, it is a function which is called to confirm
8995 that the match should indeed be shown."
8996 (interactive "sRegexp: \nP")
8997 (unless keep-previous
8998 (org-remove-occur-highlights nil nil t))
8999 (push (cons regexp callback) org-occur-parameters)
9000 (let ((cnt 0))
9001 (save-excursion
9002 (goto-char (point-min))
9003 (if (or (not keep-previous) ; do not want to keep
9004 (not org-occur-highlights)) ; no previous matches
9005 ;; hide everything
9006 (org-overview))
9007 (while (re-search-forward regexp nil t)
9008 (when (or (not callback)
9009 (save-match-data (funcall callback)))
9010 (setq cnt (1+ cnt))
9011 (when org-highlight-sparse-tree-matches
9012 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9013 (org-show-context 'occur-tree))))
9014 (when org-remove-highlights-with-change
9015 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9016 nil 'local))
9017 (unless org-sparse-tree-open-archived-trees
9018 (org-hide-archived-subtrees (point-min) (point-max)))
9019 (run-hooks 'org-occur-hook)
9020 (if (interactive-p)
9021 (message "%d match(es) for regexp %s" cnt regexp))
9022 cnt))
9024 (defun org-show-context (&optional key)
9025 "Make sure point and context and visible.
9026 How much context is shown depends upon the variables
9027 `org-show-hierarchy-above', `org-show-following-heading'. and
9028 `org-show-siblings'."
9029 (let ((heading-p (org-on-heading-p t))
9030 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9031 (following-p (org-get-alist-option org-show-following-heading key))
9032 (entry-p (org-get-alist-option org-show-entry-below key))
9033 (siblings-p (org-get-alist-option org-show-siblings key)))
9034 (catch 'exit
9035 ;; Show heading or entry text
9036 (if (and heading-p (not entry-p))
9037 (org-flag-heading nil) ; only show the heading
9038 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9039 (org-show-hidden-entry))) ; show entire entry
9040 (when following-p
9041 ;; Show next sibling, or heading below text
9042 (save-excursion
9043 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9044 (org-flag-heading nil))))
9045 (when siblings-p (org-show-siblings))
9046 (when hierarchy-p
9047 ;; show all higher headings, possibly with siblings
9048 (save-excursion
9049 (while (and (condition-case nil
9050 (progn (org-up-heading-all 1) t)
9051 (error nil))
9052 (not (bobp)))
9053 (org-flag-heading nil)
9054 (when siblings-p (org-show-siblings))))))))
9056 (defun org-reveal (&optional siblings)
9057 "Show current entry, hierarchy above it, and the following headline.
9058 This can be used to show a consistent set of context around locations
9059 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9060 not t for the search context.
9062 With optional argument SIBLINGS, on each level of the hierarchy all
9063 siblings are shown. This repairs the tree structure to what it would
9064 look like when opened with hierarchical calls to `org-cycle'."
9065 (interactive "P")
9066 (let ((org-show-hierarchy-above t)
9067 (org-show-following-heading t)
9068 (org-show-siblings (if siblings t org-show-siblings)))
9069 (org-show-context nil)))
9071 (defun org-highlight-new-match (beg end)
9072 "Highlight from BEG to END and mark the highlight is an occur headline."
9073 (let ((ov (org-make-overlay beg end)))
9074 (org-overlay-put ov 'face 'secondary-selection)
9075 (push ov org-occur-highlights)))
9077 (defun org-remove-occur-highlights (&optional beg end noremove)
9078 "Remove the occur highlights from the buffer.
9079 BEG and END are ignored. If NOREMOVE is nil, remove this function
9080 from the `before-change-functions' in the current buffer."
9081 (interactive)
9082 (unless org-inhibit-highlight-removal
9083 (mapc 'org-delete-overlay org-occur-highlights)
9084 (setq org-occur-highlights nil)
9085 (setq org-occur-parameters nil)
9086 (unless noremove
9087 (remove-hook 'before-change-functions
9088 'org-remove-occur-highlights 'local))))
9090 ;;;; Priorities
9092 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9093 "Regular expression matching the priority indicator.")
9095 (defvar org-remove-priority-next-time nil)
9097 (defun org-priority-up ()
9098 "Increase the priority of the current item."
9099 (interactive)
9100 (org-priority 'up))
9102 (defun org-priority-down ()
9103 "Decrease the priority of the current item."
9104 (interactive)
9105 (org-priority 'down))
9107 (defun org-priority (&optional action)
9108 "Change the priority of an item by ARG.
9109 ACTION can be `set', `up', `down', or a character."
9110 (interactive)
9111 (setq action (or action 'set))
9112 (let (current new news have remove)
9113 (save-excursion
9114 (org-back-to-heading)
9115 (if (looking-at org-priority-regexp)
9116 (setq current (string-to-char (match-string 2))
9117 have t)
9118 (setq current org-default-priority))
9119 (cond
9120 ((or (eq action 'set)
9121 (if (featurep 'xemacs) (characterp action) (integerp action)))
9122 (if (not (eq action 'set))
9123 (setq new action)
9124 (message "Priority %c-%c, SPC to remove: "
9125 org-highest-priority org-lowest-priority)
9126 (setq new (read-char-exclusive)))
9127 (if (and (= (upcase org-highest-priority) org-highest-priority)
9128 (= (upcase org-lowest-priority) org-lowest-priority))
9129 (setq new (upcase new)))
9130 (cond ((equal new ?\ ) (setq remove t))
9131 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9132 (error "Priority must be between `%c' and `%c'"
9133 org-highest-priority org-lowest-priority))))
9134 ((eq action 'up)
9135 (if (and (not have) (eq last-command this-command))
9136 (setq new org-lowest-priority)
9137 (setq new (if (and org-priority-start-cycle-with-default (not have))
9138 org-default-priority (1- current)))))
9139 ((eq action 'down)
9140 (if (and (not have) (eq last-command this-command))
9141 (setq new org-highest-priority)
9142 (setq new (if (and org-priority-start-cycle-with-default (not have))
9143 org-default-priority (1+ current)))))
9144 (t (error "Invalid action")))
9145 (if (or (< (upcase new) org-highest-priority)
9146 (> (upcase new) org-lowest-priority))
9147 (setq remove t))
9148 (setq news (format "%c" new))
9149 (if have
9150 (if remove
9151 (replace-match "" t t nil 1)
9152 (replace-match news t t nil 2))
9153 (if remove
9154 (error "No priority cookie found in line")
9155 (looking-at org-todo-line-regexp)
9156 (if (match-end 2)
9157 (progn
9158 (goto-char (match-end 2))
9159 (insert " [#" news "]"))
9160 (goto-char (match-beginning 3))
9161 (insert "[#" news "] ")))))
9162 (org-preserve-lc (org-set-tags nil 'align))
9163 (if remove
9164 (message "Priority removed")
9165 (message "Priority of current item set to %s" news))))
9168 (defun org-get-priority (s)
9169 "Find priority cookie and return priority."
9170 (save-match-data
9171 (if (not (string-match org-priority-regexp s))
9172 (* 1000 (- org-lowest-priority org-default-priority))
9173 (* 1000 (- org-lowest-priority
9174 (string-to-char (match-string 2 s)))))))
9176 ;;;; Tags
9178 (defun org-scan-tags (action matcher &optional todo-only)
9179 "Scan headline tags with inheritance and produce output ACTION.
9181 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9182 or `agenda' to produce an entry list for an agenda view. It can also be
9183 a Lisp form or a function that should be called at each matched headline, in
9184 this case the return value is a list of all return values from these calls.
9186 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9187 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9188 only lines with a TODO keyword are included in the output."
9189 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9190 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9191 (org-re
9192 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9193 (props (list 'face nil
9194 'done-face 'org-done
9195 'undone-face nil
9196 'mouse-face 'highlight
9197 'org-not-done-regexp org-not-done-regexp
9198 'org-todo-regexp org-todo-regexp
9199 'keymap org-agenda-keymap
9200 'help-echo
9201 (format "mouse-2 or RET jump to org file %s"
9202 (abbreviate-file-name
9203 (or (buffer-file-name (buffer-base-buffer))
9204 (buffer-name (buffer-base-buffer)))))))
9205 (case-fold-search nil)
9206 lspos tags tags-list
9207 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9208 (llast 0) rtn rtn1 level category i txt
9209 todo marker entry priority)
9210 (when (not (member action '(agenda sparse-tree)))
9211 (setq action (list 'lambda nil action)))
9212 (save-excursion
9213 (goto-char (point-min))
9214 (when (eq action 'sparse-tree)
9215 (org-overview)
9216 (org-remove-occur-highlights))
9217 (while (re-search-forward re nil t)
9218 (catch :skip
9219 (setq todo (if (match-end 1) (match-string 2))
9220 tags (if (match-end 4) (match-string 4)))
9221 (goto-char (setq lspos (1+ (match-beginning 0))))
9222 (setq level (org-reduced-level (funcall outline-level))
9223 category (org-get-category))
9224 (setq i llast llast level)
9225 ;; remove tag lists from same and sublevels
9226 (while (>= i level)
9227 (when (setq entry (assoc i tags-alist))
9228 (setq tags-alist (delete entry tags-alist)))
9229 (setq i (1- i)))
9230 ;; add the next tags
9231 (when tags
9232 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9233 tags-alist
9234 (cons (cons level tags) tags-alist)))
9235 ;; compile tags for current headline
9236 (setq tags-list
9237 (if org-use-tag-inheritance
9238 (apply 'append (mapcar 'cdr tags-alist))
9239 tags))
9240 (when (and tags org-use-tag-inheritance
9241 (not (eq t org-use-tag-inheritance)))
9242 ;; selective inheritance, remove uninherited ones
9243 (setcdr (car tags-alist)
9244 (org-remove-uniherited-tags (cdar tags-alist))))
9245 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9246 (eval matcher)
9247 (or (not org-agenda-skip-archived-trees)
9248 (not (member org-archive-tag tags-list))))
9249 (unless (eq action 'sparse-tree) (org-agenda-skip))
9251 ;; select this headline
9253 (cond
9254 ((eq action 'sparse-tree)
9255 (and org-highlight-sparse-tree-matches
9256 (org-get-heading) (match-end 0)
9257 (org-highlight-new-match
9258 (match-beginning 0) (match-beginning 1)))
9259 (org-show-context 'tags-tree))
9260 ((eq action 'agenda)
9261 (setq txt (org-format-agenda-item
9263 (concat
9264 (if org-tags-match-list-sublevels
9265 (make-string (1- level) ?.) "")
9266 (org-get-heading))
9267 category tags-list)
9268 priority (org-get-priority txt))
9269 (goto-char lspos)
9270 (setq marker (org-agenda-new-marker))
9271 (org-add-props txt props
9272 'org-marker marker 'org-hd-marker marker 'org-category category
9273 'priority priority 'type "tagsmatch")
9274 (push txt rtn))
9275 ((functionp action)
9276 (save-excursion
9277 (setq rtn1 (funcall action))
9278 (push rtn1 rtn))
9279 (goto-char (point-at-eol)))
9280 (t (error "Invalid action")))
9282 ;; if we are to skip sublevels, jump to end of subtree
9283 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9284 (when (and (eq action 'sparse-tree)
9285 (not org-sparse-tree-open-archived-trees))
9286 (org-hide-archived-subtrees (point-min) (point-max)))
9287 (nreverse rtn)))
9289 (defun org-remove-uniherited-tags (tags)
9290 "Remove all tags that are not inherited from the list TAGS."
9291 (cond
9292 ((eq org-use-tag-inheritance t) tags)
9293 ((not org-use-tag-inheritance) nil)
9294 ((stringp org-use-tag-inheritance)
9295 (delq nil (mapcar
9296 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9297 tags)))
9298 ((listp org-use-tag-inheritance)
9299 (org-delete-all org-use-tag-inheritance tags))))
9301 (defvar todo-only) ;; dynamically scoped
9303 (defun org-tags-sparse-tree (&optional todo-only match)
9304 "Create a sparse tree according to tags string MATCH.
9305 MATCH can contain positive and negative selection of tags, like
9306 \"+WORK+URGENT-WITHBOSS\".
9307 If optional argument TODO_ONLY is non-nil, only select lines that are
9308 also TODO lines."
9309 (interactive "P")
9310 (org-prepare-agenda-buffers (list (current-buffer)))
9311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9313 (defvar org-cached-props nil)
9314 (defun org-cached-entry-get (pom property)
9315 (if (or (eq t org-use-property-inheritance)
9316 (and (stringp org-use-property-inheritance)
9317 (string-match org-use-property-inheritance property))
9318 (and (listp org-use-property-inheritance)
9319 (member property org-use-property-inheritance)))
9320 ;; Caching is not possible, check it directly
9321 (org-entry-get pom property 'inherit)
9322 ;; Get all properties, so that we can do complicated checks easily
9323 (cdr (assoc property (or org-cached-props
9324 (setq org-cached-props
9325 (org-entry-properties pom)))))))
9327 (defun org-global-tags-completion-table (&optional files)
9328 "Return the list of all tags in all agenda buffer/files."
9329 (save-excursion
9330 (org-uniquify
9331 (delq nil
9332 (apply 'append
9333 (mapcar
9334 (lambda (file)
9335 (set-buffer (find-file-noselect file))
9336 (append (org-get-buffer-tags)
9337 (mapcar (lambda (x) (if (stringp (car-safe x))
9338 (list (car-safe x)) nil))
9339 org-tag-alist)))
9340 (if (and files (car files))
9341 files
9342 (org-agenda-files))))))))
9344 (defun org-make-tags-matcher (match)
9345 "Create the TAGS//TODO matcher form for the selection string MATCH."
9346 ;; todo-only is scoped dynamically into this function, and the function
9347 ;; may change it it the matcher asksk for it.
9348 (unless match
9349 ;; Get a new match request, with completion
9350 (let ((org-last-tags-completion-table
9351 (org-global-tags-completion-table)))
9352 (setq match (completing-read
9353 "Match: " 'org-tags-completion-function nil nil nil
9354 'org-tags-history))))
9356 ;; Parse the string and create a lisp form
9357 (let ((match0 match)
9358 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9359 minus tag mm
9360 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9361 orterms term orlist re-p str-p level-p level-op
9362 prop-p pn pv po cat-p gv)
9363 (if (string-match "/+" match)
9364 ;; match contains also a todo-matching request
9365 (progn
9366 (setq tagsmatch (substring match 0 (match-beginning 0))
9367 todomatch (substring match (match-end 0)))
9368 (if (string-match "^!" todomatch)
9369 (setq todo-only t todomatch (substring todomatch 1)))
9370 (if (string-match "^\\s-*$" todomatch)
9371 (setq todomatch nil)))
9372 ;; only matching tags
9373 (setq tagsmatch match todomatch nil))
9375 ;; Make the tags matcher
9376 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9377 (setq tagsmatcher t)
9378 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9379 (while (setq term (pop orterms))
9380 (while (and (equal (substring term -1) "\\") orterms)
9381 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9382 (while (string-match re term)
9383 (setq minus (and (match-end 1)
9384 (equal (match-string 1 term) "-"))
9385 tag (match-string 2 term)
9386 re-p (equal (string-to-char tag) ?{)
9387 level-p (match-end 4)
9388 prop-p (match-end 5)
9389 mm (cond
9390 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9391 (level-p
9392 (setq level-op (org-op-to-function (match-string 3 term)))
9393 `(,level-op level ,(string-to-number
9394 (match-string 4 term))))
9395 (prop-p
9396 (setq pn (match-string 5 term)
9397 po (match-string 6 term)
9398 pv (match-string 7 term)
9399 cat-p (equal pn "CATEGORY")
9400 re-p (equal (string-to-char pv) ?{)
9401 str-p (equal (string-to-char pv) ?\")
9402 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9403 (setq po (org-op-to-function po str-p))
9404 (if (equal pn "CATEGORY")
9405 (setq gv '(get-text-property (point) 'org-category))
9406 (setq gv `(org-cached-entry-get nil ,pn)))
9407 (if re-p
9408 (if (eq po 'org<>)
9409 `(not (string-match ,pv (or ,gv "")))
9410 `(string-match ,pv (or ,gv "")))
9411 (if str-p
9412 `(,po (or ,gv "") ,pv)
9413 `(,po (string-to-number (or ,gv ""))
9414 ,(string-to-number pv) ))))
9415 (t `(member ,(downcase tag) tags-list)))
9416 mm (if minus (list 'not mm) mm)
9417 term (substring term (match-end 0)))
9418 (push mm tagsmatcher))
9419 (push (if (> (length tagsmatcher) 1)
9420 (cons 'and tagsmatcher)
9421 (car tagsmatcher))
9422 orlist)
9423 (setq tagsmatcher nil))
9424 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9425 (setq tagsmatcher
9426 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9427 ;; Make the todo matcher
9428 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9429 (setq todomatcher t)
9430 (setq orterms (org-split-string todomatch "|") orlist nil)
9431 (while (setq term (pop orterms))
9432 (while (string-match re term)
9433 (setq minus (and (match-end 1)
9434 (equal (match-string 1 term) "-"))
9435 kwd (match-string 2 term)
9436 re-p (equal (string-to-char kwd) ?{)
9437 term (substring term (match-end 0))
9438 mm (if re-p
9439 `(string-match ,(substring kwd 1 -1) todo)
9440 (list 'equal 'todo kwd))
9441 mm (if minus (list 'not mm) mm))
9442 (push mm todomatcher))
9443 (push (if (> (length todomatcher) 1)
9444 (cons 'and todomatcher)
9445 (car todomatcher))
9446 orlist)
9447 (setq todomatcher nil))
9448 (setq todomatcher (if (> (length orlist) 1)
9449 (cons 'or orlist) (car orlist))))
9451 ;; Return the string and lisp forms of the matcher
9452 (setq matcher (if todomatcher
9453 (list 'and tagsmatcher todomatcher)
9454 tagsmatcher))
9455 (cons match0 matcher)))
9457 (defun org-op-to-function (op &optional stringp)
9458 (setq op
9459 (cond
9460 ((equal op "<" ) '(< string< ))
9461 ((equal op ">" ) '(> org-string> ))
9462 ((member op '("<=" "=<")) '(<= org-string<= ))
9463 ((member op '(">=" "=>")) '(>= org-string>= ))
9464 ((member op '("=" "==")) '(= string= ))
9465 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9466 (nth (if stringp 1 0) op))
9468 (defun org<> (a b) (not (= a b)))
9469 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9470 (defun org-string>= (a b) (not (string< a b)))
9471 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9472 (defun org-string<> (a b) (not (string= a b)))
9474 (defun org-match-any-p (re list)
9475 "Does re match any element of list?"
9476 (setq list (mapcar (lambda (x) (string-match re x)) list))
9477 (delq nil list))
9479 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9480 (defvar org-tags-overlay (org-make-overlay 1 1))
9481 (org-detach-overlay org-tags-overlay)
9483 (defun org-get-tags-at (&optional pos)
9484 "Get a list of all headline tags applicable at POS.
9485 POS defaults to point. If tags are inherited, the list contains
9486 the targets in the same sequence as the headlines appear, i.e.
9487 the tags of the current headline come last."
9488 (interactive)
9489 (let (tags ltags lastpos parent)
9490 (save-excursion
9491 (save-restriction
9492 (widen)
9493 (goto-char (or pos (point)))
9494 (save-match-data
9495 (condition-case nil
9496 (progn
9497 (org-back-to-heading t)
9498 (while (not (equal lastpos (point)))
9499 (setq lastpos (point))
9500 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9501 (setq ltags (org-split-string
9502 (org-match-string-no-properties 1) ":"))
9503 (setq tags (append (org-remove-uniherited-tags ltags)
9504 tags)))
9505 (or org-use-tag-inheritance (error ""))
9506 (org-up-heading-all 1)
9507 (setq parent t)))
9508 (error nil))))
9509 (append (org-remove-uniherited-tags org-file-tags) tags))))
9511 (defun org-toggle-tag (tag &optional onoff)
9512 "Toggle the tag TAG for the current line.
9513 If ONOFF is `on' or `off', don't toggle but set to this state."
9514 (unless (org-on-heading-p t) (error "Not on headling"))
9515 (let (res current)
9516 (save-excursion
9517 (beginning-of-line)
9518 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9519 (point-at-eol) t)
9520 (progn
9521 (setq current (match-string 1))
9522 (replace-match ""))
9523 (setq current ""))
9524 (setq current (nreverse (org-split-string current ":")))
9525 (cond
9526 ((eq onoff 'on)
9527 (setq res t)
9528 (or (member tag current) (push tag current)))
9529 ((eq onoff 'off)
9530 (or (not (member tag current)) (setq current (delete tag current))))
9531 (t (if (member tag current)
9532 (setq current (delete tag current))
9533 (setq res t)
9534 (push tag current))))
9535 (end-of-line 1)
9536 (if current
9537 (progn
9538 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9539 (org-set-tags nil t))
9540 (delete-horizontal-space))
9541 (run-hooks 'org-after-tags-change-hook))
9542 res))
9544 (defun org-align-tags-here (to-col)
9545 ;; Assumes that this is a headline
9546 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9547 (beginning-of-line 1)
9548 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9549 (< pos (match-beginning 2)))
9550 (progn
9551 (setq tags-l (- (match-end 2) (match-beginning 2)))
9552 (goto-char (match-beginning 1))
9553 (insert " ")
9554 (delete-region (point) (1+ (match-beginning 2)))
9555 (setq ncol (max (1+ (current-column))
9556 (1+ col)
9557 (if (> to-col 0)
9558 to-col
9559 (- (abs to-col) tags-l))))
9560 (setq p (point))
9561 (insert (make-string (- ncol (current-column)) ?\ ))
9562 (setq ncol (current-column))
9563 (when indent-tabs-mode (tabify p (point-at-eol)))
9564 (org-move-to-column (min ncol col) t))
9565 (goto-char pos))))
9567 (defun org-set-tags (&optional arg just-align)
9568 "Set the tags for the current headline.
9569 With prefix ARG, realign all tags in headings in the current buffer."
9570 (interactive "P")
9571 (let* ((re (concat "^" outline-regexp))
9572 (current (org-get-tags-string))
9573 (col (current-column))
9574 (org-setting-tags t)
9575 table current-tags inherited-tags ; computed below when needed
9576 tags p0 c0 c1 rpl)
9577 (if arg
9578 (save-excursion
9579 (goto-char (point-min))
9580 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9581 (while (re-search-forward re nil t)
9582 (org-set-tags nil t)
9583 (end-of-line 1)))
9584 (message "All tags realigned to column %d" org-tags-column))
9585 (if just-align
9586 (setq tags current)
9587 ;; Get a new set of tags from the user
9588 (save-excursion
9589 (setq table (or org-tag-alist (org-get-buffer-tags))
9590 org-last-tags-completion-table table
9591 current-tags (org-split-string current ":")
9592 inherited-tags (nreverse
9593 (nthcdr (length current-tags)
9594 (nreverse (org-get-tags-at))))
9595 tags
9596 (if (or (eq t org-use-fast-tag-selection)
9597 (and org-use-fast-tag-selection
9598 (delq nil (mapcar 'cdr table))))
9599 (org-fast-tag-selection
9600 current-tags inherited-tags table
9601 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9602 (let ((org-add-colon-after-tag-completion t))
9603 (org-trim
9604 (org-without-partial-completion
9605 (completing-read "Tags: " 'org-tags-completion-function
9606 nil nil current 'org-tags-history)))))))
9607 (while (string-match "[-+&]+" tags)
9608 ;; No boolean logic, just a list
9609 (setq tags (replace-match ":" t t tags))))
9611 (if (string-match "\\`[\t ]*\\'" tags)
9612 (setq tags "")
9613 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9614 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9616 ;; Insert new tags at the correct column
9617 (beginning-of-line 1)
9618 (cond
9619 ((and (equal current "") (equal tags "")))
9620 ((re-search-forward
9621 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9622 (point-at-eol) t)
9623 (if (equal tags "")
9624 (setq rpl "")
9625 (goto-char (match-beginning 0))
9626 (setq c0 (current-column) p0 (point)
9627 c1 (max (1+ c0) (if (> org-tags-column 0)
9628 org-tags-column
9629 (- (- org-tags-column) (length tags))))
9630 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9631 (replace-match rpl t t)
9632 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9633 tags)
9634 (t (error "Tags alignment failed")))
9635 (org-move-to-column col)
9636 (unless just-align
9637 (run-hooks 'org-after-tags-change-hook)))))
9639 (defun org-change-tag-in-region (beg end tag off)
9640 "Add or remove TAG for each entry in the region.
9641 This works in the agenda, and also in an org-mode buffer."
9642 (interactive
9643 (list (region-beginning) (region-end)
9644 (let ((org-last-tags-completion-table
9645 (if (org-mode-p)
9646 (org-get-buffer-tags)
9647 (org-global-tags-completion-table))))
9648 (completing-read
9649 "Tag: " 'org-tags-completion-function nil nil nil
9650 'org-tags-history))
9651 (progn
9652 (message "[s]et or [r]emove? ")
9653 (equal (read-char-exclusive) ?r))))
9654 (if (fboundp 'deactivate-mark) (deactivate-mark))
9655 (let ((agendap (equal major-mode 'org-agenda-mode))
9656 l1 l2 m buf pos newhead (cnt 0))
9657 (goto-char end)
9658 (setq l2 (1- (org-current-line)))
9659 (goto-char beg)
9660 (setq l1 (org-current-line))
9661 (loop for l from l1 to l2 do
9662 (goto-line l)
9663 (setq m (get-text-property (point) 'org-hd-marker))
9664 (when (or (and (org-mode-p) (org-on-heading-p))
9665 (and agendap m))
9666 (setq buf (if agendap (marker-buffer m) (current-buffer))
9667 pos (if agendap m (point)))
9668 (with-current-buffer buf
9669 (save-excursion
9670 (save-restriction
9671 (goto-char pos)
9672 (setq cnt (1+ cnt))
9673 (org-toggle-tag tag (if off 'off 'on))
9674 (setq newhead (org-get-heading)))))
9675 (and agendap (org-agenda-change-all-lines newhead m))))
9676 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9678 (defun org-tags-completion-function (string predicate &optional flag)
9679 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9680 (confirm (lambda (x) (stringp (car x)))))
9681 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9682 (setq s1 (match-string 1 string)
9683 s2 (match-string 2 string))
9684 (setq s1 "" s2 string))
9685 (cond
9686 ((eq flag nil)
9687 ;; try completion
9688 (setq rtn (try-completion s2 ctable confirm))
9689 (if (stringp rtn)
9690 (setq rtn
9691 (concat s1 s2 (substring rtn (length s2))
9692 (if (and org-add-colon-after-tag-completion
9693 (assoc rtn ctable))
9694 ":" ""))))
9695 rtn)
9696 ((eq flag t)
9697 ;; all-completions
9698 (all-completions s2 ctable confirm)
9700 ((eq flag 'lambda)
9701 ;; exact match?
9702 (assoc s2 ctable)))
9705 (defun org-fast-tag-insert (kwd tags face &optional end)
9706 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9707 (insert (format "%-12s" (concat kwd ":"))
9708 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9709 (or end "")))
9711 (defun org-fast-tag-show-exit (flag)
9712 (save-excursion
9713 (goto-line 3)
9714 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9715 (replace-match ""))
9716 (when flag
9717 (end-of-line 1)
9718 (org-move-to-column (- (window-width) 19) t)
9719 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9721 (defun org-set-current-tags-overlay (current prefix)
9722 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9723 (if (featurep 'xemacs)
9724 (org-overlay-display org-tags-overlay (concat prefix s)
9725 'secondary-selection)
9726 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9727 (org-overlay-display org-tags-overlay (concat prefix s)))))
9729 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9730 "Fast tag selection with single keys.
9731 CURRENT is the current list of tags in the headline, INHERITED is the
9732 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9733 possibly with grouping information. TODO-TABLE is a similar table with
9734 TODO keywords, should these have keys assigned to them.
9735 If the keys are nil, a-z are automatically assigned.
9736 Returns the new tags string, or nil to not change the current settings."
9737 (let* ((fulltable (append table todo-table))
9738 (maxlen (apply 'max (mapcar
9739 (lambda (x)
9740 (if (stringp (car x)) (string-width (car x)) 0))
9741 fulltable)))
9742 (buf (current-buffer))
9743 (expert (eq org-fast-tag-selection-single-key 'expert))
9744 (buffer-tags nil)
9745 (fwidth (+ maxlen 3 1 3))
9746 (ncol (/ (- (window-width) 4) fwidth))
9747 (i-face 'org-done)
9748 (c-face 'org-todo)
9749 tg cnt e c char c1 c2 ntable tbl rtn
9750 ov-start ov-end ov-prefix
9751 (exit-after-next org-fast-tag-selection-single-key)
9752 (done-keywords org-done-keywords)
9753 groups ingroup)
9754 (save-excursion
9755 (beginning-of-line 1)
9756 (if (looking-at
9757 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9758 (setq ov-start (match-beginning 1)
9759 ov-end (match-end 1)
9760 ov-prefix "")
9761 (setq ov-start (1- (point-at-eol))
9762 ov-end (1+ ov-start))
9763 (skip-chars-forward "^\n\r")
9764 (setq ov-prefix
9765 (concat
9766 (buffer-substring (1- (point)) (point))
9767 (if (> (current-column) org-tags-column)
9769 (make-string (- org-tags-column (current-column)) ?\ ))))))
9770 (org-move-overlay org-tags-overlay ov-start ov-end)
9771 (save-window-excursion
9772 (if expert
9773 (set-buffer (get-buffer-create " *Org tags*"))
9774 (delete-other-windows)
9775 (split-window-vertically)
9776 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9777 (erase-buffer)
9778 (org-set-local 'org-done-keywords done-keywords)
9779 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9780 (org-fast-tag-insert "Current" current c-face "\n\n")
9781 (org-fast-tag-show-exit exit-after-next)
9782 (org-set-current-tags-overlay current ov-prefix)
9783 (setq tbl fulltable char ?a cnt 0)
9784 (while (setq e (pop tbl))
9785 (cond
9786 ((equal e '(:startgroup))
9787 (push '() groups) (setq ingroup t)
9788 (when (not (= cnt 0))
9789 (setq cnt 0)
9790 (insert "\n"))
9791 (insert "{ "))
9792 ((equal e '(:endgroup))
9793 (setq ingroup nil cnt 0)
9794 (insert "}\n"))
9796 (setq tg (car e) c2 nil)
9797 (if (cdr e)
9798 (setq c (cdr e))
9799 ;; automatically assign a character.
9800 (setq c1 (string-to-char
9801 (downcase (substring
9802 tg (if (= (string-to-char tg) ?@) 1 0)))))
9803 (if (or (rassoc c1 ntable) (rassoc c1 table))
9804 (while (or (rassoc char ntable) (rassoc char table))
9805 (setq char (1+ char)))
9806 (setq c2 c1))
9807 (setq c (or c2 char)))
9808 (if ingroup (push tg (car groups)))
9809 (setq tg (org-add-props tg nil 'face
9810 (cond
9811 ((not (assoc tg table))
9812 (org-get-todo-face tg))
9813 ((member tg current) c-face)
9814 ((member tg inherited) i-face)
9815 (t nil))))
9816 (if (and (= cnt 0) (not ingroup)) (insert " "))
9817 (insert "[" c "] " tg (make-string
9818 (- fwidth 4 (length tg)) ?\ ))
9819 (push (cons tg c) ntable)
9820 (when (= (setq cnt (1+ cnt)) ncol)
9821 (insert "\n")
9822 (if ingroup (insert " "))
9823 (setq cnt 0)))))
9824 (setq ntable (nreverse ntable))
9825 (insert "\n")
9826 (goto-char (point-min))
9827 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9828 (fit-window-to-buffer))
9829 (setq rtn
9830 (catch 'exit
9831 (while t
9832 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9833 (if groups " [!] no groups" " [!]groups")
9834 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9835 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9836 (cond
9837 ((= c ?\r) (throw 'exit t))
9838 ((= c ?!)
9839 (setq groups (not groups))
9840 (goto-char (point-min))
9841 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9842 ((= c ?\C-c)
9843 (if (not expert)
9844 (org-fast-tag-show-exit
9845 (setq exit-after-next (not exit-after-next)))
9846 (setq expert nil)
9847 (delete-other-windows)
9848 (split-window-vertically)
9849 (org-switch-to-buffer-other-window " *Org tags*")
9850 (and (fboundp 'fit-window-to-buffer)
9851 (fit-window-to-buffer))))
9852 ((or (= c ?\C-g)
9853 (and (= c ?q) (not (rassoc c ntable))))
9854 (org-detach-overlay org-tags-overlay)
9855 (setq quit-flag t))
9856 ((= c ?\ )
9857 (setq current nil)
9858 (if exit-after-next (setq exit-after-next 'now)))
9859 ((= c ?\t)
9860 (condition-case nil
9861 (setq tg (completing-read
9862 "Tag: "
9863 (or buffer-tags
9864 (with-current-buffer buf
9865 (org-get-buffer-tags)))))
9866 (quit (setq tg "")))
9867 (when (string-match "\\S-" tg)
9868 (add-to-list 'buffer-tags (list tg))
9869 (if (member tg current)
9870 (setq current (delete tg current))
9871 (push tg current)))
9872 (if exit-after-next (setq exit-after-next 'now)))
9873 ((setq e (rassoc c todo-table) tg (car e))
9874 (with-current-buffer buf
9875 (save-excursion (org-todo tg)))
9876 (if exit-after-next (setq exit-after-next 'now)))
9877 ((setq e (rassoc c ntable) tg (car e))
9878 (if (member tg current)
9879 (setq current (delete tg current))
9880 (loop for g in groups do
9881 (if (member tg g)
9882 (mapc (lambda (x)
9883 (setq current (delete x current)))
9884 g)))
9885 (push tg current))
9886 (if exit-after-next (setq exit-after-next 'now))))
9888 ;; Create a sorted list
9889 (setq current
9890 (sort current
9891 (lambda (a b)
9892 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9893 (if (eq exit-after-next 'now) (throw 'exit t))
9894 (goto-char (point-min))
9895 (beginning-of-line 2)
9896 (delete-region (point) (point-at-eol))
9897 (org-fast-tag-insert "Current" current c-face)
9898 (org-set-current-tags-overlay current ov-prefix)
9899 (while (re-search-forward
9900 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9901 (setq tg (match-string 1))
9902 (add-text-properties
9903 (match-beginning 1) (match-end 1)
9904 (list 'face
9905 (cond
9906 ((member tg current) c-face)
9907 ((member tg inherited) i-face)
9908 (t (get-text-property (match-beginning 1) 'face))))))
9909 (goto-char (point-min)))))
9910 (org-detach-overlay org-tags-overlay)
9911 (if rtn
9912 (mapconcat 'identity current ":")
9913 nil))))
9915 (defun org-get-tags-string ()
9916 "Get the TAGS string in the current headline."
9917 (unless (org-on-heading-p t)
9918 (error "Not on a heading"))
9919 (save-excursion
9920 (beginning-of-line 1)
9921 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9922 (org-match-string-no-properties 1)
9923 "")))
9925 (defun org-get-tags ()
9926 "Get the list of tags specified in the current headline."
9927 (org-split-string (org-get-tags-string) ":"))
9929 (defun org-get-buffer-tags ()
9930 "Get a table of all tags used in the buffer, for completion."
9931 (let (tags)
9932 (save-excursion
9933 (goto-char (point-min))
9934 (while (re-search-forward
9935 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9936 (when (equal (char-after (point-at-bol 0)) ?*)
9937 (mapc (lambda (x) (add-to-list 'tags x))
9938 (org-split-string (org-match-string-no-properties 1) ":")))))
9939 (mapcar 'list tags)))
9941 ;;;; The mapping API
9943 ;;;###autoload
9944 (defun org-map-entries (func &optional match scope &rest skip)
9945 "Call FUNC at each headline selected by MATCH in SCOPE.
9947 FUNC is a function or a lisp form. The function will be called without
9948 arguments, with the cursor positioned at the beginning of the headline.
9949 The return values of all calls to the function will be collected and
9950 returned as a list.
9952 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9953 Only headlines that are matched by this query will be considered during
9954 the iteration. When MATCH is nil or t, all headlines will be
9955 visited by the iteration.
9957 SCOPE determines the scope of this command. It can be any of:
9959 nil The current buffer, respecting the restriction if any
9960 tree The subtree started with the entry at point
9961 file The current buffer, without restriction
9962 file-with-archives
9963 The current buffer, and any archives associated with it
9964 agenda All agenda files
9965 agenda-with-archives
9966 All agenda files with any archive files associated with them
9967 \(file1 file2 ...)
9968 If this is a list, all files in the list will be scanned
9970 The remaining args are treated as settings for the skipping facilities of
9971 the scanner. The following items can be given here:
9973 archive skip trees with the archive tag.
9974 comment skip trees with the COMMENT keyword
9975 function or Emacs Lisp form:
9976 will be used as value for `org-agenda-skip-function', so whenever
9977 the the function returns t, FUNC will not be called for that
9978 entry and search will continue from the point where the
9979 function leaves it."
9980 (let* ((org-agenda-skip-archived-trees (memq 'archive skip))
9981 (org-agenda-skip-comment-trees (memq 'comment skip))
9982 (org-agenda-skip-function
9983 (car (org-delete-all '(comment archive) skip)))
9984 (org-tags-match-list-sublevels t)
9985 matcher pos)
9987 (cond
9988 ((eq match t) (setq matcher t))
9989 ((eq match nil) (setq matcher t))
9990 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9992 (when (eq scope 'tree)
9993 (org-back-to-heading t)
9994 (org-narrow-to-subtree)
9995 (setq scope nil))
9997 (if (not scope)
9998 (progn
9999 (org-prepare-agenda-buffers
10000 (list (buffer-file-name (current-buffer))))
10001 (org-scan-tags func matcher))
10002 ;; Get the right scope
10003 (setq pos (point))
10004 (cond
10005 ((and scope (listp scope) (symbolp (car scope)))
10006 (setq scope (eval scope)))
10007 ((eq scope 'agenda)
10008 (setq scope (org-agenda-files t)))
10009 ((eq scope 'agenda-with-archives)
10010 (setq scope (org-agenda-files t))
10011 (setq scope (org-add-archive-files scope)))
10012 ((eq scope 'file)
10013 (setq scope (list (buffer-file-name))))
10014 ((eq scope 'file-with-archives)
10015 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10016 (org-prepare-agenda-buffers scope)
10017 (while (setq file (pop scope))
10018 (with-current-buffer (org-find-base-buffer-visiting file)
10019 (save-excursion
10020 (save-restriction
10021 (widen)
10022 (goto-char (point-min))
10023 (org-scan-tags func matcher))))))))
10025 ;;;; Properties
10027 ;;; Setting and retrieving properties
10029 (defconst org-special-properties
10030 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10031 "TIMESTAMP" "TIMESTAMP_IA")
10032 "The special properties valid in Org-mode.
10034 These are properties that are not defined in the property drawer,
10035 but in some other way.")
10037 (defconst org-default-properties
10038 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10039 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10040 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10041 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10042 "Some properties that are used by Org-mode for various purposes.
10043 Being in this list makes sure that they are offered for completion.")
10045 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10046 "Regular expression matching the first line of a property drawer.")
10048 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10049 "Regular expression matching the first line of a property drawer.")
10051 (defun org-property-action ()
10052 "Do an action on properties."
10053 (interactive)
10054 (let (c)
10055 (org-at-property-p)
10056 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10057 (setq c (read-char-exclusive))
10058 (cond
10059 ((equal c ?s)
10060 (call-interactively 'org-set-property))
10061 ((equal c ?d)
10062 (call-interactively 'org-delete-property))
10063 ((equal c ?D)
10064 (call-interactively 'org-delete-property-globally))
10065 ((equal c ?c)
10066 (call-interactively 'org-compute-property-at-point))
10067 (t (error "No such property action %c" c)))))
10069 (defun org-at-property-p ()
10070 "Is the cursor in a property line?"
10071 ;; FIXME: Does not check if we are actually in the drawer.
10072 ;; FIXME: also returns true on any drawers.....
10073 ;; This is used by C-c C-c for property action.
10074 (save-excursion
10075 (beginning-of-line 1)
10076 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10078 (defun org-get-property-block (&optional beg end force)
10079 "Return the (beg . end) range of the body of the property drawer.
10080 BEG and END can be beginning and end of subtree, if not given
10081 they will be found.
10082 If the drawer does not exist and FORCE is non-nil, create the drawer."
10083 (catch 'exit
10084 (save-excursion
10085 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10086 (end (or end (progn (outline-next-heading) (point)))))
10087 (goto-char beg)
10088 (if (re-search-forward org-property-start-re end t)
10089 (setq beg (1+ (match-end 0)))
10090 (if force
10091 (save-excursion
10092 (org-insert-property-drawer)
10093 (setq end (progn (outline-next-heading) (point))))
10094 (throw 'exit nil))
10095 (goto-char beg)
10096 (if (re-search-forward org-property-start-re end t)
10097 (setq beg (1+ (match-end 0)))))
10098 (if (re-search-forward org-property-end-re end t)
10099 (setq end (match-beginning 0))
10100 (or force (throw 'exit nil))
10101 (goto-char beg)
10102 (setq end beg)
10103 (org-indent-line-function)
10104 (insert ":END:\n"))
10105 (cons beg end)))))
10107 (defun org-entry-properties (&optional pom which)
10108 "Get all properties of the entry at point-or-marker POM.
10109 This includes the TODO keyword, the tags, time strings for deadline,
10110 scheduled, and clocking, and any additional properties defined in the
10111 entry. The return value is an alist, keys may occur multiple times
10112 if the property key was used several times.
10113 POM may also be nil, in which case the current entry is used.
10114 If WHICH is nil or `all', get all properties. If WHICH is
10115 `special' or `standard', only get that subclass."
10116 (setq which (or which 'all))
10117 (org-with-point-at pom
10118 (let ((clockstr (substring org-clock-string 0 -1))
10119 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10120 beg end range props sum-props key value string clocksum)
10121 (save-excursion
10122 (when (condition-case nil (org-back-to-heading t) (error nil))
10123 (setq beg (point))
10124 (setq sum-props (get-text-property (point) 'org-summaries))
10125 (setq clocksum (get-text-property (point) :org-clock-minutes))
10126 (outline-next-heading)
10127 (setq end (point))
10128 (when (memq which '(all special))
10129 ;; Get the special properties, like TODO and tags
10130 (goto-char beg)
10131 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10132 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10133 (when (looking-at org-priority-regexp)
10134 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10135 (when (and (setq value (org-get-tags-string))
10136 (string-match "\\S-" value))
10137 (push (cons "TAGS" value) props))
10138 (when (setq value (org-get-tags-at))
10139 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10140 props))
10141 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10142 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10143 string (if (equal key clockstr)
10144 (org-no-properties
10145 (org-trim
10146 (buffer-substring
10147 (match-beginning 3) (goto-char (point-at-eol)))))
10148 (substring (org-match-string-no-properties 3) 1 -1)))
10149 (unless key
10150 (if (= (char-after (match-beginning 3)) ?\[)
10151 (setq key "TIMESTAMP_IA")
10152 (setq key "TIMESTAMP")))
10153 (when (or (equal key clockstr) (not (assoc key props)))
10154 (push (cons key string) props)))
10158 (when (memq which '(all standard))
10159 ;; Get the standard properties, like :PORP: ...
10160 (setq range (org-get-property-block beg end))
10161 (when range
10162 (goto-char (car range))
10163 (while (re-search-forward
10164 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10165 (cdr range) t)
10166 (setq key (org-match-string-no-properties 1)
10167 value (org-trim (or (org-match-string-no-properties 2) "")))
10168 (unless (member key excluded)
10169 (push (cons key (or value "")) props)))))
10170 (if clocksum
10171 (push (cons "CLOCKSUM"
10172 (org-columns-number-to-string (/ (float clocksum) 60.)
10173 'add_times))
10174 props))
10175 (append sum-props (nreverse props)))))))
10177 (defun org-entry-get (pom property &optional inherit)
10178 "Get value of PROPERTY for entry at point-or-marker POM.
10179 If INHERIT is non-nil and the entry does not have the property,
10180 then also check higher levels of the hierarchy.
10181 If INHERIT is the symbol `selective', use inheritance only if the setting
10182 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10183 If the property is present but empty, the return value is the empty string.
10184 If the property is not present at all, nil is returned."
10185 (org-with-point-at pom
10186 (if (and inherit (if (eq inherit 'selective)
10187 (org-property-inherit-p property)
10189 (org-entry-get-with-inheritance property)
10190 (if (member property org-special-properties)
10191 ;; We need a special property. Use brute force, get all properties.
10192 (cdr (assoc property (org-entry-properties nil 'special)))
10193 (let ((range (org-get-property-block)))
10194 (if (and range
10195 (goto-char (car range))
10196 (re-search-forward
10197 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10198 (cdr range) t))
10199 ;; Found the property, return it.
10200 (if (match-end 1)
10201 (org-match-string-no-properties 1)
10202 "")))))))
10204 (defun org-property-or-variable-value (var &optional inherit)
10205 "Check if there is a property fixing the value of VAR.
10206 If yes, return this value. If not, return the current value of the variable."
10207 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10208 (if (and prop (stringp prop) (string-match "\\S-" prop))
10209 (read prop)
10210 (symbol-value var))))
10212 (defun org-entry-delete (pom property)
10213 "Delete the property PROPERTY from entry at point-or-marker POM."
10214 (org-with-point-at pom
10215 (if (member property org-special-properties)
10216 nil ; cannot delete these properties.
10217 (let ((range (org-get-property-block)))
10218 (if (and range
10219 (goto-char (car range))
10220 (re-search-forward
10221 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10222 (cdr range) t))
10223 (progn
10224 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10226 nil)))))
10228 ;; Multi-values properties are properties that contain multiple values
10229 ;; These values are assumed to be single words, separated by whitespace.
10230 (defun org-entry-add-to-multivalued-property (pom property value)
10231 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10232 (let* ((old (org-entry-get pom property))
10233 (values (and old (org-split-string old "[ \t]"))))
10234 (unless (member value values)
10235 (setq values (cons value values))
10236 (org-entry-put pom property
10237 (mapconcat 'identity values " ")))))
10239 (defun org-entry-remove-from-multivalued-property (pom property value)
10240 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10241 (let* ((old (org-entry-get pom property))
10242 (values (and old (org-split-string old "[ \t]"))))
10243 (when (member value values)
10244 (setq values (delete value values))
10245 (org-entry-put pom property
10246 (mapconcat 'identity values " ")))))
10248 (defun org-entry-member-in-multivalued-property (pom property value)
10249 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10250 (let* ((old (org-entry-get pom property))
10251 (values (and old (org-split-string old "[ \t]"))))
10252 (member value values)))
10254 (defvar org-entry-property-inherited-from (make-marker))
10256 (defun org-entry-get-with-inheritance (property)
10257 "Get entry property, and search higher levels if not present."
10258 (let (tmp)
10259 (save-excursion
10260 (save-restriction
10261 (widen)
10262 (catch 'ex
10263 (while t
10264 (when (setq tmp (org-entry-get nil property))
10265 (org-back-to-heading t)
10266 (move-marker org-entry-property-inherited-from (point))
10267 (throw 'ex tmp))
10268 (or (org-up-heading-safe) (throw 'ex nil)))))
10269 (or tmp
10270 (cdr (assoc property org-file-properties))
10271 (cdr (assoc property org-global-properties))
10272 (cdr (assoc property org-global-properties-fixed))))))
10274 (defun org-entry-put (pom property value)
10275 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10276 (org-with-point-at pom
10277 (org-back-to-heading t)
10278 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10279 range)
10280 (cond
10281 ((equal property "TODO")
10282 (when (and (stringp value) (string-match "\\S-" value)
10283 (not (member value org-todo-keywords-1)))
10284 (error "\"%s\" is not a valid TODO state" value))
10285 (if (or (not value)
10286 (not (string-match "\\S-" value)))
10287 (setq value 'none))
10288 (org-todo value)
10289 (org-set-tags nil 'align))
10290 ((equal property "PRIORITY")
10291 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10292 (string-to-char value) ?\ ))
10293 (org-set-tags nil 'align))
10294 ((equal property "SCHEDULED")
10295 (if (re-search-forward org-scheduled-time-regexp end t)
10296 (cond
10297 ((eq value 'earlier) (org-timestamp-change -1 'day))
10298 ((eq value 'later) (org-timestamp-change 1 'day))
10299 (t (call-interactively 'org-schedule)))
10300 (call-interactively 'org-schedule)))
10301 ((equal property "DEADLINE")
10302 (if (re-search-forward org-deadline-time-regexp end t)
10303 (cond
10304 ((eq value 'earlier) (org-timestamp-change -1 'day))
10305 ((eq value 'later) (org-timestamp-change 1 'day))
10306 (t (call-interactively 'org-deadline)))
10307 (call-interactively 'org-deadline)))
10308 ((member property org-special-properties)
10309 (error "The %s property can not yet be set with `org-entry-put'"
10310 property))
10311 (t ; a non-special property
10312 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10313 (setq range (org-get-property-block beg end 'force))
10314 (goto-char (car range))
10315 (if (re-search-forward
10316 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10317 (progn
10318 (delete-region (match-beginning 1) (match-end 1))
10319 (goto-char (match-beginning 1)))
10320 (goto-char (cdr range))
10321 (insert "\n")
10322 (backward-char 1)
10323 (org-indent-line-function)
10324 (insert ":" property ":"))
10325 (and value (insert " " value))
10326 (org-indent-line-function)))))))
10328 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10329 "Get all property keys in the current buffer.
10330 With INCLUDE-SPECIALS, also list the special properties that relect things
10331 like tags and TODO state.
10332 With INCLUDE-DEFAULTS, also include properties that has special meaning
10333 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10334 With INCLUDE-COLUMNS, also include property names given in COLUMN
10335 formats in the current buffer."
10336 (let (rtn range cfmt cols s p)
10337 (save-excursion
10338 (save-restriction
10339 (widen)
10340 (goto-char (point-min))
10341 (while (re-search-forward org-property-start-re nil t)
10342 (setq range (org-get-property-block))
10343 (goto-char (car range))
10344 (while (re-search-forward
10345 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10346 (cdr range) t)
10347 (add-to-list 'rtn (org-match-string-no-properties 1)))
10348 (outline-next-heading))))
10350 (when include-specials
10351 (setq rtn (append org-special-properties rtn)))
10353 (when include-defaults
10354 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10356 (when include-columns
10357 (save-excursion
10358 (save-restriction
10359 (widen)
10360 (goto-char (point-min))
10361 (while (re-search-forward
10362 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10363 nil t)
10364 (setq cfmt (match-string 2) s 0)
10365 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10366 cfmt s)
10367 (setq s (match-end 0)
10368 p (match-string 1 cfmt))
10369 (unless (or (equal p "ITEM")
10370 (member p org-special-properties))
10371 (add-to-list 'rtn (match-string 1 cfmt))))))))
10373 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10375 (defun org-property-values (key)
10376 "Return a list of all values of property KEY."
10377 (save-excursion
10378 (save-restriction
10379 (widen)
10380 (goto-char (point-min))
10381 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10382 values)
10383 (while (re-search-forward re nil t)
10384 (add-to-list 'values (org-trim (match-string 1))))
10385 (delete "" values)))))
10387 (defun org-insert-property-drawer ()
10388 "Insert a property drawer into the current entry."
10389 (interactive)
10390 (org-back-to-heading t)
10391 (looking-at outline-regexp)
10392 (let ((indent (- (match-end 0)(match-beginning 0)))
10393 (beg (point))
10394 (re (concat "^[ \t]*" org-keyword-time-regexp))
10395 end hiddenp)
10396 (outline-next-heading)
10397 (setq end (point))
10398 (goto-char beg)
10399 (while (re-search-forward re end t))
10400 (setq hiddenp (org-invisible-p))
10401 (end-of-line 1)
10402 (and (equal (char-after) ?\n) (forward-char 1))
10403 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10404 (beginning-of-line 2))
10405 (org-skip-over-state-notes)
10406 (skip-chars-backward " \t\n\r")
10407 (if (eq (char-before) ?*) (forward-char 1))
10408 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10409 (beginning-of-line 0)
10410 (org-indent-to-column indent)
10411 (beginning-of-line 2)
10412 (org-indent-to-column indent)
10413 (beginning-of-line 0)
10414 (if hiddenp
10415 (save-excursion
10416 (org-back-to-heading t)
10417 (hide-entry))
10418 (org-flag-drawer t))))
10420 (defun org-set-property (property value)
10421 "In the current entry, set PROPERTY to VALUE.
10422 When called interactively, this will prompt for a property name, offering
10423 completion on existing and default properties. And then it will prompt
10424 for a value, offering competion either on allowed values (via an inherited
10425 xxx_ALL property) or on existing values in other instances of this property
10426 in the current file."
10427 (interactive
10428 (let* ((completion-ignore-case t)
10429 (keys (org-buffer-property-keys nil t t))
10430 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10431 (prop (if (member prop0 keys)
10432 prop0
10433 (or (cdr (assoc (downcase prop0)
10434 (mapcar (lambda (x) (cons (downcase x) x))
10435 keys)))
10436 prop0)))
10437 (cur (org-entry-get nil prop))
10438 (allowed (org-property-get-allowed-values nil prop 'table))
10439 (existing (mapcar 'list (org-property-values prop)))
10440 (val (if allowed
10441 (org-completing-read "Value: " allowed nil 'req-match)
10442 (org-completing-read
10443 (concat "Value" (if (and cur (string-match "\\S-" cur))
10444 (concat "[" cur "]") "")
10445 ": ")
10446 existing nil nil "" nil cur))))
10447 (list prop (if (equal val "") cur val))))
10448 (unless (equal (org-entry-get nil property) value)
10449 (org-entry-put nil property value)))
10451 (defun org-delete-property (property)
10452 "In the current entry, delete PROPERTY."
10453 (interactive
10454 (let* ((completion-ignore-case t)
10455 (prop (completing-read
10456 "Property: " (org-entry-properties nil 'standard))))
10457 (list prop)))
10458 (message "Property %s %s" property
10459 (if (org-entry-delete nil property)
10460 "deleted"
10461 "was not present in the entry")))
10463 (defun org-delete-property-globally (property)
10464 "Remove PROPERTY globally, from all entries."
10465 (interactive
10466 (let* ((completion-ignore-case t)
10467 (prop (completing-read
10468 "Globally remove property: "
10469 (mapcar 'list (org-buffer-property-keys)))))
10470 (list prop)))
10471 (save-excursion
10472 (save-restriction
10473 (widen)
10474 (goto-char (point-min))
10475 (let ((cnt 0))
10476 (while (re-search-forward
10477 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10478 nil t)
10479 (setq cnt (1+ cnt))
10480 (replace-match ""))
10481 (message "Property \"%s\" removed from %d entries" property cnt)))))
10483 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10485 (defun org-compute-property-at-point ()
10486 "Compute the property at point.
10487 This looks for an enclosing column format, extracts the operator and
10488 then applies it to the proerty in the column format's scope."
10489 (interactive)
10490 (unless (org-at-property-p)
10491 (error "Not at a property"))
10492 (let ((prop (org-match-string-no-properties 2)))
10493 (org-columns-get-format-and-top-level)
10494 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10495 (error "No operator defined for property %s" prop))
10496 (org-columns-compute prop)))
10498 (defun org-property-get-allowed-values (pom property &optional table)
10499 "Get allowed values for the property PROPERTY.
10500 When TABLE is non-nil, return an alist that can directly be used for
10501 completion."
10502 (let (vals)
10503 (cond
10504 ((equal property "TODO")
10505 (setq vals (org-with-point-at pom
10506 (append org-todo-keywords-1 '("")))))
10507 ((equal property "PRIORITY")
10508 (let ((n org-lowest-priority))
10509 (while (>= n org-highest-priority)
10510 (push (char-to-string n) vals)
10511 (setq n (1- n)))))
10512 ((member property org-special-properties))
10514 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10516 (when (and vals (string-match "\\S-" vals))
10517 (setq vals (car (read-from-string (concat "(" vals ")"))))
10518 (setq vals (mapcar (lambda (x)
10519 (cond ((stringp x) x)
10520 ((numberp x) (number-to-string x))
10521 ((symbolp x) (symbol-name x))
10522 (t "???")))
10523 vals)))))
10524 (if table (mapcar 'list vals) vals)))
10526 (defun org-property-previous-allowed-value (&optional previous)
10527 "Switch to the next allowed value for this property."
10528 (interactive)
10529 (org-property-next-allowed-value t))
10531 (defun org-property-next-allowed-value (&optional previous)
10532 "Switch to the next allowed value for this property."
10533 (interactive)
10534 (unless (org-at-property-p)
10535 (error "Not at a property"))
10536 (let* ((key (match-string 2))
10537 (value (match-string 3))
10538 (allowed (or (org-property-get-allowed-values (point) key)
10539 (and (member value '("[ ]" "[-]" "[X]"))
10540 '("[ ]" "[X]"))))
10541 nval)
10542 (unless allowed
10543 (error "Allowed values for this property have not been defined"))
10544 (if previous (setq allowed (reverse allowed)))
10545 (if (member value allowed)
10546 (setq nval (car (cdr (member value allowed)))))
10547 (setq nval (or nval (car allowed)))
10548 (if (equal nval value)
10549 (error "Only one allowed value for this property"))
10550 (org-at-property-p)
10551 (replace-match (concat " :" key ": " nval) t t)
10552 (org-indent-line-function)
10553 (beginning-of-line 1)
10554 (skip-chars-forward " \t")))
10556 (defun org-find-entry-with-id (ident)
10557 "Locate the entry that contains the ID property with exact value IDENT.
10558 IDENT can be a string, a symbol or a number, this function will search for
10559 the string representation of it.
10560 Return the position where this entry starts, or nil if there is no such entry."
10561 (let ((id (cond
10562 ((stringp ident) ident)
10563 ((symbol-name ident) (symbol-name ident))
10564 ((numberp ident) (number-to-string ident))
10565 (t (error "IDENT %s must be a string, symbol or number" ident))))
10566 (case-fold-search nil))
10567 (save-excursion
10568 (save-restriction
10569 (widen)
10570 (goto-char (point-min))
10571 (when (re-search-forward
10572 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10573 nil t)
10574 (org-back-to-heading)
10575 (point))))))
10577 ;;;; Timestamps
10579 (defvar org-last-changed-timestamp nil)
10580 (defvar org-time-was-given) ; dynamically scoped parameter
10581 (defvar org-end-time-was-given) ; dynamically scoped parameter
10582 (defvar org-ts-what) ; dynamically scoped parameter
10584 (defun org-time-stamp (arg)
10585 "Prompt for a date/time and insert a time stamp.
10586 If the user specifies a time like HH:MM, or if this command is called
10587 with a prefix argument, the time stamp will contain date and time.
10588 Otherwise, only the date will be included. All parts of a date not
10589 specified by the user will be filled in from the current date/time.
10590 So if you press just return without typing anything, the time stamp
10591 will represent the current date/time. If there is already a timestamp
10592 at the cursor, it will be modified."
10593 (interactive "P")
10594 (let* ((ts nil)
10595 (default-time
10596 ;; Default time is either today, or, when entering a range,
10597 ;; the range start.
10598 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10599 (save-excursion
10600 (re-search-backward
10601 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10602 (- (point) 20) t)))
10603 (apply 'encode-time (org-parse-time-string (match-string 1)))
10604 (current-time)))
10605 (default-input (and ts (org-get-compact-tod ts)))
10606 org-time-was-given org-end-time-was-given time)
10607 (cond
10608 ((and (org-at-timestamp-p)
10609 (eq last-command 'org-time-stamp)
10610 (eq this-command 'org-time-stamp))
10611 (insert "--")
10612 (setq time (let ((this-command this-command))
10613 (org-read-date arg 'totime nil nil default-time default-input)))
10614 (org-insert-time-stamp time (or org-time-was-given arg)))
10615 ((org-at-timestamp-p)
10616 (setq time (let ((this-command this-command))
10617 (org-read-date arg 'totime nil nil default-time default-input)))
10618 (when (org-at-timestamp-p) ; just to get the match data
10619 (replace-match "")
10620 (setq org-last-changed-timestamp
10621 (org-insert-time-stamp
10622 time (or org-time-was-given arg)
10623 nil nil nil (list org-end-time-was-given))))
10624 (message "Timestamp updated"))
10626 (setq time (let ((this-command this-command))
10627 (org-read-date arg 'totime nil nil default-time default-input)))
10628 (org-insert-time-stamp time (or org-time-was-given arg)
10629 nil nil nil (list org-end-time-was-given))))))
10631 ;; FIXME: can we use this for something else, like computing time differences?
10632 (defun org-get-compact-tod (s)
10633 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10634 (let* ((t1 (match-string 1 s))
10635 (h1 (string-to-number (match-string 2 s)))
10636 (m1 (string-to-number (match-string 3 s)))
10637 (t2 (and (match-end 4) (match-string 5 s)))
10638 (h2 (and t2 (string-to-number (match-string 6 s))))
10639 (m2 (and t2 (string-to-number (match-string 7 s))))
10640 dh dm)
10641 (if (not t2)
10643 (setq dh (- h2 h1) dm (- m2 m1))
10644 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10645 (concat t1 "+" (number-to-string dh)
10646 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10648 (defun org-time-stamp-inactive (&optional arg)
10649 "Insert an inactive time stamp.
10650 An inactive time stamp is enclosed in square brackets instead of angle
10651 brackets. It is inactive in the sense that it does not trigger agenda entries,
10652 does not link to the calendar and cannot be changed with the S-cursor keys.
10653 So these are more for recording a certain time/date."
10654 (interactive "P")
10655 (let (org-time-was-given org-end-time-was-given time)
10656 (setq time (org-read-date arg 'totime))
10657 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10658 nil nil (list org-end-time-was-given))))
10660 (defvar org-date-ovl (org-make-overlay 1 1))
10661 (org-overlay-put org-date-ovl 'face 'org-warning)
10662 (org-detach-overlay org-date-ovl)
10664 (defvar org-ans1) ; dynamically scoped parameter
10665 (defvar org-ans2) ; dynamically scoped parameter
10667 (defvar org-plain-time-of-day-regexp) ; defined below
10669 (defvar org-read-date-overlay nil)
10670 (defvar org-dcst nil) ; dynamically scoped
10672 (defun org-read-date (&optional with-time to-time from-string prompt
10673 default-time default-input)
10674 "Read a date, possibly a time, and make things smooth for the user.
10675 The prompt will suggest to enter an ISO date, but you can also enter anything
10676 which will at least partially be understood by `parse-time-string'.
10677 Unrecognized parts of the date will default to the current day, month, year,
10678 hour and minute. If this command is called to replace a timestamp at point,
10679 of to enter the second timestamp of a range, the default time is taken from the
10680 existing stamp. For example,
10681 3-2-5 --> 2003-02-05
10682 feb 15 --> currentyear-02-15
10683 sep 12 9 --> 2009-09-12
10684 12:45 --> today 12:45
10685 22 sept 0:34 --> currentyear-09-22 0:34
10686 12 --> currentyear-currentmonth-12
10687 Fri --> nearest Friday (today or later)
10688 etc.
10690 Furthermore you can specify a relative date by giving, as the *first* thing
10691 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10692 change in days weeks, months, years.
10693 With a single plus or minus, the date is relative to today. With a double
10694 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10695 +4d --> four days from today
10696 +4 --> same as above
10697 +2w --> two weeks from today
10698 ++5 --> five days from default date
10700 The function understands only English month and weekday abbreviations,
10701 but this can be configured with the variables `parse-time-months' and
10702 `parse-time-weekdays'.
10704 While prompting, a calendar is popped up - you can also select the
10705 date with the mouse (button 1). The calendar shows a period of three
10706 months. To scroll it to other months, use the keys `>' and `<'.
10707 If you don't like the calendar, turn it off with
10708 \(setq org-read-date-popup-calendar nil)
10710 With optional argument TO-TIME, the date will immediately be converted
10711 to an internal time.
10712 With an optional argument WITH-TIME, the prompt will suggest to also
10713 insert a time. Note that when WITH-TIME is not set, you can still
10714 enter a time, and this function will inform the calling routine about
10715 this change. The calling routine may then choose to change the format
10716 used to insert the time stamp into the buffer to include the time.
10717 With optional argument FROM-STRING, read from this string instead from
10718 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10719 the time/date that is used for everything that is not specified by the
10720 user."
10721 (require 'parse-time)
10722 (let* ((org-time-stamp-rounding-minutes
10723 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10724 (org-dcst org-display-custom-times)
10725 (ct (org-current-time))
10726 (def (or default-time ct))
10727 (defdecode (decode-time def))
10728 (dummy (progn
10729 (when (< (nth 2 defdecode) org-extend-today-until)
10730 (setcar (nthcdr 2 defdecode) -1)
10731 (setcar (nthcdr 1 defdecode) 59)
10732 (setq def (apply 'encode-time defdecode)
10733 defdecode (decode-time def)))))
10734 (calendar-move-hook nil)
10735 (calendar-view-diary-initially-flag nil)
10736 (view-diary-entries-initially nil)
10737 (calendar-view-holidays-initially-flag nil)
10738 (view-calendar-holidays-initially nil)
10739 (timestr (format-time-string
10740 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10741 (prompt (concat (if prompt (concat prompt " ") "")
10742 (format "Date+time [%s]: " timestr)))
10743 ans (org-ans0 "") org-ans1 org-ans2 final)
10745 (cond
10746 (from-string (setq ans from-string))
10747 (org-read-date-popup-calendar
10748 (save-excursion
10749 (save-window-excursion
10750 (calendar)
10751 (calendar-forward-day (- (time-to-days def)
10752 (calendar-absolute-from-gregorian
10753 (calendar-current-date))))
10754 (org-eval-in-calendar nil t)
10755 (let* ((old-map (current-local-map))
10756 (map (copy-keymap calendar-mode-map))
10757 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10758 (org-defkey map (kbd "RET") 'org-calendar-select)
10759 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10760 'org-calendar-select-mouse)
10761 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10762 'org-calendar-select-mouse)
10763 (org-defkey minibuffer-local-map [(meta shift left)]
10764 (lambda () (interactive)
10765 (org-eval-in-calendar '(calendar-backward-month 1))))
10766 (org-defkey minibuffer-local-map [(meta shift right)]
10767 (lambda () (interactive)
10768 (org-eval-in-calendar '(calendar-forward-month 1))))
10769 (org-defkey minibuffer-local-map [(meta shift up)]
10770 (lambda () (interactive)
10771 (org-eval-in-calendar '(calendar-backward-year 1))))
10772 (org-defkey minibuffer-local-map [(meta shift down)]
10773 (lambda () (interactive)
10774 (org-eval-in-calendar '(calendar-forward-year 1))))
10775 (org-defkey minibuffer-local-map [(shift up)]
10776 (lambda () (interactive)
10777 (org-eval-in-calendar '(calendar-backward-week 1))))
10778 (org-defkey minibuffer-local-map [(shift down)]
10779 (lambda () (interactive)
10780 (org-eval-in-calendar '(calendar-forward-week 1))))
10781 (org-defkey minibuffer-local-map [(shift left)]
10782 (lambda () (interactive)
10783 (org-eval-in-calendar '(calendar-backward-day 1))))
10784 (org-defkey minibuffer-local-map [(shift right)]
10785 (lambda () (interactive)
10786 (org-eval-in-calendar '(calendar-forward-day 1))))
10787 (org-defkey minibuffer-local-map ">"
10788 (lambda () (interactive)
10789 (org-eval-in-calendar '(scroll-calendar-left 1))))
10790 (org-defkey minibuffer-local-map "<"
10791 (lambda () (interactive)
10792 (org-eval-in-calendar '(scroll-calendar-right 1))))
10793 (unwind-protect
10794 (progn
10795 (use-local-map map)
10796 (add-hook 'post-command-hook 'org-read-date-display)
10797 (setq org-ans0 (read-string prompt default-input nil nil))
10798 ;; org-ans0: from prompt
10799 ;; org-ans1: from mouse click
10800 ;; org-ans2: from calendar motion
10801 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10802 (remove-hook 'post-command-hook 'org-read-date-display)
10803 (use-local-map old-map)
10804 (when org-read-date-overlay
10805 (org-delete-overlay org-read-date-overlay)
10806 (setq org-read-date-overlay nil)))))))
10808 (t ; Naked prompt only
10809 (unwind-protect
10810 (setq ans (read-string prompt default-input nil timestr))
10811 (when org-read-date-overlay
10812 (org-delete-overlay org-read-date-overlay)
10813 (setq org-read-date-overlay nil)))))
10815 (setq final (org-read-date-analyze ans def defdecode))
10817 (if to-time
10818 (apply 'encode-time final)
10819 (if (and (boundp 'org-time-was-given) org-time-was-given)
10820 (format "%04d-%02d-%02d %02d:%02d"
10821 (nth 5 final) (nth 4 final) (nth 3 final)
10822 (nth 2 final) (nth 1 final))
10823 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10824 (defvar def)
10825 (defvar defdecode)
10826 (defvar with-time)
10827 (defun org-read-date-display ()
10828 "Display the currrent date prompt interpretation in the minibuffer."
10829 (when org-read-date-display-live
10830 (when org-read-date-overlay
10831 (org-delete-overlay org-read-date-overlay))
10832 (let ((p (point)))
10833 (end-of-line 1)
10834 (while (not (equal (buffer-substring
10835 (max (point-min) (- (point) 4)) (point))
10836 " "))
10837 (insert " "))
10838 (goto-char p))
10839 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10840 " " (or org-ans1 org-ans2)))
10841 (org-end-time-was-given nil)
10842 (f (org-read-date-analyze ans def defdecode))
10843 (fmts (if org-dcst
10844 org-time-stamp-custom-formats
10845 org-time-stamp-formats))
10846 (fmt (if (or with-time
10847 (and (boundp 'org-time-was-given) org-time-was-given))
10848 (cdr fmts)
10849 (car fmts)))
10850 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10851 (when (and org-end-time-was-given
10852 (string-match org-plain-time-of-day-regexp txt))
10853 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10854 org-end-time-was-given
10855 (substring txt (match-end 0)))))
10856 (setq org-read-date-overlay
10857 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10858 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10860 (defun org-read-date-analyze (ans def defdecode)
10861 "Analyze the combined answer of the date prompt."
10862 ;; FIXME: cleanup and comment
10863 (let (delta deltan deltaw deltadef year month day
10864 hour minute second wday pm h2 m2 tl wday1
10865 iso-year iso-weekday iso-week iso-year iso-date)
10867 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10868 (setq ans "+0"))
10870 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10871 (setq ans (replace-match "" t t ans)
10872 deltan (car delta)
10873 deltaw (nth 1 delta)
10874 deltadef (nth 2 delta)))
10876 ;; Check if there is an iso week date in there
10877 ;; If yes, sore the info and ostpone interpreting it until the rest
10878 ;; of the parsing is done
10879 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10880 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10881 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10882 iso-week (string-to-number (match-string 2 ans)))
10883 (setq ans (replace-match "" t t ans)))
10885 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10886 (when (string-match
10887 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10888 (setq year (if (match-end 2)
10889 (string-to-number (match-string 2 ans))
10890 (string-to-number (format-time-string "%Y")))
10891 month (string-to-number (match-string 3 ans))
10892 day (string-to-number (match-string 4 ans)))
10893 (if (< year 100) (setq year (+ 2000 year)))
10894 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10895 t nil ans)))
10896 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10897 ;; If there is a time with am/pm, and *no* time without it, we convert
10898 ;; so that matching will be successful.
10899 (loop for i from 1 to 2 do ; twice, for end time as well
10900 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10901 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10902 (setq hour (string-to-number (match-string 1 ans))
10903 minute (if (match-end 3)
10904 (string-to-number (match-string 3 ans))
10906 pm (equal ?p
10907 (string-to-char (downcase (match-string 4 ans)))))
10908 (if (and (= hour 12) (not pm))
10909 (setq hour 0)
10910 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10911 (setq ans (replace-match (format "%02d:%02d" hour minute)
10912 t t ans))))
10914 ;; Check if a time range is given as a duration
10915 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10916 (setq hour (string-to-number (match-string 1 ans))
10917 h2 (+ hour (string-to-number (match-string 3 ans)))
10918 minute (string-to-number (match-string 2 ans))
10919 m2 (+ minute (if (match-end 5) (string-to-number
10920 (match-string 5 ans))0)))
10921 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10922 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10923 t t ans)))
10925 ;; Check if there is a time range
10926 (when (boundp 'org-end-time-was-given)
10927 (setq org-time-was-given nil)
10928 (when (and (string-match org-plain-time-of-day-regexp ans)
10929 (match-end 8))
10930 (setq org-end-time-was-given (match-string 8 ans))
10931 (setq ans (concat (substring ans 0 (match-beginning 7))
10932 (substring ans (match-end 7))))))
10934 (setq tl (parse-time-string ans)
10935 day (or (nth 3 tl) (nth 3 defdecode))
10936 month (or (nth 4 tl)
10937 (if (and org-read-date-prefer-future
10938 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10939 (1+ (nth 4 defdecode))
10940 (nth 4 defdecode)))
10941 year (or (nth 5 tl)
10942 (if (and org-read-date-prefer-future
10943 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10944 (1+ (nth 5 defdecode))
10945 (nth 5 defdecode)))
10946 hour (or (nth 2 tl) (nth 2 defdecode))
10947 minute (or (nth 1 tl) (nth 1 defdecode))
10948 second (or (nth 0 tl) 0)
10949 wday (nth 6 tl))
10951 ;; Special date definitions below
10952 (cond
10953 (iso-week
10954 ;; There was an iso week
10955 (setq year (or iso-year year)
10956 day (or iso-weekday wday 1)
10957 wday nil ; to make sure that the trigger below does not match
10958 iso-date (calendar-gregorian-from-absolute
10959 (calendar-absolute-from-iso
10960 (list iso-week day year))))
10961 ; FIXME: Should we also push ISO weeks into the future?
10962 ; (when (and org-read-date-prefer-future
10963 ; (not iso-year)
10964 ; (< (calendar-absolute-from-gregorian iso-date)
10965 ; (time-to-days (current-time))))
10966 ; (setq year (1+ year)
10967 ; iso-date (calendar-gregorian-from-absolute
10968 ; (calendar-absolute-from-iso
10969 ; (list iso-week day year)))))
10970 (setq month (car iso-date)
10971 year (nth 2 iso-date)
10972 day (nth 1 iso-date)))
10973 (deltan
10974 (unless deltadef
10975 (let ((now (decode-time (current-time))))
10976 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10977 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10978 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10979 ((equal deltaw "m") (setq month (+ month deltan)))
10980 ((equal deltaw "y") (setq year (+ year deltan)))))
10981 ((and wday (not (nth 3 tl)))
10982 ;; Weekday was given, but no day, so pick that day in the week
10983 ;; on or after the derived date.
10984 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10985 (unless (equal wday wday1)
10986 (setq day (+ day (% (- wday wday1 -7) 7))))))
10987 (if (and (boundp 'org-time-was-given)
10988 (nth 2 tl))
10989 (setq org-time-was-given t))
10990 (if (< year 100) (setq year (+ 2000 year)))
10991 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10992 (list second minute hour day month year)))
10994 (defvar parse-time-weekdays)
10996 (defun org-read-date-get-relative (s today default)
10997 "Check string S for special relative date string.
10998 TODAY and DEFAULT are internal times, for today and for a default.
10999 Return shift list (N what def-flag)
11000 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11001 N is the number of WHATs to shift.
11002 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11003 the DEFAULT date rather than TODAY."
11004 (when (and
11005 (string-match
11006 (concat
11007 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11008 "\\([0-9]+\\)?"
11009 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11010 "\\([ \t]\\|$\\)") s)
11011 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11012 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11013 (string-to-char (substring (match-string 1 s) -1))
11014 ?+))
11015 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11016 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11017 (what (if (match-end 3) (match-string 3 s) "d"))
11018 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11019 (date (if rel default today))
11020 (wday (nth 6 (decode-time date)))
11021 delta)
11022 (if wday1
11023 (progn
11024 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11025 (if (= dir ?-) (setq delta (- delta 7)))
11026 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11027 (list delta "d" rel))
11028 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11030 (defun org-eval-in-calendar (form &optional keepdate)
11031 "Eval FORM in the calendar window and return to current window.
11032 Also, store the cursor date in variable org-ans2."
11033 (let ((sw (selected-window)))
11034 (select-window (get-buffer-window "*Calendar*"))
11035 (eval form)
11036 (when (and (not keepdate) (calendar-cursor-to-date))
11037 (let* ((date (calendar-cursor-to-date))
11038 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11039 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11040 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11041 (select-window sw)))
11043 ; ;; Update the prompt to show new default date
11044 ; (save-excursion
11045 ; (goto-char (point-min))
11046 ; (when (and org-ans2
11047 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11048 ; (get-text-property (match-end 0) 'field))
11049 ; (let ((inhibit-read-only t))
11050 ; (replace-match (concat "[" org-ans2 "]") t t)
11051 ; (add-text-properties (point-min) (1+ (match-end 0))
11052 ; (text-properties-at (1+ (point-min)))))))))
11054 (defun org-calendar-select ()
11055 "Return to `org-read-date' with the date currently selected.
11056 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11057 (interactive)
11058 (when (calendar-cursor-to-date)
11059 (let* ((date (calendar-cursor-to-date))
11060 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11061 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11062 (if (active-minibuffer-window) (exit-minibuffer))))
11064 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11065 "Insert a date stamp for the date given by the internal TIME.
11066 WITH-HM means, use the stamp format that includes the time of the day.
11067 INACTIVE means use square brackets instead of angular ones, so that the
11068 stamp will not contribute to the agenda.
11069 PRE and POST are optional strings to be inserted before and after the
11070 stamp.
11071 The command returns the inserted time stamp."
11072 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11073 stamp)
11074 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11075 (insert-before-markers (or pre ""))
11076 (insert-before-markers (setq stamp (format-time-string fmt time)))
11077 (when (listp extra)
11078 (setq extra (car extra))
11079 (if (and (stringp extra)
11080 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11081 (setq extra (format "-%02d:%02d"
11082 (string-to-number (match-string 1 extra))
11083 (string-to-number (match-string 2 extra))))
11084 (setq extra nil)))
11085 (when extra
11086 (backward-char 1)
11087 (insert-before-markers extra)
11088 (forward-char 1))
11089 (insert-before-markers (or post ""))
11090 stamp))
11092 (defun org-toggle-time-stamp-overlays ()
11093 "Toggle the use of custom time stamp formats."
11094 (interactive)
11095 (setq org-display-custom-times (not org-display-custom-times))
11096 (unless org-display-custom-times
11097 (let ((p (point-min)) (bmp (buffer-modified-p)))
11098 (while (setq p (next-single-property-change p 'display))
11099 (if (and (get-text-property p 'display)
11100 (eq (get-text-property p 'face) 'org-date))
11101 (remove-text-properties
11102 p (setq p (next-single-property-change p 'display))
11103 '(display t))))
11104 (set-buffer-modified-p bmp)))
11105 (if (featurep 'xemacs)
11106 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11107 (org-restart-font-lock)
11108 (setq org-table-may-need-update t)
11109 (if org-display-custom-times
11110 (message "Time stamps are overlayed with custom format")
11111 (message "Time stamp overlays removed")))
11113 (defun org-display-custom-time (beg end)
11114 "Overlay modified time stamp format over timestamp between BEG and END."
11115 (let* ((ts (buffer-substring beg end))
11116 t1 w1 with-hm tf time str w2 (off 0))
11117 (save-match-data
11118 (setq t1 (org-parse-time-string ts t))
11119 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11120 (setq off (- (match-end 0) (match-beginning 0)))))
11121 (setq end (- end off))
11122 (setq w1 (- end beg)
11123 with-hm (and (nth 1 t1) (nth 2 t1))
11124 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11125 time (org-fix-decoded-time t1)
11126 str (org-add-props
11127 (format-time-string
11128 (substring tf 1 -1) (apply 'encode-time time))
11129 nil 'mouse-face 'highlight)
11130 w2 (length str))
11131 (if (not (= w2 w1))
11132 (add-text-properties (1+ beg) (+ 2 beg)
11133 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11134 (if (featurep 'xemacs)
11135 (progn
11136 (put-text-property beg end 'invisible t)
11137 (put-text-property beg end 'end-glyph (make-glyph str)))
11138 (put-text-property beg end 'display str))))
11140 (defun org-translate-time (string)
11141 "Translate all timestamps in STRING to custom format.
11142 But do this only if the variable `org-display-custom-times' is set."
11143 (when org-display-custom-times
11144 (save-match-data
11145 (let* ((start 0)
11146 (re org-ts-regexp-both)
11147 t1 with-hm inactive tf time str beg end)
11148 (while (setq start (string-match re string start))
11149 (setq beg (match-beginning 0)
11150 end (match-end 0)
11151 t1 (save-match-data
11152 (org-parse-time-string (substring string beg end) t))
11153 with-hm (and (nth 1 t1) (nth 2 t1))
11154 inactive (equal (substring string beg (1+ beg)) "[")
11155 tf (funcall (if with-hm 'cdr 'car)
11156 org-time-stamp-custom-formats)
11157 time (org-fix-decoded-time t1)
11158 str (format-time-string
11159 (concat
11160 (if inactive "[" "<") (substring tf 1 -1)
11161 (if inactive "]" ">"))
11162 (apply 'encode-time time))
11163 string (replace-match str t t string)
11164 start (+ start (length str)))))))
11165 string)
11167 (defun org-fix-decoded-time (time)
11168 "Set 0 instead of nil for the first 6 elements of time.
11169 Don't touch the rest."
11170 (let ((n 0))
11171 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11173 (defun org-days-to-time (timestamp-string)
11174 "Difference between TIMESTAMP-STRING and now in days."
11175 (- (time-to-days (org-time-string-to-time timestamp-string))
11176 (time-to-days (current-time))))
11178 (defun org-deadline-close (timestamp-string &optional ndays)
11179 "Is the time in TIMESTAMP-STRING close to the current date?"
11180 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11181 (and (< (org-days-to-time timestamp-string) ndays)
11182 (not (org-entry-is-done-p))))
11184 (defun org-get-wdays (ts)
11185 "Get the deadline lead time appropriate for timestring TS."
11186 (cond
11187 ((<= org-deadline-warning-days 0)
11188 ;; 0 or negative, enforce this value no matter what
11189 (- org-deadline-warning-days))
11190 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11191 ;; lead time is specified.
11192 (floor (* (string-to-number (match-string 1 ts))
11193 (cdr (assoc (match-string 2 ts)
11194 '(("d" . 1) ("w" . 7)
11195 ("m" . 30.4) ("y" . 365.25)))))))
11196 ;; go for the default.
11197 (t org-deadline-warning-days)))
11199 (defun org-calendar-select-mouse (ev)
11200 "Return to `org-read-date' with the date currently selected.
11201 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11202 (interactive "e")
11203 (mouse-set-point ev)
11204 (when (calendar-cursor-to-date)
11205 (let* ((date (calendar-cursor-to-date))
11206 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11207 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11208 (if (active-minibuffer-window) (exit-minibuffer))))
11210 (defun org-check-deadlines (ndays)
11211 "Check if there are any deadlines due or past due.
11212 A deadline is considered due if it happens within `org-deadline-warning-days'
11213 days from today's date. If the deadline appears in an entry marked DONE,
11214 it is not shown. The prefix arg NDAYS can be used to test that many
11215 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11216 (interactive "P")
11217 (let* ((org-warn-days
11218 (cond
11219 ((equal ndays '(4)) 100000)
11220 (ndays (prefix-numeric-value ndays))
11221 (t (abs org-deadline-warning-days))))
11222 (case-fold-search nil)
11223 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11224 (callback
11225 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11227 (message "%d deadlines past-due or due within %d days"
11228 (org-occur regexp nil callback)
11229 org-warn-days)))
11231 (defun org-check-before-date (date)
11232 "Check if there are deadlines or scheduled entries before DATE."
11233 (interactive (list (org-read-date)))
11234 (let ((case-fold-search nil)
11235 (regexp (concat "\\<\\(" org-deadline-string
11236 "\\|" org-scheduled-string
11237 "\\) *<\\([^>]+\\)>"))
11238 (callback
11239 (lambda () (time-less-p
11240 (org-time-string-to-time (match-string 2))
11241 (org-time-string-to-time date)))))
11242 (message "%d entries before %s"
11243 (org-occur regexp nil callback) date)))
11245 (defun org-evaluate-time-range (&optional to-buffer)
11246 "Evaluate a time range by computing the difference between start and end.
11247 Normally the result is just printed in the echo area, but with prefix arg
11248 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11249 If the time range is actually in a table, the result is inserted into the
11250 next column.
11251 For time difference computation, a year is assumed to be exactly 365
11252 days in order to avoid rounding problems."
11253 (interactive "P")
11255 (org-clock-update-time-maybe)
11256 (save-excursion
11257 (unless (org-at-date-range-p t)
11258 (goto-char (point-at-bol))
11259 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11260 (if (not (org-at-date-range-p t))
11261 (error "Not at a time-stamp range, and none found in current line")))
11262 (let* ((ts1 (match-string 1))
11263 (ts2 (match-string 2))
11264 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11265 (match-end (match-end 0))
11266 (time1 (org-time-string-to-time ts1))
11267 (time2 (org-time-string-to-time ts2))
11268 (t1 (time-to-seconds time1))
11269 (t2 (time-to-seconds time2))
11270 (diff (abs (- t2 t1)))
11271 (negative (< (- t2 t1) 0))
11272 ;; (ys (floor (* 365 24 60 60)))
11273 (ds (* 24 60 60))
11274 (hs (* 60 60))
11275 (fy "%dy %dd %02d:%02d")
11276 (fy1 "%dy %dd")
11277 (fd "%dd %02d:%02d")
11278 (fd1 "%dd")
11279 (fh "%02d:%02d")
11280 y d h m align)
11281 (if havetime
11282 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11284 d (floor (/ diff ds)) diff (mod diff ds)
11285 h (floor (/ diff hs)) diff (mod diff hs)
11286 m (floor (/ diff 60)))
11287 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11289 d (floor (+ (/ diff ds) 0.5))
11290 h 0 m 0))
11291 (if (not to-buffer)
11292 (message "%s" (org-make-tdiff-string y d h m))
11293 (if (org-at-table-p)
11294 (progn
11295 (goto-char match-end)
11296 (setq align t)
11297 (and (looking-at " *|") (goto-char (match-end 0))))
11298 (goto-char match-end))
11299 (if (looking-at
11300 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11301 (replace-match ""))
11302 (if negative (insert " -"))
11303 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11304 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11305 (insert " " (format fh h m))))
11306 (if align (org-table-align))
11307 (message "Time difference inserted")))))
11309 (defun org-make-tdiff-string (y d h m)
11310 (let ((fmt "")
11311 (l nil))
11312 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11313 l (push y l)))
11314 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11315 l (push d l)))
11316 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11317 l (push h l)))
11318 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11319 l (push m l)))
11320 (apply 'format fmt (nreverse l))))
11322 (defun org-time-string-to-time (s)
11323 (apply 'encode-time (org-parse-time-string s)))
11325 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11326 "Convert a time stamp to an absolute day number.
11327 If there is a specifyer for a cyclic time stamp, get the closest date to
11328 DAYNR.
11329 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11330 (cond
11331 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11332 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11333 daynr
11334 (+ daynr 1000)))
11335 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11336 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11337 (time-to-days (current-time))) (match-string 0 s)
11338 prefer show-all))
11339 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11341 (defun org-days-to-iso-week (days)
11342 "Return the iso week number."
11343 (require 'cal-iso)
11344 (car (calendar-iso-from-absolute days)))
11346 (defun org-small-year-to-year (year)
11347 "Convert 2-digit years into 4-digit years.
11348 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11349 The year 2000 cannot be abbreviated. Any year lager than 99
11350 is retrned unchanged."
11351 (if (< year 38)
11352 (setq year (+ 2000 year))
11353 (if (< year 100)
11354 (setq year (+ 1900 year))))
11355 year)
11357 (defun org-time-from-absolute (d)
11358 "Return the time corresponding to date D.
11359 D may be an absolute day number, or a calendar-type list (month day year)."
11360 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11361 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11363 (defun org-calendar-holiday ()
11364 "List of holidays, for Diary display in Org-mode."
11365 (require 'holidays)
11366 (let ((hl (funcall
11367 (if (fboundp 'calendar-check-holidays)
11368 'calendar-check-holidays 'check-calendar-holidays) date)))
11369 (if hl (mapconcat 'identity hl "; "))))
11371 (defun org-diary-sexp-entry (sexp entry date)
11372 "Process a SEXP diary ENTRY for DATE."
11373 (require 'diary-lib)
11374 (let ((result (if calendar-debug-sexp
11375 (let ((stack-trace-on-error t))
11376 (eval (car (read-from-string sexp))))
11377 (condition-case nil
11378 (eval (car (read-from-string sexp)))
11379 (error
11380 (beep)
11381 (message "Bad sexp at line %d in %s: %s"
11382 (org-current-line)
11383 (buffer-file-name) sexp)
11384 (sleep-for 2))))))
11385 (cond ((stringp result) result)
11386 ((and (consp result)
11387 (stringp (cdr result))) (cdr result))
11388 (result entry)
11389 (t nil))))
11391 (defun org-diary-to-ical-string (frombuf)
11392 "Get iCalendar entries from diary entries in buffer FROMBUF.
11393 This uses the icalendar.el library."
11394 (let* ((tmpdir (if (featurep 'xemacs)
11395 (temp-directory)
11396 temporary-file-directory))
11397 (tmpfile (make-temp-name
11398 (expand-file-name "orgics" tmpdir)))
11399 buf rtn b e)
11400 (save-excursion
11401 (set-buffer frombuf)
11402 (icalendar-export-region (point-min) (point-max) tmpfile)
11403 (setq buf (find-buffer-visiting tmpfile))
11404 (set-buffer buf)
11405 (goto-char (point-min))
11406 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11407 (setq b (match-beginning 0)))
11408 (goto-char (point-max))
11409 (if (re-search-backward "^END:VEVENT" nil t)
11410 (setq e (match-end 0)))
11411 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11412 (kill-buffer buf)
11413 (delete-file tmpfile)
11414 rtn))
11416 (defun org-closest-date (start current change prefer show-all)
11417 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11418 When PREFER is `past' return a date that is either CURRENT or past.
11419 When PREFER is `future', return a date that is either CURRENT or future.
11420 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11421 ;; Make the proper lists from the dates
11422 (catch 'exit
11423 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11424 dn dw sday cday n1 n2
11425 d m y y1 y2 date1 date2 nmonths nm ny m2)
11427 (setq start (org-date-to-gregorian start)
11428 current (org-date-to-gregorian
11429 (if show-all
11430 current
11431 (time-to-days (current-time))))
11432 sday (calendar-absolute-from-gregorian start)
11433 cday (calendar-absolute-from-gregorian current))
11435 (if (<= cday sday) (throw 'exit sday))
11437 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11438 (setq dn (string-to-number (match-string 1 change))
11439 dw (cdr (assoc (match-string 2 change) a1)))
11440 (error "Invalid change specifyer: %s" change))
11441 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11442 (cond
11443 ((eq dw 'day)
11444 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11445 n2 (+ n1 dn)))
11446 ((eq dw 'year)
11447 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11448 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11449 (setq date1 (list m d y1)
11450 n1 (calendar-absolute-from-gregorian date1)
11451 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11452 n2 (calendar-absolute-from-gregorian date2)))
11453 ((eq dw 'month)
11454 ;; approx number of month between the tow dates
11455 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11456 ;; How often does dn fit in there?
11457 (setq d (nth 1 start) m (car start) y (nth 2 start)
11458 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11459 m (+ m nm)
11460 ny (floor (/ m 12))
11461 y (+ y ny)
11462 m (- m (* ny 12)))
11463 (while (> m 12) (setq m (- m 12) y (1+ y)))
11464 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11465 (setq m2 (+ m dn) y2 y)
11466 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11467 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11468 (while (< n2 cday)
11469 (setq n1 n2 m m2 y y2)
11470 (setq m2 (+ m dn) y2 y)
11471 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11472 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11474 (if show-all
11475 (cond
11476 ((eq prefer 'past) n1)
11477 ((eq prefer 'future) (if (= cday n1) n1 n2))
11478 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11479 (cond
11480 ((eq prefer 'past) n1)
11481 ((eq prefer 'future) (if (= cday n1) n1 n2))
11482 (t (if (= cday n1) n1 n2)))))))
11484 (defun org-date-to-gregorian (date)
11485 "Turn any specification of DATE into a gregorian date for the calendar."
11486 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11487 ((and (listp date) (= (length date) 3)) date)
11488 ((stringp date)
11489 (setq date (org-parse-time-string date))
11490 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11491 ((listp date)
11492 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11494 (defun org-parse-time-string (s &optional nodefault)
11495 "Parse the standard Org-mode time string.
11496 This should be a lot faster than the normal `parse-time-string'.
11497 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11498 hour and minute fields will be nil if not given."
11499 (if (string-match org-ts-regexp0 s)
11500 (list 0
11501 (if (or (match-beginning 8) (not nodefault))
11502 (string-to-number (or (match-string 8 s) "0")))
11503 (if (or (match-beginning 7) (not nodefault))
11504 (string-to-number (or (match-string 7 s) "0")))
11505 (string-to-number (match-string 4 s))
11506 (string-to-number (match-string 3 s))
11507 (string-to-number (match-string 2 s))
11508 nil nil nil)
11509 (make-list 9 0)))
11511 (defun org-timestamp-up (&optional arg)
11512 "Increase the date item at the cursor by one.
11513 If the cursor is on the year, change the year. If it is on the month or
11514 the day, change that.
11515 With prefix ARG, change by that many units."
11516 (interactive "p")
11517 (org-timestamp-change (prefix-numeric-value arg)))
11519 (defun org-timestamp-down (&optional arg)
11520 "Decrease the date item at the cursor by one.
11521 If the cursor is on the year, change the year. If it is on the month or
11522 the day, change that.
11523 With prefix ARG, change by that many units."
11524 (interactive "p")
11525 (org-timestamp-change (- (prefix-numeric-value arg))))
11527 (defun org-timestamp-up-day (&optional arg)
11528 "Increase the date in the time stamp by one day.
11529 With prefix ARG, change that many days."
11530 (interactive "p")
11531 (if (and (not (org-at-timestamp-p t))
11532 (org-on-heading-p))
11533 (org-todo 'up)
11534 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11536 (defun org-timestamp-down-day (&optional arg)
11537 "Decrease the date in the time stamp by one day.
11538 With prefix ARG, change that many days."
11539 (interactive "p")
11540 (if (and (not (org-at-timestamp-p t))
11541 (org-on-heading-p))
11542 (org-todo 'down)
11543 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11545 (defun org-at-timestamp-p (&optional inactive-ok)
11546 "Determine if the cursor is in or at a timestamp."
11547 (interactive)
11548 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11549 (pos (point))
11550 (ans (or (looking-at tsr)
11551 (save-excursion
11552 (skip-chars-backward "^[<\n\r\t")
11553 (if (> (point) (point-min)) (backward-char 1))
11554 (and (looking-at tsr)
11555 (> (- (match-end 0) pos) -1))))))
11556 (and ans
11557 (boundp 'org-ts-what)
11558 (setq org-ts-what
11559 (cond
11560 ((= pos (match-beginning 0)) 'bracket)
11561 ((= pos (1- (match-end 0))) 'bracket)
11562 ((org-pos-in-match-range pos 2) 'year)
11563 ((org-pos-in-match-range pos 3) 'month)
11564 ((org-pos-in-match-range pos 7) 'hour)
11565 ((org-pos-in-match-range pos 8) 'minute)
11566 ((or (org-pos-in-match-range pos 4)
11567 (org-pos-in-match-range pos 5)) 'day)
11568 ((and (> pos (or (match-end 8) (match-end 5)))
11569 (< pos (match-end 0)))
11570 (- pos (or (match-end 8) (match-end 5))))
11571 (t 'day))))
11572 ans))
11574 (defun org-toggle-timestamp-type ()
11575 "Toggle the type (<active> or [inactive]) of a time stamp."
11576 (interactive)
11577 (when (org-at-timestamp-p t)
11578 (save-excursion
11579 (goto-char (match-beginning 0))
11580 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11581 (goto-char (1- (match-end 0)))
11582 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11583 (message "Timestamp is now %sactive"
11584 (if (equal (char-before) ?>) "in" ""))))
11586 (defun org-timestamp-change (n &optional what)
11587 "Change the date in the time stamp at point.
11588 The date will be changed by N times WHAT. WHAT can be `day', `month',
11589 `year', `minute', `second'. If WHAT is not given, the cursor position
11590 in the timestamp determines what will be changed."
11591 (let ((pos (point))
11592 with-hm inactive
11593 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11594 org-ts-what
11595 extra rem
11596 ts time time0)
11597 (if (not (org-at-timestamp-p t))
11598 (error "Not at a timestamp"))
11599 (if (and (not what) (eq org-ts-what 'bracket))
11600 (org-toggle-timestamp-type)
11601 (if (and (not what) (not (eq org-ts-what 'day))
11602 org-display-custom-times
11603 (get-text-property (point) 'display)
11604 (not (get-text-property (1- (point)) 'display)))
11605 (setq org-ts-what 'day))
11606 (setq org-ts-what (or what org-ts-what)
11607 inactive (= (char-after (match-beginning 0)) ?\[)
11608 ts (match-string 0))
11609 (replace-match "")
11610 (if (string-match
11611 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11613 (setq extra (match-string 1 ts)))
11614 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11615 (setq with-hm t))
11616 (setq time0 (org-parse-time-string ts))
11617 (when (and (eq org-ts-what 'minute)
11618 (eq current-prefix-arg nil))
11619 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11620 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11621 (setcar (cdr time0) (+ (nth 1 time0)
11622 (if (> n 0) (- rem) (- dm rem))))))
11623 (setq time
11624 (encode-time (or (car time0) 0)
11625 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11626 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11627 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11628 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11629 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11630 (nthcdr 6 time0)))
11631 (when (integerp org-ts-what)
11632 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11633 (if (eq what 'calendar)
11634 (let ((cal-date (org-get-date-from-calendar)))
11635 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11636 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11637 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11638 (setcar time0 (or (car time0) 0))
11639 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11640 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11641 (setq time (apply 'encode-time time0))))
11642 (setq org-last-changed-timestamp
11643 (org-insert-time-stamp time with-hm inactive nil nil extra))
11644 (org-clock-update-time-maybe)
11645 (goto-char pos)
11646 ;; Try to recenter the calendar window, if any
11647 (if (and org-calendar-follow-timestamp-change
11648 (get-buffer-window "*Calendar*" t)
11649 (memq org-ts-what '(day month year)))
11650 (org-recenter-calendar (time-to-days time))))))
11652 (defun org-modify-ts-extra (s pos n dm)
11653 "Change the different parts of the lead-time and repeat fields in timestamp."
11654 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11655 ng h m new rem)
11656 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11657 (cond
11658 ((or (org-pos-in-match-range pos 2)
11659 (org-pos-in-match-range pos 3))
11660 (setq m (string-to-number (match-string 3 s))
11661 h (string-to-number (match-string 2 s)))
11662 (if (org-pos-in-match-range pos 2)
11663 (setq h (+ h n))
11664 (setq n (* dm (org-no-warnings (signum n))))
11665 (when (not (= 0 (setq rem (% m dm))))
11666 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11667 (setq m (+ m n)))
11668 (if (< m 0) (setq m (+ m 60) h (1- h)))
11669 (if (> m 59) (setq m (- m 60) h (1+ h)))
11670 (setq h (min 24 (max 0 h)))
11671 (setq ng 1 new (format "-%02d:%02d" h m)))
11672 ((org-pos-in-match-range pos 6)
11673 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11674 ((org-pos-in-match-range pos 5)
11675 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11677 ((org-pos-in-match-range pos 9)
11678 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11679 ((org-pos-in-match-range pos 8)
11680 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11682 (when ng
11683 (setq s (concat
11684 (substring s 0 (match-beginning ng))
11686 (substring s (match-end ng))))))
11689 (defun org-recenter-calendar (date)
11690 "If the calendar is visible, recenter it to DATE."
11691 (let* ((win (selected-window))
11692 (cwin (get-buffer-window "*Calendar*" t))
11693 (calendar-move-hook nil))
11694 (when cwin
11695 (select-window cwin)
11696 (calendar-goto-date (if (listp date) date
11697 (calendar-gregorian-from-absolute date)))
11698 (select-window win))))
11700 (defun org-goto-calendar (&optional arg)
11701 "Go to the Emacs calendar at the current date.
11702 If there is a time stamp in the current line, go to that date.
11703 A prefix ARG can be used to force the current date."
11704 (interactive "P")
11705 (let ((tsr org-ts-regexp) diff
11706 (calendar-move-hook nil)
11707 (calendar-view-holidays-initially-flag nil)
11708 (view-calendar-holidays-initially nil)
11709 (calendar-view-diary-initially-flag nil)
11710 (view-diary-entries-initially nil))
11711 (if (or (org-at-timestamp-p)
11712 (save-excursion
11713 (beginning-of-line 1)
11714 (looking-at (concat ".*" tsr))))
11715 (let ((d1 (time-to-days (current-time)))
11716 (d2 (time-to-days
11717 (org-time-string-to-time (match-string 1)))))
11718 (setq diff (- d2 d1))))
11719 (calendar)
11720 (calendar-goto-today)
11721 (if (and diff (not arg)) (calendar-forward-day diff))))
11723 (defun org-get-date-from-calendar ()
11724 "Return a list (month day year) of date at point in calendar."
11725 (with-current-buffer "*Calendar*"
11726 (save-match-data
11727 (calendar-cursor-to-date))))
11729 (defun org-date-from-calendar ()
11730 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11731 If there is already a time stamp at the cursor position, update it."
11732 (interactive)
11733 (if (org-at-timestamp-p t)
11734 (org-timestamp-change 0 'calendar)
11735 (let ((cal-date (org-get-date-from-calendar)))
11736 (org-insert-time-stamp
11737 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11739 (defun org-minutes-to-hh:mm-string (m)
11740 "Compute H:MM from a number of minutes."
11741 (let ((h (/ m 60)))
11742 (setq m (- m (* 60 h)))
11743 (format org-time-clocksum-format h m)))
11745 (defun org-hh:mm-string-to-minutes (s)
11746 "Convert a string H:MM to a number of minutes."
11747 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11748 (+ (* (string-to-number (match-string 1 s)) 60)
11749 (string-to-number (match-string 2 s)))
11752 ;;;; Agenda files
11754 ;;;###autoload
11755 (defun org-iswitchb (&optional arg)
11756 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11757 With a prefix argument, restrict available to files.
11758 With two prefix arguments, restrict available buffers to agenda files.
11760 Due to some yet unresolved reason, global function
11761 `iswitchb-mode' needs to be active for this function to work."
11762 (interactive "P")
11763 (require 'iswitchb)
11764 (let ((enabled iswitchb-mode) blist)
11765 (or enabled (iswitchb-mode 1))
11766 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11767 ((equal arg '(16)) (org-buffer-list 'agenda))
11768 (t (org-buffer-list))))
11769 (unwind-protect
11770 (let ((iswitchb-make-buflist-hook
11771 (lambda ()
11772 (setq iswitchb-temp-buflist
11773 (mapcar 'buffer-name blist)))))
11774 (switch-to-buffer
11775 (iswitchb-read-buffer
11776 "Switch-to: " nil t))
11777 (or enabled (iswitchb-mode -1))))))
11779 (defun org-buffer-list (&optional predicate tmp)
11780 "Return a list of Org buffers.
11781 PREDICATE can be either 'export, 'files or 'agenda.
11783 'export restrict the list to Export buffers.
11784 'files restrict the list to buffers visiting Org files.
11785 'agenda restrict the list to buffers visiting agenda files.
11787 If TMP is non-nil, don't include temporary buffers."
11788 (let (filter blist)
11789 (setq filter
11790 (cond ((eq predicate 'files) "\.org$")
11791 ((eq predicate 'export) "\*Org .*Export")
11792 (t "\*Org \\|\.org$")))
11793 (setq blist
11794 (mapcar
11795 (lambda(b)
11796 (let ((bname (buffer-name b))
11797 (bfile (buffer-file-name b)))
11798 (if (and (string-match filter bname)
11799 (if (eq predicate 'agenda)
11800 (member bfile
11801 (mapcar (lambda(f) (file-truename f))
11802 org-agenda-files)) t)
11803 (if tmp (not (string-match "tmp" bname)) t)) b)))
11804 (buffer-list)))
11805 (delete nil blist)))
11807 (defun org-agenda-files (&optional unrestricted ext)
11808 "Get the list of agenda files.
11809 Optional UNRESTRICTED means return the full list even if a restriction
11810 is currently in place.
11811 When EXT is non-nil, try to add all files that are created by adding EXT
11812 to the file nemes. Basically, this is a way to add the archive files
11813 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11814 a string, \"_archive\" will be used."
11815 (let ((files
11816 (cond
11817 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11818 ((stringp org-agenda-files) (org-read-agenda-file-list))
11819 ((listp org-agenda-files) org-agenda-files)
11820 (t (error "Invalid value of `org-agenda-files'")))))
11821 (setq files (apply 'append
11822 (mapcar (lambda (f)
11823 (if (file-directory-p f)
11824 (directory-files
11825 f t org-agenda-file-regexp)
11826 (list f)))
11827 files)))
11828 (when org-agenda-skip-unavailable-files
11829 (setq files (delq nil
11830 (mapcar (function
11831 (lambda (file)
11832 (and (file-readable-p file) file)))
11833 files))))
11834 (when ext
11835 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11836 ext "_archive"))
11837 (setq files (apply 'append
11838 (mapcar
11839 (lambda (f)
11840 (if (file-exists-p (concat f ext))
11841 (list f (concat f ext))
11842 (list f)))
11843 files))))
11844 files))
11846 (defun org-edit-agenda-file-list ()
11847 "Edit the list of agenda files.
11848 Depending on setup, this either uses customize to edit the variable
11849 `org-agenda-files', or it visits the file that is holding the list. In the
11850 latter case, the buffer is set up in a way that saving it automatically kills
11851 the buffer and restores the previous window configuration."
11852 (interactive)
11853 (if (stringp org-agenda-files)
11854 (let ((cw (current-window-configuration)))
11855 (find-file org-agenda-files)
11856 (org-set-local 'org-window-configuration cw)
11857 (org-add-hook 'after-save-hook
11858 (lambda ()
11859 (set-window-configuration
11860 (prog1 org-window-configuration
11861 (kill-buffer (current-buffer))))
11862 (org-install-agenda-files-menu)
11863 (message "New agenda file list installed"))
11864 nil 'local)
11865 (message "%s" (substitute-command-keys
11866 "Edit list and finish with \\[save-buffer]")))
11867 (customize-variable 'org-agenda-files)))
11869 (defun org-store-new-agenda-file-list (list)
11870 "Set new value for the agenda file list and save it correcly."
11871 (if (stringp org-agenda-files)
11872 (let ((f org-agenda-files) b)
11873 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11874 (with-temp-file f
11875 (insert (mapconcat 'identity list "\n") "\n")))
11876 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11877 (setq org-agenda-files list)
11878 (customize-save-variable 'org-agenda-files org-agenda-files))))
11880 (defun org-read-agenda-file-list ()
11881 "Read the list of agenda files from a file."
11882 (when (file-directory-p org-agenda-files)
11883 (error "`org-agenda-files' cannot be a single directory"))
11884 (when (stringp org-agenda-files)
11885 (with-temp-buffer
11886 (insert-file-contents org-agenda-files)
11887 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11890 ;;;###autoload
11891 (defun org-cycle-agenda-files ()
11892 "Cycle through the files in `org-agenda-files'.
11893 If the current buffer visits an agenda file, find the next one in the list.
11894 If the current buffer does not, find the first agenda file."
11895 (interactive)
11896 (let* ((fs (org-agenda-files t))
11897 (files (append fs (list (car fs))))
11898 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11899 file)
11900 (unless files (error "No agenda files"))
11901 (catch 'exit
11902 (while (setq file (pop files))
11903 (if (equal (file-truename file) tcf)
11904 (when (car files)
11905 (find-file (car files))
11906 (throw 'exit t))))
11907 (find-file (car fs)))
11908 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11910 (defun org-agenda-file-to-front (&optional to-end)
11911 "Move/add the current file to the top of the agenda file list.
11912 If the file is not present in the list, it is added to the front. If it is
11913 present, it is moved there. With optional argument TO-END, add/move to the
11914 end of the list."
11915 (interactive "P")
11916 (let ((org-agenda-skip-unavailable-files nil)
11917 (file-alist (mapcar (lambda (x)
11918 (cons (file-truename x) x))
11919 (org-agenda-files t)))
11920 (ctf (file-truename buffer-file-name))
11921 x had)
11922 (setq x (assoc ctf file-alist) had x)
11924 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11925 (if to-end
11926 (setq file-alist (append (delq x file-alist) (list x)))
11927 (setq file-alist (cons x (delq x file-alist))))
11928 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11929 (org-install-agenda-files-menu)
11930 (message "File %s to %s of agenda file list"
11931 (if had "moved" "added") (if to-end "end" "front"))))
11933 (defun org-remove-file (&optional file)
11934 "Remove current file from the list of files in variable `org-agenda-files'.
11935 These are the files which are being checked for agenda entries.
11936 Optional argument FILE means, use this file instead of the current."
11937 (interactive)
11938 (let* ((org-agenda-skip-unavailable-files nil)
11939 (file (or file buffer-file-name))
11940 (true-file (file-truename file))
11941 (afile (abbreviate-file-name file))
11942 (files (delq nil (mapcar
11943 (lambda (x)
11944 (if (equal true-file
11945 (file-truename x))
11946 nil x))
11947 (org-agenda-files t)))))
11948 (if (not (= (length files) (length (org-agenda-files t))))
11949 (progn
11950 (org-store-new-agenda-file-list files)
11951 (org-install-agenda-files-menu)
11952 (message "Removed file: %s" afile))
11953 (message "File was not in list: %s (not removed)" afile))))
11955 (defun org-file-menu-entry (file)
11956 (vector file (list 'find-file file) t))
11958 (defun org-check-agenda-file (file)
11959 "Make sure FILE exists. If not, ask user what to do."
11960 (when (not (file-exists-p file))
11961 (message "non-existent file %s. [R]emove from list or [A]bort?"
11962 (abbreviate-file-name file))
11963 (let ((r (downcase (read-char-exclusive))))
11964 (cond
11965 ((equal r ?r)
11966 (org-remove-file file)
11967 (throw 'nextfile t))
11968 (t (error "Abort"))))))
11970 (defun org-get-agenda-file-buffer (file)
11971 "Get a buffer visiting FILE. If the buffer needs to be created, add
11972 it to the list of buffers which might be released later."
11973 (let ((buf (org-find-base-buffer-visiting file)))
11974 (if buf
11975 buf ; just return it
11976 ;; Make a new buffer and remember it
11977 (setq buf (find-file-noselect file))
11978 (if buf (push buf org-agenda-new-buffers))
11979 buf)))
11981 (defun org-release-buffers (blist)
11982 "Release all buffers in list, asking the user for confirmation when needed.
11983 When a buffer is unmodified, it is just killed. When modified, it is saved
11984 \(if the user agrees) and then killed."
11985 (let (buf file)
11986 (while (setq buf (pop blist))
11987 (setq file (buffer-file-name buf))
11988 (when (and (buffer-modified-p buf)
11989 file
11990 (y-or-n-p (format "Save file %s? " file)))
11991 (with-current-buffer buf (save-buffer)))
11992 (kill-buffer buf))))
11994 (defun org-prepare-agenda-buffers (files)
11995 "Create buffers for all agenda files, protect archived trees and comments."
11996 (interactive)
11997 (let ((pa '(:org-archived t))
11998 (pc '(:org-comment t))
11999 (pall '(:org-archived t :org-comment t))
12000 (inhibit-read-only t)
12001 (rea (concat ":" org-archive-tag ":"))
12002 bmp file re)
12003 (save-excursion
12004 (save-restriction
12005 (while (setq file (pop files))
12006 (if (bufferp file)
12007 (set-buffer file)
12008 (org-check-agenda-file file)
12009 (set-buffer (org-get-agenda-file-buffer file)))
12010 (widen)
12011 (setq bmp (buffer-modified-p))
12012 (org-refresh-category-properties)
12013 (setq org-todo-keywords-for-agenda
12014 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12015 (setq org-done-keywords-for-agenda
12016 (append org-done-keywords-for-agenda org-done-keywords))
12017 (save-excursion
12018 (remove-text-properties (point-min) (point-max) pall)
12019 (when org-agenda-skip-archived-trees
12020 (goto-char (point-min))
12021 (while (re-search-forward rea nil t)
12022 (if (org-on-heading-p t)
12023 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12024 (goto-char (point-min))
12025 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12026 (while (re-search-forward re nil t)
12027 (add-text-properties
12028 (match-beginning 0) (org-end-of-subtree t) pc)))
12029 (set-buffer-modified-p bmp))))))
12031 ;;;; Embedded LaTeX
12033 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12034 "Keymap for the minor `org-cdlatex-mode'.")
12036 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12037 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12038 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12039 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12040 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12042 (defvar org-cdlatex-texmathp-advice-is-done nil
12043 "Flag remembering if we have applied the advice to texmathp already.")
12045 (define-minor-mode org-cdlatex-mode
12046 "Toggle the minor `org-cdlatex-mode'.
12047 This mode supports entering LaTeX environment and math in LaTeX fragments
12048 in Org-mode.
12049 \\{org-cdlatex-mode-map}"
12050 nil " OCDL" nil
12051 (when org-cdlatex-mode (require 'cdlatex))
12052 (unless org-cdlatex-texmathp-advice-is-done
12053 (setq org-cdlatex-texmathp-advice-is-done t)
12054 (defadvice texmathp (around org-math-always-on activate)
12055 "Always return t in org-mode buffers.
12056 This is because we want to insert math symbols without dollars even outside
12057 the LaTeX math segments. If Orgmode thinks that point is actually inside
12058 en embedded LaTeX fragement, let texmathp do its job.
12059 \\[org-cdlatex-mode-map]"
12060 (interactive)
12061 (let (p)
12062 (cond
12063 ((not (org-mode-p)) ad-do-it)
12064 ((eq this-command 'cdlatex-math-symbol)
12065 (setq ad-return-value t
12066 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12068 (let ((p (org-inside-LaTeX-fragment-p)))
12069 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12070 (setq ad-return-value t
12071 texmathp-why '("Org-mode embedded math" . 0))
12072 (if p ad-do-it)))))))))
12074 (defun turn-on-org-cdlatex ()
12075 "Unconditionally turn on `org-cdlatex-mode'."
12076 (org-cdlatex-mode 1))
12078 (defun org-inside-LaTeX-fragment-p ()
12079 "Test if point is inside a LaTeX fragment.
12080 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12081 sequence appearing also before point.
12082 Even though the matchers for math are configurable, this function assumes
12083 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12084 delimiters are skipped when they have been removed by customization.
12085 The return value is nil, or a cons cell with the delimiter and
12086 and the position of this delimiter.
12088 This function does a reasonably good job, but can locally be fooled by
12089 for example currency specifications. For example it will assume being in
12090 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12091 fragments that are properly closed, but during editing, we have to live
12092 with the uncertainty caused by missing closing delimiters. This function
12093 looks only before point, not after."
12094 (catch 'exit
12095 (let ((pos (point))
12096 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12097 (lim (progn
12098 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12099 (point)))
12100 dd-on str (start 0) m re)
12101 (goto-char pos)
12102 (when dodollar
12103 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12104 re (nth 1 (assoc "$" org-latex-regexps)))
12105 (while (string-match re str start)
12106 (cond
12107 ((= (match-end 0) (length str))
12108 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12109 ((= (match-end 0) (- (length str) 5))
12110 (throw 'exit nil))
12111 (t (setq start (match-end 0))))))
12112 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12113 (goto-char pos)
12114 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12115 (and (match-beginning 2) (throw 'exit nil))
12116 ;; count $$
12117 (while (re-search-backward "\\$\\$" lim t)
12118 (setq dd-on (not dd-on)))
12119 (goto-char pos)
12120 (if dd-on (cons "$$" m))))))
12123 (defun org-try-cdlatex-tab ()
12124 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12125 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12126 - inside a LaTeX fragment, or
12127 - after the first word in a line, where an abbreviation expansion could
12128 insert a LaTeX environment."
12129 (when org-cdlatex-mode
12130 (cond
12131 ((save-excursion
12132 (skip-chars-backward "a-zA-Z0-9*")
12133 (skip-chars-backward " \t")
12134 (bolp))
12135 (cdlatex-tab) t)
12136 ((org-inside-LaTeX-fragment-p)
12137 (cdlatex-tab) t)
12138 (t nil))))
12140 (defun org-cdlatex-underscore-caret (&optional arg)
12141 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12142 Revert to the normal definition outside of these fragments."
12143 (interactive "P")
12144 (if (org-inside-LaTeX-fragment-p)
12145 (call-interactively 'cdlatex-sub-superscript)
12146 (let (org-cdlatex-mode)
12147 (call-interactively (key-binding (vector last-input-event))))))
12149 (defun org-cdlatex-math-modify (&optional arg)
12150 "Execute `cdlatex-math-modify' in LaTeX fragments.
12151 Revert to the normal definition outside of these fragments."
12152 (interactive "P")
12153 (if (org-inside-LaTeX-fragment-p)
12154 (call-interactively 'cdlatex-math-modify)
12155 (let (org-cdlatex-mode)
12156 (call-interactively (key-binding (vector last-input-event))))))
12158 (defvar org-latex-fragment-image-overlays nil
12159 "List of overlays carrying the images of latex fragments.")
12160 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12162 (defun org-remove-latex-fragment-image-overlays ()
12163 "Remove all overlays with LaTeX fragment images in current buffer."
12164 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12165 (setq org-latex-fragment-image-overlays nil))
12167 (defun org-preview-latex-fragment (&optional subtree)
12168 "Preview the LaTeX fragment at point, or all locally or globally.
12169 If the cursor is in a LaTeX fragment, create the image and overlay
12170 it over the source code. If there is no fragment at point, display
12171 all fragments in the current text, from one headline to the next. With
12172 prefix SUBTREE, display all fragments in the current subtree. With a
12173 double prefix `C-u C-u', or when the cursor is before the first headline,
12174 display all fragments in the buffer.
12175 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12176 (interactive "P")
12177 (org-remove-latex-fragment-image-overlays)
12178 (save-excursion
12179 (save-restriction
12180 (let (beg end at msg)
12181 (cond
12182 ((or (equal subtree '(16))
12183 (not (save-excursion
12184 (re-search-backward (concat "^" outline-regexp) nil t))))
12185 (setq beg (point-min) end (point-max)
12186 msg "Creating images for buffer...%s"))
12187 ((equal subtree '(4))
12188 (org-back-to-heading)
12189 (setq beg (point) end (org-end-of-subtree t)
12190 msg "Creating images for subtree...%s"))
12192 (if (setq at (org-inside-LaTeX-fragment-p))
12193 (goto-char (max (point-min) (- (cdr at) 2)))
12194 (org-back-to-heading))
12195 (setq beg (point) end (progn (outline-next-heading) (point))
12196 msg (if at "Creating image...%s"
12197 "Creating images for entry...%s"))))
12198 (message msg "")
12199 (narrow-to-region beg end)
12200 (goto-char beg)
12201 (org-format-latex
12202 (concat "ltxpng/" (file-name-sans-extension
12203 (file-name-nondirectory
12204 buffer-file-name)))
12205 default-directory 'overlays msg at 'forbuffer)
12206 (message msg "done. Use `C-c C-c' to remove images.")))))
12208 (defvar org-latex-regexps
12209 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12210 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12211 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12212 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12213 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12214 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12215 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12216 "Regular expressions for matching embedded LaTeX.")
12218 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12219 "Replace LaTeX fragments with links to an image, and produce images."
12220 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12221 (let* ((prefixnodir (file-name-nondirectory prefix))
12222 (absprefix (expand-file-name prefix dir))
12223 (todir (file-name-directory absprefix))
12224 (opt org-format-latex-options)
12225 (matchers (plist-get opt :matchers))
12226 (re-list org-latex-regexps)
12227 (cnt 0) txt link beg end re e checkdir
12228 m n block linkfile movefile ov)
12229 ;; Check if there are old images files with this prefix, and remove them
12230 (when (file-directory-p todir)
12231 (mapc 'delete-file
12232 (directory-files
12233 todir 'full
12234 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12235 ;; Check the different regular expressions
12236 (while (setq e (pop re-list))
12237 (setq m (car e) re (nth 1 e) n (nth 2 e)
12238 block (if (nth 3 e) "\n\n" ""))
12239 (when (member m matchers)
12240 (goto-char (point-min))
12241 (while (re-search-forward re nil t)
12242 (when (or (not at) (equal (cdr at) (match-beginning n)))
12243 (setq txt (match-string n)
12244 beg (match-beginning n) end (match-end n)
12245 cnt (1+ cnt)
12246 linkfile (format "%s_%04d.png" prefix cnt)
12247 movefile (format "%s_%04d.png" absprefix cnt)
12248 link (concat block "[[file:" linkfile "]]" block))
12249 (if msg (message msg cnt))
12250 (goto-char beg)
12251 (unless checkdir ; make sure the directory exists
12252 (setq checkdir t)
12253 (or (file-directory-p todir) (make-directory todir)))
12254 (org-create-formula-image
12255 txt movefile opt forbuffer)
12256 (if overlays
12257 (progn
12258 (setq ov (org-make-overlay beg end))
12259 (if (featurep 'xemacs)
12260 (progn
12261 (org-overlay-put ov 'invisible t)
12262 (org-overlay-put
12263 ov 'end-glyph
12264 (make-glyph (vector 'png :file movefile))))
12265 (org-overlay-put
12266 ov 'display
12267 (list 'image :type 'png :file movefile :ascent 'center)))
12268 (push ov org-latex-fragment-image-overlays)
12269 (goto-char end))
12270 (delete-region beg end)
12271 (insert link))))))))
12273 ;; This function borrows from Ganesh Swami's latex2png.el
12274 (defun org-create-formula-image (string tofile options buffer)
12275 (let* ((tmpdir (if (featurep 'xemacs)
12276 (temp-directory)
12277 temporary-file-directory))
12278 (texfilebase (make-temp-name
12279 (expand-file-name "orgtex" tmpdir)))
12280 (texfile (concat texfilebase ".tex"))
12281 (dvifile (concat texfilebase ".dvi"))
12282 (pngfile (concat texfilebase ".png"))
12283 (fnh (if (featurep 'xemacs)
12284 (font-height (get-face-font 'default))
12285 (face-attribute 'default :height nil)))
12286 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12287 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12288 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12289 "Black"))
12290 (bg (or (plist-get options (if buffer :background :html-background))
12291 "Transparent")))
12292 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12293 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12294 (with-temp-file texfile
12295 (insert org-format-latex-header
12296 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12297 (let ((dir default-directory))
12298 (condition-case nil
12299 (progn
12300 (cd tmpdir)
12301 (call-process "latex" nil nil nil texfile))
12302 (error nil))
12303 (cd dir))
12304 (if (not (file-exists-p dvifile))
12305 (progn (message "Failed to create dvi file from %s" texfile) nil)
12306 (call-process "dvipng" nil nil nil
12307 "-E" "-fg" fg "-bg" bg
12308 "-D" dpi
12309 ;;"-x" scale "-y" scale
12310 "-T" "tight"
12311 "-o" pngfile
12312 dvifile)
12313 (if (not (file-exists-p pngfile))
12314 (progn (message "Failed to create png file from %s" texfile) nil)
12315 ;; Use the requested file name and clean up
12316 (copy-file pngfile tofile 'replace)
12317 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12318 (delete-file (concat texfilebase e)))
12319 pngfile))))
12321 (defun org-dvipng-color (attr)
12322 "Return an rgb color specification for dvipng."
12323 (apply 'format "rgb %s %s %s"
12324 (mapcar 'org-normalize-color
12325 (color-values (face-attribute 'default attr nil)))))
12327 (defun org-normalize-color (value)
12328 "Return string to be used as color value for an RGB component."
12329 (format "%g" (/ value 65535.0)))
12332 ;;;; Key bindings
12334 ;; Make `C-c C-x' a prefix key
12335 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12337 ;; TAB key with modifiers
12338 (org-defkey org-mode-map "\C-i" 'org-cycle)
12339 (org-defkey org-mode-map [(tab)] 'org-cycle)
12340 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12341 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12342 (org-defkey org-mode-map "\M-\t" 'org-complete)
12343 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12344 ;; The following line is necessary under Suse GNU/Linux
12345 (unless (featurep 'xemacs)
12346 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12347 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12348 (define-key org-mode-map [backtab] 'org-shifttab)
12350 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12351 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12352 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12354 ;; Cursor keys with modifiers
12355 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12356 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12357 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12358 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12360 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12361 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12362 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12363 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12365 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12366 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12367 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12368 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12370 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12371 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12373 ;;; Extra keys for tty access.
12374 ;; We only set them when really needed because otherwise the
12375 ;; menus don't show the simple keys
12377 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12378 (not window-system))
12379 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12380 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12381 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12382 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12383 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12384 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12385 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12386 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12387 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12388 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12389 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12390 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12391 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12392 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12393 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12394 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12395 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12396 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12397 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12398 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12399 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12400 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12402 ;; All the other keys
12404 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12405 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12406 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
12407 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12408 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12409 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12410 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12411 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12412 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12413 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12414 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12415 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12416 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12417 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12418 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12419 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12420 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12421 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12422 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12423 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12424 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12425 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12426 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12427 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12428 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12429 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12430 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12431 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12432 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12433 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12434 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12435 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12436 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12437 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12438 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12439 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12440 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12441 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12442 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12443 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12444 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12445 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12446 (org-defkey org-mode-map "\C-c^" 'org-sort)
12447 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12448 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12449 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12450 (org-defkey org-mode-map "\C-m" 'org-return)
12451 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12452 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12453 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12454 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12455 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12456 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12457 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12458 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12459 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12460 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12461 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12462 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12463 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12464 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12465 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12466 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12468 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12469 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12470 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12471 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12473 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12474 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12475 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12476 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12477 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12478 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12479 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12480 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12481 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12482 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12483 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12484 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12486 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12488 (when (featurep 'xemacs)
12489 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12491 (defvar org-table-auto-blank-field) ; defined in org-table.el
12492 (defun org-self-insert-command (N)
12493 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12494 If the cursor is in a table looking at whitespace, the whitespace is
12495 overwritten, and the table is not marked as requiring realignment."
12496 (interactive "p")
12497 (if (and (org-table-p)
12498 (progn
12499 ;; check if we blank the field, and if that triggers align
12500 (and (featurep 'org-table) org-table-auto-blank-field
12501 (member last-command
12502 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12503 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12504 ;; got extra space, this field does not determine column width
12505 (let (org-table-may-need-update) (org-table-blank-field))
12506 ;; no extra space, this field may determine column width
12507 (org-table-blank-field)))
12509 (eq N 1)
12510 (looking-at "[^|\n]* |"))
12511 (let (org-table-may-need-update)
12512 (goto-char (1- (match-end 0)))
12513 (delete-backward-char 1)
12514 (goto-char (match-beginning 0))
12515 (self-insert-command N))
12516 (setq org-table-may-need-update t)
12517 (self-insert-command N)
12518 (org-fix-tags-on-the-fly)))
12520 (defun org-fix-tags-on-the-fly ()
12521 (when (and (equal (char-after (point-at-bol)) ?*)
12522 (org-on-heading-p))
12523 (org-align-tags-here org-tags-column)))
12525 (defun org-delete-backward-char (N)
12526 "Like `delete-backward-char', insert whitespace at field end in tables.
12527 When deleting backwards, in tables this function will insert whitespace in
12528 front of the next \"|\" separator, to keep the table aligned. The table will
12529 still be marked for re-alignment if the field did fill the entire column,
12530 because, in this case the deletion might narrow the column."
12531 (interactive "p")
12532 (if (and (org-table-p)
12533 (eq N 1)
12534 (string-match "|" (buffer-substring (point-at-bol) (point)))
12535 (looking-at ".*?|"))
12536 (let ((pos (point))
12537 (noalign (looking-at "[^|\n\r]* |"))
12538 (c org-table-may-need-update))
12539 (backward-delete-char N)
12540 (skip-chars-forward "^|")
12541 (insert " ")
12542 (goto-char (1- pos))
12543 ;; noalign: if there were two spaces at the end, this field
12544 ;; does not determine the width of the column.
12545 (if noalign (setq org-table-may-need-update c)))
12546 (backward-delete-char N)
12547 (org-fix-tags-on-the-fly)))
12549 (defun org-delete-char (N)
12550 "Like `delete-char', but insert whitespace at field end in tables.
12551 When deleting characters, in tables this function will insert whitespace in
12552 front of the next \"|\" separator, to keep the table aligned. The table will
12553 still be marked for re-alignment if the field did fill the entire column,
12554 because, in this case the deletion might narrow the column."
12555 (interactive "p")
12556 (if (and (org-table-p)
12557 (not (bolp))
12558 (not (= (char-after) ?|))
12559 (eq N 1))
12560 (if (looking-at ".*?|")
12561 (let ((pos (point))
12562 (noalign (looking-at "[^|\n\r]* |"))
12563 (c org-table-may-need-update))
12564 (replace-match (concat
12565 (substring (match-string 0) 1 -1)
12566 " |"))
12567 (goto-char pos)
12568 ;; noalign: if there were two spaces at the end, this field
12569 ;; does not determine the width of the column.
12570 (if noalign (setq org-table-may-need-update c)))
12571 (delete-char N))
12572 (delete-char N)
12573 (org-fix-tags-on-the-fly)))
12575 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12576 (put 'org-self-insert-command 'delete-selection t)
12577 (put 'orgtbl-self-insert-command 'delete-selection t)
12578 (put 'org-delete-char 'delete-selection 'supersede)
12579 (put 'org-delete-backward-char 'delete-selection 'supersede)
12581 ;; Make `flyspell-mode' delay after some commands
12582 (put 'org-self-insert-command 'flyspell-delayed t)
12583 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12584 (put 'org-delete-char 'flyspell-delayed t)
12585 (put 'org-delete-backward-char 'flyspell-delayed t)
12587 ;; Make pabbrev-mode expand after org-mode commands
12588 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12589 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12591 ;; How to do this: Measure non-white length of current string
12592 ;; If equal to column width, we should realign.
12594 (defun org-remap (map &rest commands)
12595 "In MAP, remap the functions given in COMMANDS.
12596 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12597 (let (new old)
12598 (while commands
12599 (setq old (pop commands) new (pop commands))
12600 (if (fboundp 'command-remapping)
12601 (org-defkey map (vector 'remap old) new)
12602 (substitute-key-definition old new map global-map)))))
12604 (when (eq org-enable-table-editor 'optimized)
12605 ;; If the user wants maximum table support, we need to hijack
12606 ;; some standard editing functions
12607 (org-remap org-mode-map
12608 'self-insert-command 'org-self-insert-command
12609 'delete-char 'org-delete-char
12610 'delete-backward-char 'org-delete-backward-char)
12611 (org-defkey org-mode-map "|" 'org-force-self-insert))
12613 (defun org-shiftcursor-error ()
12614 "Throw an error because Shift-Cursor command was applied in wrong context."
12615 (error "This command is active in special context like tables, headlines or timestamps"))
12617 (defun org-shifttab (&optional arg)
12618 "Global visibility cycling or move to previous table field.
12619 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12620 on context.
12621 See the individual commands for more information."
12622 (interactive "P")
12623 (cond
12624 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12625 ((integerp arg)
12626 (message "Content view to level: %d" arg)
12627 (org-content (prefix-numeric-value arg))
12628 (setq org-cycle-global-status 'overview))
12629 (t (call-interactively 'org-global-cycle))))
12631 (defun org-shiftmetaleft ()
12632 "Promote subtree or delete table column.
12633 Calls `org-promote-subtree', `org-outdent-item',
12634 or `org-table-delete-column', depending on context.
12635 See the individual commands for more information."
12636 (interactive)
12637 (cond
12638 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12639 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12640 ((org-at-item-p) (call-interactively 'org-outdent-item))
12641 (t (org-shiftcursor-error))))
12643 (defun org-shiftmetaright ()
12644 "Demote subtree or insert table column.
12645 Calls `org-demote-subtree', `org-indent-item',
12646 or `org-table-insert-column', depending on context.
12647 See the individual commands for more information."
12648 (interactive)
12649 (cond
12650 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12651 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12652 ((org-at-item-p) (call-interactively 'org-indent-item))
12653 (t (org-shiftcursor-error))))
12655 (defun org-shiftmetaup (&optional arg)
12656 "Move subtree up or kill table row.
12657 Calls `org-move-subtree-up' or `org-table-kill-row' or
12658 `org-move-item-up' depending on context. See the individual commands
12659 for more information."
12660 (interactive "P")
12661 (cond
12662 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12663 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12664 ((org-at-item-p) (call-interactively 'org-move-item-up))
12665 (t (org-shiftcursor-error))))
12666 (defun org-shiftmetadown (&optional arg)
12667 "Move subtree down or insert table row.
12668 Calls `org-move-subtree-down' or `org-table-insert-row' or
12669 `org-move-item-down', depending on context. See the individual
12670 commands for more information."
12671 (interactive "P")
12672 (cond
12673 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12674 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12675 ((org-at-item-p) (call-interactively 'org-move-item-down))
12676 (t (org-shiftcursor-error))))
12678 (defun org-metaleft (&optional arg)
12679 "Promote heading or move table column to left.
12680 Calls `org-do-promote' or `org-table-move-column', depending on context.
12681 With no specific context, calls the Emacs default `backward-word'.
12682 See the individual commands for more information."
12683 (interactive "P")
12684 (cond
12685 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12686 ((or (org-on-heading-p) (org-region-active-p))
12687 (call-interactively 'org-do-promote))
12688 ((org-at-item-p) (call-interactively 'org-outdent-item))
12689 (t (call-interactively 'backward-word))))
12691 (defun org-metaright (&optional arg)
12692 "Demote subtree or move table column to right.
12693 Calls `org-do-demote' or `org-table-move-column', depending on context.
12694 With no specific context, calls the Emacs default `forward-word'.
12695 See the individual commands for more information."
12696 (interactive "P")
12697 (cond
12698 ((org-at-table-p) (call-interactively 'org-table-move-column))
12699 ((or (org-on-heading-p) (org-region-active-p))
12700 (call-interactively 'org-do-demote))
12701 ((org-at-item-p) (call-interactively 'org-indent-item))
12702 (t (call-interactively 'forward-word))))
12704 (defun org-metaup (&optional arg)
12705 "Move subtree up or move table row up.
12706 Calls `org-move-subtree-up' or `org-table-move-row' or
12707 `org-move-item-up', depending on context. See the individual commands
12708 for more information."
12709 (interactive "P")
12710 (cond
12711 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12712 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12713 ((org-at-item-p) (call-interactively 'org-move-item-up))
12714 (t (transpose-lines 1) (beginning-of-line -1))))
12716 (defun org-metadown (&optional arg)
12717 "Move subtree down or move table row down.
12718 Calls `org-move-subtree-down' or `org-table-move-row' or
12719 `org-move-item-down', depending on context. See the individual
12720 commands for more information."
12721 (interactive "P")
12722 (cond
12723 ((org-at-table-p) (call-interactively 'org-table-move-row))
12724 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12725 ((org-at-item-p) (call-interactively 'org-move-item-down))
12726 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12728 (defun org-shiftup (&optional arg)
12729 "Increase item in timestamp or increase priority of current headline.
12730 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12731 depending on context. See the individual commands for more information."
12732 (interactive "P")
12733 (cond
12734 ((org-at-timestamp-p t)
12735 (call-interactively (if org-edit-timestamp-down-means-later
12736 'org-timestamp-down 'org-timestamp-up)))
12737 ((org-on-heading-p) (call-interactively 'org-priority-up))
12738 ((org-at-item-p) (call-interactively 'org-previous-item))
12739 ((org-clocktable-try-shift 'up arg))
12740 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12742 (defun org-shiftdown (&optional arg)
12743 "Decrease item in timestamp or decrease priority of current headline.
12744 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12745 depending on context. See the individual commands for more information."
12746 (interactive "P")
12747 (cond
12748 ((org-at-timestamp-p t)
12749 (call-interactively (if org-edit-timestamp-down-means-later
12750 'org-timestamp-up 'org-timestamp-down)))
12751 ((org-on-heading-p) (call-interactively 'org-priority-down))
12752 ((org-clocktable-try-shift 'down arg))
12753 (t (call-interactively 'org-next-item))))
12755 (defun org-shiftright (&optional arg)
12756 "Next TODO keyword or timestamp one day later, depending on context."
12757 (interactive "P")
12758 (cond
12759 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12760 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12761 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12762 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12763 ((org-clocktable-try-shift 'right arg))
12764 (t (org-shiftcursor-error))))
12766 (defun org-shiftleft (&optional arg)
12767 "Previous TODO keyword or timestamp one day earlier, depending on context."
12768 (interactive "P")
12769 (cond
12770 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12771 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12772 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12773 ((org-at-property-p)
12774 (call-interactively 'org-property-previous-allowed-value))
12775 ((org-clocktable-try-shift 'left arg))
12776 (t (org-shiftcursor-error))))
12778 (defun org-shiftcontrolright ()
12779 "Switch to next TODO set."
12780 (interactive)
12781 (cond
12782 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12783 (t (org-shiftcursor-error))))
12785 (defun org-shiftcontrolleft ()
12786 "Switch to previous TODO set."
12787 (interactive)
12788 (cond
12789 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12790 (t (org-shiftcursor-error))))
12792 (defun org-ctrl-c-ret ()
12793 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12794 (interactive)
12795 (cond
12796 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12797 (t (call-interactively 'org-insert-heading))))
12799 (defun org-copy-special ()
12800 "Copy region in table or copy current subtree.
12801 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12802 See the individual commands for more information."
12803 (interactive)
12804 (call-interactively
12805 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12807 (defun org-cut-special ()
12808 "Cut region in table or cut current subtree.
12809 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12810 See the individual commands for more information."
12811 (interactive)
12812 (call-interactively
12813 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12815 (defun org-paste-special (arg)
12816 "Paste rectangular region into table, or past subtree relative to level.
12817 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12818 See the individual commands for more information."
12819 (interactive "P")
12820 (if (org-at-table-p)
12821 (org-table-paste-rectangle)
12822 (org-paste-subtree arg)))
12824 (defun org-edit-special ()
12825 "Call a special editor for the stuff at point.
12826 When at a table, call the formula editor with `org-table-edit-formulas'.
12827 When at the first line of an src example, call `org-edit-src-code'.
12828 When in an #+include line, visit the include file. Otherwise call
12829 `ffap' to visit the file at point."
12830 (interactive)
12831 (cond
12832 ((org-at-table-p)
12833 (call-interactively 'org-table-edit-formulas))
12834 ((save-excursion
12835 (beginning-of-line 1)
12836 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12837 (find-file (org-trim (match-string 1))))
12838 ((org-edit-src-code))
12839 (t (call-interactively 'ffap))))
12841 (defun org-ctrl-c-ctrl-c (&optional arg)
12842 "Set tags in headline, or update according to changed information at point.
12844 This command does many different things, depending on context:
12846 - If the cursor is in a headline, prompt for tags and insert them
12847 into the current line, aligned to `org-tags-column'. When called
12848 with prefix arg, realign all tags in the current buffer.
12850 - If the cursor is in one of the special #+KEYWORD lines, this
12851 triggers scanning the buffer for these lines and updating the
12852 information.
12854 - If the cursor is inside a table, realign the table. This command
12855 works even if the automatic table editor has been turned off.
12857 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12858 the entire table.
12860 - If the cursor is a the beginning of a dynamic block, update it.
12862 - If the cursor is inside a table created by the table.el package,
12863 activate that table.
12865 - If the current buffer is a remember buffer, close note and file it.
12866 with a prefix argument, file it without further interaction to the default
12867 location.
12869 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12870 links in this buffer.
12872 - If the cursor is on a numbered item in a plain list, renumber the
12873 ordered list.
12875 - If the cursor is on a checkbox, toggle it."
12876 (interactive "P")
12877 (let ((org-enable-table-editor t))
12878 (cond
12879 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12880 org-occur-highlights
12881 org-latex-fragment-image-overlays)
12882 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12883 (org-remove-occur-highlights)
12884 (org-remove-latex-fragment-image-overlays)
12885 (message "Temporary highlights/overlays removed from current buffer"))
12886 ((and (local-variable-p 'org-finish-function (current-buffer))
12887 (fboundp org-finish-function))
12888 (funcall org-finish-function))
12889 ((org-at-property-p)
12890 (call-interactively 'org-property-action))
12891 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12892 ((org-on-heading-p) (call-interactively 'org-set-tags))
12893 ((org-at-table.el-p)
12894 (require 'table)
12895 (beginning-of-line 1)
12896 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12897 (call-interactively 'table-recognize-table))
12898 ((org-at-table-p)
12899 (org-table-maybe-eval-formula)
12900 (if arg
12901 (call-interactively 'org-table-recalculate)
12902 (org-table-maybe-recalculate-line))
12903 (call-interactively 'org-table-align))
12904 ((org-at-item-checkbox-p)
12905 (call-interactively 'org-toggle-checkbox))
12906 ((org-at-item-p)
12907 (call-interactively 'org-maybe-renumber-ordered-list))
12908 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12909 ;; Dynamic block
12910 (beginning-of-line 1)
12911 (org-update-dblock))
12912 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12913 (cond
12914 ((equal (match-string 1) "TBLFM")
12915 ;; Recalculate the table before this line
12916 (save-excursion
12917 (beginning-of-line 1)
12918 (skip-chars-backward " \r\n\t")
12919 (if (org-at-table-p)
12920 (org-call-with-arg 'org-table-recalculate t))))
12922 ; (org-set-regexps-and-options)
12923 ; (org-restart-font-lock)
12924 (let ((org-inhibit-startup t)) (org-mode-restart))
12925 (message "Local setup has been refreshed"))))
12926 (t (error "C-c C-c can do nothing useful at this location.")))))
12928 (defun org-mode-restart ()
12929 "Restart Org-mode, to scan again for special lines.
12930 Also updates the keyword regular expressions."
12931 (interactive)
12932 (org-mode)
12933 (message "Org-mode restarted"))
12935 (defun org-kill-note-or-show-branches ()
12936 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12937 (interactive)
12938 (if (not org-finish-function)
12939 (call-interactively 'show-branches)
12940 (let ((org-note-abort t))
12941 (funcall org-finish-function))))
12943 (defun org-return (&optional indent)
12944 "Goto next table row or insert a newline.
12945 Calls `org-table-next-row' or `newline', depending on context.
12946 See the individual commands for more information."
12947 (interactive)
12948 (cond
12949 ((bobp) (if indent (newline-and-indent) (newline)))
12950 ((and (org-at-heading-p)
12951 (looking-at
12952 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12953 (org-show-entry)
12954 (end-of-line 1)
12955 (newline))
12956 ((org-at-table-p)
12957 (org-table-justify-field-maybe)
12958 (call-interactively 'org-table-next-row))
12959 (t (if indent (newline-and-indent) (newline)))))
12961 (defun org-return-indent ()
12962 "Goto next table row or insert a newline and indent.
12963 Calls `org-table-next-row' or `newline-and-indent', depending on
12964 context. See the individual commands for more information."
12965 (interactive)
12966 (org-return t))
12968 (defun org-ctrl-c-star ()
12969 "Compute table, or change heading status of lines.
12970 Calls `org-table-recalculate' or `org-toggle-region-headings',
12971 depending on context. This will also turn a plain list item or a normal
12972 line into a subheading."
12973 (interactive)
12974 (cond
12975 ((org-at-table-p)
12976 (call-interactively 'org-table-recalculate))
12977 ((org-region-active-p)
12978 ;; Convert all lines in region to list items
12979 (call-interactively 'org-toggle-region-headings))
12980 ((org-on-heading-p)
12981 (org-toggle-region-headings (point-at-bol)
12982 (min (1+ (point-at-eol)) (point-max))))
12983 ((org-at-item-p)
12984 ;; Convert to heading
12985 (let ((level (save-match-data
12986 (save-excursion
12987 (condition-case nil
12988 (progn
12989 (org-back-to-heading t)
12990 (funcall outline-level))
12991 (error 0))))))
12992 (replace-match
12993 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12994 (t (org-toggle-region-headings (point-at-bol)
12995 (min (1+ (point-at-eol)) (point-max))))))
12997 (defun org-ctrl-c-minus ()
12998 "Insert separator line in table or modify bullet status of line.
12999 Also turns a plain line or a region of lines into list items.
13000 Calls `org-table-insert-hline', `org-toggle-region-items', or
13001 `org-cycle-list-bullet', depending on context."
13002 (interactive)
13003 (cond
13004 ((org-at-table-p)
13005 (call-interactively 'org-table-insert-hline))
13006 ((org-on-heading-p)
13007 ;; Convert to item
13008 (save-excursion
13009 (beginning-of-line 1)
13010 (if (looking-at "\\*+ ")
13011 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13012 ((org-region-active-p)
13013 ;; Convert all lines in region to list items
13014 (call-interactively 'org-toggle-region-items))
13015 ((org-in-item-p)
13016 (call-interactively 'org-cycle-list-bullet))
13017 (t (org-toggle-region-items (point-at-bol)
13018 (min (1+ (point-at-eol)) (point-max))))))
13020 (defun org-toggle-region-items (beg end)
13021 "Convert all lines in region to list items.
13022 If the first line is already an item, convert all list items in the region
13023 to normal lines."
13024 (interactive "r")
13025 (let (l2 l)
13026 (save-excursion
13027 (goto-char end)
13028 (setq l2 (org-current-line))
13029 (goto-char beg)
13030 (beginning-of-line 1)
13031 (setq l (1- (org-current-line)))
13032 (if (org-at-item-p)
13033 ;; We already have items, de-itemize
13034 (while (< (setq l (1+ l)) l2)
13035 (when (org-at-item-p)
13036 (goto-char (match-beginning 2))
13037 (delete-region (match-beginning 2) (match-end 2))
13038 (and (looking-at "[ \t]+") (replace-match "")))
13039 (beginning-of-line 2))
13040 (while (< (setq l (1+ l)) l2)
13041 (unless (org-at-item-p)
13042 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13043 (replace-match "\\1- \\2")))
13044 (beginning-of-line 2))))))
13046 (defun org-toggle-region-headings (beg end)
13047 "Convert all lines in region to list items.
13048 If the first line is already an item, convert all list items in the region
13049 to normal lines."
13050 (interactive "r")
13051 (let (l2 l)
13052 (save-excursion
13053 (goto-char end)
13054 (setq l2 (org-current-line))
13055 (goto-char beg)
13056 (beginning-of-line 1)
13057 (setq l (1- (org-current-line)))
13058 (if (org-on-heading-p)
13059 ;; We already have headlines, de-star them
13060 (while (< (setq l (1+ l)) l2)
13061 (when (org-on-heading-p t)
13062 (and (looking-at outline-regexp) (replace-match "")))
13063 (beginning-of-line 2))
13064 (let* ((stars (save-excursion
13065 (re-search-backward org-complex-heading-regexp nil t)
13066 (or (match-string 1) "*")))
13067 (add-stars (if org-odd-levels-only "**" "*"))
13068 (rpl (concat stars add-stars " \\2")))
13069 (while (< (setq l (1+ l)) l2)
13070 (unless (org-on-heading-p)
13071 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13072 (replace-match rpl)))
13073 (beginning-of-line 2)))))))
13075 (defun org-meta-return (&optional arg)
13076 "Insert a new heading or wrap a region in a table.
13077 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13078 See the individual commands for more information."
13079 (interactive "P")
13080 (cond
13081 ((org-at-table-p)
13082 (call-interactively 'org-table-wrap-region))
13083 (t (call-interactively 'org-insert-heading))))
13085 ;;; Menu entries
13087 ;; Define the Org-mode menus
13088 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13089 '("Tbl"
13090 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13091 ["Next Field" org-cycle (org-at-table-p)]
13092 ["Previous Field" org-shifttab (org-at-table-p)]
13093 ["Next Row" org-return (org-at-table-p)]
13094 "--"
13095 ["Blank Field" org-table-blank-field (org-at-table-p)]
13096 ["Edit Field" org-table-edit-field (org-at-table-p)]
13097 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13098 "--"
13099 ("Column"
13100 ["Move Column Left" org-metaleft (org-at-table-p)]
13101 ["Move Column Right" org-metaright (org-at-table-p)]
13102 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13103 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13104 ("Row"
13105 ["Move Row Up" org-metaup (org-at-table-p)]
13106 ["Move Row Down" org-metadown (org-at-table-p)]
13107 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13108 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13109 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13110 "--"
13111 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13112 ("Rectangle"
13113 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13114 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13115 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13116 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13117 "--"
13118 ("Calculate"
13119 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13120 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13121 ["Edit Formulas" org-edit-special (org-at-table-p)]
13122 "--"
13123 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13124 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13125 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13126 "--"
13127 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13128 "--"
13129 ["Sum Column/Rectangle" org-table-sum
13130 (or (org-at-table-p) (org-region-active-p))]
13131 ["Which Column?" org-table-current-column (org-at-table-p)])
13132 ["Debug Formulas"
13133 org-table-toggle-formula-debugger
13134 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13135 ["Show Col/Row Numbers"
13136 org-table-toggle-coordinate-overlays
13137 :style toggle
13138 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13139 "--"
13140 ["Create" org-table-create (and (not (org-at-table-p))
13141 org-enable-table-editor)]
13142 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13143 ["Import from File" org-table-import (not (org-at-table-p))]
13144 ["Export to File" org-table-export (org-at-table-p)]
13145 "--"
13146 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13148 (easy-menu-define org-org-menu org-mode-map "Org menu"
13149 '("Org"
13150 ("Show/Hide"
13151 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13152 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13153 ["Sparse Tree..." org-sparse-tree t]
13154 ["Reveal Context" org-reveal t]
13155 ["Show All" show-all t]
13156 "--"
13157 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13158 "--"
13159 ["New Heading" org-insert-heading t]
13160 ("Navigate Headings"
13161 ["Up" outline-up-heading t]
13162 ["Next" outline-next-visible-heading t]
13163 ["Previous" outline-previous-visible-heading t]
13164 ["Next Same Level" outline-forward-same-level t]
13165 ["Previous Same Level" outline-backward-same-level t]
13166 "--"
13167 ["Jump" org-goto t])
13168 ("Edit Structure"
13169 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13170 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13171 "--"
13172 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13173 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13174 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13175 "--"
13176 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13177 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13178 ["Demote Heading" org-metaright (not (org-at-table-p))]
13179 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13180 "--"
13181 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13182 "--"
13183 ["Convert to odd levels" org-convert-to-odd-levels t]
13184 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13185 ("Editing"
13186 ["Emphasis..." org-emphasize t]
13187 ["Edit Source Example" org-edit-special t])
13188 ("Archive"
13189 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13190 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13191 ; :active t :keys "C-u C-c C-x C-a"]
13192 ["Sparse trees open ARCHIVE trees"
13193 (setq org-sparse-tree-open-archived-trees
13194 (not org-sparse-tree-open-archived-trees))
13195 :style toggle :selected org-sparse-tree-open-archived-trees]
13196 ["Cycling opens ARCHIVE trees"
13197 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13198 :style toggle :selected org-cycle-open-archived-trees]
13199 ["Agenda includes ARCHIVE trees"
13200 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
13201 :style toggle :selected (not org-agenda-skip-archived-trees)]
13202 "--"
13203 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13204 ; ["Check and Move Children" (org-archive-subtree '(4))
13205 ; :active t :keys "C-u C-c C-x C-s"]
13207 "--"
13208 ("TODO Lists"
13209 ["TODO/DONE/-" org-todo t]
13210 ("Select keyword"
13211 ["Next keyword" org-shiftright (org-on-heading-p)]
13212 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13213 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13214 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13215 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13216 ["Show TODO Tree" org-show-todo-tree t]
13217 ["Global TODO list" org-todo-list t]
13218 "--"
13219 ["Set Priority" org-priority t]
13220 ["Priority Up" org-shiftup t]
13221 ["Priority Down" org-shiftdown t])
13222 ("TAGS and Properties"
13223 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13224 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13225 "--"
13226 ["Set property" 'org-set-property t]
13227 ["Column view of properties" org-columns t]
13228 ["Insert Column View DBlock" org-insert-columns-dblock t])
13229 ("Dates and Scheduling"
13230 ["Timestamp" org-time-stamp t]
13231 ["Timestamp (inactive)" org-time-stamp-inactive t]
13232 ("Change Date"
13233 ["1 Day Later" org-shiftright t]
13234 ["1 Day Earlier" org-shiftleft t]
13235 ["1 ... Later" org-shiftup t]
13236 ["1 ... Earlier" org-shiftdown t])
13237 ["Compute Time Range" org-evaluate-time-range t]
13238 ["Schedule Item" org-schedule t]
13239 ["Deadline" org-deadline t]
13240 "--"
13241 ["Custom time format" org-toggle-time-stamp-overlays
13242 :style radio :selected org-display-custom-times]
13243 "--"
13244 ["Goto Calendar" org-goto-calendar t]
13245 ["Date from Calendar" org-date-from-calendar t])
13246 ("Logging work"
13247 ["Clock in" org-clock-in t]
13248 ["Clock out" org-clock-out t]
13249 ["Clock cancel" org-clock-cancel t]
13250 ["Goto running clock" org-clock-goto t]
13251 ["Display times" org-clock-display t]
13252 ["Create clock table" org-clock-report t]
13253 "--"
13254 ["Record DONE time"
13255 (progn (setq org-log-done (not org-log-done))
13256 (message "Switching to %s will %s record a timestamp"
13257 (car org-done-keywords)
13258 (if org-log-done "automatically" "not")))
13259 :style toggle :selected org-log-done])
13260 "--"
13261 ["Agenda Command..." org-agenda t]
13262 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13263 ("File List for Agenda")
13264 ("Special views current file"
13265 ["TODO Tree" org-show-todo-tree t]
13266 ["Check Deadlines" org-check-deadlines t]
13267 ["Timeline" org-timeline t]
13268 ["Tags Tree" org-tags-sparse-tree t])
13269 "--"
13270 ("Hyperlinks"
13271 ["Store Link (Global)" org-store-link t]
13272 ["Insert Link" org-insert-link t]
13273 ["Follow Link" org-open-at-point t]
13274 "--"
13275 ["Next link" org-next-link t]
13276 ["Previous link" org-previous-link t]
13277 "--"
13278 ["Descriptive Links"
13279 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13280 :style radio
13281 :selected (member '(org-link) buffer-invisibility-spec)]
13282 ["Literal Links"
13283 (progn
13284 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13285 :style radio
13286 :selected (not (member '(org-link) buffer-invisibility-spec))])
13287 "--"
13288 ["Export/Publish..." org-export t]
13289 ("LaTeX"
13290 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13291 :selected org-cdlatex-mode]
13292 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13293 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13294 ["Modify math symbol" org-cdlatex-math-modify
13295 (org-inside-LaTeX-fragment-p)]
13296 ["Export LaTeX fragments as images"
13297 (if (featurep 'org-exp)
13298 (setq org-export-with-LaTeX-fragments
13299 (not org-export-with-LaTeX-fragments))
13300 (require 'org-exp))
13301 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13302 org-export-with-LaTeX-fragments)])
13303 "--"
13304 ("Documentation"
13305 ["Show Version" org-version t]
13306 ["Info Documentation" org-info t])
13307 ("Customize"
13308 ["Browse Org Group" org-customize t]
13309 "--"
13310 ["Expand This Menu" org-create-customize-menu
13311 (fboundp 'customize-menu-create)])
13312 "--"
13313 ["Refresh setup" org-mode-restart t]
13316 (defun org-info (&optional node)
13317 "Read documentation for Org-mode in the info system.
13318 With optional NODE, go directly to that node."
13319 (interactive)
13320 (info (format "(org)%s" (or node ""))))
13322 (defun org-install-agenda-files-menu ()
13323 (let ((bl (buffer-list)))
13324 (save-excursion
13325 (while bl
13326 (set-buffer (pop bl))
13327 (if (org-mode-p) (setq bl nil)))
13328 (when (org-mode-p)
13329 (easy-menu-change
13330 '("Org") "File List for Agenda"
13331 (append
13332 (list
13333 ["Edit File List" (org-edit-agenda-file-list) t]
13334 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13335 ["Remove Current File from List" org-remove-file t]
13336 ["Cycle through agenda files" org-cycle-agenda-files t]
13337 ["Occur in all agenda files" org-occur-in-agenda-files t]
13338 "--")
13339 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13341 ;;;; Documentation
13343 ;;;###autoload
13344 (defun org-require-autoloaded-modules ()
13345 (interactive)
13346 (mapc 'require
13347 '(org-agenda org-archive org-clock org-colview
13348 org-exp org-id org-export-latex org-publish
13349 org-remember org-table)))
13351 ;;;###autoload
13352 (defun org-customize ()
13353 "Call the customize function with org as argument."
13354 (interactive)
13355 (org-load-modules-maybe)
13356 (org-require-autoloaded-modules)
13357 (customize-browse 'org))
13359 (defun org-create-customize-menu ()
13360 "Create a full customization menu for Org-mode, insert it into the menu."
13361 (interactive)
13362 (org-load-modules-maybe)
13363 (org-require-autoloaded-modules)
13364 (if (fboundp 'customize-menu-create)
13365 (progn
13366 (easy-menu-change
13367 '("Org") "Customize"
13368 `(["Browse Org group" org-customize t]
13369 "--"
13370 ,(customize-menu-create 'org)
13371 ["Set" Custom-set t]
13372 ["Save" Custom-save t]
13373 ["Reset to Current" Custom-reset-current t]
13374 ["Reset to Saved" Custom-reset-saved t]
13375 ["Reset to Standard Settings" Custom-reset-standard t]))
13376 (message "\"Org\"-menu now contains full customization menu"))
13377 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13379 ;;;; Miscellaneous stuff
13381 ;;; Generally useful functions
13383 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13384 "Display the given MESSAGE as a warning."
13385 (if (fboundp 'display-warning)
13386 (display-warning 'org message
13387 (if (featurep 'xemacs)
13388 'warning
13389 :warning))
13390 (let ((buf (get-buffer-create "*Org warnings*")))
13391 (with-current-buffer buf
13392 (goto-char (point-max))
13393 (insert "Warning (Org): " message)
13394 (unless (bolp)
13395 (newline)))
13396 (display-buffer buf)
13397 (sit-for 0))))
13399 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13400 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13401 (if (and marker (marker-buffer marker)
13402 (buffer-live-p (marker-buffer marker)))
13403 (progn
13404 (switch-to-buffer (marker-buffer marker))
13405 (if (or (> marker (point-max)) (< marker (point-min)))
13406 (widen))
13407 (goto-char marker))
13408 (if bookmark
13409 (bookmark-jump bookmark)
13410 (error "Cannot find location"))))
13412 (defun org-quote-csv-field (s)
13413 "Quote field for inclusion in CSV material."
13414 (if (string-match "[\",]" s)
13415 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13418 (defun org-plist-delete (plist property)
13419 "Delete PROPERTY from PLIST.
13420 This is in contrast to merely setting it to 0."
13421 (let (p)
13422 (while plist
13423 (if (not (eq property (car plist)))
13424 (setq p (plist-put p (car plist) (nth 1 plist))))
13425 (setq plist (cddr plist)))
13428 (defun org-force-self-insert (N)
13429 "Needed to enforce self-insert under remapping."
13430 (interactive "p")
13431 (self-insert-command N))
13433 (defun org-string-width (s)
13434 "Compute width of string, ignoring invisible characters.
13435 This ignores character with invisibility property `org-link', and also
13436 characters with property `org-cwidth', because these will become invisible
13437 upon the next fontification round."
13438 (let (b l)
13439 (when (or (eq t buffer-invisibility-spec)
13440 (assq 'org-link buffer-invisibility-spec))
13441 (while (setq b (text-property-any 0 (length s)
13442 'invisible 'org-link s))
13443 (setq s (concat (substring s 0 b)
13444 (substring s (or (next-single-property-change
13445 b 'invisible s) (length s)))))))
13446 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13447 (setq s (concat (substring s 0 b)
13448 (substring s (or (next-single-property-change
13449 b 'org-cwidth s) (length s))))))
13450 (setq l (string-width s) b -1)
13451 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13452 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13455 (defun org-base-buffer (buffer)
13456 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13457 (if (not buffer)
13458 buffer
13459 (or (buffer-base-buffer buffer)
13460 buffer)))
13462 (defun org-trim (s)
13463 "Remove whitespace at beginning and end of string."
13464 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13465 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13468 (defun org-wrap (string &optional width lines)
13469 "Wrap string to either a number of lines, or a width in characters.
13470 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13471 that costs. If there is a word longer than WIDTH, the text is actually
13472 wrapped to the length of that word.
13473 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13474 many lines, whatever width that takes.
13475 The return value is a list of lines, without newlines at the end."
13476 (let* ((words (org-split-string string "[ \t\n]+"))
13477 (maxword (apply 'max (mapcar 'org-string-width words)))
13478 w ll)
13479 (cond (width
13480 (org-do-wrap words (max maxword width)))
13481 (lines
13482 (setq w maxword)
13483 (setq ll (org-do-wrap words maxword))
13484 (if (<= (length ll) lines)
13486 (setq ll words)
13487 (while (> (length ll) lines)
13488 (setq w (1+ w))
13489 (setq ll (org-do-wrap words w)))
13490 ll))
13491 (t (error "Cannot wrap this")))))
13493 (defun org-do-wrap (words width)
13494 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13495 (let (lines line)
13496 (while words
13497 (setq line (pop words))
13498 (while (and words (< (+ (length line) (length (car words))) width))
13499 (setq line (concat line " " (pop words))))
13500 (setq lines (push line lines)))
13501 (nreverse lines)))
13503 (defun org-split-string (string &optional separators)
13504 "Splits STRING into substrings at SEPARATORS.
13505 No empty strings are returned if there are matches at the beginning
13506 and end of string."
13507 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13508 (start 0)
13509 notfirst
13510 (list nil))
13511 (while (and (string-match rexp string
13512 (if (and notfirst
13513 (= start (match-beginning 0))
13514 (< start (length string)))
13515 (1+ start) start))
13516 (< (match-beginning 0) (length string)))
13517 (setq notfirst t)
13518 (or (eq (match-beginning 0) 0)
13519 (and (eq (match-beginning 0) (match-end 0))
13520 (eq (match-beginning 0) start))
13521 (setq list
13522 (cons (substring string start (match-beginning 0))
13523 list)))
13524 (setq start (match-end 0)))
13525 (or (eq start (length string))
13526 (setq list
13527 (cons (substring string start)
13528 list)))
13529 (nreverse list)))
13531 (defun org-context ()
13532 "Return a list of contexts of the current cursor position.
13533 If several contexts apply, all are returned.
13534 Each context entry is a list with a symbol naming the context, and
13535 two positions indicating start and end of the context. Possible
13536 contexts are:
13538 :headline anywhere in a headline
13539 :headline-stars on the leading stars in a headline
13540 :todo-keyword on a TODO keyword (including DONE) in a headline
13541 :tags on the TAGS in a headline
13542 :priority on the priority cookie in a headline
13543 :item on the first line of a plain list item
13544 :item-bullet on the bullet/number of a plain list item
13545 :checkbox on the checkbox in a plain list item
13546 :table in an org-mode table
13547 :table-special on a special filed in a table
13548 :table-table in a table.el table
13549 :link on a hyperlink
13550 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13551 :target on a <<target>>
13552 :radio-target on a <<<radio-target>>>
13553 :latex-fragment on a LaTeX fragment
13554 :latex-preview on a LaTeX fragment with overlayed preview image
13556 This function expects the position to be visible because it uses font-lock
13557 faces as a help to recognize the following contexts: :table-special, :link,
13558 and :keyword."
13559 (let* ((f (get-text-property (point) 'face))
13560 (faces (if (listp f) f (list f)))
13561 (p (point)) clist o)
13562 ;; First the large context
13563 (cond
13564 ((org-on-heading-p t)
13565 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13566 (when (progn
13567 (beginning-of-line 1)
13568 (looking-at org-todo-line-tags-regexp))
13569 (push (org-point-in-group p 1 :headline-stars) clist)
13570 (push (org-point-in-group p 2 :todo-keyword) clist)
13571 (push (org-point-in-group p 4 :tags) clist))
13572 (goto-char p)
13573 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13574 (if (looking-at "\\[#[A-Z0-9]\\]")
13575 (push (org-point-in-group p 0 :priority) clist)))
13577 ((org-at-item-p)
13578 (push (org-point-in-group p 2 :item-bullet) clist)
13579 (push (list :item (point-at-bol)
13580 (save-excursion (org-end-of-item) (point)))
13581 clist)
13582 (and (org-at-item-checkbox-p)
13583 (push (org-point-in-group p 0 :checkbox) clist)))
13585 ((org-at-table-p)
13586 (push (list :table (org-table-begin) (org-table-end)) clist)
13587 (if (memq 'org-formula faces)
13588 (push (list :table-special
13589 (previous-single-property-change p 'face)
13590 (next-single-property-change p 'face)) clist)))
13591 ((org-at-table-p 'any)
13592 (push (list :table-table) clist)))
13593 (goto-char p)
13595 ;; Now the small context
13596 (cond
13597 ((org-at-timestamp-p)
13598 (push (org-point-in-group p 0 :timestamp) clist))
13599 ((memq 'org-link faces)
13600 (push (list :link
13601 (previous-single-property-change p 'face)
13602 (next-single-property-change p 'face)) clist))
13603 ((memq 'org-special-keyword faces)
13604 (push (list :keyword
13605 (previous-single-property-change p 'face)
13606 (next-single-property-change p 'face)) clist))
13607 ((org-on-target-p)
13608 (push (org-point-in-group p 0 :target) clist)
13609 (goto-char (1- (match-beginning 0)))
13610 (if (looking-at org-radio-target-regexp)
13611 (push (org-point-in-group p 0 :radio-target) clist))
13612 (goto-char p))
13613 ((setq o (car (delq nil
13614 (mapcar
13615 (lambda (x)
13616 (if (memq x org-latex-fragment-image-overlays) x))
13617 (org-overlays-at (point))))))
13618 (push (list :latex-fragment
13619 (org-overlay-start o) (org-overlay-end o)) clist)
13620 (push (list :latex-preview
13621 (org-overlay-start o) (org-overlay-end o)) clist))
13622 ((org-inside-LaTeX-fragment-p)
13623 ;; FIXME: positions wrong.
13624 (push (list :latex-fragment (point) (point)) clist)))
13626 (setq clist (nreverse (delq nil clist)))
13627 clist))
13629 ;; FIXME: Compare with at-regexp-p Do we need both?
13630 (defun org-in-regexp (re &optional nlines visually)
13631 "Check if point is inside a match of regexp.
13632 Normally only the current line is checked, but you can include NLINES extra
13633 lines both before and after point into the search.
13634 If VISUALLY is set, require that the cursor is not after the match but
13635 really on, so that the block visually is on the match."
13636 (catch 'exit
13637 (let ((pos (point))
13638 (eol (point-at-eol (+ 1 (or nlines 0))))
13639 (inc (if visually 1 0)))
13640 (save-excursion
13641 (beginning-of-line (- 1 (or nlines 0)))
13642 (while (re-search-forward re eol t)
13643 (if (and (<= (match-beginning 0) pos)
13644 (>= (+ inc (match-end 0)) pos))
13645 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13647 (defun org-at-regexp-p (regexp)
13648 "Is point inside a match of REGEXP in the current line?"
13649 (catch 'exit
13650 (save-excursion
13651 (let ((pos (point)) (end (point-at-eol)))
13652 (beginning-of-line 1)
13653 (while (re-search-forward regexp end t)
13654 (if (and (<= (match-beginning 0) pos)
13655 (>= (match-end 0) pos))
13656 (throw 'exit t)))
13657 nil))))
13659 (defun org-occur-in-agenda-files (regexp &optional nlines)
13660 "Call `multi-occur' with buffers for all agenda files."
13661 (interactive "sOrg-files matching: \np")
13662 (let* ((files (org-agenda-files))
13663 (tnames (mapcar 'file-truename files))
13664 (extra org-agenda-text-search-extra-files)
13666 (when (eq (car extra) 'agenda-archives)
13667 (setq extra (cdr extra))
13668 (setq files (org-add-archive-files files)))
13669 (while (setq f (pop extra))
13670 (unless (member (file-truename f) tnames)
13671 (add-to-list 'files f 'append)
13672 (add-to-list 'tnames (file-truename f) 'append)))
13673 (multi-occur
13674 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13675 regexp)))
13677 (if (boundp 'occur-mode-find-occurrence-hook)
13678 ;; Emacs 23
13679 (add-hook 'occur-mode-find-occurrence-hook
13680 (lambda ()
13681 (when (org-mode-p)
13682 (org-reveal))))
13683 ;; Emacs 22
13684 (defadvice occur-mode-goto-occurrence
13685 (after org-occur-reveal activate)
13686 (and (org-mode-p) (org-reveal)))
13687 (defadvice occur-mode-goto-occurrence-other-window
13688 (after org-occur-reveal activate)
13689 (and (org-mode-p) (org-reveal)))
13690 (defadvice occur-mode-display-occurrence
13691 (after org-occur-reveal activate)
13692 (when (org-mode-p)
13693 (let ((pos (occur-mode-find-occurrence)))
13694 (with-current-buffer (marker-buffer pos)
13695 (save-excursion
13696 (goto-char pos)
13697 (org-reveal)))))))
13699 (defun org-uniquify (list)
13700 "Remove duplicate elements from LIST."
13701 (let (res)
13702 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13703 res))
13705 (defun org-delete-all (elts list)
13706 "Remove all elements in ELTS from LIST."
13707 (while elts
13708 (setq list (delete (pop elts) list)))
13709 list)
13711 (defun org-back-over-empty-lines ()
13712 "Move backwards over witespace, to the beginning of the first empty line.
13713 Returns the number of empty lines passed."
13714 (let ((pos (point)))
13715 (skip-chars-backward " \t\n\r")
13716 (beginning-of-line 2)
13717 (goto-char (min (point) pos))
13718 (count-lines (point) pos)))
13720 (defun org-skip-whitespace ()
13721 (skip-chars-forward " \t\n\r"))
13723 (defun org-point-in-group (point group &optional context)
13724 "Check if POINT is in match-group GROUP.
13725 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13726 match. If the match group does ot exist or point is not inside it,
13727 return nil."
13728 (and (match-beginning group)
13729 (>= point (match-beginning group))
13730 (<= point (match-end group))
13731 (if context
13732 (list context (match-beginning group) (match-end group))
13733 t)))
13735 (defun org-switch-to-buffer-other-window (&rest args)
13736 "Switch to buffer in a second window on the current frame.
13737 In particular, do not allow pop-up frames."
13738 (let (pop-up-frames special-display-buffer-names special-display-regexps
13739 special-display-function)
13740 (apply 'switch-to-buffer-other-window args)))
13742 (defun org-combine-plists (&rest plists)
13743 "Create a single property list from all plists in PLISTS.
13744 The process starts by copying the first list, and then setting properties
13745 from the other lists. Settings in the last list are the most significant
13746 ones and overrule settings in the other lists."
13747 (let ((rtn (copy-sequence (pop plists)))
13748 p v ls)
13749 (while plists
13750 (setq ls (pop plists))
13751 (while ls
13752 (setq p (pop ls) v (pop ls))
13753 (setq rtn (plist-put rtn p v))))
13754 rtn))
13756 (defun org-move-line-down (arg)
13757 "Move the current line down. With prefix argument, move it past ARG lines."
13758 (interactive "p")
13759 (let ((col (current-column))
13760 beg end pos)
13761 (beginning-of-line 1) (setq beg (point))
13762 (beginning-of-line 2) (setq end (point))
13763 (beginning-of-line (+ 1 arg))
13764 (setq pos (move-marker (make-marker) (point)))
13765 (insert (delete-and-extract-region beg end))
13766 (goto-char pos)
13767 (org-move-to-column col)))
13769 (defun org-move-line-up (arg)
13770 "Move the current line up. With prefix argument, move it past ARG lines."
13771 (interactive "p")
13772 (let ((col (current-column))
13773 beg end pos)
13774 (beginning-of-line 1) (setq beg (point))
13775 (beginning-of-line 2) (setq end (point))
13776 (beginning-of-line (- arg))
13777 (setq pos (move-marker (make-marker) (point)))
13778 (insert (delete-and-extract-region beg end))
13779 (goto-char pos)
13780 (org-move-to-column col)))
13782 (defun org-replace-escapes (string table)
13783 "Replace %-escapes in STRING with values in TABLE.
13784 TABLE is an association list with keys like \"%a\" and string values.
13785 The sequences in STRING may contain normal field width and padding information,
13786 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13787 so values can contain further %-escapes if they are define later in TABLE."
13788 (let ((case-fold-search nil)
13789 e re rpl)
13790 (while (setq e (pop table))
13791 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13792 (while (string-match re string)
13793 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13794 (cdr e)))
13795 (setq string (replace-match rpl t t string))))
13796 string))
13799 (defun org-sublist (list start end)
13800 "Return a section of LIST, from START to END.
13801 Counting starts at 1."
13802 (let (rtn (c start))
13803 (setq list (nthcdr (1- start) list))
13804 (while (and list (<= c end))
13805 (push (pop list) rtn)
13806 (setq c (1+ c)))
13807 (nreverse rtn)))
13809 (defun org-find-base-buffer-visiting (file)
13810 "Like `find-buffer-visiting' but alway return the base buffer and
13811 not an indirect buffer."
13812 (let ((buf (find-buffer-visiting file)))
13813 (if buf
13814 (or (buffer-base-buffer buf) buf)
13815 nil)))
13817 (defun org-image-file-name-regexp ()
13818 "Return regexp matching the file names of images."
13819 (if (fboundp 'image-file-name-regexp)
13820 (image-file-name-regexp)
13821 (let ((image-file-name-extensions
13822 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13823 "xbm" "xpm" "pbm" "pgm" "ppm")))
13824 (concat "\\."
13825 (regexp-opt (nconc (mapcar 'upcase
13826 image-file-name-extensions)
13827 image-file-name-extensions)
13829 "\\'"))))
13831 (defun org-file-image-p (file)
13832 "Return non-nil if FILE is an image."
13833 (save-match-data
13834 (string-match (org-image-file-name-regexp) file)))
13836 ;;; Paragraph filling stuff.
13837 ;; We want this to be just right, so use the full arsenal.
13839 (defun org-indent-line-function ()
13840 "Indent line like previous, but further if previous was headline or item."
13841 (interactive)
13842 (let* ((pos (point))
13843 (itemp (org-at-item-p))
13844 column bpos bcol tpos tcol bullet btype bullet-type)
13845 ;; Find the previous relevant line
13846 (beginning-of-line 1)
13847 (cond
13848 ((looking-at "#") (setq column 0))
13849 ((looking-at "\\*+ ") (setq column 0))
13851 (beginning-of-line 0)
13852 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13853 (beginning-of-line 0))
13854 (cond
13855 ((looking-at "\\*+[ \t]+")
13856 (if (not org-adapt-indentation)
13857 (setq column 0)
13858 (goto-char (match-end 0))
13859 (setq column (current-column))))
13860 ((org-in-item-p)
13861 (org-beginning-of-item)
13862 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13863 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13864 (setq bpos (match-beginning 1) tpos (match-end 0)
13865 bcol (progn (goto-char bpos) (current-column))
13866 tcol (progn (goto-char tpos) (current-column))
13867 bullet (match-string 1)
13868 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13869 (if (> tcol (+ bcol org-description-max-indent))
13870 (setq tcol (+ bcol 5)))
13871 (if (not itemp)
13872 (setq column tcol)
13873 (goto-char pos)
13874 (beginning-of-line 1)
13875 (if (looking-at "\\S-")
13876 (progn
13877 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13878 (setq bullet (match-string 1)
13879 btype (if (string-match "[0-9]" bullet) "n" bullet))
13880 (setq column (if (equal btype bullet-type) bcol tcol)))
13881 (setq column (org-get-indentation)))))
13882 (t (setq column (org-get-indentation))))))
13883 (goto-char pos)
13884 (if (<= (current-column) (current-indentation))
13885 (org-indent-line-to column)
13886 (save-excursion (org-indent-line-to column)))
13887 (setq column (current-column))
13888 (beginning-of-line 1)
13889 (if (looking-at
13890 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13891 (replace-match (concat "\\1" (format org-property-format
13892 (match-string 2) (match-string 3)))
13893 t nil))
13894 (org-move-to-column column)))
13896 (defun org-set-autofill-regexps ()
13897 (interactive)
13898 ;; In the paragraph separator we include headlines, because filling
13899 ;; text in a line directly attached to a headline would otherwise
13900 ;; fill the headline as well.
13901 (org-set-local 'comment-start-skip "^#+[ \t]*")
13902 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13903 ;; The paragraph starter includes hand-formatted lists.
13904 (org-set-local 'paragraph-start
13905 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13906 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13907 ;; But only if the user has not turned off tables or fixed-width regions
13908 (org-set-local
13909 'auto-fill-inhibit-regexp
13910 (concat "\\*+ \\|#\\+"
13911 "\\|[ \t]*" org-keyword-time-regexp
13912 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13913 (concat
13914 "\\|[ \t]*["
13915 (if org-enable-table-editor "|" "")
13916 (if org-enable-fixed-width-editor ":" "")
13917 "]"))))
13918 ;; We use our own fill-paragraph function, to make sure that tables
13919 ;; and fixed-width regions are not wrapped. That function will pass
13920 ;; through to `fill-paragraph' when appropriate.
13921 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13922 ; Adaptive filling: To get full control, first make sure that
13923 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13924 (org-set-local 'adaptive-fill-regexp "\000")
13925 (org-set-local 'adaptive-fill-function
13926 'org-adaptive-fill-function)
13927 (org-set-local
13928 'align-mode-rules-list
13929 '((org-in-buffer-settings
13930 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13931 (modes . '(org-mode))))))
13933 (defun org-fill-paragraph (&optional justify)
13934 "Re-align a table, pass through to fill-paragraph if no table."
13935 (let ((table-p (org-at-table-p))
13936 (table.el-p (org-at-table.el-p)))
13937 (cond ((and (equal (char-after (point-at-bol)) ?*)
13938 (save-excursion (goto-char (point-at-bol))
13939 (looking-at outline-regexp)))
13940 t) ; skip headlines
13941 (table.el-p t) ; skip table.el tables
13942 (table-p (org-table-align) t) ; align org-mode tables
13943 (t nil)))) ; call paragraph-fill
13945 ;; For reference, this is the default value of adaptive-fill-regexp
13946 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13948 (defun org-adaptive-fill-function ()
13949 "Return a fill prefix for org-mode files.
13950 In particular, this makes sure hanging paragraphs for hand-formatted lists
13951 work correctly."
13952 (cond ((looking-at "#[ \t]+")
13953 (match-string 0))
13954 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13955 (save-excursion
13956 (if (> (match-end 1) (+ (match-beginning 1)
13957 org-description-max-indent))
13958 (goto-char (+ (match-beginning 1) 5))
13959 (goto-char (match-end 0)))
13960 (make-string (current-column) ?\ )))
13961 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13962 (save-excursion
13963 (goto-char (match-end 0))
13964 (make-string (current-column) ?\ )))
13965 (t nil)))
13967 ;;; Other stuff.
13969 (defun org-toggle-fixed-width-section (arg)
13970 "Toggle the fixed-width export.
13971 If there is no active region, the QUOTE keyword at the current headline is
13972 inserted or removed. When present, it causes the text between this headline
13973 and the next to be exported as fixed-width text, and unmodified.
13974 If there is an active region, this command adds or removes a colon as the
13975 first character of this line. If the first character of a line is a colon,
13976 this line is also exported in fixed-width font."
13977 (interactive "P")
13978 (let* ((cc 0)
13979 (regionp (org-region-active-p))
13980 (beg (if regionp (region-beginning) (point)))
13981 (end (if regionp (region-end)))
13982 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13983 (case-fold-search nil)
13984 (re "[ \t]*\\(:\\)")
13985 off)
13986 (if regionp
13987 (save-excursion
13988 (goto-char beg)
13989 (setq cc (current-column))
13990 (beginning-of-line 1)
13991 (setq off (looking-at re))
13992 (while (> nlines 0)
13993 (setq nlines (1- nlines))
13994 (beginning-of-line 1)
13995 (cond
13996 (arg
13997 (org-move-to-column cc t)
13998 (insert ":\n")
13999 (forward-line -1))
14000 ((and off (looking-at re))
14001 (replace-match "" t t nil 1))
14002 ((not off) (org-move-to-column cc t) (insert ":")))
14003 (forward-line 1)))
14004 (save-excursion
14005 (org-back-to-heading)
14006 (if (looking-at (concat outline-regexp
14007 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14008 (replace-match "" t t nil 1)
14009 (if (looking-at outline-regexp)
14010 (progn
14011 (goto-char (match-end 0))
14012 (insert org-quote-string " "))))))))
14014 ;;;; Functions extending outline functionality
14016 (defun org-beginning-of-line (&optional arg)
14017 "Go to the beginning of the current line. If that is invisible, continue
14018 to a visible line beginning. This makes the function of C-a more intuitive.
14019 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14020 first attempt, and only move to after the tags when the cursor is already
14021 beyond the end of the headline."
14022 (interactive "P")
14023 (let ((pos (point)) refpos)
14024 (beginning-of-line 1)
14025 (if (bobp)
14027 (backward-char 1)
14028 (if (org-invisible-p)
14029 (while (and (not (bobp)) (org-invisible-p))
14030 (backward-char 1)
14031 (beginning-of-line 1))
14032 (forward-char 1)))
14033 (when org-special-ctrl-a/e
14034 (cond
14035 ((and (looking-at org-complex-heading-regexp)
14036 (= (char-after (match-end 1)) ?\ ))
14037 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14038 (point-at-eol)))
14039 (goto-char
14040 (if (eq org-special-ctrl-a/e t)
14041 (cond ((> pos refpos) refpos)
14042 ((= pos (point)) refpos)
14043 (t (point)))
14044 (cond ((> pos (point)) (point))
14045 ((not (eq last-command this-command)) (point))
14046 (t refpos)))))
14047 ((org-at-item-p)
14048 (goto-char
14049 (if (eq org-special-ctrl-a/e t)
14050 (cond ((> pos (match-end 4)) (match-end 4))
14051 ((= pos (point)) (match-end 4))
14052 (t (point)))
14053 (cond ((> pos (point)) (point))
14054 ((not (eq last-command this-command)) (point))
14055 (t (match-end 4))))))))
14056 (org-no-warnings
14057 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14059 (defun org-end-of-line (&optional arg)
14060 "Go to the end of the line.
14061 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14062 first attempt, and only move to after the tags when the cursor is already
14063 beyond the end of the headline."
14064 (interactive "P")
14065 (if (or (not org-special-ctrl-a/e)
14066 (not (org-on-heading-p)))
14067 (end-of-line arg)
14068 (let ((pos (point)))
14069 (beginning-of-line 1)
14070 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14071 (if (eq org-special-ctrl-a/e t)
14072 (if (or (< pos (match-beginning 1))
14073 (= pos (match-end 0)))
14074 (goto-char (match-beginning 1))
14075 (goto-char (match-end 0)))
14076 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14077 (goto-char (match-end 0))
14078 (goto-char (match-beginning 1))))
14079 (end-of-line arg))))
14080 (org-no-warnings
14081 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14084 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14085 (define-key org-mode-map "\C-e" 'org-end-of-line)
14087 (defun org-kill-line (&optional arg)
14088 "Kill line, to tags or end of line."
14089 (interactive "P")
14090 (cond
14091 ((or (not org-special-ctrl-k)
14092 (bolp)
14093 (not (org-on-heading-p)))
14094 (call-interactively 'kill-line))
14095 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14096 (kill-region (point) (match-beginning 1))
14097 (org-set-tags nil t))
14098 (t (kill-region (point) (point-at-eol)))))
14100 (define-key org-mode-map "\C-k" 'org-kill-line)
14102 (defun org-invisible-p ()
14103 "Check if point is at a character currently not visible."
14104 ;; Early versions of noutline don't have `outline-invisible-p'.
14105 (if (fboundp 'outline-invisible-p)
14106 (outline-invisible-p)
14107 (get-char-property (point) 'invisible)))
14109 (defun org-invisible-p2 ()
14110 "Check if point is at a character currently not visible."
14111 (save-excursion
14112 (if (and (eolp) (not (bobp))) (backward-char 1))
14113 ;; Early versions of noutline don't have `outline-invisible-p'.
14114 (if (fboundp 'outline-invisible-p)
14115 (outline-invisible-p)
14116 (get-char-property (point) 'invisible))))
14118 (defalias 'org-back-to-heading 'outline-back-to-heading)
14119 (defalias 'org-on-heading-p 'outline-on-heading-p)
14120 (defalias 'org-at-heading-p 'outline-on-heading-p)
14121 (defun org-at-heading-or-item-p ()
14122 (or (org-on-heading-p) (org-at-item-p)))
14124 (defun org-on-target-p ()
14125 (or (org-in-regexp org-radio-target-regexp)
14126 (org-in-regexp org-target-regexp)))
14128 (defun org-up-heading-all (arg)
14129 "Move to the heading line of which the present line is a subheading.
14130 This function considers both visible and invisible heading lines.
14131 With argument, move up ARG levels."
14132 (if (fboundp 'outline-up-heading-all)
14133 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14134 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14136 (defun org-up-heading-safe ()
14137 "Move to the heading line of which the present line is a subheading.
14138 This version will not throw an error. It will return the level of the
14139 headline found, or nil if no higher level is found."
14140 (let ((pos (point)) start-level level
14141 (re (concat "^" outline-regexp)))
14142 (catch 'exit
14143 (outline-back-to-heading t)
14144 (setq start-level (funcall outline-level))
14145 (if (equal start-level 1) (throw 'exit nil))
14146 (while (re-search-backward re nil t)
14147 (setq level (funcall outline-level))
14148 (if (< level start-level) (throw 'exit level)))
14149 nil)))
14151 (defun org-first-sibling-p ()
14152 "Is this heading the first child of its parents?"
14153 (interactive)
14154 (let ((re (concat "^" outline-regexp))
14155 level l)
14156 (unless (org-at-heading-p t)
14157 (error "Not at a heading"))
14158 (setq level (funcall outline-level))
14159 (save-excursion
14160 (if (not (re-search-backward re nil t))
14162 (setq l (funcall outline-level))
14163 (< l level)))))
14165 (defun org-goto-sibling (&optional previous)
14166 "Goto the next sibling, even if it is invisible.
14167 When PREVIOUS is set, go to the previous sibling instead. Returns t
14168 when a sibling was found. When none is found, return nil and don't
14169 move point."
14170 (let ((fun (if previous 're-search-backward 're-search-forward))
14171 (pos (point))
14172 (re (concat "^" outline-regexp))
14173 level l)
14174 (when (condition-case nil (org-back-to-heading t) (error nil))
14175 (setq level (funcall outline-level))
14176 (catch 'exit
14177 (or previous (forward-char 1))
14178 (while (funcall fun re nil t)
14179 (setq l (funcall outline-level))
14180 (when (< l level) (goto-char pos) (throw 'exit nil))
14181 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14182 (goto-char pos)
14183 nil))))
14185 (defun org-show-siblings ()
14186 "Show all siblings of the current headline."
14187 (save-excursion
14188 (while (org-goto-sibling) (org-flag-heading nil)))
14189 (save-excursion
14190 (while (org-goto-sibling 'previous)
14191 (org-flag-heading nil))))
14193 (defun org-show-hidden-entry ()
14194 "Show an entry where even the heading is hidden."
14195 (save-excursion
14196 (org-show-entry)))
14198 (defun org-flag-heading (flag &optional entry)
14199 "Flag the current heading. FLAG non-nil means make invisible.
14200 When ENTRY is non-nil, show the entire entry."
14201 (save-excursion
14202 (org-back-to-heading t)
14203 ;; Check if we should show the entire entry
14204 (if entry
14205 (progn
14206 (org-show-entry)
14207 (save-excursion
14208 (and (outline-next-heading)
14209 (org-flag-heading nil))))
14210 (outline-flag-region (max (point-min) (1- (point)))
14211 (save-excursion (outline-end-of-heading) (point))
14212 flag))))
14214 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14215 ;; This is an exact copy of the original function, but it uses
14216 ;; `org-back-to-heading', to make it work also in invisible
14217 ;; trees. And is uses an invisible-OK argument.
14218 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14219 (org-back-to-heading invisible-OK)
14220 (let ((first t)
14221 (level (funcall outline-level)))
14222 (while (and (not (eobp))
14223 (or first (> (funcall outline-level) level)))
14224 (setq first nil)
14225 (outline-next-heading))
14226 (unless to-heading
14227 (if (memq (preceding-char) '(?\n ?\^M))
14228 (progn
14229 ;; Go to end of line before heading
14230 (forward-char -1)
14231 (if (memq (preceding-char) '(?\n ?\^M))
14232 ;; leave blank line before heading
14233 (forward-char -1))))))
14234 (point))
14236 (defun org-show-subtree ()
14237 "Show everything after this heading at deeper levels."
14238 (outline-flag-region
14239 (point)
14240 (save-excursion
14241 (outline-end-of-subtree) (outline-next-heading) (point))
14242 nil))
14244 (defun org-show-entry ()
14245 "Show the body directly following this heading.
14246 Show the heading too, if it is currently invisible."
14247 (interactive)
14248 (save-excursion
14249 (condition-case nil
14250 (progn
14251 (org-back-to-heading t)
14252 (outline-flag-region
14253 (max (point-min) (1- (point)))
14254 (save-excursion
14255 (re-search-forward
14256 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14257 (or (match-beginning 1) (point-max)))
14258 nil))
14259 (error nil))))
14261 (defun org-make-options-regexp (kwds)
14262 "Make a regular expression for keyword lines."
14263 (concat
14265 "#?[ \t]*\\+\\("
14266 (mapconcat 'regexp-quote kwds "\\|")
14267 "\\):[ \t]*"
14268 "\\(.+\\)"))
14270 ;; Make isearch reveal the necessary context
14271 (defun org-isearch-end ()
14272 "Reveal context after isearch exits."
14273 (when isearch-success ; only if search was successful
14274 (if (featurep 'xemacs)
14275 ;; Under XEmacs, the hook is run in the correct place,
14276 ;; we directly show the context.
14277 (org-show-context 'isearch)
14278 ;; In Emacs the hook runs *before* restoring the overlays.
14279 ;; So we have to use a one-time post-command-hook to do this.
14280 ;; (Emacs 22 has a special variable, see function `org-mode')
14281 (unless (and (boundp 'isearch-mode-end-hook-quit)
14282 isearch-mode-end-hook-quit)
14283 ;; Only when the isearch was not quitted.
14284 (org-add-hook 'post-command-hook 'org-isearch-post-command
14285 'append 'local)))))
14287 (defun org-isearch-post-command ()
14288 "Remove self from hook, and show context."
14289 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14290 (org-show-context 'isearch))
14293 ;;;; Integration with and fixes for other packages
14295 ;;; Imenu support
14297 (defvar org-imenu-markers nil
14298 "All markers currently used by Imenu.")
14299 (make-variable-buffer-local 'org-imenu-markers)
14301 (defun org-imenu-new-marker (&optional pos)
14302 "Return a new marker for use by Imenu, and remember the marker."
14303 (let ((m (make-marker)))
14304 (move-marker m (or pos (point)))
14305 (push m org-imenu-markers)
14308 (defun org-imenu-get-tree ()
14309 "Produce the index for Imenu."
14310 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14311 (setq org-imenu-markers nil)
14312 (let* ((n org-imenu-depth)
14313 (re (concat "^" outline-regexp))
14314 (subs (make-vector (1+ n) nil))
14315 (last-level 0)
14316 m tree level head)
14317 (save-excursion
14318 (save-restriction
14319 (widen)
14320 (goto-char (point-max))
14321 (while (re-search-backward re nil t)
14322 (setq level (org-reduced-level (funcall outline-level)))
14323 (when (<= level n)
14324 (looking-at org-complex-heading-regexp)
14325 (setq head (org-match-string-no-properties 4)
14326 m (org-imenu-new-marker))
14327 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14328 (if (>= level last-level)
14329 (push (cons head m) (aref subs level))
14330 (push (cons head (aref subs (1+ level))) (aref subs level))
14331 (loop for i from (1+ level) to n do (aset subs i nil)))
14332 (setq last-level level)))))
14333 (aref subs 1)))
14335 (eval-after-load "imenu"
14336 '(progn
14337 (add-hook 'imenu-after-jump-hook
14338 (lambda () (org-show-context 'org-goto)))))
14340 ;; Speedbar support
14342 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14343 "Overlay marking the agenda restriction line in speedbar.")
14344 (org-overlay-put org-speedbar-restriction-lock-overlay
14345 'face 'org-agenda-restriction-lock)
14346 (org-overlay-put org-speedbar-restriction-lock-overlay
14347 'help-echo "Agendas are currently limited to this item.")
14348 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14350 (defun org-speedbar-set-agenda-restriction ()
14351 "Restrict future agenda commands to the location at point in speedbar.
14352 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14353 (interactive)
14354 (require 'org-agenda)
14355 (let (p m tp np dir txt w)
14356 (cond
14357 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14358 'org-imenu t))
14359 (setq m (get-text-property p 'org-imenu-marker))
14360 (save-excursion
14361 (save-restriction
14362 (set-buffer (marker-buffer m))
14363 (goto-char m)
14364 (org-agenda-set-restriction-lock 'subtree))))
14365 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14366 'speedbar-function 'speedbar-find-file))
14367 (setq tp (previous-single-property-change
14368 (1+ p) 'speedbar-function)
14369 np (next-single-property-change
14370 tp 'speedbar-function)
14371 dir (speedbar-line-directory)
14372 txt (buffer-substring-no-properties (or tp (point-min))
14373 (or np (point-max))))
14374 (save-excursion
14375 (save-restriction
14376 (set-buffer (find-file-noselect
14377 (let ((default-directory dir))
14378 (expand-file-name txt))))
14379 (unless (org-mode-p)
14380 (error "Cannot restrict to non-Org-mode file"))
14381 (org-agenda-set-restriction-lock 'file))))
14382 (t (error "Don't know how to restrict Org-mode's agenda")))
14383 (org-move-overlay org-speedbar-restriction-lock-overlay
14384 (point-at-bol) (point-at-eol))
14385 (setq current-prefix-arg nil)
14386 (org-agenda-maybe-redo)))
14388 (eval-after-load "speedbar"
14389 '(progn
14390 (speedbar-add-supported-extension ".org")
14391 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14392 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14393 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14394 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14395 (add-hook 'speedbar-visiting-tag-hook
14396 (lambda () (org-show-context 'org-goto)))))
14399 ;;; Fixes and Hacks for problems with other packages
14401 ;; Make flyspell not check words in links, to not mess up our keymap
14402 (defun org-mode-flyspell-verify ()
14403 "Don't let flyspell put overlays at active buttons."
14404 (not (get-text-property (point) 'keymap)))
14406 ;; Make `bookmark-jump' show the jump location if it was hidden.
14407 (eval-after-load "bookmark"
14408 '(if (boundp 'bookmark-after-jump-hook)
14409 ;; We can use the hook
14410 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14411 ;; Hook not available, use advice
14412 (defadvice bookmark-jump (after org-make-visible activate)
14413 "Make the position visible."
14414 (org-bookmark-jump-unhide))))
14416 (defun org-bookmark-jump-unhide ()
14417 "Unhide the current position, to show the bookmark location."
14418 (and (org-mode-p)
14419 (or (org-invisible-p)
14420 (save-excursion (goto-char (max (point-min) (1- (point))))
14421 (org-invisible-p)))
14422 (org-show-context 'bookmark-jump)))
14424 ;; Make session.el ignore our circular variable
14425 (eval-after-load "session"
14426 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14428 ;;;; Experimental code
14430 (defun org-closed-in-range ()
14431 "Sparse tree of items closed in a certain time range.
14432 Still experimental, may disappear in the future."
14433 (interactive)
14434 ;; Get the time interval from the user.
14435 (let* ((time1 (time-to-seconds
14436 (org-read-date nil 'to-time nil "Starting date: ")))
14437 (time2 (time-to-seconds
14438 (org-read-date nil 'to-time nil "End date:")))
14439 ;; callback function
14440 (callback (lambda ()
14441 (let ((time
14442 (time-to-seconds
14443 (apply 'encode-time
14444 (org-parse-time-string
14445 (match-string 1))))))
14446 ;; check if time in interval
14447 (and (>= time time1) (<= time time2))))))
14448 ;; make tree, check each match with the callback
14449 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14452 ;;;; Finish up
14454 (provide 'org)
14456 (run-hooks 'org-load-hook)
14458 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14460 ;;; org.el ends here