Fix bugs with ellipsis generation in column view.
[org-mode.git] / lisp / org.el
blob878482d26d269a424bfcc80ad050824a5ce2d858
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.")
1925 (defgroup org-agenda nil
1926 "Options concerning agenda views in Org-mode."
1927 :tag "Org Agenda"
1928 :group 'org)
1930 (defvar org-category nil
1931 "Variable used by org files to set a category for agenda display.
1932 Such files should use a file variable to set it, for example
1934 # -*- mode: org; org-category: \"ELisp\"
1936 or contain a special line
1938 #+CATEGORY: ELisp
1940 If the file does not specify a category, then file's base name
1941 is used instead.")
1942 (make-variable-buffer-local 'org-category)
1944 (defcustom org-agenda-files nil
1945 "The files to be used for agenda display.
1946 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1947 \\[org-remove-file]. You can also use customize to edit the list.
1949 If an entry is a directory, all files in that directory that are matched by
1950 `org-agenda-file-regexp' will be part of the file list.
1952 If the value of the variable is not a list but a single file name, then
1953 the list of agenda files is actually stored and maintained in that file, one
1954 agenda file per line."
1955 :group 'org-agenda
1956 :type '(choice
1957 (repeat :tag "List of files and directories" file)
1958 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1960 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1961 "Regular expression to match files for `org-agenda-files'.
1962 If any element in the list in that variable contains a directory instead
1963 of a normal file, all files in that directory that are matched by this
1964 regular expression will be included."
1965 :group 'org-agenda
1966 :type 'regexp)
1968 (defcustom org-agenda-text-search-extra-files nil
1969 "List of extra files to be searched by text search commands.
1970 These files will be search in addition to the agenda files by the
1971 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1972 Note that these files will only be searched for text search commands,
1973 not for the other agenda views like todo lists, tag searches or the weekly
1974 agenda. This variable is intended to list notes and possibly archive files
1975 that should also be searched by these two commands.
1976 In fact, if the first element in the list is the symbol `agenda-archives',
1977 than all archive files of all agenda files will be added to the search
1978 scope."
1979 :group 'org-agenda
1980 :type '(set :greedy t
1981 (const :tag "Agenda Archives" agenda-archives)
1982 (repeat :inline t (file))))
1984 (if (fboundp 'defvaralias)
1985 (defvaralias 'org-agenda-multi-occur-extra-files
1986 'org-agenda-text-search-extra-files))
1988 (defcustom org-agenda-skip-unavailable-files nil
1989 "t means to just skip non-reachable files in `org-agenda-files'.
1990 Nil means to remove them, after a query, from the list."
1991 :group 'org-agenda
1992 :type 'boolean)
1994 (defcustom org-calendar-to-agenda-key [?c]
1995 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1996 The command `org-calendar-goto-agenda' will be bound to this key. The
1997 default is the character `c' because then `c' can be used to switch back and
1998 forth between agenda and calendar."
1999 :group 'org-agenda
2000 :type 'sexp)
2002 (eval-after-load "calendar"
2003 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
2004 'org-calendar-goto-agenda))
2006 (defgroup org-latex nil
2007 "Options for embedding LaTeX code into Org-mode."
2008 :tag "Org LaTeX"
2009 :group 'org)
2011 (defcustom org-format-latex-options
2012 '(:foreground default :background default :scale 1.0
2013 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2014 :matchers ("begin" "$" "$$" "\\(" "\\["))
2015 "Options for creating images from LaTeX fragments.
2016 This is a property list with the following properties:
2017 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2018 `default' means use the foreground of the default face.
2019 :background the background color, or \"Transparent\".
2020 `default' means use the background of the default face.
2021 :scale a scaling factor for the size of the images.
2022 :html-foreground, :html-background, :html-scale
2023 the same numbers for HTML export.
2024 :matchers a list indicating which matchers should be used to
2025 find LaTeX fragments. Valid members of this list are:
2026 \"begin\" find environments
2027 \"$\" find math expressions surrounded by $...$
2028 \"$$\" find math expressions surrounded by $$....$$
2029 \"\\(\" find math expressions surrounded by \\(...\\)
2030 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2031 :group 'org-latex
2032 :type 'plist)
2034 (defcustom org-format-latex-header "\\documentclass{article}
2035 \\usepackage{fullpage} % do not remove
2036 \\usepackage{amssymb}
2037 \\usepackage[usenames]{color}
2038 \\usepackage{amsmath}
2039 \\usepackage{latexsym}
2040 \\usepackage[mathscr]{eucal}
2041 \\pagestyle{empty} % do not remove"
2042 "The document header used for processing LaTeX fragments."
2043 :group 'org-latex
2044 :type 'string)
2047 (defgroup org-font-lock nil
2048 "Font-lock settings for highlighting in Org-mode."
2049 :tag "Org Font Lock"
2050 :group 'org)
2052 (defcustom org-level-color-stars-only nil
2053 "Non-nil means fontify only the stars in each headline.
2054 When nil, the entire headline is fontified.
2055 Changing it requires restart of `font-lock-mode' to become effective
2056 also in regions already fontified."
2057 :group 'org-font-lock
2058 :type 'boolean)
2060 (defcustom org-hide-leading-stars nil
2061 "Non-nil means, hide the first N-1 stars in a headline.
2062 This works by using the face `org-hide' for these stars. This
2063 face is white for a light background, and black for a dark
2064 background. You may have to customize the face `org-hide' to
2065 make this work.
2066 Changing it requires restart of `font-lock-mode' to become effective
2067 also in regions already fontified.
2068 You may also set this on a per-file basis by adding one of the following
2069 lines to the buffer:
2071 #+STARTUP: hidestars
2072 #+STARTUP: showstars"
2073 :group 'org-font-lock
2074 :type 'boolean)
2076 (defcustom org-fontify-done-headline nil
2077 "Non-nil means, change the face of a headline if it is marked DONE.
2078 Normally, only the TODO/DONE keyword indicates the state of a headline.
2079 When this is non-nil, the headline after the keyword is set to the
2080 `org-headline-done' as an additional indication."
2081 :group 'org-font-lock
2082 :type 'boolean)
2084 (defcustom org-fontify-emphasized-text t
2085 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2086 Changing this variable requires a restart of Emacs to take effect."
2087 :group 'org-font-lock
2088 :type 'boolean)
2090 (defcustom org-highlight-latex-fragments-and-specials nil
2091 "Non-nil means, fontify what is treated specially by the exporters."
2092 :group 'org-font-lock
2093 :type 'boolean)
2095 (defcustom org-hide-emphasis-markers nil
2096 "Non-nil mean font-lock should hide the emphasis marker characters."
2097 :group 'org-font-lock
2098 :type 'boolean)
2100 (defvar org-emph-re nil
2101 "Regular expression for matching emphasis.")
2102 (defvar org-verbatim-re nil
2103 "Regular expression for matching verbatim text.")
2104 (defvar org-emphasis-regexp-components) ; defined just below
2105 (defvar org-emphasis-alist) ; defined just below
2106 (defun org-set-emph-re (var val)
2107 "Set variable and compute the emphasis regular expression."
2108 (set var val)
2109 (when (and (boundp 'org-emphasis-alist)
2110 (boundp 'org-emphasis-regexp-components)
2111 org-emphasis-alist org-emphasis-regexp-components)
2112 (let* ((e org-emphasis-regexp-components)
2113 (pre (car e))
2114 (post (nth 1 e))
2115 (border (nth 2 e))
2116 (body (nth 3 e))
2117 (nl (nth 4 e))
2118 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2119 (body1 (concat body "*?"))
2120 (markers (mapconcat 'car org-emphasis-alist ""))
2121 (vmarkers (mapconcat
2122 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2123 org-emphasis-alist "")))
2124 ;; make sure special characters appear at the right position in the class
2125 (if (string-match "\\^" markers)
2126 (setq markers (concat (replace-match "" t t markers) "^")))
2127 (if (string-match "-" markers)
2128 (setq markers (concat (replace-match "" t t markers) "-")))
2129 (if (string-match "\\^" vmarkers)
2130 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2131 (if (string-match "-" vmarkers)
2132 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2133 (if (> nl 0)
2134 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2135 (int-to-string nl) "\\}")))
2136 ;; Make the regexp
2137 (setq org-emph-re
2138 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2139 "\\("
2140 "\\([" markers "]\\)"
2141 "\\("
2142 "[^" border "]\\|"
2143 "[^" border (if (and nil stacked) markers) "]"
2144 body1
2145 "[^" border (if (and nil stacked) markers) "]"
2146 "\\)"
2147 "\\3\\)"
2148 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2149 (setq org-verbatim-re
2150 (concat "\\([" pre "]\\|^\\)"
2151 "\\("
2152 "\\([" vmarkers "]\\)"
2153 "\\("
2154 "[^" border "]\\|"
2155 "[^" border "]"
2156 body1
2157 "[^" border "]"
2158 "\\)"
2159 "\\3\\)"
2160 "\\([" post "]\\|$\\)")))))
2162 (defcustom org-emphasis-regexp-components
2163 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2164 "Components used to build the regular expression for emphasis.
2165 This is a list with 6 entries. Terminology: In an emphasis string
2166 like \" *strong word* \", we call the initial space PREMATCH, the final
2167 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2168 and \"trong wor\" is the body. The different components in this variable
2169 specify what is allowed/forbidden in each part:
2171 pre Chars allowed as prematch. Beginning of line will be allowed too.
2172 post Chars allowed as postmatch. End of line will be allowed too.
2173 border The chars *forbidden* as border characters.
2174 body-regexp A regexp like \".\" to match a body character. Don't use
2175 non-shy groups here, and don't allow newline here.
2176 newline The maximum number of newlines allowed in an emphasis exp.
2178 Use customize to modify this, or restart Emacs after changing it."
2179 :group 'org-font-lock
2180 :set 'org-set-emph-re
2181 :type '(list
2182 (sexp :tag "Allowed chars in pre ")
2183 (sexp :tag "Allowed chars in post ")
2184 (sexp :tag "Forbidden chars in border ")
2185 (sexp :tag "Regexp for body ")
2186 (integer :tag "number of newlines allowed")
2187 (option (boolean :tag "Stacking (DISABLED) "))))
2189 (defcustom org-emphasis-alist
2190 `(("*" bold "<b>" "</b>")
2191 ("/" italic "<i>" "</i>")
2192 ("_" underline "<u>" "</u>")
2193 ("=" org-code "<code>" "</code>" verbatim)
2194 ("~" org-verbatim "" "" verbatim)
2195 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2196 "<del>" "</del>")
2198 "Special syntax for emphasized text.
2199 Text starting and ending with a special character will be emphasized, for
2200 example *bold*, _underlined_ and /italic/. This variable sets the marker
2201 characters, the face to be used by font-lock for highlighting in Org-mode
2202 Emacs buffers, and the HTML tags to be used for this.
2203 Use customize to modify this, or restart Emacs after changing it."
2204 :group 'org-font-lock
2205 :set 'org-set-emph-re
2206 :type '(repeat
2207 (list
2208 (string :tag "Marker character")
2209 (choice
2210 (face :tag "Font-lock-face")
2211 (plist :tag "Face property list"))
2212 (string :tag "HTML start tag")
2213 (string :tag "HTML end tag")
2214 (option (const verbatim)))))
2216 ;;; Miscellaneous options
2218 (defgroup org-completion nil
2219 "Completion in Org-mode."
2220 :tag "Org Completion"
2221 :group 'org)
2223 (defcustom org-completion-fallback-command 'hippie-expand
2224 "The expansion command called by \\[org-complete] in normal context.
2225 Normal means, no org-mode-specific context."
2226 :group 'org-completion
2227 :type 'function)
2229 ;;; Functions and variables from ther packages
2230 ;; Declared here to avoid compiler warnings
2232 ;; XEmacs only
2233 (defvar outline-mode-menu-heading)
2234 (defvar outline-mode-menu-show)
2235 (defvar outline-mode-menu-hide)
2236 (defvar zmacs-regions) ; XEmacs regions
2238 ;; Emacs only
2239 (defvar mark-active)
2241 ;; Various packages
2242 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2243 (declare-function calendar-forward-day "cal-move" (arg))
2244 (declare-function calendar-goto-date "cal-move" (date))
2245 (declare-function calendar-goto-today "cal-move" ())
2246 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2247 (defvar calc-embedded-close-formula)
2248 (defvar calc-embedded-open-formula)
2249 (declare-function cdlatex-tab "ext:cdlatex" ())
2250 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2251 (defvar font-lock-unfontify-region-function)
2252 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2253 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2254 (defvar iswitchb-temp-buflist)
2255 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2256 (declare-function org-agenda-skip "org-agenda" ())
2257 (declare-function org-format-agenda-item "org-agenda"
2258 (extra txt &optional category tags dotime noprefix remove-re))
2259 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2260 (declare-function org-agenda-change-all-lines "org-agenda"
2261 (newhead hdmarker &optional fixface))
2262 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2263 (declare-function org-agenda-maybe-redo "org-agenda" ())
2264 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2265 (beg end))
2266 (declare-function parse-time-string "parse-time" (string))
2267 (declare-function remember "remember" (&optional initial))
2268 (declare-function remember-buffer-desc "remember" ())
2269 (declare-function remember-finalize "remember" ())
2270 (defvar remember-save-after-remembering)
2271 (defvar remember-data-file)
2272 (defvar remember-register)
2273 (defvar remember-buffer)
2274 (defvar remember-handler-functions)
2275 (defvar remember-annotation-functions)
2276 (defvar texmathp-why)
2277 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2278 (declare-function table--at-cell-p "table" (position &optional object at-column))
2280 (defvar w3m-current-url)
2281 (defvar w3m-current-title)
2283 (defvar org-latex-regexps)
2285 ;;; Autoload and prepare some org modules
2287 ;; Some table stuff that needs to be defined here, because it is used
2288 ;; by the functions setting up org-mode or checking for table context.
2290 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2291 "Detects an org-type or table-type table.")
2292 (defconst org-table-line-regexp "^[ \t]*|"
2293 "Detects an org-type table line.")
2294 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2295 "Detects an org-type table line.")
2296 (defconst org-table-hline-regexp "^[ \t]*|-"
2297 "Detects an org-type table hline.")
2298 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2299 "Detects a table-type table hline.")
2300 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2301 "Searching from within a table (any type) this finds the first line
2302 outside the table.")
2304 ;; Autoload the functions in org-table.el that are needed by functions here.
2306 (eval-and-compile
2307 (org-autoload "org-table"
2308 '(org-table-align org-table-begin org-table-blank-field
2309 org-table-convert org-table-convert-region org-table-copy-down
2310 org-table-copy-region org-table-create
2311 org-table-create-or-convert-from-region
2312 org-table-create-with-table.el org-table-current-dline
2313 org-table-cut-region org-table-delete-column org-table-edit-field
2314 org-table-edit-formulas org-table-end org-table-eval-formula
2315 org-table-export org-table-field-info
2316 org-table-get-stored-formulas org-table-goto-column
2317 org-table-hline-and-move org-table-import org-table-insert-column
2318 org-table-insert-hline org-table-insert-row org-table-iterate
2319 org-table-justify-field-maybe org-table-kill-row
2320 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2321 org-table-move-column org-table-move-column-left
2322 org-table-move-column-right org-table-move-row
2323 org-table-move-row-down org-table-move-row-up
2324 org-table-next-field org-table-next-row org-table-paste-rectangle
2325 org-table-previous-field org-table-recalculate
2326 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2327 org-table-toggle-coordinate-overlays
2328 org-table-toggle-formula-debugger org-table-wrap-region
2329 orgtbl-mode turn-on-orgtbl)))
2331 (defun org-at-table-p (&optional table-type)
2332 "Return t if the cursor is inside an org-type table.
2333 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2334 (if org-enable-table-editor
2335 (save-excursion
2336 (beginning-of-line 1)
2337 (looking-at (if table-type org-table-any-line-regexp
2338 org-table-line-regexp)))
2339 nil))
2340 (defsubst org-table-p () (org-at-table-p))
2342 (defun org-at-table.el-p ()
2343 "Return t if and only if we are at a table.el table."
2344 (and (org-at-table-p 'any)
2345 (save-excursion
2346 (goto-char (org-table-begin 'any))
2347 (looking-at org-table1-hline-regexp))))
2348 (defun org-table-recognize-table.el ()
2349 "If there is a table.el table nearby, recognize it and move into it."
2350 (if org-table-tab-recognizes-table.el
2351 (if (org-at-table.el-p)
2352 (progn
2353 (beginning-of-line 1)
2354 (if (looking-at org-table-dataline-regexp)
2356 (if (looking-at org-table1-hline-regexp)
2357 (progn
2358 (beginning-of-line 2)
2359 (if (looking-at org-table-any-border-regexp)
2360 (beginning-of-line -1)))))
2361 (if (re-search-forward "|" (org-table-end t) t)
2362 (progn
2363 (require 'table)
2364 (if (table--at-cell-p (point))
2366 (message "recognizing table.el table...")
2367 (table-recognize-table)
2368 (message "recognizing table.el table...done")))
2369 (error "This should not happen..."))
2371 nil)
2372 nil))
2374 (defun org-at-table-hline-p ()
2375 "Return t if the cursor is inside a hline in a table."
2376 (if org-enable-table-editor
2377 (save-excursion
2378 (beginning-of-line 1)
2379 (looking-at org-table-hline-regexp))
2380 nil))
2382 (defvar org-table-clean-did-remove-column nil)
2384 (defun org-table-map-tables (function)
2385 "Apply FUNCTION to the start of all tables in the buffer."
2386 (save-excursion
2387 (save-restriction
2388 (widen)
2389 (goto-char (point-min))
2390 (while (re-search-forward org-table-any-line-regexp nil t)
2391 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2392 (beginning-of-line 1)
2393 (if (looking-at org-table-line-regexp)
2394 (save-excursion (funcall function)))
2395 (re-search-forward org-table-any-border-regexp nil 1))))
2396 (message "Mapping tables: done"))
2398 ;; Declare and autoload functions from org-exp.el
2400 (declare-function org-default-export-plist "org-exp")
2401 (declare-function org-infile-export-plist "org-exp")
2402 (declare-function org-get-current-options "org-exp")
2403 (eval-and-compile
2404 (org-autoload "org-exp"
2405 '(org-export org-export-as-ascii org-export-visible
2406 org-insert-export-options-template org-export-as-html-and-open
2407 org-export-as-html-batch org-export-as-html-to-buffer
2408 org-replace-region-by-html org-export-region-as-html
2409 org-export-as-html org-export-icalendar-this-file
2410 org-export-icalendar-all-agenda-files
2411 org-table-clean-before-export
2412 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2414 ;; Declare and autoload functions from org-exp.el
2416 (eval-and-compile
2417 (org-autoload "org-exp"
2418 '(org-agenda org-agenda-list org-search-view
2419 org-todo-list org-tags-view org-agenda-list-stuck-projects
2420 org-diary org-agenda-to-appt)))
2422 ;; Autoload org-remember
2424 (eval-and-compile
2425 (org-autoload "org-remember"
2426 '(org-remember-insinuate org-remember-annotation
2427 org-remember-apply-template org-remember org-remember-handler)))
2429 ;; Autoload org-clock.el
2432 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2433 (beg end))
2434 (declare-function org-update-mode-line "org-clock" ())
2435 (defvar org-clock-start-time)
2436 (defvar org-clock-marker (make-marker)
2437 "Marker recording the last clock-in.")
2439 (eval-and-compile
2440 (org-autoload
2441 "org-clock"
2442 '(org-clock-in org-clock-out org-clock-cancel
2443 org-clock-goto org-clock-sum org-clock-display
2444 org-remove-clock-overlays org-clock-report
2445 org-clocktable-shift org-dblock-write:clocktable
2446 org-get-clocktable)))
2448 (defun org-clock-update-time-maybe ()
2449 "If this is a CLOCK line, update it and return t.
2450 Otherwise, return nil."
2451 (interactive)
2452 (save-excursion
2453 (beginning-of-line 1)
2454 (skip-chars-forward " \t")
2455 (when (looking-at org-clock-string)
2456 (let ((re (concat "[ \t]*" org-clock-string
2457 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2458 "\\([ \t]*=>.*\\)?\\)?"))
2459 ts te h m s)
2460 (cond
2461 ((not (looking-at re))
2462 nil)
2463 ((not (match-end 2))
2464 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2465 (> org-clock-marker (point))
2466 (<= org-clock-marker (point-at-eol)))
2467 ;; The clock is running here
2468 (setq org-clock-start-time
2469 (apply 'encode-time
2470 (org-parse-time-string (match-string 1))))
2471 (org-update-mode-line)))
2473 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2474 (end-of-line 1)
2475 (setq ts (match-string 1)
2476 te (match-string 3))
2477 (setq s (- (time-to-seconds
2478 (apply 'encode-time (org-parse-time-string te)))
2479 (time-to-seconds
2480 (apply 'encode-time (org-parse-time-string ts))))
2481 h (floor (/ s 3600))
2482 s (- s (* 3600 h))
2483 m (floor (/ s 60))
2484 s (- s (* 60 s)))
2485 (insert " => " (format "%2d:%02d" h m))
2486 t))))))
2488 (defun org-check-running-clock ()
2489 "Check if the current buffer contains the running clock.
2490 If yes, offer to stop it and to save the buffer with the changes."
2491 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2492 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2493 (buffer-name))))
2494 (org-clock-out)
2495 (when (y-or-n-p "Save changed buffer?")
2496 (save-buffer))))
2498 (defun org-clocktable-try-shift (dir n)
2499 "Check if this line starts a clock table, if yes, shift the time block."
2500 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2501 (org-clocktable-shift dir n)))
2503 ;; Autoload archiving code
2504 ;; The stuff that is needed for cycling and tags has to be defined here.
2506 (defgroup org-archive nil
2507 "Options concerning archiving in Org-mode."
2508 :tag "Org Archive"
2509 :group 'org-structure)
2511 (defcustom org-archive-location "%s_archive::"
2512 "The location where subtrees should be archived.
2514 Otherwise, the value of this variable is a string, consisting of two
2515 parts, separated by a double-colon.
2517 The first part is a file name - when omitted, archiving happens in the same
2518 file. %s will be replaced by the current file name (without directory part).
2519 Archiving to a different file is useful to keep archived entries from
2520 contributing to the Org-mode Agenda.
2522 The part after the double colon is a headline. The archived entries will be
2523 filed under that headline. When omitted, the subtrees are simply filed away
2524 at the end of the file, as top-level entries.
2526 Here are a few examples:
2527 \"%s_archive::\"
2528 If the current file is Projects.org, archive in file
2529 Projects.org_archive, as top-level trees. This is the default.
2531 \"::* Archived Tasks\"
2532 Archive in the current file, under the top-level headline
2533 \"* Archived Tasks\".
2535 \"~/org/archive.org::\"
2536 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2538 \"basement::** Finished Tasks\"
2539 Archive in file ./basement (relative path), as level 3 trees
2540 below the level 2 heading \"** Finished Tasks\".
2542 You may set this option on a per-file basis by adding to the buffer a
2543 line like
2545 #+ARCHIVE: basement::** Finished Tasks
2547 You may also define it locally for a subtree by setting an ARCHIVE property
2548 in the entry. If such a property is found in an entry, or anywhere up
2549 the hierarchy, it will be used."
2550 :group 'org-archive
2551 :type 'string)
2553 (defcustom org-archive-tag "ARCHIVE"
2554 "The tag that marks a subtree as archived.
2555 An archived subtree does not open during visibility cycling, and does
2556 not contribute to the agenda listings.
2557 After changing this, font-lock must be restarted in the relevant buffers to
2558 get the proper fontification."
2559 :group 'org-archive
2560 :group 'org-keywords
2561 :type 'string)
2563 (defcustom org-agenda-skip-archived-trees t
2564 "Non-nil means, the agenda will skip any items located in archived trees.
2565 An archived tree is a tree marked with the tag ARCHIVE."
2566 :group 'org-archive
2567 :group 'org-agenda-skip
2568 :type 'boolean)
2570 (defcustom org-cycle-open-archived-trees nil
2571 "Non-nil means, `org-cycle' will open archived trees.
2572 An archived tree is a tree marked with the tag ARCHIVE.
2573 When nil, archived trees will stay folded. You can still open them with
2574 normal outline commands like `show-all', but not with the cycling commands."
2575 :group 'org-archive
2576 :group 'org-cycle
2577 :type 'boolean)
2579 (defcustom org-sparse-tree-open-archived-trees nil
2580 "Non-nil means sparse tree construction shows matches in archived trees.
2581 When nil, matches in these trees are highlighted, but the trees are kept in
2582 collapsed state."
2583 :group 'org-archive
2584 :group 'org-sparse-trees
2585 :type 'boolean)
2587 (defun org-cycle-hide-archived-subtrees (state)
2588 "Re-hide all archived subtrees after a visibility state change."
2589 (when (and (not org-cycle-open-archived-trees)
2590 (not (memq state '(overview folded))))
2591 (save-excursion
2592 (let* ((globalp (memq state '(contents all)))
2593 (beg (if globalp (point-min) (point)))
2594 (end (if globalp (point-max) (org-end-of-subtree t))))
2595 (org-hide-archived-subtrees beg end)
2596 (goto-char beg)
2597 (if (looking-at (concat ".*:" org-archive-tag ":"))
2598 (message "%s" (substitute-command-keys
2599 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2601 (defun org-force-cycle-archived ()
2602 "Cycle subtree even if it is archived."
2603 (interactive)
2604 (setq this-command 'org-cycle)
2605 (let ((org-cycle-open-archived-trees t))
2606 (call-interactively 'org-cycle)))
2608 (defun org-hide-archived-subtrees (beg end)
2609 "Re-hide all archived subtrees after a visibility state change."
2610 (save-excursion
2611 (let* ((re (concat ":" org-archive-tag ":")))
2612 (goto-char beg)
2613 (while (re-search-forward re end t)
2614 (and (org-on-heading-p) (hide-subtree))
2615 (org-end-of-subtree t)))))
2617 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2619 (eval-and-compile
2620 (org-autoload "org-archive"
2621 '(org-add-archive-files org-archive-subtree
2622 org-archive-to-archive-sibling org-toggle-archive-tag)))
2624 ;; Autoload Column View Code
2626 (declare-function org-columns-number-to-string "org-colview")
2627 (declare-function org-columns-get-format-and-top-level "org-colview")
2628 (declare-function org-columns-compute "org-colview")
2630 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2631 '(org-columns-number-to-string org-columns-get-format-and-top-level
2632 org-columns-compute org-agenda-columns org-columns-remove-overlays
2633 org-columns org-insert-columns-dblock))
2635 ;; Autoload ID code
2637 (org-autoload "org-id"
2638 '(org-id-get-create org-id-new org-id-copy org-id-get
2639 org-id-get-with-outline-path-completion
2640 org-id-get-with-outline-drilling
2641 org-id-goto org-id-find))
2643 ;;; Variables for pre-computed regular expressions, all buffer local
2645 (defvar org-drawer-regexp nil
2646 "Matches first line of a hidden block.")
2647 (make-variable-buffer-local 'org-drawer-regexp)
2648 (defvar org-todo-regexp nil
2649 "Matches any of the TODO state keywords.")
2650 (make-variable-buffer-local 'org-todo-regexp)
2651 (defvar org-not-done-regexp nil
2652 "Matches any of the TODO state keywords except the last one.")
2653 (make-variable-buffer-local 'org-not-done-regexp)
2654 (defvar org-todo-line-regexp nil
2655 "Matches a headline and puts TODO state into group 2 if present.")
2656 (make-variable-buffer-local 'org-todo-line-regexp)
2657 (defvar org-complex-heading-regexp nil
2658 "Matches a headline and puts everything into groups:
2659 group 1: the stars
2660 group 2: The todo keyword, maybe
2661 group 3: Priority cookie
2662 group 4: True headline
2663 group 5: Tags")
2664 (make-variable-buffer-local 'org-complex-heading-regexp)
2665 (defvar org-todo-line-tags-regexp nil
2666 "Matches a headline and puts TODO state into group 2 if present.
2667 Also put tags into group 4 if tags are present.")
2668 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2669 (defvar org-nl-done-regexp nil
2670 "Matches newline followed by a headline with the DONE keyword.")
2671 (make-variable-buffer-local 'org-nl-done-regexp)
2672 (defvar org-looking-at-done-regexp nil
2673 "Matches the DONE keyword a point.")
2674 (make-variable-buffer-local 'org-looking-at-done-regexp)
2675 (defvar org-ds-keyword-length 12
2676 "Maximum length of the Deadline and SCHEDULED keywords.")
2677 (make-variable-buffer-local 'org-ds-keyword-length)
2678 (defvar org-deadline-regexp nil
2679 "Matches the DEADLINE keyword.")
2680 (make-variable-buffer-local 'org-deadline-regexp)
2681 (defvar org-deadline-time-regexp nil
2682 "Matches the DEADLINE keyword together with a time stamp.")
2683 (make-variable-buffer-local 'org-deadline-time-regexp)
2684 (defvar org-deadline-line-regexp nil
2685 "Matches the DEADLINE keyword and the rest of the line.")
2686 (make-variable-buffer-local 'org-deadline-line-regexp)
2687 (defvar org-scheduled-regexp nil
2688 "Matches the SCHEDULED keyword.")
2689 (make-variable-buffer-local 'org-scheduled-regexp)
2690 (defvar org-scheduled-time-regexp nil
2691 "Matches the SCHEDULED keyword together with a time stamp.")
2692 (make-variable-buffer-local 'org-scheduled-time-regexp)
2693 (defvar org-closed-time-regexp nil
2694 "Matches the CLOSED keyword together with a time stamp.")
2695 (make-variable-buffer-local 'org-closed-time-regexp)
2697 (defvar org-keyword-time-regexp nil
2698 "Matches any of the 4 keywords, together with the time stamp.")
2699 (make-variable-buffer-local 'org-keyword-time-regexp)
2700 (defvar org-keyword-time-not-clock-regexp nil
2701 "Matches any of the 3 keywords, together with the time stamp.")
2702 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2703 (defvar org-maybe-keyword-time-regexp nil
2704 "Matches a timestamp, possibly preceeded by a keyword.")
2705 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2706 (defvar org-planning-or-clock-line-re nil
2707 "Matches a line with planning or clock info.")
2708 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2710 (defconst org-plain-time-of-day-regexp
2711 (concat
2712 "\\(\\<[012]?[0-9]"
2713 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2714 "\\(--?"
2715 "\\(\\<[012]?[0-9]"
2716 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2717 "\\)?")
2718 "Regular expression to match a plain time or time range.
2719 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2720 groups carry important information:
2721 0 the full match
2722 1 the first time, range or not
2723 8 the second time, if it is a range.")
2725 (defconst org-plain-time-extension-regexp
2726 (concat
2727 "\\(\\<[012]?[0-9]"
2728 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2729 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2730 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2731 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2732 groups carry important information:
2733 0 the full match
2734 7 hours of duration
2735 9 minutes of duration")
2737 (defconst org-stamp-time-of-day-regexp
2738 (concat
2739 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2740 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2741 "\\(--?"
2742 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2743 "Regular expression to match a timestamp time or time range.
2744 After a match, the following groups carry important information:
2745 0 the full match
2746 1 date plus weekday, for backreferencing to make sure both times on same day
2747 2 the first time, range or not
2748 4 the second time, if it is a range.")
2750 (defconst org-startup-options
2751 '(("fold" org-startup-folded t)
2752 ("overview" org-startup-folded t)
2753 ("nofold" org-startup-folded nil)
2754 ("showall" org-startup-folded nil)
2755 ("content" org-startup-folded content)
2756 ("hidestars" org-hide-leading-stars t)
2757 ("showstars" org-hide-leading-stars nil)
2758 ("odd" org-odd-levels-only t)
2759 ("oddeven" org-odd-levels-only nil)
2760 ("align" org-startup-align-all-tables t)
2761 ("noalign" org-startup-align-all-tables nil)
2762 ("customtime" org-display-custom-times t)
2763 ("logdone" org-log-done time)
2764 ("lognotedone" org-log-done note)
2765 ("nologdone" org-log-done nil)
2766 ("lognoteclock-out" org-log-note-clock-out t)
2767 ("nolognoteclock-out" org-log-note-clock-out nil)
2768 ("logrepeat" org-log-repeat state)
2769 ("lognoterepeat" org-log-repeat note)
2770 ("nologrepeat" org-log-repeat nil)
2771 ("constcgs" constants-unit-system cgs)
2772 ("constSI" constants-unit-system SI))
2773 "Variable associated with STARTUP options for org-mode.
2774 Each element is a list of three items: The startup options as written
2775 in the #+STARTUP line, the corresponding variable, and the value to
2776 set this variable to if the option is found. An optional forth element PUSH
2777 means to push this value onto the list in the variable.")
2779 (defun org-set-regexps-and-options ()
2780 "Precompute regular expressions for current buffer."
2781 (when (org-mode-p)
2782 (org-set-local 'org-todo-kwd-alist nil)
2783 (org-set-local 'org-todo-key-alist nil)
2784 (org-set-local 'org-todo-key-trigger nil)
2785 (org-set-local 'org-todo-keywords-1 nil)
2786 (org-set-local 'org-done-keywords nil)
2787 (org-set-local 'org-todo-heads nil)
2788 (org-set-local 'org-todo-sets nil)
2789 (org-set-local 'org-todo-log-states nil)
2790 (let ((re (org-make-options-regexp
2791 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2792 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2793 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2794 (splitre "[ \t]+")
2795 kwds kws0 kwsa key log value cat arch tags const links hw dws
2796 tail sep kws1 prio props ftags drawers
2797 ext-setup-or-nil setup-contents (start 0))
2798 (save-excursion
2799 (save-restriction
2800 (widen)
2801 (goto-char (point-min))
2802 (while (or (and ext-setup-or-nil
2803 (string-match re ext-setup-or-nil start)
2804 (setq start (match-end 0)))
2805 (and (setq ext-setup-or-nil nil start 0)
2806 (re-search-forward re nil t)))
2807 (setq key (upcase (match-string 1 ext-setup-or-nil))
2808 value (org-match-string-no-properties 2 ext-setup-or-nil))
2809 (cond
2810 ((equal key "CATEGORY")
2811 (if (string-match "[ \t]+$" value)
2812 (setq value (replace-match "" t t value)))
2813 (setq cat value))
2814 ((member key '("SEQ_TODO" "TODO"))
2815 (push (cons 'sequence (org-split-string value splitre)) kwds))
2816 ((equal key "TYP_TODO")
2817 (push (cons 'type (org-split-string value splitre)) kwds))
2818 ((equal key "TAGS")
2819 (setq tags (append tags (org-split-string value splitre))))
2820 ((equal key "COLUMNS")
2821 (org-set-local 'org-columns-default-format value))
2822 ((equal key "LINK")
2823 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2824 (push (cons (match-string 1 value)
2825 (org-trim (match-string 2 value)))
2826 links)))
2827 ((equal key "PRIORITIES")
2828 (setq prio (org-split-string value " +")))
2829 ((equal key "PROPERTY")
2830 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2831 (push (cons (match-string 1 value) (match-string 2 value))
2832 props)))
2833 ((equal key "FILETAGS")
2834 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2835 (setq ftags
2836 (append
2837 ftags
2838 (apply 'append
2839 (mapcar (lambda (x) (org-split-string x ":"))
2840 (org-split-string value)))))))
2841 ((equal key "DRAWERS")
2842 (setq drawers (org-split-string value splitre)))
2843 ((equal key "CONSTANTS")
2844 (setq const (append const (org-split-string value splitre))))
2845 ((equal key "STARTUP")
2846 (let ((opts (org-split-string value splitre))
2847 l var val)
2848 (while (setq l (pop opts))
2849 (when (setq l (assoc l org-startup-options))
2850 (setq var (nth 1 l) val (nth 2 l))
2851 (if (not (nth 3 l))
2852 (set (make-local-variable var) val)
2853 (if (not (listp (symbol-value var)))
2854 (set (make-local-variable var) nil))
2855 (set (make-local-variable var) (symbol-value var))
2856 (add-to-list var val))))))
2857 ((equal key "ARCHIVE")
2858 (string-match " *$" value)
2859 (setq arch (replace-match "" t t value))
2860 (remove-text-properties 0 (length arch)
2861 '(face t fontified t) arch))
2862 ((equal key "SETUPFILE")
2863 (setq setup-contents (org-file-contents
2864 (expand-file-name
2865 (org-remove-double-quotes value))
2866 'noerror))
2867 (if (not ext-setup-or-nil)
2868 (setq ext-setup-or-nil setup-contents start 0)
2869 (setq ext-setup-or-nil
2870 (concat (substring ext-setup-or-nil 0 start)
2871 "\n" setup-contents "\n"
2872 (substring ext-setup-or-nil start)))))
2873 ))))
2874 (when cat
2875 (org-set-local 'org-category (intern cat))
2876 (push (cons "CATEGORY" cat) props))
2877 (when prio
2878 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2879 (setq prio (mapcar 'string-to-char prio))
2880 (org-set-local 'org-highest-priority (nth 0 prio))
2881 (org-set-local 'org-lowest-priority (nth 1 prio))
2882 (org-set-local 'org-default-priority (nth 2 prio)))
2883 (and props (org-set-local 'org-file-properties (nreverse props)))
2884 (and ftags (org-set-local 'org-file-tags ftags))
2885 (and drawers (org-set-local 'org-drawers drawers))
2886 (and arch (org-set-local 'org-archive-location arch))
2887 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2888 ;; Process the TODO keywords
2889 (unless kwds
2890 ;; Use the global values as if they had been given locally.
2891 (setq kwds (default-value 'org-todo-keywords))
2892 (if (stringp (car kwds))
2893 (setq kwds (list (cons org-todo-interpretation
2894 (default-value 'org-todo-keywords)))))
2895 (setq kwds (reverse kwds)))
2896 (setq kwds (nreverse kwds))
2897 (let (inter kws kw)
2898 (while (setq kws (pop kwds))
2899 (setq inter (pop kws) sep (member "|" kws)
2900 kws0 (delete "|" (copy-sequence kws))
2901 kwsa nil
2902 kws1 (mapcar
2903 (lambda (x)
2904 ;; 1 2
2905 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2906 (progn
2907 (setq kw (match-string 1 x)
2908 key (and (match-end 2) (match-string 2 x))
2909 log (org-extract-log-state-settings x))
2910 (push (cons kw (and key (string-to-char key))) kwsa)
2911 (and log (push log org-todo-log-states))
2913 (error "Invalid TODO keyword %s" x)))
2914 kws0)
2915 kwsa (if kwsa (append '((:startgroup))
2916 (nreverse kwsa)
2917 '((:endgroup))))
2918 hw (car kws1)
2919 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2920 tail (list inter hw (car dws) (org-last dws)))
2921 (add-to-list 'org-todo-heads hw 'append)
2922 (push kws1 org-todo-sets)
2923 (setq org-done-keywords (append org-done-keywords dws nil))
2924 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2925 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2926 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2927 (setq org-todo-sets (nreverse org-todo-sets)
2928 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2929 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2930 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2931 ;; Process the constants
2932 (when const
2933 (let (e cst)
2934 (while (setq e (pop const))
2935 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2936 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2937 (setq org-table-formula-constants-local cst)))
2939 ;; Process the tags.
2940 (when tags
2941 (let (e tgs)
2942 (while (setq e (pop tags))
2943 (cond
2944 ((equal e "{") (push '(:startgroup) tgs))
2945 ((equal e "}") (push '(:endgroup) tgs))
2946 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2947 (push (cons (match-string 1 e)
2948 (string-to-char (match-string 2 e)))
2949 tgs))
2950 (t (push (list e) tgs))))
2951 (org-set-local 'org-tag-alist nil)
2952 (while (setq e (pop tgs))
2953 (or (and (stringp (car e))
2954 (assoc (car e) org-tag-alist))
2955 (push e org-tag-alist)))))
2957 ;; Compute the regular expressions and other local variables
2958 (if (not org-done-keywords)
2959 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2960 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2961 (length org-scheduled-string)
2962 (length org-clock-string)
2963 (length org-closed-string)))
2964 org-drawer-regexp
2965 (concat "^[ \t]*:\\("
2966 (mapconcat 'regexp-quote org-drawers "\\|")
2967 "\\):[ \t]*$")
2968 org-not-done-keywords
2969 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2970 org-todo-regexp
2971 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2972 "\\|") "\\)\\>")
2973 org-not-done-regexp
2974 (concat "\\<\\("
2975 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2976 "\\)\\>")
2977 org-todo-line-regexp
2978 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2979 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2980 "\\)\\>\\)?[ \t]*\\(.*\\)")
2981 org-complex-heading-regexp
2982 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2983 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2984 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2985 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2986 org-nl-done-regexp
2987 (concat "\n\\*+[ \t]+"
2988 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2989 "\\)" "\\>")
2990 org-todo-line-tags-regexp
2991 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2992 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2993 (org-re
2994 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2995 org-looking-at-done-regexp
2996 (concat "^" "\\(?:"
2997 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2998 "\\>")
2999 org-deadline-regexp (concat "\\<" org-deadline-string)
3000 org-deadline-time-regexp
3001 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3002 org-deadline-line-regexp
3003 (concat "\\<\\(" org-deadline-string "\\).*")
3004 org-scheduled-regexp
3005 (concat "\\<" org-scheduled-string)
3006 org-scheduled-time-regexp
3007 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3008 org-closed-time-regexp
3009 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3010 org-keyword-time-regexp
3011 (concat "\\<\\(" org-scheduled-string
3012 "\\|" org-deadline-string
3013 "\\|" org-closed-string
3014 "\\|" org-clock-string "\\)"
3015 " *[[<]\\([^]>]+\\)[]>]")
3016 org-keyword-time-not-clock-regexp
3017 (concat "\\<\\(" org-scheduled-string
3018 "\\|" org-deadline-string
3019 "\\|" org-closed-string
3020 "\\)"
3021 " *[[<]\\([^]>]+\\)[]>]")
3022 org-maybe-keyword-time-regexp
3023 (concat "\\(\\<\\(" org-scheduled-string
3024 "\\|" org-deadline-string
3025 "\\|" org-closed-string
3026 "\\|" org-clock-string "\\)\\)?"
3027 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3028 org-planning-or-clock-line-re
3029 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3030 "\\|" org-deadline-string
3031 "\\|" org-closed-string "\\|" org-clock-string
3032 "\\)\\>\\)")
3034 (org-compute-latex-and-specials-regexp)
3035 (org-set-font-lock-defaults))))
3037 (defun org-file-contents (file &optional noerror)
3038 "Return the contents of FILE, as a string."
3039 (if (or (not file)
3040 (not (file-readable-p file)))
3041 (if noerror
3042 (progn
3043 (message "Cannot read file %s" file)
3044 (ding) (sit-for 2)
3046 (error "Cannot read file %s" file))
3047 (with-temp-buffer
3048 (insert-file-contents file)
3049 (buffer-string))))
3051 (defun org-extract-log-state-settings (x)
3052 "Extract the log state setting from a TODO keyword string.
3053 This will extract info from a string like \"WAIT(w@/!)\"."
3054 (let (kw key log1 log2)
3055 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3056 (setq kw (match-string 1 x)
3057 key (and (match-end 2) (match-string 2 x))
3058 log1 (and (match-end 3) (match-string 3 x))
3059 log2 (and (match-end 4) (match-string 4 x)))
3060 (and (or log1 log2)
3061 (list kw
3062 (and log1 (if (equal log1 "!") 'time 'note))
3063 (and log2 (if (equal log2 "!") 'time 'note)))))))
3065 (defun org-remove-keyword-keys (list)
3066 "Remove a pair of parenthesis at the end of each string in LIST."
3067 (mapcar (lambda (x)
3068 (if (string-match "(.*)$" x)
3069 (substring x 0 (match-beginning 0))
3071 list))
3073 ;; FIXME: this could be done much better, using second characters etc.
3074 (defun org-assign-fast-keys (alist)
3075 "Assign fast keys to a keyword-key alist.
3076 Respect keys that are already there."
3077 (let (new e k c c1 c2 (char ?a))
3078 (while (setq e (pop alist))
3079 (cond
3080 ((equal e '(:startgroup)) (push e new))
3081 ((equal e '(:endgroup)) (push e new))
3083 (setq k (car e) c2 nil)
3084 (if (cdr e)
3085 (setq c (cdr e))
3086 ;; automatically assign a character.
3087 (setq c1 (string-to-char
3088 (downcase (substring
3089 k (if (= (string-to-char k) ?@) 1 0)))))
3090 (if (or (rassoc c1 new) (rassoc c1 alist))
3091 (while (or (rassoc char new) (rassoc char alist))
3092 (setq char (1+ char)))
3093 (setq c2 c1))
3094 (setq c (or c2 char)))
3095 (push (cons k c) new))))
3096 (nreverse new)))
3098 ;;; Some variables used in various places
3100 (defvar org-window-configuration nil
3101 "Used in various places to store a window configuration.")
3102 (defvar org-finish-function nil
3103 "Function to be called when `C-c C-c' is used.
3104 This is for getting out of special buffers like remember.")
3107 ;; FIXME: Occasionally check by commenting these, to make sure
3108 ;; no other functions uses these, forgetting to let-bind them.
3109 (defvar entry)
3110 (defvar state)
3111 (defvar last-state)
3112 (defvar date)
3113 (defvar description)
3115 ;; Defined somewhere in this file, but used before definition.
3116 (defvar org-html-entities)
3117 (defvar org-struct-menu)
3118 (defvar org-org-menu)
3119 (defvar org-tbl-menu)
3120 (defvar org-agenda-keymap)
3122 ;;;; Define the Org-mode
3124 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3125 (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."))
3128 ;; We use a before-change function to check if a table might need
3129 ;; an update.
3130 (defvar org-table-may-need-update t
3131 "Indicates that a table might need an update.
3132 This variable is set by `org-before-change-function'.
3133 `org-table-align' sets it back to nil.")
3134 (defun org-before-change-function (beg end)
3135 "Every change indicates that a table might need an update."
3136 (setq org-table-may-need-update t))
3137 (defvar org-mode-map)
3138 (defvar org-mode-hook nil)
3139 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3140 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3141 (defvar org-table-buffer-is-an nil)
3142 (defconst org-outline-regexp "\\*+ ")
3144 ;;;###autoload
3145 (define-derived-mode org-mode outline-mode "Org"
3146 "Outline-based notes management and organizer, alias
3147 \"Carsten's outline-mode for keeping track of everything.\"
3149 Org-mode develops organizational tasks around a NOTES file which
3150 contains information about projects as plain text. Org-mode is
3151 implemented on top of outline-mode, which is ideal to keep the content
3152 of large files well structured. It supports ToDo items, deadlines and
3153 time stamps, which magically appear in the diary listing of the Emacs
3154 calendar. Tables are easily created with a built-in table editor.
3155 Plain text URL-like links connect to websites, emails (VM), Usenet
3156 messages (Gnus), BBDB entries, and any files related to the project.
3157 For printing and sharing of notes, an Org-mode file (or a part of it)
3158 can be exported as a structured ASCII or HTML file.
3160 The following commands are available:
3162 \\{org-mode-map}"
3164 ;; Get rid of Outline menus, they are not needed
3165 ;; Need to do this here because define-derived-mode sets up
3166 ;; the keymap so late. Still, it is a waste to call this each time
3167 ;; we switch another buffer into org-mode.
3168 (if (featurep 'xemacs)
3169 (when (boundp 'outline-mode-menu-heading)
3170 ;; Assume this is Greg's port, it used easymenu
3171 (easy-menu-remove outline-mode-menu-heading)
3172 (easy-menu-remove outline-mode-menu-show)
3173 (easy-menu-remove outline-mode-menu-hide))
3174 (define-key org-mode-map [menu-bar headings] 'undefined)
3175 (define-key org-mode-map [menu-bar hide] 'undefined)
3176 (define-key org-mode-map [menu-bar show] 'undefined))
3178 (org-load-modules-maybe)
3179 (easy-menu-add org-org-menu)
3180 (easy-menu-add org-tbl-menu)
3181 (org-install-agenda-files-menu)
3182 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3183 (org-add-to-invisibility-spec '(org-cwidth))
3184 (when (featurep 'xemacs)
3185 (org-set-local 'line-move-ignore-invisible t))
3186 (org-set-local 'outline-regexp org-outline-regexp)
3187 (org-set-local 'outline-level 'org-outline-level)
3188 (when (and org-ellipsis
3189 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3190 (fboundp 'make-glyph-code))
3191 (unless org-display-table
3192 (setq org-display-table (make-display-table)))
3193 (set-display-table-slot
3194 org-display-table 4
3195 (vconcat (mapcar
3196 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3197 org-ellipsis)))
3198 (if (stringp org-ellipsis) org-ellipsis "..."))))
3199 (setq buffer-display-table org-display-table))
3200 (org-set-regexps-and-options)
3201 ;; Calc embedded
3202 (org-set-local 'calc-embedded-open-mode "# ")
3203 (modify-syntax-entry ?# "<")
3204 (modify-syntax-entry ?@ "w")
3205 (if org-startup-truncated (setq truncate-lines t))
3206 (org-set-local 'font-lock-unfontify-region-function
3207 'org-unfontify-region)
3208 ;; Activate before-change-function
3209 (org-set-local 'org-table-may-need-update t)
3210 (org-add-hook 'before-change-functions 'org-before-change-function nil
3211 'local)
3212 ;; Check for running clock before killing a buffer
3213 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3214 ;; Paragraphs and auto-filling
3215 (org-set-autofill-regexps)
3216 (setq indent-line-function 'org-indent-line-function)
3217 (org-update-radio-target-regexp)
3219 ;; Comment characters
3220 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3221 (org-set-local 'comment-padding " ")
3223 ;; Align options lines
3224 (org-set-local
3225 'align-mode-rules-list
3226 '((org-in-buffer-settings
3227 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3228 (modes . '(org-mode)))))
3230 ;; Imenu
3231 (org-set-local 'imenu-create-index-function
3232 'org-imenu-get-tree)
3234 ;; Make isearch reveal context
3235 (if (or (featurep 'xemacs)
3236 (not (boundp 'outline-isearch-open-invisible-function)))
3237 ;; Emacs 21 and XEmacs make use of the hook
3238 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3239 ;; Emacs 22 deals with this through a special variable
3240 (org-set-local 'outline-isearch-open-invisible-function
3241 (lambda (&rest ignore) (org-show-context 'isearch))))
3243 ;; If empty file that did not turn on org-mode automatically, make it to.
3244 (if (and org-insert-mode-line-in-empty-file
3245 (interactive-p)
3246 (= (point-min) (point-max)))
3247 (insert "# -*- mode: org -*-\n\n"))
3249 (unless org-inhibit-startup
3250 (when org-startup-align-all-tables
3251 (let ((bmp (buffer-modified-p)))
3252 (org-table-map-tables 'org-table-align)
3253 (set-buffer-modified-p bmp)))
3254 (org-set-startup-visibility)))
3256 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3258 (defun org-current-time ()
3259 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3260 (if (> (car org-time-stamp-rounding-minutes) 1)
3261 (let ((r (car org-time-stamp-rounding-minutes))
3262 (time (decode-time)))
3263 (apply 'encode-time
3264 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3265 (nthcdr 2 time))))
3266 (current-time)))
3268 ;;;; Font-Lock stuff, including the activators
3270 (defvar org-mouse-map (make-sparse-keymap))
3271 (org-defkey org-mouse-map
3272 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3273 (org-defkey org-mouse-map
3274 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3275 (when org-mouse-1-follows-link
3276 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3277 (when org-tab-follows-link
3278 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3279 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3280 (when org-return-follows-link
3281 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3282 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3284 (require 'font-lock)
3286 (defconst org-non-link-chars "]\t\n\r<>")
3287 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3288 "shell" "elisp"))
3289 (defvar org-link-types-re nil
3290 "Matches a link that has a url-like prefix like \"http:\"")
3291 (defvar org-link-re-with-space nil
3292 "Matches a link with spaces, optional angular brackets around it.")
3293 (defvar org-link-re-with-space2 nil
3294 "Matches a link with spaces, optional angular brackets around it.")
3295 (defvar org-angle-link-re nil
3296 "Matches link with angular brackets, spaces are allowed.")
3297 (defvar org-plain-link-re nil
3298 "Matches plain link, without spaces.")
3299 (defvar org-bracket-link-regexp nil
3300 "Matches a link in double brackets.")
3301 (defvar org-bracket-link-analytic-regexp nil
3302 "Regular expression used to analyze links.
3303 Here is what the match groups contain after a match:
3304 1: http:
3305 2: http
3306 3: path
3307 4: [desc]
3308 5: desc")
3309 (defvar org-any-link-re nil
3310 "Regular expression matching any link.")
3312 (defun org-make-link-regexps ()
3313 "Update the link regular expressions.
3314 This should be called after the variable `org-link-types' has changed."
3315 (setq org-link-types-re
3316 (concat
3317 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3318 org-link-re-with-space
3319 (concat
3320 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3321 "\\([^" org-non-link-chars " ]"
3322 "[^" org-non-link-chars "]*"
3323 "[^" org-non-link-chars " ]\\)>?")
3324 org-link-re-with-space2
3325 (concat
3326 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3327 "\\([^" org-non-link-chars " ]"
3328 "[^]\t\n\r]*"
3329 "[^" org-non-link-chars " ]\\)>?")
3330 org-angle-link-re
3331 (concat
3332 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3333 "\\([^" org-non-link-chars " ]"
3334 "[^" org-non-link-chars "]*"
3335 "\\)>")
3336 org-plain-link-re
3337 (concat
3338 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3339 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3340 org-bracket-link-regexp
3341 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3342 org-bracket-link-analytic-regexp
3343 (concat
3344 "\\[\\["
3345 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3346 "\\([^]]+\\)"
3347 "\\]"
3348 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3349 "\\]")
3350 org-any-link-re
3351 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3352 org-angle-link-re "\\)\\|\\("
3353 org-plain-link-re "\\)")))
3355 (org-make-link-regexps)
3357 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3358 "Regular expression for fast time stamp matching.")
3359 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3360 "Regular expression for fast time stamp matching.")
3361 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3362 "Regular expression matching time strings for analysis.
3363 This one does not require the space after the date, so it can be used
3364 on a string that terminates immediately after the date.")
3365 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3366 "Regular expression matching time strings for analysis.")
3367 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3368 "Regular expression matching time stamps, with groups.")
3369 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3370 "Regular expression matching time stamps (also [..]), with groups.")
3371 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3372 "Regular expression matching a time stamp range.")
3373 (defconst org-tr-regexp-both
3374 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3375 "Regular expression matching a time stamp range.")
3376 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3377 org-ts-regexp "\\)?")
3378 "Regular expression matching a time stamp or time stamp range.")
3379 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3380 org-ts-regexp-both "\\)?")
3381 "Regular expression matching a time stamp or time stamp range.
3382 The time stamps may be either active or inactive.")
3384 (defvar org-emph-face nil)
3386 (defun org-do-emphasis-faces (limit)
3387 "Run through the buffer and add overlays to links."
3388 (let (rtn)
3389 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3390 (if (not (= (char-after (match-beginning 3))
3391 (char-after (match-beginning 4))))
3392 (progn
3393 (setq rtn t)
3394 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3395 'face
3396 (nth 1 (assoc (match-string 3)
3397 org-emphasis-alist)))
3398 (add-text-properties (match-beginning 2) (match-end 2)
3399 '(font-lock-multiline t))
3400 (when org-hide-emphasis-markers
3401 (add-text-properties (match-end 4) (match-beginning 5)
3402 '(invisible org-link))
3403 (add-text-properties (match-beginning 3) (match-end 3)
3404 '(invisible org-link)))))
3405 (backward-char 1))
3406 rtn))
3408 (defun org-emphasize (&optional char)
3409 "Insert or change an emphasis, i.e. a font like bold or italic.
3410 If there is an active region, change that region to a new emphasis.
3411 If there is no region, just insert the marker characters and position
3412 the cursor between them.
3413 CHAR should be either the marker character, or the first character of the
3414 HTML tag associated with that emphasis. If CHAR is a space, the means
3415 to remove the emphasis of the selected region.
3416 If char is not given (for example in an interactive call) it
3417 will be prompted for."
3418 (interactive)
3419 (let ((eal org-emphasis-alist) e det
3420 (erc org-emphasis-regexp-components)
3421 (prompt "")
3422 (string "") beg end move tag c s)
3423 (if (org-region-active-p)
3424 (setq beg (region-beginning) end (region-end)
3425 string (buffer-substring beg end))
3426 (setq move t))
3428 (while (setq e (pop eal))
3429 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3430 c (aref tag 0))
3431 (push (cons c (string-to-char (car e))) det)
3432 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3433 (substring tag 1)))))
3434 (unless char
3435 (message "%s" (concat "Emphasis marker or tag:" prompt))
3436 (setq char (read-char-exclusive)))
3437 (setq char (or (cdr (assoc char det)) char))
3438 (if (equal char ?\ )
3439 (setq s "" move nil)
3440 (unless (assoc (char-to-string char) org-emphasis-alist)
3441 (error "No such emphasis marker: \"%c\"" char))
3442 (setq s (char-to-string char)))
3443 (while (and (> (length string) 1)
3444 (equal (substring string 0 1) (substring string -1))
3445 (assoc (substring string 0 1) org-emphasis-alist))
3446 (setq string (substring string 1 -1)))
3447 (setq string (concat s string s))
3448 (if beg (delete-region beg end))
3449 (unless (or (bolp)
3450 (string-match (concat "[" (nth 0 erc) "\n]")
3451 (char-to-string (char-before (point)))))
3452 (insert " "))
3453 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3454 (char-to-string (char-after (point))))
3455 (insert " ") (backward-char 1))
3456 (insert string)
3457 (and move (backward-char 1))))
3459 (defconst org-nonsticky-props
3460 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3463 (defun org-activate-plain-links (limit)
3464 "Run through the buffer and add overlays to links."
3465 (catch 'exit
3466 (let (f)
3467 (while (re-search-forward org-plain-link-re limit t)
3468 (setq f (get-text-property (match-beginning 0) 'face))
3469 (if (or (eq f 'org-tag)
3470 (and (listp f) (memq 'org-tag f)))
3472 (add-text-properties (match-beginning 0) (match-end 0)
3473 (list 'mouse-face 'highlight
3474 'rear-nonsticky org-nonsticky-props
3475 'keymap org-mouse-map
3477 (throw 'exit t))))))
3479 (defun org-activate-code (limit)
3480 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3481 (unless (get-text-property (match-beginning 1) 'face)
3482 (remove-text-properties (match-beginning 0) (match-end 0)
3483 '(display t invisible t intangible t))
3484 t)))
3486 (defun org-activate-angle-links (limit)
3487 "Run through the buffer and add overlays to links."
3488 (if (re-search-forward org-angle-link-re limit t)
3489 (progn
3490 (add-text-properties (match-beginning 0) (match-end 0)
3491 (list 'mouse-face 'highlight
3492 'rear-nonsticky org-nonsticky-props
3493 'keymap org-mouse-map
3495 t)))
3497 (defun org-activate-bracket-links (limit)
3498 "Run through the buffer and add overlays to bracketed links."
3499 (if (re-search-forward org-bracket-link-regexp limit t)
3500 (let* ((help (concat "LINK: "
3501 (org-match-string-no-properties 1)))
3502 ;; FIXME: above we should remove the escapes.
3503 ;; but that requires another match, protecting match data,
3504 ;; a lot of overhead for font-lock.
3505 (ip (org-maybe-intangible
3506 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3507 'keymap org-mouse-map 'mouse-face 'highlight
3508 'font-lock-multiline t 'help-echo help)))
3509 (vp (list 'rear-nonsticky org-nonsticky-props
3510 'keymap org-mouse-map 'mouse-face 'highlight
3511 ' font-lock-multiline t 'help-echo help)))
3512 ;; We need to remove the invisible property here. Table narrowing
3513 ;; may have made some of this invisible.
3514 (remove-text-properties (match-beginning 0) (match-end 0)
3515 '(invisible nil))
3516 (if (match-end 3)
3517 (progn
3518 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3519 (add-text-properties (match-beginning 3) (match-end 3) vp)
3520 (add-text-properties (match-end 3) (match-end 0) ip))
3521 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3522 (add-text-properties (match-beginning 1) (match-end 1) vp)
3523 (add-text-properties (match-end 1) (match-end 0) ip))
3524 t)))
3526 (defun org-activate-dates (limit)
3527 "Run through the buffer and add overlays to dates."
3528 (if (re-search-forward org-tsr-regexp-both limit t)
3529 (progn
3530 (add-text-properties (match-beginning 0) (match-end 0)
3531 (list 'mouse-face 'highlight
3532 'rear-nonsticky org-nonsticky-props
3533 'keymap org-mouse-map))
3534 (when org-display-custom-times
3535 (if (match-end 3)
3536 (org-display-custom-time (match-beginning 3) (match-end 3)))
3537 (org-display-custom-time (match-beginning 1) (match-end 1)))
3538 t)))
3540 (defvar org-target-link-regexp nil
3541 "Regular expression matching radio targets in plain text.")
3542 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3543 "Regular expression matching a link target.")
3544 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3545 "Regular expression matching a radio target.")
3546 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3547 "Regular expression matching any target.")
3549 (defun org-activate-target-links (limit)
3550 "Run through the buffer and add overlays to target matches."
3551 (when org-target-link-regexp
3552 (let ((case-fold-search t))
3553 (if (re-search-forward org-target-link-regexp limit t)
3554 (progn
3555 (add-text-properties (match-beginning 0) (match-end 0)
3556 (list 'mouse-face 'highlight
3557 'rear-nonsticky org-nonsticky-props
3558 'keymap org-mouse-map
3559 'help-echo "Radio target link"
3560 'org-linked-text t))
3561 t)))))
3563 (defun org-update-radio-target-regexp ()
3564 "Find all radio targets in this file and update the regular expression."
3565 (interactive)
3566 (when (memq 'radio org-activate-links)
3567 (setq org-target-link-regexp
3568 (org-make-target-link-regexp (org-all-targets 'radio)))
3569 (org-restart-font-lock)))
3571 (defun org-hide-wide-columns (limit)
3572 (let (s e)
3573 (setq s (text-property-any (point) (or limit (point-max))
3574 'org-cwidth t))
3575 (when s
3576 (setq e (next-single-property-change s 'org-cwidth))
3577 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3578 (goto-char e)
3579 t)))
3581 (defvar org-latex-and-specials-regexp nil
3582 "Regular expression for highlighting export special stuff.")
3583 (defvar org-match-substring-regexp)
3584 (defvar org-match-substring-with-braces-regexp)
3585 (defvar org-export-html-special-string-regexps)
3587 (defun org-compute-latex-and-specials-regexp ()
3588 "Compute regular expression for stuff treated specially by exporters."
3589 (if (not org-highlight-latex-fragments-and-specials)
3590 (org-set-local 'org-latex-and-specials-regexp nil)
3591 (require 'org-exp)
3592 (let*
3593 ((matchers (plist-get org-format-latex-options :matchers))
3594 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3595 org-latex-regexps)))
3596 (options (org-combine-plists (org-default-export-plist)
3597 (org-infile-export-plist)))
3598 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3599 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3600 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3601 (org-export-html-expand (plist-get options :expand-quoted-html))
3602 (org-export-with-special-strings (plist-get options :special-strings))
3603 (re-sub
3604 (cond
3605 ((equal org-export-with-sub-superscripts '{})
3606 (list org-match-substring-with-braces-regexp))
3607 (org-export-with-sub-superscripts
3608 (list org-match-substring-regexp))
3609 (t nil)))
3610 (re-latex
3611 (if org-export-with-LaTeX-fragments
3612 (mapcar (lambda (x) (nth 1 x)) latexs)))
3613 (re-macros
3614 (if org-export-with-TeX-macros
3615 (list (concat "\\\\"
3616 (regexp-opt
3617 (append (mapcar 'car org-html-entities)
3618 (if (boundp 'org-latex-entities)
3619 org-latex-entities nil))
3620 'words))) ; FIXME
3622 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3623 (re-special (if org-export-with-special-strings
3624 (mapcar (lambda (x) (car x))
3625 org-export-html-special-string-regexps)))
3626 (re-rest
3627 (delq nil
3628 (list
3629 (if org-export-html-expand "@<[^>\n]+>")
3630 ))))
3631 (org-set-local
3632 'org-latex-and-specials-regexp
3633 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3634 re-rest) "\\|")))))
3636 (defun org-do-latex-and-special-faces (limit)
3637 "Run through the buffer and add overlays to links."
3638 (when org-latex-and-specials-regexp
3639 (let (rtn d)
3640 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3641 limit t))
3642 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3643 'face))
3644 '(org-code org-verbatim underline)))
3645 (progn
3646 (setq rtn t
3647 d (cond ((member (char-after (1+ (match-beginning 0)))
3648 '(?_ ?^)) 1)
3649 (t 0)))
3650 (font-lock-prepend-text-property
3651 (+ d (match-beginning 0)) (match-end 0)
3652 'face 'org-latex-and-export-specials)
3653 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3654 '(font-lock-multiline t)))))
3655 rtn)))
3657 (defun org-restart-font-lock ()
3658 "Restart font-lock-mode, to force refontification."
3659 (when (and (boundp 'font-lock-mode) font-lock-mode)
3660 (font-lock-mode -1)
3661 (font-lock-mode 1)))
3663 (defun org-all-targets (&optional radio)
3664 "Return a list of all targets in this file.
3665 With optional argument RADIO, only find radio targets."
3666 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3667 rtn)
3668 (save-excursion
3669 (goto-char (point-min))
3670 (while (re-search-forward re nil t)
3671 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3672 rtn)))
3674 (defun org-make-target-link-regexp (targets)
3675 "Make regular expression matching all strings in TARGETS.
3676 The regular expression finds the targets also if there is a line break
3677 between words."
3678 (and targets
3679 (concat
3680 "\\<\\("
3681 (mapconcat
3682 (lambda (x)
3683 (while (string-match " +" x)
3684 (setq x (replace-match "\\s-+" t t x)))
3686 targets
3687 "\\|")
3688 "\\)\\>")))
3690 (defun org-activate-tags (limit)
3691 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3692 (progn
3693 (add-text-properties (match-beginning 1) (match-end 1)
3694 (list 'mouse-face 'highlight
3695 'rear-nonsticky org-nonsticky-props
3696 'keymap org-mouse-map))
3697 t)))
3699 (defun org-outline-level ()
3700 (save-excursion
3701 (looking-at outline-regexp)
3702 (if (match-beginning 1)
3703 (+ (org-get-string-indentation (match-string 1)) 1000)
3704 (1- (- (match-end 0) (match-beginning 0))))))
3706 (defvar org-font-lock-keywords nil)
3708 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3709 "Regular expression matching a property line.")
3711 (defvar org-font-lock-hook nil
3712 "Functions to be called for special font lock stuff.")
3714 (defun org-font-lock-hook (limit)
3715 (run-hook-with-args 'org-font-lock-hook limit))
3717 (defun org-set-font-lock-defaults ()
3718 (let* ((em org-fontify-emphasized-text)
3719 (lk org-activate-links)
3720 (org-font-lock-extra-keywords
3721 (list
3722 ;; Call the hook
3723 '(org-font-lock-hook)
3724 ;; Headlines
3725 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3726 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3727 ;; Table lines
3728 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3729 (1 'org-table t))
3730 ;; Table internals
3731 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3732 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3733 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3734 ;; Drawers
3735 (list org-drawer-regexp '(0 'org-special-keyword t))
3736 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3737 ;; Properties
3738 (list org-property-re
3739 '(1 'org-special-keyword t)
3740 '(3 'org-property-value t))
3741 (if org-format-transports-properties-p
3742 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3743 ;; Links
3744 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3745 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3746 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3747 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3748 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3749 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3750 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3751 '(org-hide-wide-columns (0 nil append))
3752 ;; TODO lines
3753 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3754 '(1 (org-get-todo-face 1) t))
3755 ;; DONE
3756 (if org-fontify-done-headline
3757 (list (concat "^[*]+ +\\<\\("
3758 (mapconcat 'regexp-quote org-done-keywords "\\|")
3759 "\\)\\(.*\\)")
3760 '(2 'org-headline-done t))
3761 nil)
3762 ;; Priorities
3763 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3764 ;; Special keywords
3765 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3766 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3767 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3768 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3769 ;; Emphasis
3770 (if em
3771 (if (featurep 'xemacs)
3772 '(org-do-emphasis-faces (0 nil append))
3773 '(org-do-emphasis-faces)))
3774 ;; Checkboxes
3775 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3776 2 'bold prepend)
3777 (if org-provide-checkbox-statistics
3778 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3779 (0 (org-get-checkbox-statistics-face) t)))
3780 ;; Description list items
3781 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3782 2 'bold prepend)
3783 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3784 '(1 'org-archived prepend))
3785 ;; Specials
3786 '(org-do-latex-and-special-faces)
3787 ;; Code
3788 '(org-activate-code (1 'org-code t))
3789 ;; COMMENT
3790 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3791 "\\|" org-quote-string "\\)\\>")
3792 '(1 'org-special-keyword t))
3793 '("^#.*" (0 'font-lock-comment-face t))
3795 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3796 ;; Now set the full font-lock-keywords
3797 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3798 (org-set-local 'font-lock-defaults
3799 '(org-font-lock-keywords t nil nil backward-paragraph))
3800 (kill-local-variable 'font-lock-keywords) nil))
3802 (defvar org-m nil)
3803 (defvar org-l nil)
3804 (defvar org-f nil)
3805 (defun org-get-level-face (n)
3806 "Get the right face for match N in font-lock matching of healdines."
3807 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3808 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3809 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3810 (cond
3811 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3812 ((eq n 2) org-f)
3813 (t (if org-level-color-stars-only nil org-f))))
3815 (defun org-get-todo-face (kwd)
3816 "Get the right face for a TODO keyword KWD.
3817 If KWD is a number, get the corresponding match group."
3818 (if (numberp kwd) (setq kwd (match-string kwd)))
3819 (or (cdr (assoc kwd org-todo-keyword-faces))
3820 (and (member kwd org-done-keywords) 'org-done)
3821 'org-todo))
3823 (defun org-unfontify-region (beg end &optional maybe_loudly)
3824 "Remove fontification and activation overlays from links."
3825 (font-lock-default-unfontify-region beg end)
3826 (let* ((buffer-undo-list t)
3827 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3828 (inhibit-modification-hooks t)
3829 deactivate-mark buffer-file-name buffer-file-truename)
3830 (remove-text-properties beg end
3831 '(mouse-face t keymap t org-linked-text t
3832 invisible t intangible t))))
3834 ;;;; Visibility cycling, including org-goto and indirect buffer
3836 ;;; Cycling
3838 (defvar org-cycle-global-status nil)
3839 (make-variable-buffer-local 'org-cycle-global-status)
3840 (defvar org-cycle-subtree-status nil)
3841 (make-variable-buffer-local 'org-cycle-subtree-status)
3843 ;;;###autoload
3844 (defun org-cycle (&optional arg)
3845 "Visibility cycling for Org-mode.
3847 - When this function is called with a prefix argument, rotate the entire
3848 buffer through 3 states (global cycling)
3849 1. OVERVIEW: Show only top-level headlines.
3850 2. CONTENTS: Show all headlines of all levels, but no body text.
3851 3. SHOW ALL: Show everything.
3852 When called with two C-c C-u prefixes, switch to the startup visibility,
3853 determined by the variable `org-startup-folded', and by any VISIBILITY
3854 properties in the buffer.
3856 - When point is at the beginning of a headline, rotate the subtree started
3857 by this line through 3 different states (local cycling)
3858 1. FOLDED: Only the main headline is shown.
3859 2. CHILDREN: The main headline and the direct children are shown.
3860 From this state, you can move to one of the children
3861 and zoom in further.
3862 3. SUBTREE: Show the entire subtree, including body text.
3864 - When there is a numeric prefix, go up to a heading with level ARG, do
3865 a `show-subtree' and return to the previous cursor position. If ARG
3866 is negative, go up that many levels.
3868 - When point is not at the beginning of a headline, execute the global
3869 binding for TAB, which is re-indenting the line. See the option
3870 `org-cycle-emulate-tab' for details.
3872 - Special case: if point is at the beginning of the buffer and there is
3873 no headline in line 1, this function will act as if called with prefix arg.
3874 But only if also the variable `org-cycle-global-at-bob' is t."
3875 (interactive "P")
3876 (org-load-modules-maybe)
3877 (let* ((outline-regexp
3878 (if (and (org-mode-p) org-cycle-include-plain-lists)
3879 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3880 outline-regexp))
3881 (bob-special (and org-cycle-global-at-bob (bobp)
3882 (not (looking-at outline-regexp))))
3883 (org-cycle-hook
3884 (if bob-special
3885 (delq 'org-optimize-window-after-visibility-change
3886 (copy-sequence org-cycle-hook))
3887 org-cycle-hook))
3888 (pos (point)))
3890 (if (or bob-special (equal arg '(4)))
3891 ;; special case: use global cycling
3892 (setq arg t))
3894 (cond
3896 ((equal arg '(16))
3897 (org-set-startup-visibility)
3898 (message "Startup visibility, plus VISIBILITY properties."))
3900 ((org-at-table-p 'any)
3901 ;; Enter the table or move to the next field in the table
3902 (or (org-table-recognize-table.el)
3903 (progn
3904 (if arg (org-table-edit-field t)
3905 (org-table-justify-field-maybe)
3906 (call-interactively 'org-table-next-field)))))
3908 ((eq arg t) ;; Global cycling
3910 (cond
3911 ((and (eq last-command this-command)
3912 (eq org-cycle-global-status 'overview))
3913 ;; We just created the overview - now do table of contents
3914 ;; This can be slow in very large buffers, so indicate action
3915 (message "CONTENTS...")
3916 (org-content)
3917 (message "CONTENTS...done")
3918 (setq org-cycle-global-status 'contents)
3919 (run-hook-with-args 'org-cycle-hook 'contents))
3921 ((and (eq last-command this-command)
3922 (eq org-cycle-global-status 'contents))
3923 ;; We just showed the table of contents - now show everything
3924 (show-all)
3925 (message "SHOW ALL")
3926 (setq org-cycle-global-status 'all)
3927 (run-hook-with-args 'org-cycle-hook 'all))
3930 ;; Default action: go to overview
3931 (org-overview)
3932 (message "OVERVIEW")
3933 (setq org-cycle-global-status 'overview)
3934 (run-hook-with-args 'org-cycle-hook 'overview))))
3936 ((and org-drawers org-drawer-regexp
3937 (save-excursion
3938 (beginning-of-line 1)
3939 (looking-at org-drawer-regexp)))
3940 ;; Toggle block visibility
3941 (org-flag-drawer
3942 (not (get-char-property (match-end 0) 'invisible))))
3944 ((integerp arg)
3945 ;; Show-subtree, ARG levels up from here.
3946 (save-excursion
3947 (org-back-to-heading)
3948 (outline-up-heading (if (< arg 0) (- arg)
3949 (- (funcall outline-level) arg)))
3950 (org-show-subtree)))
3952 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3953 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3954 ;; At a heading: rotate between three different views
3955 (org-back-to-heading)
3956 (let ((goal-column 0) eoh eol eos)
3957 ;; First, some boundaries
3958 (save-excursion
3959 (org-back-to-heading)
3960 (save-excursion
3961 (beginning-of-line 2)
3962 (while (and (not (eobp)) ;; this is like `next-line'
3963 (get-char-property (1- (point)) 'invisible))
3964 (beginning-of-line 2)) (setq eol (point)))
3965 (outline-end-of-heading) (setq eoh (point))
3966 (org-end-of-subtree t)
3967 (unless (eobp)
3968 (skip-chars-forward " \t\n")
3969 (beginning-of-line 1) ; in case this is an item
3971 (setq eos (1- (point))))
3972 ;; Find out what to do next and set `this-command'
3973 (cond
3974 ((= eos eoh)
3975 ;; Nothing is hidden behind this heading
3976 (message "EMPTY ENTRY")
3977 (setq org-cycle-subtree-status nil)
3978 (save-excursion
3979 (goto-char eos)
3980 (outline-next-heading)
3981 (if (org-invisible-p) (org-flag-heading nil))))
3982 ((or (>= eol eos)
3983 (not (string-match "\\S-" (buffer-substring eol eos))))
3984 ;; Entire subtree is hidden in one line: open it
3985 (org-show-entry)
3986 (show-children)
3987 (message "CHILDREN")
3988 (save-excursion
3989 (goto-char eos)
3990 (outline-next-heading)
3991 (if (org-invisible-p) (org-flag-heading nil)))
3992 (setq org-cycle-subtree-status 'children)
3993 (run-hook-with-args 'org-cycle-hook 'children))
3994 ((and (eq last-command this-command)
3995 (eq org-cycle-subtree-status 'children))
3996 ;; We just showed the children, now show everything.
3997 (org-show-subtree)
3998 (message "SUBTREE")
3999 (setq org-cycle-subtree-status 'subtree)
4000 (run-hook-with-args 'org-cycle-hook 'subtree))
4002 ;; Default action: hide the subtree.
4003 (hide-subtree)
4004 (message "FOLDED")
4005 (setq org-cycle-subtree-status 'folded)
4006 (run-hook-with-args 'org-cycle-hook 'folded)))))
4008 ;; TAB emulation and template completion
4009 (buffer-read-only (org-back-to-heading))
4011 ((org-try-structure-completion))
4013 ((org-try-cdlatex-tab))
4015 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4016 (or (not (bolp))
4017 (not (looking-at outline-regexp))))
4018 (call-interactively (global-key-binding "\t")))
4020 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4021 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4022 (or (and (eq org-cycle-emulate-tab 'white)
4023 (= (match-end 0) (point-at-eol)))
4024 (and (eq org-cycle-emulate-tab 'whitestart)
4025 (>= (match-end 0) pos))))
4027 (eq org-cycle-emulate-tab t))
4028 (call-interactively (global-key-binding "\t")))
4030 (t (save-excursion
4031 (org-back-to-heading)
4032 (org-cycle))))))
4034 ;;;###autoload
4035 (defun org-global-cycle (&optional arg)
4036 "Cycle the global visibility. For details see `org-cycle'.
4037 With C-u prefix arg, switch to startup visibility.
4038 With a numeric prefix, show all headlines up to that level."
4039 (interactive "P")
4040 (let ((org-cycle-include-plain-lists
4041 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4042 (cond
4043 ((integerp arg)
4044 (show-all)
4045 (hide-sublevels arg)
4046 (setq org-cycle-global-status 'contents))
4047 ((equal arg '(4))
4048 (org-set-startup-visibility)
4049 (message "Startup visibility, plus VISIBILITY properties."))
4051 (org-cycle '(4))))))
4053 (defun org-set-startup-visibility ()
4054 "Set the visibility required by startup options and properties."
4055 (cond
4056 ((eq org-startup-folded t)
4057 (org-cycle '(4)))
4058 ((eq org-startup-folded 'content)
4059 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4060 (org-cycle '(4)) (org-cycle '(4)))))
4061 (org-set-visibility-according-to-property 'no-cleanup)
4062 (org-cycle-hide-archived-subtrees 'all)
4063 (org-cycle-hide-drawers 'all)
4064 (org-cycle-show-empty-lines 'all))
4066 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4067 "Switch subtree visibilities according to :VISIBILITY: property."
4068 (interactive)
4069 (let (state)
4070 (save-excursion
4071 (goto-char (point-min))
4072 (while (re-search-forward
4073 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4074 nil t)
4075 (setq state (match-string 1))
4076 (save-excursion
4077 (org-back-to-heading t)
4078 (hide-subtree)
4079 (org-reveal)
4080 (cond
4081 ((equal state '("fold" "folded"))
4082 (hide-subtree))
4083 ((equal state "children")
4084 (org-show-hidden-entry)
4085 (show-children))
4086 ((equal state "content")
4087 (save-excursion
4088 (save-restriction
4089 (org-narrow-to-subtree)
4090 (org-content))))
4091 ((member state '("all" "showall"))
4092 (show-subtree)))))
4093 (unless no-cleanup
4094 (org-cycle-hide-archived-subtrees 'all)
4095 (org-cycle-hide-drawers 'all)
4096 (org-cycle-show-empty-lines 'all)))))
4098 (defun org-overview ()
4099 "Switch to overview mode, shoing only top-level headlines.
4100 Really, this shows all headlines with level equal or greater than the level
4101 of the first headline in the buffer. This is important, because if the
4102 first headline is not level one, then (hide-sublevels 1) gives confusing
4103 results."
4104 (interactive)
4105 (let ((level (save-excursion
4106 (goto-char (point-min))
4107 (if (re-search-forward (concat "^" outline-regexp) nil t)
4108 (progn
4109 (goto-char (match-beginning 0))
4110 (funcall outline-level))))))
4111 (and level (hide-sublevels level))))
4113 (defun org-content (&optional arg)
4114 "Show all headlines in the buffer, like a table of contents.
4115 With numerical argument N, show content up to level N."
4116 (interactive "P")
4117 (save-excursion
4118 ;; Visit all headings and show their offspring
4119 (and (integerp arg) (org-overview))
4120 (goto-char (point-max))
4121 (catch 'exit
4122 (while (and (progn (condition-case nil
4123 (outline-previous-visible-heading 1)
4124 (error (goto-char (point-min))))
4126 (looking-at outline-regexp))
4127 (if (integerp arg)
4128 (show-children (1- arg))
4129 (show-branches))
4130 (if (bobp) (throw 'exit nil))))))
4133 (defun org-optimize-window-after-visibility-change (state)
4134 "Adjust the window after a change in outline visibility.
4135 This function is the default value of the hook `org-cycle-hook'."
4136 (when (get-buffer-window (current-buffer))
4137 (cond
4138 ; ((eq state 'overview) (org-first-headline-recenter 1))
4139 ; ((eq state 'overview) (org-beginning-of-line))
4140 ((eq state 'content) nil)
4141 ((eq state 'all) nil)
4142 ((eq state 'folded) nil)
4143 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4144 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4146 (defun org-compact-display-after-subtree-move ()
4147 (let (beg end)
4148 (save-excursion
4149 (if (org-up-heading-safe)
4150 (progn
4151 (hide-subtree)
4152 (show-entry)
4153 (show-children)
4154 (org-cycle-show-empty-lines 'children)
4155 (org-cycle-hide-drawers 'children))
4156 (org-overview)))))
4158 (defun org-cycle-show-empty-lines (state)
4159 "Show empty lines above all visible headlines.
4160 The region to be covered depends on STATE when called through
4161 `org-cycle-hook'. Lisp program can use t for STATE to get the
4162 entire buffer covered. Note that an empty line is only shown if there
4163 are at least `org-cycle-separator-lines' empty lines before the headeline."
4164 (when (> org-cycle-separator-lines 0)
4165 (save-excursion
4166 (let* ((n org-cycle-separator-lines)
4167 (re (cond
4168 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4169 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4170 (t (let ((ns (number-to-string (- n 2))))
4171 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4172 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4173 beg end)
4174 (cond
4175 ((memq state '(overview contents t))
4176 (setq beg (point-min) end (point-max)))
4177 ((memq state '(children folded))
4178 (setq beg (point) end (progn (org-end-of-subtree t t)
4179 (beginning-of-line 2)
4180 (point)))))
4181 (when beg
4182 (goto-char beg)
4183 (while (re-search-forward re end t)
4184 (if (not (get-char-property (match-end 1) 'invisible))
4185 (outline-flag-region
4186 (match-beginning 1) (match-end 1) nil)))))))
4187 ;; Never hide empty lines at the end of the file.
4188 (save-excursion
4189 (goto-char (point-max))
4190 (outline-previous-heading)
4191 (outline-end-of-heading)
4192 (if (and (looking-at "[ \t\n]+")
4193 (= (match-end 0) (point-max)))
4194 (outline-flag-region (point) (match-end 0) nil))))
4196 (defun org-cycle-hide-drawers (state)
4197 "Re-hide all drawers after a visibility state change."
4198 (when (and (org-mode-p)
4199 (not (memq state '(overview folded))))
4200 (save-excursion
4201 (let* ((globalp (memq state '(contents all)))
4202 (beg (if globalp (point-min) (point)))
4203 (end (if globalp (point-max) (org-end-of-subtree t))))
4204 (goto-char beg)
4205 (while (re-search-forward org-drawer-regexp end t)
4206 (org-flag-drawer t))))))
4208 (defun org-flag-drawer (flag)
4209 (save-excursion
4210 (beginning-of-line 1)
4211 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4212 (let ((b (match-end 0))
4213 (outline-regexp org-outline-regexp))
4214 (if (re-search-forward
4215 "^[ \t]*:END:"
4216 (save-excursion (outline-next-heading) (point)) t)
4217 (outline-flag-region b (point-at-eol) flag)
4218 (error ":END: line missing"))))))
4220 (defun org-subtree-end-visible-p ()
4221 "Is the end of the current subtree visible?"
4222 (pos-visible-in-window-p
4223 (save-excursion (org-end-of-subtree t) (point))))
4225 (defun org-first-headline-recenter (&optional N)
4226 "Move cursor to the first headline and recenter the headline.
4227 Optional argument N means, put the headline into the Nth line of the window."
4228 (goto-char (point-min))
4229 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4230 (beginning-of-line)
4231 (recenter (prefix-numeric-value N))))
4233 ;;; Org-goto
4235 (defvar org-goto-window-configuration nil)
4236 (defvar org-goto-marker nil)
4237 (defvar org-goto-map
4238 (let ((map (make-sparse-keymap)))
4239 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4240 (while (setq cmd (pop cmds))
4241 (substitute-key-definition cmd cmd map global-map)))
4242 (suppress-keymap map)
4243 (org-defkey map "\C-m" 'org-goto-ret)
4244 (org-defkey map [(return)] 'org-goto-ret)
4245 (org-defkey map [(left)] 'org-goto-left)
4246 (org-defkey map [(right)] 'org-goto-right)
4247 (org-defkey map [(control ?g)] 'org-goto-quit)
4248 (org-defkey map "\C-i" 'org-cycle)
4249 (org-defkey map [(tab)] 'org-cycle)
4250 (org-defkey map [(down)] 'outline-next-visible-heading)
4251 (org-defkey map [(up)] 'outline-previous-visible-heading)
4252 (if org-goto-auto-isearch
4253 (if (fboundp 'define-key-after)
4254 (define-key-after map [t] 'org-goto-local-auto-isearch)
4255 nil)
4256 (org-defkey map "q" 'org-goto-quit)
4257 (org-defkey map "n" 'outline-next-visible-heading)
4258 (org-defkey map "p" 'outline-previous-visible-heading)
4259 (org-defkey map "f" 'outline-forward-same-level)
4260 (org-defkey map "b" 'outline-backward-same-level)
4261 (org-defkey map "u" 'outline-up-heading))
4262 (org-defkey map "/" 'org-occur)
4263 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4264 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4265 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4266 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4267 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4268 map))
4270 (defconst org-goto-help
4271 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4272 RET=jump to location [Q]uit and return to previous location
4273 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4275 (defvar org-goto-start-pos) ; dynamically scoped parameter
4277 ;; FIXME: Docstring doe not mention both interfaces
4278 (defun org-goto (&optional alternative-interface)
4279 "Look up a different location in the current file, keeping current visibility.
4281 When you want look-up or go to a different location in a document, the
4282 fastest way is often to fold the entire buffer and then dive into the tree.
4283 This method has the disadvantage, that the previous location will be folded,
4284 which may not be what you want.
4286 This command works around this by showing a copy of the current buffer
4287 in an indirect buffer, in overview mode. You can dive into the tree in
4288 that copy, use org-occur and incremental search to find a location.
4289 When pressing RET or `Q', the command returns to the original buffer in
4290 which the visibility is still unchanged. After RET is will also jump to
4291 the location selected in the indirect buffer and expose the
4292 the headline hierarchy above."
4293 (interactive "P")
4294 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4295 (org-refile-use-outline-path t)
4296 (interface
4297 (if (not alternative-interface)
4298 org-goto-interface
4299 (if (eq org-goto-interface 'outline)
4300 'outline-path-completion
4301 'outline)))
4302 (org-goto-start-pos (point))
4303 (selected-point
4304 (if (eq interface 'outline)
4305 (car (org-get-location (current-buffer) org-goto-help))
4306 (nth 3 (org-refile-get-location "Goto: ")))))
4307 (if selected-point
4308 (progn
4309 (org-mark-ring-push org-goto-start-pos)
4310 (goto-char selected-point)
4311 (if (or (org-invisible-p) (org-invisible-p2))
4312 (org-show-context 'org-goto)))
4313 (message "Quit"))))
4315 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4316 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4317 (defvar org-goto-local-auto-isearch-map) ; defined below
4319 (defun org-get-location (buf help)
4320 "Let the user select a location in the Org-mode buffer BUF.
4321 This function uses a recursive edit. It returns the selected position
4322 or nil."
4323 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4324 (isearch-hide-immediately nil)
4325 (isearch-search-fun-function
4326 (lambda () 'org-goto-local-search-forward-headings))
4327 (org-goto-selected-point org-goto-exit-command))
4328 (save-excursion
4329 (save-window-excursion
4330 (delete-other-windows)
4331 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4332 (switch-to-buffer
4333 (condition-case nil
4334 (make-indirect-buffer (current-buffer) "*org-goto*")
4335 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4336 (with-output-to-temp-buffer "*Help*"
4337 (princ help))
4338 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4339 (setq buffer-read-only nil)
4340 (let ((org-startup-truncated t)
4341 (org-startup-folded nil)
4342 (org-startup-align-all-tables nil))
4343 (org-mode)
4344 (org-overview))
4345 (setq buffer-read-only t)
4346 (if (and (boundp 'org-goto-start-pos)
4347 (integer-or-marker-p org-goto-start-pos))
4348 (let ((org-show-hierarchy-above t)
4349 (org-show-siblings t)
4350 (org-show-following-heading t))
4351 (goto-char org-goto-start-pos)
4352 (and (org-invisible-p) (org-show-context)))
4353 (goto-char (point-min)))
4354 (org-beginning-of-line)
4355 (message "Select location and press RET")
4356 (use-local-map org-goto-map)
4357 (recursive-edit)
4359 (kill-buffer "*org-goto*")
4360 (cons org-goto-selected-point org-goto-exit-command)))
4362 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4363 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4364 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4365 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4367 (defun org-goto-local-search-forward-headings (string bound noerror)
4368 "Search and make sure that anu matches are in headlines."
4369 (catch 'return
4370 (while (search-forward string bound noerror)
4371 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4372 (and (member :headline context)
4373 (not (member :tags context))))
4374 (throw 'return (point))))))
4376 (defun org-goto-local-auto-isearch ()
4377 "Start isearch."
4378 (interactive)
4379 (goto-char (point-min))
4380 (let ((keys (this-command-keys)))
4381 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4382 (isearch-mode t)
4383 (isearch-process-search-char (string-to-char keys)))))
4385 (defun org-goto-ret (&optional arg)
4386 "Finish `org-goto' by going to the new location."
4387 (interactive "P")
4388 (setq org-goto-selected-point (point)
4389 org-goto-exit-command 'return)
4390 (throw 'exit nil))
4392 (defun org-goto-left ()
4393 "Finish `org-goto' by going to the new location."
4394 (interactive)
4395 (if (org-on-heading-p)
4396 (progn
4397 (beginning-of-line 1)
4398 (setq org-goto-selected-point (point)
4399 org-goto-exit-command 'left)
4400 (throw 'exit nil))
4401 (error "Not on a heading")))
4403 (defun org-goto-right ()
4404 "Finish `org-goto' by going to the new location."
4405 (interactive)
4406 (if (org-on-heading-p)
4407 (progn
4408 (setq org-goto-selected-point (point)
4409 org-goto-exit-command 'right)
4410 (throw 'exit nil))
4411 (error "Not on a heading")))
4413 (defun org-goto-quit ()
4414 "Finish `org-goto' without cursor motion."
4415 (interactive)
4416 (setq org-goto-selected-point nil)
4417 (setq org-goto-exit-command 'quit)
4418 (throw 'exit nil))
4420 ;;; Indirect buffer display of subtrees
4422 (defvar org-indirect-dedicated-frame nil
4423 "This is the frame being used for indirect tree display.")
4424 (defvar org-last-indirect-buffer nil)
4426 (defun org-tree-to-indirect-buffer (&optional arg)
4427 "Create indirect buffer and narrow it to current subtree.
4428 With numerical prefix ARG, go up to this level and then take that tree.
4429 If ARG is negative, go up that many levels.
4430 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4431 indirect buffer previously made with this command, to avoid proliferation of
4432 indirect buffers. However, when you call the command with a `C-u' prefix, or
4433 when `org-indirect-buffer-display' is `new-frame', the last buffer
4434 is kept so that you can work with several indirect buffers at the same time.
4435 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4436 requests that a new frame be made for the new buffer, so that the dedicated
4437 frame is not changed."
4438 (interactive "P")
4439 (let ((cbuf (current-buffer))
4440 (cwin (selected-window))
4441 (pos (point))
4442 beg end level heading ibuf)
4443 (save-excursion
4444 (org-back-to-heading t)
4445 (when (numberp arg)
4446 (setq level (org-outline-level))
4447 (if (< arg 0) (setq arg (+ level arg)))
4448 (while (> (setq level (org-outline-level)) arg)
4449 (outline-up-heading 1 t)))
4450 (setq beg (point)
4451 heading (org-get-heading))
4452 (org-end-of-subtree t) (setq end (point)))
4453 (if (and (buffer-live-p org-last-indirect-buffer)
4454 (not (eq org-indirect-buffer-display 'new-frame))
4455 (not arg))
4456 (kill-buffer org-last-indirect-buffer))
4457 (setq ibuf (org-get-indirect-buffer cbuf)
4458 org-last-indirect-buffer ibuf)
4459 (cond
4460 ((or (eq org-indirect-buffer-display 'new-frame)
4461 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4462 (select-frame (make-frame))
4463 (delete-other-windows)
4464 (switch-to-buffer ibuf)
4465 (org-set-frame-title heading))
4466 ((eq org-indirect-buffer-display 'dedicated-frame)
4467 (raise-frame
4468 (select-frame (or (and org-indirect-dedicated-frame
4469 (frame-live-p org-indirect-dedicated-frame)
4470 org-indirect-dedicated-frame)
4471 (setq org-indirect-dedicated-frame (make-frame)))))
4472 (delete-other-windows)
4473 (switch-to-buffer ibuf)
4474 (org-set-frame-title (concat "Indirect: " heading)))
4475 ((eq org-indirect-buffer-display 'current-window)
4476 (switch-to-buffer ibuf))
4477 ((eq org-indirect-buffer-display 'other-window)
4478 (pop-to-buffer ibuf))
4479 (t (error "Invalid value.")))
4480 (if (featurep 'xemacs)
4481 (save-excursion (org-mode) (turn-on-font-lock)))
4482 (narrow-to-region beg end)
4483 (show-all)
4484 (goto-char pos)
4485 (and (window-live-p cwin) (select-window cwin))))
4487 (defun org-get-indirect-buffer (&optional buffer)
4488 (setq buffer (or buffer (current-buffer)))
4489 (let ((n 1) (base (buffer-name buffer)) bname)
4490 (while (buffer-live-p
4491 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4492 (setq n (1+ n)))
4493 (condition-case nil
4494 (make-indirect-buffer buffer bname 'clone)
4495 (error (make-indirect-buffer buffer bname)))))
4497 (defun org-set-frame-title (title)
4498 "Set the title of the current frame to the string TITLE."
4499 ;; FIXME: how to name a single frame in XEmacs???
4500 (unless (featurep 'xemacs)
4501 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4503 ;;;; Structure editing
4505 ;;; Inserting headlines
4507 (defun org-insert-heading (&optional force-heading)
4508 "Insert a new heading or item with same depth at point.
4509 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4510 If point is at the beginning of a headline, insert a sibling before the
4511 current headline. If point is not at the beginning, do not split the line,
4512 but create the new hedline after the current line."
4513 (interactive "P")
4514 (if (= (buffer-size) 0)
4515 (insert "\n* ")
4516 (when (or force-heading (not (org-insert-item)))
4517 (let* ((head (save-excursion
4518 (condition-case nil
4519 (progn
4520 (org-back-to-heading)
4521 (match-string 0))
4522 (error "*"))))
4523 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4524 pos)
4525 (cond
4526 ((and (org-on-heading-p) (bolp)
4527 (or (bobp)
4528 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4529 ;; insert before the current line
4530 (open-line (if blank 2 1)))
4531 ((and (bolp)
4532 (or (bobp)
4533 (save-excursion
4534 (backward-char 1) (not (org-invisible-p)))))
4535 ;; insert right here
4536 nil)
4538 ;; in the middle of the line
4539 (org-show-entry)
4540 (let ((split
4541 (org-get-alist-option org-M-RET-may-split-line 'headline))
4542 tags pos)
4543 (if (org-on-heading-p)
4544 (progn
4545 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4546 (setq tags (and (match-end 2) (match-string 2)))
4547 (and (match-end 1)
4548 (delete-region (match-beginning 1) (match-end 1)))
4549 (setq pos (point-at-bol))
4550 (or split (end-of-line 1))
4551 (delete-horizontal-space)
4552 (newline (if blank 2 1))
4553 (when tags
4554 (save-excursion
4555 (goto-char pos)
4556 (end-of-line 1)
4557 (insert " " tags)
4558 (org-set-tags nil 'align))))
4559 (or split (end-of-line 1))
4560 (newline (if blank 2 1))))))
4561 (insert head) (just-one-space)
4562 (setq pos (point))
4563 (end-of-line 1)
4564 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4565 (run-hooks 'org-insert-heading-hook)))))
4567 (defun org-get-heading (&optional no-tags)
4568 "Return the heading of the current entry, without the stars."
4569 (save-excursion
4570 (org-back-to-heading t)
4571 (if (looking-at
4572 (if no-tags
4573 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4574 "\\*+[ \t]+\\([^\r\n]*\\)"))
4575 (match-string 1) "")))
4577 (defun org-insert-heading-after-current ()
4578 "Insert a new heading with same level as current, after current subtree."
4579 (interactive)
4580 (org-back-to-heading)
4581 (org-insert-heading)
4582 (org-move-subtree-down)
4583 (end-of-line 1))
4585 (defun org-insert-todo-heading (arg)
4586 "Insert a new heading with the same level and TODO state as current heading.
4587 If the heading has no TODO state, or if the state is DONE, use the first
4588 state (TODO by default). Also with prefix arg, force first state."
4589 (interactive "P")
4590 (when (not (org-insert-item 'checkbox))
4591 (org-insert-heading)
4592 (save-excursion
4593 (org-back-to-heading)
4594 (outline-previous-heading)
4595 (looking-at org-todo-line-regexp))
4596 (if (or arg
4597 (not (match-beginning 2))
4598 (member (match-string 2) org-done-keywords))
4599 (insert (car org-todo-keywords-1) " ")
4600 (insert (match-string 2) " "))
4601 (when org-provide-todo-statistics
4602 (org-update-parent-todo-statistics))))
4604 (defun org-insert-subheading (arg)
4605 "Insert a new subheading and demote it.
4606 Works for outline headings and for plain lists alike."
4607 (interactive "P")
4608 (org-insert-heading arg)
4609 (cond
4610 ((org-on-heading-p) (org-do-demote))
4611 ((org-at-item-p) (org-indent-item 1))))
4613 (defun org-insert-todo-subheading (arg)
4614 "Insert a new subheading with TODO keyword or checkbox and demote it.
4615 Works for outline headings and for plain lists alike."
4616 (interactive "P")
4617 (org-insert-todo-heading arg)
4618 (cond
4619 ((org-on-heading-p) (org-do-demote))
4620 ((org-at-item-p) (org-indent-item 1))))
4622 ;;; Promotion and Demotion
4624 (defun org-promote-subtree ()
4625 "Promote the entire subtree.
4626 See also `org-promote'."
4627 (interactive)
4628 (save-excursion
4629 (org-map-tree 'org-promote))
4630 (org-fix-position-after-promote))
4632 (defun org-demote-subtree ()
4633 "Demote the entire subtree. See `org-demote'.
4634 See also `org-promote'."
4635 (interactive)
4636 (save-excursion
4637 (org-map-tree 'org-demote))
4638 (org-fix-position-after-promote))
4641 (defun org-do-promote ()
4642 "Promote the current heading higher up the tree.
4643 If the region is active in `transient-mark-mode', promote all headings
4644 in the region."
4645 (interactive)
4646 (save-excursion
4647 (if (org-region-active-p)
4648 (org-map-region 'org-promote (region-beginning) (region-end))
4649 (org-promote)))
4650 (org-fix-position-after-promote))
4652 (defun org-do-demote ()
4653 "Demote the current heading lower down the tree.
4654 If the region is active in `transient-mark-mode', demote all headings
4655 in the region."
4656 (interactive)
4657 (save-excursion
4658 (if (org-region-active-p)
4659 (org-map-region 'org-demote (region-beginning) (region-end))
4660 (org-demote)))
4661 (org-fix-position-after-promote))
4663 (defun org-fix-position-after-promote ()
4664 "Make sure that after pro/demotion cursor position is right."
4665 (let ((pos (point)))
4666 (when (save-excursion
4667 (beginning-of-line 1)
4668 (looking-at org-todo-line-regexp)
4669 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4670 (cond ((eobp) (insert " "))
4671 ((eolp) (insert " "))
4672 ((equal (char-after) ?\ ) (forward-char 1))))))
4674 (defun org-reduced-level (l)
4675 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4677 (defun org-get-valid-level (level &optional change)
4678 "Rectify a level change under the influence of `org-odd-levels-only'
4679 LEVEL is a current level, CHANGE is by how much the level should be
4680 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4681 even level numbers will become the next higher odd number."
4682 (if org-odd-levels-only
4683 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4684 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4685 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4686 (max 1 (+ level change))))
4688 (if (boundp 'define-obsolete-function-alias)
4689 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4690 (define-obsolete-function-alias 'org-get-legal-level
4691 'org-get-valid-level)
4692 (define-obsolete-function-alias 'org-get-legal-level
4693 'org-get-valid-level "23.1")))
4695 (defun org-promote ()
4696 "Promote the current heading higher up the tree.
4697 If the region is active in `transient-mark-mode', promote all headings
4698 in the region."
4699 (org-back-to-heading t)
4700 (let* ((level (save-match-data (funcall outline-level)))
4701 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4702 (diff (abs (- level (length up-head) -1))))
4703 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4704 (replace-match up-head nil t)
4705 ;; Fixup tag positioning
4706 (and org-auto-align-tags (org-set-tags nil t))
4707 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4709 (defun org-demote ()
4710 "Demote the current heading lower down the tree.
4711 If the region is active in `transient-mark-mode', demote all headings
4712 in the region."
4713 (org-back-to-heading t)
4714 (let* ((level (save-match-data (funcall outline-level)))
4715 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4716 (diff (abs (- level (length down-head) -1))))
4717 (replace-match down-head nil t)
4718 ;; Fixup tag positioning
4719 (and org-auto-align-tags (org-set-tags nil t))
4720 (if org-adapt-indentation (org-fixup-indentation diff))))
4722 (defun org-map-tree (fun)
4723 "Call FUN for every heading underneath the current one."
4724 (org-back-to-heading)
4725 (let ((level (funcall outline-level)))
4726 (save-excursion
4727 (funcall fun)
4728 (while (and (progn
4729 (outline-next-heading)
4730 (> (funcall outline-level) level))
4731 (not (eobp)))
4732 (funcall fun)))))
4734 (defun org-map-region (fun beg end)
4735 "Call FUN for every heading between BEG and END."
4736 (let ((org-ignore-region t))
4737 (save-excursion
4738 (setq end (copy-marker end))
4739 (goto-char beg)
4740 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4741 (< (point) end))
4742 (funcall fun))
4743 (while (and (progn
4744 (outline-next-heading)
4745 (< (point) end))
4746 (not (eobp)))
4747 (funcall fun)))))
4749 (defun org-fixup-indentation (diff)
4750 "Change the indentation in the current entry by DIFF
4751 However, if any line in the current entry has no indentation, or if it
4752 would end up with no indentation after the change, nothing at all is done."
4753 (save-excursion
4754 (let ((end (save-excursion (outline-next-heading)
4755 (point-marker)))
4756 (prohibit (if (> diff 0)
4757 "^\\S-"
4758 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4759 col)
4760 (unless (save-excursion (end-of-line 1)
4761 (re-search-forward prohibit end t))
4762 (while (and (< (point) end)
4763 (re-search-forward "^[ \t]+" end t))
4764 (goto-char (match-end 0))
4765 (setq col (current-column))
4766 (if (< diff 0) (replace-match ""))
4767 (indent-to (+ diff col))))
4768 (move-marker end nil))))
4770 (defun org-convert-to-odd-levels ()
4771 "Convert an org-mode file with all levels allowed to one with odd levels.
4772 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4773 level 5 etc."
4774 (interactive)
4775 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4776 (let ((org-odd-levels-only nil) n)
4777 (save-excursion
4778 (goto-char (point-min))
4779 (while (re-search-forward "^\\*\\*+ " nil t)
4780 (setq n (- (length (match-string 0)) 2))
4781 (while (>= (setq n (1- n)) 0)
4782 (org-demote))
4783 (end-of-line 1))))))
4786 (defun org-convert-to-oddeven-levels ()
4787 "Convert an org-mode file with only odd levels to one with odd and even levels.
4788 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4789 section with an even level, conversion would destroy the structure of the file. An error
4790 is signaled in this case."
4791 (interactive)
4792 (goto-char (point-min))
4793 ;; First check if there are no even levels
4794 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4795 (org-show-context t)
4796 (error "Not all levels are odd in this file. Conversion not possible."))
4797 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4798 (let ((org-odd-levels-only nil) n)
4799 (save-excursion
4800 (goto-char (point-min))
4801 (while (re-search-forward "^\\*\\*+ " nil t)
4802 (setq n (/ (1- (length (match-string 0))) 2))
4803 (while (>= (setq n (1- n)) 0)
4804 (org-promote))
4805 (end-of-line 1))))))
4807 (defun org-tr-level (n)
4808 "Make N odd if required."
4809 (if org-odd-levels-only (1+ (/ n 2)) n))
4811 ;;; Vertical tree motion, cutting and pasting of subtrees
4813 (defun org-move-subtree-up (&optional arg)
4814 "Move the current subtree up past ARG headlines of the same level."
4815 (interactive "p")
4816 (org-move-subtree-down (- (prefix-numeric-value arg))))
4818 (defun org-move-subtree-down (&optional arg)
4819 "Move the current subtree down past ARG headlines of the same level."
4820 (interactive "p")
4821 (setq arg (prefix-numeric-value arg))
4822 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4823 'outline-get-last-sibling))
4824 (ins-point (make-marker))
4825 (cnt (abs arg))
4826 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4827 ;; Select the tree
4828 (org-back-to-heading)
4829 (setq beg0 (point))
4830 (save-excursion
4831 (setq ne-beg (org-back-over-empty-lines))
4832 (setq beg (point)))
4833 (save-match-data
4834 (save-excursion (outline-end-of-heading)
4835 (setq folded (org-invisible-p)))
4836 (outline-end-of-subtree))
4837 (outline-next-heading)
4838 (setq ne-end (org-back-over-empty-lines))
4839 (setq end (point))
4840 (goto-char beg0)
4841 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4842 ;; include less whitespace
4843 (save-excursion
4844 (goto-char beg)
4845 (forward-line (- ne-beg ne-end))
4846 (setq beg (point))))
4847 ;; Find insertion point, with error handling
4848 (while (> cnt 0)
4849 (or (and (funcall movfunc) (looking-at outline-regexp))
4850 (progn (goto-char beg0)
4851 (error "Cannot move past superior level or buffer limit")))
4852 (setq cnt (1- cnt)))
4853 (if (> arg 0)
4854 ;; Moving forward - still need to move over subtree
4855 (progn (org-end-of-subtree t t)
4856 (save-excursion
4857 (org-back-over-empty-lines)
4858 (or (bolp) (newline)))))
4859 (setq ne-ins (org-back-over-empty-lines))
4860 (move-marker ins-point (point))
4861 (setq txt (buffer-substring beg end))
4862 (org-save-markers-in-region beg end)
4863 (delete-region beg end)
4864 (outline-flag-region (1- beg) beg nil)
4865 (outline-flag-region (1- (point)) (point) nil)
4866 (let ((bbb (point)))
4867 (insert-before-markers txt)
4868 (org-reinstall-markers-in-region bbb)
4869 (move-marker ins-point bbb))
4870 (or (bolp) (insert "\n"))
4871 (setq ins-end (point))
4872 (goto-char ins-point)
4873 (org-skip-whitespace)
4874 (when (and (< arg 0)
4875 (org-first-sibling-p)
4876 (> ne-ins ne-beg))
4877 ;; Move whitespace back to beginning
4878 (save-excursion
4879 (goto-char ins-end)
4880 (let ((kill-whole-line t))
4881 (kill-line (- ne-ins ne-beg)) (point)))
4882 (insert (make-string (- ne-ins ne-beg) ?\n)))
4883 (move-marker ins-point nil)
4884 (org-compact-display-after-subtree-move)
4885 (unless folded
4886 (org-show-entry)
4887 (show-children)
4888 (org-cycle-hide-drawers 'children))))
4890 (defvar org-subtree-clip ""
4891 "Clipboard for cut and paste of subtrees.
4892 This is actually only a copy of the kill, because we use the normal kill
4893 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4895 (defvar org-subtree-clip-folded nil
4896 "Was the last copied subtree folded?
4897 This is used to fold the tree back after pasting.")
4899 (defun org-cut-subtree (&optional n)
4900 "Cut the current subtree into the clipboard.
4901 With prefix arg N, cut this many sequential subtrees.
4902 This is a short-hand for marking the subtree and then cutting it."
4903 (interactive "p")
4904 (org-copy-subtree n 'cut))
4906 (defun org-copy-subtree (&optional n cut force-store-markers)
4907 "Cut the current subtree into the clipboard.
4908 With prefix arg N, cut this many sequential subtrees.
4909 This is a short-hand for marking the subtree and then copying it.
4910 If CUT is non-nil, actually cut the subtree.
4911 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4912 of some markers in the region, even if CUT is non-nil. This is
4913 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4914 (interactive "p")
4915 (let (beg end folded (beg0 (point)))
4916 (if (interactive-p)
4917 (org-back-to-heading nil) ; take what looks like a subtree
4918 (org-back-to-heading t)) ; take what is really there
4919 (org-back-over-empty-lines)
4920 (setq beg (point))
4921 (skip-chars-forward " \t\r\n")
4922 (save-match-data
4923 (save-excursion (outline-end-of-heading)
4924 (setq folded (org-invisible-p)))
4925 (condition-case nil
4926 (outline-forward-same-level (1- n))
4927 (error nil))
4928 (org-end-of-subtree t t))
4929 (org-back-over-empty-lines)
4930 (setq end (point))
4931 (goto-char beg0)
4932 (when (> end beg)
4933 (setq org-subtree-clip-folded folded)
4934 (when (or cut force-store-markers)
4935 (org-save-markers-in-region beg end))
4936 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4937 (setq org-subtree-clip (current-kill 0))
4938 (message "%s: Subtree(s) with %d characters"
4939 (if cut "Cut" "Copied")
4940 (length org-subtree-clip)))))
4942 (defun org-paste-subtree (&optional level tree)
4943 "Paste the clipboard as a subtree, with modification of headline level.
4944 The entire subtree is promoted or demoted in order to match a new headline
4945 level. By default, the new level is derived from the visible headings
4946 before and after the insertion point, and taken to be the inferior headline
4947 level of the two. So if the previous visible heading is level 3 and the
4948 next is level 4 (or vice versa), level 4 will be used for insertion.
4949 This makes sure that the subtree remains an independent subtree and does
4950 not swallow low level entries.
4952 You can also force a different level, either by using a numeric prefix
4953 argument, or by inserting the heading marker by hand. For example, if the
4954 cursor is after \"*****\", then the tree will be shifted to level 5.
4956 If you want to insert the tree as is, just use \\[yank].
4958 If optional TREE is given, use this text instead of the kill ring."
4959 (interactive "P")
4960 (unless (org-kill-is-subtree-p tree)
4961 (error "%s"
4962 (substitute-command-keys
4963 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4964 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4965 (^re (concat "^\\(" outline-regexp "\\)"))
4966 (re (concat "\\(" outline-regexp "\\)"))
4967 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4969 (old-level (if (string-match ^re txt)
4970 (- (match-end 0) (match-beginning 0) 1)
4971 -1))
4972 (force-level (cond (level (prefix-numeric-value level))
4973 ((string-match
4974 ^re_ (buffer-substring (point-at-bol) (point)))
4975 (- (match-end 1) (match-beginning 1)))
4976 (t nil)))
4977 (previous-level (save-excursion
4978 (condition-case nil
4979 (progn
4980 (outline-previous-visible-heading 1)
4981 (if (looking-at re)
4982 (- (match-end 0) (match-beginning 0) 1)
4984 (error 1))))
4985 (next-level (save-excursion
4986 (condition-case nil
4987 (progn
4988 (or (looking-at outline-regexp)
4989 (outline-next-visible-heading 1))
4990 (if (looking-at re)
4991 (- (match-end 0) (match-beginning 0) 1)
4993 (error 1))))
4994 (new-level (or force-level (max previous-level next-level)))
4995 (shift (if (or (= old-level -1)
4996 (= new-level -1)
4997 (= old-level new-level))
4999 (- new-level old-level)))
5000 (delta (if (> shift 0) -1 1))
5001 (func (if (> shift 0) 'org-demote 'org-promote))
5002 (org-odd-levels-only nil)
5003 beg end)
5004 ;; Remove the forced level indicator
5005 (if force-level
5006 (delete-region (point-at-bol) (point)))
5007 ;; Paste
5008 (beginning-of-line 1)
5009 (org-back-over-empty-lines)
5010 (setq beg (point))
5011 (insert-before-markers txt)
5012 (unless (string-match "\n\\'" txt) (insert "\n"))
5013 (org-reinstall-markers-in-region beg)
5014 (setq end (point))
5015 (goto-char beg)
5016 (skip-chars-forward " \t\n\r")
5017 (setq beg (point))
5018 ;; Shift if necessary
5019 (unless (= shift 0)
5020 (save-restriction
5021 (narrow-to-region beg end)
5022 (while (not (= shift 0))
5023 (org-map-region func (point-min) (point-max))
5024 (setq shift (+ delta shift)))
5025 (goto-char (point-min))))
5026 (when (interactive-p)
5027 (message "Clipboard pasted as level %d subtree" new-level))
5028 (if (and kill-ring
5029 (eq org-subtree-clip (current-kill 0))
5030 org-subtree-clip-folded)
5031 ;; The tree was folded before it was killed/copied
5032 (hide-subtree))))
5034 (defun org-kill-is-subtree-p (&optional txt)
5035 "Check if the current kill is an outline subtree, or a set of trees.
5036 Returns nil if kill does not start with a headline, or if the first
5037 headline level is not the largest headline level in the tree.
5038 So this will actually accept several entries of equal levels as well,
5039 which is OK for `org-paste-subtree'.
5040 If optional TXT is given, check this string instead of the current kill."
5041 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5042 (start-level (and kill
5043 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5044 org-outline-regexp "\\)")
5045 kill)
5046 (- (match-end 2) (match-beginning 2) 1)))
5047 (re (concat "^" org-outline-regexp))
5048 (start (1+ (match-beginning 2))))
5049 (if (not start-level)
5050 (progn
5051 nil) ;; does not even start with a heading
5052 (catch 'exit
5053 (while (setq start (string-match re kill (1+ start)))
5054 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5055 (throw 'exit nil)))
5056 t))))
5058 (defvar org-markers-to-move nil
5059 "Markers that should be moved with a cut-and-paste operation.
5060 Those markers are stored together with their positions relative to
5061 the start of the region.")
5063 (defun org-save-markers-in-region (beg end)
5064 "Check markers in region.
5065 If these markers are between BEG and END, record their position relative
5066 to BEG, so that after moving the block of text, we can put the markers back
5067 into place.
5068 This function gets called just before an entry or tree gets cut from the
5069 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5070 called immediately, to move the markers with the entries."
5071 (setq org-markers-to-move nil)
5072 (when (featurep 'org-clock)
5073 (org-clock-save-markers-for-cut-and-paste beg end))
5074 (when (featurep 'org-agenda)
5075 (org-agenda-save-markers-for-cut-and-paste beg end)))
5077 (defun org-check-and-save-marker (marker beg end)
5078 "Check if MARKER is between BEG and END.
5079 If yes, remember the marker and the distance to BEG."
5080 (when (and (marker-buffer marker)
5081 (equal (marker-buffer marker) (current-buffer)))
5082 (if (and (>= marker beg) (< marker end))
5083 (push (cons marker (- marker beg)) org-markers-to-move))))
5085 (defun org-reinstall-markers-in-region (beg)
5086 "Move all remembered markers to their position relative to BEG."
5087 (mapc (lambda (x)
5088 (move-marker (car x) (+ beg (cdr x))))
5089 org-markers-to-move)
5090 (setq org-markers-to-move nil))
5092 (defun org-narrow-to-subtree ()
5093 "Narrow buffer to the current subtree."
5094 (interactive)
5095 (save-excursion
5096 (save-match-data
5097 (narrow-to-region
5098 (progn (org-back-to-heading) (point))
5099 (progn (org-end-of-subtree t t) (point))))))
5102 ;;; Outline Sorting
5104 (defun org-sort (with-case)
5105 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5106 Optional argument WITH-CASE means sort case-sensitively."
5107 (interactive "P")
5108 (if (org-at-table-p)
5109 (org-call-with-arg 'org-table-sort-lines with-case)
5110 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5112 (defun org-sort-remove-invisible (s)
5113 (remove-text-properties 0 (length s) org-rm-props s)
5114 (while (string-match org-bracket-link-regexp s)
5115 (setq s (replace-match (if (match-end 2)
5116 (match-string 3 s)
5117 (match-string 1 s)) t t s)))
5120 (defvar org-priority-regexp) ; defined later in the file
5122 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5123 "Sort entries on a certain level of an outline tree.
5124 If there is an active region, the entries in the region are sorted.
5125 Else, if the cursor is before the first entry, sort the top-level items.
5126 Else, the children of the entry at point are sorted.
5128 Sorting can be alphabetically, numerically, and by date/time as given by
5129 the first time stamp in the entry. The command prompts for the sorting
5130 type unless it has been given to the function through the SORTING-TYPE
5131 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5132 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5133 called with point at the beginning of the record. It must return either
5134 a string or a number that should serve as the sorting key for that record.
5136 Comparing entries ignores case by default. However, with an optional argument
5137 WITH-CASE, the sorting considers case as well."
5138 (interactive "P")
5139 (let ((case-func (if with-case 'identity 'downcase))
5140 start beg end stars re re2
5141 txt what tmp plain-list-p)
5142 ;; Find beginning and end of region to sort
5143 (cond
5144 ((org-region-active-p)
5145 ;; we will sort the region
5146 (setq end (region-end)
5147 what "region")
5148 (goto-char (region-beginning))
5149 (if (not (org-on-heading-p)) (outline-next-heading))
5150 (setq start (point)))
5151 ((org-at-item-p)
5152 ;; we will sort this plain list
5153 (org-beginning-of-item-list) (setq start (point))
5154 (org-end-of-item-list) (setq end (point))
5155 (goto-char start)
5156 (setq plain-list-p t
5157 what "plain list"))
5158 ((or (org-on-heading-p)
5159 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5160 ;; we will sort the children of the current headline
5161 (org-back-to-heading)
5162 (setq start (point)
5163 end (progn (org-end-of-subtree t t)
5164 (org-back-over-empty-lines)
5165 (point))
5166 what "children")
5167 (goto-char start)
5168 (show-subtree)
5169 (outline-next-heading))
5171 ;; we will sort the top-level entries in this file
5172 (goto-char (point-min))
5173 (or (org-on-heading-p) (outline-next-heading))
5174 (setq start (point) end (point-max) what "top-level")
5175 (goto-char start)
5176 (show-all)))
5178 (setq beg (point))
5179 (if (>= beg end) (error "Nothing to sort"))
5181 (unless plain-list-p
5182 (looking-at "\\(\\*+\\)")
5183 (setq stars (match-string 1)
5184 re (concat "^" (regexp-quote stars) " +")
5185 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5186 txt (buffer-substring beg end))
5187 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5188 (if (and (not (equal stars "*")) (string-match re2 txt))
5189 (error "Region to sort contains a level above the first entry")))
5191 (unless sorting-type
5192 (message
5193 (if plain-list-p
5194 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5195 "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:")
5196 what)
5197 (setq sorting-type (read-char-exclusive))
5199 (and (= (downcase sorting-type) ?f)
5200 (setq getkey-func
5201 (completing-read "Sort using function: "
5202 obarray 'fboundp t nil nil))
5203 (setq getkey-func (intern getkey-func)))
5205 (and (= (downcase sorting-type) ?r)
5206 (setq property
5207 (completing-read "Property: "
5208 (mapcar 'list (org-buffer-property-keys t))
5209 nil t))))
5211 (message "Sorting entries...")
5213 (save-restriction
5214 (narrow-to-region start end)
5216 (let ((dcst (downcase sorting-type))
5217 (now (current-time)))
5218 (sort-subr
5219 (/= dcst sorting-type)
5220 ;; This function moves to the beginning character of the "record" to
5221 ;; be sorted.
5222 (if plain-list-p
5223 (lambda nil
5224 (if (org-at-item-p) t (goto-char (point-max))))
5225 (lambda nil
5226 (if (re-search-forward re nil t)
5227 (goto-char (match-beginning 0))
5228 (goto-char (point-max)))))
5229 ;; This function moves to the last character of the "record" being
5230 ;; sorted.
5231 (if plain-list-p
5232 'org-end-of-item
5233 (lambda nil
5234 (save-match-data
5235 (condition-case nil
5236 (outline-forward-same-level 1)
5237 (error
5238 (goto-char (point-max)))))))
5240 ;; This function returns the value that gets sorted against.
5241 (if plain-list-p
5242 (lambda nil
5243 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5244 (cond
5245 ((= dcst ?n)
5246 (string-to-number (buffer-substring (match-end 0)
5247 (point-at-eol))))
5248 ((= dcst ?a)
5249 (buffer-substring (match-end 0) (point-at-eol)))
5250 ((= dcst ?t)
5251 (if (re-search-forward org-ts-regexp
5252 (point-at-eol) t)
5253 (org-time-string-to-time (match-string 0))
5254 now))
5255 ((= dcst ?f)
5256 (if getkey-func
5257 (progn
5258 (setq tmp (funcall getkey-func))
5259 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5260 tmp)
5261 (error "Invalid key function `%s'" getkey-func)))
5262 (t (error "Invalid sorting type `%c'" sorting-type)))))
5263 (lambda nil
5264 (cond
5265 ((= dcst ?n)
5266 (if (looking-at outline-regexp)
5267 (string-to-number (buffer-substring (match-end 0)
5268 (point-at-eol)))
5269 nil))
5270 ((= dcst ?a)
5271 (funcall case-func (buffer-substring (point-at-bol)
5272 (point-at-eol))))
5273 ((= dcst ?t)
5274 (if (re-search-forward org-ts-regexp
5275 (save-excursion
5276 (forward-line 2)
5277 (point)) t)
5278 (org-time-string-to-time (match-string 0))
5279 now))
5280 ((= dcst ?p)
5281 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5282 (string-to-char (match-string 2))
5283 org-default-priority))
5284 ((= dcst ?r)
5285 (or (org-entry-get nil property) ""))
5286 ((= dcst ?o)
5287 (if (looking-at org-complex-heading-regexp)
5288 (- 9999 (length (member (match-string 2)
5289 org-todo-keywords-1)))))
5290 ((= dcst ?f)
5291 (if getkey-func
5292 (progn
5293 (setq tmp (funcall getkey-func))
5294 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5295 tmp)
5296 (error "Invalid key function `%s'" getkey-func)))
5297 (t (error "Invalid sorting type `%c'" sorting-type)))))
5299 (cond
5300 ((= dcst ?a) 'string<)
5301 ((= dcst ?t) 'time-less-p)
5302 (t nil)))))
5303 (message "Sorting entries...done")))
5305 (defun org-do-sort (table what &optional with-case sorting-type)
5306 "Sort TABLE of WHAT according to SORTING-TYPE.
5307 The user will be prompted for the SORTING-TYPE if the call to this
5308 function does not specify it. WHAT is only for the prompt, to indicate
5309 what is being sorted. The sorting key will be extracted from
5310 the car of the elements of the table.
5311 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5312 (unless sorting-type
5313 (message
5314 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5315 what)
5316 (setq sorting-type (read-char-exclusive)))
5317 (let ((dcst (downcase sorting-type))
5318 extractfun comparefun)
5319 ;; Define the appropriate functions
5320 (cond
5321 ((= dcst ?n)
5322 (setq extractfun 'string-to-number
5323 comparefun (if (= dcst sorting-type) '< '>)))
5324 ((= dcst ?a)
5325 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5326 (lambda(x) (downcase (org-sort-remove-invisible x))))
5327 comparefun (if (= dcst sorting-type)
5328 'string<
5329 (lambda (a b) (and (not (string< a b))
5330 (not (string= a b)))))))
5331 ((= dcst ?t)
5332 (setq extractfun
5333 (lambda (x)
5334 (if (string-match org-ts-regexp x)
5335 (time-to-seconds
5336 (org-time-string-to-time (match-string 0 x)))
5338 comparefun (if (= dcst sorting-type) '< '>)))
5339 (t (error "Invalid sorting type `%c'" sorting-type)))
5341 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5342 table)
5343 (lambda (a b) (funcall comparefun (car a) (car b))))))
5345 ;;; Editing source examples
5347 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5348 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5349 (defvar org-edit-src-force-single-line nil)
5350 (defvar org-edit-src-from-org-mode nil)
5352 (define-minor-mode org-exit-edit-mode
5353 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5355 (defun org-edit-src-code ()
5356 "Edit the source code example at point.
5357 An indirect buffer is created, and that buffer is then narrowed to the
5358 example at point and switched to the correct language mode. When done,
5359 exit by killing the buffer with \\[org-edit-src-exit]."
5360 (interactive)
5361 (let ((line (org-current-line))
5362 (case-fold-search t)
5363 (msg (substitute-command-keys
5364 "Edit, then exit with C-c ' (C-c and single quote)"))
5365 (info (org-edit-src-find-region-and-lang))
5366 (org-mode-p (eq major-mode 'org-mode))
5367 beg end lang lang-f single)
5368 (if (not info)
5370 (setq beg (nth 0 info)
5371 end (nth 1 info)
5372 lang (nth 2 info)
5373 single (nth 3 info)
5374 lang-f (intern (concat lang "-mode")))
5375 (unless (functionp lang-f)
5376 (error "No such language mode: %s" lang-f))
5377 (goto-line line)
5378 (if (get-buffer "*Org Edit Src Example*")
5379 (kill-buffer "*Org Edit Src Example*"))
5380 (switch-to-buffer (make-indirect-buffer (current-buffer)
5381 "*Org Edit Src Example*"))
5382 (narrow-to-region beg end)
5383 (remove-text-properties beg end '(display nil invisible nil
5384 intangible nil))
5385 (let ((org-inhibit-startup t))
5386 (funcall lang-f))
5387 (set (make-local-variable 'org-edit-src-force-single-line) single)
5388 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5389 (when org-mode-p
5390 (goto-char (point-min))
5391 (while (re-search-forward "^," nil t)
5392 (replace-match "")))
5393 (goto-line line)
5394 (org-exit-edit-mode)
5395 (org-set-local 'header-line-format msg)
5396 (message "%s" msg)
5397 t)))
5399 (defun org-edit-src-find-region-and-lang ()
5400 "Find the region and language for a local edit.
5401 Return a list with beginning and end of the region, a string representing
5402 the language, a switch telling of the content should be in a single line."
5403 (let ((re-list
5405 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5406 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5407 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5408 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5409 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5410 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5411 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5412 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5413 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5414 ("^#\\+html:" "\n" "html" single-line)
5415 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5416 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5417 ("^#\\+latex:" "\n" "latex" single-line)
5418 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5419 ("^#\\+ascii:" "\n" "ascii" single-line)
5421 (pos (point))
5422 re re1 re2 single beg end lang)
5423 (catch 'exit
5424 (while (setq entry (pop re-list))
5425 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5426 single (nth 3 entry))
5427 (save-excursion
5428 (if (or (looking-at re1)
5429 (re-search-backward re1 nil t))
5430 (progn
5431 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5432 (if (and (re-search-forward re2 nil t)
5433 (>= (match-end 0) pos))
5434 (throw 'exit (list beg (match-beginning 0) lang single))))
5435 (if (or (looking-at re2)
5436 (re-search-forward re2 nil t))
5437 (progn
5438 (setq end (match-beginning 0))
5439 (if (and (re-search-backward re1 nil t)
5440 (<= (match-beginning 0) pos))
5441 (throw 'exit
5442 (list (match-end 0) end
5443 (org-edit-src-get-lang lang) single)))))))))))
5445 (defun org-edit-src-get-lang (lang)
5446 "Extract the src language."
5447 (let ((m (match-string 0)))
5448 (cond
5449 ((stringp lang) lang)
5450 ((integerp lang) (match-string lang))
5451 ((and (eq lang lang)
5452 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5453 (match-string 1 m))
5454 ((and (eq lang lang)
5455 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5456 (match-string 1 m))
5457 (t "fundamental"))))
5459 (defun org-edit-src-exit ()
5460 "Exit special edit and protect problematic lines."
5461 (interactive)
5462 (unless (buffer-base-buffer (current-buffer))
5463 (error "This is not an indirect buffer, something is wrong..."))
5464 (unless (> (point-min) 1)
5465 (error "This buffer is not narrowed, something is wrong..."))
5466 (goto-char (point-min))
5467 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5468 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5469 (when (org-bound-and-true-p org-edit-src-force-single-line)
5470 (goto-char (point-min))
5471 (while (re-search-forward "\n" nil t)
5472 (replace-match " "))
5473 (goto-char (point-min))
5474 (if (looking-at "\\s-*") (replace-match " "))
5475 (if (re-search-forward "\\s-+\\'" nil t)
5476 (replace-match "")))
5477 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5478 (goto-char (point-min))
5479 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5480 (replace-match ",\\1"))
5481 (when font-lock-mode
5482 (font-lock-unfontify-region (point-min) (point-max)))
5483 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5484 (kill-buffer (current-buffer)))
5486 ;;;; Plain list items, including checkboxes
5488 ;;; Plain list items
5490 (defun org-at-item-p ()
5491 "Is point in a line starting a hand-formatted item?"
5492 (let ((llt org-plain-list-ordered-item-terminator))
5493 (save-excursion
5494 (goto-char (point-at-bol))
5495 (looking-at
5496 (cond
5497 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5498 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5499 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5500 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5502 (defun org-in-item-p ()
5503 "It the cursor inside a plain list item.
5504 Does not have to be the first line."
5505 (save-excursion
5506 (condition-case nil
5507 (progn
5508 (org-beginning-of-item)
5509 (org-at-item-p)
5511 (error nil))))
5513 (defun org-insert-item (&optional checkbox)
5514 "Insert a new item at the current level.
5515 Return t when things worked, nil when we are not in an item."
5516 (when (save-excursion
5517 (condition-case nil
5518 (progn
5519 (org-beginning-of-item)
5520 (org-at-item-p)
5521 (if (org-invisible-p) (error "Invisible item"))
5523 (error nil)))
5524 (let* ((bul (match-string 0))
5525 (descp (save-excursion (goto-char (match-beginning 0))
5526 (beginning-of-line 1)
5527 (save-match-data
5528 (looking-at "[ \t]*.*? ::"))))
5529 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5530 (match-end 0)))
5531 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5532 pos)
5533 (if descp (setq checkbox nil))
5534 (cond
5535 ((and (org-at-item-p) (<= (point) eow))
5536 ;; before the bullet
5537 (beginning-of-line 1)
5538 (open-line (if blank 2 1)))
5539 ((<= (point) eow)
5540 (beginning-of-line 1))
5542 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5543 (end-of-line 1)
5544 (delete-horizontal-space))
5545 (newline (if blank 2 1))))
5546 (insert bul
5547 (if checkbox "[ ]" "")
5548 (if descp (concat (if checkbox " " "")
5549 (read-string "Term: ") " :: ") ""))
5550 (just-one-space)
5551 (setq pos (point))
5552 (end-of-line 1)
5553 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5554 (org-maybe-renumber-ordered-list)
5555 (and checkbox (org-update-checkbox-count-maybe))
5558 ;;; Checkboxes
5560 (defun org-at-item-checkbox-p ()
5561 "Is point at a line starting a plain-list item with a checklet?"
5562 (and (org-at-item-p)
5563 (save-excursion
5564 (goto-char (match-end 0))
5565 (skip-chars-forward " \t")
5566 (looking-at "\\[[- X]\\]"))))
5568 (defun org-toggle-checkbox (&optional arg)
5569 "Toggle the checkbox in the current line."
5570 (interactive "P")
5571 (catch 'exit
5572 (let (beg end status (firstnew 'unknown))
5573 (cond
5574 ((org-region-active-p)
5575 (setq beg (region-beginning) end (region-end)))
5576 ((org-on-heading-p)
5577 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5578 ((org-at-item-checkbox-p)
5579 (let ((pos (point)))
5580 (replace-match
5581 (cond (arg "[-]")
5582 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5583 (t "[ ]"))
5584 t t)
5585 (goto-char pos))
5586 (throw 'exit t))
5587 (t (error "Not at a checkbox or heading, and no active region")))
5588 (save-excursion
5589 (goto-char beg)
5590 (while (< (point) end)
5591 (when (org-at-item-checkbox-p)
5592 (setq status (equal (match-string 0) "[X]"))
5593 (when (eq firstnew 'unknown)
5594 (setq firstnew (not status)))
5595 (replace-match
5596 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5597 (beginning-of-line 2)))))
5598 (org-update-checkbox-count-maybe))
5600 (defun org-update-checkbox-count-maybe ()
5601 "Update checkbox statistics unless turned off by user."
5602 (when org-provide-checkbox-statistics
5603 (org-update-checkbox-count)))
5605 (defun org-update-checkbox-count (&optional all)
5606 "Update the checkbox statistics in the current section.
5607 This will find all statistic cookies like [57%] and [6/12] and update them
5608 with the current numbers. With optional prefix argument ALL, do this for
5609 the whole buffer."
5610 (interactive "P")
5611 (save-excursion
5612 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5613 (beg (condition-case nil
5614 (progn (outline-back-to-heading) (point))
5615 (error (point-min))))
5616 (end (move-marker (make-marker)
5617 (progn (outline-next-heading) (point))))
5618 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5619 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5620 (re-find (concat re "\\|" re-box))
5621 beg-cookie end-cookie is-percent c-on c-off lim
5622 eline curr-ind next-ind continue-from startsearch
5623 (cstat 0)
5625 (when all
5626 (goto-char (point-min))
5627 (outline-next-heading)
5628 (setq beg (point) end (point-max)))
5629 (goto-char end)
5630 ;; find each statistic cookie
5631 (while (re-search-backward re-find beg t)
5632 (setq beg-cookie (match-beginning 1)
5633 end-cookie (match-end 1)
5634 cstat (+ cstat (if end-cookie 1 0))
5635 startsearch (point-at-eol)
5636 continue-from (point-at-bol)
5637 is-percent (match-beginning 2)
5638 lim (cond
5639 ((org-on-heading-p) (outline-next-heading) (point))
5640 ((org-at-item-p) (org-end-of-item) (point))
5641 (t nil))
5642 c-on 0
5643 c-off 0)
5644 (when lim
5645 ;; find first checkbox for this cookie and gather
5646 ;; statistics from all that are at this indentation level
5647 (goto-char startsearch)
5648 (if (re-search-forward re-box lim t)
5649 (progn
5650 (org-beginning-of-item)
5651 (setq curr-ind (org-get-indentation))
5652 (setq next-ind curr-ind)
5653 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5654 (save-excursion (end-of-line) (setq eline (point)))
5655 (if (re-search-forward re-box eline t)
5656 (if (member (match-string 2) '("[ ]" "[-]"))
5657 (setq c-off (1+ c-off))
5658 (setq c-on (1+ c-on))
5661 (org-end-of-item)
5662 (setq next-ind (org-get-indentation))
5664 (goto-char continue-from)
5665 ;; update cookie
5666 (when end-cookie
5667 (delete-region beg-cookie end-cookie)
5668 (goto-char beg-cookie)
5669 (insert
5670 (if is-percent
5671 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5672 (format "[%d/%d]" c-on (+ c-on c-off)))))
5673 ;; update items checkbox if it has one
5674 (when (org-at-item-p)
5675 (org-beginning-of-item)
5676 (when (and (> (+ c-on c-off) 0)
5677 (re-search-forward re-box (point-at-eol) t))
5678 (setq beg-cookie (match-beginning 2)
5679 end-cookie (match-end 2))
5680 (delete-region beg-cookie end-cookie)
5681 (goto-char beg-cookie)
5682 (cond ((= c-off 0) (insert "[X]"))
5683 ((= c-on 0) (insert "[ ]"))
5684 (t (insert "[-]")))
5686 (goto-char continue-from))
5687 (when (interactive-p)
5688 (message "Checkbox satistics updated %s (%d places)"
5689 (if all "in entire file" "in current outline entry") cstat)))))
5691 (defun org-get-checkbox-statistics-face ()
5692 "Select the face for checkbox statistics.
5693 The face will be `org-done' when all relevant boxes are checked. Otherwise
5694 it will be `org-todo'."
5695 (if (match-end 1)
5696 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5697 (if (and (> (match-end 2) (match-beginning 2))
5698 (equal (match-string 2) (match-string 3)))
5699 'org-done
5700 'org-todo)))
5702 (defun org-get-indentation (&optional line)
5703 "Get the indentation of the current line, interpreting tabs.
5704 When LINE is given, assume it represents a line and compute its indentation."
5705 (if line
5706 (if (string-match "^ *" (org-remove-tabs line))
5707 (match-end 0))
5708 (save-excursion
5709 (beginning-of-line 1)
5710 (skip-chars-forward " \t")
5711 (current-column))))
5713 (defun org-remove-tabs (s &optional width)
5714 "Replace tabulators in S with spaces.
5715 Assumes that s is a single line, starting in column 0."
5716 (setq width (or width tab-width))
5717 (while (string-match "\t" s)
5718 (setq s (replace-match
5719 (make-string
5720 (- (* width (/ (+ (match-beginning 0) width) width))
5721 (match-beginning 0)) ?\ )
5722 t t s)))
5725 (defun org-fix-indentation (line ind)
5726 "Fix indentation in LINE.
5727 IND is a cons cell with target and minimum indentation.
5728 If the current indenation in LINE is smaller than the minimum,
5729 leave it alone. If it is larger than ind, set it to the target."
5730 (let* ((l (org-remove-tabs line))
5731 (i (org-get-indentation l))
5732 (i1 (car ind)) (i2 (cdr ind)))
5733 (if (>= i i2) (setq l (substring line i2)))
5734 (if (> i1 0)
5735 (concat (make-string i1 ?\ ) l)
5736 l)))
5738 (defun org-beginning-of-item ()
5739 "Go to the beginning of the current hand-formatted item.
5740 If the cursor is not in an item, throw an error."
5741 (interactive)
5742 (let ((pos (point))
5743 (limit (save-excursion
5744 (condition-case nil
5745 (progn
5746 (org-back-to-heading)
5747 (beginning-of-line 2) (point))
5748 (error (point-min)))))
5749 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5750 ind ind1)
5751 (if (org-at-item-p)
5752 (beginning-of-line 1)
5753 (beginning-of-line 1)
5754 (skip-chars-forward " \t")
5755 (setq ind (current-column))
5756 (if (catch 'exit
5757 (while t
5758 (beginning-of-line 0)
5759 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5761 (if (looking-at "[ \t]*$")
5762 (setq ind1 ind-empty)
5763 (skip-chars-forward " \t")
5764 (setq ind1 (current-column)))
5765 (if (< ind1 ind)
5766 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5768 (goto-char pos)
5769 (error "Not in an item")))))
5771 (defun org-end-of-item ()
5772 "Go to the end of the current hand-formatted item.
5773 If the cursor is not in an item, throw an error."
5774 (interactive)
5775 (let* ((pos (point))
5776 ind1
5777 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5778 (limit (save-excursion (outline-next-heading) (point)))
5779 (ind (save-excursion
5780 (org-beginning-of-item)
5781 (skip-chars-forward " \t")
5782 (current-column)))
5783 (end (catch 'exit
5784 (while t
5785 (beginning-of-line 2)
5786 (if (eobp) (throw 'exit (point)))
5787 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5788 (if (looking-at "[ \t]*$")
5789 (setq ind1 ind-empty)
5790 (skip-chars-forward " \t")
5791 (setq ind1 (current-column)))
5792 (if (<= ind1 ind)
5793 (throw 'exit (point-at-bol)))))))
5794 (if end
5795 (goto-char end)
5796 (goto-char pos)
5797 (error "Not in an item"))))
5799 (defun org-next-item ()
5800 "Move to the beginning of the next item in the current plain list.
5801 Error if not at a plain list, or if this is the last item in the list."
5802 (interactive)
5803 (let (ind ind1 (pos (point)))
5804 (org-beginning-of-item)
5805 (setq ind (org-get-indentation))
5806 (org-end-of-item)
5807 (setq ind1 (org-get-indentation))
5808 (unless (and (org-at-item-p) (= ind ind1))
5809 (goto-char pos)
5810 (error "On last item"))))
5812 (defun org-previous-item ()
5813 "Move to the beginning of the previous item in the current plain list.
5814 Error if not at a plain list, or if this is the first item in the list."
5815 (interactive)
5816 (let (beg ind ind1 (pos (point)))
5817 (org-beginning-of-item)
5818 (setq beg (point))
5819 (setq ind (org-get-indentation))
5820 (goto-char beg)
5821 (catch 'exit
5822 (while t
5823 (beginning-of-line 0)
5824 (if (looking-at "[ \t]*$")
5826 (if (<= (setq ind1 (org-get-indentation)) ind)
5827 (throw 'exit t)))))
5828 (condition-case nil
5829 (if (or (not (org-at-item-p))
5830 (< ind1 (1- ind)))
5831 (error "")
5832 (org-beginning-of-item))
5833 (error (goto-char pos)
5834 (error "On first item")))))
5836 (defun org-first-list-item-p ()
5837 "Is this heading the item in a plain list?"
5838 (unless (org-at-item-p)
5839 (error "Not at a plain list item"))
5840 (org-beginning-of-item)
5841 (= (point) (save-excursion (org-beginning-of-item-list))))
5843 (defun org-move-item-down ()
5844 "Move the plain list item at point down, i.e. swap with following item.
5845 Subitems (items with larger indentation) are considered part of the item,
5846 so this really moves item trees."
5847 (interactive)
5848 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5849 (org-beginning-of-item)
5850 (setq beg0 (point))
5851 (save-excursion
5852 (setq ne-beg (org-back-over-empty-lines))
5853 (setq beg (point)))
5854 (goto-char beg0)
5855 (setq ind (org-get-indentation))
5856 (org-end-of-item)
5857 (setq end0 (point))
5858 (setq ind1 (org-get-indentation))
5859 (setq ne-end (org-back-over-empty-lines))
5860 (setq end (point))
5861 (goto-char beg0)
5862 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5863 ;; include less whitespace
5864 (save-excursion
5865 (goto-char beg)
5866 (forward-line (- ne-beg ne-end))
5867 (setq beg (point))))
5868 (goto-char end0)
5869 (if (and (org-at-item-p) (= ind ind1))
5870 (progn
5871 (org-end-of-item)
5872 (org-back-over-empty-lines)
5873 (setq txt (buffer-substring beg end))
5874 (save-excursion
5875 (delete-region beg end))
5876 (setq pos (point))
5877 (insert txt)
5878 (goto-char pos) (org-skip-whitespace)
5879 (org-maybe-renumber-ordered-list))
5880 (goto-char pos)
5881 (error "Cannot move this item further down"))))
5883 (defun org-move-item-up (arg)
5884 "Move the plain list item at point up, i.e. swap with previous item.
5885 Subitems (items with larger indentation) are considered part of the item,
5886 so this really moves item trees."
5887 (interactive "p")
5888 (let (beg beg0 end ind ind1 (pos (point)) txt
5889 ne-beg ne-ins ins-end)
5890 (org-beginning-of-item)
5891 (setq beg0 (point))
5892 (setq ind (org-get-indentation))
5893 (save-excursion
5894 (setq ne-beg (org-back-over-empty-lines))
5895 (setq beg (point)))
5896 (goto-char beg0)
5897 (org-end-of-item)
5898 (setq end (point))
5899 (goto-char beg0)
5900 (catch 'exit
5901 (while t
5902 (beginning-of-line 0)
5903 (if (looking-at "[ \t]*$")
5904 (if org-empty-line-terminates-plain-lists
5905 (progn
5906 (goto-char pos)
5907 (error "Cannot move this item further up"))
5908 nil)
5909 (if (<= (setq ind1 (org-get-indentation)) ind)
5910 (throw 'exit t)))))
5911 (condition-case nil
5912 (org-beginning-of-item)
5913 (error (goto-char beg)
5914 (error "Cannot move this item further up")))
5915 (setq ind1 (org-get-indentation))
5916 (if (and (org-at-item-p) (= ind ind1))
5917 (progn
5918 (setq ne-ins (org-back-over-empty-lines))
5919 (setq txt (buffer-substring beg end))
5920 (save-excursion
5921 (delete-region beg end))
5922 (setq pos (point))
5923 (insert txt)
5924 (setq ins-end (point))
5925 (goto-char pos) (org-skip-whitespace)
5927 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5928 ;; Move whitespace back to beginning
5929 (save-excursion
5930 (goto-char ins-end)
5931 (let ((kill-whole-line t))
5932 (kill-line (- ne-ins ne-beg)) (point)))
5933 (insert (make-string (- ne-ins ne-beg) ?\n)))
5935 (org-maybe-renumber-ordered-list))
5936 (goto-char pos)
5937 (error "Cannot move this item further up"))))
5939 (defun org-maybe-renumber-ordered-list ()
5940 "Renumber the ordered list at point if setup allows it.
5941 This tests the user option `org-auto-renumber-ordered-lists' before
5942 doing the renumbering."
5943 (interactive)
5944 (when (and org-auto-renumber-ordered-lists
5945 (org-at-item-p))
5946 (if (match-beginning 3)
5947 (org-renumber-ordered-list 1)
5948 (org-fix-bullet-type))))
5950 (defun org-maybe-renumber-ordered-list-safe ()
5951 (condition-case nil
5952 (save-excursion
5953 (org-maybe-renumber-ordered-list))
5954 (error nil)))
5956 (defun org-cycle-list-bullet (&optional which)
5957 "Cycle through the different itemize/enumerate bullets.
5958 This cycle the entire list level through the sequence:
5960 `-' -> `+' -> `*' -> `1.' -> `1)'
5962 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5963 0 meand `-', 1 means `+' etc."
5964 (interactive "P")
5965 (org-preserve-lc
5966 (org-beginning-of-item-list)
5967 (org-at-item-p)
5968 (beginning-of-line 1)
5969 (let ((current (match-string 0))
5970 (prevp (eq which 'previous))
5971 new)
5972 (setq new (cond
5973 ((and (numberp which)
5974 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5975 ((string-match "-" current) (if prevp "1)" "+"))
5976 ((string-match "\\+" current)
5977 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5978 ((string-match "\\*" current) (if prevp "+" "1."))
5979 ((string-match "\\." current) (if prevp "*" "1)"))
5980 ((string-match ")" current) (if prevp "1." "-"))
5981 (t (error "This should not happen"))))
5982 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5983 (org-fix-bullet-type)
5984 (org-maybe-renumber-ordered-list))))
5986 (defun org-get-string-indentation (s)
5987 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5988 (let ((n -1) (i 0) (w tab-width) c)
5989 (catch 'exit
5990 (while (< (setq n (1+ n)) (length s))
5991 (setq c (aref s n))
5992 (cond ((= c ?\ ) (setq i (1+ i)))
5993 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5994 (t (throw 'exit t)))))
5997 (defun org-renumber-ordered-list (arg)
5998 "Renumber an ordered plain list.
5999 Cursor needs to be in the first line of an item, the line that starts
6000 with something like \"1.\" or \"2)\"."
6001 (interactive "p")
6002 (unless (and (org-at-item-p)
6003 (match-beginning 3))
6004 (error "This is not an ordered list"))
6005 (let ((line (org-current-line))
6006 (col (current-column))
6007 (ind (org-get-string-indentation
6008 (buffer-substring (point-at-bol) (match-beginning 3))))
6009 ;; (term (substring (match-string 3) -1))
6010 ind1 (n (1- arg))
6011 fmt)
6012 ;; find where this list begins
6013 (org-beginning-of-item-list)
6014 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6015 (setq fmt (concat "%d" (match-string 1)))
6016 (beginning-of-line 0)
6017 ;; walk forward and replace these numbers
6018 (catch 'exit
6019 (while t
6020 (catch 'next
6021 (beginning-of-line 2)
6022 (if (eobp) (throw 'exit nil))
6023 (if (looking-at "[ \t]*$") (throw 'next nil))
6024 (skip-chars-forward " \t") (setq ind1 (current-column))
6025 (if (> ind1 ind) (throw 'next t))
6026 (if (< ind1 ind) (throw 'exit t))
6027 (if (not (org-at-item-p)) (throw 'exit nil))
6028 (delete-region (match-beginning 2) (match-end 2))
6029 (goto-char (match-beginning 2))
6030 (insert (format fmt (setq n (1+ n)))))))
6031 (goto-line line)
6032 (org-move-to-column col)))
6034 (defun org-fix-bullet-type ()
6035 "Make sure all items in this list have the same bullet as the firsst item."
6036 (interactive)
6037 (unless (org-at-item-p) (error "This is not a list"))
6038 (let ((line (org-current-line))
6039 (col (current-column))
6040 (ind (current-indentation))
6041 ind1 bullet)
6042 ;; find where this list begins
6043 (org-beginning-of-item-list)
6044 (beginning-of-line 1)
6045 ;; find out what the bullet type is
6046 (looking-at "[ \t]*\\(\\S-+\\)")
6047 (setq bullet (match-string 1))
6048 ;; walk forward and replace these numbers
6049 (beginning-of-line 0)
6050 (catch 'exit
6051 (while t
6052 (catch 'next
6053 (beginning-of-line 2)
6054 (if (eobp) (throw 'exit nil))
6055 (if (looking-at "[ \t]*$") (throw 'next nil))
6056 (skip-chars-forward " \t") (setq ind1 (current-column))
6057 (if (> ind1 ind) (throw 'next t))
6058 (if (< ind1 ind) (throw 'exit t))
6059 (if (not (org-at-item-p)) (throw 'exit nil))
6060 (skip-chars-forward " \t")
6061 (looking-at "\\S-+")
6062 (replace-match bullet))))
6063 (goto-line line)
6064 (org-move-to-column col)
6065 (if (string-match "[0-9]" bullet)
6066 (org-renumber-ordered-list 1))))
6068 (defun org-beginning-of-item-list ()
6069 "Go to the beginning of the current item list.
6070 I.e. to the first item in this list."
6071 (interactive)
6072 (org-beginning-of-item)
6073 (let ((pos (point-at-bol))
6074 (ind (org-get-indentation))
6075 ind1)
6076 ;; find where this list begins
6077 (catch 'exit
6078 (while t
6079 (catch 'next
6080 (beginning-of-line 0)
6081 (if (looking-at "[ \t]*$")
6082 (throw (if (bobp) 'exit 'next) t))
6083 (skip-chars-forward " \t") (setq ind1 (current-column))
6084 (if (or (< ind1 ind)
6085 (and (= ind1 ind)
6086 (not (org-at-item-p)))
6087 (bobp))
6088 (throw 'exit t)
6089 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6090 (goto-char pos)))
6093 (defun org-end-of-item-list ()
6094 "Go to the end of the current item list.
6095 I.e. to the text after the last item."
6096 (interactive)
6097 (org-beginning-of-item)
6098 (let ((pos (point-at-bol))
6099 (ind (org-get-indentation))
6100 ind1)
6101 ;; find where this list begins
6102 (catch 'exit
6103 (while t
6104 (catch 'next
6105 (beginning-of-line 2)
6106 (if (looking-at "[ \t]*$")
6107 (throw (if (eobp) 'exit 'next) t))
6108 (skip-chars-forward " \t") (setq ind1 (current-column))
6109 (if (or (< ind1 ind)
6110 (and (= ind1 ind)
6111 (not (org-at-item-p)))
6112 (eobp))
6113 (progn
6114 (setq pos (point-at-bol))
6115 (throw 'exit t))))))
6116 (goto-char pos)))
6119 (defvar org-last-indent-begin-marker (make-marker))
6120 (defvar org-last-indent-end-marker (make-marker))
6122 (defun org-outdent-item (arg)
6123 "Outdent a local list item."
6124 (interactive "p")
6125 (org-indent-item (- arg)))
6127 (defun org-indent-item (arg)
6128 "Indent a local list item."
6129 (interactive "p")
6130 (unless (org-at-item-p)
6131 (error "Not on an item"))
6132 (save-excursion
6133 (let (beg end ind ind1 tmp delta ind-down ind-up)
6134 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6135 (setq beg org-last-indent-begin-marker
6136 end org-last-indent-end-marker)
6137 (org-beginning-of-item)
6138 (setq beg (move-marker org-last-indent-begin-marker (point)))
6139 (org-end-of-item)
6140 (setq end (move-marker org-last-indent-end-marker (point))))
6141 (goto-char beg)
6142 (setq tmp (org-item-indent-positions)
6143 ind (car tmp)
6144 ind-down (nth 2 tmp)
6145 ind-up (nth 1 tmp)
6146 delta (if (> arg 0)
6147 (if ind-down (- ind-down ind) 2)
6148 (if ind-up (- ind-up ind) -2)))
6149 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6150 (while (< (point) end)
6151 (beginning-of-line 1)
6152 (skip-chars-forward " \t") (setq ind1 (current-column))
6153 (delete-region (point-at-bol) (point))
6154 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6155 (beginning-of-line 2))))
6156 (org-fix-bullet-type)
6157 (org-maybe-renumber-ordered-list-safe)
6158 (save-excursion
6159 (beginning-of-line 0)
6160 (condition-case nil (org-beginning-of-item) (error nil))
6161 (org-maybe-renumber-ordered-list-safe)))
6163 (defun org-item-indent-positions ()
6164 "Return indentation for plain list items.
6165 This returns a list with three values: The current indentation, the
6166 parent indentation and the indentation a child should habe.
6167 Assumes cursor in item line."
6168 (let* ((bolpos (point-at-bol))
6169 (ind (org-get-indentation))
6170 ind-down ind-up pos)
6171 (save-excursion
6172 (org-beginning-of-item-list)
6173 (skip-chars-backward "\n\r \t")
6174 (when (org-in-item-p)
6175 (org-beginning-of-item)
6176 (setq ind-up (org-get-indentation))))
6177 (setq pos (point))
6178 (save-excursion
6179 (cond
6180 ((and (condition-case nil (progn (org-previous-item) t)
6181 (error nil))
6182 (or (forward-char 1) t)
6183 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6184 (setq ind-down (org-get-indentation)))
6185 ((and (goto-char pos)
6186 (org-at-item-p))
6187 (goto-char (match-end 0))
6188 (skip-chars-forward " \t")
6189 (setq ind-down (current-column)))))
6190 (list ind ind-up ind-down)))
6192 ;;; The orgstruct minor mode
6194 ;; Define a minor mode which can be used in other modes in order to
6195 ;; integrate the org-mode structure editing commands.
6197 ;; This is really a hack, because the org-mode structure commands use
6198 ;; keys which normally belong to the major mode. Here is how it
6199 ;; works: The minor mode defines all the keys necessary to operate the
6200 ;; structure commands, but wraps the commands into a function which
6201 ;; tests if the cursor is currently at a headline or a plain list
6202 ;; item. If that is the case, the structure command is used,
6203 ;; temporarily setting many Org-mode variables like regular
6204 ;; expressions for filling etc. However, when any of those keys is
6205 ;; used at a different location, function uses `key-binding' to look
6206 ;; up if the key has an associated command in another currently active
6207 ;; keymap (minor modes, major mode, global), and executes that
6208 ;; command. There might be problems if any of the keys is otherwise
6209 ;; used as a prefix key.
6211 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6212 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6213 ;; addresses this by checking explicitly for both bindings.
6215 (defvar orgstruct-mode-map (make-sparse-keymap)
6216 "Keymap for the minor `orgstruct-mode'.")
6218 (defvar org-local-vars nil
6219 "List of local variables, for use by `orgstruct-mode'")
6221 ;;;###autoload
6222 (define-minor-mode orgstruct-mode
6223 "Toggle the minor more `orgstruct-mode'.
6224 This mode is for using Org-mode structure commands in other modes.
6225 The following key behave as if Org-mode was active, if the cursor
6226 is on a headline, or on a plain list item (both in the definition
6227 of Org-mode).
6229 M-up Move entry/item up
6230 M-down Move entry/item down
6231 M-left Promote
6232 M-right Demote
6233 M-S-up Move entry/item up
6234 M-S-down Move entry/item down
6235 M-S-left Promote subtree
6236 M-S-right Demote subtree
6237 M-q Fill paragraph and items like in Org-mode
6238 C-c ^ Sort entries
6239 C-c - Cycle list bullet
6240 TAB Cycle item visibility
6241 M-RET Insert new heading/item
6242 S-M-RET Insert new TODO heading / Chekbox item
6243 C-c C-c Set tags / toggle checkbox"
6244 nil " OrgStruct" nil
6245 (org-load-modules-maybe)
6246 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6248 ;;;###autoload
6249 (defun turn-on-orgstruct ()
6250 "Unconditionally turn on `orgstruct-mode'."
6251 (orgstruct-mode 1))
6253 ;;;###autoload
6254 (defun turn-on-orgstruct++ ()
6255 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6256 In addition to setting orgstruct-mode, this also exports all indentation and
6257 autofilling variables from org-mode into the buffer. Note that turning
6258 off orgstruct-mode will *not* remove these additional settings."
6259 (orgstruct-mode 1)
6260 (let (var val)
6261 (mapc
6262 (lambda (x)
6263 (when (string-match
6264 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6265 (symbol-name (car x)))
6266 (setq var (car x) val (nth 1 x))
6267 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6268 org-local-vars)))
6270 (defun orgstruct-error ()
6271 "Error when there is no default binding for a structure key."
6272 (interactive)
6273 (error "This key has no function outside structure elements"))
6275 (defun orgstruct-setup ()
6276 "Setup orgstruct keymaps."
6277 (let ((nfunc 0)
6278 (bindings
6279 (list
6280 '([(meta up)] org-metaup)
6281 '([(meta down)] org-metadown)
6282 '([(meta left)] org-metaleft)
6283 '([(meta right)] org-metaright)
6284 '([(meta shift up)] org-shiftmetaup)
6285 '([(meta shift down)] org-shiftmetadown)
6286 '([(meta shift left)] org-shiftmetaleft)
6287 '([(meta shift right)] org-shiftmetaright)
6288 '([(shift up)] org-shiftup)
6289 '([(shift down)] org-shiftdown)
6290 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6291 '("\M-q" fill-paragraph)
6292 '("\C-c^" org-sort)
6293 '("\C-c-" org-cycle-list-bullet)))
6294 elt key fun cmd)
6295 (while (setq elt (pop bindings))
6296 (setq nfunc (1+ nfunc))
6297 (setq key (org-key (car elt))
6298 fun (nth 1 elt)
6299 cmd (orgstruct-make-binding fun nfunc key))
6300 (org-defkey orgstruct-mode-map key cmd))
6302 ;; Special treatment needed for TAB and RET
6303 (org-defkey orgstruct-mode-map [(tab)]
6304 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6305 (org-defkey orgstruct-mode-map "\C-i"
6306 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6308 (org-defkey orgstruct-mode-map "\M-\C-m"
6309 (orgstruct-make-binding 'org-insert-heading 105
6310 "\M-\C-m" [(meta return)]))
6311 (org-defkey orgstruct-mode-map [(meta return)]
6312 (orgstruct-make-binding 'org-insert-heading 106
6313 [(meta return)] "\M-\C-m"))
6315 (org-defkey orgstruct-mode-map [(shift meta return)]
6316 (orgstruct-make-binding 'org-insert-todo-heading 107
6317 [(meta return)] "\M-\C-m"))
6319 (unless org-local-vars
6320 (setq org-local-vars (org-get-local-variables)))
6324 (defun orgstruct-make-binding (fun n &rest keys)
6325 "Create a function for binding in the structure minor mode.
6326 FUN is the command to call inside a table. N is used to create a unique
6327 command name. KEYS are keys that should be checked in for a command
6328 to execute outside of tables."
6329 (eval
6330 (list 'defun
6331 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6332 '(arg)
6333 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6334 "Outside of structure, run the binding of `"
6335 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6336 "'.")
6337 '(interactive "p")
6338 (list 'if
6339 '(org-context-p 'headline 'item)
6340 (list 'org-run-like-in-org-mode (list 'quote fun))
6341 (list 'let '(orgstruct-mode)
6342 (list 'call-interactively
6343 (append '(or)
6344 (mapcar (lambda (k)
6345 (list 'key-binding k))
6346 keys)
6347 '('orgstruct-error))))))))
6349 (defun org-context-p (&rest contexts)
6350 "Check if local context is and of CONTEXTS.
6351 Possible values in the list of contexts are `table', `headline', and `item'."
6352 (let ((pos (point)))
6353 (goto-char (point-at-bol))
6354 (prog1 (or (and (memq 'table contexts)
6355 (looking-at "[ \t]*|"))
6356 (and (memq 'headline contexts)
6357 (looking-at "\\*+"))
6358 (and (memq 'item contexts)
6359 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6360 (goto-char pos))))
6362 (defun org-get-local-variables ()
6363 "Return a list of all local variables in an org-mode buffer."
6364 (let (varlist)
6365 (with-current-buffer (get-buffer-create "*Org tmp*")
6366 (erase-buffer)
6367 (org-mode)
6368 (setq varlist (buffer-local-variables)))
6369 (kill-buffer "*Org tmp*")
6370 (delq nil
6371 (mapcar
6372 (lambda (x)
6373 (setq x
6374 (if (symbolp x)
6375 (list x)
6376 (list (car x) (list 'quote (cdr x)))))
6377 (if (string-match
6378 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6379 (symbol-name (car x)))
6380 x nil))
6381 varlist))))
6383 ;;;###autoload
6384 (defun org-run-like-in-org-mode (cmd)
6385 (org-load-modules-maybe)
6386 (unless org-local-vars
6387 (setq org-local-vars (org-get-local-variables)))
6388 (eval (list 'let org-local-vars
6389 (list 'call-interactively (list 'quote cmd)))))
6391 ;;;; Archiving
6393 (defun org-get-category (&optional pos)
6394 "Get the category applying to position POS."
6395 (get-text-property (or pos (point)) 'org-category))
6397 (defun org-refresh-category-properties ()
6398 "Refresh category text properties in the buffer."
6399 (let ((def-cat (cond
6400 ((null org-category)
6401 (if buffer-file-name
6402 (file-name-sans-extension
6403 (file-name-nondirectory buffer-file-name))
6404 "???"))
6405 ((symbolp org-category) (symbol-name org-category))
6406 (t org-category)))
6407 beg end cat pos optionp)
6408 (org-unmodified
6409 (save-excursion
6410 (save-restriction
6411 (widen)
6412 (goto-char (point-min))
6413 (put-text-property (point) (point-max) 'org-category def-cat)
6414 (while (re-search-forward
6415 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6416 (setq pos (match-end 0)
6417 optionp (equal (char-after (match-beginning 0)) ?#)
6418 cat (org-trim (match-string 2)))
6419 (if optionp
6420 (setq beg (point-at-bol) end (point-max))
6421 (org-back-to-heading t)
6422 (setq beg (point) end (org-end-of-subtree t t)))
6423 (put-text-property beg end 'org-category cat)
6424 (goto-char pos)))))))
6427 ;;;; Link Stuff
6429 ;;; Link abbreviations
6431 (defun org-link-expand-abbrev (link)
6432 "Apply replacements as defined in `org-link-abbrev-alist."
6433 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6434 (let* ((key (match-string 1 link))
6435 (as (or (assoc key org-link-abbrev-alist-local)
6436 (assoc key org-link-abbrev-alist)))
6437 (tag (and (match-end 2) (match-string 3 link)))
6438 rpl)
6439 (if (not as)
6440 link
6441 (setq rpl (cdr as))
6442 (cond
6443 ((symbolp rpl) (funcall rpl tag))
6444 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6445 (t (concat rpl tag)))))
6446 link))
6448 ;;; Storing and inserting links
6450 (defvar org-insert-link-history nil
6451 "Minibuffer history for links inserted with `org-insert-link'.")
6453 (defvar org-stored-links nil
6454 "Contains the links stored with `org-store-link'.")
6456 (defvar org-store-link-plist nil
6457 "Plist with info about the most recently link created with `org-store-link'.")
6459 (defvar org-link-protocols nil
6460 "Link protocols added to Org-mode using `org-add-link-type'.")
6462 (defvar org-store-link-functions nil
6463 "List of functions that are called to create and store a link.
6464 Each function will be called in turn until one returns a non-nil
6465 value. Each function should check if it is responsible for creating
6466 this link (for example by looking at the major mode).
6467 If not, it must exit and return nil.
6468 If yes, it should return a non-nil value after a calling
6469 `org-store-link-props' with a list of properties and values.
6470 Special properties are:
6472 :type The link prefix. like \"http\". This must be given.
6473 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6474 This is obligatory as well.
6475 :description Optional default description for the second pair
6476 of brackets in an Org-mode link. The user can still change
6477 this when inserting this link into an Org-mode buffer.
6479 In addition to these, any additional properties can be specified
6480 and then used in remember templates.")
6482 (defun org-add-link-type (type &optional follow export)
6483 "Add TYPE to the list of `org-link-types'.
6484 Re-compute all regular expressions depending on `org-link-types'
6486 FOLLOW and EXPORT are two functions.
6488 FOLLOW should take the link path as the single argument and do whatever
6489 is necessary to follow the link, for example find a file or display
6490 a mail message.
6492 EXPORT should format the link path for export to one of the export formats.
6493 It should be a function accepting three arguments:
6495 path the path of the link, the text after the prefix (like \"http:\")
6496 desc the description of the link, if any, nil if there was no descripton
6497 format the export format, a symbol like `html' or `latex'.
6499 The function may use the FORMAT information to return different values
6500 depending on the format. The return value will be put literally into
6501 the exported file.
6502 Org-mode has a built-in default for exporting links. If you are happy with
6503 this default, there is no need to define an export function for the link
6504 type. For a simple example of an export function, see `org-bbdb.el'."
6505 (add-to-list 'org-link-types type t)
6506 (org-make-link-regexps)
6507 (if (assoc type org-link-protocols)
6508 (setcdr (assoc type org-link-protocols) (list follow export))
6509 (push (list type follow export) org-link-protocols)))
6512 ;;;###autoload
6513 (defun org-store-link (arg)
6514 "\\<org-mode-map>Store an org-link to the current location.
6515 This link is added to `org-stored-links' and can later be inserted
6516 into an org-buffer with \\[org-insert-link].
6518 For some link types, a prefix arg is interpreted:
6519 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6520 For file links, arg negates `org-context-in-file-links'."
6521 (interactive "P")
6522 (org-load-modules-maybe)
6523 (setq org-store-link-plist nil) ; reset
6524 (let (link cpltxt desc description search txt)
6525 (cond
6527 ((run-hook-with-args-until-success 'org-store-link-functions)
6528 (setq link (plist-get org-store-link-plist :link)
6529 desc (or (plist-get org-store-link-plist :description) link)))
6531 ((eq major-mode 'calendar-mode)
6532 (let ((cd (calendar-cursor-to-date)))
6533 (setq link
6534 (format-time-string
6535 (car org-time-stamp-formats)
6536 (apply 'encode-time
6537 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6538 nil nil nil))))
6539 (org-store-link-props :type "calendar" :date cd)))
6541 ((eq major-mode 'w3-mode)
6542 (setq cpltxt (url-view-url t)
6543 link (org-make-link cpltxt))
6544 (org-store-link-props :type "w3" :url (url-view-url t)))
6546 ((eq major-mode 'w3m-mode)
6547 (setq cpltxt (or w3m-current-title w3m-current-url)
6548 link (org-make-link w3m-current-url))
6549 (org-store-link-props :type "w3m" :url (url-view-url t)))
6551 ((setq search (run-hook-with-args-until-success
6552 'org-create-file-search-functions))
6553 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6554 "::" search))
6555 (setq cpltxt (or description link)))
6557 ((eq major-mode 'image-mode)
6558 (setq cpltxt (concat "file:"
6559 (abbreviate-file-name buffer-file-name))
6560 link (org-make-link cpltxt))
6561 (org-store-link-props :type "image" :file buffer-file-name))
6563 ((eq major-mode 'dired-mode)
6564 ;; link to the file in the current line
6565 (setq cpltxt (concat "file:"
6566 (abbreviate-file-name
6567 (expand-file-name
6568 (dired-get-filename nil t))))
6569 link (org-make-link cpltxt)))
6571 ((and buffer-file-name (org-mode-p))
6572 ;; Just link to current headline
6573 (setq cpltxt (concat "file:"
6574 (abbreviate-file-name buffer-file-name)))
6575 ;; Add a context search string
6576 (when (org-xor org-context-in-file-links arg)
6577 ;; Check if we are on a target
6578 (if (org-in-regexp "<<\\(.*?\\)>>")
6579 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6580 (setq txt (cond
6581 ((org-on-heading-p) nil)
6582 ((org-region-active-p)
6583 (buffer-substring (region-beginning) (region-end)))
6584 (t nil)))
6585 (when (or (null txt) (string-match "\\S-" txt))
6586 (setq cpltxt
6587 (concat cpltxt "::"
6588 (condition-case nil
6589 (org-make-org-heading-search-string txt)
6590 (error "")))
6591 desc "NONE"))))
6592 (if (string-match "::\\'" cpltxt)
6593 (setq cpltxt (substring cpltxt 0 -2)))
6594 (setq link (org-make-link cpltxt)))
6596 ((buffer-file-name (buffer-base-buffer))
6597 ;; Just link to this file here.
6598 (setq cpltxt (concat "file:"
6599 (abbreviate-file-name
6600 (buffer-file-name (buffer-base-buffer)))))
6601 ;; Add a context string
6602 (when (org-xor org-context-in-file-links arg)
6603 (setq txt (if (org-region-active-p)
6604 (buffer-substring (region-beginning) (region-end))
6605 (buffer-substring (point-at-bol) (point-at-eol))))
6606 ;; Only use search option if there is some text.
6607 (when (string-match "\\S-" txt)
6608 (setq cpltxt
6609 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6610 desc "NONE")))
6611 (setq link (org-make-link cpltxt)))
6613 ((interactive-p)
6614 (error "Cannot link to a buffer which is not visiting a file"))
6616 (t (setq link nil)))
6618 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6619 (setq link (or link cpltxt)
6620 desc (or desc cpltxt))
6621 (if (equal desc "NONE") (setq desc nil))
6623 (if (and (interactive-p) link)
6624 (progn
6625 (setq org-stored-links
6626 (cons (list link desc) org-stored-links))
6627 (message "Stored: %s" (or desc link)))
6628 (and link (org-make-link-string link desc)))))
6630 (defun org-store-link-props (&rest plist)
6631 "Store link properties, extract names and addresses."
6632 (let (x adr)
6633 (when (setq x (plist-get plist :from))
6634 (setq adr (mail-extract-address-components x))
6635 (plist-put plist :fromname (car adr))
6636 (plist-put plist :fromaddress (nth 1 adr)))
6637 (when (setq x (plist-get plist :to))
6638 (setq adr (mail-extract-address-components x))
6639 (plist-put plist :toname (car adr))
6640 (plist-put plist :toaddress (nth 1 adr))))
6641 (let ((from (plist-get plist :from))
6642 (to (plist-get plist :to)))
6643 (when (and from to org-from-is-user-regexp)
6644 (plist-put plist :fromto
6645 (if (string-match org-from-is-user-regexp from)
6646 (concat "to %t")
6647 (concat "from %f")))))
6648 (setq org-store-link-plist plist))
6650 (defun org-add-link-props (&rest plist)
6651 "Add these properties to the link property list."
6652 (let (key value)
6653 (while plist
6654 (setq key (pop plist) value (pop plist))
6655 (setq org-store-link-plist
6656 (plist-put org-store-link-plist key value)))))
6658 (defun org-email-link-description (&optional fmt)
6659 "Return the description part of an email link.
6660 This takes information from `org-store-link-plist' and formats it
6661 according to FMT (default from `org-email-link-description-format')."
6662 (setq fmt (or fmt org-email-link-description-format))
6663 (let* ((p org-store-link-plist)
6664 (to (plist-get p :toaddress))
6665 (from (plist-get p :fromaddress))
6666 (table
6667 (list
6668 (cons "%c" (plist-get p :fromto))
6669 (cons "%F" (plist-get p :from))
6670 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6671 (cons "%T" (plist-get p :to))
6672 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6673 (cons "%s" (plist-get p :subject))
6674 (cons "%m" (plist-get p :message-id)))))
6675 (when (string-match "%c" fmt)
6676 ;; Check if the user wrote this message
6677 (if (and org-from-is-user-regexp from to
6678 (save-match-data (string-match org-from-is-user-regexp from)))
6679 (setq fmt (replace-match "to %t" t t fmt))
6680 (setq fmt (replace-match "from %f" t t fmt))))
6681 (org-replace-escapes fmt table)))
6683 (defun org-make-org-heading-search-string (&optional string heading)
6684 "Make search string for STRING or current headline."
6685 (interactive)
6686 (let ((s (or string (org-get-heading))))
6687 (unless (and string (not heading))
6688 ;; We are using a headline, clean up garbage in there.
6689 (if (string-match org-todo-regexp s)
6690 (setq s (replace-match "" t t s)))
6691 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6692 (setq s (replace-match "" t t s)))
6693 (setq s (org-trim s))
6694 (if (string-match (concat "^\\(" org-quote-string "\\|"
6695 org-comment-string "\\)") s)
6696 (setq s (replace-match "" t t s)))
6697 (while (string-match org-ts-regexp s)
6698 (setq s (replace-match "" t t s))))
6699 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6700 (setq s (replace-match " " t t s)))
6701 (or string (setq s (concat "*" s))) ; Add * for headlines
6702 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6704 (defun org-make-link (&rest strings)
6705 "Concatenate STRINGS."
6706 (apply 'concat strings))
6708 (defun org-make-link-string (link &optional description)
6709 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6710 (unless (string-match "\\S-" link)
6711 (error "Empty link"))
6712 (when (stringp description)
6713 ;; Remove brackets from the description, they are fatal.
6714 (while (string-match "\\[" description)
6715 (setq description (replace-match "{" t t description)))
6716 (while (string-match "\\]" description)
6717 (setq description (replace-match "}" t t description))))
6718 (when (equal (org-link-escape link) description)
6719 ;; No description needed, it is identical
6720 (setq description nil))
6721 (when (and (not description)
6722 (not (equal link (org-link-escape link))))
6723 (setq description link))
6724 (concat "[[" (org-link-escape link) "]"
6725 (if description (concat "[" description "]") "")
6726 "]"))
6728 (defconst org-link-escape-chars
6729 '((?\ . "%20")
6730 (?\[ . "%5B")
6731 (?\] . "%5D")
6732 (?\340 . "%E0") ; `a
6733 (?\342 . "%E2") ; ^a
6734 (?\347 . "%E7") ; ,c
6735 (?\350 . "%E8") ; `e
6736 (?\351 . "%E9") ; 'e
6737 (?\352 . "%EA") ; ^e
6738 (?\356 . "%EE") ; ^i
6739 (?\364 . "%F4") ; ^o
6740 (?\371 . "%F9") ; `u
6741 (?\373 . "%FB") ; ^u
6742 (?\; . "%3B")
6743 (?? . "%3F")
6744 (?= . "%3D")
6745 (?+ . "%2B")
6747 "Association list of escapes for some characters problematic in links.
6748 This is the list that is used for internal purposes.")
6750 (defconst org-link-escape-chars-browser
6751 '((?\ . "%20")) ; 32 for the SPC char
6752 "Association list of escapes for some characters problematic in links.
6753 This is the list that is used before handing over to the browser.")
6755 (defun org-link-escape (text &optional table)
6756 "Escape charaters in TEXT that are problematic for links."
6757 (setq table (or table org-link-escape-chars))
6758 (when text
6759 (let ((re (mapconcat (lambda (x) (regexp-quote
6760 (char-to-string (car x))))
6761 table "\\|")))
6762 (while (string-match re text)
6763 (setq text
6764 (replace-match
6765 (cdr (assoc (string-to-char (match-string 0 text))
6766 table))
6767 t t text)))
6768 text)))
6770 (defun org-link-unescape (text &optional table)
6771 "Reverse the action of `org-link-escape'."
6772 (setq table (or table org-link-escape-chars))
6773 (when text
6774 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6775 table "\\|")))
6776 (while (string-match re text)
6777 (setq text
6778 (replace-match
6779 (char-to-string (car (rassoc (match-string 0 text) table)))
6780 t t text)))
6781 text)))
6783 (defun org-xor (a b)
6784 "Exclusive or."
6785 (if a (not b) b))
6787 (defun org-get-header (header)
6788 "Find a header field in the current buffer."
6789 (save-excursion
6790 (goto-char (point-min))
6791 (let ((case-fold-search t) s)
6792 (cond
6793 ((eq header 'from)
6794 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6795 (setq s (match-string 1)))
6796 (while (string-match "\"" s)
6797 (setq s (replace-match "" t t s)))
6798 (if (string-match "[<(].*" s)
6799 (setq s (replace-match "" t t s))))
6800 ((eq header 'message-id)
6801 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6802 (setq s (match-string 1))))
6803 ((eq header 'subject)
6804 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6805 (setq s (match-string 1)))))
6806 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6807 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6808 s)))
6811 (defun org-fixup-message-id-for-http (s)
6812 "Replace special characters in a message id, so it can be used in an http query."
6813 (while (string-match "<" s)
6814 (setq s (replace-match "%3C" t t s)))
6815 (while (string-match ">" s)
6816 (setq s (replace-match "%3E" t t s)))
6817 (while (string-match "@" s)
6818 (setq s (replace-match "%40" t t s)))
6821 ;;;###autoload
6822 (defun org-insert-link-global ()
6823 "Insert a link like Org-mode does.
6824 This command can be called in any mode to insert a link in Org-mode syntax."
6825 (interactive)
6826 (org-load-modules-maybe)
6827 (org-run-like-in-org-mode 'org-insert-link))
6829 (defun org-insert-link (&optional complete-file link-location)
6830 "Insert a link. At the prompt, enter the link.
6832 Completion can be used to select a link previously stored with
6833 `org-store-link'. When the empty string is entered (i.e. if you just
6834 press RET at the prompt), the link defaults to the most recently
6835 stored link. As SPC triggers completion in the minibuffer, you need to
6836 use M-SPC or C-q SPC to force the insertion of a space character.
6838 You will also be prompted for a description, and if one is given, it will
6839 be displayed in the buffer instead of the link.
6841 If there is already a link at point, this command will allow you to edit link
6842 and description parts.
6844 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6845 be selected using completion. The path to the file will be relative to the
6846 current directory if the file is in the current directory or a subdirectory.
6847 Otherwise, the link will be the absolute path as completed in the minibuffer
6848 \(i.e. normally ~/path/to/file).
6850 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6851 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6852 of `org-keep-stored-link-after-insertion'.
6854 If `org-make-link-description-function' is non-nil, this function will be
6855 called with the link target, and the result will be the default
6856 link description.
6858 If the LINK-LOCATION parameter is non-nil, this value will be
6859 used as the link location instead of reading one interactively."
6860 (interactive "P")
6861 (let* ((wcf (current-window-configuration))
6862 (region (if (org-region-active-p)
6863 (buffer-substring (region-beginning) (region-end))))
6864 (remove (and region (list (region-beginning) (region-end))))
6865 (desc region)
6866 tmphist ; byte-compile incorrectly complains about this
6867 (link link-location)
6868 entry file)
6869 (cond
6870 (link-location) ; specified by arg, just use it.
6871 ((org-in-regexp org-bracket-link-regexp 1)
6872 ;; We do have a link at point, and we are going to edit it.
6873 (setq remove (list (match-beginning 0) (match-end 0)))
6874 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6875 (setq link (read-string "Link: "
6876 (org-link-unescape
6877 (org-match-string-no-properties 1)))))
6878 ((or (org-in-regexp org-angle-link-re)
6879 (org-in-regexp org-plain-link-re))
6880 ;; Convert to bracket link
6881 (setq remove (list (match-beginning 0) (match-end 0))
6882 link (read-string "Link: "
6883 (org-remove-angle-brackets (match-string 0)))))
6884 ((equal complete-file '(4))
6885 ;; Completing read for file names.
6886 (setq file (read-file-name "File: "))
6887 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6888 (pwd1 (file-name-as-directory (abbreviate-file-name
6889 (expand-file-name ".")))))
6890 (cond
6891 ((equal complete-file '(16))
6892 (setq link (org-make-link
6893 "file:"
6894 (abbreviate-file-name (expand-file-name file)))))
6895 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6896 (setq link (org-make-link "file:" (match-string 1 file))))
6897 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6898 (expand-file-name file))
6899 (setq link (org-make-link
6900 "file:" (match-string 1 (expand-file-name file)))))
6901 (t (setq link (org-make-link "file:" file))))))
6903 ;; Read link, with completion for stored links.
6904 (with-output-to-temp-buffer "*Org Links*"
6905 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6906 (when org-stored-links
6907 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6908 (princ (mapconcat
6909 (lambda (x)
6910 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6911 (reverse org-stored-links) "\n"))))
6912 (let ((cw (selected-window)))
6913 (select-window (get-buffer-window "*Org Links*"))
6914 (shrink-window-if-larger-than-buffer)
6915 (setq truncate-lines t)
6916 (select-window cw))
6917 ;; Fake a link history, containing the stored links.
6918 (setq tmphist (append (mapcar 'car org-stored-links)
6919 org-insert-link-history))
6920 (unwind-protect
6921 (setq link (org-completing-read
6922 "Link: "
6923 (append
6924 (mapcar (lambda (x) (list (concat (car x) ":")))
6925 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6926 (mapcar (lambda (x) (list (concat x ":")))
6927 org-link-types))
6928 nil nil nil
6929 'tmphist
6930 (or (car (car org-stored-links)))))
6931 (set-window-configuration wcf)
6932 (kill-buffer "*Org Links*"))
6933 (setq entry (assoc link org-stored-links))
6934 (or entry (push link org-insert-link-history))
6935 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6936 (not org-keep-stored-link-after-insertion))
6937 (setq org-stored-links (delq (assoc link org-stored-links)
6938 org-stored-links)))
6939 (setq desc (or desc (nth 1 entry)))))
6941 (if (string-match org-plain-link-re link)
6942 ;; URL-like link, normalize the use of angular brackets.
6943 (setq link (org-make-link (org-remove-angle-brackets link))))
6945 ;; Check if we are linking to the current file with a search option
6946 ;; If yes, simplify the link by using only the search option.
6947 (when (and buffer-file-name
6948 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6949 (let* ((path (match-string 1 link))
6950 (case-fold-search nil)
6951 (search (match-string 2 link)))
6952 (save-match-data
6953 (if (equal (file-truename buffer-file-name) (file-truename path))
6954 ;; We are linking to this same file, with a search option
6955 (setq link search)))))
6957 ;; Check if we can/should use a relative path. If yes, simplify the link
6958 (when (string-match "\\<file:\\(.*\\)" link)
6959 (let* ((path (match-string 1 link))
6960 (origpath path)
6961 (case-fold-search nil))
6962 (cond
6963 ((eq org-link-file-path-type 'absolute)
6964 (setq path (abbreviate-file-name (expand-file-name path))))
6965 ((eq org-link-file-path-type 'noabbrev)
6966 (setq path (expand-file-name path)))
6967 ((eq org-link-file-path-type 'relative)
6968 (setq path (file-relative-name path)))
6970 (save-match-data
6971 (if (string-match (concat "^" (regexp-quote
6972 (file-name-as-directory
6973 (expand-file-name "."))))
6974 (expand-file-name path))
6975 ;; We are linking a file with relative path name.
6976 (setq path (substring (expand-file-name path)
6977 (match-end 0)))))))
6978 (setq link (concat "file:" path))
6979 (if (equal desc origpath)
6980 (setq desc path))))
6982 (if org-make-link-description-function
6983 (setq desc (funcall org-make-link-description-function link desc)))
6985 (setq desc (read-string "Description: " desc))
6986 (unless (string-match "\\S-" desc) (setq desc nil))
6987 (if remove (apply 'delete-region remove))
6988 (insert (org-make-link-string link desc))))
6990 (defun org-completing-read (&rest args)
6991 (let ((minibuffer-local-completion-map
6992 (copy-keymap minibuffer-local-completion-map)))
6993 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6994 (apply 'completing-read args)))
6996 ;;; Opening/following a link
6998 (defvar org-link-search-failed nil)
7000 (defun org-next-link ()
7001 "Move forward to the next link.
7002 If the link is in hidden text, expose it."
7003 (interactive)
7004 (when (and org-link-search-failed (eq this-command last-command))
7005 (goto-char (point-min))
7006 (message "Link search wrapped back to beginning of buffer"))
7007 (setq org-link-search-failed nil)
7008 (let* ((pos (point))
7009 (ct (org-context))
7010 (a (assoc :link ct)))
7011 (if a (goto-char (nth 2 a)))
7012 (if (re-search-forward org-any-link-re nil t)
7013 (progn
7014 (goto-char (match-beginning 0))
7015 (if (org-invisible-p) (org-show-context)))
7016 (goto-char pos)
7017 (setq org-link-search-failed t)
7018 (error "No further link found"))))
7020 (defun org-previous-link ()
7021 "Move backward to the previous link.
7022 If the link is in hidden text, expose it."
7023 (interactive)
7024 (when (and org-link-search-failed (eq this-command last-command))
7025 (goto-char (point-max))
7026 (message "Link search wrapped back to end of buffer"))
7027 (setq org-link-search-failed nil)
7028 (let* ((pos (point))
7029 (ct (org-context))
7030 (a (assoc :link ct)))
7031 (if a (goto-char (nth 1 a)))
7032 (if (re-search-backward org-any-link-re nil t)
7033 (progn
7034 (goto-char (match-beginning 0))
7035 (if (org-invisible-p) (org-show-context)))
7036 (goto-char pos)
7037 (setq org-link-search-failed t)
7038 (error "No further link found"))))
7040 (defun org-find-file-at-mouse (ev)
7041 "Open file link or URL at mouse."
7042 (interactive "e")
7043 (mouse-set-point ev)
7044 (org-open-at-point 'in-emacs))
7046 (defun org-open-at-mouse (ev)
7047 "Open file link or URL at mouse."
7048 (interactive "e")
7049 (mouse-set-point ev)
7050 (org-open-at-point))
7052 (defvar org-window-config-before-follow-link nil
7053 "The window configuration before following a link.
7054 This is saved in case the need arises to restore it.")
7056 (defvar org-open-link-marker (make-marker)
7057 "Marker pointing to the location where `org-open-at-point; was called.")
7059 ;;;###autoload
7060 (defun org-open-at-point-global ()
7061 "Follow a link like Org-mode does.
7062 This command can be called in any mode to follow a link that has
7063 Org-mode syntax."
7064 (interactive)
7065 (org-run-like-in-org-mode 'org-open-at-point))
7067 ;;;###autoload
7068 (defun org-open-link-from-string (s &optional arg)
7069 "Open a link in the string S, as if it was in Org-mode."
7070 (interactive "sLink: \nP")
7071 (with-temp-buffer
7072 (let ((org-inhibit-startup t))
7073 (org-mode)
7074 (insert s)
7075 (goto-char (point-min))
7076 (org-open-at-point arg))))
7078 (defun org-open-at-point (&optional in-emacs)
7079 "Open link at or after point.
7080 If there is no link at point, this function will search forward up to
7081 the end of the current subtree.
7082 Normally, files will be opened by an appropriate application. If the
7083 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7084 (interactive "P")
7085 (org-load-modules-maybe)
7086 (move-marker org-open-link-marker (point))
7087 (setq org-window-config-before-follow-link (current-window-configuration))
7088 (org-remove-occur-highlights nil nil t)
7089 (if (org-at-timestamp-p t)
7090 (org-follow-timestamp-link)
7091 (let (type path link line search (pos (point)))
7092 (catch 'match
7093 (save-excursion
7094 (skip-chars-forward "^]\n\r")
7095 (when (org-in-regexp org-bracket-link-regexp)
7096 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7097 (while (string-match " *\n *" link)
7098 (setq link (replace-match " " t t link)))
7099 (setq link (org-link-expand-abbrev link))
7100 (if (string-match org-link-re-with-space2 link)
7101 (setq type (match-string 1 link) path (match-string 2 link))
7102 (setq type "thisfile" path link))
7103 (throw 'match t)))
7105 (when (get-text-property (point) 'org-linked-text)
7106 (setq type "thisfile"
7107 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7108 (1+ (point)) (point))
7109 path (buffer-substring
7110 (previous-single-property-change pos 'org-linked-text)
7111 (next-single-property-change pos 'org-linked-text)))
7112 (throw 'match t))
7114 (save-excursion
7115 (when (or (org-in-regexp org-angle-link-re)
7116 (org-in-regexp org-plain-link-re))
7117 (setq type (match-string 1) path (match-string 2))
7118 (throw 'match t)))
7119 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7120 (setq type "tree-match"
7121 path (match-string 1))
7122 (throw 'match t))
7123 (save-excursion
7124 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7125 (setq type "tags"
7126 path (match-string 1))
7127 (while (string-match ":" path)
7128 (setq path (replace-match "+" t t path)))
7129 (throw 'match t))))
7130 (unless path
7131 (error "No link found"))
7132 ;; Remove any trailing spaces in path
7133 (if (string-match " +\\'" path)
7134 (setq path (replace-match "" t t path)))
7136 (cond
7138 ((assoc type org-link-protocols)
7139 (funcall (nth 1 (assoc type org-link-protocols)) path))
7141 ((equal type "mailto")
7142 (let ((cmd (car org-link-mailto-program))
7143 (args (cdr org-link-mailto-program)) args1
7144 (address path) (subject "") a)
7145 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7146 (setq address (match-string 1 path)
7147 subject (org-link-escape (match-string 2 path))))
7148 (while args
7149 (cond
7150 ((not (stringp (car args))) (push (pop args) args1))
7151 (t (setq a (pop args))
7152 (if (string-match "%a" a)
7153 (setq a (replace-match address t t a)))
7154 (if (string-match "%s" a)
7155 (setq a (replace-match subject t t a)))
7156 (push a args1))))
7157 (apply cmd (nreverse args1))))
7159 ((member type '("http" "https" "ftp" "news"))
7160 (browse-url (concat type ":" (org-link-escape
7161 path org-link-escape-chars-browser))))
7163 ((member type '("message"))
7164 (browse-url (concat type ":" path)))
7166 ((string= type "tags")
7167 (org-tags-view in-emacs path))
7168 ((string= type "thisfile")
7169 (if in-emacs
7170 (switch-to-buffer-other-window
7171 (org-get-buffer-for-internal-link (current-buffer)))
7172 (org-mark-ring-push))
7173 (let ((cmd `(org-link-search
7174 ,path
7175 ,(cond ((equal in-emacs '(4)) 'occur)
7176 ((equal in-emacs '(16)) 'org-occur)
7177 (t nil))
7178 ,pos)))
7179 (condition-case nil (eval cmd)
7180 (error (progn (widen) (eval cmd))))))
7182 ((string= type "tree-match")
7183 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7185 ((string= type "file")
7186 (if (string-match "::\\([0-9]+\\)\\'" path)
7187 (setq line (string-to-number (match-string 1 path))
7188 path (substring path 0 (match-beginning 0)))
7189 (if (string-match "::\\(.+\\)\\'" path)
7190 (setq search (match-string 1 path)
7191 path (substring path 0 (match-beginning 0)))))
7192 (if (string-match "[*?{]" (file-name-nondirectory path))
7193 (dired path)
7194 (org-open-file path in-emacs line search)))
7196 ((string= type "news")
7197 (require 'org-gnus)
7198 (org-gnus-follow-link path))
7200 ((string= type "shell")
7201 (let ((cmd path))
7202 (if (or (not org-confirm-shell-link-function)
7203 (funcall org-confirm-shell-link-function
7204 (format "Execute \"%s\" in shell? "
7205 (org-add-props cmd nil
7206 'face 'org-warning))))
7207 (progn
7208 (message "Executing %s" cmd)
7209 (shell-command cmd))
7210 (error "Abort"))))
7212 ((string= type "elisp")
7213 (let ((cmd path))
7214 (if (or (not org-confirm-elisp-link-function)
7215 (funcall org-confirm-elisp-link-function
7216 (format "Execute \"%s\" as elisp? "
7217 (org-add-props cmd nil
7218 'face 'org-warning))))
7219 (message "%s => %s" cmd (eval (read cmd)))
7220 (error "Abort"))))
7223 (browse-url-at-point)))))
7224 (move-marker org-open-link-marker nil)
7225 (run-hook-with-args 'org-follow-link-hook))
7227 ;;;; Time estimates
7229 (defun org-get-effort (&optional pom)
7230 "Get the effort estimate for the current entry."
7231 (org-entry-get pom org-effort-property))
7233 ;;; File search
7235 (defvar org-create-file-search-functions nil
7236 "List of functions to construct the right search string for a file link.
7237 These functions are called in turn with point at the location to
7238 which the link should point.
7240 A function in the hook should first test if it would like to
7241 handle this file type, for example by checking the major-mode or
7242 the file extension. If it decides not to handle this file, it
7243 should just return nil to give other functions a chance. If it
7244 does handle the file, it must return the search string to be used
7245 when following the link. The search string will be part of the
7246 file link, given after a double colon, and `org-open-at-point'
7247 will automatically search for it. If special measures must be
7248 taken to make the search successful, another function should be
7249 added to the companion hook `org-execute-file-search-functions',
7250 which see.
7252 A function in this hook may also use `setq' to set the variable
7253 `description' to provide a suggestion for the descriptive text to
7254 be used for this link when it gets inserted into an Org-mode
7255 buffer with \\[org-insert-link].")
7257 (defvar org-execute-file-search-functions nil
7258 "List of functions to execute a file search triggered by a link.
7260 Functions added to this hook must accept a single argument, the
7261 search string that was part of the file link, the part after the
7262 double colon. The function must first check if it would like to
7263 handle this search, for example by checking the major-mode or the
7264 file extension. If it decides not to handle this search, it
7265 should just return nil to give other functions a chance. If it
7266 does handle the search, it must return a non-nil value to keep
7267 other functions from trying.
7269 Each function can access the current prefix argument through the
7270 variable `current-prefix-argument'. Note that a single prefix is
7271 used to force opening a link in Emacs, so it may be good to only
7272 use a numeric or double prefix to guide the search function.
7274 In case this is needed, a function in this hook can also restore
7275 the window configuration before `org-open-at-point' was called using:
7277 (set-window-configuration org-window-config-before-follow-link)")
7279 (defun org-link-search (s &optional type avoid-pos)
7280 "Search for a link search option.
7281 If S is surrounded by forward slashes, it is interpreted as a
7282 regular expression. In org-mode files, this will create an `org-occur'
7283 sparse tree. In ordinary files, `occur' will be used to list matches.
7284 If the current buffer is in `dired-mode', grep will be used to search
7285 in all files. If AVOID-POS is given, ignore matches near that position."
7286 (let ((case-fold-search t)
7287 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7288 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7289 (append '(("") (" ") ("\t") ("\n"))
7290 org-emphasis-alist)
7291 "\\|") "\\)"))
7292 (pos (point))
7293 (pre nil) (post nil)
7294 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7295 (cond
7296 ;; First check if there are any special
7297 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7298 ;; Now try the builtin stuff
7299 ((save-excursion
7300 (goto-char (point-min))
7301 (and
7302 (re-search-forward
7303 (concat "<<" (regexp-quote s0) ">>") nil t)
7304 (setq type 'dedicated
7305 pos (match-beginning 0))))
7306 ;; There is an exact target for this
7307 (goto-char pos))
7308 ((string-match "^/\\(.*\\)/$" s)
7309 ;; A regular expression
7310 (cond
7311 ((org-mode-p)
7312 (org-occur (match-string 1 s)))
7313 ;;((eq major-mode 'dired-mode)
7314 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7315 (t (org-do-occur (match-string 1 s)))))
7317 ;; A normal search strings
7318 (when (equal (string-to-char s) ?*)
7319 ;; Anchor on headlines, post may include tags.
7320 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7321 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7322 s (substring s 1)))
7323 (remove-text-properties
7324 0 (length s)
7325 '(face nil mouse-face nil keymap nil fontified nil) s)
7326 ;; Make a series of regular expressions to find a match
7327 (setq words (org-split-string s "[ \n\r\t]+")
7329 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7330 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7331 "\\)" markers)
7332 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7333 re2a (concat "[ \t\r\n]" re2a_)
7334 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7335 re4 (concat "[^a-zA-Z_]" re4_)
7337 re1 (concat pre re2 post)
7338 re3 (concat pre (if pre re4_ re4) post)
7339 re5 (concat pre ".*" re4)
7340 re2 (concat pre re2)
7341 re2a (concat pre (if pre re2a_ re2a))
7342 re4 (concat pre (if pre re4_ re4))
7343 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7344 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7345 re5 "\\)"
7347 (cond
7348 ((eq type 'org-occur) (org-occur reall))
7349 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7350 (t (goto-char (point-min))
7351 (setq type 'fuzzy)
7352 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7353 (org-search-not-self 1 re1 nil t)
7354 (org-search-not-self 1 re2 nil t)
7355 (org-search-not-self 1 re2a nil t)
7356 (org-search-not-self 1 re3 nil t)
7357 (org-search-not-self 1 re4 nil t)
7358 (org-search-not-self 1 re5 nil t)
7360 (goto-char (match-beginning 1))
7361 (goto-char pos)
7362 (error "No match")))))
7364 ;; Normal string-search
7365 (goto-char (point-min))
7366 (if (search-forward s nil t)
7367 (goto-char (match-beginning 0))
7368 (error "No match"))))
7369 (and (org-mode-p) (org-show-context 'link-search))
7370 type))
7372 (defun org-search-not-self (group &rest args)
7373 "Execute `re-search-forward', but only accept matches that do not
7374 enclose the position of `org-open-link-marker'."
7375 (let ((m org-open-link-marker))
7376 (catch 'exit
7377 (while (apply 're-search-forward args)
7378 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7379 (goto-char (match-end group))
7380 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7381 (> (match-beginning 0) (marker-position m))
7382 (< (match-end 0) (marker-position m)))
7383 (save-match-data
7384 (or (not (org-in-regexp
7385 org-bracket-link-analytic-regexp 1))
7386 (not (match-end 4)) ; no description
7387 (and (<= (match-beginning 4) (point))
7388 (>= (match-end 4) (point))))))
7389 (throw 'exit (point))))))))
7391 (defun org-get-buffer-for-internal-link (buffer)
7392 "Return a buffer to be used for displaying the link target of internal links."
7393 (cond
7394 ((not org-display-internal-link-with-indirect-buffer)
7395 buffer)
7396 ((string-match "(Clone)$" (buffer-name buffer))
7397 (message "Buffer is already a clone, not making another one")
7398 ;; we also do not modify visibility in this case
7399 buffer)
7400 (t ; make a new indirect buffer for displaying the link
7401 (let* ((bn (buffer-name buffer))
7402 (ibn (concat bn "(Clone)"))
7403 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7404 (with-current-buffer ib (org-overview))
7405 ib))))
7407 (defun org-do-occur (regexp &optional cleanup)
7408 "Call the Emacs command `occur'.
7409 If CLEANUP is non-nil, remove the printout of the regular expression
7410 in the *Occur* buffer. This is useful if the regex is long and not useful
7411 to read."
7412 (occur regexp)
7413 (when cleanup
7414 (let ((cwin (selected-window)) win beg end)
7415 (when (setq win (get-buffer-window "*Occur*"))
7416 (select-window win))
7417 (goto-char (point-min))
7418 (when (re-search-forward "match[a-z]+" nil t)
7419 (setq beg (match-end 0))
7420 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7421 (setq end (1- (match-beginning 0)))))
7422 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7423 (goto-char (point-min))
7424 (select-window cwin))))
7426 ;;; The mark ring for links jumps
7428 (defvar org-mark-ring nil
7429 "Mark ring for positions before jumps in Org-mode.")
7430 (defvar org-mark-ring-last-goto nil
7431 "Last position in the mark ring used to go back.")
7432 ;; Fill and close the ring
7433 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7434 (loop for i from 1 to org-mark-ring-length do
7435 (push (make-marker) org-mark-ring))
7436 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7437 org-mark-ring)
7439 (defun org-mark-ring-push (&optional pos buffer)
7440 "Put the current position or POS into the mark ring and rotate it."
7441 (interactive)
7442 (setq pos (or pos (point)))
7443 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7444 (move-marker (car org-mark-ring)
7445 (or pos (point))
7446 (or buffer (current-buffer)))
7447 (message "%s"
7448 (substitute-command-keys
7449 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7451 (defun org-mark-ring-goto (&optional n)
7452 "Jump to the previous position in the mark ring.
7453 With prefix arg N, jump back that many stored positions. When
7454 called several times in succession, walk through the entire ring.
7455 Org-mode commands jumping to a different position in the current file,
7456 or to another Org-mode file, automatically push the old position
7457 onto the ring."
7458 (interactive "p")
7459 (let (p m)
7460 (if (eq last-command this-command)
7461 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7462 (setq p org-mark-ring))
7463 (setq org-mark-ring-last-goto p)
7464 (setq m (car p))
7465 (switch-to-buffer (marker-buffer m))
7466 (goto-char m)
7467 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7469 (defun org-remove-angle-brackets (s)
7470 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7471 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7473 (defun org-add-angle-brackets (s)
7474 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7475 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7477 (defun org-remove-double-quotes (s)
7478 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7479 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7482 ;;; Following specific links
7484 (defun org-follow-timestamp-link ()
7485 (cond
7486 ((org-at-date-range-p t)
7487 (let ((org-agenda-start-on-weekday)
7488 (t1 (match-string 1))
7489 (t2 (match-string 2)))
7490 (setq t1 (time-to-days (org-time-string-to-time t1))
7491 t2 (time-to-days (org-time-string-to-time t2)))
7492 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7493 ((org-at-timestamp-p t)
7494 (org-agenda-list nil (time-to-days (org-time-string-to-time
7495 (substring (match-string 1) 0 10)))
7497 (t (error "This should not happen"))))
7500 ;;; Following file links
7501 (defvar org-wait nil)
7502 (defun org-open-file (path &optional in-emacs line search)
7503 "Open the file at PATH.
7504 First, this expands any special file name abbreviations. Then the
7505 configuration variable `org-file-apps' is checked if it contains an
7506 entry for this file type, and if yes, the corresponding command is launched.
7507 If no application is found, Emacs simply visits the file.
7508 With optional argument IN-EMACS, Emacs will visit the file.
7509 Optional LINE specifies a line to go to, optional SEARCH a string to
7510 search for. If LINE or SEARCH is given, the file will always be
7511 opened in Emacs.
7512 If the file does not exist, an error is thrown."
7513 (setq in-emacs (or in-emacs line search))
7514 (let* ((file (if (equal path "")
7515 buffer-file-name
7516 (substitute-in-file-name (expand-file-name path))))
7517 (apps (append org-file-apps (org-default-apps)))
7518 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7519 (dirp (if remp nil (file-directory-p file)))
7520 (dfile (downcase file))
7521 (old-buffer (current-buffer))
7522 (old-pos (point))
7523 (old-mode major-mode)
7524 ext cmd)
7525 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7526 (setq ext (match-string 1 dfile))
7527 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7528 (setq ext (match-string 1 dfile))))
7529 (if in-emacs
7530 (setq cmd 'emacs)
7531 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7532 (and dirp (cdr (assoc 'directory apps)))
7533 (cdr (assoc ext apps))
7534 (cdr (assoc t apps)))))
7535 (when (eq cmd 'mailcap)
7536 (require 'mailcap)
7537 (mailcap-parse-mailcaps)
7538 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7539 (command (mailcap-mime-info mime-type)))
7540 (if (stringp command)
7541 (setq cmd command)
7542 (setq cmd 'emacs))))
7543 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7544 (not (file-exists-p file))
7545 (not org-open-non-existing-files))
7546 (error "No such file: %s" file))
7547 (cond
7548 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7549 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7550 (while (string-match "['\"]%s['\"]" cmd)
7551 (setq cmd (replace-match "%s" t t cmd)))
7552 (while (string-match "%s" cmd)
7553 (setq cmd (replace-match
7554 (save-match-data
7555 (shell-quote-argument
7556 (convert-standard-filename file)))
7557 t t cmd)))
7558 (save-window-excursion
7559 (start-process-shell-command cmd nil cmd)
7560 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7562 ((or (stringp cmd)
7563 (eq cmd 'emacs))
7564 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7565 (widen)
7566 (if line (goto-line line)
7567 (if search (org-link-search search))))
7568 ((consp cmd)
7569 (let ((file (convert-standard-filename file)))
7570 (eval cmd)))
7571 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7572 (and (org-mode-p) (eq old-mode 'org-mode)
7573 (or (not (equal old-buffer (current-buffer)))
7574 (not (equal old-pos (point))))
7575 (org-mark-ring-push old-pos old-buffer))))
7577 (defun org-default-apps ()
7578 "Return the default applications for this operating system."
7579 (cond
7580 ((eq system-type 'darwin)
7581 org-file-apps-defaults-macosx)
7582 ((eq system-type 'windows-nt)
7583 org-file-apps-defaults-windowsnt)
7584 (t org-file-apps-defaults-gnu)))
7586 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7587 (defun org-file-remote-p (file)
7588 "Test whether FILE specifies a location on a remote system.
7589 Return non-nil if the location is indeed remote.
7591 For example, the filename \"/user@host:/foo\" specifies a location
7592 on the system \"/user@host:\"."
7593 (cond ((fboundp 'file-remote-p)
7594 (file-remote-p file))
7595 ((fboundp 'tramp-handle-file-remote-p)
7596 (tramp-handle-file-remote-p file))
7597 ((and (boundp 'ange-ftp-name-format)
7598 (string-match (car ange-ftp-name-format) file))
7600 (t nil)))
7603 ;;;; Refiling
7605 (defun org-get-org-file ()
7606 "Read a filename, with default directory `org-directory'."
7607 (let ((default (or org-default-notes-file remember-data-file)))
7608 (read-file-name (format "File name [%s]: " default)
7609 (file-name-as-directory org-directory)
7610 default)))
7612 (defun org-notes-order-reversed-p ()
7613 "Check if the current file should receive notes in reversed order."
7614 (cond
7615 ((not org-reverse-note-order) nil)
7616 ((eq t org-reverse-note-order) t)
7617 ((not (listp org-reverse-note-order)) nil)
7618 (t (catch 'exit
7619 (let ((all org-reverse-note-order)
7620 entry)
7621 (while (setq entry (pop all))
7622 (if (string-match (car entry) buffer-file-name)
7623 (throw 'exit (cdr entry))))
7624 nil)))))
7626 (defvar org-refile-target-table nil
7627 "The list of refile targets, created by `org-refile'.")
7629 (defvar org-agenda-new-buffers nil
7630 "Buffers created to visit agenda files.")
7632 (defun org-get-refile-targets (&optional default-buffer)
7633 "Produce a table with refile targets."
7634 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7635 targets txt re files f desc descre)
7636 (with-current-buffer (or default-buffer (current-buffer))
7637 (while (setq entry (pop entries))
7638 (setq files (car entry) desc (cdr entry))
7639 (cond
7640 ((null files) (setq files (list (current-buffer))))
7641 ((eq files 'org-agenda-files)
7642 (setq files (org-agenda-files 'unrestricted)))
7643 ((and (symbolp files) (fboundp files))
7644 (setq files (funcall files)))
7645 ((and (symbolp files) (boundp files))
7646 (setq files (symbol-value files))))
7647 (if (stringp files) (setq files (list files)))
7648 (cond
7649 ((eq (car desc) :tag)
7650 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7651 ((eq (car desc) :todo)
7652 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7653 ((eq (car desc) :regexp)
7654 (setq descre (cdr desc)))
7655 ((eq (car desc) :level)
7656 (setq descre (concat "^\\*\\{" (number-to-string
7657 (if org-odd-levels-only
7658 (1- (* 2 (cdr desc)))
7659 (cdr desc)))
7660 "\\}[ \t]")))
7661 ((eq (car desc) :maxlevel)
7662 (setq descre (concat "^\\*\\{1," (number-to-string
7663 (if org-odd-levels-only
7664 (1- (* 2 (cdr desc)))
7665 (cdr desc)))
7666 "\\}[ \t]")))
7667 (t (error "Bad refiling target description %s" desc)))
7668 (while (setq f (pop files))
7669 (save-excursion
7670 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7671 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7672 (save-excursion
7673 (save-restriction
7674 (widen)
7675 (goto-char (point-min))
7676 (while (re-search-forward descre nil t)
7677 (goto-char (point-at-bol))
7678 (when (looking-at org-complex-heading-regexp)
7679 (setq txt (match-string 4)
7680 re (concat "^" (regexp-quote
7681 (buffer-substring (match-beginning 1)
7682 (match-end 4)))))
7683 (if (match-end 5) (setq re (concat re "[ \t]+"
7684 (regexp-quote
7685 (match-string 5)))))
7686 (setq re (concat re "[ \t]*$"))
7687 (when org-refile-use-outline-path
7688 (setq txt (mapconcat 'identity
7689 (append
7690 (if (eq org-refile-use-outline-path 'file)
7691 (list (file-name-nondirectory
7692 (buffer-file-name (buffer-base-buffer))))
7693 (if (eq org-refile-use-outline-path 'full-file-path)
7694 (list (buffer-file-name (buffer-base-buffer)))))
7695 (org-get-outline-path)
7696 (list txt))
7697 "/")))
7698 (push (list txt f re (point)) targets))
7699 (goto-char (point-at-eol))))))))
7700 (nreverse targets))))
7702 (defun org-get-outline-path ()
7703 "Return the outline path to the current entry, as a list."
7704 (let (rtn)
7705 (save-excursion
7706 (while (org-up-heading-safe)
7707 (when (looking-at org-complex-heading-regexp)
7708 (push (org-match-string-no-properties 4) rtn)))
7709 rtn)))
7711 (defvar org-refile-history nil
7712 "History for refiling operations.")
7714 (defun org-refile (&optional goto default-buffer)
7715 "Move the entry at point to another heading.
7716 The list of target headings is compiled using the information in
7717 `org-refile-targets', which see. This list is created before each use
7718 and will therefore always be up-to-date.
7720 At the target location, the entry is filed as a subitem of the target heading.
7721 Depending on `org-reverse-note-order', the new subitem will either be the
7722 first of the last subitem.
7724 With prefix arg GOTO, the command will only visit the target location,
7725 not actually move anything.
7726 With a double prefix `C-c C-c', go to the location where the last refiling
7727 operation has put the subtree."
7728 (interactive "P")
7729 (let* ((cbuf (current-buffer))
7730 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7731 pos it nbuf file re level reversed)
7732 (if (equal goto '(16))
7733 (org-refile-goto-last-stored)
7734 (when (setq it (org-refile-get-location
7735 (if goto "Goto: " "Refile to: ") default-buffer))
7736 (setq file (nth 1 it)
7737 re (nth 2 it)
7738 pos (nth 3 it))
7739 (setq nbuf (or (find-buffer-visiting file)
7740 (find-file-noselect file)))
7741 (if goto
7742 (progn
7743 (switch-to-buffer nbuf)
7744 (goto-char pos)
7745 (org-show-context 'org-goto))
7746 (org-copy-subtree 1 nil t)
7747 (save-excursion
7748 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7749 (find-file-noselect file))))
7750 (setq reversed (org-notes-order-reversed-p))
7751 (save-excursion
7752 (save-restriction
7753 (widen)
7754 (goto-char pos)
7755 (looking-at outline-regexp)
7756 (setq level (org-get-valid-level (funcall outline-level) 1))
7757 (goto-char
7758 (if reversed
7759 (outline-next-heading)
7760 (or (save-excursion (outline-get-next-sibling))
7761 (org-end-of-subtree t t)
7762 (point-max))))
7763 (bookmark-set "org-refile-last-stored")
7764 (org-paste-subtree level))))
7765 (org-cut-subtree)
7766 (setq org-markers-to-move nil)
7767 (message "Entry refiled to \"%s\"" (car it)))))))
7769 (defun org-refile-goto-last-stored ()
7770 "Go to the location where the last refile was stored."
7771 (interactive)
7772 (bookmark-jump "org-refile-last-stored")
7773 (message "This is the location of the last refile"))
7775 (defun org-refile-get-location (&optional prompt default-buffer)
7776 "Prompt the user for a refile location, using PROMPT."
7777 (let ((org-refile-targets org-refile-targets)
7778 (org-refile-use-outline-path org-refile-use-outline-path))
7779 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7780 (unless org-refile-target-table
7781 (error "No refile targets"))
7782 (let* ((cbuf (current-buffer))
7783 (cfunc (if org-refile-use-outline-path
7784 'org-olpath-completing-read
7785 'completing-read))
7786 (extra (if org-refile-use-outline-path "/" ""))
7787 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7788 (fname (and filename (file-truename filename)))
7789 (tbl (mapcar
7790 (lambda (x)
7791 (if (not (equal fname (file-truename (nth 1 x))))
7792 (cons (concat (car x) extra " ("
7793 (file-name-nondirectory (nth 1 x)) ")")
7794 (cdr x))
7795 (cons (concat (car x) extra) (cdr x))))
7796 org-refile-target-table))
7797 (completion-ignore-case t))
7798 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7799 tbl)))
7801 (defun org-olpath-completing-read (prompt collection &rest args)
7802 "Read an outline path like a file name."
7803 (let ((thetable collection))
7804 (apply
7805 'completing-read prompt
7806 (lambda (string predicate &optional flag)
7807 (let (rtn r s f (l (length string)))
7808 (cond
7809 ((eq flag nil)
7810 ;; try completion
7811 (try-completion string thetable))
7812 ((eq flag t)
7813 ;; all-completions
7814 (setq rtn (all-completions string thetable predicate))
7815 (mapcar
7816 (lambda (x)
7817 (setq r (substring x l))
7818 (if (string-match " ([^)]*)$" x)
7819 (setq f (match-string 0 x))
7820 (setq f ""))
7821 (if (string-match "/" r)
7822 (concat string (substring r 0 (match-end 0)) f)
7824 rtn))
7825 ((eq flag 'lambda)
7826 ;; exact match?
7827 (assoc string thetable)))
7829 args)))
7831 ;;;; Dynamic blocks
7833 (defun org-find-dblock (name)
7834 "Find the first dynamic block with name NAME in the buffer.
7835 If not found, stay at current position and return nil."
7836 (let (pos)
7837 (save-excursion
7838 (goto-char (point-min))
7839 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7840 nil t)
7841 (match-beginning 0))))
7842 (if pos (goto-char pos))
7843 pos))
7845 (defconst org-dblock-start-re
7846 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7847 "Matches the startline of a dynamic block, with parameters.")
7849 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7850 "Matches the end of a dyhamic block.")
7852 (defun org-create-dblock (plist)
7853 "Create a dynamic block section, with parameters taken from PLIST.
7854 PLIST must containe a :name entry which is used as name of the block."
7855 (unless (bolp) (newline))
7856 (let ((name (plist-get plist :name)))
7857 (insert "#+BEGIN: " name)
7858 (while plist
7859 (if (eq (car plist) :name)
7860 (setq plist (cddr plist))
7861 (insert " " (prin1-to-string (pop plist)))))
7862 (insert "\n\n#+END:\n")
7863 (beginning-of-line -2)))
7865 (defun org-prepare-dblock ()
7866 "Prepare dynamic block for refresh.
7867 This empties the block, puts the cursor at the insert position and returns
7868 the property list including an extra property :name with the block name."
7869 (unless (looking-at org-dblock-start-re)
7870 (error "Not at a dynamic block"))
7871 (let* ((begdel (1+ (match-end 0)))
7872 (name (org-no-properties (match-string 1)))
7873 (params (append (list :name name)
7874 (read (concat "(" (match-string 3) ")")))))
7875 (unless (re-search-forward org-dblock-end-re nil t)
7876 (error "Dynamic block not terminated"))
7877 (setq params
7878 (append params
7879 (list :content (buffer-substring
7880 begdel (match-beginning 0)))))
7881 (delete-region begdel (match-beginning 0))
7882 (goto-char begdel)
7883 (open-line 1)
7884 params))
7886 (defun org-map-dblocks (&optional command)
7887 "Apply COMMAND to all dynamic blocks in the current buffer.
7888 If COMMAND is not given, use `org-update-dblock'."
7889 (let ((cmd (or command 'org-update-dblock))
7890 pos)
7891 (save-excursion
7892 (goto-char (point-min))
7893 (while (re-search-forward org-dblock-start-re nil t)
7894 (goto-char (setq pos (match-beginning 0)))
7895 (condition-case nil
7896 (funcall cmd)
7897 (error (message "Error during update of dynamic block")))
7898 (goto-char pos)
7899 (unless (re-search-forward org-dblock-end-re nil t)
7900 (error "Dynamic block not terminated"))))))
7902 (defun org-dblock-update (&optional arg)
7903 "User command for updating dynamic blocks.
7904 Update the dynamic block at point. With prefix ARG, update all dynamic
7905 blocks in the buffer."
7906 (interactive "P")
7907 (if arg
7908 (org-update-all-dblocks)
7909 (or (looking-at org-dblock-start-re)
7910 (org-beginning-of-dblock))
7911 (org-update-dblock)))
7913 (defun org-update-dblock ()
7914 "Update the dynamic block at point
7915 This means to empty the block, parse for parameters and then call
7916 the correct writing function."
7917 (save-window-excursion
7918 (let* ((pos (point))
7919 (line (org-current-line))
7920 (params (org-prepare-dblock))
7921 (name (plist-get params :name))
7922 (cmd (intern (concat "org-dblock-write:" name))))
7923 (message "Updating dynamic block `%s' at line %d..." name line)
7924 (funcall cmd params)
7925 (message "Updating dynamic block `%s' at line %d...done" name line)
7926 (goto-char pos))))
7928 (defun org-beginning-of-dblock ()
7929 "Find the beginning of the dynamic block at point.
7930 Error if there is no scuh block at point."
7931 (let ((pos (point))
7932 beg)
7933 (end-of-line 1)
7934 (if (and (re-search-backward org-dblock-start-re nil t)
7935 (setq beg (match-beginning 0))
7936 (re-search-forward org-dblock-end-re nil t)
7937 (> (match-end 0) pos))
7938 (goto-char beg)
7939 (goto-char pos)
7940 (error "Not in a dynamic block"))))
7942 (defun org-update-all-dblocks ()
7943 "Update all dynamic blocks in the buffer.
7944 This function can be used in a hook."
7945 (when (org-mode-p)
7946 (org-map-dblocks 'org-update-dblock)))
7949 ;;;; Completion
7951 (defconst org-additional-option-like-keywords
7952 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7953 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7954 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7956 (defcustom org-structure-template-alist
7958 ("s" "#+begin_src ?\n\n#+end_src"
7959 "<src lang=\"?\">\n\n</src>")
7960 ("e" "#+begin_example\n?\n#+end_example"
7961 "<example>\n?\n</example>")
7962 ("q" "#+begin_quote\n?\n#+end_quote"
7963 "<quote>\n?\n</quote>")
7964 ("v" "#+begin_verse\n?\n#+end_verse"
7965 "<verse>\n?\n/verse>")
7966 ("l" "#+begin_latex\n?\n#+end_latex"
7967 "<literal style=\"latex\">\n?\n</literal>")
7968 ("L" "#+latex: "
7969 "<literal style=\"latex\">?</literal>")
7970 ("h" "#+begin_html\n?\n#+end_html"
7971 "<literal style=\"html\">\n?\n</literal>")
7972 ("H" "#+html: "
7973 "<literal style=\"html\">?</literal>")
7974 ("a" "#+begin_ascii\n?\n#+end_ascii")
7975 ("A" "#+ascii: ")
7976 ("i" "#+include %file ?"
7977 "<include file=%file markup=\"?\">")
7979 "Structure completion elements.
7980 This is a list of abbreviation keys and values. The value gets inserted
7981 it you type @samp{.} followed by the key and then the completion key,
7982 usually `M-TAB'. %file will be replaced by a file name after prompting
7983 for the file uning completion.
7984 There are two templates for each key, the first uses the original Org syntax,
7985 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7986 the default when the /org-mtags.el/ module has been loaded. See also the
7987 variable `org-mtags-prefere-muse-templates'.
7988 This is an experimental feature, it is undecided if it is going to stay in."
7989 :group 'org-completion
7990 :type '(repeat
7991 (string :tag "Key")
7992 (string :tag "Template")
7993 (string :tag "Muse Template")))
7995 (defun org-try-structure-completion ()
7996 "Try to complete a structure template before point.
7997 This looks for strings like \"<e\" on an otherwise empty line and
7998 expands them."
7999 (let ((l (buffer-substring (point-at-bol) (point)))
8001 (when (and (looking-at "[ \t]*$")
8002 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8003 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8004 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8005 (match-beginning 1)) a)
8006 t)))
8008 (defun org-complete-expand-structure-template (start cell)
8009 "Expand a structure template."
8010 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8011 (rpl (nth (if musep 2 1) cell)))
8012 (delete-region start (point))
8013 (when (string-match "\\`#\\+" rpl)
8014 (cond
8015 ((bolp))
8016 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8017 (delete-region (point-at-bol) (point)))
8018 (t (newline))))
8019 (setq start (point))
8020 (if (string-match "%file" rpl)
8021 (setq rpl (replace-match
8022 (concat
8023 "\""
8024 (save-match-data
8025 (abbreviate-file-name (read-file-name "Include file: ")))
8026 "\"")
8027 t t rpl)))
8028 (insert rpl)
8029 (if (re-search-backward "\\?" start t) (delete-char 1))))
8032 (defun org-complete (&optional arg)
8033 "Perform completion on word at point.
8034 At the beginning of a headline, this completes TODO keywords as given in
8035 `org-todo-keywords'.
8036 If the current word is preceded by a backslash, completes the TeX symbols
8037 that are supported for HTML support.
8038 If the current word is preceded by \"#+\", completes special words for
8039 setting file options.
8040 In the line after \"#+STARTUP:, complete valid keywords.\"
8041 At all other locations, this simply calls the value of
8042 `org-completion-fallback-command'."
8043 (interactive "P")
8044 (org-without-partial-completion
8045 (catch 'exit
8046 (let* ((a nil)
8047 (end (point))
8048 (beg1 (save-excursion
8049 (skip-chars-backward (org-re "[:alnum:]_@"))
8050 (point)))
8051 (beg (save-excursion
8052 (skip-chars-backward "a-zA-Z0-9_:$")
8053 (point)))
8054 (confirm (lambda (x) (stringp (car x))))
8055 (searchhead (equal (char-before beg) ?*))
8056 (struct
8057 (when (and (member (char-before beg1) '(?. ?<))
8058 (setq a (assoc (buffer-substring beg1 (point))
8059 org-structure-template-alist)))
8060 (org-complete-expand-structure-template (1- beg1) a)
8061 (throw 'exit t)))
8062 (tag (and (equal (char-before beg1) ?:)
8063 (equal (char-after (point-at-bol)) ?*)))
8064 (prop (and (equal (char-before beg1) ?:)
8065 (not (equal (char-after (point-at-bol)) ?*))))
8066 (texp (equal (char-before beg) ?\\))
8067 (link (equal (char-before beg) ?\[))
8068 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8069 beg)
8070 "#+"))
8071 (startup (string-match "^#\\+STARTUP:.*"
8072 (buffer-substring (point-at-bol) (point))))
8073 (completion-ignore-case opt)
8074 (type nil)
8075 (tbl nil)
8076 (table (cond
8077 (opt
8078 (setq type :opt)
8079 (require 'org-exp)
8080 (append
8081 (mapcar
8082 (lambda (x)
8083 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8084 (cons (match-string 2 x) (match-string 1 x)))
8085 (org-split-string (org-get-current-options) "\n"))
8086 (mapcar 'list org-additional-option-like-keywords)))
8087 (startup
8088 (setq type :startup)
8089 org-startup-options)
8090 (link (append org-link-abbrev-alist-local
8091 org-link-abbrev-alist))
8092 (texp
8093 (setq type :tex)
8094 org-html-entities)
8095 ((string-match "\\`\\*+[ \t]+\\'"
8096 (buffer-substring (point-at-bol) beg))
8097 (setq type :todo)
8098 (mapcar 'list org-todo-keywords-1))
8099 (searchhead
8100 (setq type :searchhead)
8101 (save-excursion
8102 (goto-char (point-min))
8103 (while (re-search-forward org-todo-line-regexp nil t)
8104 (push (list
8105 (org-make-org-heading-search-string
8106 (match-string 3) t))
8107 tbl)))
8108 tbl)
8109 (tag (setq type :tag beg beg1)
8110 (or org-tag-alist (org-get-buffer-tags)))
8111 (prop (setq type :prop beg beg1)
8112 (mapcar 'list (org-buffer-property-keys nil t t)))
8113 (t (progn
8114 (call-interactively org-completion-fallback-command)
8115 (throw 'exit nil)))))
8116 (pattern (buffer-substring-no-properties beg end))
8117 (completion (try-completion pattern table confirm)))
8118 (cond ((eq completion t)
8119 (if (not (assoc (upcase pattern) table))
8120 (message "Already complete")
8121 (if (and (equal type :opt)
8122 (not (member (car (assoc (upcase pattern) table))
8123 org-additional-option-like-keywords)))
8124 (insert (substring (cdr (assoc (upcase pattern) table))
8125 (length pattern)))
8126 (if (memq type '(:tag :prop)) (insert ":")))))
8127 ((null completion)
8128 (message "Can't find completion for \"%s\"" pattern)
8129 (ding))
8130 ((not (string= pattern completion))
8131 (delete-region beg end)
8132 (if (string-match " +$" completion)
8133 (setq completion (replace-match "" t t completion)))
8134 (insert completion)
8135 (if (get-buffer-window "*Completions*")
8136 (delete-window (get-buffer-window "*Completions*")))
8137 (if (assoc completion table)
8138 (if (eq type :todo) (insert " ")
8139 (if (memq type '(:tag :prop)) (insert ":"))))
8140 (if (and (equal type :opt) (assoc completion table))
8141 (message "%s" (substitute-command-keys
8142 "Press \\[org-complete] again to insert example settings"))))
8144 (message "Making completion list...")
8145 (let ((list (sort (all-completions pattern table confirm)
8146 'string<)))
8147 (with-output-to-temp-buffer "*Completions*"
8148 (condition-case nil
8149 ;; Protection needed for XEmacs and emacs 21
8150 (display-completion-list list pattern)
8151 (error (display-completion-list list)))))
8152 (message "Making completion list...%s" "done")))))))
8154 ;;;; TODO, DEADLINE, Comments
8156 (defun org-toggle-comment ()
8157 "Change the COMMENT state of an entry."
8158 (interactive)
8159 (save-excursion
8160 (org-back-to-heading)
8161 (let (case-fold-search)
8162 (if (looking-at (concat outline-regexp
8163 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8164 (replace-match "" t t nil 1)
8165 (if (looking-at outline-regexp)
8166 (progn
8167 (goto-char (match-end 0))
8168 (insert org-comment-string " ")))))))
8170 (defvar org-last-todo-state-is-todo nil
8171 "This is non-nil when the last TODO state change led to a TODO state.
8172 If the last change removed the TODO tag or switched to DONE, then
8173 this is nil.")
8175 (defvar org-setting-tags nil) ; dynamically skiped
8177 (defun org-parse-local-options (string var)
8178 "Parse STRING for startup setting relevant for variable VAR."
8179 (let ((rtn (symbol-value var))
8180 e opts)
8181 (save-match-data
8182 (if (or (not string) (not (string-match "\\S-" string)))
8184 (setq opts (delq nil (mapcar (lambda (x)
8185 (setq e (assoc x org-startup-options))
8186 (if (eq (nth 1 e) var) e nil))
8187 (org-split-string string "[ \t]+"))))
8188 (if (not opts)
8190 (setq rtn nil)
8191 (while (setq e (pop opts))
8192 (if (not (nth 3 e))
8193 (setq rtn (nth 2 e))
8194 (if (not (listp rtn)) (setq rtn nil))
8195 (push (nth 2 e) rtn)))
8196 rtn)))))
8198 (defvar org-blocker-hook nil
8199 "Hook for functions that are allowed to block a state change.
8201 Each function gets as its single argument a property list, see
8202 `org-trigger-hook' for more information about this list.
8204 If any of the functions in this hook returns nil, the state change
8205 is blocked.")
8207 (defvar org-trigger-hook nil
8208 "Hook for functions that are triggered by a state change.
8210 Each function gets as its single argument a property list with at least
8211 the following elements:
8213 (:type type-of-change :position pos-at-entry-start
8214 :from old-state :to new-state)
8216 Depending on the type, more properties may be present.
8218 This mechanism is currently implemented for:
8220 TODO state changes
8221 ------------------
8222 :type todo-state-change
8223 :from previous state (keyword as a string), or nil
8224 :to new state (keyword as a string), or nil")
8227 (defun org-todo (&optional arg)
8228 "Change the TODO state of an item.
8229 The state of an item is given by a keyword at the start of the heading,
8230 like
8231 *** TODO Write paper
8232 *** DONE Call mom
8234 The different keywords are specified in the variable `org-todo-keywords'.
8235 By default the available states are \"TODO\" and \"DONE\".
8236 So for this example: when the item starts with TODO, it is changed to DONE.
8237 When it starts with DONE, the DONE is removed. And when neither TODO nor
8238 DONE are present, add TODO at the beginning of the heading.
8240 With C-u prefix arg, use completion to determine the new state.
8241 With numeric prefix arg, switch to that state.
8243 For calling through lisp, arg is also interpreted in the following way:
8244 'none -> empty state
8245 \"\"(empty string) -> switch to empty state
8246 'done -> switch to DONE
8247 'nextset -> switch to the next set of keywords
8248 'previousset -> switch to the previous set of keywords
8249 \"WAITING\" -> switch to the specified keyword, but only if it
8250 really is a member of `org-todo-keywords'."
8251 (interactive "P")
8252 (save-excursion
8253 (catch 'exit
8254 (org-back-to-heading)
8255 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8256 (or (looking-at (concat " +" org-todo-regexp " *"))
8257 (looking-at " *"))
8258 (let* ((match-data (match-data))
8259 (startpos (point-at-bol))
8260 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8261 (org-log-done org-log-done)
8262 (org-log-repeat org-log-repeat)
8263 (org-todo-log-states org-todo-log-states)
8264 (this (match-string 1))
8265 (hl-pos (match-beginning 0))
8266 (head (org-get-todo-sequence-head this))
8267 (ass (assoc head org-todo-kwd-alist))
8268 (interpret (nth 1 ass))
8269 (done-word (nth 3 ass))
8270 (final-done-word (nth 4 ass))
8271 (last-state (or this ""))
8272 (completion-ignore-case t)
8273 (member (member this org-todo-keywords-1))
8274 (tail (cdr member))
8275 (state (cond
8276 ((and org-todo-key-trigger
8277 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8278 (and (not arg) org-use-fast-todo-selection
8279 (not (eq org-use-fast-todo-selection 'prefix)))))
8280 ;; Use fast selection
8281 (org-fast-todo-selection))
8282 ((and (equal arg '(4))
8283 (or (not org-use-fast-todo-selection)
8284 (not org-todo-key-trigger)))
8285 ;; Read a state with completion
8286 (completing-read "State: " (mapcar (lambda(x) (list x))
8287 org-todo-keywords-1)
8288 nil t))
8289 ((eq arg 'right)
8290 (if this
8291 (if tail (car tail) nil)
8292 (car org-todo-keywords-1)))
8293 ((eq arg 'left)
8294 (if (equal member org-todo-keywords-1)
8296 (if this
8297 (nth (- (length org-todo-keywords-1) (length tail) 2)
8298 org-todo-keywords-1)
8299 (org-last org-todo-keywords-1))))
8300 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8301 (setq arg nil))) ; hack to fall back to cycling
8302 (arg
8303 ;; user or caller requests a specific state
8304 (cond
8305 ((equal arg "") nil)
8306 ((eq arg 'none) nil)
8307 ((eq arg 'done) (or done-word (car org-done-keywords)))
8308 ((eq arg 'nextset)
8309 (or (car (cdr (member head org-todo-heads)))
8310 (car org-todo-heads)))
8311 ((eq arg 'previousset)
8312 (let ((org-todo-heads (reverse org-todo-heads)))
8313 (or (car (cdr (member head org-todo-heads)))
8314 (car org-todo-heads))))
8315 ((car (member arg org-todo-keywords-1)))
8316 ((nth (1- (prefix-numeric-value arg))
8317 org-todo-keywords-1))))
8318 ((null member) (or head (car org-todo-keywords-1)))
8319 ((equal this final-done-word) nil) ;; -> make empty
8320 ((null tail) nil) ;; -> first entry
8321 ((eq interpret 'sequence)
8322 (car tail))
8323 ((memq interpret '(type priority))
8324 (if (eq this-command last-command)
8325 (car tail)
8326 (if (> (length tail) 0)
8327 (or done-word (car org-done-keywords))
8328 nil)))
8329 (t nil)))
8330 (next (if state (concat " " state " ") " "))
8331 (change-plist (list :type 'todo-state-change :from this :to state
8332 :position startpos))
8333 dolog now-done-p)
8334 (when org-blocker-hook
8335 (unless (save-excursion
8336 (save-match-data
8337 (run-hook-with-args-until-failure
8338 'org-blocker-hook change-plist)))
8339 (if (interactive-p)
8340 (error "TODO state change from %s to %s blocked" this state)
8341 ;; fail silently
8342 (message "TODO state change from %s to %s blocked" this state)
8343 (throw 'exit nil))))
8344 (store-match-data match-data)
8345 (replace-match next t t)
8346 (unless (pos-visible-in-window-p hl-pos)
8347 (message "TODO state changed to %s" (org-trim next)))
8348 (unless head
8349 (setq head (org-get-todo-sequence-head state)
8350 ass (assoc head org-todo-kwd-alist)
8351 interpret (nth 1 ass)
8352 done-word (nth 3 ass)
8353 final-done-word (nth 4 ass)))
8354 (when (memq arg '(nextset previousset))
8355 (message "Keyword-Set %d/%d: %s"
8356 (- (length org-todo-sets) -1
8357 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8358 (length org-todo-sets)
8359 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8360 (setq org-last-todo-state-is-todo
8361 (not (member state org-done-keywords)))
8362 (setq now-done-p (and (member state org-done-keywords)
8363 (not (member this org-done-keywords))))
8364 (and logging (org-local-logging logging))
8365 (when (and (or org-todo-log-states org-log-done)
8366 (not (memq arg '(nextset previousset))))
8367 ;; we need to look at recording a time and note
8368 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8369 (nth 2 (assoc this org-todo-log-states))))
8370 (when (and state
8371 (member state org-not-done-keywords)
8372 (not (member this org-not-done-keywords)))
8373 ;; This is now a todo state and was not one before
8374 ;; If there was a CLOSED time stamp, get rid of it.
8375 (org-add-planning-info nil nil 'closed))
8376 (when (and now-done-p org-log-done)
8377 ;; It is now done, and it was not done before
8378 (org-add-planning-info 'closed (org-current-time))
8379 (if (and (not dolog) (eq 'note org-log-done))
8380 (org-add-log-setup 'done state 'findpos 'note)))
8381 (when (and state dolog)
8382 ;; This is a non-nil state, and we need to log it
8383 (org-add-log-setup 'state state 'findpos dolog)))
8384 ;; Fixup tag positioning
8385 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8386 (when org-provide-todo-statistics
8387 (org-update-parent-todo-statistics))
8388 (run-hooks 'org-after-todo-state-change-hook)
8389 (if (and arg (not (member state org-done-keywords)))
8390 (setq head (org-get-todo-sequence-head state)))
8391 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8392 ;; Do we need to trigger a repeat?
8393 (when now-done-p (org-auto-repeat-maybe state))
8394 ;; Fixup cursor location if close to the keyword
8395 (if (and (outline-on-heading-p)
8396 (not (bolp))
8397 (save-excursion (beginning-of-line 1)
8398 (looking-at org-todo-line-regexp))
8399 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8400 (progn
8401 (goto-char (or (match-end 2) (match-end 1)))
8402 (just-one-space)))
8403 (when org-trigger-hook
8404 (save-excursion
8405 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8407 (defun org-update-parent-todo-statistics ()
8408 "Update any statistics cookie in the parent of the current headline."
8409 (interactive)
8410 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8411 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8412 (catch 'exit
8413 (save-excursion
8414 (setq level (org-up-heading-safe))
8415 (unless (and level
8416 (re-search-forward box-re (point-at-eol) t))
8417 (throw 'exit nil))
8418 (setq is-percent (match-end 2))
8419 (save-match-data
8420 (unless (outline-next-heading) (throw 'exit nil))
8421 (while (looking-at org-todo-line-regexp)
8422 (setq kwd (match-string 2))
8423 (and kwd (setq cnt-all (1+ cnt-all)))
8424 (and (member kwd org-done-keywords)
8425 (setq cnt-done (1+ cnt-done)))
8426 (condition-case nil
8427 (outline-forward-same-level 1)
8428 (error (end-of-line 1)))))
8429 (replace-match
8430 (if is-percent
8431 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8432 (format "[%d/%d]" cnt-done cnt-all)))
8433 (run-hook-with-args 'org-after-todo-statistics-hook
8434 cnt-done (- cnt-all cnt-done))))))
8436 (defvar org-after-todo-statistics-hook nil
8437 "Hook that is called after a TODO statistics cookie has been updated.
8438 Each function is called with two arguments: the number of not-done entries
8439 and the number of done entries.
8441 For example, the following function, when added to this hook, will switch
8442 an entry to DONE when all children are done, and back to TODO when new
8443 entries are set to a TODO status. Note that this hook is only called
8444 when there is a statistics cookie in the headline!
8446 (defun org-summary-todo (n-done n-not-done)
8447 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8448 (let (org-log-done org-log-states) ; turn off logging
8449 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8452 (defun org-local-logging (value)
8453 "Get logging settings from a property VALUE."
8454 (let* (words w a)
8455 ;; directly set the variables, they are already local.
8456 (setq org-log-done nil
8457 org-log-repeat nil
8458 org-todo-log-states nil)
8459 (setq words (org-split-string value))
8460 (while (setq w (pop words))
8461 (cond
8462 ((setq a (assoc w org-startup-options))
8463 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8464 (set (nth 1 a) (nth 2 a))))
8465 ((setq a (org-extract-log-state-settings w))
8466 (and (member (car a) org-todo-keywords-1)
8467 (push a org-todo-log-states)))))))
8469 (defun org-get-todo-sequence-head (kwd)
8470 "Return the head of the TODO sequence to which KWD belongs.
8471 If KWD is not set, check if there is a text property remembering the
8472 right sequence."
8473 (let (p)
8474 (cond
8475 ((not kwd)
8476 (or (get-text-property (point-at-bol) 'org-todo-head)
8477 (progn
8478 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8479 nil (point-at-eol)))
8480 (get-text-property p 'org-todo-head))))
8481 ((not (member kwd org-todo-keywords-1))
8482 (car org-todo-keywords-1))
8483 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8485 (defun org-fast-todo-selection ()
8486 "Fast TODO keyword selection with single keys.
8487 Returns the new TODO keyword, or nil if no state change should occur."
8488 (let* ((fulltable org-todo-key-alist)
8489 (done-keywords org-done-keywords) ;; needed for the faces.
8490 (maxlen (apply 'max (mapcar
8491 (lambda (x)
8492 (if (stringp (car x)) (string-width (car x)) 0))
8493 fulltable)))
8494 (expert nil)
8495 (fwidth (+ maxlen 3 1 3))
8496 (ncol (/ (- (window-width) 4) fwidth))
8497 tg cnt e c tbl
8498 groups ingroup)
8499 (save-window-excursion
8500 (if expert
8501 (set-buffer (get-buffer-create " *Org todo*"))
8502 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8503 (erase-buffer)
8504 (org-set-local 'org-done-keywords done-keywords)
8505 (setq tbl fulltable cnt 0)
8506 (while (setq e (pop tbl))
8507 (cond
8508 ((equal e '(:startgroup))
8509 (push '() groups) (setq ingroup t)
8510 (when (not (= cnt 0))
8511 (setq cnt 0)
8512 (insert "\n"))
8513 (insert "{ "))
8514 ((equal e '(:endgroup))
8515 (setq ingroup nil cnt 0)
8516 (insert "}\n"))
8518 (setq tg (car e) c (cdr e))
8519 (if ingroup (push tg (car groups)))
8520 (setq tg (org-add-props tg nil 'face
8521 (org-get-todo-face tg)))
8522 (if (and (= cnt 0) (not ingroup)) (insert " "))
8523 (insert "[" c "] " tg (make-string
8524 (- fwidth 4 (length tg)) ?\ ))
8525 (when (= (setq cnt (1+ cnt)) ncol)
8526 (insert "\n")
8527 (if ingroup (insert " "))
8528 (setq cnt 0)))))
8529 (insert "\n")
8530 (goto-char (point-min))
8531 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8532 (fit-window-to-buffer))
8533 (message "[a-z..]:Set [SPC]:clear")
8534 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8535 (cond
8536 ((or (= c ?\C-g)
8537 (and (= c ?q) (not (rassoc c fulltable))))
8538 (setq quit-flag t))
8539 ((= c ?\ ) nil)
8540 ((setq e (rassoc c fulltable) tg (car e))
8542 (t (setq quit-flag t))))))
8544 (defun org-entry-is-todo-p ()
8545 (member (org-get-todo-state) org-not-done-keywords))
8547 (defun org-entry-is-done-p ()
8548 (member (org-get-todo-state) org-done-keywords))
8550 (defun org-get-todo-state ()
8551 (save-excursion
8552 (org-back-to-heading t)
8553 (and (looking-at org-todo-line-regexp)
8554 (match-end 2)
8555 (match-string 2))))
8557 (defun org-at-date-range-p (&optional inactive-ok)
8558 "Is the cursor inside a date range?"
8559 (interactive)
8560 (save-excursion
8561 (catch 'exit
8562 (let ((pos (point)))
8563 (skip-chars-backward "^[<\r\n")
8564 (skip-chars-backward "<[")
8565 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8566 (>= (match-end 0) pos)
8567 (throw 'exit t))
8568 (skip-chars-backward "^<[\r\n")
8569 (skip-chars-backward "<[")
8570 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8571 (>= (match-end 0) pos)
8572 (throw 'exit t)))
8573 nil)))
8575 (defun org-get-repeat ()
8576 "Check if tere is a deadline/schedule with repeater in this entry."
8577 (save-match-data
8578 (save-excursion
8579 (org-back-to-heading t)
8580 (if (re-search-forward
8581 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8582 (match-string 1)))))
8584 (defvar org-last-changed-timestamp)
8585 (defvar org-log-post-message)
8586 (defvar org-log-note-purpose)
8587 (defvar org-log-note-how)
8588 (defun org-auto-repeat-maybe (done-word)
8589 "Check if the current headline contains a repeated deadline/schedule.
8590 If yes, set TODO state back to what it was and change the base date
8591 of repeating deadline/scheduled time stamps to new date.
8592 This function is run automatically after each state change to a DONE state."
8593 ;; last-state is dynamically scoped into this function
8594 (let* ((repeat (org-get-repeat))
8595 (aa (assoc last-state org-todo-kwd-alist))
8596 (interpret (nth 1 aa))
8597 (head (nth 2 aa))
8598 (whata '(("d" . day) ("m" . month) ("y" . year)))
8599 (msg "Entry repeats: ")
8600 (org-log-done nil)
8601 (org-todo-log-states nil)
8602 (nshiftmax 10) (nshift 0)
8603 re type n what ts mb0 time)
8604 (when repeat
8605 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8606 (org-todo (if (eq interpret 'type) last-state head))
8607 (when org-log-repeat
8608 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8609 (memq 'org-add-log-note post-command-hook))
8610 ;; OK, we are already setup for some record
8611 (if (eq org-log-repeat 'note)
8612 ;; make sure we take a note, not only a time stamp
8613 (setq org-log-note-how 'note))
8614 ;; Set up for taking a record
8615 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8616 'findpos org-log-repeat)))
8617 (org-back-to-heading t)
8618 (org-add-planning-info nil nil 'closed)
8619 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8620 org-deadline-time-regexp "\\)\\|\\("
8621 org-ts-regexp "\\)"))
8622 (while (re-search-forward
8623 re (save-excursion (outline-next-heading) (point)) t)
8624 (setq type (if (match-end 1) org-scheduled-string
8625 (if (match-end 3) org-deadline-string "Plain:"))
8626 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8627 mb0 (match-beginning 0))
8628 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8629 (setq n (string-to-number (match-string 2 ts))
8630 what (match-string 3 ts))
8631 (if (equal what "w") (setq n (* n 7) what "d"))
8632 ;; Preparation, see if we need to modify the start date for the change
8633 (when (match-end 1)
8634 (setq time (save-match-data (org-time-string-to-time ts)))
8635 (cond
8636 ((equal (match-string 1 ts) ".")
8637 ;; Shift starting date to today
8638 (org-timestamp-change
8639 (- (time-to-days (current-time)) (time-to-days time))
8640 'day))
8641 ((equal (match-string 1 ts) "+")
8642 (while (or (= nshift 0)
8643 (<= (time-to-days time) (time-to-days (current-time))))
8644 (when (= (incf nshift) nshiftmax)
8645 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8646 (error "Abort")))
8647 (org-timestamp-change n (cdr (assoc what whata)))
8648 (org-at-timestamp-p t)
8649 (setq ts (match-string 1))
8650 (setq time (save-match-data (org-time-string-to-time ts))))
8651 (org-timestamp-change (- n) (cdr (assoc what whata)))
8652 ;; rematch, so that we have everything in place for the real shift
8653 (org-at-timestamp-p t)
8654 (setq ts (match-string 1))
8655 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8656 (org-timestamp-change n (cdr (assoc what whata)))
8657 (setq msg (concat msg type org-last-changed-timestamp " "))))
8658 (setq org-log-post-message msg)
8659 (message "%s" msg))))
8661 (defun org-show-todo-tree (arg)
8662 "Make a compact tree which shows all headlines marked with TODO.
8663 The tree will show the lines where the regexp matches, and all higher
8664 headlines above the match.
8665 With a \\[universal-argument] prefix, also show the DONE entries.
8666 With a numeric prefix N, construct a sparse tree for the Nth element
8667 of `org-todo-keywords-1'."
8668 (interactive "P")
8669 (let ((case-fold-search nil)
8670 (kwd-re
8671 (cond ((null arg) org-not-done-regexp)
8672 ((equal arg '(4))
8673 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8674 (mapcar 'list org-todo-keywords-1))))
8675 (concat "\\("
8676 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8677 "\\)\\>")))
8678 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8679 (regexp-quote (nth (1- (prefix-numeric-value arg))
8680 org-todo-keywords-1)))
8681 (t (error "Invalid prefix argument: %s" arg)))))
8682 (message "%d TODO entries found"
8683 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8685 (defun org-deadline (&optional remove)
8686 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8687 With argument REMOVE, remove any deadline from the item."
8688 (interactive "P")
8689 (if remove
8690 (progn
8691 (org-remove-timestamp-with-keyword org-deadline-string)
8692 (message "Item no longer has a deadline."))
8693 (org-add-planning-info 'deadline nil 'closed)))
8695 (defun org-schedule (&optional remove)
8696 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8697 With argument REMOVE, remove any scheduling date from the item."
8698 (interactive "P")
8699 (if remove
8700 (progn
8701 (org-remove-timestamp-with-keyword org-scheduled-string)
8702 (message "Item is no longer scheduled."))
8703 (org-add-planning-info 'scheduled nil 'closed)))
8705 (defun org-remove-timestamp-with-keyword (keyword)
8706 "Remove all time stamps with KEYWORD in the current entry."
8707 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8708 beg)
8709 (save-excursion
8710 (org-back-to-heading t)
8711 (setq beg (point))
8712 (org-end-of-subtree t t)
8713 (while (re-search-backward re beg t)
8714 (replace-match "")
8715 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8716 (equal (char-before) ?\ ))
8717 (backward-delete-char 1)
8718 (if (string-match "^[ \t]*$" (buffer-substring
8719 (point-at-bol) (point-at-eol)))
8720 (delete-region (point-at-bol)
8721 (min (point-max) (1+ (point-at-eol))))))))))
8723 (defun org-add-planning-info (what &optional time &rest remove)
8724 "Insert new timestamp with keyword in the line directly after the headline.
8725 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8726 If non is given, the user is prompted for a date.
8727 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8728 be removed."
8729 (interactive)
8730 (let (org-time-was-given org-end-time-was-given ts
8731 end default-time default-input)
8733 (when (and (not time) (memq what '(scheduled deadline)))
8734 ;; Try to get a default date/time from existing timestamp
8735 (save-excursion
8736 (org-back-to-heading t)
8737 (setq end (save-excursion (outline-next-heading) (point)))
8738 (when (re-search-forward (if (eq what 'scheduled)
8739 org-scheduled-time-regexp
8740 org-deadline-time-regexp)
8741 end t)
8742 (setq ts (match-string 1)
8743 default-time
8744 (apply 'encode-time (org-parse-time-string ts))
8745 default-input (and ts (org-get-compact-tod ts))))))
8746 (when what
8747 ;; If necessary, get the time from the user
8748 (setq time (or time (org-read-date nil 'to-time nil nil
8749 default-time default-input))))
8751 (when (and org-insert-labeled-timestamps-at-point
8752 (member what '(scheduled deadline)))
8753 (insert
8754 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8755 (org-insert-time-stamp time org-time-was-given
8756 nil nil nil (list org-end-time-was-given))
8757 (setq what nil))
8758 (save-excursion
8759 (save-restriction
8760 (let (col list elt ts buffer-invisibility-spec)
8761 (org-back-to-heading t)
8762 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8763 (goto-char (match-end 1))
8764 (setq col (current-column))
8765 (goto-char (match-end 0))
8766 (if (eobp) (insert "\n") (forward-char 1))
8767 (if (and (not (looking-at outline-regexp))
8768 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8769 "[^\r\n]*"))
8770 (not (equal (match-string 1) org-clock-string)))
8771 (narrow-to-region (match-beginning 0) (match-end 0))
8772 (insert-before-markers "\n")
8773 (backward-char 1)
8774 (narrow-to-region (point) (point))
8775 (and org-adapt-indentation (org-indent-to-column col)))
8776 ;; Check if we have to remove something.
8777 (setq list (cons what remove))
8778 (while list
8779 (setq elt (pop list))
8780 (goto-char (point-min))
8781 (when (or (and (eq elt 'scheduled)
8782 (re-search-forward org-scheduled-time-regexp nil t))
8783 (and (eq elt 'deadline)
8784 (re-search-forward org-deadline-time-regexp nil t))
8785 (and (eq elt 'closed)
8786 (re-search-forward org-closed-time-regexp nil t)))
8787 (replace-match "")
8788 (if (looking-at "--+<[^>]+>") (replace-match ""))
8789 (if (looking-at " +") (replace-match ""))))
8790 (goto-char (point-max))
8791 (when what
8792 (insert
8793 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8794 (cond ((eq what 'scheduled) org-scheduled-string)
8795 ((eq what 'deadline) org-deadline-string)
8796 ((eq what 'closed) org-closed-string))
8797 " ")
8798 (setq ts (org-insert-time-stamp
8799 time
8800 (or org-time-was-given
8801 (and (eq what 'closed) org-log-done-with-time))
8802 (eq what 'closed)
8803 nil nil (list org-end-time-was-given)))
8804 (end-of-line 1))
8805 (goto-char (point-min))
8806 (widen)
8807 (if (and (looking-at "[ \t]+\n")
8808 (equal (char-before) ?\n))
8809 (delete-region (1- (point)) (point-at-eol)))
8810 ts)))))
8812 (defvar org-log-note-marker (make-marker))
8813 (defvar org-log-note-purpose nil)
8814 (defvar org-log-note-state nil)
8815 (defvar org-log-note-how nil)
8816 (defvar org-log-note-window-configuration nil)
8817 (defvar org-log-note-return-to (make-marker))
8818 (defvar org-log-post-message nil
8819 "Message to be displayed after a log note has been stored.
8820 The auto-repeater uses this.")
8822 (defun org-add-note ()
8823 "Add a note to the current entry.
8824 This is done in the same way as adding a state change note."
8825 (interactive)
8826 (org-add-log-setup 'note nil t nil))
8828 (defun org-add-log-setup (&optional purpose state findpos how)
8829 "Set up the post command hook to take a note.
8830 If this is about to TODO state change, the new state is expected in STATE.
8831 When FINDPOS is non-nil, find the correct position for the note in
8832 the current entry. If not, assume that it can be inserted at point."
8833 (save-excursion
8834 (when findpos
8835 (org-back-to-heading t)
8836 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8837 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8838 "[^\r\n]*\\)?"))
8839 (goto-char (match-end 0))
8840 (unless org-log-states-order-reversed
8841 (and (= (char-after) ?\n) (forward-char 1))
8842 (org-skip-over-state-notes)
8843 (skip-chars-backward " \t\n\r")))
8844 (move-marker org-log-note-marker (point))
8845 (setq org-log-note-purpose purpose
8846 org-log-note-state state
8847 org-log-note-how how)
8848 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8850 (defun org-skip-over-state-notes ()
8851 "Skip past the list of State notes in an entry."
8852 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8853 (while (looking-at "[ \t]*- State")
8854 (condition-case nil
8855 (org-next-item)
8856 (error (org-end-of-item)))))
8858 (defun org-add-log-note (&optional purpose)
8859 "Pop up a window for taking a note, and add this note later at point."
8860 (remove-hook 'post-command-hook 'org-add-log-note)
8861 (setq org-log-note-window-configuration (current-window-configuration))
8862 (delete-other-windows)
8863 (move-marker org-log-note-return-to (point))
8864 (switch-to-buffer (marker-buffer org-log-note-marker))
8865 (goto-char org-log-note-marker)
8866 (org-switch-to-buffer-other-window "*Org Note*")
8867 (erase-buffer)
8868 (if (memq org-log-note-how '(time state))
8869 (org-store-log-note)
8870 (let ((org-inhibit-startup t)) (org-mode))
8871 (insert (format "# Insert note for %s.
8872 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8873 (cond
8874 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8875 ((eq org-log-note-purpose 'done) "closed todo item")
8876 ((eq org-log-note-purpose 'state)
8877 (format "state change to \"%s\"" org-log-note-state))
8878 ((eq org-log-note-purpose 'note)
8879 "this entry")
8880 (t (error "This should not happen")))))
8881 (org-set-local 'org-finish-function 'org-store-log-note)))
8883 (defvar org-note-abort nil) ; dynamically scoped
8884 (defun org-store-log-note ()
8885 "Finish taking a log note, and insert it to where it belongs."
8886 (let ((txt (buffer-string))
8887 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8888 lines ind)
8889 (kill-buffer (current-buffer))
8890 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8891 (setq txt (replace-match "" t t txt)))
8892 (if (string-match "\\s-+\\'" txt)
8893 (setq txt (replace-match "" t t txt)))
8894 (setq lines (org-split-string txt "\n"))
8895 (when (and note (string-match "\\S-" note))
8896 (setq note
8897 (org-replace-escapes
8898 note
8899 (list (cons "%u" (user-login-name))
8900 (cons "%U" user-full-name)
8901 (cons "%t" (format-time-string
8902 (org-time-stamp-format 'long 'inactive)
8903 (current-time)))
8904 (cons "%s" (if org-log-note-state
8905 (concat "\"" org-log-note-state "\"")
8906 "")))))
8907 (if lines (setq note (concat note " \\\\")))
8908 (push note lines))
8909 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8910 (when lines
8911 (save-excursion
8912 (set-buffer (marker-buffer org-log-note-marker))
8913 (save-excursion
8914 (goto-char org-log-note-marker)
8915 (move-marker org-log-note-marker nil)
8916 (end-of-line 1)
8917 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8918 (indent-relative nil)
8919 (insert "- " (pop lines))
8920 (org-indent-line-function)
8921 (beginning-of-line 1)
8922 (looking-at "[ \t]*")
8923 (setq ind (concat (match-string 0) " "))
8924 (end-of-line 1)
8925 (while lines (insert "\n" ind (pop lines)))))))
8926 (set-window-configuration org-log-note-window-configuration)
8927 (with-current-buffer (marker-buffer org-log-note-return-to)
8928 (goto-char org-log-note-return-to))
8929 (move-marker org-log-note-return-to nil)
8930 (and org-log-post-message (message "%s" org-log-post-message)))
8932 (defun org-sparse-tree (&optional arg)
8933 "Create a sparse tree, prompt for the details.
8934 This command can create sparse trees. You first need to select the type
8935 of match used to create the tree:
8937 t Show entries with a specific TODO keyword.
8938 T Show entries selected by a tags match.
8939 p Enter a property name and its value (both with completion on existing
8940 names/values) and show entries with that property.
8941 r Show entries matching a regular expression
8942 d Show deadlines due within `org-deadline-warning-days'."
8943 (interactive "P")
8944 (let (ans kwd value)
8945 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8946 (setq ans (read-char-exclusive))
8947 (cond
8948 ((equal ans ?d)
8949 (call-interactively 'org-check-deadlines))
8950 ((equal ans ?b)
8951 (call-interactively 'org-check-before-date))
8952 ((equal ans ?t)
8953 (org-show-todo-tree '(4)))
8954 ((equal ans ?T)
8955 (call-interactively 'org-tags-sparse-tree))
8956 ((member ans '(?p ?P))
8957 (setq kwd (completing-read "Property: "
8958 (mapcar 'list (org-buffer-property-keys))))
8959 (setq value (completing-read "Value: "
8960 (mapcar 'list (org-property-values kwd))))
8961 (unless (string-match "\\`{.*}\\'" value)
8962 (setq value (concat "\"" value "\"")))
8963 (org-tags-sparse-tree arg (concat kwd "=" value)))
8964 ((member ans '(?r ?R ?/))
8965 (call-interactively 'org-occur))
8966 (t (error "No such sparse tree command \"%c\"" ans)))))
8968 (defvar org-occur-highlights nil
8969 "List of overlays used for occur matches.")
8970 (make-variable-buffer-local 'org-occur-highlights)
8971 (defvar org-occur-parameters nil
8972 "Parameters of the active org-occur calls.
8973 This is a list, each call to org-occur pushes as cons cell,
8974 containing the regular expression and the callback, onto the list.
8975 The list can contain several entries if `org-occur' has been called
8976 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8977 will only contain one set of parameters. When the highlights are
8978 removed (for example with `C-c C-c', or with the next edit (depending
8979 on `org-remove-highlights-with-change'), this variable is emptied
8980 as well.")
8981 (make-variable-buffer-local 'org-occur-parameters)
8983 (defun org-occur (regexp &optional keep-previous callback)
8984 "Make a compact tree which shows all matches of REGEXP.
8985 The tree will show the lines where the regexp matches, and all higher
8986 headlines above the match. It will also show the heading after the match,
8987 to make sure editing the matching entry is easy.
8988 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8989 call to `org-occur' will be kept, to allow stacking of calls to this
8990 command.
8991 If CALLBACK is non-nil, it is a function which is called to confirm
8992 that the match should indeed be shown."
8993 (interactive "sRegexp: \nP")
8994 (unless keep-previous
8995 (org-remove-occur-highlights nil nil t))
8996 (push (cons regexp callback) org-occur-parameters)
8997 (let ((cnt 0))
8998 (save-excursion
8999 (goto-char (point-min))
9000 (if (or (not keep-previous) ; do not want to keep
9001 (not org-occur-highlights)) ; no previous matches
9002 ;; hide everything
9003 (org-overview))
9004 (while (re-search-forward regexp nil t)
9005 (when (or (not callback)
9006 (save-match-data (funcall callback)))
9007 (setq cnt (1+ cnt))
9008 (when org-highlight-sparse-tree-matches
9009 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9010 (org-show-context 'occur-tree))))
9011 (when org-remove-highlights-with-change
9012 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9013 nil 'local))
9014 (unless org-sparse-tree-open-archived-trees
9015 (org-hide-archived-subtrees (point-min) (point-max)))
9016 (run-hooks 'org-occur-hook)
9017 (if (interactive-p)
9018 (message "%d match(es) for regexp %s" cnt regexp))
9019 cnt))
9021 (defun org-show-context (&optional key)
9022 "Make sure point and context and visible.
9023 How much context is shown depends upon the variables
9024 `org-show-hierarchy-above', `org-show-following-heading'. and
9025 `org-show-siblings'."
9026 (let ((heading-p (org-on-heading-p t))
9027 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9028 (following-p (org-get-alist-option org-show-following-heading key))
9029 (entry-p (org-get-alist-option org-show-entry-below key))
9030 (siblings-p (org-get-alist-option org-show-siblings key)))
9031 (catch 'exit
9032 ;; Show heading or entry text
9033 (if (and heading-p (not entry-p))
9034 (org-flag-heading nil) ; only show the heading
9035 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9036 (org-show-hidden-entry))) ; show entire entry
9037 (when following-p
9038 ;; Show next sibling, or heading below text
9039 (save-excursion
9040 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9041 (org-flag-heading nil))))
9042 (when siblings-p (org-show-siblings))
9043 (when hierarchy-p
9044 ;; show all higher headings, possibly with siblings
9045 (save-excursion
9046 (while (and (condition-case nil
9047 (progn (org-up-heading-all 1) t)
9048 (error nil))
9049 (not (bobp)))
9050 (org-flag-heading nil)
9051 (when siblings-p (org-show-siblings))))))))
9053 (defun org-reveal (&optional siblings)
9054 "Show current entry, hierarchy above it, and the following headline.
9055 This can be used to show a consistent set of context around locations
9056 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9057 not t for the search context.
9059 With optional argument SIBLINGS, on each level of the hierarchy all
9060 siblings are shown. This repairs the tree structure to what it would
9061 look like when opened with hierarchical calls to `org-cycle'."
9062 (interactive "P")
9063 (let ((org-show-hierarchy-above t)
9064 (org-show-following-heading t)
9065 (org-show-siblings (if siblings t org-show-siblings)))
9066 (org-show-context nil)))
9068 (defun org-highlight-new-match (beg end)
9069 "Highlight from BEG to END and mark the highlight is an occur headline."
9070 (let ((ov (org-make-overlay beg end)))
9071 (org-overlay-put ov 'face 'secondary-selection)
9072 (push ov org-occur-highlights)))
9074 (defun org-remove-occur-highlights (&optional beg end noremove)
9075 "Remove the occur highlights from the buffer.
9076 BEG and END are ignored. If NOREMOVE is nil, remove this function
9077 from the `before-change-functions' in the current buffer."
9078 (interactive)
9079 (unless org-inhibit-highlight-removal
9080 (mapc 'org-delete-overlay org-occur-highlights)
9081 (setq org-occur-highlights nil)
9082 (setq org-occur-parameters nil)
9083 (unless noremove
9084 (remove-hook 'before-change-functions
9085 'org-remove-occur-highlights 'local))))
9087 ;;;; Priorities
9089 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9090 "Regular expression matching the priority indicator.")
9092 (defvar org-remove-priority-next-time nil)
9094 (defun org-priority-up ()
9095 "Increase the priority of the current item."
9096 (interactive)
9097 (org-priority 'up))
9099 (defun org-priority-down ()
9100 "Decrease the priority of the current item."
9101 (interactive)
9102 (org-priority 'down))
9104 (defun org-priority (&optional action)
9105 "Change the priority of an item by ARG.
9106 ACTION can be `set', `up', `down', or a character."
9107 (interactive)
9108 (setq action (or action 'set))
9109 (let (current new news have remove)
9110 (save-excursion
9111 (org-back-to-heading)
9112 (if (looking-at org-priority-regexp)
9113 (setq current (string-to-char (match-string 2))
9114 have t)
9115 (setq current org-default-priority))
9116 (cond
9117 ((or (eq action 'set)
9118 (if (featurep 'xemacs) (characterp action) (integerp action)))
9119 (if (not (eq action 'set))
9120 (setq new action)
9121 (message "Priority %c-%c, SPC to remove: "
9122 org-highest-priority org-lowest-priority)
9123 (setq new (read-char-exclusive)))
9124 (if (and (= (upcase org-highest-priority) org-highest-priority)
9125 (= (upcase org-lowest-priority) org-lowest-priority))
9126 (setq new (upcase new)))
9127 (cond ((equal new ?\ ) (setq remove t))
9128 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9129 (error "Priority must be between `%c' and `%c'"
9130 org-highest-priority org-lowest-priority))))
9131 ((eq action 'up)
9132 (if (and (not have) (eq last-command this-command))
9133 (setq new org-lowest-priority)
9134 (setq new (if (and org-priority-start-cycle-with-default (not have))
9135 org-default-priority (1- current)))))
9136 ((eq action 'down)
9137 (if (and (not have) (eq last-command this-command))
9138 (setq new org-highest-priority)
9139 (setq new (if (and org-priority-start-cycle-with-default (not have))
9140 org-default-priority (1+ current)))))
9141 (t (error "Invalid action")))
9142 (if (or (< (upcase new) org-highest-priority)
9143 (> (upcase new) org-lowest-priority))
9144 (setq remove t))
9145 (setq news (format "%c" new))
9146 (if have
9147 (if remove
9148 (replace-match "" t t nil 1)
9149 (replace-match news t t nil 2))
9150 (if remove
9151 (error "No priority cookie found in line")
9152 (looking-at org-todo-line-regexp)
9153 (if (match-end 2)
9154 (progn
9155 (goto-char (match-end 2))
9156 (insert " [#" news "]"))
9157 (goto-char (match-beginning 3))
9158 (insert "[#" news "] ")))))
9159 (org-preserve-lc (org-set-tags nil 'align))
9160 (if remove
9161 (message "Priority removed")
9162 (message "Priority of current item set to %s" news))))
9165 (defun org-get-priority (s)
9166 "Find priority cookie and return priority."
9167 (save-match-data
9168 (if (not (string-match org-priority-regexp s))
9169 (* 1000 (- org-lowest-priority org-default-priority))
9170 (* 1000 (- org-lowest-priority
9171 (string-to-char (match-string 2 s)))))))
9173 ;;;; Tags
9175 (defun org-scan-tags (action matcher &optional todo-only)
9176 "Scan headline tags with inheritance and produce output ACTION.
9177 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9178 evaluated, testing if a given set of tags qualifies a headline for
9179 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9180 are included in the output."
9181 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9182 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9183 (org-re
9184 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9185 (props (list 'face nil
9186 'done-face 'org-done
9187 'undone-face nil
9188 'mouse-face 'highlight
9189 'org-not-done-regexp org-not-done-regexp
9190 'org-todo-regexp org-todo-regexp
9191 'keymap org-agenda-keymap
9192 'help-echo
9193 (format "mouse-2 or RET jump to org file %s"
9194 (abbreviate-file-name
9195 (or (buffer-file-name (buffer-base-buffer))
9196 (buffer-name (buffer-base-buffer)))))))
9197 (case-fold-search nil)
9198 lspos tags tags-list
9199 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9200 (llast 0) rtn level category i txt
9201 todo marker entry priority)
9202 (save-excursion
9203 (goto-char (point-min))
9204 (when (eq action 'sparse-tree)
9205 (org-overview)
9206 (org-remove-occur-highlights))
9207 (while (re-search-forward re nil t)
9208 (catch :skip
9209 (setq todo (if (match-end 1) (match-string 2))
9210 tags (if (match-end 4) (match-string 4)))
9211 (goto-char (setq lspos (1+ (match-beginning 0))))
9212 (setq level (org-reduced-level (funcall outline-level))
9213 category (org-get-category))
9214 (setq i llast llast level)
9215 ;; remove tag lists from same and sublevels
9216 (while (>= i level)
9217 (when (setq entry (assoc i tags-alist))
9218 (setq tags-alist (delete entry tags-alist)))
9219 (setq i (1- i)))
9220 ;; add the next tags
9221 (when tags
9222 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9223 tags-alist
9224 (cons (cons level tags) tags-alist)))
9225 ;; compile tags for current headline
9226 (setq tags-list
9227 (if org-use-tag-inheritance
9228 (apply 'append (mapcar 'cdr tags-alist))
9229 tags))
9230 (when (and tags org-use-tag-inheritance
9231 (not (eq t org-use-tag-inheritance)))
9232 ;; selective inheritance, remove uninherited ones
9233 (setcdr (car tags-alist)
9234 (org-remove-uniherited-tags (cdar tags-alist))))
9235 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9236 (eval matcher)
9237 (or (not org-agenda-skip-archived-trees)
9238 (not (member org-archive-tag tags-list))))
9239 (and (eq action 'agenda) (org-agenda-skip))
9240 ;; list this headline
9242 (if (eq action 'sparse-tree)
9243 (progn
9244 (and org-highlight-sparse-tree-matches
9245 (org-get-heading) (match-end 0)
9246 (org-highlight-new-match
9247 (match-beginning 0) (match-beginning 1)))
9248 (org-show-context 'tags-tree))
9249 (setq txt (org-format-agenda-item
9251 (concat
9252 (if org-tags-match-list-sublevels
9253 (make-string (1- level) ?.) "")
9254 (org-get-heading))
9255 category tags-list)
9256 priority (org-get-priority txt))
9257 (goto-char lspos)
9258 (setq marker (org-agenda-new-marker))
9259 (org-add-props txt props
9260 'org-marker marker 'org-hd-marker marker 'org-category category
9261 'priority priority 'type "tagsmatch")
9262 (push txt rtn))
9263 ;; if we are to skip sublevels, jump to end of subtree
9264 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9265 (when (and (eq action 'sparse-tree)
9266 (not org-sparse-tree-open-archived-trees))
9267 (org-hide-archived-subtrees (point-min) (point-max)))
9268 (nreverse rtn)))
9270 (defun org-remove-uniherited-tags (tags)
9271 "Remove all tags that are not inherited from the list TAGS."
9272 (cond
9273 ((eq org-use-tag-inheritance t) tags)
9274 ((not org-use-tag-inheritance) nil)
9275 ((stringp org-use-tag-inheritance)
9276 (delq nil (mapcar
9277 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9278 tags)))
9279 ((listp org-use-tag-inheritance)
9280 (org-delete-all org-use-tag-inheritance tags))))
9282 (defvar todo-only) ;; dynamically scoped
9284 (defun org-tags-sparse-tree (&optional todo-only match)
9285 "Create a sparse tree according to tags string MATCH.
9286 MATCH can contain positive and negative selection of tags, like
9287 \"+WORK+URGENT-WITHBOSS\".
9288 If optional argument TODO_ONLY is non-nil, only select lines that are
9289 also TODO lines."
9290 (interactive "P")
9291 (org-prepare-agenda-buffers (list (current-buffer)))
9292 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9294 (defvar org-cached-props nil)
9295 (defun org-cached-entry-get (pom property)
9296 (if (or (eq t org-use-property-inheritance)
9297 (and (stringp org-use-property-inheritance)
9298 (string-match org-use-property-inheritance property))
9299 (and (listp org-use-property-inheritance)
9300 (member property org-use-property-inheritance)))
9301 ;; Caching is not possible, check it directly
9302 (org-entry-get pom property 'inherit)
9303 ;; Get all properties, so that we can do complicated checks easily
9304 (cdr (assoc property (or org-cached-props
9305 (setq org-cached-props
9306 (org-entry-properties pom)))))))
9308 (defun org-global-tags-completion-table (&optional files)
9309 "Return the list of all tags in all agenda buffer/files."
9310 (save-excursion
9311 (org-uniquify
9312 (delq nil
9313 (apply 'append
9314 (mapcar
9315 (lambda (file)
9316 (set-buffer (find-file-noselect file))
9317 (append (org-get-buffer-tags)
9318 (mapcar (lambda (x) (if (stringp (car-safe x))
9319 (list (car-safe x)) nil))
9320 org-tag-alist)))
9321 (if (and files (car files))
9322 files
9323 (org-agenda-files))))))))
9325 (defun org-make-tags-matcher (match)
9326 "Create the TAGS//TODO matcher form for the selection string MATCH."
9327 ;; todo-only is scoped dynamically into this function, and the function
9328 ;; may change it it the matcher asksk for it.
9329 (unless match
9330 ;; Get a new match request, with completion
9331 (let ((org-last-tags-completion-table
9332 (org-global-tags-completion-table)))
9333 (setq match (completing-read
9334 "Match: " 'org-tags-completion-function nil nil nil
9335 'org-tags-history))))
9337 ;; Parse the string and create a lisp form
9338 (let ((match0 match)
9339 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9340 minus tag mm
9341 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9342 orterms term orlist re-p str-p level-p level-op
9343 prop-p pn pv po cat-p gv)
9344 (if (string-match "/+" match)
9345 ;; match contains also a todo-matching request
9346 (progn
9347 (setq tagsmatch (substring match 0 (match-beginning 0))
9348 todomatch (substring match (match-end 0)))
9349 (if (string-match "^!" todomatch)
9350 (setq todo-only t todomatch (substring todomatch 1)))
9351 (if (string-match "^\\s-*$" todomatch)
9352 (setq todomatch nil)))
9353 ;; only matching tags
9354 (setq tagsmatch match todomatch nil))
9356 ;; Make the tags matcher
9357 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9358 (setq tagsmatcher t)
9359 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9360 (while (setq term (pop orterms))
9361 (while (and (equal (substring term -1) "\\") orterms)
9362 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9363 (while (string-match re term)
9364 (setq minus (and (match-end 1)
9365 (equal (match-string 1 term) "-"))
9366 tag (match-string 2 term)
9367 re-p (equal (string-to-char tag) ?{)
9368 level-p (match-end 4)
9369 prop-p (match-end 5)
9370 mm (cond
9371 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9372 (level-p
9373 (setq level-op (org-op-to-function (match-string 3 term)))
9374 `(,level-op level ,(string-to-number
9375 (match-string 4 term))))
9376 (prop-p
9377 (setq pn (match-string 5 term)
9378 po (match-string 6 term)
9379 pv (match-string 7 term)
9380 cat-p (equal pn "CATEGORY")
9381 re-p (equal (string-to-char pv) ?{)
9382 str-p (equal (string-to-char pv) ?\")
9383 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9384 (setq po (org-op-to-function po str-p))
9385 (if (equal pn "CATEGORY")
9386 (setq gv '(get-text-property (point) 'org-category))
9387 (setq gv `(org-cached-entry-get nil ,pn)))
9388 (if re-p
9389 (if (eq po 'org<>)
9390 `(not (string-match ,pv (or ,gv "")))
9391 `(string-match ,pv (or ,gv "")))
9392 (if str-p
9393 `(,po (or ,gv "") ,pv)
9394 `(,po (string-to-number (or ,gv ""))
9395 ,(string-to-number pv) ))))
9396 (t `(member ,(downcase tag) tags-list)))
9397 mm (if minus (list 'not mm) mm)
9398 term (substring term (match-end 0)))
9399 (push mm tagsmatcher))
9400 (push (if (> (length tagsmatcher) 1)
9401 (cons 'and tagsmatcher)
9402 (car tagsmatcher))
9403 orlist)
9404 (setq tagsmatcher nil))
9405 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9406 (setq tagsmatcher
9407 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9408 ;; Make the todo matcher
9409 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9410 (setq todomatcher t)
9411 (setq orterms (org-split-string todomatch "|") orlist nil)
9412 (while (setq term (pop orterms))
9413 (while (string-match re term)
9414 (setq minus (and (match-end 1)
9415 (equal (match-string 1 term) "-"))
9416 kwd (match-string 2 term)
9417 re-p (equal (string-to-char kwd) ?{)
9418 term (substring term (match-end 0))
9419 mm (if re-p
9420 `(string-match ,(substring kwd 1 -1) todo)
9421 (list 'equal 'todo kwd))
9422 mm (if minus (list 'not mm) mm))
9423 (push mm todomatcher))
9424 (push (if (> (length todomatcher) 1)
9425 (cons 'and todomatcher)
9426 (car todomatcher))
9427 orlist)
9428 (setq todomatcher nil))
9429 (setq todomatcher (if (> (length orlist) 1)
9430 (cons 'or orlist) (car orlist))))
9432 ;; Return the string and lisp forms of the matcher
9433 (setq matcher (if todomatcher
9434 (list 'and tagsmatcher todomatcher)
9435 tagsmatcher))
9436 (cons match0 matcher)))
9438 (defun org-op-to-function (op &optional stringp)
9439 (setq op
9440 (cond
9441 ((equal op "<" ) '(< string< ))
9442 ((equal op ">" ) '(> org-string> ))
9443 ((member op '("<=" "=<")) '(<= org-string<= ))
9444 ((member op '(">=" "=>")) '(>= org-string>= ))
9445 ((member op '("=" "==")) '(= string= ))
9446 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9447 (nth (if stringp 1 0) op))
9449 (defun org<> (a b) (not (= a b)))
9450 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9451 (defun org-string>= (a b) (not (string< a b)))
9452 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9453 (defun org-string<> (a b) (not (string= a b)))
9455 (defun org-match-any-p (re list)
9456 "Does re match any element of list?"
9457 (setq list (mapcar (lambda (x) (string-match re x)) list))
9458 (delq nil list))
9460 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9461 (defvar org-tags-overlay (org-make-overlay 1 1))
9462 (org-detach-overlay org-tags-overlay)
9464 (defun org-get-tags-at (&optional pos)
9465 "Get a list of all headline tags applicable at POS.
9466 POS defaults to point. If tags are inherited, the list contains
9467 the targets in the same sequence as the headlines appear, i.e.
9468 sthe tags of the current headline come last."
9469 (interactive)
9470 (let (tags ltags lastpos parent)
9471 (save-excursion
9472 (save-restriction
9473 (widen)
9474 (goto-char (or pos (point)))
9475 (save-match-data
9476 (condition-case nil
9477 (progn
9478 (org-back-to-heading t)
9479 (while (not (equal lastpos (point)))
9480 (setq lastpos (point))
9481 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9482 (setq ltags (org-split-string
9483 (org-match-string-no-properties 1) ":"))
9484 (setq tags (append (org-remove-uniherited-tags ltags)
9485 tags)))
9486 (or org-use-tag-inheritance (error ""))
9487 (org-up-heading-all 1)
9488 (setq parent t)))
9489 (error nil))))
9490 tags)))
9492 (defun org-toggle-tag (tag &optional onoff)
9493 "Toggle the tag TAG for the current line.
9494 If ONOFF is `on' or `off', don't toggle but set to this state."
9495 (unless (org-on-heading-p t) (error "Not on headling"))
9496 (let (res current)
9497 (save-excursion
9498 (beginning-of-line)
9499 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9500 (point-at-eol) t)
9501 (progn
9502 (setq current (match-string 1))
9503 (replace-match ""))
9504 (setq current ""))
9505 (setq current (nreverse (org-split-string current ":")))
9506 (cond
9507 ((eq onoff 'on)
9508 (setq res t)
9509 (or (member tag current) (push tag current)))
9510 ((eq onoff 'off)
9511 (or (not (member tag current)) (setq current (delete tag current))))
9512 (t (if (member tag current)
9513 (setq current (delete tag current))
9514 (setq res t)
9515 (push tag current))))
9516 (end-of-line 1)
9517 (if current
9518 (progn
9519 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9520 (org-set-tags nil t))
9521 (delete-horizontal-space))
9522 (run-hooks 'org-after-tags-change-hook))
9523 res))
9525 (defun org-align-tags-here (to-col)
9526 ;; Assumes that this is a headline
9527 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9528 (beginning-of-line 1)
9529 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9530 (< pos (match-beginning 2)))
9531 (progn
9532 (setq tags-l (- (match-end 2) (match-beginning 2)))
9533 (goto-char (match-beginning 1))
9534 (insert " ")
9535 (delete-region (point) (1+ (match-beginning 2)))
9536 (setq ncol (max (1+ (current-column))
9537 (1+ col)
9538 (if (> to-col 0)
9539 to-col
9540 (- (abs to-col) tags-l))))
9541 (setq p (point))
9542 (insert (make-string (- ncol (current-column)) ?\ ))
9543 (setq ncol (current-column))
9544 (tabify p (point-at-eol))
9545 (org-move-to-column (min ncol col) t))
9546 (goto-char pos))))
9548 (defun org-set-tags (&optional arg just-align)
9549 "Set the tags for the current headline.
9550 With prefix ARG, realign all tags in headings in the current buffer."
9551 (interactive "P")
9552 (let* ((re (concat "^" outline-regexp))
9553 (current (org-get-tags-string))
9554 (col (current-column))
9555 (org-setting-tags t)
9556 table current-tags inherited-tags ; computed below when needed
9557 tags p0 c0 c1 rpl)
9558 (if arg
9559 (save-excursion
9560 (goto-char (point-min))
9561 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9562 (while (re-search-forward re nil t)
9563 (org-set-tags nil t)
9564 (end-of-line 1)))
9565 (message "All tags realigned to column %d" org-tags-column))
9566 (if just-align
9567 (setq tags current)
9568 ;; Get a new set of tags from the user
9569 (save-excursion
9570 (setq table (or org-tag-alist (org-get-buffer-tags))
9571 org-last-tags-completion-table table
9572 current-tags (org-split-string current ":")
9573 inherited-tags (nreverse
9574 (nthcdr (length current-tags)
9575 (nreverse (org-get-tags-at))))
9576 tags
9577 (if (or (eq t org-use-fast-tag-selection)
9578 (and org-use-fast-tag-selection
9579 (delq nil (mapcar 'cdr table))))
9580 (org-fast-tag-selection
9581 current-tags inherited-tags table
9582 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9583 (let ((org-add-colon-after-tag-completion t))
9584 (org-trim
9585 (org-without-partial-completion
9586 (completing-read "Tags: " 'org-tags-completion-function
9587 nil nil current 'org-tags-history)))))))
9588 (while (string-match "[-+&]+" tags)
9589 ;; No boolean logic, just a list
9590 (setq tags (replace-match ":" t t tags))))
9592 (if (string-match "\\`[\t ]*\\'" tags)
9593 (setq tags "")
9594 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9595 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9597 ;; Insert new tags at the correct column
9598 (beginning-of-line 1)
9599 (cond
9600 ((and (equal current "") (equal tags "")))
9601 ((re-search-forward
9602 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9603 (point-at-eol) t)
9604 (if (equal tags "")
9605 (setq rpl "")
9606 (goto-char (match-beginning 0))
9607 (setq c0 (current-column) p0 (point)
9608 c1 (max (1+ c0) (if (> org-tags-column 0)
9609 org-tags-column
9610 (- (- org-tags-column) (length tags))))
9611 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9612 (replace-match rpl t t)
9613 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9614 tags)
9615 (t (error "Tags alignment failed")))
9616 (org-move-to-column col)
9617 (unless just-align
9618 (run-hooks 'org-after-tags-change-hook)))))
9620 (defun org-change-tag-in-region (beg end tag off)
9621 "Add or remove TAG for each entry in the region.
9622 This works in the agenda, and also in an org-mode buffer."
9623 (interactive
9624 (list (region-beginning) (region-end)
9625 (let ((org-last-tags-completion-table
9626 (if (org-mode-p)
9627 (org-get-buffer-tags)
9628 (org-global-tags-completion-table))))
9629 (completing-read
9630 "Tag: " 'org-tags-completion-function nil nil nil
9631 'org-tags-history))
9632 (progn
9633 (message "[s]et or [r]emove? ")
9634 (equal (read-char-exclusive) ?r))))
9635 (if (fboundp 'deactivate-mark) (deactivate-mark))
9636 (let ((agendap (equal major-mode 'org-agenda-mode))
9637 l1 l2 m buf pos newhead (cnt 0))
9638 (goto-char end)
9639 (setq l2 (1- (org-current-line)))
9640 (goto-char beg)
9641 (setq l1 (org-current-line))
9642 (loop for l from l1 to l2 do
9643 (goto-line l)
9644 (setq m (get-text-property (point) 'org-hd-marker))
9645 (when (or (and (org-mode-p) (org-on-heading-p))
9646 (and agendap m))
9647 (setq buf (if agendap (marker-buffer m) (current-buffer))
9648 pos (if agendap m (point)))
9649 (with-current-buffer buf
9650 (save-excursion
9651 (save-restriction
9652 (goto-char pos)
9653 (setq cnt (1+ cnt))
9654 (org-toggle-tag tag (if off 'off 'on))
9655 (setq newhead (org-get-heading)))))
9656 (and agendap (org-agenda-change-all-lines newhead m))))
9657 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9659 (defun org-tags-completion-function (string predicate &optional flag)
9660 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9661 (confirm (lambda (x) (stringp (car x)))))
9662 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9663 (setq s1 (match-string 1 string)
9664 s2 (match-string 2 string))
9665 (setq s1 "" s2 string))
9666 (cond
9667 ((eq flag nil)
9668 ;; try completion
9669 (setq rtn (try-completion s2 ctable confirm))
9670 (if (stringp rtn)
9671 (setq rtn
9672 (concat s1 s2 (substring rtn (length s2))
9673 (if (and org-add-colon-after-tag-completion
9674 (assoc rtn ctable))
9675 ":" ""))))
9676 rtn)
9677 ((eq flag t)
9678 ;; all-completions
9679 (all-completions s2 ctable confirm)
9681 ((eq flag 'lambda)
9682 ;; exact match?
9683 (assoc s2 ctable)))
9686 (defun org-fast-tag-insert (kwd tags face &optional end)
9687 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9688 (insert (format "%-12s" (concat kwd ":"))
9689 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9690 (or end "")))
9692 (defun org-fast-tag-show-exit (flag)
9693 (save-excursion
9694 (goto-line 3)
9695 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9696 (replace-match ""))
9697 (when flag
9698 (end-of-line 1)
9699 (org-move-to-column (- (window-width) 19) t)
9700 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9702 (defun org-set-current-tags-overlay (current prefix)
9703 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9704 (if (featurep 'xemacs)
9705 (org-overlay-display org-tags-overlay (concat prefix s)
9706 'secondary-selection)
9707 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9708 (org-overlay-display org-tags-overlay (concat prefix s)))))
9710 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9711 "Fast tag selection with single keys.
9712 CURRENT is the current list of tags in the headline, INHERITED is the
9713 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9714 possibly with grouping information. TODO-TABLE is a similar table with
9715 TODO keywords, should these have keys assigned to them.
9716 If the keys are nil, a-z are automatically assigned.
9717 Returns the new tags string, or nil to not change the current settings."
9718 (let* ((fulltable (append table todo-table))
9719 (maxlen (apply 'max (mapcar
9720 (lambda (x)
9721 (if (stringp (car x)) (string-width (car x)) 0))
9722 fulltable)))
9723 (buf (current-buffer))
9724 (expert (eq org-fast-tag-selection-single-key 'expert))
9725 (buffer-tags nil)
9726 (fwidth (+ maxlen 3 1 3))
9727 (ncol (/ (- (window-width) 4) fwidth))
9728 (i-face 'org-done)
9729 (c-face 'org-todo)
9730 tg cnt e c char c1 c2 ntable tbl rtn
9731 ov-start ov-end ov-prefix
9732 (exit-after-next org-fast-tag-selection-single-key)
9733 (done-keywords org-done-keywords)
9734 groups ingroup)
9735 (save-excursion
9736 (beginning-of-line 1)
9737 (if (looking-at
9738 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9739 (setq ov-start (match-beginning 1)
9740 ov-end (match-end 1)
9741 ov-prefix "")
9742 (setq ov-start (1- (point-at-eol))
9743 ov-end (1+ ov-start))
9744 (skip-chars-forward "^\n\r")
9745 (setq ov-prefix
9746 (concat
9747 (buffer-substring (1- (point)) (point))
9748 (if (> (current-column) org-tags-column)
9750 (make-string (- org-tags-column (current-column)) ?\ ))))))
9751 (org-move-overlay org-tags-overlay ov-start ov-end)
9752 (save-window-excursion
9753 (if expert
9754 (set-buffer (get-buffer-create " *Org tags*"))
9755 (delete-other-windows)
9756 (split-window-vertically)
9757 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9758 (erase-buffer)
9759 (org-set-local 'org-done-keywords done-keywords)
9760 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9761 (org-fast-tag-insert "Current" current c-face "\n\n")
9762 (org-fast-tag-show-exit exit-after-next)
9763 (org-set-current-tags-overlay current ov-prefix)
9764 (setq tbl fulltable char ?a cnt 0)
9765 (while (setq e (pop tbl))
9766 (cond
9767 ((equal e '(:startgroup))
9768 (push '() groups) (setq ingroup t)
9769 (when (not (= cnt 0))
9770 (setq cnt 0)
9771 (insert "\n"))
9772 (insert "{ "))
9773 ((equal e '(:endgroup))
9774 (setq ingroup nil cnt 0)
9775 (insert "}\n"))
9777 (setq tg (car e) c2 nil)
9778 (if (cdr e)
9779 (setq c (cdr e))
9780 ;; automatically assign a character.
9781 (setq c1 (string-to-char
9782 (downcase (substring
9783 tg (if (= (string-to-char tg) ?@) 1 0)))))
9784 (if (or (rassoc c1 ntable) (rassoc c1 table))
9785 (while (or (rassoc char ntable) (rassoc char table))
9786 (setq char (1+ char)))
9787 (setq c2 c1))
9788 (setq c (or c2 char)))
9789 (if ingroup (push tg (car groups)))
9790 (setq tg (org-add-props tg nil 'face
9791 (cond
9792 ((not (assoc tg table))
9793 (org-get-todo-face tg))
9794 ((member tg current) c-face)
9795 ((member tg inherited) i-face)
9796 (t nil))))
9797 (if (and (= cnt 0) (not ingroup)) (insert " "))
9798 (insert "[" c "] " tg (make-string
9799 (- fwidth 4 (length tg)) ?\ ))
9800 (push (cons tg c) ntable)
9801 (when (= (setq cnt (1+ cnt)) ncol)
9802 (insert "\n")
9803 (if ingroup (insert " "))
9804 (setq cnt 0)))))
9805 (setq ntable (nreverse ntable))
9806 (insert "\n")
9807 (goto-char (point-min))
9808 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9809 (fit-window-to-buffer))
9810 (setq rtn
9811 (catch 'exit
9812 (while t
9813 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9814 (if groups " [!] no groups" " [!]groups")
9815 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9816 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9817 (cond
9818 ((= c ?\r) (throw 'exit t))
9819 ((= c ?!)
9820 (setq groups (not groups))
9821 (goto-char (point-min))
9822 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9823 ((= c ?\C-c)
9824 (if (not expert)
9825 (org-fast-tag-show-exit
9826 (setq exit-after-next (not exit-after-next)))
9827 (setq expert nil)
9828 (delete-other-windows)
9829 (split-window-vertically)
9830 (org-switch-to-buffer-other-window " *Org tags*")
9831 (and (fboundp 'fit-window-to-buffer)
9832 (fit-window-to-buffer))))
9833 ((or (= c ?\C-g)
9834 (and (= c ?q) (not (rassoc c ntable))))
9835 (org-detach-overlay org-tags-overlay)
9836 (setq quit-flag t))
9837 ((= c ?\ )
9838 (setq current nil)
9839 (if exit-after-next (setq exit-after-next 'now)))
9840 ((= c ?\t)
9841 (condition-case nil
9842 (setq tg (completing-read
9843 "Tag: "
9844 (or buffer-tags
9845 (with-current-buffer buf
9846 (org-get-buffer-tags)))))
9847 (quit (setq tg "")))
9848 (when (string-match "\\S-" tg)
9849 (add-to-list 'buffer-tags (list tg))
9850 (if (member tg current)
9851 (setq current (delete tg current))
9852 (push tg current)))
9853 (if exit-after-next (setq exit-after-next 'now)))
9854 ((setq e (rassoc c todo-table) tg (car e))
9855 (with-current-buffer buf
9856 (save-excursion (org-todo tg)))
9857 (if exit-after-next (setq exit-after-next 'now)))
9858 ((setq e (rassoc c ntable) tg (car e))
9859 (if (member tg current)
9860 (setq current (delete tg current))
9861 (loop for g in groups do
9862 (if (member tg g)
9863 (mapc (lambda (x)
9864 (setq current (delete x current)))
9865 g)))
9866 (push tg current))
9867 (if exit-after-next (setq exit-after-next 'now))))
9869 ;; Create a sorted list
9870 (setq current
9871 (sort current
9872 (lambda (a b)
9873 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9874 (if (eq exit-after-next 'now) (throw 'exit t))
9875 (goto-char (point-min))
9876 (beginning-of-line 2)
9877 (delete-region (point) (point-at-eol))
9878 (org-fast-tag-insert "Current" current c-face)
9879 (org-set-current-tags-overlay current ov-prefix)
9880 (while (re-search-forward
9881 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9882 (setq tg (match-string 1))
9883 (add-text-properties
9884 (match-beginning 1) (match-end 1)
9885 (list 'face
9886 (cond
9887 ((member tg current) c-face)
9888 ((member tg inherited) i-face)
9889 (t (get-text-property (match-beginning 1) 'face))))))
9890 (goto-char (point-min)))))
9891 (org-detach-overlay org-tags-overlay)
9892 (if rtn
9893 (mapconcat 'identity current ":")
9894 nil))))
9896 (defun org-get-tags-string ()
9897 "Get the TAGS string in the current headline."
9898 (unless (org-on-heading-p t)
9899 (error "Not on a heading"))
9900 (save-excursion
9901 (beginning-of-line 1)
9902 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9903 (org-match-string-no-properties 1)
9904 "")))
9906 (defun org-get-tags ()
9907 "Get the list of tags specified in the current headline."
9908 (org-split-string (org-get-tags-string) ":"))
9910 (defun org-get-buffer-tags ()
9911 "Get a table of all tags used in the buffer, for completion."
9912 (let (tags)
9913 (save-excursion
9914 (goto-char (point-min))
9915 (while (re-search-forward
9916 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9917 (when (equal (char-after (point-at-bol 0)) ?*)
9918 (mapc (lambda (x) (add-to-list 'tags x))
9919 (org-split-string (org-match-string-no-properties 1) ":")))))
9920 (mapcar 'list tags)))
9923 ;;;; Properties
9925 ;;; Setting and retrieving properties
9927 (defconst org-special-properties
9928 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9929 "TIMESTAMP" "TIMESTAMP_IA")
9930 "The special properties valid in Org-mode.
9932 These are properties that are not defined in the property drawer,
9933 but in some other way.")
9935 (defconst org-default-properties
9936 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9937 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9938 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9939 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9940 "Some properties that are used by Org-mode for various purposes.
9941 Being in this list makes sure that they are offered for completion.")
9943 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9944 "Regular expression matching the first line of a property drawer.")
9946 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9947 "Regular expression matching the first line of a property drawer.")
9949 (defun org-property-action ()
9950 "Do an action on properties."
9951 (interactive)
9952 (let (c)
9953 (org-at-property-p)
9954 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9955 (setq c (read-char-exclusive))
9956 (cond
9957 ((equal c ?s)
9958 (call-interactively 'org-set-property))
9959 ((equal c ?d)
9960 (call-interactively 'org-delete-property))
9961 ((equal c ?D)
9962 (call-interactively 'org-delete-property-globally))
9963 ((equal c ?c)
9964 (call-interactively 'org-compute-property-at-point))
9965 (t (error "No such property action %c" c)))))
9967 (defun org-at-property-p ()
9968 "Is the cursor in a property line?"
9969 ;; FIXME: Does not check if we are actually in the drawer.
9970 ;; FIXME: also returns true on any drawers.....
9971 ;; This is used by C-c C-c for property action.
9972 (save-excursion
9973 (beginning-of-line 1)
9974 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9976 (defun org-get-property-block (&optional beg end force)
9977 "Return the (beg . end) range of the body of the property drawer.
9978 BEG and END can be beginning and end of subtree, if not given
9979 they will be found.
9980 If the drawer does not exist and FORCE is non-nil, create the drawer."
9981 (catch 'exit
9982 (save-excursion
9983 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9984 (end (or end (progn (outline-next-heading) (point)))))
9985 (goto-char beg)
9986 (if (re-search-forward org-property-start-re end t)
9987 (setq beg (1+ (match-end 0)))
9988 (if force
9989 (save-excursion
9990 (org-insert-property-drawer)
9991 (setq end (progn (outline-next-heading) (point))))
9992 (throw 'exit nil))
9993 (goto-char beg)
9994 (if (re-search-forward org-property-start-re end t)
9995 (setq beg (1+ (match-end 0)))))
9996 (if (re-search-forward org-property-end-re end t)
9997 (setq end (match-beginning 0))
9998 (or force (throw 'exit nil))
9999 (goto-char beg)
10000 (setq end beg)
10001 (org-indent-line-function)
10002 (insert ":END:\n"))
10003 (cons beg end)))))
10005 (defun org-entry-properties (&optional pom which)
10006 "Get all properties of the entry at point-or-marker POM.
10007 This includes the TODO keyword, the tags, time strings for deadline,
10008 scheduled, and clocking, and any additional properties defined in the
10009 entry. The return value is an alist, keys may occur multiple times
10010 if the property key was used several times.
10011 POM may also be nil, in which case the current entry is used.
10012 If WHICH is nil or `all', get all properties. If WHICH is
10013 `special' or `standard', only get that subclass."
10014 (setq which (or which 'all))
10015 (org-with-point-at pom
10016 (let ((clockstr (substring org-clock-string 0 -1))
10017 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10018 beg end range props sum-props key value string clocksum)
10019 (save-excursion
10020 (when (condition-case nil (org-back-to-heading t) (error nil))
10021 (setq beg (point))
10022 (setq sum-props (get-text-property (point) 'org-summaries))
10023 (setq clocksum (get-text-property (point) :org-clock-minutes))
10024 (outline-next-heading)
10025 (setq end (point))
10026 (when (memq which '(all special))
10027 ;; Get the special properties, like TODO and tags
10028 (goto-char beg)
10029 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10030 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10031 (when (looking-at org-priority-regexp)
10032 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10033 (when (and (setq value (org-get-tags-string))
10034 (string-match "\\S-" value))
10035 (push (cons "TAGS" value) props))
10036 (when (setq value (org-get-tags-at))
10037 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10038 props))
10039 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10040 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10041 string (if (equal key clockstr)
10042 (org-no-properties
10043 (org-trim
10044 (buffer-substring
10045 (match-beginning 3) (goto-char (point-at-eol)))))
10046 (substring (org-match-string-no-properties 3) 1 -1)))
10047 (unless key
10048 (if (= (char-after (match-beginning 3)) ?\[)
10049 (setq key "TIMESTAMP_IA")
10050 (setq key "TIMESTAMP")))
10051 (when (or (equal key clockstr) (not (assoc key props)))
10052 (push (cons key string) props)))
10056 (when (memq which '(all standard))
10057 ;; Get the standard properties, like :PORP: ...
10058 (setq range (org-get-property-block beg end))
10059 (when range
10060 (goto-char (car range))
10061 (while (re-search-forward
10062 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10063 (cdr range) t)
10064 (setq key (org-match-string-no-properties 1)
10065 value (org-trim (or (org-match-string-no-properties 2) "")))
10066 (unless (member key excluded)
10067 (push (cons key (or value "")) props)))))
10068 (if clocksum
10069 (push (cons "CLOCKSUM"
10070 (org-columns-number-to-string (/ (float clocksum) 60.)
10071 'add_times))
10072 props))
10073 (append sum-props (nreverse props)))))))
10075 (defun org-entry-get (pom property &optional inherit)
10076 "Get value of PROPERTY for entry at point-or-marker POM.
10077 If INHERIT is non-nil and the entry does not have the property,
10078 then also check higher levels of the hierarchy.
10079 If INHERIT is the symbol `selective', use inheritance only if the setting
10080 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10081 If the property is present but empty, the return value is the empty string.
10082 If the property is not present at all, nil is returned."
10083 (org-with-point-at pom
10084 (if (and inherit (if (eq inherit 'selective)
10085 (org-property-inherit-p property)
10087 (org-entry-get-with-inheritance property)
10088 (if (member property org-special-properties)
10089 ;; We need a special property. Use brute force, get all properties.
10090 (cdr (assoc property (org-entry-properties nil 'special)))
10091 (let ((range (org-get-property-block)))
10092 (if (and range
10093 (goto-char (car range))
10094 (re-search-forward
10095 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10096 (cdr range) t))
10097 ;; Found the property, return it.
10098 (if (match-end 1)
10099 (org-match-string-no-properties 1)
10100 "")))))))
10102 (defun org-property-or-variable-value (var &optional inherit)
10103 "Check if there is a property fixing the value of VAR.
10104 If yes, return this value. If not, return the current value of the variable."
10105 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10106 (if (and prop (stringp prop) (string-match "\\S-" prop))
10107 (read prop)
10108 (symbol-value var))))
10110 (defun org-entry-delete (pom property)
10111 "Delete the property PROPERTY from entry at point-or-marker POM."
10112 (org-with-point-at pom
10113 (if (member property org-special-properties)
10114 nil ; cannot delete these properties.
10115 (let ((range (org-get-property-block)))
10116 (if (and range
10117 (goto-char (car range))
10118 (re-search-forward
10119 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10120 (cdr range) t))
10121 (progn
10122 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10124 nil)))))
10126 ;; Multi-values properties are properties that contain multiple values
10127 ;; These values are assumed to be single words, separated by whitespace.
10128 (defun org-entry-add-to-multivalued-property (pom property value)
10129 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10130 (let* ((old (org-entry-get pom property))
10131 (values (and old (org-split-string old "[ \t]"))))
10132 (unless (member value values)
10133 (setq values (cons value values))
10134 (org-entry-put pom property
10135 (mapconcat 'identity values " ")))))
10137 (defun org-entry-remove-from-multivalued-property (pom property value)
10138 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10139 (let* ((old (org-entry-get pom property))
10140 (values (and old (org-split-string old "[ \t]"))))
10141 (when (member value values)
10142 (setq values (delete value values))
10143 (org-entry-put pom property
10144 (mapconcat 'identity values " ")))))
10146 (defun org-entry-member-in-multivalued-property (pom property value)
10147 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10148 (let* ((old (org-entry-get pom property))
10149 (values (and old (org-split-string old "[ \t]"))))
10150 (member value values)))
10152 (defvar org-entry-property-inherited-from (make-marker))
10154 (defun org-entry-get-with-inheritance (property)
10155 "Get entry property, and search higher levels if not present."
10156 (let (tmp)
10157 (save-excursion
10158 (save-restriction
10159 (widen)
10160 (catch 'ex
10161 (while t
10162 (when (setq tmp (org-entry-get nil property))
10163 (org-back-to-heading t)
10164 (move-marker org-entry-property-inherited-from (point))
10165 (throw 'ex tmp))
10166 (or (org-up-heading-safe) (throw 'ex nil)))))
10167 (or tmp
10168 (cdr (assoc property org-file-properties))
10169 (cdr (assoc property org-global-properties))
10170 (cdr (assoc property org-global-properties-fixed))))))
10172 (defun org-entry-put (pom property value)
10173 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10174 (org-with-point-at pom
10175 (org-back-to-heading t)
10176 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10177 range)
10178 (cond
10179 ((equal property "TODO")
10180 (when (and (stringp value) (string-match "\\S-" value)
10181 (not (member value org-todo-keywords-1)))
10182 (error "\"%s\" is not a valid TODO state" value))
10183 (if (or (not value)
10184 (not (string-match "\\S-" value)))
10185 (setq value 'none))
10186 (org-todo value)
10187 (org-set-tags nil 'align))
10188 ((equal property "PRIORITY")
10189 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10190 (string-to-char value) ?\ ))
10191 (org-set-tags nil 'align))
10192 ((equal property "SCHEDULED")
10193 (if (re-search-forward org-scheduled-time-regexp end t)
10194 (cond
10195 ((eq value 'earlier) (org-timestamp-change -1 'day))
10196 ((eq value 'later) (org-timestamp-change 1 'day))
10197 (t (call-interactively 'org-schedule)))
10198 (call-interactively 'org-schedule)))
10199 ((equal property "DEADLINE")
10200 (if (re-search-forward org-deadline-time-regexp end t)
10201 (cond
10202 ((eq value 'earlier) (org-timestamp-change -1 'day))
10203 ((eq value 'later) (org-timestamp-change 1 'day))
10204 (t (call-interactively 'org-deadline)))
10205 (call-interactively 'org-deadline)))
10206 ((member property org-special-properties)
10207 (error "The %s property can not yet be set with `org-entry-put'"
10208 property))
10209 (t ; a non-special property
10210 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10211 (setq range (org-get-property-block beg end 'force))
10212 (goto-char (car range))
10213 (if (re-search-forward
10214 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10215 (progn
10216 (delete-region (match-beginning 1) (match-end 1))
10217 (goto-char (match-beginning 1)))
10218 (goto-char (cdr range))
10219 (insert "\n")
10220 (backward-char 1)
10221 (org-indent-line-function)
10222 (insert ":" property ":"))
10223 (and value (insert " " value))
10224 (org-indent-line-function)))))))
10226 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10227 "Get all property keys in the current buffer.
10228 With INCLUDE-SPECIALS, also list the special properties that relect things
10229 like tags and TODO state.
10230 With INCLUDE-DEFAULTS, also include properties that has special meaning
10231 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10232 With INCLUDE-COLUMNS, also include property names given in COLUMN
10233 formats in the current buffer."
10234 (let (rtn range cfmt cols s p)
10235 (save-excursion
10236 (save-restriction
10237 (widen)
10238 (goto-char (point-min))
10239 (while (re-search-forward org-property-start-re nil t)
10240 (setq range (org-get-property-block))
10241 (goto-char (car range))
10242 (while (re-search-forward
10243 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10244 (cdr range) t)
10245 (add-to-list 'rtn (org-match-string-no-properties 1)))
10246 (outline-next-heading))))
10248 (when include-specials
10249 (setq rtn (append org-special-properties rtn)))
10251 (when include-defaults
10252 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10254 (when include-columns
10255 (save-excursion
10256 (save-restriction
10257 (widen)
10258 (goto-char (point-min))
10259 (while (re-search-forward
10260 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10261 nil t)
10262 (setq cfmt (match-string 2) s 0)
10263 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10264 cfmt s)
10265 (setq s (match-end 0)
10266 p (match-string 1 cfmt))
10267 (unless (or (equal p "ITEM")
10268 (member p org-special-properties))
10269 (add-to-list 'rtn (match-string 1 cfmt))))))))
10271 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10273 (defun org-property-values (key)
10274 "Return a list of all values of property KEY."
10275 (save-excursion
10276 (save-restriction
10277 (widen)
10278 (goto-char (point-min))
10279 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10280 values)
10281 (while (re-search-forward re nil t)
10282 (add-to-list 'values (org-trim (match-string 1))))
10283 (delete "" values)))))
10285 (defun org-insert-property-drawer ()
10286 "Insert a property drawer into the current entry."
10287 (interactive)
10288 (org-back-to-heading t)
10289 (looking-at outline-regexp)
10290 (let ((indent (- (match-end 0)(match-beginning 0)))
10291 (beg (point))
10292 (re (concat "^[ \t]*" org-keyword-time-regexp))
10293 end hiddenp)
10294 (outline-next-heading)
10295 (setq end (point))
10296 (goto-char beg)
10297 (while (re-search-forward re end t))
10298 (setq hiddenp (org-invisible-p))
10299 (end-of-line 1)
10300 (and (equal (char-after) ?\n) (forward-char 1))
10301 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10302 (beginning-of-line 2))
10303 (org-skip-over-state-notes)
10304 (skip-chars-backward " \t\n\r")
10305 (if (eq (char-before) ?*) (forward-char 1))
10306 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10307 (beginning-of-line 0)
10308 (org-indent-to-column indent)
10309 (beginning-of-line 2)
10310 (org-indent-to-column indent)
10311 (beginning-of-line 0)
10312 (if hiddenp
10313 (save-excursion
10314 (org-back-to-heading t)
10315 (hide-entry))
10316 (org-flag-drawer t))))
10318 (defun org-set-property (property value)
10319 "In the current entry, set PROPERTY to VALUE.
10320 When called interactively, this will prompt for a property name, offering
10321 completion on existing and default properties. And then it will prompt
10322 for a value, offering competion either on allowed values (via an inherited
10323 xxx_ALL property) or on existing values in other instances of this property
10324 in the current file."
10325 (interactive
10326 (let* ((completion-ignore-case t)
10327 (keys (org-buffer-property-keys nil t t))
10328 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10329 (prop (if (member prop0 keys)
10330 prop0
10331 (or (cdr (assoc (downcase prop0)
10332 (mapcar (lambda (x) (cons (downcase x) x))
10333 keys)))
10334 prop0)))
10335 (cur (org-entry-get nil prop))
10336 (allowed (org-property-get-allowed-values nil prop 'table))
10337 (existing (mapcar 'list (org-property-values prop)))
10338 (val (if allowed
10339 (org-completing-read "Value: " allowed nil 'req-match)
10340 (org-completing-read
10341 (concat "Value" (if (and cur (string-match "\\S-" cur))
10342 (concat "[" cur "]") "")
10343 ": ")
10344 existing nil nil "" nil cur))))
10345 (list prop (if (equal val "") cur val))))
10346 (unless (equal (org-entry-get nil property) value)
10347 (org-entry-put nil property value)))
10349 (defun org-delete-property (property)
10350 "In the current entry, delete PROPERTY."
10351 (interactive
10352 (let* ((completion-ignore-case t)
10353 (prop (completing-read
10354 "Property: " (org-entry-properties nil 'standard))))
10355 (list prop)))
10356 (message "Property %s %s" property
10357 (if (org-entry-delete nil property)
10358 "deleted"
10359 "was not present in the entry")))
10361 (defun org-delete-property-globally (property)
10362 "Remove PROPERTY globally, from all entries."
10363 (interactive
10364 (let* ((completion-ignore-case t)
10365 (prop (completing-read
10366 "Globally remove property: "
10367 (mapcar 'list (org-buffer-property-keys)))))
10368 (list prop)))
10369 (save-excursion
10370 (save-restriction
10371 (widen)
10372 (goto-char (point-min))
10373 (let ((cnt 0))
10374 (while (re-search-forward
10375 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10376 nil t)
10377 (setq cnt (1+ cnt))
10378 (replace-match ""))
10379 (message "Property \"%s\" removed from %d entries" property cnt)))))
10381 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10383 (defun org-compute-property-at-point ()
10384 "Compute the property at point.
10385 This looks for an enclosing column format, extracts the operator and
10386 then applies it to the proerty in the column format's scope."
10387 (interactive)
10388 (unless (org-at-property-p)
10389 (error "Not at a property"))
10390 (let ((prop (org-match-string-no-properties 2)))
10391 (org-columns-get-format-and-top-level)
10392 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10393 (error "No operator defined for property %s" prop))
10394 (org-columns-compute prop)))
10396 (defun org-property-get-allowed-values (pom property &optional table)
10397 "Get allowed values for the property PROPERTY.
10398 When TABLE is non-nil, return an alist that can directly be used for
10399 completion."
10400 (let (vals)
10401 (cond
10402 ((equal property "TODO")
10403 (setq vals (org-with-point-at pom
10404 (append org-todo-keywords-1 '("")))))
10405 ((equal property "PRIORITY")
10406 (let ((n org-lowest-priority))
10407 (while (>= n org-highest-priority)
10408 (push (char-to-string n) vals)
10409 (setq n (1- n)))))
10410 ((member property org-special-properties))
10412 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10414 (when (and vals (string-match "\\S-" vals))
10415 (setq vals (car (read-from-string (concat "(" vals ")"))))
10416 (setq vals (mapcar (lambda (x)
10417 (cond ((stringp x) x)
10418 ((numberp x) (number-to-string x))
10419 ((symbolp x) (symbol-name x))
10420 (t "???")))
10421 vals)))))
10422 (if table (mapcar 'list vals) vals)))
10424 (defun org-property-previous-allowed-value (&optional previous)
10425 "Switch to the next allowed value for this property."
10426 (interactive)
10427 (org-property-next-allowed-value t))
10429 (defun org-property-next-allowed-value (&optional previous)
10430 "Switch to the next allowed value for this property."
10431 (interactive)
10432 (unless (org-at-property-p)
10433 (error "Not at a property"))
10434 (let* ((key (match-string 2))
10435 (value (match-string 3))
10436 (allowed (or (org-property-get-allowed-values (point) key)
10437 (and (member value '("[ ]" "[-]" "[X]"))
10438 '("[ ]" "[X]"))))
10439 nval)
10440 (unless allowed
10441 (error "Allowed values for this property have not been defined"))
10442 (if previous (setq allowed (reverse allowed)))
10443 (if (member value allowed)
10444 (setq nval (car (cdr (member value allowed)))))
10445 (setq nval (or nval (car allowed)))
10446 (if (equal nval value)
10447 (error "Only one allowed value for this property"))
10448 (org-at-property-p)
10449 (replace-match (concat " :" key ": " nval) t t)
10450 (org-indent-line-function)
10451 (beginning-of-line 1)
10452 (skip-chars-forward " \t")))
10454 (defun org-find-entry-with-id (ident)
10455 "Locate the entry that contains the ID property with exact value IDENT.
10456 IDENT can be a string, a symbol or a number, this function will search for
10457 the string representation of it.
10458 Return the position where this entry starts, or nil if there is no such entry."
10459 (let ((id (cond
10460 ((stringp ident) ident)
10461 ((symbol-name ident) (symbol-name ident))
10462 ((numberp ident) (number-to-string ident))
10463 (t (error "IDENT %s must be a string, symbol or number" ident))))
10464 (case-fold-search nil))
10465 (save-excursion
10466 (save-restriction
10467 (widen)
10468 (goto-char (point-min))
10469 (when (re-search-forward
10470 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10471 nil t)
10472 (org-back-to-heading)
10473 (point))))))
10475 ;;;; Timestamps
10477 (defvar org-last-changed-timestamp nil)
10478 (defvar org-time-was-given) ; dynamically scoped parameter
10479 (defvar org-end-time-was-given) ; dynamically scoped parameter
10480 (defvar org-ts-what) ; dynamically scoped parameter
10482 (defun org-time-stamp (arg)
10483 "Prompt for a date/time and insert a time stamp.
10484 If the user specifies a time like HH:MM, or if this command is called
10485 with a prefix argument, the time stamp will contain date and time.
10486 Otherwise, only the date will be included. All parts of a date not
10487 specified by the user will be filled in from the current date/time.
10488 So if you press just return without typing anything, the time stamp
10489 will represent the current date/time. If there is already a timestamp
10490 at the cursor, it will be modified."
10491 (interactive "P")
10492 (let* ((ts nil)
10493 (default-time
10494 ;; Default time is either today, or, when entering a range,
10495 ;; the range start.
10496 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10497 (save-excursion
10498 (re-search-backward
10499 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10500 (- (point) 20) t)))
10501 (apply 'encode-time (org-parse-time-string (match-string 1)))
10502 (current-time)))
10503 (default-input (and ts (org-get-compact-tod ts)))
10504 org-time-was-given org-end-time-was-given time)
10505 (cond
10506 ((and (org-at-timestamp-p)
10507 (eq last-command 'org-time-stamp)
10508 (eq this-command 'org-time-stamp))
10509 (insert "--")
10510 (setq time (let ((this-command this-command))
10511 (org-read-date arg 'totime nil nil default-time default-input)))
10512 (org-insert-time-stamp time (or org-time-was-given arg)))
10513 ((org-at-timestamp-p)
10514 (setq time (let ((this-command this-command))
10515 (org-read-date arg 'totime nil nil default-time default-input)))
10516 (when (org-at-timestamp-p) ; just to get the match data
10517 (replace-match "")
10518 (setq org-last-changed-timestamp
10519 (org-insert-time-stamp
10520 time (or org-time-was-given arg)
10521 nil nil nil (list org-end-time-was-given))))
10522 (message "Timestamp updated"))
10524 (setq time (let ((this-command this-command))
10525 (org-read-date arg 'totime nil nil default-time default-input)))
10526 (org-insert-time-stamp time (or org-time-was-given arg)
10527 nil nil nil (list org-end-time-was-given))))))
10529 ;; FIXME: can we use this for something else, like computing time differences?
10530 (defun org-get-compact-tod (s)
10531 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10532 (let* ((t1 (match-string 1 s))
10533 (h1 (string-to-number (match-string 2 s)))
10534 (m1 (string-to-number (match-string 3 s)))
10535 (t2 (and (match-end 4) (match-string 5 s)))
10536 (h2 (and t2 (string-to-number (match-string 6 s))))
10537 (m2 (and t2 (string-to-number (match-string 7 s))))
10538 dh dm)
10539 (if (not t2)
10541 (setq dh (- h2 h1) dm (- m2 m1))
10542 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10543 (concat t1 "+" (number-to-string dh)
10544 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10546 (defun org-time-stamp-inactive (&optional arg)
10547 "Insert an inactive time stamp.
10548 An inactive time stamp is enclosed in square brackets instead of angle
10549 brackets. It is inactive in the sense that it does not trigger agenda entries,
10550 does not link to the calendar and cannot be changed with the S-cursor keys.
10551 So these are more for recording a certain time/date."
10552 (interactive "P")
10553 (let (org-time-was-given org-end-time-was-given time)
10554 (setq time (org-read-date arg 'totime))
10555 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10556 nil nil (list org-end-time-was-given))))
10558 (defvar org-date-ovl (org-make-overlay 1 1))
10559 (org-overlay-put org-date-ovl 'face 'org-warning)
10560 (org-detach-overlay org-date-ovl)
10562 (defvar org-ans1) ; dynamically scoped parameter
10563 (defvar org-ans2) ; dynamically scoped parameter
10565 (defvar org-plain-time-of-day-regexp) ; defined below
10567 (defvar org-read-date-overlay nil)
10568 (defvar org-dcst nil) ; dynamically scoped
10570 (defun org-read-date (&optional with-time to-time from-string prompt
10571 default-time default-input)
10572 "Read a date, possibly a time, and make things smooth for the user.
10573 The prompt will suggest to enter an ISO date, but you can also enter anything
10574 which will at least partially be understood by `parse-time-string'.
10575 Unrecognized parts of the date will default to the current day, month, year,
10576 hour and minute. If this command is called to replace a timestamp at point,
10577 of to enter the second timestamp of a range, the default time is taken from the
10578 existing stamp. For example,
10579 3-2-5 --> 2003-02-05
10580 feb 15 --> currentyear-02-15
10581 sep 12 9 --> 2009-09-12
10582 12:45 --> today 12:45
10583 22 sept 0:34 --> currentyear-09-22 0:34
10584 12 --> currentyear-currentmonth-12
10585 Fri --> nearest Friday (today or later)
10586 etc.
10588 Furthermore you can specify a relative date by giving, as the *first* thing
10589 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10590 change in days weeks, months, years.
10591 With a single plus or minus, the date is relative to today. With a double
10592 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10593 +4d --> four days from today
10594 +4 --> same as above
10595 +2w --> two weeks from today
10596 ++5 --> five days from default date
10598 The function understands only English month and weekday abbreviations,
10599 but this can be configured with the variables `parse-time-months' and
10600 `parse-time-weekdays'.
10602 While prompting, a calendar is popped up - you can also select the
10603 date with the mouse (button 1). The calendar shows a period of three
10604 months. To scroll it to other months, use the keys `>' and `<'.
10605 If you don't like the calendar, turn it off with
10606 \(setq org-read-date-popup-calendar nil)
10608 With optional argument TO-TIME, the date will immediately be converted
10609 to an internal time.
10610 With an optional argument WITH-TIME, the prompt will suggest to also
10611 insert a time. Note that when WITH-TIME is not set, you can still
10612 enter a time, and this function will inform the calling routine about
10613 this change. The calling routine may then choose to change the format
10614 used to insert the time stamp into the buffer to include the time.
10615 With optional argument FROM-STRING, read from this string instead from
10616 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10617 the time/date that is used for everything that is not specified by the
10618 user."
10619 (require 'parse-time)
10620 (let* ((org-time-stamp-rounding-minutes
10621 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10622 (org-dcst org-display-custom-times)
10623 (ct (org-current-time))
10624 (def (or default-time ct))
10625 (defdecode (decode-time def))
10626 (dummy (progn
10627 (when (< (nth 2 defdecode) org-extend-today-until)
10628 (setcar (nthcdr 2 defdecode) -1)
10629 (setcar (nthcdr 1 defdecode) 59)
10630 (setq def (apply 'encode-time defdecode)
10631 defdecode (decode-time def)))))
10632 (calendar-move-hook nil)
10633 (calendar-view-diary-initially-flag nil)
10634 (view-diary-entries-initially nil)
10635 (calendar-view-holidays-initially-flag nil)
10636 (view-calendar-holidays-initially nil)
10637 (timestr (format-time-string
10638 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10639 (prompt (concat (if prompt (concat prompt " ") "")
10640 (format "Date+time [%s]: " timestr)))
10641 ans (org-ans0 "") org-ans1 org-ans2 final)
10643 (cond
10644 (from-string (setq ans from-string))
10645 (org-read-date-popup-calendar
10646 (save-excursion
10647 (save-window-excursion
10648 (calendar)
10649 (calendar-forward-day (- (time-to-days def)
10650 (calendar-absolute-from-gregorian
10651 (calendar-current-date))))
10652 (org-eval-in-calendar nil t)
10653 (let* ((old-map (current-local-map))
10654 (map (copy-keymap calendar-mode-map))
10655 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10656 (org-defkey map (kbd "RET") 'org-calendar-select)
10657 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10658 'org-calendar-select-mouse)
10659 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10660 'org-calendar-select-mouse)
10661 (org-defkey minibuffer-local-map [(meta shift left)]
10662 (lambda () (interactive)
10663 (org-eval-in-calendar '(calendar-backward-month 1))))
10664 (org-defkey minibuffer-local-map [(meta shift right)]
10665 (lambda () (interactive)
10666 (org-eval-in-calendar '(calendar-forward-month 1))))
10667 (org-defkey minibuffer-local-map [(meta shift up)]
10668 (lambda () (interactive)
10669 (org-eval-in-calendar '(calendar-backward-year 1))))
10670 (org-defkey minibuffer-local-map [(meta shift down)]
10671 (lambda () (interactive)
10672 (org-eval-in-calendar '(calendar-forward-year 1))))
10673 (org-defkey minibuffer-local-map [(shift up)]
10674 (lambda () (interactive)
10675 (org-eval-in-calendar '(calendar-backward-week 1))))
10676 (org-defkey minibuffer-local-map [(shift down)]
10677 (lambda () (interactive)
10678 (org-eval-in-calendar '(calendar-forward-week 1))))
10679 (org-defkey minibuffer-local-map [(shift left)]
10680 (lambda () (interactive)
10681 (org-eval-in-calendar '(calendar-backward-day 1))))
10682 (org-defkey minibuffer-local-map [(shift right)]
10683 (lambda () (interactive)
10684 (org-eval-in-calendar '(calendar-forward-day 1))))
10685 (org-defkey minibuffer-local-map ">"
10686 (lambda () (interactive)
10687 (org-eval-in-calendar '(scroll-calendar-left 1))))
10688 (org-defkey minibuffer-local-map "<"
10689 (lambda () (interactive)
10690 (org-eval-in-calendar '(scroll-calendar-right 1))))
10691 (unwind-protect
10692 (progn
10693 (use-local-map map)
10694 (add-hook 'post-command-hook 'org-read-date-display)
10695 (setq org-ans0 (read-string prompt default-input nil nil))
10696 ;; org-ans0: from prompt
10697 ;; org-ans1: from mouse click
10698 ;; org-ans2: from calendar motion
10699 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10700 (remove-hook 'post-command-hook 'org-read-date-display)
10701 (use-local-map old-map)
10702 (when org-read-date-overlay
10703 (org-delete-overlay org-read-date-overlay)
10704 (setq org-read-date-overlay nil)))))))
10706 (t ; Naked prompt only
10707 (unwind-protect
10708 (setq ans (read-string prompt default-input nil timestr))
10709 (when org-read-date-overlay
10710 (org-delete-overlay org-read-date-overlay)
10711 (setq org-read-date-overlay nil)))))
10713 (setq final (org-read-date-analyze ans def defdecode))
10715 (if to-time
10716 (apply 'encode-time final)
10717 (if (and (boundp 'org-time-was-given) org-time-was-given)
10718 (format "%04d-%02d-%02d %02d:%02d"
10719 (nth 5 final) (nth 4 final) (nth 3 final)
10720 (nth 2 final) (nth 1 final))
10721 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10722 (defvar def)
10723 (defvar defdecode)
10724 (defvar with-time)
10725 (defun org-read-date-display ()
10726 "Display the currrent date prompt interpretation in the minibuffer."
10727 (when org-read-date-display-live
10728 (when org-read-date-overlay
10729 (org-delete-overlay org-read-date-overlay))
10730 (let ((p (point)))
10731 (end-of-line 1)
10732 (while (not (equal (buffer-substring
10733 (max (point-min) (- (point) 4)) (point))
10734 " "))
10735 (insert " "))
10736 (goto-char p))
10737 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10738 " " (or org-ans1 org-ans2)))
10739 (org-end-time-was-given nil)
10740 (f (org-read-date-analyze ans def defdecode))
10741 (fmts (if org-dcst
10742 org-time-stamp-custom-formats
10743 org-time-stamp-formats))
10744 (fmt (if (or with-time
10745 (and (boundp 'org-time-was-given) org-time-was-given))
10746 (cdr fmts)
10747 (car fmts)))
10748 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10749 (when (and org-end-time-was-given
10750 (string-match org-plain-time-of-day-regexp txt))
10751 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10752 org-end-time-was-given
10753 (substring txt (match-end 0)))))
10754 (setq org-read-date-overlay
10755 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10756 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10758 (defun org-read-date-analyze (ans def defdecode)
10759 "Analyze the combined answer of the date prompt."
10760 ;; FIXME: cleanup and comment
10761 (let (delta deltan deltaw deltadef year month day
10762 hour minute second wday pm h2 m2 tl wday1
10763 iso-year iso-weekday iso-week iso-year iso-date)
10765 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10766 (setq ans "+0"))
10768 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10769 (setq ans (replace-match "" t t ans)
10770 deltan (car delta)
10771 deltaw (nth 1 delta)
10772 deltadef (nth 2 delta)))
10774 ;; Check if there is an iso week date in there
10775 ;; If yes, sore the info and ostpone interpreting it until the rest
10776 ;; of the parsing is done
10777 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10778 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10779 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10780 iso-week (string-to-number (match-string 2 ans)))
10781 (setq ans (replace-match "" t t ans)))
10783 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10784 (when (string-match
10785 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10786 (setq year (if (match-end 2)
10787 (string-to-number (match-string 2 ans))
10788 (string-to-number (format-time-string "%Y")))
10789 month (string-to-number (match-string 3 ans))
10790 day (string-to-number (match-string 4 ans)))
10791 (if (< year 100) (setq year (+ 2000 year)))
10792 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10793 t nil ans)))
10794 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10795 ;; If there is a time with am/pm, and *no* time without it, we convert
10796 ;; so that matching will be successful.
10797 (loop for i from 1 to 2 do ; twice, for end time as well
10798 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10799 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10800 (setq hour (string-to-number (match-string 1 ans))
10801 minute (if (match-end 3)
10802 (string-to-number (match-string 3 ans))
10804 pm (equal ?p
10805 (string-to-char (downcase (match-string 4 ans)))))
10806 (if (and (= hour 12) (not pm))
10807 (setq hour 0)
10808 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10809 (setq ans (replace-match (format "%02d:%02d" hour minute)
10810 t t ans))))
10812 ;; Check if a time range is given as a duration
10813 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10814 (setq hour (string-to-number (match-string 1 ans))
10815 h2 (+ hour (string-to-number (match-string 3 ans)))
10816 minute (string-to-number (match-string 2 ans))
10817 m2 (+ minute (if (match-end 5) (string-to-number
10818 (match-string 5 ans))0)))
10819 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10820 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10821 t t ans)))
10823 ;; Check if there is a time range
10824 (when (boundp 'org-end-time-was-given)
10825 (setq org-time-was-given nil)
10826 (when (and (string-match org-plain-time-of-day-regexp ans)
10827 (match-end 8))
10828 (setq org-end-time-was-given (match-string 8 ans))
10829 (setq ans (concat (substring ans 0 (match-beginning 7))
10830 (substring ans (match-end 7))))))
10832 (setq tl (parse-time-string ans)
10833 day (or (nth 3 tl) (nth 3 defdecode))
10834 month (or (nth 4 tl)
10835 (if (and org-read-date-prefer-future
10836 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10837 (1+ (nth 4 defdecode))
10838 (nth 4 defdecode)))
10839 year (or (nth 5 tl)
10840 (if (and org-read-date-prefer-future
10841 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10842 (1+ (nth 5 defdecode))
10843 (nth 5 defdecode)))
10844 hour (or (nth 2 tl) (nth 2 defdecode))
10845 minute (or (nth 1 tl) (nth 1 defdecode))
10846 second (or (nth 0 tl) 0)
10847 wday (nth 6 tl))
10849 ;; Special date definitions below
10850 (cond
10851 (iso-week
10852 ;; There was an iso week
10853 (setq year (or iso-year year)
10854 day (or iso-weekday wday 1)
10855 wday nil ; to make sure that the trigger below does not match
10856 iso-date (calendar-gregorian-from-absolute
10857 (calendar-absolute-from-iso
10858 (list iso-week day year))))
10859 ; FIXME: Should we also push ISO weeks into the future?
10860 ; (when (and org-read-date-prefer-future
10861 ; (not iso-year)
10862 ; (< (calendar-absolute-from-gregorian iso-date)
10863 ; (time-to-days (current-time))))
10864 ; (setq year (1+ year)
10865 ; iso-date (calendar-gregorian-from-absolute
10866 ; (calendar-absolute-from-iso
10867 ; (list iso-week day year)))))
10868 (setq month (car iso-date)
10869 year (nth 2 iso-date)
10870 day (nth 1 iso-date)))
10871 (deltan
10872 (unless deltadef
10873 (let ((now (decode-time (current-time))))
10874 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10875 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10876 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10877 ((equal deltaw "m") (setq month (+ month deltan)))
10878 ((equal deltaw "y") (setq year (+ year deltan)))))
10879 ((and wday (not (nth 3 tl)))
10880 ;; Weekday was given, but no day, so pick that day in the week
10881 ;; on or after the derived date.
10882 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10883 (unless (equal wday wday1)
10884 (setq day (+ day (% (- wday wday1 -7) 7))))))
10885 (if (and (boundp 'org-time-was-given)
10886 (nth 2 tl))
10887 (setq org-time-was-given t))
10888 (if (< year 100) (setq year (+ 2000 year)))
10889 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10890 (list second minute hour day month year)))
10892 (defvar parse-time-weekdays)
10894 (defun org-read-date-get-relative (s today default)
10895 "Check string S for special relative date string.
10896 TODAY and DEFAULT are internal times, for today and for a default.
10897 Return shift list (N what def-flag)
10898 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10899 N is the number of WHATs to shift.
10900 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10901 the DEFAULT date rather than TODAY."
10902 (when (and
10903 (string-match
10904 (concat
10905 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10906 "\\([0-9]+\\)?"
10907 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10908 "\\([ \t]\\|$\\)") s)
10909 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10910 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10911 (string-to-char (substring (match-string 1 s) -1))
10912 ?+))
10913 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10914 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10915 (what (if (match-end 3) (match-string 3 s) "d"))
10916 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10917 (date (if rel default today))
10918 (wday (nth 6 (decode-time date)))
10919 delta)
10920 (if wday1
10921 (progn
10922 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10923 (if (= dir ?-) (setq delta (- delta 7)))
10924 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10925 (list delta "d" rel))
10926 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10928 (defun org-eval-in-calendar (form &optional keepdate)
10929 "Eval FORM in the calendar window and return to current window.
10930 Also, store the cursor date in variable org-ans2."
10931 (let ((sw (selected-window)))
10932 (select-window (get-buffer-window "*Calendar*"))
10933 (eval form)
10934 (when (and (not keepdate) (calendar-cursor-to-date))
10935 (let* ((date (calendar-cursor-to-date))
10936 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10937 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10938 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10939 (select-window sw)))
10941 ; ;; Update the prompt to show new default date
10942 ; (save-excursion
10943 ; (goto-char (point-min))
10944 ; (when (and org-ans2
10945 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10946 ; (get-text-property (match-end 0) 'field))
10947 ; (let ((inhibit-read-only t))
10948 ; (replace-match (concat "[" org-ans2 "]") t t)
10949 ; (add-text-properties (point-min) (1+ (match-end 0))
10950 ; (text-properties-at (1+ (point-min)))))))))
10952 (defun org-calendar-select ()
10953 "Return to `org-read-date' with the date currently selected.
10954 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10955 (interactive)
10956 (when (calendar-cursor-to-date)
10957 (let* ((date (calendar-cursor-to-date))
10958 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10959 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10960 (if (active-minibuffer-window) (exit-minibuffer))))
10962 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10963 "Insert a date stamp for the date given by the internal TIME.
10964 WITH-HM means, use the stamp format that includes the time of the day.
10965 INACTIVE means use square brackets instead of angular ones, so that the
10966 stamp will not contribute to the agenda.
10967 PRE and POST are optional strings to be inserted before and after the
10968 stamp.
10969 The command returns the inserted time stamp."
10970 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10971 stamp)
10972 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10973 (insert-before-markers (or pre ""))
10974 (insert-before-markers (setq stamp (format-time-string fmt time)))
10975 (when (listp extra)
10976 (setq extra (car extra))
10977 (if (and (stringp extra)
10978 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10979 (setq extra (format "-%02d:%02d"
10980 (string-to-number (match-string 1 extra))
10981 (string-to-number (match-string 2 extra))))
10982 (setq extra nil)))
10983 (when extra
10984 (backward-char 1)
10985 (insert-before-markers extra)
10986 (forward-char 1))
10987 (insert-before-markers (or post ""))
10988 stamp))
10990 (defun org-toggle-time-stamp-overlays ()
10991 "Toggle the use of custom time stamp formats."
10992 (interactive)
10993 (setq org-display-custom-times (not org-display-custom-times))
10994 (unless org-display-custom-times
10995 (let ((p (point-min)) (bmp (buffer-modified-p)))
10996 (while (setq p (next-single-property-change p 'display))
10997 (if (and (get-text-property p 'display)
10998 (eq (get-text-property p 'face) 'org-date))
10999 (remove-text-properties
11000 p (setq p (next-single-property-change p 'display))
11001 '(display t))))
11002 (set-buffer-modified-p bmp)))
11003 (if (featurep 'xemacs)
11004 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11005 (org-restart-font-lock)
11006 (setq org-table-may-need-update t)
11007 (if org-display-custom-times
11008 (message "Time stamps are overlayed with custom format")
11009 (message "Time stamp overlays removed")))
11011 (defun org-display-custom-time (beg end)
11012 "Overlay modified time stamp format over timestamp between BEG and END."
11013 (let* ((ts (buffer-substring beg end))
11014 t1 w1 with-hm tf time str w2 (off 0))
11015 (save-match-data
11016 (setq t1 (org-parse-time-string ts t))
11017 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11018 (setq off (- (match-end 0) (match-beginning 0)))))
11019 (setq end (- end off))
11020 (setq w1 (- end beg)
11021 with-hm (and (nth 1 t1) (nth 2 t1))
11022 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11023 time (org-fix-decoded-time t1)
11024 str (org-add-props
11025 (format-time-string
11026 (substring tf 1 -1) (apply 'encode-time time))
11027 nil 'mouse-face 'highlight)
11028 w2 (length str))
11029 (if (not (= w2 w1))
11030 (add-text-properties (1+ beg) (+ 2 beg)
11031 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11032 (if (featurep 'xemacs)
11033 (progn
11034 (put-text-property beg end 'invisible t)
11035 (put-text-property beg end 'end-glyph (make-glyph str)))
11036 (put-text-property beg end 'display str))))
11038 (defun org-translate-time (string)
11039 "Translate all timestamps in STRING to custom format.
11040 But do this only if the variable `org-display-custom-times' is set."
11041 (when org-display-custom-times
11042 (save-match-data
11043 (let* ((start 0)
11044 (re org-ts-regexp-both)
11045 t1 with-hm inactive tf time str beg end)
11046 (while (setq start (string-match re string start))
11047 (setq beg (match-beginning 0)
11048 end (match-end 0)
11049 t1 (save-match-data
11050 (org-parse-time-string (substring string beg end) t))
11051 with-hm (and (nth 1 t1) (nth 2 t1))
11052 inactive (equal (substring string beg (1+ beg)) "[")
11053 tf (funcall (if with-hm 'cdr 'car)
11054 org-time-stamp-custom-formats)
11055 time (org-fix-decoded-time t1)
11056 str (format-time-string
11057 (concat
11058 (if inactive "[" "<") (substring tf 1 -1)
11059 (if inactive "]" ">"))
11060 (apply 'encode-time time))
11061 string (replace-match str t t string)
11062 start (+ start (length str)))))))
11063 string)
11065 (defun org-fix-decoded-time (time)
11066 "Set 0 instead of nil for the first 6 elements of time.
11067 Don't touch the rest."
11068 (let ((n 0))
11069 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11071 (defun org-days-to-time (timestamp-string)
11072 "Difference between TIMESTAMP-STRING and now in days."
11073 (- (time-to-days (org-time-string-to-time timestamp-string))
11074 (time-to-days (current-time))))
11076 (defun org-deadline-close (timestamp-string &optional ndays)
11077 "Is the time in TIMESTAMP-STRING close to the current date?"
11078 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11079 (and (< (org-days-to-time timestamp-string) ndays)
11080 (not (org-entry-is-done-p))))
11082 (defun org-get-wdays (ts)
11083 "Get the deadline lead time appropriate for timestring TS."
11084 (cond
11085 ((<= org-deadline-warning-days 0)
11086 ;; 0 or negative, enforce this value no matter what
11087 (- org-deadline-warning-days))
11088 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11089 ;; lead time is specified.
11090 (floor (* (string-to-number (match-string 1 ts))
11091 (cdr (assoc (match-string 2 ts)
11092 '(("d" . 1) ("w" . 7)
11093 ("m" . 30.4) ("y" . 365.25)))))))
11094 ;; go for the default.
11095 (t org-deadline-warning-days)))
11097 (defun org-calendar-select-mouse (ev)
11098 "Return to `org-read-date' with the date currently selected.
11099 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11100 (interactive "e")
11101 (mouse-set-point ev)
11102 (when (calendar-cursor-to-date)
11103 (let* ((date (calendar-cursor-to-date))
11104 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11105 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11106 (if (active-minibuffer-window) (exit-minibuffer))))
11108 (defun org-check-deadlines (ndays)
11109 "Check if there are any deadlines due or past due.
11110 A deadline is considered due if it happens within `org-deadline-warning-days'
11111 days from today's date. If the deadline appears in an entry marked DONE,
11112 it is not shown. The prefix arg NDAYS can be used to test that many
11113 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11114 (interactive "P")
11115 (let* ((org-warn-days
11116 (cond
11117 ((equal ndays '(4)) 100000)
11118 (ndays (prefix-numeric-value ndays))
11119 (t (abs org-deadline-warning-days))))
11120 (case-fold-search nil)
11121 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11122 (callback
11123 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11125 (message "%d deadlines past-due or due within %d days"
11126 (org-occur regexp nil callback)
11127 org-warn-days)))
11129 (defun org-check-before-date (date)
11130 "Check if there are deadlines or scheduled entries before DATE."
11131 (interactive (list (org-read-date)))
11132 (let ((case-fold-search nil)
11133 (regexp (concat "\\<\\(" org-deadline-string
11134 "\\|" org-scheduled-string
11135 "\\) *<\\([^>]+\\)>"))
11136 (callback
11137 (lambda () (time-less-p
11138 (org-time-string-to-time (match-string 2))
11139 (org-time-string-to-time date)))))
11140 (message "%d entries before %s"
11141 (org-occur regexp nil callback) date)))
11143 (defun org-evaluate-time-range (&optional to-buffer)
11144 "Evaluate a time range by computing the difference between start and end.
11145 Normally the result is just printed in the echo area, but with prefix arg
11146 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11147 If the time range is actually in a table, the result is inserted into the
11148 next column.
11149 For time difference computation, a year is assumed to be exactly 365
11150 days in order to avoid rounding problems."
11151 (interactive "P")
11153 (org-clock-update-time-maybe)
11154 (save-excursion
11155 (unless (org-at-date-range-p t)
11156 (goto-char (point-at-bol))
11157 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11158 (if (not (org-at-date-range-p t))
11159 (error "Not at a time-stamp range, and none found in current line")))
11160 (let* ((ts1 (match-string 1))
11161 (ts2 (match-string 2))
11162 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11163 (match-end (match-end 0))
11164 (time1 (org-time-string-to-time ts1))
11165 (time2 (org-time-string-to-time ts2))
11166 (t1 (time-to-seconds time1))
11167 (t2 (time-to-seconds time2))
11168 (diff (abs (- t2 t1)))
11169 (negative (< (- t2 t1) 0))
11170 ;; (ys (floor (* 365 24 60 60)))
11171 (ds (* 24 60 60))
11172 (hs (* 60 60))
11173 (fy "%dy %dd %02d:%02d")
11174 (fy1 "%dy %dd")
11175 (fd "%dd %02d:%02d")
11176 (fd1 "%dd")
11177 (fh "%02d:%02d")
11178 y d h m align)
11179 (if havetime
11180 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11182 d (floor (/ diff ds)) diff (mod diff ds)
11183 h (floor (/ diff hs)) diff (mod diff hs)
11184 m (floor (/ diff 60)))
11185 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11187 d (floor (+ (/ diff ds) 0.5))
11188 h 0 m 0))
11189 (if (not to-buffer)
11190 (message "%s" (org-make-tdiff-string y d h m))
11191 (if (org-at-table-p)
11192 (progn
11193 (goto-char match-end)
11194 (setq align t)
11195 (and (looking-at " *|") (goto-char (match-end 0))))
11196 (goto-char match-end))
11197 (if (looking-at
11198 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11199 (replace-match ""))
11200 (if negative (insert " -"))
11201 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11202 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11203 (insert " " (format fh h m))))
11204 (if align (org-table-align))
11205 (message "Time difference inserted")))))
11207 (defun org-make-tdiff-string (y d h m)
11208 (let ((fmt "")
11209 (l nil))
11210 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11211 l (push y l)))
11212 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11213 l (push d l)))
11214 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11215 l (push h l)))
11216 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11217 l (push m l)))
11218 (apply 'format fmt (nreverse l))))
11220 (defun org-time-string-to-time (s)
11221 (apply 'encode-time (org-parse-time-string s)))
11223 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11224 "Convert a time stamp to an absolute day number.
11225 If there is a specifyer for a cyclic time stamp, get the closest date to
11226 DAYNR.
11227 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11228 (cond
11229 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11230 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11231 daynr
11232 (+ daynr 1000)))
11233 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11234 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11235 (time-to-days (current-time))) (match-string 0 s)
11236 prefer show-all))
11237 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11239 (defun org-days-to-iso-week (days)
11240 "Return the iso week number."
11241 (require 'cal-iso)
11242 (car (calendar-iso-from-absolute days)))
11244 (defun org-small-year-to-year (year)
11245 "Convert 2-digit years into 4-digit years.
11246 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11247 The year 2000 cannot be abbreviated. Any year lager than 99
11248 is retrned unchanged."
11249 (if (< year 38)
11250 (setq year (+ 2000 year))
11251 (if (< year 100)
11252 (setq year (+ 1900 year))))
11253 year)
11255 (defun org-time-from-absolute (d)
11256 "Return the time corresponding to date D.
11257 D may be an absolute day number, or a calendar-type list (month day year)."
11258 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11259 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11261 (defun org-calendar-holiday ()
11262 "List of holidays, for Diary display in Org-mode."
11263 (require 'holidays)
11264 (let ((hl (funcall
11265 (if (fboundp 'calendar-check-holidays)
11266 'calendar-check-holidays 'check-calendar-holidays) date)))
11267 (if hl (mapconcat 'identity hl "; "))))
11269 (defun org-diary-sexp-entry (sexp entry date)
11270 "Process a SEXP diary ENTRY for DATE."
11271 (require 'diary-lib)
11272 (let ((result (if calendar-debug-sexp
11273 (let ((stack-trace-on-error t))
11274 (eval (car (read-from-string sexp))))
11275 (condition-case nil
11276 (eval (car (read-from-string sexp)))
11277 (error
11278 (beep)
11279 (message "Bad sexp at line %d in %s: %s"
11280 (org-current-line)
11281 (buffer-file-name) sexp)
11282 (sleep-for 2))))))
11283 (cond ((stringp result) result)
11284 ((and (consp result)
11285 (stringp (cdr result))) (cdr result))
11286 (result entry)
11287 (t nil))))
11289 (defun org-diary-to-ical-string (frombuf)
11290 "Get iCalendar entries from diary entries in buffer FROMBUF.
11291 This uses the icalendar.el library."
11292 (let* ((tmpdir (if (featurep 'xemacs)
11293 (temp-directory)
11294 temporary-file-directory))
11295 (tmpfile (make-temp-name
11296 (expand-file-name "orgics" tmpdir)))
11297 buf rtn b e)
11298 (save-excursion
11299 (set-buffer frombuf)
11300 (icalendar-export-region (point-min) (point-max) tmpfile)
11301 (setq buf (find-buffer-visiting tmpfile))
11302 (set-buffer buf)
11303 (goto-char (point-min))
11304 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11305 (setq b (match-beginning 0)))
11306 (goto-char (point-max))
11307 (if (re-search-backward "^END:VEVENT" nil t)
11308 (setq e (match-end 0)))
11309 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11310 (kill-buffer buf)
11311 (kill-buffer frombuf)
11312 (delete-file tmpfile)
11313 rtn))
11315 (defun org-closest-date (start current change prefer show-all)
11316 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11317 When PREFER is `past' return a date that is either CURRENT or past.
11318 When PREFER is `future', return a date that is either CURRENT or future.
11319 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11320 ;; Make the proper lists from the dates
11321 (catch 'exit
11322 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11323 dn dw sday cday n1 n2
11324 d m y y1 y2 date1 date2 nmonths nm ny m2)
11326 (setq start (org-date-to-gregorian start)
11327 current (org-date-to-gregorian
11328 (if show-all
11329 current
11330 (time-to-days (current-time))))
11331 sday (calendar-absolute-from-gregorian start)
11332 cday (calendar-absolute-from-gregorian current))
11334 (if (<= cday sday) (throw 'exit sday))
11336 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11337 (setq dn (string-to-number (match-string 1 change))
11338 dw (cdr (assoc (match-string 2 change) a1)))
11339 (error "Invalid change specifyer: %s" change))
11340 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11341 (cond
11342 ((eq dw 'day)
11343 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11344 n2 (+ n1 dn)))
11345 ((eq dw 'year)
11346 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11347 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11348 (setq date1 (list m d y1)
11349 n1 (calendar-absolute-from-gregorian date1)
11350 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11351 n2 (calendar-absolute-from-gregorian date2)))
11352 ((eq dw 'month)
11353 ;; approx number of month between the tow dates
11354 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11355 ;; How often does dn fit in there?
11356 (setq d (nth 1 start) m (car start) y (nth 2 start)
11357 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11358 m (+ m nm)
11359 ny (floor (/ m 12))
11360 y (+ y ny)
11361 m (- m (* ny 12)))
11362 (while (> m 12) (setq m (- m 12) y (1+ y)))
11363 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11364 (setq m2 (+ m dn) y2 y)
11365 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11366 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11367 (while (< n2 cday)
11368 (setq n1 n2 m m2 y y2)
11369 (setq m2 (+ m dn) y2 y)
11370 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11371 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11373 (if show-all
11374 (cond
11375 ((eq prefer 'past) n1)
11376 ((eq prefer 'future) (if (= cday n1) n1 n2))
11377 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11378 (cond
11379 ((eq prefer 'past) n1)
11380 ((eq prefer 'future) (if (= cday n1) n1 n2))
11381 (t (if (= cday n1) n1 n2)))))))
11383 (defun org-date-to-gregorian (date)
11384 "Turn any specification of DATE into a gregorian date for the calendar."
11385 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11386 ((and (listp date) (= (length date) 3)) date)
11387 ((stringp date)
11388 (setq date (org-parse-time-string date))
11389 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11390 ((listp date)
11391 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11393 (defun org-parse-time-string (s &optional nodefault)
11394 "Parse the standard Org-mode time string.
11395 This should be a lot faster than the normal `parse-time-string'.
11396 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11397 hour and minute fields will be nil if not given."
11398 (if (string-match org-ts-regexp0 s)
11399 (list 0
11400 (if (or (match-beginning 8) (not nodefault))
11401 (string-to-number (or (match-string 8 s) "0")))
11402 (if (or (match-beginning 7) (not nodefault))
11403 (string-to-number (or (match-string 7 s) "0")))
11404 (string-to-number (match-string 4 s))
11405 (string-to-number (match-string 3 s))
11406 (string-to-number (match-string 2 s))
11407 nil nil nil)
11408 (make-list 9 0)))
11410 (defun org-timestamp-up (&optional arg)
11411 "Increase the date item at the cursor by one.
11412 If the cursor is on the year, change the year. If it is on the month or
11413 the day, change that.
11414 With prefix ARG, change by that many units."
11415 (interactive "p")
11416 (org-timestamp-change (prefix-numeric-value arg)))
11418 (defun org-timestamp-down (&optional arg)
11419 "Decrease the date item at the cursor by one.
11420 If the cursor is on the year, change the year. If it is on the month or
11421 the day, change that.
11422 With prefix ARG, change by that many units."
11423 (interactive "p")
11424 (org-timestamp-change (- (prefix-numeric-value arg))))
11426 (defun org-timestamp-up-day (&optional arg)
11427 "Increase the date in the time stamp by one day.
11428 With prefix ARG, change that many days."
11429 (interactive "p")
11430 (if (and (not (org-at-timestamp-p t))
11431 (org-on-heading-p))
11432 (org-todo 'up)
11433 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11435 (defun org-timestamp-down-day (&optional arg)
11436 "Decrease the date in the time stamp by one day.
11437 With prefix ARG, change that many days."
11438 (interactive "p")
11439 (if (and (not (org-at-timestamp-p t))
11440 (org-on-heading-p))
11441 (org-todo 'down)
11442 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11444 (defun org-at-timestamp-p (&optional inactive-ok)
11445 "Determine if the cursor is in or at a timestamp."
11446 (interactive)
11447 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11448 (pos (point))
11449 (ans (or (looking-at tsr)
11450 (save-excursion
11451 (skip-chars-backward "^[<\n\r\t")
11452 (if (> (point) (point-min)) (backward-char 1))
11453 (and (looking-at tsr)
11454 (> (- (match-end 0) pos) -1))))))
11455 (and ans
11456 (boundp 'org-ts-what)
11457 (setq org-ts-what
11458 (cond
11459 ((= pos (match-beginning 0)) 'bracket)
11460 ((= pos (1- (match-end 0))) 'bracket)
11461 ((org-pos-in-match-range pos 2) 'year)
11462 ((org-pos-in-match-range pos 3) 'month)
11463 ((org-pos-in-match-range pos 7) 'hour)
11464 ((org-pos-in-match-range pos 8) 'minute)
11465 ((or (org-pos-in-match-range pos 4)
11466 (org-pos-in-match-range pos 5)) 'day)
11467 ((and (> pos (or (match-end 8) (match-end 5)))
11468 (< pos (match-end 0)))
11469 (- pos (or (match-end 8) (match-end 5))))
11470 (t 'day))))
11471 ans))
11473 (defun org-toggle-timestamp-type ()
11474 "Toggle the type (<active> or [inactive]) of a time stamp."
11475 (interactive)
11476 (when (org-at-timestamp-p t)
11477 (save-excursion
11478 (goto-char (match-beginning 0))
11479 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11480 (goto-char (1- (match-end 0)))
11481 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11482 (message "Timestamp is now %sactive"
11483 (if (equal (char-before) ?>) "in" ""))))
11485 (defun org-timestamp-change (n &optional what)
11486 "Change the date in the time stamp at point.
11487 The date will be changed by N times WHAT. WHAT can be `day', `month',
11488 `year', `minute', `second'. If WHAT is not given, the cursor position
11489 in the timestamp determines what will be changed."
11490 (let ((pos (point))
11491 with-hm inactive
11492 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11493 org-ts-what
11494 extra rem
11495 ts time time0)
11496 (if (not (org-at-timestamp-p t))
11497 (error "Not at a timestamp"))
11498 (if (and (not what) (eq org-ts-what 'bracket))
11499 (org-toggle-timestamp-type)
11500 (if (and (not what) (not (eq org-ts-what 'day))
11501 org-display-custom-times
11502 (get-text-property (point) 'display)
11503 (not (get-text-property (1- (point)) 'display)))
11504 (setq org-ts-what 'day))
11505 (setq org-ts-what (or what org-ts-what)
11506 inactive (= (char-after (match-beginning 0)) ?\[)
11507 ts (match-string 0))
11508 (replace-match "")
11509 (if (string-match
11510 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11512 (setq extra (match-string 1 ts)))
11513 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11514 (setq with-hm t))
11515 (setq time0 (org-parse-time-string ts))
11516 (when (and (eq org-ts-what 'minute)
11517 (eq current-prefix-arg nil))
11518 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11519 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11520 (setcar (cdr time0) (+ (nth 1 time0)
11521 (if (> n 0) (- rem) (- dm rem))))))
11522 (setq time
11523 (encode-time (or (car time0) 0)
11524 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11525 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11526 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11527 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11528 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11529 (nthcdr 6 time0)))
11530 (when (integerp org-ts-what)
11531 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11532 (if (eq what 'calendar)
11533 (let ((cal-date (org-get-date-from-calendar)))
11534 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11535 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11536 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11537 (setcar time0 (or (car time0) 0))
11538 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11539 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11540 (setq time (apply 'encode-time time0))))
11541 (setq org-last-changed-timestamp
11542 (org-insert-time-stamp time with-hm inactive nil nil extra))
11543 (org-clock-update-time-maybe)
11544 (goto-char pos)
11545 ;; Try to recenter the calendar window, if any
11546 (if (and org-calendar-follow-timestamp-change
11547 (get-buffer-window "*Calendar*" t)
11548 (memq org-ts-what '(day month year)))
11549 (org-recenter-calendar (time-to-days time))))))
11551 (defun org-modify-ts-extra (s pos n dm)
11552 "Change the different parts of the lead-time and repeat fields in timestamp."
11553 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11554 ng h m new rem)
11555 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11556 (cond
11557 ((or (org-pos-in-match-range pos 2)
11558 (org-pos-in-match-range pos 3))
11559 (setq m (string-to-number (match-string 3 s))
11560 h (string-to-number (match-string 2 s)))
11561 (if (org-pos-in-match-range pos 2)
11562 (setq h (+ h n))
11563 (setq n (* dm (org-no-warnings (signum n))))
11564 (when (not (= 0 (setq rem (% m dm))))
11565 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11566 (setq m (+ m n)))
11567 (if (< m 0) (setq m (+ m 60) h (1- h)))
11568 (if (> m 59) (setq m (- m 60) h (1+ h)))
11569 (setq h (min 24 (max 0 h)))
11570 (setq ng 1 new (format "-%02d:%02d" h m)))
11571 ((org-pos-in-match-range pos 6)
11572 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11573 ((org-pos-in-match-range pos 5)
11574 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11576 ((org-pos-in-match-range pos 9)
11577 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11578 ((org-pos-in-match-range pos 8)
11579 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11581 (when ng
11582 (setq s (concat
11583 (substring s 0 (match-beginning ng))
11585 (substring s (match-end ng))))))
11588 (defun org-recenter-calendar (date)
11589 "If the calendar is visible, recenter it to DATE."
11590 (let* ((win (selected-window))
11591 (cwin (get-buffer-window "*Calendar*" t))
11592 (calendar-move-hook nil))
11593 (when cwin
11594 (select-window cwin)
11595 (calendar-goto-date (if (listp date) date
11596 (calendar-gregorian-from-absolute date)))
11597 (select-window win))))
11599 (defun org-goto-calendar (&optional arg)
11600 "Go to the Emacs calendar at the current date.
11601 If there is a time stamp in the current line, go to that date.
11602 A prefix ARG can be used to force the current date."
11603 (interactive "P")
11604 (let ((tsr org-ts-regexp) diff
11605 (calendar-move-hook nil)
11606 (calendar-view-holidays-initially-flag nil)
11607 (view-calendar-holidays-initially nil)
11608 (calendar-view-diary-initially-flag nil)
11609 (view-diary-entries-initially nil))
11610 (if (or (org-at-timestamp-p)
11611 (save-excursion
11612 (beginning-of-line 1)
11613 (looking-at (concat ".*" tsr))))
11614 (let ((d1 (time-to-days (current-time)))
11615 (d2 (time-to-days
11616 (org-time-string-to-time (match-string 1)))))
11617 (setq diff (- d2 d1))))
11618 (calendar)
11619 (calendar-goto-today)
11620 (if (and diff (not arg)) (calendar-forward-day diff))))
11622 (defun org-get-date-from-calendar ()
11623 "Return a list (month day year) of date at point in calendar."
11624 (with-current-buffer "*Calendar*"
11625 (save-match-data
11626 (calendar-cursor-to-date))))
11628 (defun org-date-from-calendar ()
11629 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11630 If there is already a time stamp at the cursor position, update it."
11631 (interactive)
11632 (if (org-at-timestamp-p t)
11633 (org-timestamp-change 0 'calendar)
11634 (let ((cal-date (org-get-date-from-calendar)))
11635 (org-insert-time-stamp
11636 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11638 (defun org-minutes-to-hh:mm-string (m)
11639 "Compute H:MM from a number of minutes."
11640 (let ((h (/ m 60)))
11641 (setq m (- m (* 60 h)))
11642 (format org-time-clocksum-format h m)))
11644 (defun org-hh:mm-string-to-minutes (s)
11645 "Convert a string H:MM to a number of minutes."
11646 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11647 (+ (* (string-to-number (match-string 1 s)) 60)
11648 (string-to-number (match-string 2 s)))
11651 ;;;; Agenda files
11653 ;;;###autoload
11654 (defun org-iswitchb (&optional arg)
11655 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11656 With a prefix argument, restrict available to files.
11657 With two prefix arguments, restrict available buffers to agenda files.
11659 Due to some yet unresolved reason, global function
11660 `iswitchb-mode' needs to be active for this function to work."
11661 (interactive "P")
11662 (require 'iswitchb)
11663 (let ((enabled iswitchb-mode) blist)
11664 (or enabled (iswitchb-mode 1))
11665 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11666 ((equal arg '(16)) (org-buffer-list 'agenda))
11667 (t (org-buffer-list))))
11668 (unwind-protect
11669 (let ((iswitchb-make-buflist-hook
11670 (lambda ()
11671 (setq iswitchb-temp-buflist
11672 (mapcar 'buffer-name blist)))))
11673 (switch-to-buffer
11674 (iswitchb-read-buffer
11675 "Switch-to: " nil t))
11676 (or enabled (iswitchb-mode -1))))))
11678 (defun org-buffer-list (&optional predicate tmp)
11679 "Return a list of Org buffers.
11680 PREDICATE can be either 'export, 'files or 'agenda.
11682 'export restrict the list to Export buffers.
11683 'files restrict the list to buffers visiting Org files.
11684 'agenda restrict the list to buffers visiting agenda files.
11686 If TMP is non-nil, don't include temporary buffers."
11687 (let (filter blist)
11688 (setq filter
11689 (cond ((eq predicate 'files) "\.org$")
11690 ((eq predicate 'export) "\*Org .*Export")
11691 (t "\*Org \\|\.org$")))
11692 (setq blist
11693 (mapcar
11694 (lambda(b)
11695 (let ((bname (buffer-name b))
11696 (bfile (buffer-file-name b)))
11697 (if (and (string-match filter bname)
11698 (if (eq predicate 'agenda)
11699 (member bfile
11700 (mapcar (lambda(f) (file-truename f))
11701 org-agenda-files)) t)
11702 (if tmp (not (string-match "tmp" bname)) t)) b)))
11703 (buffer-list)))
11704 (delete nil blist)))
11706 (defun org-agenda-files (&optional unrestricted ext)
11707 "Get the list of agenda files.
11708 Optional UNRESTRICTED means return the full list even if a restriction
11709 is currently in place.
11710 When EXT is non-nil, try to add all files that are created by adding EXT
11711 to the file nemes. Basically, this is a way to add the archive files
11712 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11713 a string, \"_archive\" will be used."
11714 (let ((files
11715 (cond
11716 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11717 ((stringp org-agenda-files) (org-read-agenda-file-list))
11718 ((listp org-agenda-files) org-agenda-files)
11719 (t (error "Invalid value of `org-agenda-files'")))))
11720 (setq files (apply 'append
11721 (mapcar (lambda (f)
11722 (if (file-directory-p f)
11723 (directory-files
11724 f t org-agenda-file-regexp)
11725 (list f)))
11726 files)))
11727 (when org-agenda-skip-unavailable-files
11728 (setq files (delq nil
11729 (mapcar (function
11730 (lambda (file)
11731 (and (file-readable-p file) file)))
11732 files))))
11733 (when ext
11734 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11735 ext "_archive"))
11736 (setq files (apply 'append
11737 (mapcar
11738 (lambda (f)
11739 (if (file-exists-p (concat f ext))
11740 (list f (concat f ext))
11741 (list f)))
11742 files))))
11743 files))
11745 (defun org-edit-agenda-file-list ()
11746 "Edit the list of agenda files.
11747 Depending on setup, this either uses customize to edit the variable
11748 `org-agenda-files', or it visits the file that is holding the list. In the
11749 latter case, the buffer is set up in a way that saving it automatically kills
11750 the buffer and restores the previous window configuration."
11751 (interactive)
11752 (if (stringp org-agenda-files)
11753 (let ((cw (current-window-configuration)))
11754 (find-file org-agenda-files)
11755 (org-set-local 'org-window-configuration cw)
11756 (org-add-hook 'after-save-hook
11757 (lambda ()
11758 (set-window-configuration
11759 (prog1 org-window-configuration
11760 (kill-buffer (current-buffer))))
11761 (org-install-agenda-files-menu)
11762 (message "New agenda file list installed"))
11763 nil 'local)
11764 (message "%s" (substitute-command-keys
11765 "Edit list and finish with \\[save-buffer]")))
11766 (customize-variable 'org-agenda-files)))
11768 (defun org-store-new-agenda-file-list (list)
11769 "Set new value for the agenda file list and save it correcly."
11770 (if (stringp org-agenda-files)
11771 (let ((f org-agenda-files) b)
11772 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11773 (with-temp-file f
11774 (insert (mapconcat 'identity list "\n") "\n")))
11775 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11776 (setq org-agenda-files list)
11777 (customize-save-variable 'org-agenda-files org-agenda-files))))
11779 (defun org-read-agenda-file-list ()
11780 "Read the list of agenda files from a file."
11781 (when (file-directory-p org-agenda-files)
11782 (error "`org-agenda-files' cannot be a single directory"))
11783 (when (stringp org-agenda-files)
11784 (with-temp-buffer
11785 (insert-file-contents org-agenda-files)
11786 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11789 ;;;###autoload
11790 (defun org-cycle-agenda-files ()
11791 "Cycle through the files in `org-agenda-files'.
11792 If the current buffer visits an agenda file, find the next one in the list.
11793 If the current buffer does not, find the first agenda file."
11794 (interactive)
11795 (let* ((fs (org-agenda-files t))
11796 (files (append fs (list (car fs))))
11797 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11798 file)
11799 (unless files (error "No agenda files"))
11800 (catch 'exit
11801 (while (setq file (pop files))
11802 (if (equal (file-truename file) tcf)
11803 (when (car files)
11804 (find-file (car files))
11805 (throw 'exit t))))
11806 (find-file (car fs)))
11807 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11809 (defun org-agenda-file-to-front (&optional to-end)
11810 "Move/add the current file to the top of the agenda file list.
11811 If the file is not present in the list, it is added to the front. If it is
11812 present, it is moved there. With optional argument TO-END, add/move to the
11813 end of the list."
11814 (interactive "P")
11815 (let ((org-agenda-skip-unavailable-files nil)
11816 (file-alist (mapcar (lambda (x)
11817 (cons (file-truename x) x))
11818 (org-agenda-files t)))
11819 (ctf (file-truename buffer-file-name))
11820 x had)
11821 (setq x (assoc ctf file-alist) had x)
11823 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11824 (if to-end
11825 (setq file-alist (append (delq x file-alist) (list x)))
11826 (setq file-alist (cons x (delq x file-alist))))
11827 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11828 (org-install-agenda-files-menu)
11829 (message "File %s to %s of agenda file list"
11830 (if had "moved" "added") (if to-end "end" "front"))))
11832 (defun org-remove-file (&optional file)
11833 "Remove current file from the list of files in variable `org-agenda-files'.
11834 These are the files which are being checked for agenda entries.
11835 Optional argument FILE means, use this file instead of the current."
11836 (interactive)
11837 (let* ((org-agenda-skip-unavailable-files nil)
11838 (file (or file buffer-file-name))
11839 (true-file (file-truename file))
11840 (afile (abbreviate-file-name file))
11841 (files (delq nil (mapcar
11842 (lambda (x)
11843 (if (equal true-file
11844 (file-truename x))
11845 nil x))
11846 (org-agenda-files t)))))
11847 (if (not (= (length files) (length (org-agenda-files t))))
11848 (progn
11849 (org-store-new-agenda-file-list files)
11850 (org-install-agenda-files-menu)
11851 (message "Removed file: %s" afile))
11852 (message "File was not in list: %s (not removed)" afile))))
11854 (defun org-file-menu-entry (file)
11855 (vector file (list 'find-file file) t))
11857 (defun org-check-agenda-file (file)
11858 "Make sure FILE exists. If not, ask user what to do."
11859 (when (not (file-exists-p file))
11860 (message "non-existent file %s. [R]emove from list or [A]bort?"
11861 (abbreviate-file-name file))
11862 (let ((r (downcase (read-char-exclusive))))
11863 (cond
11864 ((equal r ?r)
11865 (org-remove-file file)
11866 (throw 'nextfile t))
11867 (t (error "Abort"))))))
11869 (defun org-get-agenda-file-buffer (file)
11870 "Get a buffer visiting FILE. If the buffer needs to be created, add
11871 it to the list of buffers which might be released later."
11872 (let ((buf (org-find-base-buffer-visiting file)))
11873 (if buf
11874 buf ; just return it
11875 ;; Make a new buffer and remember it
11876 (setq buf (find-file-noselect file))
11877 (if buf (push buf org-agenda-new-buffers))
11878 buf)))
11880 (defun org-release-buffers (blist)
11881 "Release all buffers in list, asking the user for confirmation when needed.
11882 When a buffer is unmodified, it is just killed. When modified, it is saved
11883 \(if the user agrees) and then killed."
11884 (let (buf file)
11885 (while (setq buf (pop blist))
11886 (setq file (buffer-file-name buf))
11887 (when (and (buffer-modified-p buf)
11888 file
11889 (y-or-n-p (format "Save file %s? " file)))
11890 (with-current-buffer buf (save-buffer)))
11891 (kill-buffer buf))))
11893 (defun org-prepare-agenda-buffers (files)
11894 "Create buffers for all agenda files, protect archived trees and comments."
11895 (interactive)
11896 (let ((pa '(:org-archived t))
11897 (pc '(:org-comment t))
11898 (pall '(:org-archived t :org-comment t))
11899 (inhibit-read-only t)
11900 (rea (concat ":" org-archive-tag ":"))
11901 bmp file re)
11902 (save-excursion
11903 (save-restriction
11904 (while (setq file (pop files))
11905 (if (bufferp file)
11906 (set-buffer file)
11907 (org-check-agenda-file file)
11908 (set-buffer (org-get-agenda-file-buffer file)))
11909 (widen)
11910 (setq bmp (buffer-modified-p))
11911 (org-refresh-category-properties)
11912 (setq org-todo-keywords-for-agenda
11913 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11914 (setq org-done-keywords-for-agenda
11915 (append org-done-keywords-for-agenda org-done-keywords))
11916 (save-excursion
11917 (remove-text-properties (point-min) (point-max) pall)
11918 (when org-agenda-skip-archived-trees
11919 (goto-char (point-min))
11920 (while (re-search-forward rea nil t)
11921 (if (org-on-heading-p t)
11922 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11923 (goto-char (point-min))
11924 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11925 (while (re-search-forward re nil t)
11926 (add-text-properties
11927 (match-beginning 0) (org-end-of-subtree t) pc)))
11928 (set-buffer-modified-p bmp))))))
11930 ;;;; Embedded LaTeX
11932 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11933 "Keymap for the minor `org-cdlatex-mode'.")
11935 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11936 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11937 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11938 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11939 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11941 (defvar org-cdlatex-texmathp-advice-is-done nil
11942 "Flag remembering if we have applied the advice to texmathp already.")
11944 (define-minor-mode org-cdlatex-mode
11945 "Toggle the minor `org-cdlatex-mode'.
11946 This mode supports entering LaTeX environment and math in LaTeX fragments
11947 in Org-mode.
11948 \\{org-cdlatex-mode-map}"
11949 nil " OCDL" nil
11950 (when org-cdlatex-mode (require 'cdlatex))
11951 (unless org-cdlatex-texmathp-advice-is-done
11952 (setq org-cdlatex-texmathp-advice-is-done t)
11953 (defadvice texmathp (around org-math-always-on activate)
11954 "Always return t in org-mode buffers.
11955 This is because we want to insert math symbols without dollars even outside
11956 the LaTeX math segments. If Orgmode thinks that point is actually inside
11957 en embedded LaTeX fragement, let texmathp do its job.
11958 \\[org-cdlatex-mode-map]"
11959 (interactive)
11960 (let (p)
11961 (cond
11962 ((not (org-mode-p)) ad-do-it)
11963 ((eq this-command 'cdlatex-math-symbol)
11964 (setq ad-return-value t
11965 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11967 (let ((p (org-inside-LaTeX-fragment-p)))
11968 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11969 (setq ad-return-value t
11970 texmathp-why '("Org-mode embedded math" . 0))
11971 (if p ad-do-it)))))))))
11973 (defun turn-on-org-cdlatex ()
11974 "Unconditionally turn on `org-cdlatex-mode'."
11975 (org-cdlatex-mode 1))
11977 (defun org-inside-LaTeX-fragment-p ()
11978 "Test if point is inside a LaTeX fragment.
11979 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11980 sequence appearing also before point.
11981 Even though the matchers for math are configurable, this function assumes
11982 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11983 delimiters are skipped when they have been removed by customization.
11984 The return value is nil, or a cons cell with the delimiter and
11985 and the position of this delimiter.
11987 This function does a reasonably good job, but can locally be fooled by
11988 for example currency specifications. For example it will assume being in
11989 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11990 fragments that are properly closed, but during editing, we have to live
11991 with the uncertainty caused by missing closing delimiters. This function
11992 looks only before point, not after."
11993 (catch 'exit
11994 (let ((pos (point))
11995 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11996 (lim (progn
11997 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11998 (point)))
11999 dd-on str (start 0) m re)
12000 (goto-char pos)
12001 (when dodollar
12002 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12003 re (nth 1 (assoc "$" org-latex-regexps)))
12004 (while (string-match re str start)
12005 (cond
12006 ((= (match-end 0) (length str))
12007 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12008 ((= (match-end 0) (- (length str) 5))
12009 (throw 'exit nil))
12010 (t (setq start (match-end 0))))))
12011 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12012 (goto-char pos)
12013 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12014 (and (match-beginning 2) (throw 'exit nil))
12015 ;; count $$
12016 (while (re-search-backward "\\$\\$" lim t)
12017 (setq dd-on (not dd-on)))
12018 (goto-char pos)
12019 (if dd-on (cons "$$" m))))))
12022 (defun org-try-cdlatex-tab ()
12023 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12024 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12025 - inside a LaTeX fragment, or
12026 - after the first word in a line, where an abbreviation expansion could
12027 insert a LaTeX environment."
12028 (when org-cdlatex-mode
12029 (cond
12030 ((save-excursion
12031 (skip-chars-backward "a-zA-Z0-9*")
12032 (skip-chars-backward " \t")
12033 (bolp))
12034 (cdlatex-tab) t)
12035 ((org-inside-LaTeX-fragment-p)
12036 (cdlatex-tab) t)
12037 (t nil))))
12039 (defun org-cdlatex-underscore-caret (&optional arg)
12040 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12041 Revert to the normal definition outside of these fragments."
12042 (interactive "P")
12043 (if (org-inside-LaTeX-fragment-p)
12044 (call-interactively 'cdlatex-sub-superscript)
12045 (let (org-cdlatex-mode)
12046 (call-interactively (key-binding (vector last-input-event))))))
12048 (defun org-cdlatex-math-modify (&optional arg)
12049 "Execute `cdlatex-math-modify' in LaTeX fragments.
12050 Revert to the normal definition outside of these fragments."
12051 (interactive "P")
12052 (if (org-inside-LaTeX-fragment-p)
12053 (call-interactively 'cdlatex-math-modify)
12054 (let (org-cdlatex-mode)
12055 (call-interactively (key-binding (vector last-input-event))))))
12057 (defvar org-latex-fragment-image-overlays nil
12058 "List of overlays carrying the images of latex fragments.")
12059 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12061 (defun org-remove-latex-fragment-image-overlays ()
12062 "Remove all overlays with LaTeX fragment images in current buffer."
12063 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12064 (setq org-latex-fragment-image-overlays nil))
12066 (defun org-preview-latex-fragment (&optional subtree)
12067 "Preview the LaTeX fragment at point, or all locally or globally.
12068 If the cursor is in a LaTeX fragment, create the image and overlay
12069 it over the source code. If there is no fragment at point, display
12070 all fragments in the current text, from one headline to the next. With
12071 prefix SUBTREE, display all fragments in the current subtree. With a
12072 double prefix `C-u C-u', or when the cursor is before the first headline,
12073 display all fragments in the buffer.
12074 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12075 (interactive "P")
12076 (org-remove-latex-fragment-image-overlays)
12077 (save-excursion
12078 (save-restriction
12079 (let (beg end at msg)
12080 (cond
12081 ((or (equal subtree '(16))
12082 (not (save-excursion
12083 (re-search-backward (concat "^" outline-regexp) nil t))))
12084 (setq beg (point-min) end (point-max)
12085 msg "Creating images for buffer...%s"))
12086 ((equal subtree '(4))
12087 (org-back-to-heading)
12088 (setq beg (point) end (org-end-of-subtree t)
12089 msg "Creating images for subtree...%s"))
12091 (if (setq at (org-inside-LaTeX-fragment-p))
12092 (goto-char (max (point-min) (- (cdr at) 2)))
12093 (org-back-to-heading))
12094 (setq beg (point) end (progn (outline-next-heading) (point))
12095 msg (if at "Creating image...%s"
12096 "Creating images for entry...%s"))))
12097 (message msg "")
12098 (narrow-to-region beg end)
12099 (goto-char beg)
12100 (org-format-latex
12101 (concat "ltxpng/" (file-name-sans-extension
12102 (file-name-nondirectory
12103 buffer-file-name)))
12104 default-directory 'overlays msg at 'forbuffer)
12105 (message msg "done. Use `C-c C-c' to remove images.")))))
12107 (defvar org-latex-regexps
12108 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12109 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12110 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12111 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12112 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12113 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12114 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12115 "Regular expressions for matching embedded LaTeX.")
12117 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12118 "Replace LaTeX fragments with links to an image, and produce images."
12119 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12120 (let* ((prefixnodir (file-name-nondirectory prefix))
12121 (absprefix (expand-file-name prefix dir))
12122 (todir (file-name-directory absprefix))
12123 (opt org-format-latex-options)
12124 (matchers (plist-get opt :matchers))
12125 (re-list org-latex-regexps)
12126 (cnt 0) txt link beg end re e checkdir
12127 m n block linkfile movefile ov)
12128 ;; Check if there are old images files with this prefix, and remove them
12129 (when (file-directory-p todir)
12130 (mapc 'delete-file
12131 (directory-files
12132 todir 'full
12133 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12134 ;; Check the different regular expressions
12135 (while (setq e (pop re-list))
12136 (setq m (car e) re (nth 1 e) n (nth 2 e)
12137 block (if (nth 3 e) "\n\n" ""))
12138 (when (member m matchers)
12139 (goto-char (point-min))
12140 (while (re-search-forward re nil t)
12141 (when (or (not at) (equal (cdr at) (match-beginning n)))
12142 (setq txt (match-string n)
12143 beg (match-beginning n) end (match-end n)
12144 cnt (1+ cnt)
12145 linkfile (format "%s_%04d.png" prefix cnt)
12146 movefile (format "%s_%04d.png" absprefix cnt)
12147 link (concat block "[[file:" linkfile "]]" block))
12148 (if msg (message msg cnt))
12149 (goto-char beg)
12150 (unless checkdir ; make sure the directory exists
12151 (setq checkdir t)
12152 (or (file-directory-p todir) (make-directory todir)))
12153 (org-create-formula-image
12154 txt movefile opt forbuffer)
12155 (if overlays
12156 (progn
12157 (setq ov (org-make-overlay beg end))
12158 (if (featurep 'xemacs)
12159 (progn
12160 (org-overlay-put ov 'invisible t)
12161 (org-overlay-put
12162 ov 'end-glyph
12163 (make-glyph (vector 'png :file movefile))))
12164 (org-overlay-put
12165 ov 'display
12166 (list 'image :type 'png :file movefile :ascent 'center)))
12167 (push ov org-latex-fragment-image-overlays)
12168 (goto-char end))
12169 (delete-region beg end)
12170 (insert link))))))))
12172 ;; This function borrows from Ganesh Swami's latex2png.el
12173 (defun org-create-formula-image (string tofile options buffer)
12174 (let* ((tmpdir (if (featurep 'xemacs)
12175 (temp-directory)
12176 temporary-file-directory))
12177 (texfilebase (make-temp-name
12178 (expand-file-name "orgtex" tmpdir)))
12179 (texfile (concat texfilebase ".tex"))
12180 (dvifile (concat texfilebase ".dvi"))
12181 (pngfile (concat texfilebase ".png"))
12182 (fnh (if (featurep 'xemacs)
12183 (font-height (get-face-font 'default))
12184 (face-attribute 'default :height nil)))
12185 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12186 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12187 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12188 "Black"))
12189 (bg (or (plist-get options (if buffer :background :html-background))
12190 "Transparent")))
12191 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12192 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12193 (with-temp-file texfile
12194 (insert org-format-latex-header
12195 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12196 (let ((dir default-directory))
12197 (condition-case nil
12198 (progn
12199 (cd tmpdir)
12200 (call-process "latex" nil nil nil texfile))
12201 (error nil))
12202 (cd dir))
12203 (if (not (file-exists-p dvifile))
12204 (progn (message "Failed to create dvi file from %s" texfile) nil)
12205 (call-process "dvipng" nil nil nil
12206 "-E" "-fg" fg "-bg" bg
12207 "-D" dpi
12208 ;;"-x" scale "-y" scale
12209 "-T" "tight"
12210 "-o" pngfile
12211 dvifile)
12212 (if (not (file-exists-p pngfile))
12213 (progn (message "Failed to create png file from %s" texfile) nil)
12214 ;; Use the requested file name and clean up
12215 (copy-file pngfile tofile 'replace)
12216 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12217 (delete-file (concat texfilebase e)))
12218 pngfile))))
12220 (defun org-dvipng-color (attr)
12221 "Return an rgb color specification for dvipng."
12222 (apply 'format "rgb %s %s %s"
12223 (mapcar 'org-normalize-color
12224 (color-values (face-attribute 'default attr nil)))))
12226 (defun org-normalize-color (value)
12227 "Return string to be used as color value for an RGB component."
12228 (format "%g" (/ value 65535.0)))
12231 ;;;; Key bindings
12233 ;; Make `C-c C-x' a prefix key
12234 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12236 ;; TAB key with modifiers
12237 (org-defkey org-mode-map "\C-i" 'org-cycle)
12238 (org-defkey org-mode-map [(tab)] 'org-cycle)
12239 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12240 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12241 (org-defkey org-mode-map "\M-\t" 'org-complete)
12242 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12243 ;; The following line is necessary under Suse GNU/Linux
12244 (unless (featurep 'xemacs)
12245 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12246 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12247 (define-key org-mode-map [backtab] 'org-shifttab)
12249 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12250 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12251 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12253 ;; Cursor keys with modifiers
12254 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12255 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12256 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12257 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12259 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12260 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12261 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12262 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12264 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12265 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12266 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12267 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12269 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12270 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12272 ;;; Extra keys for tty access.
12273 ;; We only set them when really needed because otherwise the
12274 ;; menus don't show the simple keys
12276 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12277 (not window-system))
12278 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12279 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12280 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12281 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12282 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12283 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12284 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12285 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12286 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12287 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12288 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12289 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12290 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12291 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12292 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12293 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12294 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12295 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12296 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12297 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12298 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12299 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12301 ;; All the other keys
12303 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12304 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12305 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
12306 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12307 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12308 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12309 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12310 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12311 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12312 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12313 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12314 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12315 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12316 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12317 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12318 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12319 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12320 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12321 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12322 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12323 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12324 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12325 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12326 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12327 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12328 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12329 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12330 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12331 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12332 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12333 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12334 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12335 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12336 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12337 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12338 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12339 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12340 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12341 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12342 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12343 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12344 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12345 (org-defkey org-mode-map "\C-c^" 'org-sort)
12346 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12347 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12348 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12349 (org-defkey org-mode-map "\C-m" 'org-return)
12350 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12351 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12352 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12353 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12354 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12355 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12356 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12357 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12358 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12359 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12360 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12361 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12362 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12363 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12364 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12365 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12367 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12368 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12369 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12370 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12372 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12373 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12374 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12375 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12376 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12377 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12378 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12379 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12380 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12381 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12382 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12383 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12385 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12387 (when (featurep 'xemacs)
12388 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12390 (defvar org-table-auto-blank-field) ; defined in org-table.el
12391 (defun org-self-insert-command (N)
12392 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12393 If the cursor is in a table looking at whitespace, the whitespace is
12394 overwritten, and the table is not marked as requiring realignment."
12395 (interactive "p")
12396 (if (and (org-table-p)
12397 (progn
12398 ;; check if we blank the field, and if that triggers align
12399 (and (featurep 'org-table) org-table-auto-blank-field
12400 (member last-command
12401 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12402 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12403 ;; got extra space, this field does not determine column width
12404 (let (org-table-may-need-update) (org-table-blank-field))
12405 ;; no extra space, this field may determine column width
12406 (org-table-blank-field)))
12408 (eq N 1)
12409 (looking-at "[^|\n]* |"))
12410 (let (org-table-may-need-update)
12411 (goto-char (1- (match-end 0)))
12412 (delete-backward-char 1)
12413 (goto-char (match-beginning 0))
12414 (self-insert-command N))
12415 (setq org-table-may-need-update t)
12416 (self-insert-command N)
12417 (org-fix-tags-on-the-fly)))
12419 (defun org-fix-tags-on-the-fly ()
12420 (when (and (equal (char-after (point-at-bol)) ?*)
12421 (org-on-heading-p))
12422 (org-align-tags-here org-tags-column)))
12424 (defun org-delete-backward-char (N)
12425 "Like `delete-backward-char', insert whitespace at field end in tables.
12426 When deleting backwards, in tables this function will insert whitespace in
12427 front of the next \"|\" separator, to keep the table aligned. The table will
12428 still be marked for re-alignment if the field did fill the entire column,
12429 because, in this case the deletion might narrow the column."
12430 (interactive "p")
12431 (if (and (org-table-p)
12432 (eq N 1)
12433 (string-match "|" (buffer-substring (point-at-bol) (point)))
12434 (looking-at ".*?|"))
12435 (let ((pos (point))
12436 (noalign (looking-at "[^|\n\r]* |"))
12437 (c org-table-may-need-update))
12438 (backward-delete-char N)
12439 (skip-chars-forward "^|")
12440 (insert " ")
12441 (goto-char (1- pos))
12442 ;; noalign: if there were two spaces at the end, this field
12443 ;; does not determine the width of the column.
12444 (if noalign (setq org-table-may-need-update c)))
12445 (backward-delete-char N)
12446 (org-fix-tags-on-the-fly)))
12448 (defun org-delete-char (N)
12449 "Like `delete-char', but insert whitespace at field end in tables.
12450 When deleting characters, in tables this function will insert whitespace in
12451 front of the next \"|\" separator, to keep the table aligned. The table will
12452 still be marked for re-alignment if the field did fill the entire column,
12453 because, in this case the deletion might narrow the column."
12454 (interactive "p")
12455 (if (and (org-table-p)
12456 (not (bolp))
12457 (not (= (char-after) ?|))
12458 (eq N 1))
12459 (if (looking-at ".*?|")
12460 (let ((pos (point))
12461 (noalign (looking-at "[^|\n\r]* |"))
12462 (c org-table-may-need-update))
12463 (replace-match (concat
12464 (substring (match-string 0) 1 -1)
12465 " |"))
12466 (goto-char pos)
12467 ;; noalign: if there were two spaces at the end, this field
12468 ;; does not determine the width of the column.
12469 (if noalign (setq org-table-may-need-update c)))
12470 (delete-char N))
12471 (delete-char N)
12472 (org-fix-tags-on-the-fly)))
12474 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12475 (put 'org-self-insert-command 'delete-selection t)
12476 (put 'orgtbl-self-insert-command 'delete-selection t)
12477 (put 'org-delete-char 'delete-selection 'supersede)
12478 (put 'org-delete-backward-char 'delete-selection 'supersede)
12480 ;; Make `flyspell-mode' delay after some commands
12481 (put 'org-self-insert-command 'flyspell-delayed t)
12482 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12483 (put 'org-delete-char 'flyspell-delayed t)
12484 (put 'org-delete-backward-char 'flyspell-delayed t)
12486 ;; Make pabbrev-mode expand after org-mode commands
12487 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12488 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12490 ;; How to do this: Measure non-white length of current string
12491 ;; If equal to column width, we should realign.
12493 (defun org-remap (map &rest commands)
12494 "In MAP, remap the functions given in COMMANDS.
12495 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12496 (let (new old)
12497 (while commands
12498 (setq old (pop commands) new (pop commands))
12499 (if (fboundp 'command-remapping)
12500 (org-defkey map (vector 'remap old) new)
12501 (substitute-key-definition old new map global-map)))))
12503 (when (eq org-enable-table-editor 'optimized)
12504 ;; If the user wants maximum table support, we need to hijack
12505 ;; some standard editing functions
12506 (org-remap org-mode-map
12507 'self-insert-command 'org-self-insert-command
12508 'delete-char 'org-delete-char
12509 'delete-backward-char 'org-delete-backward-char)
12510 (org-defkey org-mode-map "|" 'org-force-self-insert))
12512 (defun org-shiftcursor-error ()
12513 "Throw an error because Shift-Cursor command was applied in wrong context."
12514 (error "This command is active in special context like tables, headlines or timestamps"))
12516 (defun org-shifttab (&optional arg)
12517 "Global visibility cycling or move to previous table field.
12518 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12519 on context.
12520 See the individual commands for more information."
12521 (interactive "P")
12522 (cond
12523 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12524 ((integerp arg)
12525 (message "Content view to level: %d" arg)
12526 (org-content (prefix-numeric-value arg))
12527 (setq org-cycle-global-status 'overview))
12528 (t (call-interactively 'org-global-cycle))))
12530 (defun org-shiftmetaleft ()
12531 "Promote subtree or delete table column.
12532 Calls `org-promote-subtree', `org-outdent-item',
12533 or `org-table-delete-column', depending on context.
12534 See the individual commands for more information."
12535 (interactive)
12536 (cond
12537 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12538 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12539 ((org-at-item-p) (call-interactively 'org-outdent-item))
12540 (t (org-shiftcursor-error))))
12542 (defun org-shiftmetaright ()
12543 "Demote subtree or insert table column.
12544 Calls `org-demote-subtree', `org-indent-item',
12545 or `org-table-insert-column', depending on context.
12546 See the individual commands for more information."
12547 (interactive)
12548 (cond
12549 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12550 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12551 ((org-at-item-p) (call-interactively 'org-indent-item))
12552 (t (org-shiftcursor-error))))
12554 (defun org-shiftmetaup (&optional arg)
12555 "Move subtree up or kill table row.
12556 Calls `org-move-subtree-up' or `org-table-kill-row' or
12557 `org-move-item-up' depending on context. See the individual commands
12558 for more information."
12559 (interactive "P")
12560 (cond
12561 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12562 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12563 ((org-at-item-p) (call-interactively 'org-move-item-up))
12564 (t (org-shiftcursor-error))))
12565 (defun org-shiftmetadown (&optional arg)
12566 "Move subtree down or insert table row.
12567 Calls `org-move-subtree-down' or `org-table-insert-row' or
12568 `org-move-item-down', depending on context. See the individual
12569 commands for more information."
12570 (interactive "P")
12571 (cond
12572 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12573 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12574 ((org-at-item-p) (call-interactively 'org-move-item-down))
12575 (t (org-shiftcursor-error))))
12577 (defun org-metaleft (&optional arg)
12578 "Promote heading or move table column to left.
12579 Calls `org-do-promote' or `org-table-move-column', depending on context.
12580 With no specific context, calls the Emacs default `backward-word'.
12581 See the individual commands for more information."
12582 (interactive "P")
12583 (cond
12584 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12585 ((or (org-on-heading-p) (org-region-active-p))
12586 (call-interactively 'org-do-promote))
12587 ((org-at-item-p) (call-interactively 'org-outdent-item))
12588 (t (call-interactively 'backward-word))))
12590 (defun org-metaright (&optional arg)
12591 "Demote subtree or move table column to right.
12592 Calls `org-do-demote' or `org-table-move-column', depending on context.
12593 With no specific context, calls the Emacs default `forward-word'.
12594 See the individual commands for more information."
12595 (interactive "P")
12596 (cond
12597 ((org-at-table-p) (call-interactively 'org-table-move-column))
12598 ((or (org-on-heading-p) (org-region-active-p))
12599 (call-interactively 'org-do-demote))
12600 ((org-at-item-p) (call-interactively 'org-indent-item))
12601 (t (call-interactively 'forward-word))))
12603 (defun org-metaup (&optional arg)
12604 "Move subtree up or move table row up.
12605 Calls `org-move-subtree-up' or `org-table-move-row' or
12606 `org-move-item-up', depending on context. See the individual commands
12607 for more information."
12608 (interactive "P")
12609 (cond
12610 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12611 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12612 ((org-at-item-p) (call-interactively 'org-move-item-up))
12613 (t (transpose-lines 1) (beginning-of-line -1))))
12615 (defun org-metadown (&optional arg)
12616 "Move subtree down or move table row down.
12617 Calls `org-move-subtree-down' or `org-table-move-row' or
12618 `org-move-item-down', depending on context. See the individual
12619 commands for more information."
12620 (interactive "P")
12621 (cond
12622 ((org-at-table-p) (call-interactively 'org-table-move-row))
12623 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12624 ((org-at-item-p) (call-interactively 'org-move-item-down))
12625 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12627 (defun org-shiftup (&optional arg)
12628 "Increase item in timestamp or increase priority of current headline.
12629 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12630 depending on context. See the individual commands for more information."
12631 (interactive "P")
12632 (cond
12633 ((org-at-timestamp-p t)
12634 (call-interactively (if org-edit-timestamp-down-means-later
12635 'org-timestamp-down 'org-timestamp-up)))
12636 ((org-on-heading-p) (call-interactively 'org-priority-up))
12637 ((org-at-item-p) (call-interactively 'org-previous-item))
12638 ((org-clocktable-try-shift 'up arg))
12639 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12641 (defun org-shiftdown (&optional arg)
12642 "Decrease item in timestamp or decrease priority of current headline.
12643 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12644 depending on context. See the individual commands for more information."
12645 (interactive "P")
12646 (cond
12647 ((org-at-timestamp-p t)
12648 (call-interactively (if org-edit-timestamp-down-means-later
12649 'org-timestamp-up 'org-timestamp-down)))
12650 ((org-on-heading-p) (call-interactively 'org-priority-down))
12651 ((org-clocktable-try-shift 'down arg))
12652 (t (call-interactively 'org-next-item))))
12654 (defun org-shiftright (&optional arg)
12655 "Next TODO keyword or timestamp one day later, depending on context."
12656 (interactive "P")
12657 (cond
12658 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12659 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12660 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12661 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12662 ((org-clocktable-try-shift 'right arg))
12663 (t (org-shiftcursor-error))))
12665 (defun org-shiftleft (&optional arg)
12666 "Previous TODO keyword or timestamp one day earlier, depending on context."
12667 (interactive "P")
12668 (cond
12669 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12670 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12671 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12672 ((org-at-property-p)
12673 (call-interactively 'org-property-previous-allowed-value))
12674 ((org-clocktable-try-shift 'left arg))
12675 (t (org-shiftcursor-error))))
12677 (defun org-shiftcontrolright ()
12678 "Switch to next TODO set."
12679 (interactive)
12680 (cond
12681 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12682 (t (org-shiftcursor-error))))
12684 (defun org-shiftcontrolleft ()
12685 "Switch to previous TODO set."
12686 (interactive)
12687 (cond
12688 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12689 (t (org-shiftcursor-error))))
12691 (defun org-ctrl-c-ret ()
12692 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12693 (interactive)
12694 (cond
12695 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12696 (t (call-interactively 'org-insert-heading))))
12698 (defun org-copy-special ()
12699 "Copy region in table or copy current subtree.
12700 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12701 See the individual commands for more information."
12702 (interactive)
12703 (call-interactively
12704 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12706 (defun org-cut-special ()
12707 "Cut region in table or cut current subtree.
12708 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12709 See the individual commands for more information."
12710 (interactive)
12711 (call-interactively
12712 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12714 (defun org-paste-special (arg)
12715 "Paste rectangular region into table, or past subtree relative to level.
12716 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12717 See the individual commands for more information."
12718 (interactive "P")
12719 (if (org-at-table-p)
12720 (org-table-paste-rectangle)
12721 (org-paste-subtree arg)))
12723 (defun org-edit-special ()
12724 "Call a special editor for the stuff at point.
12725 When at a table, call the formula editor with `org-table-edit-formulas'.
12726 When at the first line of an src example, call `org-edit-src-code'.
12727 When in an #+include line, visit the include file. Otherwise call
12728 `ffap' to visit the file at point."
12729 (interactive)
12730 (cond
12731 ((org-at-table-p)
12732 (call-interactively 'org-table-edit-formulas))
12733 ((save-excursion
12734 (beginning-of-line 1)
12735 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12736 (find-file (org-trim (match-string 1))))
12737 ((org-edit-src-code))
12738 (t (call-interactively 'ffap))))
12740 (defun org-ctrl-c-ctrl-c (&optional arg)
12741 "Set tags in headline, or update according to changed information at point.
12743 This command does many different things, depending on context:
12745 - If the cursor is in a headline, prompt for tags and insert them
12746 into the current line, aligned to `org-tags-column'. When called
12747 with prefix arg, realign all tags in the current buffer.
12749 - If the cursor is in one of the special #+KEYWORD lines, this
12750 triggers scanning the buffer for these lines and updating the
12751 information.
12753 - If the cursor is inside a table, realign the table. This command
12754 works even if the automatic table editor has been turned off.
12756 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12757 the entire table.
12759 - If the cursor is a the beginning of a dynamic block, update it.
12761 - If the cursor is inside a table created by the table.el package,
12762 activate that table.
12764 - If the current buffer is a remember buffer, close note and file it.
12765 with a prefix argument, file it without further interaction to the default
12766 location.
12768 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12769 links in this buffer.
12771 - If the cursor is on a numbered item in a plain list, renumber the
12772 ordered list.
12774 - If the cursor is on a checkbox, toggle it."
12775 (interactive "P")
12776 (let ((org-enable-table-editor t))
12777 (cond
12778 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12779 org-occur-highlights
12780 org-latex-fragment-image-overlays)
12781 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12782 (org-remove-occur-highlights)
12783 (org-remove-latex-fragment-image-overlays)
12784 (message "Temporary highlights/overlays removed from current buffer"))
12785 ((and (local-variable-p 'org-finish-function (current-buffer))
12786 (fboundp org-finish-function))
12787 (funcall org-finish-function))
12788 ((org-at-property-p)
12789 (call-interactively 'org-property-action))
12790 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12791 ((org-on-heading-p) (call-interactively 'org-set-tags))
12792 ((org-at-table.el-p)
12793 (require 'table)
12794 (beginning-of-line 1)
12795 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12796 (call-interactively 'table-recognize-table))
12797 ((org-at-table-p)
12798 (org-table-maybe-eval-formula)
12799 (if arg
12800 (call-interactively 'org-table-recalculate)
12801 (org-table-maybe-recalculate-line))
12802 (call-interactively 'org-table-align))
12803 ((org-at-item-checkbox-p)
12804 (call-interactively 'org-toggle-checkbox))
12805 ((org-at-item-p)
12806 (call-interactively 'org-maybe-renumber-ordered-list))
12807 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12808 ;; Dynamic block
12809 (beginning-of-line 1)
12810 (org-update-dblock))
12811 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12812 (cond
12813 ((equal (match-string 1) "TBLFM")
12814 ;; Recalculate the table before this line
12815 (save-excursion
12816 (beginning-of-line 1)
12817 (skip-chars-backward " \r\n\t")
12818 (if (org-at-table-p)
12819 (org-call-with-arg 'org-table-recalculate t))))
12821 ; (org-set-regexps-and-options)
12822 ; (org-restart-font-lock)
12823 (let ((org-inhibit-startup t)) (org-mode-restart))
12824 (message "Local setup has been refreshed"))))
12825 (t (error "C-c C-c can do nothing useful at this location.")))))
12827 (defun org-mode-restart ()
12828 "Restart Org-mode, to scan again for special lines.
12829 Also updates the keyword regular expressions."
12830 (interactive)
12831 (org-mode)
12832 (message "Org-mode restarted"))
12834 (defun org-kill-note-or-show-branches ()
12835 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12836 (interactive)
12837 (if (not org-finish-function)
12838 (call-interactively 'show-branches)
12839 (let ((org-note-abort t))
12840 (funcall org-finish-function))))
12842 (defun org-return (&optional indent)
12843 "Goto next table row or insert a newline.
12844 Calls `org-table-next-row' or `newline', depending on context.
12845 See the individual commands for more information."
12846 (interactive)
12847 (cond
12848 ((bobp) (if indent (newline-and-indent) (newline)))
12849 ((and (org-at-heading-p)
12850 (looking-at
12851 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12852 (org-show-entry)
12853 (end-of-line 1)
12854 (newline))
12855 ((org-at-table-p)
12856 (org-table-justify-field-maybe)
12857 (call-interactively 'org-table-next-row))
12858 (t (if indent (newline-and-indent) (newline)))))
12860 (defun org-return-indent ()
12861 "Goto next table row or insert a newline and indent.
12862 Calls `org-table-next-row' or `newline-and-indent', depending on
12863 context. See the individual commands for more information."
12864 (interactive)
12865 (org-return t))
12867 (defun org-ctrl-c-star ()
12868 "Compute table, or change heading status of lines.
12869 Calls `org-table-recalculate' or `org-toggle-region-headings',
12870 depending on context. This will also turn a plain list item or a normal
12871 line into a subheading."
12872 (interactive)
12873 (cond
12874 ((org-at-table-p)
12875 (call-interactively 'org-table-recalculate))
12876 ((org-region-active-p)
12877 ;; Convert all lines in region to list items
12878 (call-interactively 'org-toggle-region-headings))
12879 ((org-on-heading-p)
12880 (org-toggle-region-headings (point-at-bol)
12881 (min (1+ (point-at-eol)) (point-max))))
12882 ((org-at-item-p)
12883 ;; Convert to heading
12884 (let ((level (save-match-data
12885 (save-excursion
12886 (condition-case nil
12887 (progn
12888 (org-back-to-heading t)
12889 (funcall outline-level))
12890 (error 0))))))
12891 (replace-match
12892 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12893 (t (org-toggle-region-headings (point-at-bol)
12894 (min (1+ (point-at-eol)) (point-max))))))
12896 (defun org-ctrl-c-minus ()
12897 "Insert separator line in table or modify bullet status of line.
12898 Also turns a plain line or a region of lines into list items.
12899 Calls `org-table-insert-hline', `org-toggle-region-items', or
12900 `org-cycle-list-bullet', depending on context."
12901 (interactive)
12902 (cond
12903 ((org-at-table-p)
12904 (call-interactively 'org-table-insert-hline))
12905 ((org-on-heading-p)
12906 ;; Convert to item
12907 (save-excursion
12908 (beginning-of-line 1)
12909 (if (looking-at "\\*+ ")
12910 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12911 ((org-region-active-p)
12912 ;; Convert all lines in region to list items
12913 (call-interactively 'org-toggle-region-items))
12914 ((org-in-item-p)
12915 (call-interactively 'org-cycle-list-bullet))
12916 (t (org-toggle-region-items (point-at-bol)
12917 (min (1+ (point-at-eol)) (point-max))))))
12919 (defun org-toggle-region-items (beg end)
12920 "Convert all lines in region to list items.
12921 If the first line is already an item, convert all list items in the region
12922 to normal lines."
12923 (interactive "r")
12924 (let (l2 l)
12925 (save-excursion
12926 (goto-char end)
12927 (setq l2 (org-current-line))
12928 (goto-char beg)
12929 (beginning-of-line 1)
12930 (setq l (1- (org-current-line)))
12931 (if (org-at-item-p)
12932 ;; We already have items, de-itemize
12933 (while (< (setq l (1+ l)) l2)
12934 (when (org-at-item-p)
12935 (goto-char (match-beginning 2))
12936 (delete-region (match-beginning 2) (match-end 2))
12937 (and (looking-at "[ \t]+") (replace-match "")))
12938 (beginning-of-line 2))
12939 (while (< (setq l (1+ l)) l2)
12940 (unless (org-at-item-p)
12941 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12942 (replace-match "\\1- \\2")))
12943 (beginning-of-line 2))))))
12945 (defun org-toggle-region-headings (beg end)
12946 "Convert all lines in region to list items.
12947 If the first line is already an item, convert all list items in the region
12948 to normal lines."
12949 (interactive "r")
12950 (let (l2 l)
12951 (save-excursion
12952 (goto-char end)
12953 (setq l2 (org-current-line))
12954 (goto-char beg)
12955 (beginning-of-line 1)
12956 (setq l (1- (org-current-line)))
12957 (if (org-on-heading-p)
12958 ;; We already have headlines, de-star them
12959 (while (< (setq l (1+ l)) l2)
12960 (when (org-on-heading-p t)
12961 (and (looking-at outline-regexp) (replace-match "")))
12962 (beginning-of-line 2))
12963 (let* ((stars (save-excursion
12964 (re-search-backward org-complex-heading-regexp nil t)
12965 (or (match-string 1) "*")))
12966 (add-stars (if org-odd-levels-only "**" "*"))
12967 (rpl (concat stars add-stars " \\2")))
12968 (while (< (setq l (1+ l)) l2)
12969 (unless (org-on-heading-p)
12970 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12971 (replace-match rpl)))
12972 (beginning-of-line 2)))))))
12974 (defun org-meta-return (&optional arg)
12975 "Insert a new heading or wrap a region in a table.
12976 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12977 See the individual commands for more information."
12978 (interactive "P")
12979 (cond
12980 ((org-at-table-p)
12981 (call-interactively 'org-table-wrap-region))
12982 (t (call-interactively 'org-insert-heading))))
12984 ;;; Menu entries
12986 ;; Define the Org-mode menus
12987 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12988 '("Tbl"
12989 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12990 ["Next Field" org-cycle (org-at-table-p)]
12991 ["Previous Field" org-shifttab (org-at-table-p)]
12992 ["Next Row" org-return (org-at-table-p)]
12993 "--"
12994 ["Blank Field" org-table-blank-field (org-at-table-p)]
12995 ["Edit Field" org-table-edit-field (org-at-table-p)]
12996 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12997 "--"
12998 ("Column"
12999 ["Move Column Left" org-metaleft (org-at-table-p)]
13000 ["Move Column Right" org-metaright (org-at-table-p)]
13001 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13002 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13003 ("Row"
13004 ["Move Row Up" org-metaup (org-at-table-p)]
13005 ["Move Row Down" org-metadown (org-at-table-p)]
13006 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13007 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13008 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13009 "--"
13010 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13011 ("Rectangle"
13012 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13013 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13014 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13015 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13016 "--"
13017 ("Calculate"
13018 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13019 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13020 ["Edit Formulas" org-edit-special (org-at-table-p)]
13021 "--"
13022 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13023 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13024 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13025 "--"
13026 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13027 "--"
13028 ["Sum Column/Rectangle" org-table-sum
13029 (or (org-at-table-p) (org-region-active-p))]
13030 ["Which Column?" org-table-current-column (org-at-table-p)])
13031 ["Debug Formulas"
13032 org-table-toggle-formula-debugger
13033 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13034 ["Show Col/Row Numbers"
13035 org-table-toggle-coordinate-overlays
13036 :style toggle
13037 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13038 "--"
13039 ["Create" org-table-create (and (not (org-at-table-p))
13040 org-enable-table-editor)]
13041 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13042 ["Import from File" org-table-import (not (org-at-table-p))]
13043 ["Export to File" org-table-export (org-at-table-p)]
13044 "--"
13045 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13047 (easy-menu-define org-org-menu org-mode-map "Org menu"
13048 '("Org"
13049 ("Show/Hide"
13050 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13051 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13052 ["Sparse Tree..." org-sparse-tree t]
13053 ["Reveal Context" org-reveal t]
13054 ["Show All" show-all t]
13055 "--"
13056 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13057 "--"
13058 ["New Heading" org-insert-heading t]
13059 ("Navigate Headings"
13060 ["Up" outline-up-heading t]
13061 ["Next" outline-next-visible-heading t]
13062 ["Previous" outline-previous-visible-heading t]
13063 ["Next Same Level" outline-forward-same-level t]
13064 ["Previous Same Level" outline-backward-same-level t]
13065 "--"
13066 ["Jump" org-goto t])
13067 ("Edit Structure"
13068 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13069 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13070 "--"
13071 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13072 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13073 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13074 "--"
13075 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13076 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13077 ["Demote Heading" org-metaright (not (org-at-table-p))]
13078 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13079 "--"
13080 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13081 "--"
13082 ["Convert to odd levels" org-convert-to-odd-levels t]
13083 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13084 ("Editing"
13085 ["Emphasis..." org-emphasize t]
13086 ["Edit Source Example" org-edit-special t])
13087 ("Archive"
13088 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13089 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13090 ; :active t :keys "C-u C-c C-x C-a"]
13091 ["Sparse trees open ARCHIVE trees"
13092 (setq org-sparse-tree-open-archived-trees
13093 (not org-sparse-tree-open-archived-trees))
13094 :style toggle :selected org-sparse-tree-open-archived-trees]
13095 ["Cycling opens ARCHIVE trees"
13096 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13097 :style toggle :selected org-cycle-open-archived-trees]
13098 ["Agenda includes ARCHIVE trees"
13099 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
13100 :style toggle :selected (not org-agenda-skip-archived-trees)]
13101 "--"
13102 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13103 ; ["Check and Move Children" (org-archive-subtree '(4))
13104 ; :active t :keys "C-u C-c C-x C-s"]
13106 "--"
13107 ("TODO Lists"
13108 ["TODO/DONE/-" org-todo t]
13109 ("Select keyword"
13110 ["Next keyword" org-shiftright (org-on-heading-p)]
13111 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13112 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13113 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13114 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13115 ["Show TODO Tree" org-show-todo-tree t]
13116 ["Global TODO list" org-todo-list t]
13117 "--"
13118 ["Set Priority" org-priority t]
13119 ["Priority Up" org-shiftup t]
13120 ["Priority Down" org-shiftdown t])
13121 ("TAGS and Properties"
13122 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13123 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13124 "--"
13125 ["Set property" 'org-set-property t]
13126 ["Column view of properties" org-columns t]
13127 ["Insert Column View DBlock" org-insert-columns-dblock t])
13128 ("Dates and Scheduling"
13129 ["Timestamp" org-time-stamp t]
13130 ["Timestamp (inactive)" org-time-stamp-inactive t]
13131 ("Change Date"
13132 ["1 Day Later" org-shiftright t]
13133 ["1 Day Earlier" org-shiftleft t]
13134 ["1 ... Later" org-shiftup t]
13135 ["1 ... Earlier" org-shiftdown t])
13136 ["Compute Time Range" org-evaluate-time-range t]
13137 ["Schedule Item" org-schedule t]
13138 ["Deadline" org-deadline t]
13139 "--"
13140 ["Custom time format" org-toggle-time-stamp-overlays
13141 :style radio :selected org-display-custom-times]
13142 "--"
13143 ["Goto Calendar" org-goto-calendar t]
13144 ["Date from Calendar" org-date-from-calendar t])
13145 ("Logging work"
13146 ["Clock in" org-clock-in t]
13147 ["Clock out" org-clock-out t]
13148 ["Clock cancel" org-clock-cancel t]
13149 ["Goto running clock" org-clock-goto t]
13150 ["Display times" org-clock-display t]
13151 ["Create clock table" org-clock-report t]
13152 "--"
13153 ["Record DONE time"
13154 (progn (setq org-log-done (not org-log-done))
13155 (message "Switching to %s will %s record a timestamp"
13156 (car org-done-keywords)
13157 (if org-log-done "automatically" "not")))
13158 :style toggle :selected org-log-done])
13159 "--"
13160 ["Agenda Command..." org-agenda t]
13161 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13162 ("File List for Agenda")
13163 ("Special views current file"
13164 ["TODO Tree" org-show-todo-tree t]
13165 ["Check Deadlines" org-check-deadlines t]
13166 ["Timeline" org-timeline t]
13167 ["Tags Tree" org-tags-sparse-tree t])
13168 "--"
13169 ("Hyperlinks"
13170 ["Store Link (Global)" org-store-link t]
13171 ["Insert Link" org-insert-link t]
13172 ["Follow Link" org-open-at-point t]
13173 "--"
13174 ["Next link" org-next-link t]
13175 ["Previous link" org-previous-link t]
13176 "--"
13177 ["Descriptive Links"
13178 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13179 :style radio
13180 :selected (member '(org-link) buffer-invisibility-spec)]
13181 ["Literal Links"
13182 (progn
13183 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13184 :style radio
13185 :selected (not (member '(org-link) buffer-invisibility-spec))])
13186 "--"
13187 ["Export/Publish..." org-export t]
13188 ("LaTeX"
13189 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13190 :selected org-cdlatex-mode]
13191 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13192 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13193 ["Modify math symbol" org-cdlatex-math-modify
13194 (org-inside-LaTeX-fragment-p)]
13195 ["Export LaTeX fragments as images"
13196 (if (featurep 'org-exp)
13197 (setq org-export-with-LaTeX-fragments
13198 (not org-export-with-LaTeX-fragments))
13199 (require 'org-exp))
13200 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13201 org-export-with-LaTeX-fragments)])
13202 "--"
13203 ("Documentation"
13204 ["Show Version" org-version t]
13205 ["Info Documentation" org-info t])
13206 ("Customize"
13207 ["Browse Org Group" org-customize t]
13208 "--"
13209 ["Expand This Menu" org-create-customize-menu
13210 (fboundp 'customize-menu-create)])
13211 "--"
13212 ["Refresh setup" org-mode-restart t]
13215 (defun org-info (&optional node)
13216 "Read documentation for Org-mode in the info system.
13217 With optional NODE, go directly to that node."
13218 (interactive)
13219 (info (format "(org)%s" (or node ""))))
13221 (defun org-install-agenda-files-menu ()
13222 (let ((bl (buffer-list)))
13223 (save-excursion
13224 (while bl
13225 (set-buffer (pop bl))
13226 (if (org-mode-p) (setq bl nil)))
13227 (when (org-mode-p)
13228 (easy-menu-change
13229 '("Org") "File List for Agenda"
13230 (append
13231 (list
13232 ["Edit File List" (org-edit-agenda-file-list) t]
13233 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13234 ["Remove Current File from List" org-remove-file t]
13235 ["Cycle through agenda files" org-cycle-agenda-files t]
13236 ["Occur in all agenda files" org-occur-in-agenda-files t]
13237 "--")
13238 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13240 ;;;; Documentation
13242 ;;;###autoload
13243 (defun org-require-autoloaded-modules ()
13244 (interactive)
13245 (mapc 'require
13246 '(org-agenda org-archive org-clock org-colview
13247 org-exp org-id org-export-latex org-publish
13248 org-remember org-table)))
13250 ;;;###autoload
13251 (defun org-customize ()
13252 "Call the customize function with org as argument."
13253 (interactive)
13254 (org-load-modules-maybe)
13255 (org-require-autoloaded-modules)
13256 (customize-browse 'org))
13258 (defun org-create-customize-menu ()
13259 "Create a full customization menu for Org-mode, insert it into the menu."
13260 (interactive)
13261 (org-load-modules-maybe)
13262 (org-require-autoloaded-modules)
13263 (if (fboundp 'customize-menu-create)
13264 (progn
13265 (easy-menu-change
13266 '("Org") "Customize"
13267 `(["Browse Org group" org-customize t]
13268 "--"
13269 ,(customize-menu-create 'org)
13270 ["Set" Custom-set t]
13271 ["Save" Custom-save t]
13272 ["Reset to Current" Custom-reset-current t]
13273 ["Reset to Saved" Custom-reset-saved t]
13274 ["Reset to Standard Settings" Custom-reset-standard t]))
13275 (message "\"Org\"-menu now contains full customization menu"))
13276 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13278 ;;;; Miscellaneous stuff
13280 ;;; Generally useful functions
13282 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13283 "Display the given MESSAGE as a warning."
13284 (if (fboundp 'display-warning)
13285 (display-warning 'org message
13286 (if (featurep 'xemacs)
13287 'warning
13288 :warning))
13289 (let ((buf (get-buffer-create "*Org warnings*")))
13290 (with-current-buffer buf
13291 (goto-char (point-max))
13292 (insert "Warning (Org): " message)
13293 (unless (bolp)
13294 (newline)))
13295 (display-buffer buf)
13296 (sit-for 0))))
13298 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13299 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13300 (if (and marker (marker-buffer marker)
13301 (buffer-live-p (marker-buffer marker)))
13302 (progn
13303 (switch-to-buffer (marker-buffer marker))
13304 (if (or (> marker (point-max)) (< marker (point-min)))
13305 (widen))
13306 (goto-char marker))
13307 (if bookmark
13308 (bookmark-jump bookmark)
13309 (error "Cannot find location"))))
13311 (defun org-quote-csv-field (s)
13312 "Quote field for inclusion in CSV material."
13313 (if (string-match "[\",]" s)
13314 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13317 (defun org-plist-delete (plist property)
13318 "Delete PROPERTY from PLIST.
13319 This is in contrast to merely setting it to 0."
13320 (let (p)
13321 (while plist
13322 (if (not (eq property (car plist)))
13323 (setq p (plist-put p (car plist) (nth 1 plist))))
13324 (setq plist (cddr plist)))
13327 (defun org-force-self-insert (N)
13328 "Needed to enforce self-insert under remapping."
13329 (interactive "p")
13330 (self-insert-command N))
13332 (defun org-string-width (s)
13333 "Compute width of string, ignoring invisible characters.
13334 This ignores character with invisibility property `org-link', and also
13335 characters with property `org-cwidth', because these will become invisible
13336 upon the next fontification round."
13337 (let (b l)
13338 (when (or (eq t buffer-invisibility-spec)
13339 (assq 'org-link buffer-invisibility-spec))
13340 (while (setq b (text-property-any 0 (length s)
13341 'invisible 'org-link s))
13342 (setq s (concat (substring s 0 b)
13343 (substring s (or (next-single-property-change
13344 b 'invisible s) (length s)))))))
13345 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13346 (setq s (concat (substring s 0 b)
13347 (substring s (or (next-single-property-change
13348 b 'org-cwidth s) (length s))))))
13349 (setq l (string-width s) b -1)
13350 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13351 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13354 (defun org-base-buffer (buffer)
13355 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13356 (if (not buffer)
13357 buffer
13358 (or (buffer-base-buffer buffer)
13359 buffer)))
13361 (defun org-trim (s)
13362 "Remove whitespace at beginning and end of string."
13363 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13364 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13367 (defun org-wrap (string &optional width lines)
13368 "Wrap string to either a number of lines, or a width in characters.
13369 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13370 that costs. If there is a word longer than WIDTH, the text is actually
13371 wrapped to the length of that word.
13372 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13373 many lines, whatever width that takes.
13374 The return value is a list of lines, without newlines at the end."
13375 (let* ((words (org-split-string string "[ \t\n]+"))
13376 (maxword (apply 'max (mapcar 'org-string-width words)))
13377 w ll)
13378 (cond (width
13379 (org-do-wrap words (max maxword width)))
13380 (lines
13381 (setq w maxword)
13382 (setq ll (org-do-wrap words maxword))
13383 (if (<= (length ll) lines)
13385 (setq ll words)
13386 (while (> (length ll) lines)
13387 (setq w (1+ w))
13388 (setq ll (org-do-wrap words w)))
13389 ll))
13390 (t (error "Cannot wrap this")))))
13392 (defun org-do-wrap (words width)
13393 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13394 (let (lines line)
13395 (while words
13396 (setq line (pop words))
13397 (while (and words (< (+ (length line) (length (car words))) width))
13398 (setq line (concat line " " (pop words))))
13399 (setq lines (push line lines)))
13400 (nreverse lines)))
13402 (defun org-split-string (string &optional separators)
13403 "Splits STRING into substrings at SEPARATORS.
13404 No empty strings are returned if there are matches at the beginning
13405 and end of string."
13406 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13407 (start 0)
13408 notfirst
13409 (list nil))
13410 (while (and (string-match rexp string
13411 (if (and notfirst
13412 (= start (match-beginning 0))
13413 (< start (length string)))
13414 (1+ start) start))
13415 (< (match-beginning 0) (length string)))
13416 (setq notfirst t)
13417 (or (eq (match-beginning 0) 0)
13418 (and (eq (match-beginning 0) (match-end 0))
13419 (eq (match-beginning 0) start))
13420 (setq list
13421 (cons (substring string start (match-beginning 0))
13422 list)))
13423 (setq start (match-end 0)))
13424 (or (eq start (length string))
13425 (setq list
13426 (cons (substring string start)
13427 list)))
13428 (nreverse list)))
13430 (defun org-context ()
13431 "Return a list of contexts of the current cursor position.
13432 If several contexts apply, all are returned.
13433 Each context entry is a list with a symbol naming the context, and
13434 two positions indicating start and end of the context. Possible
13435 contexts are:
13437 :headline anywhere in a headline
13438 :headline-stars on the leading stars in a headline
13439 :todo-keyword on a TODO keyword (including DONE) in a headline
13440 :tags on the TAGS in a headline
13441 :priority on the priority cookie in a headline
13442 :item on the first line of a plain list item
13443 :item-bullet on the bullet/number of a plain list item
13444 :checkbox on the checkbox in a plain list item
13445 :table in an org-mode table
13446 :table-special on a special filed in a table
13447 :table-table in a table.el table
13448 :link on a hyperlink
13449 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13450 :target on a <<target>>
13451 :radio-target on a <<<radio-target>>>
13452 :latex-fragment on a LaTeX fragment
13453 :latex-preview on a LaTeX fragment with overlayed preview image
13455 This function expects the position to be visible because it uses font-lock
13456 faces as a help to recognize the following contexts: :table-special, :link,
13457 and :keyword."
13458 (let* ((f (get-text-property (point) 'face))
13459 (faces (if (listp f) f (list f)))
13460 (p (point)) clist o)
13461 ;; First the large context
13462 (cond
13463 ((org-on-heading-p t)
13464 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13465 (when (progn
13466 (beginning-of-line 1)
13467 (looking-at org-todo-line-tags-regexp))
13468 (push (org-point-in-group p 1 :headline-stars) clist)
13469 (push (org-point-in-group p 2 :todo-keyword) clist)
13470 (push (org-point-in-group p 4 :tags) clist))
13471 (goto-char p)
13472 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13473 (if (looking-at "\\[#[A-Z0-9]\\]")
13474 (push (org-point-in-group p 0 :priority) clist)))
13476 ((org-at-item-p)
13477 (push (org-point-in-group p 2 :item-bullet) clist)
13478 (push (list :item (point-at-bol)
13479 (save-excursion (org-end-of-item) (point)))
13480 clist)
13481 (and (org-at-item-checkbox-p)
13482 (push (org-point-in-group p 0 :checkbox) clist)))
13484 ((org-at-table-p)
13485 (push (list :table (org-table-begin) (org-table-end)) clist)
13486 (if (memq 'org-formula faces)
13487 (push (list :table-special
13488 (previous-single-property-change p 'face)
13489 (next-single-property-change p 'face)) clist)))
13490 ((org-at-table-p 'any)
13491 (push (list :table-table) clist)))
13492 (goto-char p)
13494 ;; Now the small context
13495 (cond
13496 ((org-at-timestamp-p)
13497 (push (org-point-in-group p 0 :timestamp) clist))
13498 ((memq 'org-link faces)
13499 (push (list :link
13500 (previous-single-property-change p 'face)
13501 (next-single-property-change p 'face)) clist))
13502 ((memq 'org-special-keyword faces)
13503 (push (list :keyword
13504 (previous-single-property-change p 'face)
13505 (next-single-property-change p 'face)) clist))
13506 ((org-on-target-p)
13507 (push (org-point-in-group p 0 :target) clist)
13508 (goto-char (1- (match-beginning 0)))
13509 (if (looking-at org-radio-target-regexp)
13510 (push (org-point-in-group p 0 :radio-target) clist))
13511 (goto-char p))
13512 ((setq o (car (delq nil
13513 (mapcar
13514 (lambda (x)
13515 (if (memq x org-latex-fragment-image-overlays) x))
13516 (org-overlays-at (point))))))
13517 (push (list :latex-fragment
13518 (org-overlay-start o) (org-overlay-end o)) clist)
13519 (push (list :latex-preview
13520 (org-overlay-start o) (org-overlay-end o)) clist))
13521 ((org-inside-LaTeX-fragment-p)
13522 ;; FIXME: positions wrong.
13523 (push (list :latex-fragment (point) (point)) clist)))
13525 (setq clist (nreverse (delq nil clist)))
13526 clist))
13528 ;; FIXME: Compare with at-regexp-p Do we need both?
13529 (defun org-in-regexp (re &optional nlines visually)
13530 "Check if point is inside a match of regexp.
13531 Normally only the current line is checked, but you can include NLINES extra
13532 lines both before and after point into the search.
13533 If VISUALLY is set, require that the cursor is not after the match but
13534 really on, so that the block visually is on the match."
13535 (catch 'exit
13536 (let ((pos (point))
13537 (eol (point-at-eol (+ 1 (or nlines 0))))
13538 (inc (if visually 1 0)))
13539 (save-excursion
13540 (beginning-of-line (- 1 (or nlines 0)))
13541 (while (re-search-forward re eol t)
13542 (if (and (<= (match-beginning 0) pos)
13543 (>= (+ inc (match-end 0)) pos))
13544 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13546 (defun org-at-regexp-p (regexp)
13547 "Is point inside a match of REGEXP in the current line?"
13548 (catch 'exit
13549 (save-excursion
13550 (let ((pos (point)) (end (point-at-eol)))
13551 (beginning-of-line 1)
13552 (while (re-search-forward regexp end t)
13553 (if (and (<= (match-beginning 0) pos)
13554 (>= (match-end 0) pos))
13555 (throw 'exit t)))
13556 nil))))
13558 (defun org-occur-in-agenda-files (regexp &optional nlines)
13559 "Call `multi-occur' with buffers for all agenda files."
13560 (interactive "sOrg-files matching: \np")
13561 (let* ((files (org-agenda-files))
13562 (tnames (mapcar 'file-truename files))
13563 (extra org-agenda-text-search-extra-files)
13565 (when (eq (car extra) 'agenda-archives)
13566 (setq extra (cdr extra))
13567 (setq files (org-add-archive-files files)))
13568 (while (setq f (pop extra))
13569 (unless (member (file-truename f) tnames)
13570 (add-to-list 'files f 'append)
13571 (add-to-list 'tnames (file-truename f) 'append)))
13572 (multi-occur
13573 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13574 regexp)))
13576 (if (boundp 'occur-mode-find-occurrence-hook)
13577 ;; Emacs 23
13578 (add-hook 'occur-mode-find-occurrence-hook
13579 (lambda ()
13580 (when (org-mode-p)
13581 (org-reveal))))
13582 ;; Emacs 22
13583 (defadvice occur-mode-goto-occurrence
13584 (after org-occur-reveal activate)
13585 (and (org-mode-p) (org-reveal)))
13586 (defadvice occur-mode-goto-occurrence-other-window
13587 (after org-occur-reveal activate)
13588 (and (org-mode-p) (org-reveal)))
13589 (defadvice occur-mode-display-occurrence
13590 (after org-occur-reveal activate)
13591 (when (org-mode-p)
13592 (let ((pos (occur-mode-find-occurrence)))
13593 (with-current-buffer (marker-buffer pos)
13594 (save-excursion
13595 (goto-char pos)
13596 (org-reveal)))))))
13598 (defun org-uniquify (list)
13599 "Remove duplicate elements from LIST."
13600 (let (res)
13601 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13602 res))
13604 (defun org-delete-all (elts list)
13605 "Remove all elements in ELTS from LIST."
13606 (while elts
13607 (setq list (delete (pop elts) list)))
13608 list)
13610 (defun org-back-over-empty-lines ()
13611 "Move backwards over witespace, to the beginning of the first empty line.
13612 Returns the number of empty lines passed."
13613 (let ((pos (point)))
13614 (skip-chars-backward " \t\n\r")
13615 (beginning-of-line 2)
13616 (goto-char (min (point) pos))
13617 (count-lines (point) pos)))
13619 (defun org-skip-whitespace ()
13620 (skip-chars-forward " \t\n\r"))
13622 (defun org-point-in-group (point group &optional context)
13623 "Check if POINT is in match-group GROUP.
13624 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13625 match. If the match group does ot exist or point is not inside it,
13626 return nil."
13627 (and (match-beginning group)
13628 (>= point (match-beginning group))
13629 (<= point (match-end group))
13630 (if context
13631 (list context (match-beginning group) (match-end group))
13632 t)))
13634 (defun org-switch-to-buffer-other-window (&rest args)
13635 "Switch to buffer in a second window on the current frame.
13636 In particular, do not allow pop-up frames."
13637 (let (pop-up-frames special-display-buffer-names special-display-regexps
13638 special-display-function)
13639 (apply 'switch-to-buffer-other-window args)))
13641 (defun org-combine-plists (&rest plists)
13642 "Create a single property list from all plists in PLISTS.
13643 The process starts by copying the first list, and then setting properties
13644 from the other lists. Settings in the last list are the most significant
13645 ones and overrule settings in the other lists."
13646 (let ((rtn (copy-sequence (pop plists)))
13647 p v ls)
13648 (while plists
13649 (setq ls (pop plists))
13650 (while ls
13651 (setq p (pop ls) v (pop ls))
13652 (setq rtn (plist-put rtn p v))))
13653 rtn))
13655 (defun org-move-line-down (arg)
13656 "Move the current line down. With prefix argument, move it past ARG lines."
13657 (interactive "p")
13658 (let ((col (current-column))
13659 beg end pos)
13660 (beginning-of-line 1) (setq beg (point))
13661 (beginning-of-line 2) (setq end (point))
13662 (beginning-of-line (+ 1 arg))
13663 (setq pos (move-marker (make-marker) (point)))
13664 (insert (delete-and-extract-region beg end))
13665 (goto-char pos)
13666 (org-move-to-column col)))
13668 (defun org-move-line-up (arg)
13669 "Move the current line up. With prefix argument, move it past ARG lines."
13670 (interactive "p")
13671 (let ((col (current-column))
13672 beg end pos)
13673 (beginning-of-line 1) (setq beg (point))
13674 (beginning-of-line 2) (setq end (point))
13675 (beginning-of-line (- arg))
13676 (setq pos (move-marker (make-marker) (point)))
13677 (insert (delete-and-extract-region beg end))
13678 (goto-char pos)
13679 (org-move-to-column col)))
13681 (defun org-replace-escapes (string table)
13682 "Replace %-escapes in STRING with values in TABLE.
13683 TABLE is an association list with keys like \"%a\" and string values.
13684 The sequences in STRING may contain normal field width and padding information,
13685 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13686 so values can contain further %-escapes if they are define later in TABLE."
13687 (let ((case-fold-search nil)
13688 e re rpl)
13689 (while (setq e (pop table))
13690 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13691 (while (string-match re string)
13692 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13693 (cdr e)))
13694 (setq string (replace-match rpl t t string))))
13695 string))
13698 (defun org-sublist (list start end)
13699 "Return a section of LIST, from START to END.
13700 Counting starts at 1."
13701 (let (rtn (c start))
13702 (setq list (nthcdr (1- start) list))
13703 (while (and list (<= c end))
13704 (push (pop list) rtn)
13705 (setq c (1+ c)))
13706 (nreverse rtn)))
13708 (defun org-find-base-buffer-visiting (file)
13709 "Like `find-buffer-visiting' but alway return the base buffer and
13710 not an indirect buffer."
13711 (let ((buf (find-buffer-visiting file)))
13712 (if buf
13713 (or (buffer-base-buffer buf) buf)
13714 nil)))
13716 (defun org-image-file-name-regexp ()
13717 "Return regexp matching the file names of images."
13718 (if (fboundp 'image-file-name-regexp)
13719 (image-file-name-regexp)
13720 (let ((image-file-name-extensions
13721 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13722 "xbm" "xpm" "pbm" "pgm" "ppm")))
13723 (concat "\\."
13724 (regexp-opt (nconc (mapcar 'upcase
13725 image-file-name-extensions)
13726 image-file-name-extensions)
13728 "\\'"))))
13730 (defun org-file-image-p (file)
13731 "Return non-nil if FILE is an image."
13732 (save-match-data
13733 (string-match (org-image-file-name-regexp) file)))
13735 ;;; Paragraph filling stuff.
13736 ;; We want this to be just right, so use the full arsenal.
13738 (defun org-indent-line-function ()
13739 "Indent line like previous, but further if previous was headline or item."
13740 (interactive)
13741 (let* ((pos (point))
13742 (itemp (org-at-item-p))
13743 column bpos bcol tpos tcol bullet btype bullet-type)
13744 ;; Find the previous relevant line
13745 (beginning-of-line 1)
13746 (cond
13747 ((looking-at "#") (setq column 0))
13748 ((looking-at "\\*+ ") (setq column 0))
13750 (beginning-of-line 0)
13751 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13752 (beginning-of-line 0))
13753 (cond
13754 ((looking-at "\\*+[ \t]+")
13755 (if (not org-adapt-indentation)
13756 (setq column 0)
13757 (goto-char (match-end 0))
13758 (setq column (current-column))))
13759 ((org-in-item-p)
13760 (org-beginning-of-item)
13761 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13762 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13763 (setq bpos (match-beginning 1) tpos (match-end 0)
13764 bcol (progn (goto-char bpos) (current-column))
13765 tcol (progn (goto-char tpos) (current-column))
13766 bullet (match-string 1)
13767 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13768 (if (> tcol (+ bcol org-description-max-indent))
13769 (setq tcol (+ bcol 5)))
13770 (if (not itemp)
13771 (setq column tcol)
13772 (goto-char pos)
13773 (beginning-of-line 1)
13774 (if (looking-at "\\S-")
13775 (progn
13776 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13777 (setq bullet (match-string 1)
13778 btype (if (string-match "[0-9]" bullet) "n" bullet))
13779 (setq column (if (equal btype bullet-type) bcol tcol)))
13780 (setq column (org-get-indentation)))))
13781 (t (setq column (org-get-indentation))))))
13782 (goto-char pos)
13783 (if (<= (current-column) (current-indentation))
13784 (org-indent-line-to column)
13785 (save-excursion (org-indent-line-to column)))
13786 (setq column (current-column))
13787 (beginning-of-line 1)
13788 (if (looking-at
13789 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13790 (replace-match (concat "\\1" (format org-property-format
13791 (match-string 2) (match-string 3)))
13792 t nil))
13793 (org-move-to-column column)))
13795 (defun org-set-autofill-regexps ()
13796 (interactive)
13797 ;; In the paragraph separator we include headlines, because filling
13798 ;; text in a line directly attached to a headline would otherwise
13799 ;; fill the headline as well.
13800 (org-set-local 'comment-start-skip "^#+[ \t]*")
13801 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13802 ;; The paragraph starter includes hand-formatted lists.
13803 (org-set-local 'paragraph-start
13804 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13805 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13806 ;; But only if the user has not turned off tables or fixed-width regions
13807 (org-set-local
13808 'auto-fill-inhibit-regexp
13809 (concat "\\*+ \\|#\\+"
13810 "\\|[ \t]*" org-keyword-time-regexp
13811 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13812 (concat
13813 "\\|[ \t]*["
13814 (if org-enable-table-editor "|" "")
13815 (if org-enable-fixed-width-editor ":" "")
13816 "]"))))
13817 ;; We use our own fill-paragraph function, to make sure that tables
13818 ;; and fixed-width regions are not wrapped. That function will pass
13819 ;; through to `fill-paragraph' when appropriate.
13820 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13821 ; Adaptive filling: To get full control, first make sure that
13822 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13823 (org-set-local 'adaptive-fill-regexp "\000")
13824 (org-set-local 'adaptive-fill-function
13825 'org-adaptive-fill-function)
13826 (org-set-local
13827 'align-mode-rules-list
13828 '((org-in-buffer-settings
13829 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13830 (modes . '(org-mode))))))
13832 (defun org-fill-paragraph (&optional justify)
13833 "Re-align a table, pass through to fill-paragraph if no table."
13834 (let ((table-p (org-at-table-p))
13835 (table.el-p (org-at-table.el-p)))
13836 (cond ((and (equal (char-after (point-at-bol)) ?*)
13837 (save-excursion (goto-char (point-at-bol))
13838 (looking-at outline-regexp)))
13839 t) ; skip headlines
13840 (table.el-p t) ; skip table.el tables
13841 (table-p (org-table-align) t) ; align org-mode tables
13842 (t nil)))) ; call paragraph-fill
13844 ;; For reference, this is the default value of adaptive-fill-regexp
13845 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13847 (defun org-adaptive-fill-function ()
13848 "Return a fill prefix for org-mode files.
13849 In particular, this makes sure hanging paragraphs for hand-formatted lists
13850 work correctly."
13851 (cond ((looking-at "#[ \t]+")
13852 (match-string 0))
13853 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13854 (save-excursion
13855 (if (> (match-end 1) (+ (match-beginning 1)
13856 org-description-max-indent))
13857 (goto-char (+ (match-beginning 1) 5))
13858 (goto-char (match-end 0)))
13859 (make-string (current-column) ?\ )))
13860 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13861 (save-excursion
13862 (goto-char (match-end 0))
13863 (make-string (current-column) ?\ )))
13864 (t nil)))
13866 ;;; Other stuff.
13868 (defun org-toggle-fixed-width-section (arg)
13869 "Toggle the fixed-width export.
13870 If there is no active region, the QUOTE keyword at the current headline is
13871 inserted or removed. When present, it causes the text between this headline
13872 and the next to be exported as fixed-width text, and unmodified.
13873 If there is an active region, this command adds or removes a colon as the
13874 first character of this line. If the first character of a line is a colon,
13875 this line is also exported in fixed-width font."
13876 (interactive "P")
13877 (let* ((cc 0)
13878 (regionp (org-region-active-p))
13879 (beg (if regionp (region-beginning) (point)))
13880 (end (if regionp (region-end)))
13881 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13882 (case-fold-search nil)
13883 (re "[ \t]*\\(:\\)")
13884 off)
13885 (if regionp
13886 (save-excursion
13887 (goto-char beg)
13888 (setq cc (current-column))
13889 (beginning-of-line 1)
13890 (setq off (looking-at re))
13891 (while (> nlines 0)
13892 (setq nlines (1- nlines))
13893 (beginning-of-line 1)
13894 (cond
13895 (arg
13896 (org-move-to-column cc t)
13897 (insert ":\n")
13898 (forward-line -1))
13899 ((and off (looking-at re))
13900 (replace-match "" t t nil 1))
13901 ((not off) (org-move-to-column cc t) (insert ":")))
13902 (forward-line 1)))
13903 (save-excursion
13904 (org-back-to-heading)
13905 (if (looking-at (concat outline-regexp
13906 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13907 (replace-match "" t t nil 1)
13908 (if (looking-at outline-regexp)
13909 (progn
13910 (goto-char (match-end 0))
13911 (insert org-quote-string " "))))))))
13913 ;;;; Functions extending outline functionality
13915 (defun org-beginning-of-line (&optional arg)
13916 "Go to the beginning of the current line. If that is invisible, continue
13917 to a visible line beginning. This makes the function of C-a more intuitive.
13918 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13919 first attempt, and only move to after the tags when the cursor is already
13920 beyond the end of the headline."
13921 (interactive "P")
13922 (let ((pos (point)))
13923 (beginning-of-line 1)
13924 (if (bobp)
13926 (backward-char 1)
13927 (if (org-invisible-p)
13928 (while (and (not (bobp)) (org-invisible-p))
13929 (backward-char 1)
13930 (beginning-of-line 1))
13931 (forward-char 1)))
13932 (when org-special-ctrl-a/e
13933 (cond
13934 ((and (looking-at org-todo-line-regexp)
13935 (= (char-after (match-end 1)) ?\ ))
13936 (goto-char
13937 (if (eq org-special-ctrl-a/e t)
13938 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13939 ((= pos (point)) (match-beginning 3))
13940 (t (point)))
13941 (cond ((> pos (point)) (point))
13942 ((not (eq last-command this-command)) (point))
13943 (t (match-beginning 3))))))
13944 ((org-at-item-p)
13945 (goto-char
13946 (if (eq org-special-ctrl-a/e t)
13947 (cond ((> pos (match-end 4)) (match-end 4))
13948 ((= pos (point)) (match-end 4))
13949 (t (point)))
13950 (cond ((> pos (point)) (point))
13951 ((not (eq last-command this-command)) (point))
13952 (t (match-end 4))))))))))
13954 (defun org-end-of-line (&optional arg)
13955 "Go to the end of the line.
13956 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13957 first attempt, and only move to after the tags when the cursor is already
13958 beyond the end of the headline."
13959 (interactive "P")
13960 (if (or (not org-special-ctrl-a/e)
13961 (not (org-on-heading-p)))
13962 (end-of-line arg)
13963 (let ((pos (point)))
13964 (beginning-of-line 1)
13965 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13966 (if (eq org-special-ctrl-a/e t)
13967 (if (or (< pos (match-beginning 1))
13968 (= pos (match-end 0)))
13969 (goto-char (match-beginning 1))
13970 (goto-char (match-end 0)))
13971 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13972 (goto-char (match-end 0))
13973 (goto-char (match-beginning 1))))
13974 (end-of-line arg)))))
13976 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13977 (define-key org-mode-map "\C-e" 'org-end-of-line)
13979 (defun org-kill-line (&optional arg)
13980 "Kill line, to tags or end of line."
13981 (interactive "P")
13982 (cond
13983 ((or (not org-special-ctrl-k)
13984 (bolp)
13985 (not (org-on-heading-p)))
13986 (call-interactively 'kill-line))
13987 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13988 (kill-region (point) (match-beginning 1))
13989 (org-set-tags nil t))
13990 (t (kill-region (point) (point-at-eol)))))
13992 (define-key org-mode-map "\C-k" 'org-kill-line)
13994 (defun org-invisible-p ()
13995 "Check if point is at a character currently not visible."
13996 ;; Early versions of noutline don't have `outline-invisible-p'.
13997 (if (fboundp 'outline-invisible-p)
13998 (outline-invisible-p)
13999 (get-char-property (point) 'invisible)))
14001 (defun org-invisible-p2 ()
14002 "Check if point is at a character currently not visible."
14003 (save-excursion
14004 (if (and (eolp) (not (bobp))) (backward-char 1))
14005 ;; Early versions of noutline don't have `outline-invisible-p'.
14006 (if (fboundp 'outline-invisible-p)
14007 (outline-invisible-p)
14008 (get-char-property (point) 'invisible))))
14010 (defalias 'org-back-to-heading 'outline-back-to-heading)
14011 (defalias 'org-on-heading-p 'outline-on-heading-p)
14012 (defalias 'org-at-heading-p 'outline-on-heading-p)
14013 (defun org-at-heading-or-item-p ()
14014 (or (org-on-heading-p) (org-at-item-p)))
14016 (defun org-on-target-p ()
14017 (or (org-in-regexp org-radio-target-regexp)
14018 (org-in-regexp org-target-regexp)))
14020 (defun org-up-heading-all (arg)
14021 "Move to the heading line of which the present line is a subheading.
14022 This function considers both visible and invisible heading lines.
14023 With argument, move up ARG levels."
14024 (if (fboundp 'outline-up-heading-all)
14025 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14026 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14028 (defun org-up-heading-safe ()
14029 "Move to the heading line of which the present line is a subheading.
14030 This version will not throw an error. It will return the level of the
14031 headline found, or nil if no higher level is found."
14032 (let ((pos (point)) start-level level
14033 (re (concat "^" outline-regexp)))
14034 (catch 'exit
14035 (outline-back-to-heading t)
14036 (setq start-level (funcall outline-level))
14037 (if (equal start-level 1) (throw 'exit nil))
14038 (while (re-search-backward re nil t)
14039 (setq level (funcall outline-level))
14040 (if (< level start-level) (throw 'exit level)))
14041 nil)))
14043 (defun org-first-sibling-p ()
14044 "Is this heading the first child of its parents?"
14045 (interactive)
14046 (let ((re (concat "^" outline-regexp))
14047 level l)
14048 (unless (org-at-heading-p t)
14049 (error "Not at a heading"))
14050 (setq level (funcall outline-level))
14051 (save-excursion
14052 (if (not (re-search-backward re nil t))
14054 (setq l (funcall outline-level))
14055 (< l level)))))
14057 (defun org-goto-sibling (&optional previous)
14058 "Goto the next sibling, even if it is invisible.
14059 When PREVIOUS is set, go to the previous sibling instead. Returns t
14060 when a sibling was found. When none is found, return nil and don't
14061 move point."
14062 (let ((fun (if previous 're-search-backward 're-search-forward))
14063 (pos (point))
14064 (re (concat "^" outline-regexp))
14065 level l)
14066 (when (condition-case nil (org-back-to-heading t) (error nil))
14067 (setq level (funcall outline-level))
14068 (catch 'exit
14069 (or previous (forward-char 1))
14070 (while (funcall fun re nil t)
14071 (setq l (funcall outline-level))
14072 (when (< l level) (goto-char pos) (throw 'exit nil))
14073 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14074 (goto-char pos)
14075 nil))))
14077 (defun org-show-siblings ()
14078 "Show all siblings of the current headline."
14079 (save-excursion
14080 (while (org-goto-sibling) (org-flag-heading nil)))
14081 (save-excursion
14082 (while (org-goto-sibling 'previous)
14083 (org-flag-heading nil))))
14085 (defun org-show-hidden-entry ()
14086 "Show an entry where even the heading is hidden."
14087 (save-excursion
14088 (org-show-entry)))
14090 (defun org-flag-heading (flag &optional entry)
14091 "Flag the current heading. FLAG non-nil means make invisible.
14092 When ENTRY is non-nil, show the entire entry."
14093 (save-excursion
14094 (org-back-to-heading t)
14095 ;; Check if we should show the entire entry
14096 (if entry
14097 (progn
14098 (org-show-entry)
14099 (save-excursion
14100 (and (outline-next-heading)
14101 (org-flag-heading nil))))
14102 (outline-flag-region (max (point-min) (1- (point)))
14103 (save-excursion (outline-end-of-heading) (point))
14104 flag))))
14106 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14107 ;; This is an exact copy of the original function, but it uses
14108 ;; `org-back-to-heading', to make it work also in invisible
14109 ;; trees. And is uses an invisible-OK argument.
14110 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14111 (org-back-to-heading invisible-OK)
14112 (let ((first t)
14113 (level (funcall outline-level)))
14114 (while (and (not (eobp))
14115 (or first (> (funcall outline-level) level)))
14116 (setq first nil)
14117 (outline-next-heading))
14118 (unless to-heading
14119 (if (memq (preceding-char) '(?\n ?\^M))
14120 (progn
14121 ;; Go to end of line before heading
14122 (forward-char -1)
14123 (if (memq (preceding-char) '(?\n ?\^M))
14124 ;; leave blank line before heading
14125 (forward-char -1))))))
14126 (point))
14128 (defun org-show-subtree ()
14129 "Show everything after this heading at deeper levels."
14130 (outline-flag-region
14131 (point)
14132 (save-excursion
14133 (outline-end-of-subtree) (outline-next-heading) (point))
14134 nil))
14136 (defun org-show-entry ()
14137 "Show the body directly following this heading.
14138 Show the heading too, if it is currently invisible."
14139 (interactive)
14140 (save-excursion
14141 (condition-case nil
14142 (progn
14143 (org-back-to-heading t)
14144 (outline-flag-region
14145 (max (point-min) (1- (point)))
14146 (save-excursion
14147 (re-search-forward
14148 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14149 (or (match-beginning 1) (point-max)))
14150 nil))
14151 (error nil))))
14153 (defun org-make-options-regexp (kwds)
14154 "Make a regular expression for keyword lines."
14155 (concat
14157 "#?[ \t]*\\+\\("
14158 (mapconcat 'regexp-quote kwds "\\|")
14159 "\\):[ \t]*"
14160 "\\(.+\\)"))
14162 ;; Make isearch reveal the necessary context
14163 (defun org-isearch-end ()
14164 "Reveal context after isearch exits."
14165 (when isearch-success ; only if search was successful
14166 (if (featurep 'xemacs)
14167 ;; Under XEmacs, the hook is run in the correct place,
14168 ;; we directly show the context.
14169 (org-show-context 'isearch)
14170 ;; In Emacs the hook runs *before* restoring the overlays.
14171 ;; So we have to use a one-time post-command-hook to do this.
14172 ;; (Emacs 22 has a special variable, see function `org-mode')
14173 (unless (and (boundp 'isearch-mode-end-hook-quit)
14174 isearch-mode-end-hook-quit)
14175 ;; Only when the isearch was not quitted.
14176 (org-add-hook 'post-command-hook 'org-isearch-post-command
14177 'append 'local)))))
14179 (defun org-isearch-post-command ()
14180 "Remove self from hook, and show context."
14181 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14182 (org-show-context 'isearch))
14185 ;;;; Integration with and fixes for other packages
14187 ;;; Imenu support
14189 (defvar org-imenu-markers nil
14190 "All markers currently used by Imenu.")
14191 (make-variable-buffer-local 'org-imenu-markers)
14193 (defun org-imenu-new-marker (&optional pos)
14194 "Return a new marker for use by Imenu, and remember the marker."
14195 (let ((m (make-marker)))
14196 (move-marker m (or pos (point)))
14197 (push m org-imenu-markers)
14200 (defun org-imenu-get-tree ()
14201 "Produce the index for Imenu."
14202 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14203 (setq org-imenu-markers nil)
14204 (let* ((n org-imenu-depth)
14205 (re (concat "^" outline-regexp))
14206 (subs (make-vector (1+ n) nil))
14207 (last-level 0)
14208 m tree level head)
14209 (save-excursion
14210 (save-restriction
14211 (widen)
14212 (goto-char (point-max))
14213 (while (re-search-backward re nil t)
14214 (setq level (org-reduced-level (funcall outline-level)))
14215 (when (<= level n)
14216 (looking-at org-complex-heading-regexp)
14217 (setq head (org-match-string-no-properties 4)
14218 m (org-imenu-new-marker))
14219 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14220 (if (>= level last-level)
14221 (push (cons head m) (aref subs level))
14222 (push (cons head (aref subs (1+ level))) (aref subs level))
14223 (loop for i from (1+ level) to n do (aset subs i nil)))
14224 (setq last-level level)))))
14225 (aref subs 1)))
14227 (eval-after-load "imenu"
14228 '(progn
14229 (add-hook 'imenu-after-jump-hook
14230 (lambda () (org-show-context 'org-goto)))))
14232 ;; Speedbar support
14234 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14235 "Overlay marking the agenda restriction line in speedbar.")
14236 (org-overlay-put org-speedbar-restriction-lock-overlay
14237 'face 'org-agenda-restriction-lock)
14238 (org-overlay-put org-speedbar-restriction-lock-overlay
14239 'help-echo "Agendas are currently limited to this item.")
14240 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14242 (defun org-speedbar-set-agenda-restriction ()
14243 "Restrict future agenda commands to the location at point in speedbar.
14244 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14245 (interactive)
14246 (require 'org-agenda)
14247 (let (p m tp np dir txt w)
14248 (cond
14249 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14250 'org-imenu t))
14251 (setq m (get-text-property p 'org-imenu-marker))
14252 (save-excursion
14253 (save-restriction
14254 (set-buffer (marker-buffer m))
14255 (goto-char m)
14256 (org-agenda-set-restriction-lock 'subtree))))
14257 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14258 'speedbar-function 'speedbar-find-file))
14259 (setq tp (previous-single-property-change
14260 (1+ p) 'speedbar-function)
14261 np (next-single-property-change
14262 tp 'speedbar-function)
14263 dir (speedbar-line-directory)
14264 txt (buffer-substring-no-properties (or tp (point-min))
14265 (or np (point-max))))
14266 (save-excursion
14267 (save-restriction
14268 (set-buffer (find-file-noselect
14269 (let ((default-directory dir))
14270 (expand-file-name txt))))
14271 (unless (org-mode-p)
14272 (error "Cannot restrict to non-Org-mode file"))
14273 (org-agenda-set-restriction-lock 'file))))
14274 (t (error "Don't know how to restrict Org-mode's agenda")))
14275 (org-move-overlay org-speedbar-restriction-lock-overlay
14276 (point-at-bol) (point-at-eol))
14277 (setq current-prefix-arg nil)
14278 (org-agenda-maybe-redo)))
14280 (eval-after-load "speedbar"
14281 '(progn
14282 (speedbar-add-supported-extension ".org")
14283 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14284 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14285 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14286 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14287 (add-hook 'speedbar-visiting-tag-hook
14288 (lambda () (org-show-context 'org-goto)))))
14291 ;;; Fixes and Hacks for problems with other packages
14293 ;; Make flyspell not check words in links, to not mess up our keymap
14294 (defun org-mode-flyspell-verify ()
14295 "Don't let flyspell put overlays at active buttons."
14296 (not (get-text-property (point) 'keymap)))
14298 ;; Make `bookmark-jump' show the jump location if it was hidden.
14299 (eval-after-load "bookmark"
14300 '(if (boundp 'bookmark-after-jump-hook)
14301 ;; We can use the hook
14302 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14303 ;; Hook not available, use advice
14304 (defadvice bookmark-jump (after org-make-visible activate)
14305 "Make the position visible."
14306 (org-bookmark-jump-unhide))))
14308 (defun org-bookmark-jump-unhide ()
14309 "Unhide the current position, to show the bookmark location."
14310 (and (org-mode-p)
14311 (or (org-invisible-p)
14312 (save-excursion (goto-char (max (point-min) (1- (point))))
14313 (org-invisible-p)))
14314 (org-show-context 'bookmark-jump)))
14316 ;; Make session.el ignore our circular variable
14317 (eval-after-load "session"
14318 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14320 ;;;; Experimental code
14322 (defun org-closed-in-range ()
14323 "Sparse tree of items closed in a certain time range.
14324 Still experimental, may disappear in the future."
14325 (interactive)
14326 ;; Get the time interval from the user.
14327 (let* ((time1 (time-to-seconds
14328 (org-read-date nil 'to-time nil "Starting date: ")))
14329 (time2 (time-to-seconds
14330 (org-read-date nil 'to-time nil "End date:")))
14331 ;; callback function
14332 (callback (lambda ()
14333 (let ((time
14334 (time-to-seconds
14335 (apply 'encode-time
14336 (org-parse-time-string
14337 (match-string 1))))))
14338 ;; check if time in interval
14339 (and (>= time time1) (<= time time2))))))
14340 ;; make tree, check each match with the callback
14341 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14344 ;;;; Finish up
14346 (provide 'org)
14348 (run-hooks 'org-load-hook)
14350 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14352 ;;; org.el ends here