Release 6.07b.
[org-mode/org-tableheadings.git] / lisp / org.el
bloba3c38dd65f5a2297ec3defb49afbbdd8e3bda575
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.07b
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.07b"
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-align-all-tables nil
224 "Non-nil means, align all tables when visiting a file.
225 This is useful when the column width in tables is forced with <N> cookies
226 in table fields. Such tables will look correct only after the first re-align.
227 This can also be configured on a per-file basis by adding one of
228 the following lines anywhere in the buffer:
229 #+STARTUP: align
230 #+STARTUP: noalign"
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-insert-mode-line-in-empty-file nil
235 "Non-nil means insert the first line setting Org-mode in empty files.
236 When the function `org-mode' is called interactively in an empty file, this
237 normally means that the file name does not automatically trigger Org-mode.
238 To ensure that the file will always be in Org-mode in the future, a
239 line enforcing Org-mode will be inserted into the buffer, if this option
240 has been set."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-replace-disputed-keys nil
245 "Non-nil means use alternative key bindings for some keys.
246 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
247 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
248 If you want to use Org-mode together with one of these other modes,
249 or more generally if you would like to move some Org-mode commands to
250 other keys, set this variable and configure the keys with the variable
251 `org-disputed-keys'.
253 This option is only relevant at load-time of Org-mode, and must be set
254 *before* org.el is loaded. Changing it requires a restart of Emacs to
255 become effective."
256 :group 'org-startup
257 :type 'boolean)
259 (defcustom org-use-extra-keys nil
260 "Non-nil means use extra key sequence definitions for certain
261 commands. This happens automatically if you run XEmacs or if
262 window-system is nil. This variable lets you do the same
263 manually. You must set it before loading org.
265 Example: on Carbon Emacs 22 running graphically, with an external
266 keyboard on a Powerbook, the default way of setting M-left might
267 not work for either Alt or ESC. Setting this variable will make
268 it work for ESC."
269 :group 'org-startup
270 :type 'boolean)
272 (if (fboundp 'defvaralias)
273 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
275 (defcustom org-disputed-keys
276 '(([(shift up)] . [(meta p)])
277 ([(shift down)] . [(meta n)])
278 ([(shift left)] . [(meta -)])
279 ([(shift right)] . [(meta +)])
280 ([(control shift right)] . [(meta shift +)])
281 ([(control shift left)] . [(meta shift -)]))
282 "Keys for which Org-mode and other modes compete.
283 This is an alist, cars are the default keys, second element specifies
284 the alternative to use when `org-replace-disputed-keys' is t.
286 Keys can be specified in any syntax supported by `define-key'.
287 The value of this option takes effect only at Org-mode's startup,
288 therefore you'll have to restart Emacs to apply it after changing."
289 :group 'org-startup
290 :type 'alist)
292 (defun org-key (key)
293 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
294 Or return the original if not disputed."
295 (if org-replace-disputed-keys
296 (let* ((nkey (key-description key))
297 (x (org-find-if (lambda (x)
298 (equal (key-description (car x)) nkey))
299 org-disputed-keys)))
300 (if x (cdr x) key))
301 key))
303 (defun org-find-if (predicate seq)
304 (catch 'exit
305 (while seq
306 (if (funcall predicate (car seq))
307 (throw 'exit (car seq))
308 (pop seq)))))
310 (defun org-defkey (keymap key def)
311 "Define a key, possibly translated, as returned by `org-key'."
312 (define-key keymap (org-key key) def))
314 (defcustom org-ellipsis nil
315 "The ellipsis to use in the Org-mode outline.
316 When nil, just use the standard three dots. When a string, use that instead,
317 When a face, use the standart 3 dots, but with the specified face.
318 The change affects only Org-mode (which will then use its own display table).
319 Changing this requires executing `M-x org-mode' in a buffer to become
320 effective."
321 :group 'org-startup
322 :type '(choice (const :tag "Default" nil)
323 (face :tag "Face" :value org-warning)
324 (string :tag "String" :value "...#")))
326 (defvar org-display-table nil
327 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
329 (defgroup org-keywords nil
330 "Keywords in Org-mode."
331 :tag "Org Keywords"
332 :group 'org)
334 (defcustom org-deadline-string "DEADLINE:"
335 "String to mark deadline entries.
336 A deadline is this string, followed by a time stamp. Should be a word,
337 terminated by a colon. You can insert a schedule keyword and
338 a timestamp with \\[org-deadline].
339 Changes become only effective after restarting Emacs."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-scheduled-string "SCHEDULED:"
344 "String to mark scheduled TODO entries.
345 A schedule is this string, followed by a time stamp. Should be a word,
346 terminated by a colon. You can insert a schedule keyword and
347 a timestamp with \\[org-schedule].
348 Changes become only effective after restarting Emacs."
349 :group 'org-keywords
350 :type 'string)
352 (defcustom org-closed-string "CLOSED:"
353 "String used as the prefix for timestamps logging closing a TODO entry."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-clock-string "CLOCK:"
358 "String used as prefix for timestamps clocking work hours on an item."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-comment-string "COMMENT"
363 "Entries starting with this keyword will never be exported.
364 An entry can be toggled between COMMENT and normal with
365 \\[org-toggle-comment].
366 Changes become only effective after restarting Emacs."
367 :group 'org-keywords
368 :type 'string)
370 (defcustom org-quote-string "QUOTE"
371 "Entries starting with this keyword will be exported in fixed-width font.
372 Quoting applies only to the text in the entry following the headline, and does
373 not extend beyond the next headline, even if that is lower level.
374 An entry can be toggled between QUOTE and normal with
375 \\[org-toggle-fixed-width-section]."
376 :group 'org-keywords
377 :type 'string)
379 (defconst org-repeat-re
380 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
381 "Regular expression for specifying repeated events.
382 After a match, group 1 contains the repeat expression.")
384 (defgroup org-structure nil
385 "Options concerning the general structure of Org-mode files."
386 :tag "Org Structure"
387 :group 'org)
389 (defgroup org-reveal-location nil
390 "Options about how to make context of a location visible."
391 :tag "Org Reveal Location"
392 :group 'org-structure)
394 (defconst org-context-choice
395 '(choice
396 (const :tag "Always" t)
397 (const :tag "Never" nil)
398 (repeat :greedy t :tag "Individual contexts"
399 (cons
400 (choice :tag "Context"
401 (const agenda)
402 (const org-goto)
403 (const occur-tree)
404 (const tags-tree)
405 (const link-search)
406 (const mark-goto)
407 (const bookmark-jump)
408 (const isearch)
409 (const default))
410 (boolean))))
411 "Contexts for the reveal options.")
413 (defcustom org-show-hierarchy-above '((default . t))
414 "Non-nil means, show full hierarchy when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the hierarchy of headings
417 above the exposed location is shown.
418 Turning this off for example for sparse trees makes them very compact.
419 Instead of t, this can also be an alist specifying this option for different
420 contexts. Valid contexts are
421 agenda when exposing an entry from the agenda
422 org-goto when using the command `org-goto' on key C-c C-j
423 occur-tree when using the command `org-occur' on key C-c /
424 tags-tree when constructing a sparse tree based on tags matches
425 link-search when exposing search matches associated with a link
426 mark-goto when exposing the jump goal of a mark
427 bookmark-jump when exposing a bookmark location
428 isearch when exiting from an incremental search
429 default default for all contexts not set explicitly"
430 :group 'org-reveal-location
431 :type org-context-choice)
433 (defcustom org-show-following-heading '((default . nil))
434 "Non-nil means, show following heading when revealing a location.
435 Org-mode often shows locations in an org-mode file which might have
436 been invisible before. When this is set, the heading following the
437 match is shown.
438 Turning this off for example for sparse trees makes them very compact,
439 but makes it harder to edit the location of the match. In such a case,
440 use the command \\[org-reveal] to show more context.
441 Instead of t, this can also be an alist specifying this option for different
442 contexts. See `org-show-hierarchy-above' for valid contexts."
443 :group 'org-reveal-location
444 :type org-context-choice)
446 (defcustom org-show-siblings '((default . nil) (isearch t))
447 "Non-nil means, show all sibling heading when revealing a location.
448 Org-mode often shows locations in an org-mode file which might have
449 been invisible before. When this is set, the sibling of the current entry
450 heading are all made visible. If `org-show-hierarchy-above' is t,
451 the same happens on each level of the hierarchy above the current entry.
453 By default this is on for the isearch context, off for all other contexts.
454 Turning this off for example for sparse trees makes them very compact,
455 but makes it harder to edit the location of the match. In such a case,
456 use the command \\[org-reveal] to show more context.
457 Instead of t, this can also be an alist specifying this option for different
458 contexts. See `org-show-hierarchy-above' for valid contexts."
459 :group 'org-reveal-location
460 :type org-context-choice)
462 (defcustom org-show-entry-below '((default . nil))
463 "Non-nil means, show the entry below a headline when revealing a location.
464 Org-mode often shows locations in an org-mode file which might have
465 been invisible before. When this is set, the text below the headline that is
466 exposed is also shown.
468 By default this is off for all contexts.
469 Instead of t, this can also be an alist specifying this option for different
470 contexts. See `org-show-hierarchy-above' for valid contexts."
471 :group 'org-reveal-location
472 :type org-context-choice)
474 (defcustom org-indirect-buffer-display 'other-window
475 "How should indirect tree buffers be displayed?
476 This applies to indirect buffers created with the commands
477 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
478 Valid values are:
479 current-window Display in the current window
480 other-window Just display in another window.
481 dedicated-frame Create one new frame, and re-use it each time.
482 new-frame Make a new frame each time. Note that in this case
483 previously-made indirect buffers are kept, and you need to
484 kill these buffers yourself."
485 :group 'org-structure
486 :group 'org-agenda-windows
487 :type '(choice
488 (const :tag "In current window" current-window)
489 (const :tag "In current frame, other window" other-window)
490 (const :tag "Each time a new frame" new-frame)
491 (const :tag "One dedicated frame" dedicated-frame)))
493 (defgroup org-cycle nil
494 "Options concerning visibility cycling in Org-mode."
495 :tag "Org Cycle"
496 :group 'org-structure)
498 (defcustom org-drawers '("PROPERTIES" "CLOCK")
499 "Names of drawers. Drawers are not opened by cycling on the headline above.
500 Drawers only open with a TAB on the drawer line itself. A drawer looks like
501 this:
502 :DRAWERNAME:
503 .....
504 :END:
505 The drawer \"PROPERTIES\" is special for capturing properties through
506 the property API.
508 Drawers can be defined on the per-file basis with a line like:
510 #+DRAWERS: HIDDEN STATE PROPERTIES"
511 :group 'org-structure
512 :type '(repeat (string :tag "Drawer Name")))
514 (defcustom org-cycle-global-at-bob nil
515 "Cycle globally if cursor is at beginning of buffer and not at a headline.
516 This makes it possible to do global cycling without having to use S-TAB or
517 C-u TAB. For this special case to work, the first line of the buffer
518 must not be a headline - it may be empty ot some other text. When used in
519 this way, `org-cycle-hook' is disables temporarily, to make sure the
520 cursor stays at the beginning of the buffer.
521 When this option is nil, don't do anything special at the beginning
522 of the buffer."
523 :group 'org-cycle
524 :type 'boolean)
526 (defcustom org-cycle-emulate-tab t
527 "Where should `org-cycle' emulate TAB.
528 nil Never
529 white Only in completely white lines
530 whitestart Only at the beginning of lines, before the first non-white char
531 t Everywhere except in headlines
532 exc-hl-bol Everywhere except at the start of a headline
533 If TAB is used in a place where it does not emulate TAB, the current subtree
534 visibility is cycled."
535 :group 'org-cycle
536 :type '(choice (const :tag "Never" nil)
537 (const :tag "Only in completely white lines" white)
538 (const :tag "Before first char in a line" whitestart)
539 (const :tag "Everywhere except in headlines" t)
540 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
543 (defcustom org-cycle-separator-lines 2
544 "Number of empty lines needed to keep an empty line between collapsed trees.
545 If you leave an empty line between the end of a subtree and the following
546 headline, this empty line is hidden when the subtree is folded.
547 Org-mode will leave (exactly) one empty line visible if the number of
548 empty lines is equal or larger to the number given in this variable.
549 So the default 2 means, at least 2 empty lines after the end of a subtree
550 are needed to produce free space between a collapsed subtree and the
551 following headline.
553 Special case: when 0, never leave empty lines in collapsed view."
554 :group 'org-cycle
555 :type 'integer)
556 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
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-yank-folded-subtrees t
636 "Non-nil means, when yanking subtrees, fold them.
637 If the kill is a single subtree, or a sequence of subtrees, i.e. if
638 it starts with a heading and all other headings in it are either children
639 or siblings, then fold all the subtrees."
640 :group 'org-edit-structure
641 :type 'boolean)
643 (defcustom org-M-RET-may-split-line '((default . t))
644 "Non-nil means, M-RET will split the line at the cursor position.
645 When nil, it will go to the end of the line before making a
646 new line.
647 You may also set this option in a different way for different
648 contexts. Valid contexts are:
650 headline when creating a new headline
651 item when creating a new item
652 table in a table field
653 default the value to be used for all contexts not explicitly
654 customized"
655 :group 'org-structure
656 :group 'org-table
657 :type '(choice
658 (const :tag "Always" t)
659 (const :tag "Never" nil)
660 (repeat :greedy t :tag "Individual contexts"
661 (cons
662 (choice :tag "Context"
663 (const headline)
664 (const item)
665 (const table)
666 (const default))
667 (boolean)))))
670 (defcustom org-insert-heading-respect-content nil
671 "Non-nil means, insert new headings after the current subtree.
672 When nil, the new heading is created directly after the current line.
673 The commands \\[org-insert-heading-respect-content] and
674 \\[org-insert-todo-heading-respect-content] turn this variable on
675 for the duration of the command."
676 :group 'org-structure
677 :type 'boolean)
679 (defcustom org-blank-before-new-entry '((heading . nil)
680 (plain-list-item . nil))
681 "Should `org-insert-heading' leave a blank line before new heading/item?
682 The value is an alist, with `heading' and `plain-list-item' as car,
683 and a boolean flag as cdr."
684 :group 'org-edit-structure
685 :type '(list
686 (cons (const heading) (boolean))
687 (cons (const plain-list-item) (boolean))))
689 (defcustom org-insert-heading-hook nil
690 "Hook being run after inserting a new heading."
691 :group 'org-edit-structure
692 :type 'hook)
694 (defcustom org-enable-fixed-width-editor t
695 "Non-nil means, lines starting with \":\" are treated as fixed-width.
696 This currently only means, they are never auto-wrapped.
697 When nil, such lines will be treated like ordinary lines.
698 See also the QUOTE keyword."
699 :group 'org-edit-structure
700 :type 'boolean)
702 (defcustom org-edit-fixed-width-region-mode 'artist-mode
703 "The mode that should be used to edit fixed-width regions.
704 These are the regions where each line starts with a colon."
705 :group 'org-edit-structure
706 :type '(choice
707 (const artist-mode)
708 (const picture-mode)
709 (const fundamental-mode)
710 (function :tag "Other (specify)")))
712 (defcustom org-goto-auto-isearch t
713 "Non-nil means, typing characters in org-goto starts incremental search."
714 :group 'org-edit-structure
715 :type 'boolean)
717 (defgroup org-sparse-trees nil
718 "Options concerning sparse trees in Org-mode."
719 :tag "Org Sparse Trees"
720 :group 'org-structure)
722 (defcustom org-highlight-sparse-tree-matches t
723 "Non-nil means, highlight all matches that define a sparse tree.
724 The highlights will automatically disappear the next time the buffer is
725 changed by an edit command."
726 :group 'org-sparse-trees
727 :type 'boolean)
729 (defcustom org-remove-highlights-with-change t
730 "Non-nil means, any change to the buffer will remove temporary highlights.
731 Such highlights are created by `org-occur' and `org-clock-display'.
732 When nil, `C-c C-c needs to be used to get rid of the highlights.
733 The highlights created by `org-preview-latex-fragment' always need
734 `C-c C-c' to be removed."
735 :group 'org-sparse-trees
736 :group 'org-time
737 :type 'boolean)
740 (defcustom org-occur-hook '(org-first-headline-recenter)
741 "Hook that is run after `org-occur' has constructed a sparse tree.
742 This can be used to recenter the window to show as much of the structure
743 as possible."
744 :group 'org-sparse-trees
745 :type 'hook)
747 (defgroup org-plain-lists nil
748 "Options concerning plain lists in Org-mode."
749 :tag "Org Plain lists"
750 :group 'org-structure)
752 (defcustom org-cycle-include-plain-lists nil
753 "Non-nil means, include plain lists into visibility cycling.
754 This means that during cycling, plain list items will *temporarily* be
755 interpreted as outline headlines with a level given by 1000+i where i is the
756 indentation of the bullet. In all other operations, plain list items are
757 not seen as headlines. For example, you cannot assign a TODO keyword to
758 such an item."
759 :group 'org-plain-lists
760 :type 'boolean)
762 (defcustom org-plain-list-ordered-item-terminator t
763 "The character that makes a line with leading number an ordered list item.
764 Valid values are ?. and ?\). To get both terminators, use t. While
765 ?. may look nicer, it creates the danger that a line with leading
766 number may be incorrectly interpreted as an item. ?\) therefore is
767 the safe choice."
768 :group 'org-plain-lists
769 :type '(choice (const :tag "dot like in \"2.\"" ?.)
770 (const :tag "paren like in \"2)\"" ?\))
771 (const :tab "both" t)))
773 (defcustom org-empty-line-terminates-plain-lists nil
774 "Non-nil means, an empty line ends all plain list levels.
775 When nil, empty lines are part of the preceeding item."
776 :group 'org-plain-lists
777 :type 'boolean)
779 (defcustom org-auto-renumber-ordered-lists t
780 "Non-nil means, automatically renumber ordered plain lists.
781 Renumbering happens when the sequence have been changed with
782 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
783 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
784 :group 'org-plain-lists
785 :type 'boolean)
787 (defcustom org-provide-checkbox-statistics t
788 "Non-nil means, update checkbox statistics after insert and toggle.
789 When this is set, checkbox statistics is updated each time you either insert
790 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
791 with \\[org-ctrl-c-ctrl-c\\]."
792 :group 'org-plain-lists
793 :type 'boolean)
795 (defcustom org-description-max-indent 20
796 "Maximum indentation for the second line of a description list.
797 When the indentation would be larger than this, it will become
798 5 characters instead."
799 :group 'org-plain-lists
800 :type 'integer)
802 (defgroup org-imenu-and-speedbar nil
803 "Options concerning imenu and speedbar in Org-mode."
804 :tag "Org Imenu and Speedbar"
805 :group 'org-structure)
807 (defcustom org-imenu-depth 2
808 "The maximum level for Imenu access to Org-mode headlines.
809 This also applied for speedbar access."
810 :group 'org-imenu-and-speedbar
811 :type 'number)
813 (defgroup org-table nil
814 "Options concerning tables in Org-mode."
815 :tag "Org Table"
816 :group 'org)
818 (defcustom org-enable-table-editor 'optimized
819 "Non-nil means, lines starting with \"|\" are handled by the table editor.
820 When nil, such lines will be treated like ordinary lines.
822 When equal to the symbol `optimized', the table editor will be optimized to
823 do the following:
824 - Automatic overwrite mode in front of whitespace in table fields.
825 This makes the structure of the table stay in tact as long as the edited
826 field does not exceed the column width.
827 - Minimize the number of realigns. Normally, the table is aligned each time
828 TAB or RET are pressed to move to another field. With optimization this
829 happens only if changes to a field might have changed the column width.
830 Optimization requires replacing the functions `self-insert-command',
831 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
832 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
833 very good at guessing when a re-align will be necessary, but you can always
834 force one with \\[org-ctrl-c-ctrl-c].
836 If you would like to use the optimized version in Org-mode, but the
837 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
839 This variable can be used to turn on and off the table editor during a session,
840 but in order to toggle optimization, a restart is required.
842 See also the variable `org-table-auto-blank-field'."
843 :group 'org-table
844 :type '(choice
845 (const :tag "off" nil)
846 (const :tag "on" t)
847 (const :tag "on, optimized" optimized)))
849 (defcustom org-table-tab-recognizes-table.el t
850 "Non-nil means, TAB will automatically notice a table.el table.
851 When it sees such a table, it moves point into it and - if necessary -
852 calls `table-recognize-table'."
853 :group 'org-table-editing
854 :type 'boolean)
856 (defgroup org-link nil
857 "Options concerning links in Org-mode."
858 :tag "Org Link"
859 :group 'org)
861 (defvar org-link-abbrev-alist-local nil
862 "Buffer-local version of `org-link-abbrev-alist', which see.
863 The value of this is taken from the #+LINK lines.")
864 (make-variable-buffer-local 'org-link-abbrev-alist-local)
866 (defcustom org-link-abbrev-alist nil
867 "Alist of link abbreviations.
868 The car of each element is a string, to be replaced at the start of a link.
869 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
870 links in Org-mode buffers can have an optional tag after a double colon, e.g.
872 [[linkkey:tag][description]]
874 If REPLACE is a string, the tag will simply be appended to create the link.
875 If the string contains \"%s\", the tag will be inserted there.
877 REPLACE may also be a function that will be called with the tag as the
878 only argument to create the link, which should be returned as a string.
880 See the manual for examples."
881 :group 'org-link
882 :type 'alist)
884 (defcustom org-descriptive-links t
885 "Non-nil means, hide link part and only show description of bracket links.
886 Bracket links are like [[link][descritpion]]. This variable sets the initial
887 state in new org-mode buffers. The setting can then be toggled on a
888 per-buffer basis from the Org->Hyperlinks menu."
889 :group 'org-link
890 :type 'boolean)
892 (defcustom org-link-file-path-type 'adaptive
893 "How the path name in file links should be stored.
894 Valid values are:
896 relative Relative to the current directory, i.e. the directory of the file
897 into which the link is being inserted.
898 absolute Absolute path, if possible with ~ for home directory.
899 noabbrev Absolute path, no abbreviation of home directory.
900 adaptive Use relative path for files in the current directory and sub-
901 directories of it. For other files, use an absolute path."
902 :group 'org-link
903 :type '(choice
904 (const relative)
905 (const absolute)
906 (const noabbrev)
907 (const adaptive)))
909 (defcustom org-activate-links '(bracket angle plain radio tag date)
910 "Types of links that should be activated in Org-mode files.
911 This is a list of symbols, each leading to the activation of a certain link
912 type. In principle, it does not hurt to turn on most link types - there may
913 be a small gain when turning off unused link types. The types are:
915 bracket The recommended [[link][description]] or [[link]] links with hiding.
916 angular Links in angular brackes that may contain whitespace like
917 <bbdb:Carsten Dominik>.
918 plain Plain links in normal text, no whitespace, like http://google.com.
919 radio Text that is matched by a radio target, see manual for details.
920 tag Tag settings in a headline (link to tag search).
921 date Time stamps (link to calendar).
923 Changing this variable requires a restart of Emacs to become effective."
924 :group 'org-link
925 :type '(set (const :tag "Double bracket links (new style)" bracket)
926 (const :tag "Angular bracket links (old style)" angular)
927 (const :tag "Plain text links" plain)
928 (const :tag "Radio target matches" radio)
929 (const :tag "Tags" tag)
930 (const :tag "Timestamps" date)))
932 (defcustom org-make-link-description-function nil
933 "Function to use to generate link descriptions from links. If
934 nil the link location will be used. This function must take two
935 parameters; the first is the link and the second the description
936 org-insert-link has generated, and should return the description
937 to use."
938 :group 'org-link
939 :type 'function)
941 (defgroup org-link-store nil
942 "Options concerning storing links in Org-mode."
943 :tag "Org Store Link"
944 :group 'org-link)
946 (defcustom org-email-link-description-format "Email %c: %.30s"
947 "Format of the description part of a link to an email or usenet message.
948 The following %-excapes will be replaced by corresponding information:
950 %F full \"From\" field
951 %f name, taken from \"From\" field, address if no name
952 %T full \"To\" field
953 %t first name in \"To\" field, address if no name
954 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
955 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
956 %s subject
957 %m message-id.
959 You may use normal field width specification between the % and the letter.
960 This is for example useful to limit the length of the subject.
962 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
963 :group 'org-link-store
964 :type 'string)
966 (defcustom org-from-is-user-regexp
967 (let (r1 r2)
968 (when (and user-mail-address (not (string= user-mail-address "")))
969 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
970 (when (and user-full-name (not (string= user-full-name "")))
971 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
972 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
973 "Regexp mached against the \"From:\" header of an email or usenet message.
974 It should match if the message is from the user him/herself."
975 :group 'org-link-store
976 :type 'regexp)
978 (defcustom org-context-in-file-links t
979 "Non-nil means, file links from `org-store-link' contain context.
980 A search string will be added to the file name with :: as separator and
981 used to find the context when the link is activated by the command
982 `org-open-at-point'.
983 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
984 negates this setting for the duration of the command."
985 :group 'org-link-store
986 :type 'boolean)
988 (defcustom org-keep-stored-link-after-insertion nil
989 "Non-nil means, keep link in list for entire session.
991 The command `org-store-link' adds a link pointing to the current
992 location to an internal list. These links accumulate during a session.
993 The command `org-insert-link' can be used to insert links into any
994 Org-mode file (offering completion for all stored links). When this
995 option is nil, every link which has been inserted once using \\[org-insert-link]
996 will be removed from the list, to make completing the unused links
997 more efficient."
998 :group 'org-link-store
999 :type 'boolean)
1001 (defgroup org-link-follow nil
1002 "Options concerning following links in Org-mode."
1003 :tag "Org Follow Link"
1004 :group 'org-link)
1006 (defcustom org-follow-link-hook nil
1007 "Hook that is run after a link has been followed."
1008 :group 'org-link-follow
1009 :type 'hook)
1011 (defcustom org-tab-follows-link nil
1012 "Non-nil means, on links TAB will follow the link.
1013 Needs to be set before org.el is loaded."
1014 :group 'org-link-follow
1015 :type 'boolean)
1017 (defcustom org-return-follows-link nil
1018 "Non-nil means, on links RET will follow the link.
1019 Needs to be set before org.el is loaded."
1020 :group 'org-link-follow
1021 :type 'boolean)
1023 (defcustom org-mouse-1-follows-link
1024 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1025 "Non-nil means, mouse-1 on a link will follow the link.
1026 A longer mouse click will still set point. Does not work on XEmacs.
1027 Needs to be set before org.el is loaded."
1028 :group 'org-link-follow
1029 :type 'boolean)
1031 (defcustom org-mark-ring-length 4
1032 "Number of different positions to be recorded in the ring
1033 Changing this requires a restart of Emacs to work correctly."
1034 :group 'org-link-follow
1035 :type 'interger)
1037 (defcustom org-link-frame-setup
1038 '((vm . vm-visit-folder-other-frame)
1039 (gnus . gnus-other-frame)
1040 (file . find-file-other-window))
1041 "Setup the frame configuration for following links.
1042 When following a link with Emacs, it may often be useful to display
1043 this link in another window or frame. This variable can be used to
1044 set this up for the different types of links.
1045 For VM, use any of
1046 `vm-visit-folder'
1047 `vm-visit-folder-other-frame'
1048 For Gnus, use any of
1049 `gnus'
1050 `gnus-other-frame'
1051 For FILE, use any of
1052 `find-file'
1053 `find-file-other-window'
1054 `find-file-other-frame'
1055 For the calendar, use the variable `calendar-setup'.
1056 For BBDB, it is currently only possible to display the matches in
1057 another window."
1058 :group 'org-link-follow
1059 :type '(list
1060 (cons (const vm)
1061 (choice
1062 (const vm-visit-folder)
1063 (const vm-visit-folder-other-window)
1064 (const vm-visit-folder-other-frame)))
1065 (cons (const gnus)
1066 (choice
1067 (const gnus)
1068 (const gnus-other-frame)))
1069 (cons (const file)
1070 (choice
1071 (const find-file)
1072 (const find-file-other-window)
1073 (const find-file-other-frame)))))
1075 (defcustom org-display-internal-link-with-indirect-buffer nil
1076 "Non-nil means, use indirect buffer to display infile links.
1077 Activating internal links (from one location in a file to another location
1078 in the same file) normally just jumps to the location. When the link is
1079 activated with a C-u prefix (or with mouse-3), the link is displayed in
1080 another window. When this option is set, the other window actually displays
1081 an indirect buffer clone of the current buffer, to avoid any visibility
1082 changes to the current buffer."
1083 :group 'org-link-follow
1084 :type 'boolean)
1086 (defcustom org-open-non-existing-files nil
1087 "Non-nil means, `org-open-file' will open non-existing files.
1088 When nil, an error will be generated."
1089 :group 'org-link-follow
1090 :type 'boolean)
1092 (defcustom org-open-directory-means-index-dot-org nil
1093 "Non-nil means, a link to a directory really means to index.org.
1094 When nil, following a directory link will run dired or open a finder/explorer
1095 window on that directory."
1096 :group 'org-link-follow
1097 :type 'boolean)
1099 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1100 "Function and arguments to call for following mailto links.
1101 This is a list with the first element being a lisp function, and the
1102 remaining elements being arguments to the function. In string arguments,
1103 %a will be replaced by the address, and %s will be replaced by the subject
1104 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1105 :group 'org-link-follow
1106 :type '(choice
1107 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1108 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1109 (const :tag "message-mail" (message-mail "%a" "%s"))
1110 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1112 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1113 "Non-nil means, ask for confirmation before executing shell links.
1114 Shell links can be dangerous: just think about a link
1116 [[shell:rm -rf ~/*][Google Search]]
1118 This link would show up in your Org-mode document as \"Google Search\",
1119 but really it would remove your entire home directory.
1120 Therefore we advise against setting this variable to nil.
1121 Just change it to `y-or-n-p' of you want to confirm with a
1122 single keystroke rather than having to type \"yes\"."
1123 :group 'org-link-follow
1124 :type '(choice
1125 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1126 (const :tag "with y-or-n (faster)" y-or-n-p)
1127 (const :tag "no confirmation (dangerous)" nil)))
1129 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1130 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1131 Elisp links can be dangerous: just think about a link
1133 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1135 This link would show up in your Org-mode document as \"Google Search\",
1136 but really it would remove your entire home directory.
1137 Therefore we advise against setting this variable to nil.
1138 Just change it to `y-or-n-p' of you want to confirm with a
1139 single keystroke rather than having to type \"yes\"."
1140 :group 'org-link-follow
1141 :type '(choice
1142 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1143 (const :tag "with y-or-n (faster)" y-or-n-p)
1144 (const :tag "no confirmation (dangerous)" nil)))
1146 (defconst org-file-apps-defaults-gnu
1147 '((remote . emacs)
1148 (t . mailcap))
1149 "Default file applications on a UNIX or GNU/Linux system.
1150 See `org-file-apps'.")
1152 (defconst org-file-apps-defaults-macosx
1153 '((remote . emacs)
1154 (t . "open %s")
1155 ("ps" . "gv %s")
1156 ("ps.gz" . "gv %s")
1157 ("eps" . "gv %s")
1158 ("eps.gz" . "gv %s")
1159 ("dvi" . "xdvi %s")
1160 ("fig" . "xfig %s"))
1161 "Default file applications on a MacOS X system.
1162 The system \"open\" is known as a default, but we use X11 applications
1163 for some files for which the OS does not have a good default.
1164 See `org-file-apps'.")
1166 (defconst org-file-apps-defaults-windowsnt
1167 (list
1168 '(remote . emacs)
1169 (cons t
1170 (list (if (featurep 'xemacs)
1171 'mswindows-shell-execute
1172 'w32-shell-execute)
1173 "open" 'file)))
1174 "Default file applications on a Windows NT system.
1175 The system \"open\" is used for most files.
1176 See `org-file-apps'.")
1178 (defcustom org-file-apps
1180 ("txt" . emacs)
1181 ("tex" . emacs)
1182 ("ltx" . emacs)
1183 ("org" . emacs)
1184 ("el" . emacs)
1185 ("bib" . emacs)
1187 "External applications for opening `file:path' items in a document.
1188 Org-mode uses system defaults for different file types, but
1189 you can use this variable to set the application for a given file
1190 extension. The entries in this list are cons cells where the car identifies
1191 files and the cdr the corresponding command. Possible values for the
1192 file identifier are
1193 \"ext\" A string identifying an extension
1194 `directory' Matches a directory
1195 `remote' Matches a remote file, accessible through tramp or efs.
1196 Remote files most likely should be visited through Emacs
1197 because external applications cannot handle such paths.
1198 t Default for all remaining files
1200 Possible values for the command are:
1201 `emacs' The file will be visited by the current Emacs process.
1202 `default' Use the default application for this file type.
1203 string A command to be executed by a shell; %s will be replaced
1204 by the path to the file.
1205 sexp A Lisp form which will be evaluated. The file path will
1206 be available in the Lisp variable `file'.
1207 For more examples, see the system specific constants
1208 `org-file-apps-defaults-macosx'
1209 `org-file-apps-defaults-windowsnt'
1210 `org-file-apps-defaults-gnu'."
1211 :group 'org-link-follow
1212 :type '(repeat
1213 (cons (choice :value ""
1214 (string :tag "Extension")
1215 (const :tag "Default for unrecognized files" t)
1216 (const :tag "Remote file" remote)
1217 (const :tag "Links to a directory" directory))
1218 (choice :value ""
1219 (const :tag "Visit with Emacs" emacs)
1220 (const :tag "Use system default" default)
1221 (string :tag "Command")
1222 (sexp :tag "Lisp form")))))
1224 (defgroup org-refile nil
1225 "Options concerning refiling entries in Org-mode."
1226 :tag "Org Remember"
1227 :group 'org)
1229 (defcustom org-directory "~/org"
1230 "Directory with org files.
1231 This directory will be used as default to prompt for org files.
1232 Used by the hooks for remember.el."
1233 :group 'org-refile
1234 :group 'org-remember
1235 :type 'directory)
1237 (defcustom org-default-notes-file "~/.notes"
1238 "Default target for storing notes.
1239 Used by the hooks for remember.el. This can be a string, or nil to mean
1240 the value of `remember-data-file'.
1241 You can set this on a per-template basis with the variable
1242 `org-remember-templates'."
1243 :group 'org-refile
1244 :group 'org-remember
1245 :type '(choice
1246 (const :tag "Default from remember-data-file" nil)
1247 file))
1249 (defcustom org-goto-interface 'outline
1250 "The default interface to be used for `org-goto'.
1251 Allowed vaues are:
1252 outline The interface shows an outline of the relevant file
1253 and the correct heading is found by moving through
1254 the outline or by searching with incremental search.
1255 outline-path-completion Headlines in the current buffer are offered via
1256 completion."
1257 :group 'org-refile
1258 :type '(choice
1259 (const :tag "Outline" outline)
1260 (const :tag "Outline-path-completion" outline-path-completion)))
1262 (defcustom org-reverse-note-order nil
1263 "Non-nil means, store new notes at the beginning of a file or entry.
1264 When nil, new notes will be filed to the end of a file or entry.
1265 This can also be a list with cons cells of regular expressions that
1266 are matched against file names, and values."
1267 :group 'org-remember
1268 :type '(choice
1269 (const :tag "Reverse always" t)
1270 (const :tag "Reverse never" nil)
1271 (repeat :tag "By file name regexp"
1272 (cons regexp boolean))))
1274 (defcustom org-refile-targets nil
1275 "Targets for refiling entries with \\[org-refile].
1276 This is list of cons cells. Each cell contains:
1277 - a specification of the files to be considered, either a list of files,
1278 or a symbol whose function or variable value will be used to retrieve
1279 a file name or a list of file names. Nil means, refile to a different
1280 heading in the current buffer.
1281 - A specification of how to find candidate refile targets. This may be
1282 any of
1283 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1284 This tag has to be present in all target headlines, inheritance will
1285 not be considered.
1286 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1287 todo keyword.
1288 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1289 headlines that are refiling targets.
1290 - a cons cell (:level . N). Any headline of level N is considered a target.
1291 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1293 When this variable is nil, all top-level headlines in the current buffer
1294 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1295 :group 'org-remember
1296 :type '(repeat
1297 (cons
1298 (choice :value org-agenda-files
1299 (const :tag "All agenda files" org-agenda-files)
1300 (const :tag "Current buffer" nil)
1301 (function) (variable) (file))
1302 (choice :tag "Identify target headline by"
1303 (cons :tag "Specific tag" (const :tag) (string))
1304 (cons :tag "TODO keyword" (const :todo) (string))
1305 (cons :tag "Regular expression" (const :regexp) (regexp))
1306 (cons :tag "Level number" (const :level) (integer))
1307 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1309 (defcustom org-refile-use-outline-path nil
1310 "Non-nil means, provide refile targets as paths.
1311 So a level 3 headline will be available as level1/level2/level3.
1312 When the value is `file', also include the file name (without directory)
1313 into the path. When `full-file-path', include the full file path."
1314 :group 'org-remember
1315 :type '(choice
1316 (const :tag "Not" nil)
1317 (const :tag "Yes" t)
1318 (const :tag "Start with file name" file)
1319 (const :tag "Start with full file path" full-file-path)))
1321 (defgroup org-todo nil
1322 "Options concerning TODO items in Org-mode."
1323 :tag "Org TODO"
1324 :group 'org)
1326 (defgroup org-progress nil
1327 "Options concerning Progress logging in Org-mode."
1328 :tag "Org Progress"
1329 :group 'org-time)
1331 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1332 "List of TODO entry keyword sequences and their interpretation.
1333 \\<org-mode-map>This is a list of sequences.
1335 Each sequence starts with a symbol, either `sequence' or `type',
1336 indicating if the keywords should be interpreted as a sequence of
1337 action steps, or as different types of TODO items. The first
1338 keywords are states requiring action - these states will select a headline
1339 for inclusion into the global TODO list Org-mode produces. If one of
1340 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1341 signify that no further action is necessary. If \"|\" is not found,
1342 the last keyword is treated as the only DONE state of the sequence.
1344 The command \\[org-todo] cycles an entry through these states, and one
1345 additional state where no keyword is present. For details about this
1346 cycling, see the manual.
1348 TODO keywords and interpretation can also be set on a per-file basis with
1349 the special #+SEQ_TODO and #+TYP_TODO lines.
1351 Each keyword can optionally specify a character for fast state selection
1352 \(in combination with the variable `org-use-fast-todo-selection')
1353 and specifiers for state change logging, using the same syntax
1354 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1355 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1356 indicates to record a time stamp each time this state is selected.
1358 Each keyword may also specify if a timestamp or a note should be
1359 recorded when entering or leaving the state, by adding additional
1360 characters in the parenthesis after the keyword. This looks like this:
1361 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1362 record only the time of the state change. With X and Y being either
1363 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1364 Y when leaving the state if and only if the *target* state does not
1365 define X. You may omit any of the fast-selection key or X or /Y,
1366 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1368 For backward compatibility, this variable may also be just a list
1369 of keywords - in this case the interptetation (sequence or type) will be
1370 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1371 :group 'org-todo
1372 :group 'org-keywords
1373 :type '(choice
1374 (repeat :tag "Old syntax, just keywords"
1375 (string :tag "Keyword"))
1376 (repeat :tag "New syntax"
1377 (cons
1378 (choice
1379 :tag "Interpretation"
1380 (const :tag "Sequence (cycling hits every state)" sequence)
1381 (const :tag "Type (cycling directly to DONE)" type))
1382 (repeat
1383 (string :tag "Keyword"))))))
1385 (defvar org-todo-keywords-1 nil
1386 "All TODO and DONE keywords active in a buffer.")
1387 (make-variable-buffer-local 'org-todo-keywords-1)
1388 (defvar org-todo-keywords-for-agenda nil)
1389 (defvar org-done-keywords-for-agenda nil)
1390 (defvar org-todo-keyword-alist-for-agenda nil)
1391 (defvar org-tag-alist-for-agenda nil)
1392 (defvar org-agenda-contributing-files nil)
1393 (defvar org-not-done-keywords nil)
1394 (make-variable-buffer-local 'org-not-done-keywords)
1395 (defvar org-done-keywords nil)
1396 (make-variable-buffer-local 'org-done-keywords)
1397 (defvar org-todo-heads nil)
1398 (make-variable-buffer-local 'org-todo-heads)
1399 (defvar org-todo-sets nil)
1400 (make-variable-buffer-local 'org-todo-sets)
1401 (defvar org-todo-log-states nil)
1402 (make-variable-buffer-local 'org-todo-log-states)
1403 (defvar org-todo-kwd-alist nil)
1404 (make-variable-buffer-local 'org-todo-kwd-alist)
1405 (defvar org-todo-key-alist nil)
1406 (make-variable-buffer-local 'org-todo-key-alist)
1407 (defvar org-todo-key-trigger nil)
1408 (make-variable-buffer-local 'org-todo-key-trigger)
1410 (defcustom org-todo-interpretation 'sequence
1411 "Controls how TODO keywords are interpreted.
1412 This variable is in principle obsolete and is only used for
1413 backward compatibility, if the interpretation of todo keywords is
1414 not given already in `org-todo-keywords'. See that variable for
1415 more information."
1416 :group 'org-todo
1417 :group 'org-keywords
1418 :type '(choice (const sequence)
1419 (const type)))
1421 (defcustom org-use-fast-todo-selection 'prefix
1422 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1423 This variable describes if and under what circumstances the cycling
1424 mechanism for TODO keywords will be replaced by a single-key, direct
1425 selection scheme.
1427 When nil, fast selection is never used.
1429 When the symbol `prefix', it will be used when `org-todo' is called with
1430 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1431 in an agenda buffer.
1433 When t, fast selection is used by default. In this case, the prefix
1434 argument forces cycling instead.
1436 In all cases, the special interface is only used if access keys have actually
1437 been assigned by the user, i.e. if keywords in the configuration are followed
1438 by a letter in parenthesis, like TODO(t)."
1439 :group 'org-todo
1440 :type '(choice
1441 (const :tag "Never" nil)
1442 (const :tag "By default" t)
1443 (const :tag "Only with C-u C-c C-t" prefix)))
1445 (defcustom org-provide-todo-statistics t
1446 "Non-nil means, update todo statistics after insert and toggle.
1447 When this is set, todo statistics is updated in the parent of the current
1448 entry each time a todo state is changed."
1449 :group 'org-todo
1450 :type 'boolean)
1452 (defcustom org-after-todo-state-change-hook nil
1453 "Hook which is run after the state of a TODO item was changed.
1454 The new state (a string with a TODO keyword, or nil) is available in the
1455 Lisp variable `state'."
1456 :group 'org-todo
1457 :type 'hook)
1459 (defcustom org-log-done nil
1460 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1461 When equal to the list (done), also prompt for a closing note.
1462 This can also be configured on a per-file basis by adding one of
1463 the following lines anywhere in the buffer:
1465 #+STARTUP: logdone
1466 #+STARTUP: lognotedone
1467 #+STARTUP: nologdone"
1468 :group 'org-todo
1469 :group 'org-progress
1470 :type '(choice
1471 (const :tag "No logging" nil)
1472 (const :tag "Record CLOSED timestamp" time)
1473 (const :tag "Record CLOSED timestamp with closing note." note)))
1475 ;; Normalize old uses of org-log-done.
1476 (cond
1477 ((eq org-log-done t) (setq org-log-done 'time))
1478 ((and (listp org-log-done) (memq 'done org-log-done))
1479 (setq org-log-done 'note)))
1481 (defcustom org-log-note-clock-out nil
1482 "Non-nil means, record a note when clocking out of an item.
1483 This can also be configured on a per-file basis by adding one of
1484 the following lines anywhere in the buffer:
1486 #+STARTUP: lognoteclock-out
1487 #+STARTUP: nolognoteclock-out"
1488 :group 'org-todo
1489 :group 'org-progress
1490 :type 'boolean)
1492 (defcustom org-log-done-with-time t
1493 "Non-nil means, the CLOSED time stamp will contain date and time.
1494 When nil, only the date will be recorded."
1495 :group 'org-progress
1496 :type 'boolean)
1498 (defcustom org-log-note-headings
1499 '((done . "CLOSING NOTE %t")
1500 (state . "State %-12s %t")
1501 (note . "Note taken on %t")
1502 (clock-out . ""))
1503 "Headings for notes added to entries.
1504 The value is an alist, with the car being a symbol indicating the note
1505 context, and the cdr is the heading to be used. The heading may also be the
1506 empty string.
1507 %t in the heading will be replaced by a time stamp.
1508 %s will be replaced by the new TODO state, in double quotes.
1509 %u will be replaced by the user name.
1510 %U will be replaced by the full user name."
1511 :group 'org-todo
1512 :group 'org-progress
1513 :type '(list :greedy t
1514 (cons (const :tag "Heading when closing an item" done) string)
1515 (cons (const :tag
1516 "Heading when changing todo state (todo sequence only)"
1517 state) string)
1518 (cons (const :tag "Heading when just taking a note" note) string)
1519 (cons (const :tag "Heading when clocking out" clock-out) string)))
1521 (unless (assq 'note org-log-note-headings)
1522 (push '(note . "%t") org-log-note-headings))
1524 (defcustom org-log-states-order-reversed t
1525 "Non-nil means, the latest state change note will be directly after heading.
1526 When nil, the notes will be orderer according to time."
1527 :group 'org-todo
1528 :group 'org-progress
1529 :type 'boolean)
1531 (defcustom org-log-repeat 'time
1532 "Non-nil means, record moving through the DONE state when triggering repeat.
1533 An auto-repeating tasks is immediately switched back to TODO when marked
1534 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1535 the TODO keyword definition, or recording a closing note by setting
1536 `org-log-done', there will be no record of the task moving through DONE.
1537 This variable forces taking a note anyway. Possible values are:
1539 nil Don't force a record
1540 time Record a time stamp
1541 note Record a note
1543 This option can also be set with on a per-file-basis with
1545 #+STARTUP: logrepeat
1546 #+STARTUP: lognoterepeat
1547 #+STARTUP: nologrepeat
1549 You can have local logging settings for a subtree by setting the LOGGING
1550 property to one or more of these keywords."
1551 :group 'org-todo
1552 :group 'org-progress
1553 :type '(choice
1554 (const :tag "Don't force a record" nil)
1555 (const :tag "Force recording the DONE state" time)
1556 (const :tag "Force recording a note with the DONE state" note)))
1559 (defgroup org-priorities nil
1560 "Priorities in Org-mode."
1561 :tag "Org Priorities"
1562 :group 'org-todo)
1564 (defcustom org-highest-priority ?A
1565 "The highest priority of TODO items. A character like ?A, ?B etc.
1566 Must have a smaller ASCII number than `org-lowest-priority'."
1567 :group 'org-priorities
1568 :type 'character)
1570 (defcustom org-lowest-priority ?C
1571 "The lowest priority of TODO items. A character like ?A, ?B etc.
1572 Must have a larger ASCII number than `org-highest-priority'."
1573 :group 'org-priorities
1574 :type 'character)
1576 (defcustom org-default-priority ?B
1577 "The default priority of TODO items.
1578 This is the priority an item get if no explicit priority is given."
1579 :group 'org-priorities
1580 :type 'character)
1582 (defcustom org-priority-start-cycle-with-default t
1583 "Non-nil means, start with default priority when starting to cycle.
1584 When this is nil, the first step in the cycle will be (depending on the
1585 command used) one higher or lower that the default priority."
1586 :group 'org-priorities
1587 :type 'boolean)
1589 (defgroup org-time nil
1590 "Options concerning time stamps and deadlines in Org-mode."
1591 :tag "Org Time"
1592 :group 'org)
1594 (defcustom org-insert-labeled-timestamps-at-point nil
1595 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1596 When nil, these labeled time stamps are forces into the second line of an
1597 entry, just after the headline. When scheduling from the global TODO list,
1598 the time stamp will always be forced into the second line."
1599 :group 'org-time
1600 :type 'boolean)
1602 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1603 "Formats for `format-time-string' which are used for time stamps.
1604 It is not recommended to change this constant.")
1606 (defcustom org-time-stamp-rounding-minutes '(0 5)
1607 "Number of minutes to round time stamps to.
1608 These are two values, the first applies when first creating a time stamp.
1609 The second applies when changing it with the commands `S-up' and `S-down'.
1610 When changing the time stamp, this means that it will change in steps
1611 of N minutes, as given by the second value.
1613 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1614 numbers should be factors of 60, so for example 5, 10, 15.
1616 When this is larger than 1, you can still force an exact time-stamp by using
1617 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1618 and by using a prefix arg to `S-up/down' to specify the exact number
1619 of minutes to shift."
1620 :group 'org-time
1621 :get '(lambda (var) ; Make sure all entries have 5 elements
1622 (if (integerp (default-value var))
1623 (list (default-value var) 5)
1624 (default-value var)))
1625 :type '(list
1626 (integer :tag "when inserting times")
1627 (integer :tag "when modifying times")))
1629 ;; Normalize old customizations of this variable.
1630 (when (integerp org-time-stamp-rounding-minutes)
1631 (setq org-time-stamp-rounding-minutes
1632 (list org-time-stamp-rounding-minutes
1633 org-time-stamp-rounding-minutes)))
1635 (defcustom org-display-custom-times nil
1636 "Non-nil means, overlay custom formats over all time stamps.
1637 The formats are defined through the variable `org-time-stamp-custom-formats'.
1638 To turn this on on a per-file basis, insert anywhere in the file:
1639 #+STARTUP: customtime"
1640 :group 'org-time
1641 :set 'set-default
1642 :type 'sexp)
1643 (make-variable-buffer-local 'org-display-custom-times)
1645 (defcustom org-time-stamp-custom-formats
1646 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1647 "Custom formats for time stamps. See `format-time-string' for the syntax.
1648 These are overlayed over the default ISO format if the variable
1649 `org-display-custom-times' is set. Time like %H:%M should be at the
1650 end of the second format."
1651 :group 'org-time
1652 :type 'sexp)
1654 (defun org-time-stamp-format (&optional long inactive)
1655 "Get the right format for a time string."
1656 (let ((f (if long (cdr org-time-stamp-formats)
1657 (car org-time-stamp-formats))))
1658 (if inactive
1659 (concat "[" (substring f 1 -1) "]")
1660 f)))
1662 (defcustom org-time-clocksum-format "%d:%02d"
1663 "The format string used when creating CLOCKSUM lines, or when
1664 org-mode generates a time duration."
1665 :group 'org-time
1666 :type 'string)
1668 (defcustom org-deadline-warning-days 14
1669 "No. of days before expiration during which a deadline becomes active.
1670 This variable governs the display in sparse trees and in the agenda.
1671 When 0 or negative, it means use this number (the absolute value of it)
1672 even if a deadline has a different individual lead time specified."
1673 :group 'org-time
1674 :group 'org-agenda-daily/weekly
1675 :type 'number)
1677 (defcustom org-read-date-prefer-future t
1678 "Non-nil means, assume future for incomplete date input from user.
1679 This affects the following situations:
1680 1. The user gives a day, but no month.
1681 For example, if today is the 15th, and you enter \"3\", Org-mode will
1682 read this as the third of *next* month. However, if you enter \"17\",
1683 it will be considered as *this* month.
1684 2. The user gives a month but not a year.
1685 For example, if it is april and you enter \"feb 2\", this will be read
1686 as feb 2, *next* year. \"May 5\", however, will be this year.
1688 Currently this does not work for ISO week specifications.
1690 When this option is nil, the current month and year will always be used
1691 as defaults."
1692 :group 'org-time
1693 :type 'boolean)
1695 (defcustom org-read-date-display-live t
1696 "Non-nil means, display current interpretation of date prompt live.
1697 This display will be in an overlay, in the minibuffer."
1698 :group 'org-time
1699 :type 'boolean)
1701 (defcustom org-read-date-popup-calendar t
1702 "Non-nil means, pop up a calendar when prompting for a date.
1703 In the calendar, the date can be selected with mouse-1. However, the
1704 minibuffer will also be active, and you can simply enter the date as well.
1705 When nil, only the minibuffer will be available."
1706 :group 'org-time
1707 :type 'boolean)
1708 (if (fboundp 'defvaralias)
1709 (defvaralias 'org-popup-calendar-for-date-prompt
1710 'org-read-date-popup-calendar))
1712 (defcustom org-extend-today-until 0
1713 "The hour when your day really ends. Must be an integer.
1714 This has influence for the following applications:
1715 - When switching the agenda to \"today\". It it is still earlier than
1716 the time given here, the day recognized as TODAY is actually yesterday.
1717 - When a date is read from the user and it is still before the time given
1718 here, the current date and time will be assumed to be yesterday, 23:59.
1719 Also, timestamps inserted in remember templates follow this rule.
1721 IMPORTANT: This is a feature whose implementation is and likely will
1722 remain incomplete. Really, it is only here because past midnight seems to
1723 ne the favorite working time of John Wiegley :-)"
1724 :group 'org-time
1725 :type 'number)
1727 (defcustom org-edit-timestamp-down-means-later nil
1728 "Non-nil means, S-down will increase the time in a time stamp.
1729 When nil, S-up will increase."
1730 :group 'org-time
1731 :type 'boolean)
1733 (defcustom org-calendar-follow-timestamp-change t
1734 "Non-nil means, make the calendar window follow timestamp changes.
1735 When a timestamp is modified and the calendar window is visible, it will be
1736 moved to the new date."
1737 :group 'org-time
1738 :type 'boolean)
1740 (defgroup org-tags nil
1741 "Options concerning tags in Org-mode."
1742 :tag "Org Tags"
1743 :group 'org)
1745 (defcustom org-tag-alist nil
1746 "List of tags allowed in Org-mode files.
1747 When this list is nil, Org-mode will base TAG input on what is already in the
1748 buffer.
1749 The value of this variable is an alist, the car of each entry must be a
1750 keyword as a string, the cdr may be a character that is used to select
1751 that tag through the fast-tag-selection interface.
1752 See the manual for details."
1753 :group 'org-tags
1754 :type '(repeat
1755 (choice
1756 (cons (string :tag "Tag name")
1757 (character :tag "Access char"))
1758 (const :tag "Start radio group" (:startgroup))
1759 (const :tag "End radio group" (:endgroup)))))
1761 (defvar org-file-tags nil
1762 "List of tags that can be inherited by all entries in the file.
1763 The tags will be inherited if the variable `org-use-tag-inheritance'
1764 says they should be.
1765 This variable is populated from #+TAG lines.")
1767 (defcustom org-use-fast-tag-selection 'auto
1768 "Non-nil means, use fast tag selection scheme.
1769 This is a special interface to select and deselect tags with single keys.
1770 When nil, fast selection is never used.
1771 When the symbol `auto', fast selection is used if and only if selection
1772 characters for tags have been configured, either through the variable
1773 `org-tag-alist' or through a #+TAGS line in the buffer.
1774 When t, fast selection is always used and selection keys are assigned
1775 automatically if necessary."
1776 :group 'org-tags
1777 :type '(choice
1778 (const :tag "Always" t)
1779 (const :tag "Never" nil)
1780 (const :tag "When selection characters are configured" 'auto)))
1782 (defcustom org-fast-tag-selection-single-key nil
1783 "Non-nil means, fast tag selection exits after first change.
1784 When nil, you have to press RET to exit it.
1785 During fast tag selection, you can toggle this flag with `C-c'.
1786 This variable can also have the value `expert'. In this case, the window
1787 displaying the tags menu is not even shown, until you press C-c again."
1788 :group 'org-tags
1789 :type '(choice
1790 (const :tag "No" nil)
1791 (const :tag "Yes" t)
1792 (const :tag "Expert" expert)))
1794 (defvar org-fast-tag-selection-include-todo nil
1795 "Non-nil means, fast tags selection interface will also offer TODO states.
1796 This is an undocumented feature, you should not rely on it.")
1798 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1799 "The column to which tags should be indented in a headline.
1800 If this number is positive, it specifies the column. If it is negative,
1801 it means that the tags should be flushright to that column. For example,
1802 -80 works well for a normal 80 character screen."
1803 :group 'org-tags
1804 :type 'integer)
1806 (defcustom org-auto-align-tags t
1807 "Non-nil means, realign tags after pro/demotion of TODO state change.
1808 These operations change the length of a headline and therefore shift
1809 the tags around. With this options turned on, after each such operation
1810 the tags are again aligned to `org-tags-column'."
1811 :group 'org-tags
1812 :type 'boolean)
1814 (defcustom org-use-tag-inheritance t
1815 "Non-nil means, tags in levels apply also for sublevels.
1816 When nil, only the tags directly given in a specific line apply there.
1817 If this option is t, a match early-on in a tree can lead to a large
1818 number of matches in the subtree. If you only want to see the first
1819 match in a tree during a search, check out the variable
1820 `org-tags-match-list-sublevels'.
1822 This may also be a list of tags that should be inherited, or a regexp that
1823 matches tags that should be inherited."
1824 :group 'org-tags
1825 :type '(choice
1826 (const :tag "Not" nil)
1827 (const :tag "Always" t)
1828 (repeat :tag "Specific tags" (string :tag "Tag"))
1829 (regexp :tag "Tags matched by regexp")))
1831 (defun org-tag-inherit-p (tag)
1832 "Check if TAG is one that should be inherited."
1833 (cond
1834 ((eq org-use-tag-inheritance t) t)
1835 ((not org-use-tag-inheritance) nil)
1836 ((stringp org-use-tag-inheritance)
1837 (string-match org-use-tag-inheritance tag))
1838 ((listp org-use-tag-inheritance)
1839 (member tag org-use-tag-inheritance))
1840 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1842 (defcustom org-tags-match-list-sublevels t
1843 "Non-nil means list also sublevels of headlines matching tag search.
1844 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1845 the sublevels of a headline matching a tag search often also match
1846 the same search. Listing all of them can create very long lists.
1847 Setting this variable to nil causes subtrees of a match to be skipped.
1848 This option is off by default, because inheritance in on. If you turn
1849 inheritance off, you very likely want to turn this option on.
1851 As a special case, if the tag search is restricted to TODO items, the
1852 value of this variable is ignored and sublevels are always checked, to
1853 make sure all corresponding TODO items find their way into the list."
1854 :group 'org-tags
1855 :type 'boolean)
1857 (defvar org-tags-history nil
1858 "History of minibuffer reads for tags.")
1859 (defvar org-last-tags-completion-table nil
1860 "The last used completion table for tags.")
1861 (defvar org-after-tags-change-hook nil
1862 "Hook that is run after the tags in a line have changed.")
1864 (defgroup org-properties nil
1865 "Options concerning properties in Org-mode."
1866 :tag "Org Properties"
1867 :group 'org)
1869 (defcustom org-property-format "%-10s %s"
1870 "How property key/value pairs should be formatted by `indent-line'.
1871 When `indent-line' hits a property definition, it will format the line
1872 according to this format, mainly to make sure that the values are
1873 lined-up with respect to each other."
1874 :group 'org-properties
1875 :type 'string)
1877 (defcustom org-use-property-inheritance nil
1878 "Non-nil means, properties apply also for sublevels.
1880 This setting is chiefly used during property searches. Turning it on can
1881 cause significant overhead when doing a search, which is why it is not
1882 on by default.
1884 When nil, only the properties directly given in the current entry count.
1885 When t, every property is inherited. The value may also be a list of
1886 properties that should have inheritance, or a regular expression matching
1887 properties that should be inherited.
1889 However, note that some special properties use inheritance under special
1890 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1891 and the properties ending in \"_ALL\" when they are used as descriptor
1892 for valid values of a property.
1894 Note for programmers:
1895 When querying an entry with `org-entry-get', you can control if inheritance
1896 should be used. By default, `org-entry-get' looks only at the local
1897 properties. You can request inheritance by setting the inherit argument
1898 to t (to force inheritance) or to `selective' (to respect the setting
1899 in this variable)."
1900 :group 'org-properties
1901 :type '(choice
1902 (const :tag "Not" nil)
1903 (const :tag "Always" t)
1904 (repeat :tag "Specific properties" (string :tag "Property"))
1905 (regexp :tag "Properties matched by regexp")))
1907 (defun org-property-inherit-p (property)
1908 "Check if PROPERTY is one that should be inherited."
1909 (cond
1910 ((eq org-use-property-inheritance t) t)
1911 ((not org-use-property-inheritance) nil)
1912 ((stringp org-use-property-inheritance)
1913 (string-match org-use-property-inheritance property))
1914 ((listp org-use-property-inheritance)
1915 (member property org-use-property-inheritance))
1916 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1918 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1919 "The default column format, if no other format has been defined.
1920 This variable can be set on the per-file basis by inserting a line
1922 #+COLUMNS: %25ITEM ....."
1923 :group 'org-properties
1924 :type 'string)
1926 (defcustom org-columns-ellipses ".."
1927 "The ellipses to be used when a field in column view is truncated.
1928 When this is the empty string, as many characters as possible are shown,
1929 but then there will be no visual indication that the field has been truncated.
1930 When this is a string of length N, the last N characters of a truncated
1931 field are replaced by this string. If the column is narrower than the
1932 ellipses string, only part of the ellipses string will be shown."
1933 :group 'org-properties
1934 :type 'string)
1936 (defcustom org-columns-modify-value-for-display-function nil
1937 "Function that modifies values for display in column view.
1938 For example, it can be used to cut out a certain part from a time stamp.
1939 The function must take 2 argments:
1941 column-title The tite of the column (*not* the property name)
1942 value The value that should be modified.
1944 The function should return the value that should be displayed,
1945 or nil if the normal value should be used."
1946 :group 'org-properties
1947 :type 'function)
1949 (defcustom org-effort-property "Effort"
1950 "The property that is being used to keep track of effort estimates.
1951 Effort estimates given in this property need to have the format H:MM."
1952 :group 'org-properties
1953 :group 'org-progress
1954 :type '(string :tag "Property"))
1956 (defconst org-global-properties-fixed
1957 '(("VISIBILITY_ALL" . "folded children content all"))
1958 "List of property/value pairs that can be inherited by any entry.
1959 These are fixed values, for the preset properties.")
1962 (defcustom org-global-properties nil
1963 "List of property/value pairs that can be inherited by any entry.
1964 You can set buffer-local values for this by adding lines like
1966 #+PROPERTY: NAME VALUE"
1967 :group 'org-properties
1968 :type '(repeat
1969 (cons (string :tag "Property")
1970 (string :tag "Value"))))
1972 (defvar org-file-properties nil
1973 "List of property/value pairs that can be inherited by any entry.
1974 Valid for the current buffer.
1975 This variable is populated from #+PROPERTY lines.")
1976 (make-variable-buffer-local 'org-file-properties)
1978 (defgroup org-agenda nil
1979 "Options concerning agenda views in Org-mode."
1980 :tag "Org Agenda"
1981 :group 'org)
1983 (defvar org-category nil
1984 "Variable used by org files to set a category for agenda display.
1985 Such files should use a file variable to set it, for example
1987 # -*- mode: org; org-category: \"ELisp\"
1989 or contain a special line
1991 #+CATEGORY: ELisp
1993 If the file does not specify a category, then file's base name
1994 is used instead.")
1995 (make-variable-buffer-local 'org-category)
1996 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1998 (defcustom org-agenda-files nil
1999 "The files to be used for agenda display.
2000 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2001 \\[org-remove-file]. You can also use customize to edit the list.
2003 If an entry is a directory, all files in that directory that are matched by
2004 `org-agenda-file-regexp' will be part of the file list.
2006 If the value of the variable is not a list but a single file name, then
2007 the list of agenda files is actually stored and maintained in that file, one
2008 agenda file per line."
2009 :group 'org-agenda
2010 :type '(choice
2011 (repeat :tag "List of files and directories" file)
2012 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2014 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2015 "Regular expression to match files for `org-agenda-files'.
2016 If any element in the list in that variable contains a directory instead
2017 of a normal file, all files in that directory that are matched by this
2018 regular expression will be included."
2019 :group 'org-agenda
2020 :type 'regexp)
2022 (defcustom org-agenda-text-search-extra-files nil
2023 "List of extra files to be searched by text search commands.
2024 These files will be search in addition to the agenda files by the
2025 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2026 Note that these files will only be searched for text search commands,
2027 not for the other agenda views like todo lists, tag searches or the weekly
2028 agenda. This variable is intended to list notes and possibly archive files
2029 that should also be searched by these two commands.
2030 In fact, if the first element in the list is the symbol `agenda-archives',
2031 than all archive files of all agenda files will be added to the search
2032 scope."
2033 :group 'org-agenda
2034 :type '(set :greedy t
2035 (const :tag "Agenda Archives" agenda-archives)
2036 (repeat :inline t (file))))
2038 (if (fboundp 'defvaralias)
2039 (defvaralias 'org-agenda-multi-occur-extra-files
2040 'org-agenda-text-search-extra-files))
2042 (defcustom org-agenda-skip-unavailable-files nil
2043 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2044 A nil value means to remove them, after a query, from the list."
2045 :group 'org-agenda
2046 :type 'boolean)
2048 (defcustom org-calendar-to-agenda-key [?c]
2049 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2050 The command `org-calendar-goto-agenda' will be bound to this key. The
2051 default is the character `c' because then `c' can be used to switch back and
2052 forth between agenda and calendar."
2053 :group 'org-agenda
2054 :type 'sexp)
2056 (defcustom org-calendar-agenda-action-key [?k]
2057 "The key to be installed in `calendar-mode-map' for agenda-action.
2058 The command `org-agenda-action' will be bound to this key. The
2059 default is the character `k' because we use the same key in the agenda."
2060 :group 'org-agenda
2061 :type 'sexp)
2063 (eval-after-load "calendar"
2064 '(progn
2065 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2066 'org-calendar-goto-agenda)
2067 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2068 'org-agenda-action)))
2070 (defgroup org-latex nil
2071 "Options for embedding LaTeX code into Org-mode."
2072 :tag "Org LaTeX"
2073 :group 'org)
2075 (defcustom org-format-latex-options
2076 '(:foreground default :background default :scale 1.0
2077 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2078 :matchers ("begin" "$" "$$" "\\(" "\\["))
2079 "Options for creating images from LaTeX fragments.
2080 This is a property list with the following properties:
2081 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2082 `default' means use the foreground of the default face.
2083 :background the background color, or \"Transparent\".
2084 `default' means use the background of the default face.
2085 :scale a scaling factor for the size of the images.
2086 :html-foreground, :html-background, :html-scale
2087 the same numbers for HTML export.
2088 :matchers a list indicating which matchers should be used to
2089 find LaTeX fragments. Valid members of this list are:
2090 \"begin\" find environments
2091 \"$\" find math expressions surrounded by $...$
2092 \"$$\" find math expressions surrounded by $$....$$
2093 \"\\(\" find math expressions surrounded by \\(...\\)
2094 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2095 :group 'org-latex
2096 :type 'plist)
2098 (defcustom org-format-latex-header "\\documentclass{article}
2099 \\usepackage{fullpage} % do not remove
2100 \\usepackage{amssymb}
2101 \\usepackage[usenames]{color}
2102 \\usepackage{amsmath}
2103 \\usepackage{latexsym}
2104 \\usepackage[mathscr]{eucal}
2105 \\pagestyle{empty} % do not remove"
2106 "The document header used for processing LaTeX fragments."
2107 :group 'org-latex
2108 :type 'string)
2111 (defgroup org-font-lock nil
2112 "Font-lock settings for highlighting in Org-mode."
2113 :tag "Org Font Lock"
2114 :group 'org)
2116 (defcustom org-level-color-stars-only nil
2117 "Non-nil means fontify only the stars in each headline.
2118 When nil, the entire headline is fontified.
2119 Changing it requires restart of `font-lock-mode' to become effective
2120 also in regions already fontified."
2121 :group 'org-font-lock
2122 :type 'boolean)
2124 (defcustom org-hide-leading-stars nil
2125 "Non-nil means, hide the first N-1 stars in a headline.
2126 This works by using the face `org-hide' for these stars. This
2127 face is white for a light background, and black for a dark
2128 background. You may have to customize the face `org-hide' to
2129 make this work.
2130 Changing it requires restart of `font-lock-mode' to become effective
2131 also in regions already fontified.
2132 You may also set this on a per-file basis by adding one of the following
2133 lines to the buffer:
2135 #+STARTUP: hidestars
2136 #+STARTUP: showstars"
2137 :group 'org-font-lock
2138 :type 'boolean)
2140 (defcustom org-fontify-done-headline nil
2141 "Non-nil means, change the face of a headline if it is marked DONE.
2142 Normally, only the TODO/DONE keyword indicates the state of a headline.
2143 When this is non-nil, the headline after the keyword is set to the
2144 `org-headline-done' as an additional indication."
2145 :group 'org-font-lock
2146 :type 'boolean)
2148 (defcustom org-fontify-emphasized-text t
2149 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2150 Changing this variable requires a restart of Emacs to take effect."
2151 :group 'org-font-lock
2152 :type 'boolean)
2154 (defcustom org-highlight-latex-fragments-and-specials nil
2155 "Non-nil means, fontify what is treated specially by the exporters."
2156 :group 'org-font-lock
2157 :type 'boolean)
2159 (defcustom org-hide-emphasis-markers nil
2160 "Non-nil mean font-lock should hide the emphasis marker characters."
2161 :group 'org-font-lock
2162 :type 'boolean)
2164 (defvar org-emph-re nil
2165 "Regular expression for matching emphasis.")
2166 (defvar org-verbatim-re nil
2167 "Regular expression for matching verbatim text.")
2168 (defvar org-emphasis-regexp-components) ; defined just below
2169 (defvar org-emphasis-alist) ; defined just below
2170 (defun org-set-emph-re (var val)
2171 "Set variable and compute the emphasis regular expression."
2172 (set var val)
2173 (when (and (boundp 'org-emphasis-alist)
2174 (boundp 'org-emphasis-regexp-components)
2175 org-emphasis-alist org-emphasis-regexp-components)
2176 (let* ((e org-emphasis-regexp-components)
2177 (pre (car e))
2178 (post (nth 1 e))
2179 (border (nth 2 e))
2180 (body (nth 3 e))
2181 (nl (nth 4 e))
2182 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2183 (body1 (concat body "*?"))
2184 (markers (mapconcat 'car org-emphasis-alist ""))
2185 (vmarkers (mapconcat
2186 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2187 org-emphasis-alist "")))
2188 ;; make sure special characters appear at the right position in the class
2189 (if (string-match "\\^" markers)
2190 (setq markers (concat (replace-match "" t t markers) "^")))
2191 (if (string-match "-" markers)
2192 (setq markers (concat (replace-match "" t t markers) "-")))
2193 (if (string-match "\\^" vmarkers)
2194 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2195 (if (string-match "-" vmarkers)
2196 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2197 (if (> nl 0)
2198 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2199 (int-to-string nl) "\\}")))
2200 ;; Make the regexp
2201 (setq org-emph-re
2202 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2203 "\\("
2204 "\\([" markers "]\\)"
2205 "\\("
2206 "[^" border "]\\|"
2207 "[^" border (if (and nil stacked) markers) "]"
2208 body1
2209 "[^" border (if (and nil stacked) markers) "]"
2210 "\\)"
2211 "\\3\\)"
2212 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2213 (setq org-verbatim-re
2214 (concat "\\([" pre "]\\|^\\)"
2215 "\\("
2216 "\\([" vmarkers "]\\)"
2217 "\\("
2218 "[^" border "]\\|"
2219 "[^" border "]"
2220 body1
2221 "[^" border "]"
2222 "\\)"
2223 "\\3\\)"
2224 "\\([" post "]\\|$\\)")))))
2226 (defcustom org-emphasis-regexp-components
2227 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2228 "Components used to build the regular expression for emphasis.
2229 This is a list with 6 entries. Terminology: In an emphasis string
2230 like \" *strong word* \", we call the initial space PREMATCH, the final
2231 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2232 and \"trong wor\" is the body. The different components in this variable
2233 specify what is allowed/forbidden in each part:
2235 pre Chars allowed as prematch. Beginning of line will be allowed too.
2236 post Chars allowed as postmatch. End of line will be allowed too.
2237 border The chars *forbidden* as border characters.
2238 body-regexp A regexp like \".\" to match a body character. Don't use
2239 non-shy groups here, and don't allow newline here.
2240 newline The maximum number of newlines allowed in an emphasis exp.
2242 Use customize to modify this, or restart Emacs after changing it."
2243 :group 'org-font-lock
2244 :set 'org-set-emph-re
2245 :type '(list
2246 (sexp :tag "Allowed chars in pre ")
2247 (sexp :tag "Allowed chars in post ")
2248 (sexp :tag "Forbidden chars in border ")
2249 (sexp :tag "Regexp for body ")
2250 (integer :tag "number of newlines allowed")
2251 (option (boolean :tag "Please ignore this button"))))
2253 (defcustom org-emphasis-alist
2254 `(("*" bold "<b>" "</b>")
2255 ("/" italic "<i>" "</i>")
2256 ("_" underline "<u>" "</u>")
2257 ("=" org-code "<code>" "</code>" verbatim)
2258 ("~" org-verbatim "" "" verbatim)
2259 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2260 "<del>" "</del>")
2262 "Special syntax for emphasized text.
2263 Text starting and ending with a special character will be emphasized, for
2264 example *bold*, _underlined_ and /italic/. This variable sets the marker
2265 characters, the face to be used by font-lock for highlighting in Org-mode
2266 Emacs buffers, and the HTML tags to be used for this.
2267 Use customize to modify this, or restart Emacs after changing it."
2268 :group 'org-font-lock
2269 :set 'org-set-emph-re
2270 :type '(repeat
2271 (list
2272 (string :tag "Marker character")
2273 (choice
2274 (face :tag "Font-lock-face")
2275 (plist :tag "Face property list"))
2276 (string :tag "HTML start tag")
2277 (string :tag "HTML end tag")
2278 (option (const verbatim)))))
2280 ;;; Miscellaneous options
2282 (defgroup org-completion nil
2283 "Completion in Org-mode."
2284 :tag "Org Completion"
2285 :group 'org)
2287 (defcustom org-completion-fallback-command 'hippie-expand
2288 "The expansion command called by \\[org-complete] in normal context.
2289 Normal means, no org-mode-specific context."
2290 :group 'org-completion
2291 :type 'function)
2293 ;;; Functions and variables from ther packages
2294 ;; Declared here to avoid compiler warnings
2296 ;; XEmacs only
2297 (defvar outline-mode-menu-heading)
2298 (defvar outline-mode-menu-show)
2299 (defvar outline-mode-menu-hide)
2300 (defvar zmacs-regions) ; XEmacs regions
2302 ;; Emacs only
2303 (defvar mark-active)
2305 ;; Various packages
2306 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2307 (declare-function calendar-forward-day "cal-move" (arg))
2308 (declare-function calendar-goto-date "cal-move" (date))
2309 (declare-function calendar-goto-today "cal-move" ())
2310 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2311 (defvar calc-embedded-close-formula)
2312 (defvar calc-embedded-open-formula)
2313 (declare-function cdlatex-tab "ext:cdlatex" ())
2314 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2315 (defvar font-lock-unfontify-region-function)
2316 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2317 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2318 (defvar iswitchb-temp-buflist)
2319 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2320 (declare-function org-agenda-skip "org-agenda" ())
2321 (declare-function org-format-agenda-item "org-agenda"
2322 (extra txt &optional category tags dotime noprefix remove-re))
2323 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2324 (declare-function org-agenda-change-all-lines "org-agenda"
2325 (newhead hdmarker &optional fixface))
2326 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2327 (declare-function org-agenda-maybe-redo "org-agenda" ())
2328 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2329 (beg end))
2330 (declare-function parse-time-string "parse-time" (string))
2331 (declare-function remember "remember" (&optional initial))
2332 (declare-function remember-buffer-desc "remember" ())
2333 (declare-function remember-finalize "remember" ())
2334 (defvar remember-save-after-remembering)
2335 (defvar remember-data-file)
2336 (defvar remember-register)
2337 (defvar remember-buffer)
2338 (defvar remember-handler-functions)
2339 (defvar remember-annotation-functions)
2340 (defvar texmathp-why)
2341 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2342 (declare-function table--at-cell-p "table" (position &optional object at-column))
2344 (defvar w3m-current-url)
2345 (defvar w3m-current-title)
2347 (defvar org-latex-regexps)
2349 ;;; Autoload and prepare some org modules
2351 ;; Some table stuff that needs to be defined here, because it is used
2352 ;; by the functions setting up org-mode or checking for table context.
2354 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2355 "Detects an org-type or table-type table.")
2356 (defconst org-table-line-regexp "^[ \t]*|"
2357 "Detects an org-type table line.")
2358 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2359 "Detects an org-type table line.")
2360 (defconst org-table-hline-regexp "^[ \t]*|-"
2361 "Detects an org-type table hline.")
2362 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2363 "Detects a table-type table hline.")
2364 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2365 "Searching from within a table (any type) this finds the first line
2366 outside the table.")
2368 ;; Autoload the functions in org-table.el that are needed by functions here.
2370 (eval-and-compile
2371 (org-autoload "org-table"
2372 '(org-table-align org-table-begin org-table-blank-field
2373 org-table-convert org-table-convert-region org-table-copy-down
2374 org-table-copy-region org-table-create
2375 org-table-create-or-convert-from-region
2376 org-table-create-with-table.el org-table-current-dline
2377 org-table-cut-region org-table-delete-column org-table-edit-field
2378 org-table-edit-formulas org-table-end org-table-eval-formula
2379 org-table-export org-table-field-info
2380 org-table-get-stored-formulas org-table-goto-column
2381 org-table-hline-and-move org-table-import org-table-insert-column
2382 org-table-insert-hline org-table-insert-row org-table-iterate
2383 org-table-justify-field-maybe org-table-kill-row
2384 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2385 org-table-move-column org-table-move-column-left
2386 org-table-move-column-right org-table-move-row
2387 org-table-move-row-down org-table-move-row-up
2388 org-table-next-field org-table-next-row org-table-paste-rectangle
2389 org-table-previous-field org-table-recalculate
2390 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2391 org-table-toggle-coordinate-overlays
2392 org-table-toggle-formula-debugger org-table-wrap-region
2393 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2395 (defun org-at-table-p (&optional table-type)
2396 "Return t if the cursor is inside an org-type table.
2397 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2398 (if org-enable-table-editor
2399 (save-excursion
2400 (beginning-of-line 1)
2401 (looking-at (if table-type org-table-any-line-regexp
2402 org-table-line-regexp)))
2403 nil))
2404 (defsubst org-table-p () (org-at-table-p))
2406 (defun org-at-table.el-p ()
2407 "Return t if and only if we are at a table.el table."
2408 (and (org-at-table-p 'any)
2409 (save-excursion
2410 (goto-char (org-table-begin 'any))
2411 (looking-at org-table1-hline-regexp))))
2412 (defun org-table-recognize-table.el ()
2413 "If there is a table.el table nearby, recognize it and move into it."
2414 (if org-table-tab-recognizes-table.el
2415 (if (org-at-table.el-p)
2416 (progn
2417 (beginning-of-line 1)
2418 (if (looking-at org-table-dataline-regexp)
2420 (if (looking-at org-table1-hline-regexp)
2421 (progn
2422 (beginning-of-line 2)
2423 (if (looking-at org-table-any-border-regexp)
2424 (beginning-of-line -1)))))
2425 (if (re-search-forward "|" (org-table-end t) t)
2426 (progn
2427 (require 'table)
2428 (if (table--at-cell-p (point))
2430 (message "recognizing table.el table...")
2431 (table-recognize-table)
2432 (message "recognizing table.el table...done")))
2433 (error "This should not happen..."))
2435 nil)
2436 nil))
2438 (defun org-at-table-hline-p ()
2439 "Return t if the cursor is inside a hline in a table."
2440 (if org-enable-table-editor
2441 (save-excursion
2442 (beginning-of-line 1)
2443 (looking-at org-table-hline-regexp))
2444 nil))
2446 (defvar org-table-clean-did-remove-column nil)
2448 (defun org-table-map-tables (function)
2449 "Apply FUNCTION to the start of all tables in the buffer."
2450 (save-excursion
2451 (save-restriction
2452 (widen)
2453 (goto-char (point-min))
2454 (while (re-search-forward org-table-any-line-regexp nil t)
2455 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2456 (beginning-of-line 1)
2457 (if (looking-at org-table-line-regexp)
2458 (save-excursion (funcall function)))
2459 (re-search-forward org-table-any-border-regexp nil 1))))
2460 (message "Mapping tables: done"))
2462 ;; Declare and autoload functions from org-exp.el
2464 (declare-function org-default-export-plist "org-exp")
2465 (declare-function org-infile-export-plist "org-exp")
2466 (declare-function org-get-current-options "org-exp")
2467 (eval-and-compile
2468 (org-autoload "org-exp"
2469 '(org-export org-export-as-ascii org-export-visible
2470 org-insert-export-options-template org-export-as-html-and-open
2471 org-export-as-html-batch org-export-as-html-to-buffer
2472 org-replace-region-by-html org-export-region-as-html
2473 org-export-as-html org-export-icalendar-this-file
2474 org-export-icalendar-all-agenda-files
2475 org-table-clean-before-export
2476 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2478 ;; Declare and autoload functions from org-exp.el
2480 (eval-and-compile
2481 (org-autoload "org-exp"
2482 '(org-agenda org-agenda-list org-search-view
2483 org-todo-list org-tags-view org-agenda-list-stuck-projects
2484 org-diary org-agenda-to-appt)))
2486 ;; Autoload org-remember
2488 (eval-and-compile
2489 (org-autoload "org-remember"
2490 '(org-remember-insinuate org-remember-annotation
2491 org-remember-apply-template org-remember org-remember-handler)))
2493 ;; Autoload org-clock.el
2496 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2497 (beg end))
2498 (declare-function org-update-mode-line "org-clock" ())
2499 (defvar org-clock-start-time)
2500 (defvar org-clock-marker (make-marker)
2501 "Marker recording the last clock-in.")
2503 (eval-and-compile
2504 (org-autoload
2505 "org-clock"
2506 '(org-clock-in org-clock-out org-clock-cancel
2507 org-clock-goto org-clock-sum org-clock-display
2508 org-remove-clock-overlays org-clock-report
2509 org-clocktable-shift org-dblock-write:clocktable
2510 org-get-clocktable)))
2512 (defun org-clock-update-time-maybe ()
2513 "If this is a CLOCK line, update it and return t.
2514 Otherwise, return nil."
2515 (interactive)
2516 (save-excursion
2517 (beginning-of-line 1)
2518 (skip-chars-forward " \t")
2519 (when (looking-at org-clock-string)
2520 (let ((re (concat "[ \t]*" org-clock-string
2521 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2522 "\\([ \t]*=>.*\\)?\\)?"))
2523 ts te h m s)
2524 (cond
2525 ((not (looking-at re))
2526 nil)
2527 ((not (match-end 2))
2528 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2529 (> org-clock-marker (point))
2530 (<= org-clock-marker (point-at-eol)))
2531 ;; The clock is running here
2532 (setq org-clock-start-time
2533 (apply 'encode-time
2534 (org-parse-time-string (match-string 1))))
2535 (org-update-mode-line)))
2537 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2538 (end-of-line 1)
2539 (setq ts (match-string 1)
2540 te (match-string 3))
2541 (setq s (- (time-to-seconds
2542 (apply 'encode-time (org-parse-time-string te)))
2543 (time-to-seconds
2544 (apply 'encode-time (org-parse-time-string ts))))
2545 h (floor (/ s 3600))
2546 s (- s (* 3600 h))
2547 m (floor (/ s 60))
2548 s (- s (* 60 s)))
2549 (insert " => " (format "%2d:%02d" h m))
2550 t))))))
2552 (defun org-check-running-clock ()
2553 "Check if the current buffer contains the running clock.
2554 If yes, offer to stop it and to save the buffer with the changes."
2555 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2556 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2557 (buffer-name))))
2558 (org-clock-out)
2559 (when (y-or-n-p "Save changed buffer?")
2560 (save-buffer))))
2562 (defun org-clocktable-try-shift (dir n)
2563 "Check if this line starts a clock table, if yes, shift the time block."
2564 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2565 (org-clocktable-shift dir n)))
2567 ;; Autoload archiving code
2568 ;; The stuff that is needed for cycling and tags has to be defined here.
2570 (defgroup org-archive nil
2571 "Options concerning archiving in Org-mode."
2572 :tag "Org Archive"
2573 :group 'org-structure)
2575 (defcustom org-archive-location "%s_archive::"
2576 "The location where subtrees should be archived.
2578 Otherwise, the value of this variable is a string, consisting of two
2579 parts, separated by a double-colon.
2581 The first part is a file name - when omitted, archiving happens in the same
2582 file. %s will be replaced by the current file name (without directory part).
2583 Archiving to a different file is useful to keep archived entries from
2584 contributing to the Org-mode Agenda.
2586 The part after the double colon is a headline. The archived entries will be
2587 filed under that headline. When omitted, the subtrees are simply filed away
2588 at the end of the file, as top-level entries.
2590 Here are a few examples:
2591 \"%s_archive::\"
2592 If the current file is Projects.org, archive in file
2593 Projects.org_archive, as top-level trees. This is the default.
2595 \"::* Archived Tasks\"
2596 Archive in the current file, under the top-level headline
2597 \"* Archived Tasks\".
2599 \"~/org/archive.org::\"
2600 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2602 \"basement::** Finished Tasks\"
2603 Archive in file ./basement (relative path), as level 3 trees
2604 below the level 2 heading \"** Finished Tasks\".
2606 You may set this option on a per-file basis by adding to the buffer a
2607 line like
2609 #+ARCHIVE: basement::** Finished Tasks
2611 You may also define it locally for a subtree by setting an ARCHIVE property
2612 in the entry. If such a property is found in an entry, or anywhere up
2613 the hierarchy, it will be used."
2614 :group 'org-archive
2615 :type 'string)
2617 (defcustom org-archive-tag "ARCHIVE"
2618 "The tag that marks a subtree as archived.
2619 An archived subtree does not open during visibility cycling, and does
2620 not contribute to the agenda listings.
2621 After changing this, font-lock must be restarted in the relevant buffers to
2622 get the proper fontification."
2623 :group 'org-archive
2624 :group 'org-keywords
2625 :type 'string)
2627 (defcustom org-agenda-skip-archived-trees t
2628 "Non-nil means, the agenda will skip any items located in archived trees.
2629 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2630 variable is no longer recommended, you should leave it at the value t.
2631 Instead, use the key `v' to cycle the archives-mode in the agenda."
2632 :group 'org-archive
2633 :group 'org-agenda-skip
2634 :type 'boolean)
2636 (defcustom org-cycle-open-archived-trees nil
2637 "Non-nil means, `org-cycle' will open archived trees.
2638 An archived tree is a tree marked with the tag ARCHIVE.
2639 When nil, archived trees will stay folded. You can still open them with
2640 normal outline commands like `show-all', but not with the cycling commands."
2641 :group 'org-archive
2642 :group 'org-cycle
2643 :type 'boolean)
2645 (defcustom org-sparse-tree-open-archived-trees nil
2646 "Non-nil means sparse tree construction shows matches in archived trees.
2647 When nil, matches in these trees are highlighted, but the trees are kept in
2648 collapsed state."
2649 :group 'org-archive
2650 :group 'org-sparse-trees
2651 :type 'boolean)
2653 (defun org-cycle-hide-archived-subtrees (state)
2654 "Re-hide all archived subtrees after a visibility state change."
2655 (when (and (not org-cycle-open-archived-trees)
2656 (not (memq state '(overview folded))))
2657 (save-excursion
2658 (let* ((globalp (memq state '(contents all)))
2659 (beg (if globalp (point-min) (point)))
2660 (end (if globalp (point-max) (org-end-of-subtree t))))
2661 (org-hide-archived-subtrees beg end)
2662 (goto-char beg)
2663 (if (looking-at (concat ".*:" org-archive-tag ":"))
2664 (message "%s" (substitute-command-keys
2665 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2667 (defun org-force-cycle-archived ()
2668 "Cycle subtree even if it is archived."
2669 (interactive)
2670 (setq this-command 'org-cycle)
2671 (let ((org-cycle-open-archived-trees t))
2672 (call-interactively 'org-cycle)))
2674 (defun org-hide-archived-subtrees (beg end)
2675 "Re-hide all archived subtrees after a visibility state change."
2676 (save-excursion
2677 (let* ((re (concat ":" org-archive-tag ":")))
2678 (goto-char beg)
2679 (while (re-search-forward re end t)
2680 (and (org-on-heading-p) (hide-subtree))
2681 (org-end-of-subtree t)))))
2683 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2685 (eval-and-compile
2686 (org-autoload "org-archive"
2687 '(org-add-archive-files org-archive-subtree
2688 org-archive-to-archive-sibling org-toggle-archive-tag)))
2690 ;; Autoload Column View Code
2692 (declare-function org-columns-number-to-string "org-colview")
2693 (declare-function org-columns-get-format-and-top-level "org-colview")
2694 (declare-function org-columns-compute "org-colview")
2696 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2697 '(org-columns-number-to-string org-columns-get-format-and-top-level
2698 org-columns-compute org-agenda-columns org-columns-remove-overlays
2699 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2701 ;; Autoload ID code
2703 (org-autoload "org-id"
2704 '(org-id-get-create org-id-new org-id-copy org-id-get
2705 org-id-get-with-outline-path-completion
2706 org-id-get-with-outline-drilling
2707 org-id-goto org-id-find))
2709 ;;; Variables for pre-computed regular expressions, all buffer local
2711 (defvar org-drawer-regexp nil
2712 "Matches first line of a hidden block.")
2713 (make-variable-buffer-local 'org-drawer-regexp)
2714 (defvar org-todo-regexp nil
2715 "Matches any of the TODO state keywords.")
2716 (make-variable-buffer-local 'org-todo-regexp)
2717 (defvar org-not-done-regexp nil
2718 "Matches any of the TODO state keywords except the last one.")
2719 (make-variable-buffer-local 'org-not-done-regexp)
2720 (defvar org-todo-line-regexp nil
2721 "Matches a headline and puts TODO state into group 2 if present.")
2722 (make-variable-buffer-local 'org-todo-line-regexp)
2723 (defvar org-complex-heading-regexp nil
2724 "Matches a headline and puts everything into groups:
2725 group 1: the stars
2726 group 2: The todo keyword, maybe
2727 group 3: Priority cookie
2728 group 4: True headline
2729 group 5: Tags")
2730 (make-variable-buffer-local 'org-complex-heading-regexp)
2731 (defvar org-todo-line-tags-regexp nil
2732 "Matches a headline and puts TODO state into group 2 if present.
2733 Also put tags into group 4 if tags are present.")
2734 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2735 (defvar org-nl-done-regexp nil
2736 "Matches newline followed by a headline with the DONE keyword.")
2737 (make-variable-buffer-local 'org-nl-done-regexp)
2738 (defvar org-looking-at-done-regexp nil
2739 "Matches the DONE keyword a point.")
2740 (make-variable-buffer-local 'org-looking-at-done-regexp)
2741 (defvar org-ds-keyword-length 12
2742 "Maximum length of the Deadline and SCHEDULED keywords.")
2743 (make-variable-buffer-local 'org-ds-keyword-length)
2744 (defvar org-deadline-regexp nil
2745 "Matches the DEADLINE keyword.")
2746 (make-variable-buffer-local 'org-deadline-regexp)
2747 (defvar org-deadline-time-regexp nil
2748 "Matches the DEADLINE keyword together with a time stamp.")
2749 (make-variable-buffer-local 'org-deadline-time-regexp)
2750 (defvar org-deadline-line-regexp nil
2751 "Matches the DEADLINE keyword and the rest of the line.")
2752 (make-variable-buffer-local 'org-deadline-line-regexp)
2753 (defvar org-scheduled-regexp nil
2754 "Matches the SCHEDULED keyword.")
2755 (make-variable-buffer-local 'org-scheduled-regexp)
2756 (defvar org-scheduled-time-regexp nil
2757 "Matches the SCHEDULED keyword together with a time stamp.")
2758 (make-variable-buffer-local 'org-scheduled-time-regexp)
2759 (defvar org-closed-time-regexp nil
2760 "Matches the CLOSED keyword together with a time stamp.")
2761 (make-variable-buffer-local 'org-closed-time-regexp)
2763 (defvar org-keyword-time-regexp nil
2764 "Matches any of the 4 keywords, together with the time stamp.")
2765 (make-variable-buffer-local 'org-keyword-time-regexp)
2766 (defvar org-keyword-time-not-clock-regexp nil
2767 "Matches any of the 3 keywords, together with the time stamp.")
2768 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2769 (defvar org-maybe-keyword-time-regexp nil
2770 "Matches a timestamp, possibly preceeded by a keyword.")
2771 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2772 (defvar org-planning-or-clock-line-re nil
2773 "Matches a line with planning or clock info.")
2774 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2776 (defconst org-plain-time-of-day-regexp
2777 (concat
2778 "\\(\\<[012]?[0-9]"
2779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2780 "\\(--?"
2781 "\\(\\<[012]?[0-9]"
2782 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2783 "\\)?")
2784 "Regular expression to match a plain time or time range.
2785 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2786 groups carry important information:
2787 0 the full match
2788 1 the first time, range or not
2789 8 the second time, if it is a range.")
2791 (defconst org-plain-time-extension-regexp
2792 (concat
2793 "\\(\\<[012]?[0-9]"
2794 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2795 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2796 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2797 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2798 groups carry important information:
2799 0 the full match
2800 7 hours of duration
2801 9 minutes of duration")
2803 (defconst org-stamp-time-of-day-regexp
2804 (concat
2805 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2806 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2807 "\\(--?"
2808 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2809 "Regular expression to match a timestamp time or time range.
2810 After a match, the following groups carry important information:
2811 0 the full match
2812 1 date plus weekday, for backreferencing to make sure both times on same day
2813 2 the first time, range or not
2814 4 the second time, if it is a range.")
2816 (defconst org-startup-options
2817 '(("fold" org-startup-folded t)
2818 ("overview" org-startup-folded t)
2819 ("nofold" org-startup-folded nil)
2820 ("showall" org-startup-folded nil)
2821 ("content" org-startup-folded content)
2822 ("hidestars" org-hide-leading-stars t)
2823 ("showstars" org-hide-leading-stars nil)
2824 ("odd" org-odd-levels-only t)
2825 ("oddeven" org-odd-levels-only nil)
2826 ("align" org-startup-align-all-tables t)
2827 ("noalign" org-startup-align-all-tables nil)
2828 ("customtime" org-display-custom-times t)
2829 ("logdone" org-log-done time)
2830 ("lognotedone" org-log-done note)
2831 ("nologdone" org-log-done nil)
2832 ("lognoteclock-out" org-log-note-clock-out t)
2833 ("nolognoteclock-out" org-log-note-clock-out nil)
2834 ("logrepeat" org-log-repeat state)
2835 ("lognoterepeat" org-log-repeat note)
2836 ("nologrepeat" org-log-repeat nil)
2837 ("constcgs" constants-unit-system cgs)
2838 ("constSI" constants-unit-system SI))
2839 "Variable associated with STARTUP options for org-mode.
2840 Each element is a list of three items: The startup options as written
2841 in the #+STARTUP line, the corresponding variable, and the value to
2842 set this variable to if the option is found. An optional forth element PUSH
2843 means to push this value onto the list in the variable.")
2845 (defun org-set-regexps-and-options ()
2846 "Precompute regular expressions for current buffer."
2847 (when (org-mode-p)
2848 (org-set-local 'org-todo-kwd-alist nil)
2849 (org-set-local 'org-todo-key-alist nil)
2850 (org-set-local 'org-todo-key-trigger nil)
2851 (org-set-local 'org-todo-keywords-1 nil)
2852 (org-set-local 'org-done-keywords nil)
2853 (org-set-local 'org-todo-heads nil)
2854 (org-set-local 'org-todo-sets nil)
2855 (org-set-local 'org-todo-log-states nil)
2856 (org-set-local 'org-file-properties nil)
2857 (org-set-local 'org-file-tags nil)
2858 (let ((re (org-make-options-regexp
2859 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2860 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2861 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2862 (splitre "[ \t]+")
2863 kwds kws0 kwsa key log value cat arch tags const links hw dws
2864 tail sep kws1 prio props ftags drawers
2865 ext-setup-or-nil setup-contents (start 0))
2866 (save-excursion
2867 (save-restriction
2868 (widen)
2869 (goto-char (point-min))
2870 (while (or (and ext-setup-or-nil
2871 (string-match re ext-setup-or-nil start)
2872 (setq start (match-end 0)))
2873 (and (setq ext-setup-or-nil nil start 0)
2874 (re-search-forward re nil t)))
2875 (setq key (upcase (match-string 1 ext-setup-or-nil))
2876 value (org-match-string-no-properties 2 ext-setup-or-nil))
2877 (cond
2878 ((equal key "CATEGORY")
2879 (if (string-match "[ \t]+$" value)
2880 (setq value (replace-match "" t t value)))
2881 (setq cat value))
2882 ((member key '("SEQ_TODO" "TODO"))
2883 (push (cons 'sequence (org-split-string value splitre)) kwds))
2884 ((equal key "TYP_TODO")
2885 (push (cons 'type (org-split-string value splitre)) kwds))
2886 ((equal key "TAGS")
2887 (setq tags (append tags (org-split-string value splitre))))
2888 ((equal key "COLUMNS")
2889 (org-set-local 'org-columns-default-format value))
2890 ((equal key "LINK")
2891 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2892 (push (cons (match-string 1 value)
2893 (org-trim (match-string 2 value)))
2894 links)))
2895 ((equal key "PRIORITIES")
2896 (setq prio (org-split-string value " +")))
2897 ((equal key "PROPERTY")
2898 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2899 (push (cons (match-string 1 value) (match-string 2 value))
2900 props)))
2901 ((equal key "FILETAGS")
2902 (when (string-match "\\S-" value)
2903 (setq ftags
2904 (append
2905 ftags
2906 (apply 'append
2907 (mapcar (lambda (x) (org-split-string x ":"))
2908 (org-split-string value)))))))
2909 ((equal key "DRAWERS")
2910 (setq drawers (org-split-string value splitre)))
2911 ((equal key "CONSTANTS")
2912 (setq const (append const (org-split-string value splitre))))
2913 ((equal key "STARTUP")
2914 (let ((opts (org-split-string value splitre))
2915 l var val)
2916 (while (setq l (pop opts))
2917 (when (setq l (assoc l org-startup-options))
2918 (setq var (nth 1 l) val (nth 2 l))
2919 (if (not (nth 3 l))
2920 (set (make-local-variable var) val)
2921 (if (not (listp (symbol-value var)))
2922 (set (make-local-variable var) nil))
2923 (set (make-local-variable var) (symbol-value var))
2924 (add-to-list var val))))))
2925 ((equal key "ARCHIVE")
2926 (string-match " *$" value)
2927 (setq arch (replace-match "" t t value))
2928 (remove-text-properties 0 (length arch)
2929 '(face t fontified t) arch))
2930 ((equal key "SETUPFILE")
2931 (setq setup-contents (org-file-contents
2932 (expand-file-name
2933 (org-remove-double-quotes value))
2934 'noerror))
2935 (if (not ext-setup-or-nil)
2936 (setq ext-setup-or-nil setup-contents start 0)
2937 (setq ext-setup-or-nil
2938 (concat (substring ext-setup-or-nil 0 start)
2939 "\n" setup-contents "\n"
2940 (substring ext-setup-or-nil start)))))
2941 ))))
2942 (when cat
2943 (org-set-local 'org-category (intern cat))
2944 (push (cons "CATEGORY" cat) props))
2945 (when prio
2946 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2947 (setq prio (mapcar 'string-to-char prio))
2948 (org-set-local 'org-highest-priority (nth 0 prio))
2949 (org-set-local 'org-lowest-priority (nth 1 prio))
2950 (org-set-local 'org-default-priority (nth 2 prio)))
2951 (and props (org-set-local 'org-file-properties (nreverse props)))
2952 (and ftags (org-set-local 'org-file-tags ftags))
2953 (and drawers (org-set-local 'org-drawers drawers))
2954 (and arch (org-set-local 'org-archive-location arch))
2955 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2956 ;; Process the TODO keywords
2957 (unless kwds
2958 ;; Use the global values as if they had been given locally.
2959 (setq kwds (default-value 'org-todo-keywords))
2960 (if (stringp (car kwds))
2961 (setq kwds (list (cons org-todo-interpretation
2962 (default-value 'org-todo-keywords)))))
2963 (setq kwds (reverse kwds)))
2964 (setq kwds (nreverse kwds))
2965 (let (inter kws kw)
2966 (while (setq kws (pop kwds))
2967 (setq inter (pop kws) sep (member "|" kws)
2968 kws0 (delete "|" (copy-sequence kws))
2969 kwsa nil
2970 kws1 (mapcar
2971 (lambda (x)
2972 ;; 1 2
2973 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2974 (progn
2975 (setq kw (match-string 1 x)
2976 key (and (match-end 2) (match-string 2 x))
2977 log (org-extract-log-state-settings x))
2978 (push (cons kw (and key (string-to-char key))) kwsa)
2979 (and log (push log org-todo-log-states))
2981 (error "Invalid TODO keyword %s" x)))
2982 kws0)
2983 kwsa (if kwsa (append '((:startgroup))
2984 (nreverse kwsa)
2985 '((:endgroup))))
2986 hw (car kws1)
2987 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2988 tail (list inter hw (car dws) (org-last dws)))
2989 (add-to-list 'org-todo-heads hw 'append)
2990 (push kws1 org-todo-sets)
2991 (setq org-done-keywords (append org-done-keywords dws nil))
2992 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2993 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2994 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2995 (setq org-todo-sets (nreverse org-todo-sets)
2996 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2997 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2998 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2999 ;; Process the constants
3000 (when const
3001 (let (e cst)
3002 (while (setq e (pop const))
3003 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3004 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3005 (setq org-table-formula-constants-local cst)))
3007 ;; Process the tags.
3008 (when tags
3009 (let (e tgs)
3010 (while (setq e (pop tags))
3011 (cond
3012 ((equal e "{") (push '(:startgroup) tgs))
3013 ((equal e "}") (push '(:endgroup) tgs))
3014 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3015 (push (cons (match-string 1 e)
3016 (string-to-char (match-string 2 e)))
3017 tgs))
3018 (t (push (list e) tgs))))
3019 (org-set-local 'org-tag-alist nil)
3020 (while (setq e (pop tgs))
3021 (or (and (stringp (car e))
3022 (assoc (car e) org-tag-alist))
3023 (push e org-tag-alist)))))
3025 ;; Compute the regular expressions and other local variables
3026 (if (not org-done-keywords)
3027 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3028 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3029 (length org-scheduled-string)
3030 (length org-clock-string)
3031 (length org-closed-string)))
3032 org-drawer-regexp
3033 (concat "^[ \t]*:\\("
3034 (mapconcat 'regexp-quote org-drawers "\\|")
3035 "\\):[ \t]*$")
3036 org-not-done-keywords
3037 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3038 org-todo-regexp
3039 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3040 "\\|") "\\)\\>")
3041 org-not-done-regexp
3042 (concat "\\<\\("
3043 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3044 "\\)\\>")
3045 org-todo-line-regexp
3046 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3047 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3048 "\\)\\>\\)?[ \t]*\\(.*\\)")
3049 org-complex-heading-regexp
3050 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3051 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3052 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3053 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3054 org-nl-done-regexp
3055 (concat "\n\\*+[ \t]+"
3056 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3057 "\\)" "\\>")
3058 org-todo-line-tags-regexp
3059 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3060 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3061 (org-re
3062 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3063 org-looking-at-done-regexp
3064 (concat "^" "\\(?:"
3065 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3066 "\\>")
3067 org-deadline-regexp (concat "\\<" org-deadline-string)
3068 org-deadline-time-regexp
3069 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3070 org-deadline-line-regexp
3071 (concat "\\<\\(" org-deadline-string "\\).*")
3072 org-scheduled-regexp
3073 (concat "\\<" org-scheduled-string)
3074 org-scheduled-time-regexp
3075 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3076 org-closed-time-regexp
3077 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3078 org-keyword-time-regexp
3079 (concat "\\<\\(" org-scheduled-string
3080 "\\|" org-deadline-string
3081 "\\|" org-closed-string
3082 "\\|" org-clock-string "\\)"
3083 " *[[<]\\([^]>]+\\)[]>]")
3084 org-keyword-time-not-clock-regexp
3085 (concat "\\<\\(" org-scheduled-string
3086 "\\|" org-deadline-string
3087 "\\|" org-closed-string
3088 "\\)"
3089 " *[[<]\\([^]>]+\\)[]>]")
3090 org-maybe-keyword-time-regexp
3091 (concat "\\(\\<\\(" org-scheduled-string
3092 "\\|" org-deadline-string
3093 "\\|" org-closed-string
3094 "\\|" org-clock-string "\\)\\)?"
3095 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3096 org-planning-or-clock-line-re
3097 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3098 "\\|" org-deadline-string
3099 "\\|" org-closed-string "\\|" org-clock-string
3100 "\\)\\>\\)")
3102 (org-compute-latex-and-specials-regexp)
3103 (org-set-font-lock-defaults))))
3105 (defun org-file-contents (file &optional noerror)
3106 "Return the contents of FILE, as a string."
3107 (if (or (not file)
3108 (not (file-readable-p file)))
3109 (if noerror
3110 (progn
3111 (message "Cannot read file %s" file)
3112 (ding) (sit-for 2)
3114 (error "Cannot read file %s" file))
3115 (with-temp-buffer
3116 (insert-file-contents file)
3117 (buffer-string))))
3119 (defun org-extract-log-state-settings (x)
3120 "Extract the log state setting from a TODO keyword string.
3121 This will extract info from a string like \"WAIT(w@/!)\"."
3122 (let (kw key log1 log2)
3123 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3124 (setq kw (match-string 1 x)
3125 key (and (match-end 2) (match-string 2 x))
3126 log1 (and (match-end 3) (match-string 3 x))
3127 log2 (and (match-end 4) (match-string 4 x)))
3128 (and (or log1 log2)
3129 (list kw
3130 (and log1 (if (equal log1 "!") 'time 'note))
3131 (and log2 (if (equal log2 "!") 'time 'note)))))))
3133 (defun org-remove-keyword-keys (list)
3134 "Remove a pair of parenthesis at the end of each string in LIST."
3135 (mapcar (lambda (x)
3136 (if (string-match "(.*)$" x)
3137 (substring x 0 (match-beginning 0))
3139 list))
3141 ;; FIXME: this could be done much better, using second characters etc.
3142 (defun org-assign-fast-keys (alist)
3143 "Assign fast keys to a keyword-key alist.
3144 Respect keys that are already there."
3145 (let (new e k c c1 c2 (char ?a))
3146 (while (setq e (pop alist))
3147 (cond
3148 ((equal e '(:startgroup)) (push e new))
3149 ((equal e '(:endgroup)) (push e new))
3151 (setq k (car e) c2 nil)
3152 (if (cdr e)
3153 (setq c (cdr e))
3154 ;; automatically assign a character.
3155 (setq c1 (string-to-char
3156 (downcase (substring
3157 k (if (= (string-to-char k) ?@) 1 0)))))
3158 (if (or (rassoc c1 new) (rassoc c1 alist))
3159 (while (or (rassoc char new) (rassoc char alist))
3160 (setq char (1+ char)))
3161 (setq c2 c1))
3162 (setq c (or c2 char)))
3163 (push (cons k c) new))))
3164 (nreverse new)))
3166 ;;; Some variables used in various places
3168 (defvar org-window-configuration nil
3169 "Used in various places to store a window configuration.")
3170 (defvar org-finish-function nil
3171 "Function to be called when `C-c C-c' is used.
3172 This is for getting out of special buffers like remember.")
3175 ;; FIXME: Occasionally check by commenting these, to make sure
3176 ;; no other functions uses these, forgetting to let-bind them.
3177 (defvar entry)
3178 (defvar state)
3179 (defvar last-state)
3180 (defvar date)
3181 (defvar description)
3183 ;; Defined somewhere in this file, but used before definition.
3184 (defvar org-html-entities)
3185 (defvar org-struct-menu)
3186 (defvar org-org-menu)
3187 (defvar org-tbl-menu)
3188 (defvar org-agenda-keymap)
3190 ;;;; Define the Org-mode
3192 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3193 (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."))
3196 ;; We use a before-change function to check if a table might need
3197 ;; an update.
3198 (defvar org-table-may-need-update t
3199 "Indicates that a table might need an update.
3200 This variable is set by `org-before-change-function'.
3201 `org-table-align' sets it back to nil.")
3202 (defun org-before-change-function (beg end)
3203 "Every change indicates that a table might need an update."
3204 (setq org-table-may-need-update t))
3205 (defvar org-mode-map)
3206 (defvar org-mode-hook nil)
3207 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3208 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3209 (defvar org-table-buffer-is-an nil)
3210 (defconst org-outline-regexp "\\*+ ")
3212 ;;;###autoload
3213 (define-derived-mode org-mode outline-mode "Org"
3214 "Outline-based notes management and organizer, alias
3215 \"Carsten's outline-mode for keeping track of everything.\"
3217 Org-mode develops organizational tasks around a NOTES file which
3218 contains information about projects as plain text. Org-mode is
3219 implemented on top of outline-mode, which is ideal to keep the content
3220 of large files well structured. It supports ToDo items, deadlines and
3221 time stamps, which magically appear in the diary listing of the Emacs
3222 calendar. Tables are easily created with a built-in table editor.
3223 Plain text URL-like links connect to websites, emails (VM), Usenet
3224 messages (Gnus), BBDB entries, and any files related to the project.
3225 For printing and sharing of notes, an Org-mode file (or a part of it)
3226 can be exported as a structured ASCII or HTML file.
3228 The following commands are available:
3230 \\{org-mode-map}"
3232 ;; Get rid of Outline menus, they are not needed
3233 ;; Need to do this here because define-derived-mode sets up
3234 ;; the keymap so late. Still, it is a waste to call this each time
3235 ;; we switch another buffer into org-mode.
3236 (if (featurep 'xemacs)
3237 (when (boundp 'outline-mode-menu-heading)
3238 ;; Assume this is Greg's port, it used easymenu
3239 (easy-menu-remove outline-mode-menu-heading)
3240 (easy-menu-remove outline-mode-menu-show)
3241 (easy-menu-remove outline-mode-menu-hide))
3242 (define-key org-mode-map [menu-bar headings] 'undefined)
3243 (define-key org-mode-map [menu-bar hide] 'undefined)
3244 (define-key org-mode-map [menu-bar show] 'undefined))
3246 (org-load-modules-maybe)
3247 (easy-menu-add org-org-menu)
3248 (easy-menu-add org-tbl-menu)
3249 (org-install-agenda-files-menu)
3250 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3251 (org-add-to-invisibility-spec '(org-cwidth))
3252 (when (featurep 'xemacs)
3253 (org-set-local 'line-move-ignore-invisible t))
3254 (org-set-local 'outline-regexp org-outline-regexp)
3255 (org-set-local 'outline-level 'org-outline-level)
3256 (when (and org-ellipsis
3257 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3258 (fboundp 'make-glyph-code))
3259 (unless org-display-table
3260 (setq org-display-table (make-display-table)))
3261 (set-display-table-slot
3262 org-display-table 4
3263 (vconcat (mapcar
3264 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3265 org-ellipsis)))
3266 (if (stringp org-ellipsis) org-ellipsis "..."))))
3267 (setq buffer-display-table org-display-table))
3268 (org-set-regexps-and-options)
3269 ;; Calc embedded
3270 (org-set-local 'calc-embedded-open-mode "# ")
3271 (modify-syntax-entry ?# "<")
3272 (modify-syntax-entry ?@ "w")
3273 (if org-startup-truncated (setq truncate-lines t))
3274 (org-set-local 'font-lock-unfontify-region-function
3275 'org-unfontify-region)
3276 ;; Activate before-change-function
3277 (org-set-local 'org-table-may-need-update t)
3278 (org-add-hook 'before-change-functions 'org-before-change-function nil
3279 'local)
3280 ;; Check for running clock before killing a buffer
3281 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3282 ;; Paragraphs and auto-filling
3283 (org-set-autofill-regexps)
3284 (setq indent-line-function 'org-indent-line-function)
3285 (org-update-radio-target-regexp)
3287 ;; Comment characters
3288 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3289 (org-set-local 'comment-padding " ")
3291 ;; Align options lines
3292 (org-set-local
3293 'align-mode-rules-list
3294 '((org-in-buffer-settings
3295 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3296 (modes . '(org-mode)))))
3298 ;; Imenu
3299 (org-set-local 'imenu-create-index-function
3300 'org-imenu-get-tree)
3302 ;; Make isearch reveal context
3303 (if (or (featurep 'xemacs)
3304 (not (boundp 'outline-isearch-open-invisible-function)))
3305 ;; Emacs 21 and XEmacs make use of the hook
3306 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3307 ;; Emacs 22 deals with this through a special variable
3308 (org-set-local 'outline-isearch-open-invisible-function
3309 (lambda (&rest ignore) (org-show-context 'isearch))))
3311 ;; If empty file that did not turn on org-mode automatically, make it to.
3312 (if (and org-insert-mode-line-in-empty-file
3313 (interactive-p)
3314 (= (point-min) (point-max)))
3315 (insert "# -*- mode: org -*-\n\n"))
3317 (unless org-inhibit-startup
3318 (when org-startup-align-all-tables
3319 (let ((bmp (buffer-modified-p)))
3320 (org-table-map-tables 'org-table-align)
3321 (set-buffer-modified-p bmp)))
3322 (org-set-startup-visibility)))
3324 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3326 (defun org-current-time ()
3327 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3328 (if (> (car org-time-stamp-rounding-minutes) 1)
3329 (let ((r (car org-time-stamp-rounding-minutes))
3330 (time (decode-time)))
3331 (apply 'encode-time
3332 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3333 (nthcdr 2 time))))
3334 (current-time)))
3336 ;;;; Font-Lock stuff, including the activators
3338 (defvar org-mouse-map (make-sparse-keymap))
3339 (org-defkey org-mouse-map
3340 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3341 (org-defkey org-mouse-map
3342 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3343 (when org-mouse-1-follows-link
3344 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3345 (when org-tab-follows-link
3346 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3347 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3348 (when org-return-follows-link
3349 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3350 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3352 (require 'font-lock)
3354 (defconst org-non-link-chars "]\t\n\r<>")
3355 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3356 "shell" "elisp"))
3357 (defvar org-link-types-re nil
3358 "Matches a link that has a url-like prefix like \"http:\"")
3359 (defvar org-link-re-with-space nil
3360 "Matches a link with spaces, optional angular brackets around it.")
3361 (defvar org-link-re-with-space2 nil
3362 "Matches a link with spaces, optional angular brackets around it.")
3363 (defvar org-angle-link-re nil
3364 "Matches link with angular brackets, spaces are allowed.")
3365 (defvar org-plain-link-re nil
3366 "Matches plain link, without spaces.")
3367 (defvar org-bracket-link-regexp nil
3368 "Matches a link in double brackets.")
3369 (defvar org-bracket-link-analytic-regexp nil
3370 "Regular expression used to analyze links.
3371 Here is what the match groups contain after a match:
3372 1: http:
3373 2: http
3374 3: path
3375 4: [desc]
3376 5: desc")
3377 (defvar org-any-link-re nil
3378 "Regular expression matching any link.")
3380 (defun org-make-link-regexps ()
3381 "Update the link regular expressions.
3382 This should be called after the variable `org-link-types' has changed."
3383 (setq org-link-types-re
3384 (concat
3385 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3386 org-link-re-with-space
3387 (concat
3388 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3389 "\\([^" org-non-link-chars " ]"
3390 "[^" org-non-link-chars "]*"
3391 "[^" org-non-link-chars " ]\\)>?")
3392 org-link-re-with-space2
3393 (concat
3394 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3395 "\\([^" org-non-link-chars " ]"
3396 "[^]\t\n\r]*"
3397 "[^" org-non-link-chars " ]\\)>?")
3398 org-angle-link-re
3399 (concat
3400 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3401 "\\([^" org-non-link-chars " ]"
3402 "[^" org-non-link-chars "]*"
3403 "\\)>")
3404 org-plain-link-re
3405 (concat
3406 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3407 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3408 org-bracket-link-regexp
3409 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3410 org-bracket-link-analytic-regexp
3411 (concat
3412 "\\[\\["
3413 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3414 "\\([^]]+\\)"
3415 "\\]"
3416 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3417 "\\]")
3418 org-any-link-re
3419 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3420 org-angle-link-re "\\)\\|\\("
3421 org-plain-link-re "\\)")))
3423 (org-make-link-regexps)
3425 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3426 "Regular expression for fast time stamp matching.")
3427 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3428 "Regular expression for fast time stamp matching.")
3429 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3430 "Regular expression matching time strings for analysis.
3431 This one does not require the space after the date, so it can be used
3432 on a string that terminates immediately after the date.")
3433 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3434 "Regular expression matching time strings for analysis.")
3435 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3436 "Regular expression matching time stamps, with groups.")
3437 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3438 "Regular expression matching time stamps (also [..]), with groups.")
3439 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3440 "Regular expression matching a time stamp range.")
3441 (defconst org-tr-regexp-both
3442 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3443 "Regular expression matching a time stamp range.")
3444 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3445 org-ts-regexp "\\)?")
3446 "Regular expression matching a time stamp or time stamp range.")
3447 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3448 org-ts-regexp-both "\\)?")
3449 "Regular expression matching a time stamp or time stamp range.
3450 The time stamps may be either active or inactive.")
3452 (defvar org-emph-face nil)
3454 (defun org-do-emphasis-faces (limit)
3455 "Run through the buffer and add overlays to links."
3456 (let (rtn)
3457 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3458 (if (not (= (char-after (match-beginning 3))
3459 (char-after (match-beginning 4))))
3460 (progn
3461 (setq rtn t)
3462 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3463 'face
3464 (nth 1 (assoc (match-string 3)
3465 org-emphasis-alist)))
3466 (add-text-properties (match-beginning 2) (match-end 2)
3467 '(font-lock-multiline t))
3468 (when org-hide-emphasis-markers
3469 (add-text-properties (match-end 4) (match-beginning 5)
3470 '(invisible org-link))
3471 (add-text-properties (match-beginning 3) (match-end 3)
3472 '(invisible org-link)))))
3473 (backward-char 1))
3474 rtn))
3476 (defun org-emphasize (&optional char)
3477 "Insert or change an emphasis, i.e. a font like bold or italic.
3478 If there is an active region, change that region to a new emphasis.
3479 If there is no region, just insert the marker characters and position
3480 the cursor between them.
3481 CHAR should be either the marker character, or the first character of the
3482 HTML tag associated with that emphasis. If CHAR is a space, the means
3483 to remove the emphasis of the selected region.
3484 If char is not given (for example in an interactive call) it
3485 will be prompted for."
3486 (interactive)
3487 (let ((eal org-emphasis-alist) e det
3488 (erc org-emphasis-regexp-components)
3489 (prompt "")
3490 (string "") beg end move tag c s)
3491 (if (org-region-active-p)
3492 (setq beg (region-beginning) end (region-end)
3493 string (buffer-substring beg end))
3494 (setq move t))
3496 (while (setq e (pop eal))
3497 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3498 c (aref tag 0))
3499 (push (cons c (string-to-char (car e))) det)
3500 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3501 (substring tag 1)))))
3502 (unless char
3503 (message "%s" (concat "Emphasis marker or tag:" prompt))
3504 (setq char (read-char-exclusive)))
3505 (setq char (or (cdr (assoc char det)) char))
3506 (if (equal char ?\ )
3507 (setq s "" move nil)
3508 (unless (assoc (char-to-string char) org-emphasis-alist)
3509 (error "No such emphasis marker: \"%c\"" char))
3510 (setq s (char-to-string char)))
3511 (while (and (> (length string) 1)
3512 (equal (substring string 0 1) (substring string -1))
3513 (assoc (substring string 0 1) org-emphasis-alist))
3514 (setq string (substring string 1 -1)))
3515 (setq string (concat s string s))
3516 (if beg (delete-region beg end))
3517 (unless (or (bolp)
3518 (string-match (concat "[" (nth 0 erc) "\n]")
3519 (char-to-string (char-before (point)))))
3520 (insert " "))
3521 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3522 (char-to-string (char-after (point))))
3523 (insert " ") (backward-char 1))
3524 (insert string)
3525 (and move (backward-char 1))))
3527 (defconst org-nonsticky-props
3528 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3531 (defun org-activate-plain-links (limit)
3532 "Run through the buffer and add overlays to links."
3533 (catch 'exit
3534 (let (f)
3535 (while (re-search-forward org-plain-link-re limit t)
3536 (setq f (get-text-property (match-beginning 0) 'face))
3537 (if (or (eq f 'org-tag)
3538 (and (listp f) (memq 'org-tag f)))
3540 (add-text-properties (match-beginning 0) (match-end 0)
3541 (list 'mouse-face 'highlight
3542 'rear-nonsticky org-nonsticky-props
3543 'keymap org-mouse-map
3545 (throw 'exit t))))))
3547 (defun org-activate-code (limit)
3548 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3549 (progn
3550 (remove-text-properties (match-beginning 0) (match-end 0)
3551 '(display t invisible t intangible t))
3552 t)))
3554 (defun org-activate-angle-links (limit)
3555 "Run through the buffer and add overlays to links."
3556 (if (re-search-forward org-angle-link-re limit t)
3557 (progn
3558 (add-text-properties (match-beginning 0) (match-end 0)
3559 (list 'mouse-face 'highlight
3560 'rear-nonsticky org-nonsticky-props
3561 'keymap org-mouse-map
3563 t)))
3565 (defun org-activate-bracket-links (limit)
3566 "Run through the buffer and add overlays to bracketed links."
3567 (if (re-search-forward org-bracket-link-regexp limit t)
3568 (let* ((help (concat "LINK: "
3569 (org-match-string-no-properties 1)))
3570 ;; FIXME: above we should remove the escapes.
3571 ;; but that requires another match, protecting match data,
3572 ;; a lot of overhead for font-lock.
3573 (ip (org-maybe-intangible
3574 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3575 'keymap org-mouse-map 'mouse-face 'highlight
3576 'font-lock-multiline t 'help-echo help)))
3577 (vp (list 'rear-nonsticky org-nonsticky-props
3578 'keymap org-mouse-map 'mouse-face 'highlight
3579 ' font-lock-multiline t 'help-echo help)))
3580 ;; We need to remove the invisible property here. Table narrowing
3581 ;; may have made some of this invisible.
3582 (remove-text-properties (match-beginning 0) (match-end 0)
3583 '(invisible nil))
3584 (if (match-end 3)
3585 (progn
3586 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3587 (add-text-properties (match-beginning 3) (match-end 3) vp)
3588 (add-text-properties (match-end 3) (match-end 0) ip))
3589 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3590 (add-text-properties (match-beginning 1) (match-end 1) vp)
3591 (add-text-properties (match-end 1) (match-end 0) ip))
3592 t)))
3594 (defun org-activate-dates (limit)
3595 "Run through the buffer and add overlays to dates."
3596 (if (re-search-forward org-tsr-regexp-both limit t)
3597 (progn
3598 (add-text-properties (match-beginning 0) (match-end 0)
3599 (list 'mouse-face 'highlight
3600 'rear-nonsticky org-nonsticky-props
3601 'keymap org-mouse-map))
3602 (when org-display-custom-times
3603 (if (match-end 3)
3604 (org-display-custom-time (match-beginning 3) (match-end 3)))
3605 (org-display-custom-time (match-beginning 1) (match-end 1)))
3606 t)))
3608 (defvar org-target-link-regexp nil
3609 "Regular expression matching radio targets in plain text.")
3610 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3611 "Regular expression matching a link target.")
3612 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3613 "Regular expression matching a radio target.")
3614 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3615 "Regular expression matching any target.")
3617 (defun org-activate-target-links (limit)
3618 "Run through the buffer and add overlays to target matches."
3619 (when org-target-link-regexp
3620 (let ((case-fold-search t))
3621 (if (re-search-forward org-target-link-regexp limit t)
3622 (progn
3623 (add-text-properties (match-beginning 0) (match-end 0)
3624 (list 'mouse-face 'highlight
3625 'rear-nonsticky org-nonsticky-props
3626 'keymap org-mouse-map
3627 'help-echo "Radio target link"
3628 'org-linked-text t))
3629 t)))))
3631 (defun org-update-radio-target-regexp ()
3632 "Find all radio targets in this file and update the regular expression."
3633 (interactive)
3634 (when (memq 'radio org-activate-links)
3635 (setq org-target-link-regexp
3636 (org-make-target-link-regexp (org-all-targets 'radio)))
3637 (org-restart-font-lock)))
3639 (defun org-hide-wide-columns (limit)
3640 (let (s e)
3641 (setq s (text-property-any (point) (or limit (point-max))
3642 'org-cwidth t))
3643 (when s
3644 (setq e (next-single-property-change s 'org-cwidth))
3645 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3646 (goto-char e)
3647 t)))
3649 (defvar org-latex-and-specials-regexp nil
3650 "Regular expression for highlighting export special stuff.")
3651 (defvar org-match-substring-regexp)
3652 (defvar org-match-substring-with-braces-regexp)
3653 (defvar org-export-html-special-string-regexps)
3655 (defun org-compute-latex-and-specials-regexp ()
3656 "Compute regular expression for stuff treated specially by exporters."
3657 (if (not org-highlight-latex-fragments-and-specials)
3658 (org-set-local 'org-latex-and-specials-regexp nil)
3659 (require 'org-exp)
3660 (let*
3661 ((matchers (plist-get org-format-latex-options :matchers))
3662 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3663 org-latex-regexps)))
3664 (options (org-combine-plists (org-default-export-plist)
3665 (org-infile-export-plist)))
3666 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3667 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3668 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3669 (org-export-html-expand (plist-get options :expand-quoted-html))
3670 (org-export-with-special-strings (plist-get options :special-strings))
3671 (re-sub
3672 (cond
3673 ((equal org-export-with-sub-superscripts '{})
3674 (list org-match-substring-with-braces-regexp))
3675 (org-export-with-sub-superscripts
3676 (list org-match-substring-regexp))
3677 (t nil)))
3678 (re-latex
3679 (if org-export-with-LaTeX-fragments
3680 (mapcar (lambda (x) (nth 1 x)) latexs)))
3681 (re-macros
3682 (if org-export-with-TeX-macros
3683 (list (concat "\\\\"
3684 (regexp-opt
3685 (append (mapcar 'car org-html-entities)
3686 (if (boundp 'org-latex-entities)
3687 org-latex-entities nil))
3688 'words))) ; FIXME
3690 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3691 (re-special (if org-export-with-special-strings
3692 (mapcar (lambda (x) (car x))
3693 org-export-html-special-string-regexps)))
3694 (re-rest
3695 (delq nil
3696 (list
3697 (if org-export-html-expand "@<[^>\n]+>")
3698 ))))
3699 (org-set-local
3700 'org-latex-and-specials-regexp
3701 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3702 re-rest) "\\|")))))
3704 (defun org-do-latex-and-special-faces (limit)
3705 "Run through the buffer and add overlays to links."
3706 (when org-latex-and-specials-regexp
3707 (let (rtn d)
3708 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3709 limit t))
3710 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3711 'face))
3712 '(org-code org-verbatim underline)))
3713 (progn
3714 (setq rtn t
3715 d (cond ((member (char-after (1+ (match-beginning 0)))
3716 '(?_ ?^)) 1)
3717 (t 0)))
3718 (font-lock-prepend-text-property
3719 (+ d (match-beginning 0)) (match-end 0)
3720 'face 'org-latex-and-export-specials)
3721 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3722 '(font-lock-multiline t)))))
3723 rtn)))
3725 (defun org-restart-font-lock ()
3726 "Restart font-lock-mode, to force refontification."
3727 (when (and (boundp 'font-lock-mode) font-lock-mode)
3728 (font-lock-mode -1)
3729 (font-lock-mode 1)))
3731 (defun org-all-targets (&optional radio)
3732 "Return a list of all targets in this file.
3733 With optional argument RADIO, only find radio targets."
3734 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3735 rtn)
3736 (save-excursion
3737 (goto-char (point-min))
3738 (while (re-search-forward re nil t)
3739 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3740 rtn)))
3742 (defun org-make-target-link-regexp (targets)
3743 "Make regular expression matching all strings in TARGETS.
3744 The regular expression finds the targets also if there is a line break
3745 between words."
3746 (and targets
3747 (concat
3748 "\\<\\("
3749 (mapconcat
3750 (lambda (x)
3751 (while (string-match " +" x)
3752 (setq x (replace-match "\\s-+" t t x)))
3754 targets
3755 "\\|")
3756 "\\)\\>")))
3758 (defun org-activate-tags (limit)
3759 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3760 (progn
3761 (add-text-properties (match-beginning 1) (match-end 1)
3762 (list 'mouse-face 'highlight
3763 'rear-nonsticky org-nonsticky-props
3764 'keymap org-mouse-map))
3765 t)))
3767 (defun org-outline-level ()
3768 (save-excursion
3769 (looking-at outline-regexp)
3770 (if (match-beginning 1)
3771 (+ (org-get-string-indentation (match-string 1)) 1000)
3772 (1- (- (match-end 0) (match-beginning 0))))))
3774 (defvar org-font-lock-keywords nil)
3776 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3777 "Regular expression matching a property line.")
3779 (defvar org-font-lock-hook nil
3780 "Functions to be called for special font lock stuff.")
3782 (defun org-font-lock-hook (limit)
3783 (run-hook-with-args 'org-font-lock-hook limit))
3785 (defun org-set-font-lock-defaults ()
3786 (let* ((em org-fontify-emphasized-text)
3787 (lk org-activate-links)
3788 (org-font-lock-extra-keywords
3789 (list
3790 ;; Call the hook
3791 '(org-font-lock-hook)
3792 ;; Headlines
3793 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3794 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3795 ;; Table lines
3796 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3797 (1 'org-table t))
3798 ;; Table internals
3799 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3800 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3801 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3802 ;; Drawers
3803 (list org-drawer-regexp '(0 'org-special-keyword t))
3804 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3805 ;; Properties
3806 (list org-property-re
3807 '(1 'org-special-keyword t)
3808 '(3 'org-property-value t))
3809 (if org-format-transports-properties-p
3810 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3811 ;; Links
3812 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3813 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3814 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3815 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3816 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3817 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3818 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3819 '(org-hide-wide-columns (0 nil append))
3820 ;; TODO lines
3821 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3822 '(1 (org-get-todo-face 1) t))
3823 ;; DONE
3824 (if org-fontify-done-headline
3825 (list (concat "^[*]+ +\\<\\("
3826 (mapconcat 'regexp-quote org-done-keywords "\\|")
3827 "\\)\\(.*\\)")
3828 '(2 'org-headline-done t))
3829 nil)
3830 ;; Priorities
3831 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3832 ;; Special keywords
3833 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3834 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3835 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3836 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3837 ;; Emphasis
3838 (if em
3839 (if (featurep 'xemacs)
3840 '(org-do-emphasis-faces (0 nil append))
3841 '(org-do-emphasis-faces)))
3842 ;; Checkboxes
3843 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3844 2 'bold prepend)
3845 (if org-provide-checkbox-statistics
3846 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3847 (0 (org-get-checkbox-statistics-face) t)))
3848 ;; Description list items
3849 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3850 2 'bold prepend)
3851 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3852 '(1 'org-archived prepend))
3853 ;; Specials
3854 '(org-do-latex-and-special-faces)
3855 ;; Code
3856 '(org-activate-code (1 'org-code t))
3857 ;; COMMENT
3858 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3859 "\\|" org-quote-string "\\)\\>")
3860 '(1 'org-special-keyword t))
3861 '("^#.*" (0 'font-lock-comment-face t))
3863 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3864 ;; Now set the full font-lock-keywords
3865 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3866 (org-set-local 'font-lock-defaults
3867 '(org-font-lock-keywords t nil nil backward-paragraph))
3868 (kill-local-variable 'font-lock-keywords) nil))
3870 (defvar org-m nil)
3871 (defvar org-l nil)
3872 (defvar org-f nil)
3873 (defun org-get-level-face (n)
3874 "Get the right face for match N in font-lock matching of healdines."
3875 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3876 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3877 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3878 (cond
3879 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3880 ((eq n 2) org-f)
3881 (t (if org-level-color-stars-only nil org-f))))
3883 (defun org-get-todo-face (kwd)
3884 "Get the right face for a TODO keyword KWD.
3885 If KWD is a number, get the corresponding match group."
3886 (if (numberp kwd) (setq kwd (match-string kwd)))
3887 (or (cdr (assoc kwd org-todo-keyword-faces))
3888 (and (member kwd org-done-keywords) 'org-done)
3889 'org-todo))
3891 (defun org-unfontify-region (beg end &optional maybe_loudly)
3892 "Remove fontification and activation overlays from links."
3893 (font-lock-default-unfontify-region beg end)
3894 (let* ((buffer-undo-list t)
3895 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3896 (inhibit-modification-hooks t)
3897 deactivate-mark buffer-file-name buffer-file-truename)
3898 (remove-text-properties beg end
3899 '(mouse-face t keymap t org-linked-text t
3900 invisible t intangible t))))
3902 ;;;; Visibility cycling, including org-goto and indirect buffer
3904 ;;; Cycling
3906 (defvar org-cycle-global-status nil)
3907 (make-variable-buffer-local 'org-cycle-global-status)
3908 (defvar org-cycle-subtree-status nil)
3909 (make-variable-buffer-local 'org-cycle-subtree-status)
3911 ;;;###autoload
3912 (defun org-cycle (&optional arg)
3913 "Visibility cycling for Org-mode.
3915 - When this function is called with a prefix argument, rotate the entire
3916 buffer through 3 states (global cycling)
3917 1. OVERVIEW: Show only top-level headlines.
3918 2. CONTENTS: Show all headlines of all levels, but no body text.
3919 3. SHOW ALL: Show everything.
3920 When called with two C-c C-u prefixes, switch to the startup visibility,
3921 determined by the variable `org-startup-folded', and by any VISIBILITY
3922 properties in the buffer.
3924 - When point is at the beginning of a headline, rotate the subtree started
3925 by this line through 3 different states (local cycling)
3926 1. FOLDED: Only the main headline is shown.
3927 2. CHILDREN: The main headline and the direct children are shown.
3928 From this state, you can move to one of the children
3929 and zoom in further.
3930 3. SUBTREE: Show the entire subtree, including body text.
3932 - When there is a numeric prefix, go up to a heading with level ARG, do
3933 a `show-subtree' and return to the previous cursor position. If ARG
3934 is negative, go up that many levels.
3936 - When point is not at the beginning of a headline, execute the global
3937 binding for TAB, which is re-indenting the line. See the option
3938 `org-cycle-emulate-tab' for details.
3940 - Special case: if point is at the beginning of the buffer and there is
3941 no headline in line 1, this function will act as if called with prefix arg.
3942 But only if also the variable `org-cycle-global-at-bob' is t."
3943 (interactive "P")
3944 (org-load-modules-maybe)
3945 (let* ((outline-regexp
3946 (if (and (org-mode-p) org-cycle-include-plain-lists)
3947 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3948 outline-regexp))
3949 (bob-special (and org-cycle-global-at-bob (bobp)
3950 (not (looking-at outline-regexp))))
3951 (org-cycle-hook
3952 (if bob-special
3953 (delq 'org-optimize-window-after-visibility-change
3954 (copy-sequence org-cycle-hook))
3955 org-cycle-hook))
3956 (pos (point)))
3958 (if (or bob-special (equal arg '(4)))
3959 ;; special case: use global cycling
3960 (setq arg t))
3962 (cond
3964 ((equal arg '(16))
3965 (org-set-startup-visibility)
3966 (message "Startup visibility, plus VISIBILITY properties."))
3968 ((org-at-table-p 'any)
3969 ;; Enter the table or move to the next field in the table
3970 (or (org-table-recognize-table.el)
3971 (progn
3972 (if arg (org-table-edit-field t)
3973 (org-table-justify-field-maybe)
3974 (call-interactively 'org-table-next-field)))))
3976 ((eq arg t) ;; Global cycling
3978 (cond
3979 ((and (eq last-command this-command)
3980 (eq org-cycle-global-status 'overview))
3981 ;; We just created the overview - now do table of contents
3982 ;; This can be slow in very large buffers, so indicate action
3983 (message "CONTENTS...")
3984 (org-content)
3985 (message "CONTENTS...done")
3986 (setq org-cycle-global-status 'contents)
3987 (run-hook-with-args 'org-cycle-hook 'contents))
3989 ((and (eq last-command this-command)
3990 (eq org-cycle-global-status 'contents))
3991 ;; We just showed the table of contents - now show everything
3992 (show-all)
3993 (message "SHOW ALL")
3994 (setq org-cycle-global-status 'all)
3995 (run-hook-with-args 'org-cycle-hook 'all))
3998 ;; Default action: go to overview
3999 (org-overview)
4000 (message "OVERVIEW")
4001 (setq org-cycle-global-status 'overview)
4002 (run-hook-with-args 'org-cycle-hook 'overview))))
4004 ((and org-drawers org-drawer-regexp
4005 (save-excursion
4006 (beginning-of-line 1)
4007 (looking-at org-drawer-regexp)))
4008 ;; Toggle block visibility
4009 (org-flag-drawer
4010 (not (get-char-property (match-end 0) 'invisible))))
4012 ((integerp arg)
4013 ;; Show-subtree, ARG levels up from here.
4014 (save-excursion
4015 (org-back-to-heading)
4016 (outline-up-heading (if (< arg 0) (- arg)
4017 (- (funcall outline-level) arg)))
4018 (org-show-subtree)))
4020 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4021 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4022 ;; At a heading: rotate between three different views
4023 (org-back-to-heading)
4024 (let ((goal-column 0) eoh eol eos)
4025 ;; First, some boundaries
4026 (save-excursion
4027 (org-back-to-heading)
4028 (save-excursion
4029 (beginning-of-line 2)
4030 (while (and (not (eobp)) ;; this is like `next-line'
4031 (get-char-property (1- (point)) 'invisible))
4032 (beginning-of-line 2)) (setq eol (point)))
4033 (outline-end-of-heading) (setq eoh (point))
4034 (org-end-of-subtree t)
4035 (unless (eobp)
4036 (skip-chars-forward " \t\n")
4037 (beginning-of-line 1) ; in case this is an item
4039 (setq eos (1- (point))))
4040 ;; Find out what to do next and set `this-command'
4041 (cond
4042 ((= eos eoh)
4043 ;; Nothing is hidden behind this heading
4044 (message "EMPTY ENTRY")
4045 (setq org-cycle-subtree-status nil)
4046 (save-excursion
4047 (goto-char eos)
4048 (outline-next-heading)
4049 (if (org-invisible-p) (org-flag-heading nil))))
4050 ((or (>= eol eos)
4051 (not (string-match "\\S-" (buffer-substring eol eos))))
4052 ;; Entire subtree is hidden in one line: open it
4053 (org-show-entry)
4054 (show-children)
4055 (message "CHILDREN")
4056 (save-excursion
4057 (goto-char eos)
4058 (outline-next-heading)
4059 (if (org-invisible-p) (org-flag-heading nil)))
4060 (setq org-cycle-subtree-status 'children)
4061 (run-hook-with-args 'org-cycle-hook 'children))
4062 ((and (eq last-command this-command)
4063 (eq org-cycle-subtree-status 'children))
4064 ;; We just showed the children, now show everything.
4065 (org-show-subtree)
4066 (message "SUBTREE")
4067 (setq org-cycle-subtree-status 'subtree)
4068 (run-hook-with-args 'org-cycle-hook 'subtree))
4070 ;; Default action: hide the subtree.
4071 (hide-subtree)
4072 (message "FOLDED")
4073 (setq org-cycle-subtree-status 'folded)
4074 (run-hook-with-args 'org-cycle-hook 'folded)))))
4076 ;; TAB emulation and template completion
4077 (buffer-read-only (org-back-to-heading))
4079 ((org-try-structure-completion))
4081 ((org-try-cdlatex-tab))
4083 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4084 (or (not (bolp))
4085 (not (looking-at outline-regexp))))
4086 (call-interactively (global-key-binding "\t")))
4088 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4089 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4090 (or (and (eq org-cycle-emulate-tab 'white)
4091 (= (match-end 0) (point-at-eol)))
4092 (and (eq org-cycle-emulate-tab 'whitestart)
4093 (>= (match-end 0) pos))))
4095 (eq org-cycle-emulate-tab t))
4096 (call-interactively (global-key-binding "\t")))
4098 (t (save-excursion
4099 (org-back-to-heading)
4100 (org-cycle))))))
4102 ;;;###autoload
4103 (defun org-global-cycle (&optional arg)
4104 "Cycle the global visibility. For details see `org-cycle'.
4105 With C-u prefix arg, switch to startup visibility.
4106 With a numeric prefix, show all headlines up to that level."
4107 (interactive "P")
4108 (let ((org-cycle-include-plain-lists
4109 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4110 (cond
4111 ((integerp arg)
4112 (show-all)
4113 (hide-sublevels arg)
4114 (setq org-cycle-global-status 'contents))
4115 ((equal arg '(4))
4116 (org-set-startup-visibility)
4117 (message "Startup visibility, plus VISIBILITY properties."))
4119 (org-cycle '(4))))))
4121 (defun org-set-startup-visibility ()
4122 "Set the visibility required by startup options and properties."
4123 (cond
4124 ((eq org-startup-folded t)
4125 (org-cycle '(4)))
4126 ((eq org-startup-folded 'content)
4127 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4128 (org-cycle '(4)) (org-cycle '(4)))))
4129 (org-set-visibility-according-to-property 'no-cleanup)
4130 (org-cycle-hide-archived-subtrees 'all)
4131 (org-cycle-hide-drawers 'all)
4132 (org-cycle-show-empty-lines 'all))
4134 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4135 "Switch subtree visibilities according to :VISIBILITY: property."
4136 (interactive)
4137 (let (state)
4138 (save-excursion
4139 (goto-char (point-min))
4140 (while (re-search-forward
4141 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4142 nil t)
4143 (setq state (match-string 1))
4144 (save-excursion
4145 (org-back-to-heading t)
4146 (hide-subtree)
4147 (org-reveal)
4148 (cond
4149 ((equal state '("fold" "folded"))
4150 (hide-subtree))
4151 ((equal state "children")
4152 (org-show-hidden-entry)
4153 (show-children))
4154 ((equal state "content")
4155 (save-excursion
4156 (save-restriction
4157 (org-narrow-to-subtree)
4158 (org-content))))
4159 ((member state '("all" "showall"))
4160 (show-subtree)))))
4161 (unless no-cleanup
4162 (org-cycle-hide-archived-subtrees 'all)
4163 (org-cycle-hide-drawers 'all)
4164 (org-cycle-show-empty-lines 'all)))))
4166 (defun org-overview ()
4167 "Switch to overview mode, shoing only top-level headlines.
4168 Really, this shows all headlines with level equal or greater than the level
4169 of the first headline in the buffer. This is important, because if the
4170 first headline is not level one, then (hide-sublevels 1) gives confusing
4171 results."
4172 (interactive)
4173 (let ((level (save-excursion
4174 (goto-char (point-min))
4175 (if (re-search-forward (concat "^" outline-regexp) nil t)
4176 (progn
4177 (goto-char (match-beginning 0))
4178 (funcall outline-level))))))
4179 (and level (hide-sublevels level))))
4181 (defun org-content (&optional arg)
4182 "Show all headlines in the buffer, like a table of contents.
4183 With numerical argument N, show content up to level N."
4184 (interactive "P")
4185 (save-excursion
4186 ;; Visit all headings and show their offspring
4187 (and (integerp arg) (org-overview))
4188 (goto-char (point-max))
4189 (catch 'exit
4190 (while (and (progn (condition-case nil
4191 (outline-previous-visible-heading 1)
4192 (error (goto-char (point-min))))
4194 (looking-at outline-regexp))
4195 (if (integerp arg)
4196 (show-children (1- arg))
4197 (show-branches))
4198 (if (bobp) (throw 'exit nil))))))
4201 (defun org-optimize-window-after-visibility-change (state)
4202 "Adjust the window after a change in outline visibility.
4203 This function is the default value of the hook `org-cycle-hook'."
4204 (when (get-buffer-window (current-buffer))
4205 (cond
4206 ; ((eq state 'overview) (org-first-headline-recenter 1))
4207 ; ((eq state 'overview) (org-beginning-of-line))
4208 ((eq state 'content) nil)
4209 ((eq state 'all) nil)
4210 ((eq state 'folded) nil)
4211 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4212 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4214 (defun org-compact-display-after-subtree-move ()
4215 (let (beg end)
4216 (save-excursion
4217 (if (org-up-heading-safe)
4218 (progn
4219 (hide-subtree)
4220 (show-entry)
4221 (show-children)
4222 (org-cycle-show-empty-lines 'children)
4223 (org-cycle-hide-drawers 'children))
4224 (org-overview)))))
4226 (defun org-cycle-show-empty-lines (state)
4227 "Show empty lines above all visible headlines.
4228 The region to be covered depends on STATE when called through
4229 `org-cycle-hook'. Lisp program can use t for STATE to get the
4230 entire buffer covered. Note that an empty line is only shown if there
4231 are at least `org-cycle-separator-lines' empty lines before the headeline."
4232 (when (> org-cycle-separator-lines 0)
4233 (save-excursion
4234 (let* ((n org-cycle-separator-lines)
4235 (re (cond
4236 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4237 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4238 (t (let ((ns (number-to-string (- n 2))))
4239 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4240 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4241 beg end)
4242 (cond
4243 ((memq state '(overview contents t))
4244 (setq beg (point-min) end (point-max)))
4245 ((memq state '(children folded))
4246 (setq beg (point) end (progn (org-end-of-subtree t t)
4247 (beginning-of-line 2)
4248 (point)))))
4249 (when beg
4250 (goto-char beg)
4251 (while (re-search-forward re end t)
4252 (if (not (get-char-property (match-end 1) 'invisible))
4253 (outline-flag-region
4254 (match-beginning 1) (match-end 1) nil)))))))
4255 ;; Never hide empty lines at the end of the file.
4256 (save-excursion
4257 (goto-char (point-max))
4258 (outline-previous-heading)
4259 (outline-end-of-heading)
4260 (if (and (looking-at "[ \t\n]+")
4261 (= (match-end 0) (point-max)))
4262 (outline-flag-region (point) (match-end 0) nil))))
4264 (defun org-show-empty-lines-in-parent ()
4265 "Move to the parent and re-show empty lines before visible headlines."
4266 (save-excursion
4267 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4268 (org-cycle-show-empty-lines context))))
4270 (defun org-cycle-hide-drawers (state)
4271 "Re-hide all drawers after a visibility state change."
4272 (when (and (org-mode-p)
4273 (not (memq state '(overview folded))))
4274 (save-excursion
4275 (let* ((globalp (memq state '(contents all)))
4276 (beg (if globalp (point-min) (point)))
4277 (end (if globalp (point-max) (org-end-of-subtree t))))
4278 (goto-char beg)
4279 (while (re-search-forward org-drawer-regexp end t)
4280 (org-flag-drawer t))))))
4282 (defun org-flag-drawer (flag)
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4286 (let ((b (match-end 0))
4287 (outline-regexp org-outline-regexp))
4288 (if (re-search-forward
4289 "^[ \t]*:END:"
4290 (save-excursion (outline-next-heading) (point)) t)
4291 (outline-flag-region b (point-at-eol) flag)
4292 (error ":END: line missing"))))))
4294 (defun org-subtree-end-visible-p ()
4295 "Is the end of the current subtree visible?"
4296 (pos-visible-in-window-p
4297 (save-excursion (org-end-of-subtree t) (point))))
4299 (defun org-first-headline-recenter (&optional N)
4300 "Move cursor to the first headline and recenter the headline.
4301 Optional argument N means, put the headline into the Nth line of the window."
4302 (goto-char (point-min))
4303 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4304 (beginning-of-line)
4305 (recenter (prefix-numeric-value N))))
4307 ;;; Org-goto
4309 (defvar org-goto-window-configuration nil)
4310 (defvar org-goto-marker nil)
4311 (defvar org-goto-map
4312 (let ((map (make-sparse-keymap)))
4313 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4314 (while (setq cmd (pop cmds))
4315 (substitute-key-definition cmd cmd map global-map)))
4316 (suppress-keymap map)
4317 (org-defkey map "\C-m" 'org-goto-ret)
4318 (org-defkey map [(return)] 'org-goto-ret)
4319 (org-defkey map [(left)] 'org-goto-left)
4320 (org-defkey map [(right)] 'org-goto-right)
4321 (org-defkey map [(control ?g)] 'org-goto-quit)
4322 (org-defkey map "\C-i" 'org-cycle)
4323 (org-defkey map [(tab)] 'org-cycle)
4324 (org-defkey map [(down)] 'outline-next-visible-heading)
4325 (org-defkey map [(up)] 'outline-previous-visible-heading)
4326 (if org-goto-auto-isearch
4327 (if (fboundp 'define-key-after)
4328 (define-key-after map [t] 'org-goto-local-auto-isearch)
4329 nil)
4330 (org-defkey map "q" 'org-goto-quit)
4331 (org-defkey map "n" 'outline-next-visible-heading)
4332 (org-defkey map "p" 'outline-previous-visible-heading)
4333 (org-defkey map "f" 'outline-forward-same-level)
4334 (org-defkey map "b" 'outline-backward-same-level)
4335 (org-defkey map "u" 'outline-up-heading))
4336 (org-defkey map "/" 'org-occur)
4337 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4338 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4339 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4340 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4341 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4342 map))
4344 (defconst org-goto-help
4345 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4346 RET=jump to location [Q]uit and return to previous location
4347 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4349 (defvar org-goto-start-pos) ; dynamically scoped parameter
4351 ;; FIXME: Docstring doe not mention both interfaces
4352 (defun org-goto (&optional alternative-interface)
4353 "Look up a different location in the current file, keeping current visibility.
4355 When you want look-up or go to a different location in a document, the
4356 fastest way is often to fold the entire buffer and then dive into the tree.
4357 This method has the disadvantage, that the previous location will be folded,
4358 which may not be what you want.
4360 This command works around this by showing a copy of the current buffer
4361 in an indirect buffer, in overview mode. You can dive into the tree in
4362 that copy, use org-occur and incremental search to find a location.
4363 When pressing RET or `Q', the command returns to the original buffer in
4364 which the visibility is still unchanged. After RET is will also jump to
4365 the location selected in the indirect buffer and expose the
4366 the headline hierarchy above."
4367 (interactive "P")
4368 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4369 (org-refile-use-outline-path t)
4370 (interface
4371 (if (not alternative-interface)
4372 org-goto-interface
4373 (if (eq org-goto-interface 'outline)
4374 'outline-path-completion
4375 'outline)))
4376 (org-goto-start-pos (point))
4377 (selected-point
4378 (if (eq interface 'outline)
4379 (car (org-get-location (current-buffer) org-goto-help))
4380 (nth 3 (org-refile-get-location "Goto: ")))))
4381 (if selected-point
4382 (progn
4383 (org-mark-ring-push org-goto-start-pos)
4384 (goto-char selected-point)
4385 (if (or (org-invisible-p) (org-invisible-p2))
4386 (org-show-context 'org-goto)))
4387 (message "Quit"))))
4389 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4390 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4391 (defvar org-goto-local-auto-isearch-map) ; defined below
4393 (defun org-get-location (buf help)
4394 "Let the user select a location in the Org-mode buffer BUF.
4395 This function uses a recursive edit. It returns the selected position
4396 or nil."
4397 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4398 (isearch-hide-immediately nil)
4399 (isearch-search-fun-function
4400 (lambda () 'org-goto-local-search-headings))
4401 (org-goto-selected-point org-goto-exit-command))
4402 (save-excursion
4403 (save-window-excursion
4404 (delete-other-windows)
4405 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4406 (switch-to-buffer
4407 (condition-case nil
4408 (make-indirect-buffer (current-buffer) "*org-goto*")
4409 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4410 (with-output-to-temp-buffer "*Help*"
4411 (princ help))
4412 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4413 (setq buffer-read-only nil)
4414 (let ((org-startup-truncated t)
4415 (org-startup-folded nil)
4416 (org-startup-align-all-tables nil))
4417 (org-mode)
4418 (org-overview))
4419 (setq buffer-read-only t)
4420 (if (and (boundp 'org-goto-start-pos)
4421 (integer-or-marker-p org-goto-start-pos))
4422 (let ((org-show-hierarchy-above t)
4423 (org-show-siblings t)
4424 (org-show-following-heading t))
4425 (goto-char org-goto-start-pos)
4426 (and (org-invisible-p) (org-show-context)))
4427 (goto-char (point-min)))
4428 (org-beginning-of-line)
4429 (message "Select location and press RET")
4430 (use-local-map org-goto-map)
4431 (recursive-edit)
4433 (kill-buffer "*org-goto*")
4434 (cons org-goto-selected-point org-goto-exit-command)))
4436 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4437 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4438 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4439 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4441 (defun org-goto-local-search-headings (string bound noerror)
4442 "Search and make sure that any matches are in headlines."
4443 (catch 'return
4444 (while (if isearch-forward
4445 (search-forward string bound noerror)
4446 (search-backward string bound noerror))
4447 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4448 (and (member :headline context)
4449 (not (member :tags context))))
4450 (throw 'return (point))))))
4452 (defun org-goto-local-auto-isearch ()
4453 "Start isearch."
4454 (interactive)
4455 (goto-char (point-min))
4456 (let ((keys (this-command-keys)))
4457 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4458 (isearch-mode t)
4459 (isearch-process-search-char (string-to-char keys)))))
4461 (defun org-goto-ret (&optional arg)
4462 "Finish `org-goto' by going to the new location."
4463 (interactive "P")
4464 (setq org-goto-selected-point (point)
4465 org-goto-exit-command 'return)
4466 (throw 'exit nil))
4468 (defun org-goto-left ()
4469 "Finish `org-goto' by going to the new location."
4470 (interactive)
4471 (if (org-on-heading-p)
4472 (progn
4473 (beginning-of-line 1)
4474 (setq org-goto-selected-point (point)
4475 org-goto-exit-command 'left)
4476 (throw 'exit nil))
4477 (error "Not on a heading")))
4479 (defun org-goto-right ()
4480 "Finish `org-goto' by going to the new location."
4481 (interactive)
4482 (if (org-on-heading-p)
4483 (progn
4484 (setq org-goto-selected-point (point)
4485 org-goto-exit-command 'right)
4486 (throw 'exit nil))
4487 (error "Not on a heading")))
4489 (defun org-goto-quit ()
4490 "Finish `org-goto' without cursor motion."
4491 (interactive)
4492 (setq org-goto-selected-point nil)
4493 (setq org-goto-exit-command 'quit)
4494 (throw 'exit nil))
4496 ;;; Indirect buffer display of subtrees
4498 (defvar org-indirect-dedicated-frame nil
4499 "This is the frame being used for indirect tree display.")
4500 (defvar org-last-indirect-buffer nil)
4502 (defun org-tree-to-indirect-buffer (&optional arg)
4503 "Create indirect buffer and narrow it to current subtree.
4504 With numerical prefix ARG, go up to this level and then take that tree.
4505 If ARG is negative, go up that many levels.
4506 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4507 indirect buffer previously made with this command, to avoid proliferation of
4508 indirect buffers. However, when you call the command with a `C-u' prefix, or
4509 when `org-indirect-buffer-display' is `new-frame', the last buffer
4510 is kept so that you can work with several indirect buffers at the same time.
4511 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4512 requests that a new frame be made for the new buffer, so that the dedicated
4513 frame is not changed."
4514 (interactive "P")
4515 (let ((cbuf (current-buffer))
4516 (cwin (selected-window))
4517 (pos (point))
4518 beg end level heading ibuf)
4519 (save-excursion
4520 (org-back-to-heading t)
4521 (when (numberp arg)
4522 (setq level (org-outline-level))
4523 (if (< arg 0) (setq arg (+ level arg)))
4524 (while (> (setq level (org-outline-level)) arg)
4525 (outline-up-heading 1 t)))
4526 (setq beg (point)
4527 heading (org-get-heading))
4528 (org-end-of-subtree t) (setq end (point)))
4529 (if (and (buffer-live-p org-last-indirect-buffer)
4530 (not (eq org-indirect-buffer-display 'new-frame))
4531 (not arg))
4532 (kill-buffer org-last-indirect-buffer))
4533 (setq ibuf (org-get-indirect-buffer cbuf)
4534 org-last-indirect-buffer ibuf)
4535 (cond
4536 ((or (eq org-indirect-buffer-display 'new-frame)
4537 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4538 (select-frame (make-frame))
4539 (delete-other-windows)
4540 (switch-to-buffer ibuf)
4541 (org-set-frame-title heading))
4542 ((eq org-indirect-buffer-display 'dedicated-frame)
4543 (raise-frame
4544 (select-frame (or (and org-indirect-dedicated-frame
4545 (frame-live-p org-indirect-dedicated-frame)
4546 org-indirect-dedicated-frame)
4547 (setq org-indirect-dedicated-frame (make-frame)))))
4548 (delete-other-windows)
4549 (switch-to-buffer ibuf)
4550 (org-set-frame-title (concat "Indirect: " heading)))
4551 ((eq org-indirect-buffer-display 'current-window)
4552 (switch-to-buffer ibuf))
4553 ((eq org-indirect-buffer-display 'other-window)
4554 (pop-to-buffer ibuf))
4555 (t (error "Invalid value.")))
4556 (if (featurep 'xemacs)
4557 (save-excursion (org-mode) (turn-on-font-lock)))
4558 (narrow-to-region beg end)
4559 (show-all)
4560 (goto-char pos)
4561 (and (window-live-p cwin) (select-window cwin))))
4563 (defun org-get-indirect-buffer (&optional buffer)
4564 (setq buffer (or buffer (current-buffer)))
4565 (let ((n 1) (base (buffer-name buffer)) bname)
4566 (while (buffer-live-p
4567 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4568 (setq n (1+ n)))
4569 (condition-case nil
4570 (make-indirect-buffer buffer bname 'clone)
4571 (error (make-indirect-buffer buffer bname)))))
4573 (defun org-set-frame-title (title)
4574 "Set the title of the current frame to the string TITLE."
4575 ;; FIXME: how to name a single frame in XEmacs???
4576 (unless (featurep 'xemacs)
4577 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4579 ;;;; Structure editing
4581 ;;; Inserting headlines
4583 (defun org-insert-heading (&optional force-heading)
4584 "Insert a new heading or item with same depth at point.
4585 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4586 If point is at the beginning of a headline, insert a sibling before the
4587 current headline. If point is not at the beginning, do not split the line,
4588 but create the new hedline after the current line."
4589 (interactive "P")
4590 (if (= (buffer-size) 0)
4591 (insert "\n* ")
4592 (when (or force-heading (not (org-insert-item)))
4593 (let* ((head (save-excursion
4594 (condition-case nil
4595 (progn
4596 (org-back-to-heading)
4597 (match-string 0))
4598 (error "*"))))
4599 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4600 pos)
4601 (cond
4602 ((and (org-on-heading-p) (bolp)
4603 (or (bobp)
4604 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4605 ;; insert before the current line
4606 (open-line (if blank 2 1)))
4607 ((and (bolp)
4608 (or (bobp)
4609 (save-excursion
4610 (backward-char 1) (not (org-invisible-p)))))
4611 ;; insert right here
4612 nil)
4614 ;; in the middle of the line
4615 (org-show-entry)
4616 (let ((split
4617 (org-get-alist-option org-M-RET-may-split-line 'headline))
4618 tags pos)
4619 (cond
4620 (org-insert-heading-respect-content
4621 (org-end-of-subtree nil t)
4622 (open-line 1))
4623 ((org-on-heading-p)
4624 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4625 (setq tags (and (match-end 2) (match-string 2)))
4626 (and (match-end 1)
4627 (delete-region (match-beginning 1) (match-end 1)))
4628 (setq pos (point-at-bol))
4629 (or split (end-of-line 1))
4630 (delete-horizontal-space)
4631 (newline (if blank 2 1))
4632 (when tags
4633 (save-excursion
4634 (goto-char pos)
4635 (end-of-line 1)
4636 (insert " " tags)
4637 (org-set-tags nil 'align))))
4639 (or split (end-of-line 1))
4640 (newline (if blank 2 1)))))))
4641 (insert head) (just-one-space)
4642 (setq pos (point))
4643 (end-of-line 1)
4644 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4645 (run-hooks 'org-insert-heading-hook)))))
4647 (defun org-get-heading (&optional no-tags)
4648 "Return the heading of the current entry, without the stars."
4649 (save-excursion
4650 (org-back-to-heading t)
4651 (if (looking-at
4652 (if no-tags
4653 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4654 "\\*+[ \t]+\\([^\r\n]*\\)"))
4655 (match-string 1) "")))
4657 (defun org-insert-heading-after-current ()
4658 "Insert a new heading with same level as current, after current subtree."
4659 (interactive)
4660 (org-back-to-heading)
4661 (org-insert-heading)
4662 (org-move-subtree-down)
4663 (end-of-line 1))
4665 (defun org-insert-heading-respect-content ()
4666 (interactive)
4667 (let ((org-insert-heading-respect-content t))
4668 (call-interactively 'org-insert-heading)))
4670 (defun org-insert-todo-heading-respect-content ()
4671 (interactive)
4672 (let ((org-insert-heading-respect-content t))
4673 (call-interactively 'org-insert-todo-todo-heading)))
4675 (defun org-insert-todo-heading (arg)
4676 "Insert a new heading with the same level and TODO state as current heading.
4677 If the heading has no TODO state, or if the state is DONE, use the first
4678 state (TODO by default). Also with prefix arg, force first state."
4679 (interactive "P")
4680 (when (not (org-insert-item 'checkbox))
4681 (org-insert-heading)
4682 (save-excursion
4683 (org-back-to-heading)
4684 (outline-previous-heading)
4685 (looking-at org-todo-line-regexp))
4686 (if (or arg
4687 (not (match-beginning 2))
4688 (member (match-string 2) org-done-keywords))
4689 (insert (car org-todo-keywords-1) " ")
4690 (insert (match-string 2) " "))
4691 (when org-provide-todo-statistics
4692 (org-update-parent-todo-statistics))))
4694 (defun org-insert-subheading (arg)
4695 "Insert a new subheading and demote it.
4696 Works for outline headings and for plain lists alike."
4697 (interactive "P")
4698 (org-insert-heading arg)
4699 (cond
4700 ((org-on-heading-p) (org-do-demote))
4701 ((org-at-item-p) (org-indent-item 1))))
4703 (defun org-insert-todo-subheading (arg)
4704 "Insert a new subheading with TODO keyword or checkbox and demote it.
4705 Works for outline headings and for plain lists alike."
4706 (interactive "P")
4707 (org-insert-todo-heading arg)
4708 (cond
4709 ((org-on-heading-p) (org-do-demote))
4710 ((org-at-item-p) (org-indent-item 1))))
4712 ;;; Promotion and Demotion
4714 (defun org-promote-subtree ()
4715 "Promote the entire subtree.
4716 See also `org-promote'."
4717 (interactive)
4718 (save-excursion
4719 (org-map-tree 'org-promote))
4720 (org-fix-position-after-promote))
4722 (defun org-demote-subtree ()
4723 "Demote the entire subtree. See `org-demote'.
4724 See also `org-promote'."
4725 (interactive)
4726 (save-excursion
4727 (org-map-tree 'org-demote))
4728 (org-fix-position-after-promote))
4731 (defun org-do-promote ()
4732 "Promote the current heading higher up the tree.
4733 If the region is active in `transient-mark-mode', promote all headings
4734 in the region."
4735 (interactive)
4736 (save-excursion
4737 (if (org-region-active-p)
4738 (org-map-region 'org-promote (region-beginning) (region-end))
4739 (org-promote)))
4740 (org-fix-position-after-promote))
4742 (defun org-do-demote ()
4743 "Demote the current heading lower down the tree.
4744 If the region is active in `transient-mark-mode', demote all headings
4745 in the region."
4746 (interactive)
4747 (save-excursion
4748 (if (org-region-active-p)
4749 (org-map-region 'org-demote (region-beginning) (region-end))
4750 (org-demote)))
4751 (org-fix-position-after-promote))
4753 (defun org-fix-position-after-promote ()
4754 "Make sure that after pro/demotion cursor position is right."
4755 (let ((pos (point)))
4756 (when (save-excursion
4757 (beginning-of-line 1)
4758 (looking-at org-todo-line-regexp)
4759 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4760 (cond ((eobp) (insert " "))
4761 ((eolp) (insert " "))
4762 ((equal (char-after) ?\ ) (forward-char 1))))))
4764 (defun org-reduced-level (l)
4765 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4767 (defun org-get-valid-level (level &optional change)
4768 "Rectify a level change under the influence of `org-odd-levels-only'
4769 LEVEL is a current level, CHANGE is by how much the level should be
4770 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4771 even level numbers will become the next higher odd number."
4772 (if org-odd-levels-only
4773 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4774 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4775 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4776 (max 1 (+ level change))))
4778 (if (boundp 'define-obsolete-function-alias)
4779 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4780 (define-obsolete-function-alias 'org-get-legal-level
4781 'org-get-valid-level)
4782 (define-obsolete-function-alias 'org-get-legal-level
4783 'org-get-valid-level "23.1")))
4785 (defun org-promote ()
4786 "Promote the current heading higher up the tree.
4787 If the region is active in `transient-mark-mode', promote all headings
4788 in the region."
4789 (org-back-to-heading t)
4790 (let* ((level (save-match-data (funcall outline-level)))
4791 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4792 (diff (abs (- level (length up-head) -1))))
4793 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4794 (replace-match up-head nil t)
4795 ;; Fixup tag positioning
4796 (and org-auto-align-tags (org-set-tags nil t))
4797 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4799 (defun org-demote ()
4800 "Demote the current heading lower down the tree.
4801 If the region is active in `transient-mark-mode', demote all headings
4802 in the region."
4803 (org-back-to-heading t)
4804 (let* ((level (save-match-data (funcall outline-level)))
4805 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4806 (diff (abs (- level (length down-head) -1))))
4807 (replace-match down-head nil t)
4808 ;; Fixup tag positioning
4809 (and org-auto-align-tags (org-set-tags nil t))
4810 (if org-adapt-indentation (org-fixup-indentation diff))))
4812 (defun org-map-tree (fun)
4813 "Call FUN for every heading underneath the current one."
4814 (org-back-to-heading)
4815 (let ((level (funcall outline-level)))
4816 (save-excursion
4817 (funcall fun)
4818 (while (and (progn
4819 (outline-next-heading)
4820 (> (funcall outline-level) level))
4821 (not (eobp)))
4822 (funcall fun)))))
4824 (defun org-map-region (fun beg end)
4825 "Call FUN for every heading between BEG and END."
4826 (let ((org-ignore-region t))
4827 (save-excursion
4828 (setq end (copy-marker end))
4829 (goto-char beg)
4830 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4831 (< (point) end))
4832 (funcall fun))
4833 (while (and (progn
4834 (outline-next-heading)
4835 (< (point) end))
4836 (not (eobp)))
4837 (funcall fun)))))
4839 (defun org-fixup-indentation (diff)
4840 "Change the indentation in the current entry by DIFF
4841 However, if any line in the current entry has no indentation, or if it
4842 would end up with no indentation after the change, nothing at all is done."
4843 (save-excursion
4844 (let ((end (save-excursion (outline-next-heading)
4845 (point-marker)))
4846 (prohibit (if (> diff 0)
4847 "^\\S-"
4848 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4849 col)
4850 (unless (save-excursion (end-of-line 1)
4851 (re-search-forward prohibit end t))
4852 (while (and (< (point) end)
4853 (re-search-forward "^[ \t]+" end t))
4854 (goto-char (match-end 0))
4855 (setq col (current-column))
4856 (if (< diff 0) (replace-match ""))
4857 (indent-to (+ diff col))))
4858 (move-marker end nil))))
4860 (defun org-convert-to-odd-levels ()
4861 "Convert an org-mode file with all levels allowed to one with odd levels.
4862 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4863 level 5 etc."
4864 (interactive)
4865 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4866 (let ((org-odd-levels-only nil) n)
4867 (save-excursion
4868 (goto-char (point-min))
4869 (while (re-search-forward "^\\*\\*+ " nil t)
4870 (setq n (- (length (match-string 0)) 2))
4871 (while (>= (setq n (1- n)) 0)
4872 (org-demote))
4873 (end-of-line 1))))))
4876 (defun org-convert-to-oddeven-levels ()
4877 "Convert an org-mode file with only odd levels to one with odd and even levels.
4878 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4879 section with an even level, conversion would destroy the structure of the file. An error
4880 is signaled in this case."
4881 (interactive)
4882 (goto-char (point-min))
4883 ;; First check if there are no even levels
4884 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4885 (org-show-context t)
4886 (error "Not all levels are odd in this file. Conversion not possible."))
4887 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4888 (let ((org-odd-levels-only nil) n)
4889 (save-excursion
4890 (goto-char (point-min))
4891 (while (re-search-forward "^\\*\\*+ " nil t)
4892 (setq n (/ (1- (length (match-string 0))) 2))
4893 (while (>= (setq n (1- n)) 0)
4894 (org-promote))
4895 (end-of-line 1))))))
4897 (defun org-tr-level (n)
4898 "Make N odd if required."
4899 (if org-odd-levels-only (1+ (/ n 2)) n))
4901 ;;; Vertical tree motion, cutting and pasting of subtrees
4903 (defun org-move-subtree-up (&optional arg)
4904 "Move the current subtree up past ARG headlines of the same level."
4905 (interactive "p")
4906 (org-move-subtree-down (- (prefix-numeric-value arg))))
4908 (defun org-move-subtree-down (&optional arg)
4909 "Move the current subtree down past ARG headlines of the same level."
4910 (interactive "p")
4911 (setq arg (prefix-numeric-value arg))
4912 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4913 'outline-get-last-sibling))
4914 (ins-point (make-marker))
4915 (cnt (abs arg))
4916 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4917 ;; Select the tree
4918 (org-back-to-heading)
4919 (setq beg0 (point))
4920 (save-excursion
4921 (setq ne-beg (org-back-over-empty-lines))
4922 (setq beg (point)))
4923 (save-match-data
4924 (save-excursion (outline-end-of-heading)
4925 (setq folded (org-invisible-p)))
4926 (outline-end-of-subtree))
4927 (outline-next-heading)
4928 (setq ne-end (org-back-over-empty-lines))
4929 (setq end (point))
4930 (goto-char beg0)
4931 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4932 ;; include less whitespace
4933 (save-excursion
4934 (goto-char beg)
4935 (forward-line (- ne-beg ne-end))
4936 (setq beg (point))))
4937 ;; Find insertion point, with error handling
4938 (while (> cnt 0)
4939 (or (and (funcall movfunc) (looking-at outline-regexp))
4940 (progn (goto-char beg0)
4941 (error "Cannot move past superior level or buffer limit")))
4942 (setq cnt (1- cnt)))
4943 (if (> arg 0)
4944 ;; Moving forward - still need to move over subtree
4945 (progn (org-end-of-subtree t t)
4946 (save-excursion
4947 (org-back-over-empty-lines)
4948 (or (bolp) (newline)))))
4949 (setq ne-ins (org-back-over-empty-lines))
4950 (move-marker ins-point (point))
4951 (setq txt (buffer-substring beg end))
4952 (org-save-markers-in-region beg end)
4953 (delete-region beg end)
4954 (outline-flag-region (1- beg) beg nil)
4955 (outline-flag-region (1- (point)) (point) nil)
4956 (let ((bbb (point)))
4957 (insert-before-markers txt)
4958 (org-reinstall-markers-in-region bbb)
4959 (move-marker ins-point bbb))
4960 (or (bolp) (insert "\n"))
4961 (setq ins-end (point))
4962 (goto-char ins-point)
4963 (org-skip-whitespace)
4964 (when (and (< arg 0)
4965 (org-first-sibling-p)
4966 (> ne-ins ne-beg))
4967 ;; Move whitespace back to beginning
4968 (save-excursion
4969 (goto-char ins-end)
4970 (let ((kill-whole-line t))
4971 (kill-line (- ne-ins ne-beg)) (point)))
4972 (insert (make-string (- ne-ins ne-beg) ?\n)))
4973 (move-marker ins-point nil)
4974 (org-compact-display-after-subtree-move)
4975 (org-show-empty-lines-in-parent)
4976 (unless folded
4977 (org-show-entry)
4978 (show-children)
4979 (org-cycle-hide-drawers 'children))))
4981 (defvar org-subtree-clip ""
4982 "Clipboard for cut and paste of subtrees.
4983 This is actually only a copy of the kill, because we use the normal kill
4984 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4986 (defvar org-subtree-clip-folded nil
4987 "Was the last copied subtree folded?
4988 This is used to fold the tree back after pasting.")
4990 (defun org-cut-subtree (&optional n)
4991 "Cut the current subtree into the clipboard.
4992 With prefix arg N, cut this many sequential subtrees.
4993 This is a short-hand for marking the subtree and then cutting it."
4994 (interactive "p")
4995 (org-copy-subtree n 'cut))
4997 (defun org-copy-subtree (&optional n cut force-store-markers)
4998 "Cut the current subtree into the clipboard.
4999 With prefix arg N, cut this many sequential subtrees.
5000 This is a short-hand for marking the subtree and then copying it.
5001 If CUT is non-nil, actually cut the subtree.
5002 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5003 of some markers in the region, even if CUT is non-nil. This is
5004 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5005 (interactive "p")
5006 (let (beg end folded (beg0 (point)))
5007 (if (interactive-p)
5008 (org-back-to-heading nil) ; take what looks like a subtree
5009 (org-back-to-heading t)) ; take what is really there
5010 (org-back-over-empty-lines)
5011 (setq beg (point))
5012 (skip-chars-forward " \t\r\n")
5013 (save-match-data
5014 (save-excursion (outline-end-of-heading)
5015 (setq folded (org-invisible-p)))
5016 (condition-case nil
5017 (outline-forward-same-level (1- n))
5018 (error nil))
5019 (org-end-of-subtree t t))
5020 (org-back-over-empty-lines)
5021 (setq end (point))
5022 (goto-char beg0)
5023 (when (> end beg)
5024 (setq org-subtree-clip-folded folded)
5025 (when (or cut force-store-markers)
5026 (org-save-markers-in-region beg end))
5027 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5028 (setq org-subtree-clip (current-kill 0))
5029 (message "%s: Subtree(s) with %d characters"
5030 (if cut "Cut" "Copied")
5031 (length org-subtree-clip)))))
5033 (defun org-paste-subtree (&optional level tree)
5034 "Paste the clipboard as a subtree, with modification of headline level.
5035 The entire subtree is promoted or demoted in order to match a new headline
5036 level. By default, the new level is derived from the visible headings
5037 before and after the insertion point, and taken to be the inferior headline
5038 level of the two. So if the previous visible heading is level 3 and the
5039 next is level 4 (or vice versa), level 4 will be used for insertion.
5040 This makes sure that the subtree remains an independent subtree and does
5041 not swallow low level entries.
5043 You can also force a different level, either by using a numeric prefix
5044 argument, or by inserting the heading marker by hand. For example, if the
5045 cursor is after \"*****\", then the tree will be shifted to level 5.
5047 If you want to insert the tree as is, just use \\[yank].
5049 If optional TREE is given, use this text instead of the kill ring."
5050 (interactive "P")
5051 (unless (org-kill-is-subtree-p tree)
5052 (error "%s"
5053 (substitute-command-keys
5054 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5055 (let* ((visp (not (org-invisible-p)))
5056 (txt (or tree (and kill-ring (current-kill 0))))
5057 (^re (concat "^\\(" outline-regexp "\\)"))
5058 (re (concat "\\(" outline-regexp "\\)"))
5059 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5061 (old-level (if (string-match ^re txt)
5062 (- (match-end 0) (match-beginning 0) 1)
5063 -1))
5064 (force-level (cond (level (prefix-numeric-value level))
5065 ((string-match
5066 ^re_ (buffer-substring (point-at-bol) (point)))
5067 (- (match-end 1) (match-beginning 1)))
5068 (t nil)))
5069 (previous-level (save-excursion
5070 (condition-case nil
5071 (progn
5072 (outline-previous-visible-heading 1)
5073 (if (looking-at re)
5074 (- (match-end 0) (match-beginning 0) 1)
5076 (error 1))))
5077 (next-level (save-excursion
5078 (condition-case nil
5079 (progn
5080 (or (looking-at outline-regexp)
5081 (outline-next-visible-heading 1))
5082 (if (looking-at re)
5083 (- (match-end 0) (match-beginning 0) 1)
5085 (error 1))))
5086 (new-level (or force-level (max previous-level next-level)))
5087 (shift (if (or (= old-level -1)
5088 (= new-level -1)
5089 (= old-level new-level))
5091 (- new-level old-level)))
5092 (delta (if (> shift 0) -1 1))
5093 (func (if (> shift 0) 'org-demote 'org-promote))
5094 (org-odd-levels-only nil)
5095 beg end)
5096 ;; Remove the forced level indicator
5097 (if force-level
5098 (delete-region (point-at-bol) (point)))
5099 ;; Paste
5100 (beginning-of-line 1)
5101 (org-back-over-empty-lines)
5102 (setq beg (point))
5103 (insert-before-markers txt)
5104 (unless (string-match "\n\\'" txt) (insert "\n"))
5105 (org-reinstall-markers-in-region beg)
5106 (setq end (point))
5107 (goto-char beg)
5108 (skip-chars-forward " \t\n\r")
5109 (setq beg (point))
5110 (if (and (org-invisible-p) visp)
5111 (save-excursion (outline-show-heading)))
5112 ;; Shift if necessary
5113 (unless (= shift 0)
5114 (save-restriction
5115 (narrow-to-region beg end)
5116 (while (not (= shift 0))
5117 (org-map-region func (point-min) (point-max))
5118 (setq shift (+ delta shift)))
5119 (goto-char (point-min))))
5120 (when (interactive-p)
5121 (message "Clipboard pasted as level %d subtree" new-level))
5122 (if (and kill-ring
5123 (eq org-subtree-clip (current-kill 0))
5124 org-subtree-clip-folded)
5125 ;; The tree was folded before it was killed/copied
5126 (hide-subtree))))
5128 (defun org-kill-is-subtree-p (&optional txt)
5129 "Check if the current kill is an outline subtree, or a set of trees.
5130 Returns nil if kill does not start with a headline, or if the first
5131 headline level is not the largest headline level in the tree.
5132 So this will actually accept several entries of equal levels as well,
5133 which is OK for `org-paste-subtree'.
5134 If optional TXT is given, check this string instead of the current kill."
5135 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5136 (start-level (and kill
5137 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5138 org-outline-regexp "\\)")
5139 kill)
5140 (- (match-end 2) (match-beginning 2) 1)))
5141 (re (concat "^" org-outline-regexp))
5142 (start (1+ (or (match-beginning 2) -1))))
5143 (if (not start-level)
5144 (progn
5145 nil) ;; does not even start with a heading
5146 (catch 'exit
5147 (while (setq start (string-match re kill (1+ start)))
5148 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5149 (throw 'exit nil)))
5150 t))))
5152 (defvar org-markers-to-move nil
5153 "Markers that should be moved with a cut-and-paste operation.
5154 Those markers are stored together with their positions relative to
5155 the start of the region.")
5157 (defun org-save-markers-in-region (beg end)
5158 "Check markers in region.
5159 If these markers are between BEG and END, record their position relative
5160 to BEG, so that after moving the block of text, we can put the markers back
5161 into place.
5162 This function gets called just before an entry or tree gets cut from the
5163 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5164 called immediately, to move the markers with the entries."
5165 (setq org-markers-to-move nil)
5166 (when (featurep 'org-clock)
5167 (org-clock-save-markers-for-cut-and-paste beg end))
5168 (when (featurep 'org-agenda)
5169 (org-agenda-save-markers-for-cut-and-paste beg end)))
5171 (defun org-check-and-save-marker (marker beg end)
5172 "Check if MARKER is between BEG and END.
5173 If yes, remember the marker and the distance to BEG."
5174 (when (and (marker-buffer marker)
5175 (equal (marker-buffer marker) (current-buffer)))
5176 (if (and (>= marker beg) (< marker end))
5177 (push (cons marker (- marker beg)) org-markers-to-move))))
5179 (defun org-reinstall-markers-in-region (beg)
5180 "Move all remembered markers to their position relative to BEG."
5181 (mapc (lambda (x)
5182 (move-marker (car x) (+ beg (cdr x))))
5183 org-markers-to-move)
5184 (setq org-markers-to-move nil))
5186 (defun org-narrow-to-subtree ()
5187 "Narrow buffer to the current subtree."
5188 (interactive)
5189 (save-excursion
5190 (save-match-data
5191 (narrow-to-region
5192 (progn (org-back-to-heading) (point))
5193 (progn (org-end-of-subtree t) (point))))))
5196 ;;; Outline Sorting
5198 (defun org-sort (with-case)
5199 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5200 Optional argument WITH-CASE means sort case-sensitively."
5201 (interactive "P")
5202 (if (org-at-table-p)
5203 (org-call-with-arg 'org-table-sort-lines with-case)
5204 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5206 (defun org-sort-remove-invisible (s)
5207 (remove-text-properties 0 (length s) org-rm-props s)
5208 (while (string-match org-bracket-link-regexp s)
5209 (setq s (replace-match (if (match-end 2)
5210 (match-string 3 s)
5211 (match-string 1 s)) t t s)))
5214 (defvar org-priority-regexp) ; defined later in the file
5216 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5217 "Sort entries on a certain level of an outline tree.
5218 If there is an active region, the entries in the region are sorted.
5219 Else, if the cursor is before the first entry, sort the top-level items.
5220 Else, the children of the entry at point are sorted.
5222 Sorting can be alphabetically, numerically, and by date/time as given by
5223 the first time stamp in the entry. The command prompts for the sorting
5224 type unless it has been given to the function through the SORTING-TYPE
5225 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5226 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5227 called with point at the beginning of the record. It must return either
5228 a string or a number that should serve as the sorting key for that record.
5230 Comparing entries ignores case by default. However, with an optional argument
5231 WITH-CASE, the sorting considers case as well."
5232 (interactive "P")
5233 (let ((case-func (if with-case 'identity 'downcase))
5234 start beg end stars re re2
5235 txt what tmp plain-list-p)
5236 ;; Find beginning and end of region to sort
5237 (cond
5238 ((org-region-active-p)
5239 ;; we will sort the region
5240 (setq end (region-end)
5241 what "region")
5242 (goto-char (region-beginning))
5243 (if (not (org-on-heading-p)) (outline-next-heading))
5244 (setq start (point)))
5245 ((org-at-item-p)
5246 ;; we will sort this plain list
5247 (org-beginning-of-item-list) (setq start (point))
5248 (org-end-of-item-list) (setq end (point))
5249 (goto-char start)
5250 (setq plain-list-p t
5251 what "plain list"))
5252 ((or (org-on-heading-p)
5253 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5254 ;; we will sort the children of the current headline
5255 (org-back-to-heading)
5256 (setq start (point)
5257 end (progn (org-end-of-subtree t t)
5258 (org-back-over-empty-lines)
5259 (point))
5260 what "children")
5261 (goto-char start)
5262 (show-subtree)
5263 (outline-next-heading))
5265 ;; we will sort the top-level entries in this file
5266 (goto-char (point-min))
5267 (or (org-on-heading-p) (outline-next-heading))
5268 (setq start (point) end (point-max) what "top-level")
5269 (goto-char start)
5270 (show-all)))
5272 (setq beg (point))
5273 (if (>= beg end) (error "Nothing to sort"))
5275 (unless plain-list-p
5276 (looking-at "\\(\\*+\\)")
5277 (setq stars (match-string 1)
5278 re (concat "^" (regexp-quote stars) " +")
5279 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5280 txt (buffer-substring beg end))
5281 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5282 (if (and (not (equal stars "*")) (string-match re2 txt))
5283 (error "Region to sort contains a level above the first entry")))
5285 (unless sorting-type
5286 (message
5287 (if plain-list-p
5288 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5289 "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:")
5290 what)
5291 (setq sorting-type (read-char-exclusive))
5293 (and (= (downcase sorting-type) ?f)
5294 (setq getkey-func
5295 (completing-read "Sort using function: "
5296 obarray 'fboundp t nil nil))
5297 (setq getkey-func (intern getkey-func)))
5299 (and (= (downcase sorting-type) ?r)
5300 (setq property
5301 (completing-read "Property: "
5302 (mapcar 'list (org-buffer-property-keys t))
5303 nil t))))
5305 (message "Sorting entries...")
5307 (save-restriction
5308 (narrow-to-region start end)
5310 (let ((dcst (downcase sorting-type))
5311 (now (current-time)))
5312 (sort-subr
5313 (/= dcst sorting-type)
5314 ;; This function moves to the beginning character of the "record" to
5315 ;; be sorted.
5316 (if plain-list-p
5317 (lambda nil
5318 (if (org-at-item-p) t (goto-char (point-max))))
5319 (lambda nil
5320 (if (re-search-forward re nil t)
5321 (goto-char (match-beginning 0))
5322 (goto-char (point-max)))))
5323 ;; This function moves to the last character of the "record" being
5324 ;; sorted.
5325 (if plain-list-p
5326 'org-end-of-item
5327 (lambda nil
5328 (save-match-data
5329 (condition-case nil
5330 (outline-forward-same-level 1)
5331 (error
5332 (goto-char (point-max)))))))
5334 ;; This function returns the value that gets sorted against.
5335 (if plain-list-p
5336 (lambda nil
5337 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5338 (cond
5339 ((= dcst ?n)
5340 (string-to-number (buffer-substring (match-end 0)
5341 (point-at-eol))))
5342 ((= dcst ?a)
5343 (buffer-substring (match-end 0) (point-at-eol)))
5344 ((= dcst ?t)
5345 (if (re-search-forward org-ts-regexp
5346 (point-at-eol) t)
5347 (org-time-string-to-time (match-string 0))
5348 now))
5349 ((= dcst ?f)
5350 (if getkey-func
5351 (progn
5352 (setq tmp (funcall getkey-func))
5353 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5354 tmp)
5355 (error "Invalid key function `%s'" getkey-func)))
5356 (t (error "Invalid sorting type `%c'" sorting-type)))))
5357 (lambda nil
5358 (cond
5359 ((= dcst ?n)
5360 (if (looking-at org-complex-heading-regexp)
5361 (string-to-number (match-string 4))
5362 nil))
5363 ((= dcst ?a)
5364 (if (looking-at org-complex-heading-regexp)
5365 (funcall case-func (match-string 4))
5366 nil))
5367 ((= dcst ?t)
5368 (if (re-search-forward org-ts-regexp
5369 (save-excursion
5370 (forward-line 2)
5371 (point)) t)
5372 (org-time-string-to-time (match-string 0))
5373 now))
5374 ((= dcst ?p)
5375 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5376 (string-to-char (match-string 2))
5377 org-default-priority))
5378 ((= dcst ?r)
5379 (or (org-entry-get nil property) ""))
5380 ((= dcst ?o)
5381 (if (looking-at org-complex-heading-regexp)
5382 (- 9999 (length (member (match-string 2)
5383 org-todo-keywords-1)))))
5384 ((= dcst ?f)
5385 (if getkey-func
5386 (progn
5387 (setq tmp (funcall getkey-func))
5388 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5389 tmp)
5390 (error "Invalid key function `%s'" getkey-func)))
5391 (t (error "Invalid sorting type `%c'" sorting-type)))))
5393 (cond
5394 ((= dcst ?a) 'string<)
5395 ((= dcst ?t) 'time-less-p)
5396 (t nil)))))
5397 (message "Sorting entries...done")))
5399 (defun org-do-sort (table what &optional with-case sorting-type)
5400 "Sort TABLE of WHAT according to SORTING-TYPE.
5401 The user will be prompted for the SORTING-TYPE if the call to this
5402 function does not specify it. WHAT is only for the prompt, to indicate
5403 what is being sorted. The sorting key will be extracted from
5404 the car of the elements of the table.
5405 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5406 (unless sorting-type
5407 (message
5408 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5409 what)
5410 (setq sorting-type (read-char-exclusive)))
5411 (let ((dcst (downcase sorting-type))
5412 extractfun comparefun)
5413 ;; Define the appropriate functions
5414 (cond
5415 ((= dcst ?n)
5416 (setq extractfun 'string-to-number
5417 comparefun (if (= dcst sorting-type) '< '>)))
5418 ((= dcst ?a)
5419 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5420 (lambda(x) (downcase (org-sort-remove-invisible x))))
5421 comparefun (if (= dcst sorting-type)
5422 'string<
5423 (lambda (a b) (and (not (string< a b))
5424 (not (string= a b)))))))
5425 ((= dcst ?t)
5426 (setq extractfun
5427 (lambda (x)
5428 (if (string-match org-ts-regexp x)
5429 (time-to-seconds
5430 (org-time-string-to-time (match-string 0 x)))
5432 comparefun (if (= dcst sorting-type) '< '>)))
5433 (t (error "Invalid sorting type `%c'" sorting-type)))
5435 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5436 table)
5437 (lambda (a b) (funcall comparefun (car a) (car b))))))
5439 ;;; Editing source examples
5441 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5442 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5443 (defvar org-edit-src-force-single-line nil)
5444 (defvar org-edit-src-from-org-mode nil)
5445 (defvar org-edit-src-picture nil)
5447 (define-minor-mode org-exit-edit-mode
5448 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5450 (defun org-edit-src-code ()
5451 "Edit the source code example at point.
5452 An indirect buffer is created, and that buffer is then narrowed to the
5453 example at point and switched to the correct language mode. When done,
5454 exit by killing the buffer with \\[org-edit-src-exit]."
5455 (interactive)
5456 (let ((line (org-current-line))
5457 (case-fold-search t)
5458 (msg (substitute-command-keys
5459 "Edit, then exit with C-c ' (C-c and single quote)"))
5460 (info (org-edit-src-find-region-and-lang))
5461 (org-mode-p (eq major-mode 'org-mode))
5462 beg end lang lang-f single)
5463 (if (not info)
5465 (setq beg (nth 0 info)
5466 end (nth 1 info)
5467 lang (nth 2 info)
5468 single (nth 3 info)
5469 lang-f (intern (concat lang "-mode")))
5470 (unless (functionp lang-f)
5471 (error "No such language mode: %s" lang-f))
5472 (goto-line line)
5473 (if (get-buffer "*Org Edit Src Example*")
5474 (kill-buffer "*Org Edit Src Example*"))
5475 (switch-to-buffer (make-indirect-buffer (current-buffer)
5476 "*Org Edit Src Example*"))
5477 (narrow-to-region beg end)
5478 (remove-text-properties beg end '(display nil invisible nil
5479 intangible nil))
5480 (let ((org-inhibit-startup t))
5481 (funcall lang-f))
5482 (set (make-local-variable 'org-edit-src-force-single-line) single)
5483 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5484 (when org-mode-p
5485 (goto-char (point-min))
5486 (while (re-search-forward "^," nil t)
5487 (replace-match "")))
5488 (goto-line line)
5489 (org-exit-edit-mode)
5490 (org-set-local 'header-line-format msg)
5491 (message "%s" msg)
5492 t)))
5494 (defun org-edit-fixed-width-region ()
5495 "Edit the fixed-width ascii drawing at point.
5496 This must be a region where each line starts with ca colon followed by
5497 a space character.
5498 An indirect buffer is created, and that buffer is then narrowed to the
5499 example at point and switched to artist-mode. When done,
5500 exit by killing the buffer with \\[org-edit-src-exit]."
5501 (interactive)
5502 (let ((line (org-current-line))
5503 (case-fold-search t)
5504 (msg (substitute-command-keys
5505 "Edit, then exit with C-c ' (C-c and single quote)"))
5506 (org-mode-p (eq major-mode 'org-mode))
5507 beg end lang lang-f)
5508 (beginning-of-line 1)
5509 (if (looking-at "[ \t]*[^:\n \t]")
5511 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5512 (setq beg (point) end (match-end 0))
5513 (save-excursion
5514 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5515 (setq beg (point-at-bol 2))
5516 (setq beg (point))))
5517 (save-excursion
5518 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5519 (setq end (match-beginning 0))
5520 (setq end (point))))
5521 (goto-line line)
5522 (if (get-buffer "*Org Edit Picture*")
5523 (kill-buffer "*Org Edit Picture*"))
5524 (switch-to-buffer (make-indirect-buffer (current-buffer)
5525 "*Org Edit Picture*"))
5526 (narrow-to-region beg end)
5527 (remove-text-properties beg end '(display nil invisible nil
5528 intangible nil))
5529 (when (fboundp 'font-lock-unfontify-region)
5530 (font-lock-unfontify-region (point-min) (point-max)))
5531 (cond
5532 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5533 (fundamental-mode)
5534 (artist-mode 1))
5535 (t (funcall org-edit-fixed-width-region-mode)))
5536 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5537 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5538 (set (make-local-variable 'org-edit-src-picture) t)
5539 (goto-char (point-min))
5540 (while (re-search-forward "^[ \t]*: " nil t)
5541 (replace-match ""))
5542 (goto-line line)
5543 (org-exit-edit-mode)
5544 (org-set-local 'header-line-format msg)
5545 (message "%s" msg)
5546 t))))
5548 (defun org-edit-src-find-region-and-lang ()
5549 "Find the region and language for a local edit.
5550 Return a list with beginning and end of the region, a string representing
5551 the language, a switch telling of the content should be in a single line."
5552 (let ((re-list
5554 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5555 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5556 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5557 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5558 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5559 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5560 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5561 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5562 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5563 ("^#\\+html:" "\n" "html" single-line)
5564 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5565 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5566 ("^#\\+latex:" "\n" "latex" single-line)
5567 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5568 ("^#\\+ascii:" "\n" "ascii" single-line)
5570 (pos (point))
5571 re re1 re2 single beg end lang)
5572 (catch 'exit
5573 (while (setq entry (pop re-list))
5574 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5575 single (nth 3 entry))
5576 (save-excursion
5577 (if (or (looking-at re1)
5578 (re-search-backward re1 nil t))
5579 (progn
5580 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5581 (if (and (re-search-forward re2 nil t)
5582 (>= (match-end 0) pos))
5583 (throw 'exit (list beg (match-beginning 0) lang single))))
5584 (if (or (looking-at re2)
5585 (re-search-forward re2 nil t))
5586 (progn
5587 (setq end (match-beginning 0))
5588 (if (and (re-search-backward re1 nil t)
5589 (<= (match-beginning 0) pos))
5590 (throw 'exit
5591 (list (match-end 0) end
5592 (org-edit-src-get-lang lang) single)))))))))))
5594 (defun org-edit-src-get-lang (lang)
5595 "Extract the src language."
5596 (let ((m (match-string 0)))
5597 (cond
5598 ((stringp lang) lang)
5599 ((integerp lang) (match-string lang))
5600 ((and (eq lang lang)
5601 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5602 (match-string 1 m))
5603 ((and (eq lang lang)
5604 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5605 (match-string 1 m))
5606 (t "fundamental"))))
5608 (defun org-edit-src-exit ()
5609 "Exit special edit and protect problematic lines."
5610 (interactive)
5611 (unless (buffer-base-buffer (current-buffer))
5612 (error "This is not an indirect buffer, something is wrong..."))
5613 (unless (> (point-min) 1)
5614 (error "This buffer is not narrowed, something is wrong..."))
5615 (goto-char (point-min))
5616 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5617 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5618 (when (org-bound-and-true-p org-edit-src-force-single-line)
5619 (goto-char (point-min))
5620 (while (re-search-forward "\n" nil t)
5621 (replace-match " "))
5622 (goto-char (point-min))
5623 (if (looking-at "\\s-*") (replace-match " "))
5624 (if (re-search-forward "\\s-+\\'" nil t)
5625 (replace-match "")))
5626 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5627 (goto-char (point-min))
5628 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5629 (replace-match ",\\1"))
5630 (when font-lock-mode
5631 (font-lock-unfontify-region (point-min) (point-max)))
5632 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5633 (when (org-bound-and-true-p org-edit-src-picture)
5634 (goto-char (point-min))
5635 (while (re-search-forward "^" nil t)
5636 (replace-match ": "))
5637 (when font-lock-mode
5638 (font-lock-unfontify-region (point-min) (point-max)))
5639 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5640 (kill-buffer (current-buffer))
5641 (and (org-mode-p) (org-restart-font-lock)))
5643 ;;;; Plain list items, including checkboxes
5645 ;;; Plain list items
5647 (defun org-at-item-p ()
5648 "Is point in a line starting a hand-formatted item?"
5649 (let ((llt org-plain-list-ordered-item-terminator))
5650 (save-excursion
5651 (goto-char (point-at-bol))
5652 (looking-at
5653 (cond
5654 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5655 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5656 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5657 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5659 (defun org-in-item-p ()
5660 "It the cursor inside a plain list item.
5661 Does not have to be the first line."
5662 (save-excursion
5663 (condition-case nil
5664 (progn
5665 (org-beginning-of-item)
5666 (org-at-item-p)
5668 (error nil))))
5670 (defun org-insert-item (&optional checkbox)
5671 "Insert a new item at the current level.
5672 Return t when things worked, nil when we are not in an item."
5673 (when (save-excursion
5674 (condition-case nil
5675 (progn
5676 (org-beginning-of-item)
5677 (org-at-item-p)
5678 (if (org-invisible-p) (error "Invisible item"))
5680 (error nil)))
5681 (let* ((bul (match-string 0))
5682 (descp (save-excursion (goto-char (match-beginning 0))
5683 (beginning-of-line 1)
5684 (save-match-data
5685 (looking-at "[ \t]*.*? ::"))))
5686 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5687 (match-end 0)))
5688 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5689 pos)
5690 (if descp (setq checkbox nil))
5691 (cond
5692 ((and (org-at-item-p) (<= (point) eow))
5693 ;; before the bullet
5694 (beginning-of-line 1)
5695 (open-line (if blank 2 1)))
5696 ((<= (point) eow)
5697 (beginning-of-line 1))
5699 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5700 (end-of-line 1)
5701 (delete-horizontal-space))
5702 (newline (if blank 2 1))))
5703 (insert bul
5704 (if checkbox "[ ]" "")
5705 (if descp (concat (if checkbox " " "")
5706 (read-string "Term: ") " :: ") ""))
5707 (just-one-space)
5708 (setq pos (point))
5709 (end-of-line 1)
5710 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5711 (org-maybe-renumber-ordered-list)
5712 (and checkbox (org-update-checkbox-count-maybe))
5715 ;;; Checkboxes
5717 (defun org-at-item-checkbox-p ()
5718 "Is point at a line starting a plain-list item with a checklet?"
5719 (and (org-at-item-p)
5720 (save-excursion
5721 (goto-char (match-end 0))
5722 (skip-chars-forward " \t")
5723 (looking-at "\\[[- X]\\]"))))
5725 (defun org-toggle-checkbox (&optional arg)
5726 "Toggle the checkbox in the current line."
5727 (interactive "P")
5728 (catch 'exit
5729 (let (beg end status (firstnew 'unknown))
5730 (cond
5731 ((org-region-active-p)
5732 (setq beg (region-beginning) end (region-end)))
5733 ((org-on-heading-p)
5734 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5735 ((org-at-item-checkbox-p)
5736 (let ((pos (point)))
5737 (replace-match
5738 (cond (arg "[-]")
5739 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5740 (t "[ ]"))
5741 t t)
5742 (goto-char pos))
5743 (throw 'exit t))
5744 (t (error "Not at a checkbox or heading, and no active region")))
5745 (save-excursion
5746 (goto-char beg)
5747 (while (< (point) end)
5748 (when (org-at-item-checkbox-p)
5749 (setq status (equal (match-string 0) "[X]"))
5750 (when (eq firstnew 'unknown)
5751 (setq firstnew (not status)))
5752 (replace-match
5753 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5754 (beginning-of-line 2)))))
5755 (org-update-checkbox-count-maybe))
5757 (defun org-update-checkbox-count-maybe ()
5758 "Update checkbox statistics unless turned off by user."
5759 (when org-provide-checkbox-statistics
5760 (org-update-checkbox-count)))
5762 (defun org-update-checkbox-count (&optional all)
5763 "Update the checkbox statistics in the current section.
5764 This will find all statistic cookies like [57%] and [6/12] and update them
5765 with the current numbers. With optional prefix argument ALL, do this for
5766 the whole buffer."
5767 (interactive "P")
5768 (save-excursion
5769 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5770 (beg (condition-case nil
5771 (progn (outline-back-to-heading) (point))
5772 (error (point-min))))
5773 (end (move-marker (make-marker)
5774 (progn (outline-next-heading) (point))))
5775 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5776 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5777 (re-find (concat re "\\|" re-box))
5778 beg-cookie end-cookie is-percent c-on c-off lim
5779 eline curr-ind next-ind continue-from startsearch
5780 (cstat 0)
5782 (when all
5783 (goto-char (point-min))
5784 (outline-next-heading)
5785 (setq beg (point) end (point-max)))
5786 (goto-char end)
5787 ;; find each statistic cookie
5788 (while (re-search-backward re-find beg t)
5789 (setq beg-cookie (match-beginning 1)
5790 end-cookie (match-end 1)
5791 cstat (+ cstat (if end-cookie 1 0))
5792 startsearch (point-at-eol)
5793 continue-from (point-at-bol)
5794 is-percent (match-beginning 2)
5795 lim (cond
5796 ((org-on-heading-p) (outline-next-heading) (point))
5797 ((org-at-item-p) (org-end-of-item) (point))
5798 (t nil))
5799 c-on 0
5800 c-off 0)
5801 (when lim
5802 ;; find first checkbox for this cookie and gather
5803 ;; statistics from all that are at this indentation level
5804 (goto-char startsearch)
5805 (if (re-search-forward re-box lim t)
5806 (progn
5807 (org-beginning-of-item)
5808 (setq curr-ind (org-get-indentation))
5809 (setq next-ind curr-ind)
5810 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5811 (save-excursion (end-of-line) (setq eline (point)))
5812 (if (re-search-forward re-box eline t)
5813 (if (member (match-string 2) '("[ ]" "[-]"))
5814 (setq c-off (1+ c-off))
5815 (setq c-on (1+ c-on))
5818 (org-end-of-item)
5819 (setq next-ind (org-get-indentation))
5821 (goto-char continue-from)
5822 ;; update cookie
5823 (when end-cookie
5824 (delete-region beg-cookie end-cookie)
5825 (goto-char beg-cookie)
5826 (insert
5827 (if is-percent
5828 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5829 (format "[%d/%d]" c-on (+ c-on c-off)))))
5830 ;; update items checkbox if it has one
5831 (when (org-at-item-p)
5832 (org-beginning-of-item)
5833 (when (and (> (+ c-on c-off) 0)
5834 (re-search-forward re-box (point-at-eol) t))
5835 (setq beg-cookie (match-beginning 2)
5836 end-cookie (match-end 2))
5837 (delete-region beg-cookie end-cookie)
5838 (goto-char beg-cookie)
5839 (cond ((= c-off 0) (insert "[X]"))
5840 ((= c-on 0) (insert "[ ]"))
5841 (t (insert "[-]")))
5843 (goto-char continue-from))
5844 (when (interactive-p)
5845 (message "Checkbox satistics updated %s (%d places)"
5846 (if all "in entire file" "in current outline entry") cstat)))))
5848 (defun org-get-checkbox-statistics-face ()
5849 "Select the face for checkbox statistics.
5850 The face will be `org-done' when all relevant boxes are checked. Otherwise
5851 it will be `org-todo'."
5852 (if (match-end 1)
5853 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5854 (if (and (> (match-end 2) (match-beginning 2))
5855 (equal (match-string 2) (match-string 3)))
5856 'org-done
5857 'org-todo)))
5859 (defun org-get-indentation (&optional line)
5860 "Get the indentation of the current line, interpreting tabs.
5861 When LINE is given, assume it represents a line and compute its indentation."
5862 (if line
5863 (if (string-match "^ *" (org-remove-tabs line))
5864 (match-end 0))
5865 (save-excursion
5866 (beginning-of-line 1)
5867 (skip-chars-forward " \t")
5868 (current-column))))
5870 (defun org-remove-tabs (s &optional width)
5871 "Replace tabulators in S with spaces.
5872 Assumes that s is a single line, starting in column 0."
5873 (setq width (or width tab-width))
5874 (while (string-match "\t" s)
5875 (setq s (replace-match
5876 (make-string
5877 (- (* width (/ (+ (match-beginning 0) width) width))
5878 (match-beginning 0)) ?\ )
5879 t t s)))
5882 (defun org-fix-indentation (line ind)
5883 "Fix indentation in LINE.
5884 IND is a cons cell with target and minimum indentation.
5885 If the current indenation in LINE is smaller than the minimum,
5886 leave it alone. If it is larger than ind, set it to the target."
5887 (let* ((l (org-remove-tabs line))
5888 (i (org-get-indentation l))
5889 (i1 (car ind)) (i2 (cdr ind)))
5890 (if (>= i i2) (setq l (substring line i2)))
5891 (if (> i1 0)
5892 (concat (make-string i1 ?\ ) l)
5893 l)))
5895 (defun org-beginning-of-item ()
5896 "Go to the beginning of the current hand-formatted item.
5897 If the cursor is not in an item, throw an error."
5898 (interactive)
5899 (let ((pos (point))
5900 (limit (save-excursion
5901 (condition-case nil
5902 (progn
5903 (org-back-to-heading)
5904 (beginning-of-line 2) (point))
5905 (error (point-min)))))
5906 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5907 ind ind1)
5908 (if (org-at-item-p)
5909 (beginning-of-line 1)
5910 (beginning-of-line 1)
5911 (skip-chars-forward " \t")
5912 (setq ind (current-column))
5913 (if (catch 'exit
5914 (while t
5915 (beginning-of-line 0)
5916 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5918 (if (looking-at "[ \t]*$")
5919 (setq ind1 ind-empty)
5920 (skip-chars-forward " \t")
5921 (setq ind1 (current-column)))
5922 (if (< ind1 ind)
5923 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5925 (goto-char pos)
5926 (error "Not in an item")))))
5928 (defun org-end-of-item ()
5929 "Go to the end of the current hand-formatted item.
5930 If the cursor is not in an item, throw an error."
5931 (interactive)
5932 (let* ((pos (point))
5933 ind1
5934 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5935 (limit (save-excursion (outline-next-heading) (point)))
5936 (ind (save-excursion
5937 (org-beginning-of-item)
5938 (skip-chars-forward " \t")
5939 (current-column)))
5940 (end (catch 'exit
5941 (while t
5942 (beginning-of-line 2)
5943 (if (eobp) (throw 'exit (point)))
5944 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5945 (if (looking-at "[ \t]*$")
5946 (setq ind1 ind-empty)
5947 (skip-chars-forward " \t")
5948 (setq ind1 (current-column)))
5949 (if (<= ind1 ind)
5950 (throw 'exit (point-at-bol)))))))
5951 (if end
5952 (goto-char end)
5953 (goto-char pos)
5954 (error "Not in an item"))))
5956 (defun org-next-item ()
5957 "Move to the beginning of the next item in the current plain list.
5958 Error if not at a plain list, or if this is the last item in the list."
5959 (interactive)
5960 (let (ind ind1 (pos (point)))
5961 (org-beginning-of-item)
5962 (setq ind (org-get-indentation))
5963 (org-end-of-item)
5964 (setq ind1 (org-get-indentation))
5965 (unless (and (org-at-item-p) (= ind ind1))
5966 (goto-char pos)
5967 (error "On last item"))))
5969 (defun org-previous-item ()
5970 "Move to the beginning of the previous item in the current plain list.
5971 Error if not at a plain list, or if this is the first item in the list."
5972 (interactive)
5973 (let (beg ind ind1 (pos (point)))
5974 (org-beginning-of-item)
5975 (setq beg (point))
5976 (setq ind (org-get-indentation))
5977 (goto-char beg)
5978 (catch 'exit
5979 (while t
5980 (beginning-of-line 0)
5981 (if (looking-at "[ \t]*$")
5983 (if (<= (setq ind1 (org-get-indentation)) ind)
5984 (throw 'exit t)))))
5985 (condition-case nil
5986 (if (or (not (org-at-item-p))
5987 (< ind1 (1- ind)))
5988 (error "")
5989 (org-beginning-of-item))
5990 (error (goto-char pos)
5991 (error "On first item")))))
5993 (defun org-first-list-item-p ()
5994 "Is this heading the item in a plain list?"
5995 (unless (org-at-item-p)
5996 (error "Not at a plain list item"))
5997 (org-beginning-of-item)
5998 (= (point) (save-excursion (org-beginning-of-item-list))))
6000 (defun org-move-item-down ()
6001 "Move the plain list item at point down, i.e. swap with following item.
6002 Subitems (items with larger indentation) are considered part of the item,
6003 so this really moves item trees."
6004 (interactive)
6005 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
6006 (org-beginning-of-item)
6007 (setq beg0 (point))
6008 (save-excursion
6009 (setq ne-beg (org-back-over-empty-lines))
6010 (setq beg (point)))
6011 (goto-char beg0)
6012 (setq ind (org-get-indentation))
6013 (org-end-of-item)
6014 (setq end0 (point))
6015 (setq ind1 (org-get-indentation))
6016 (setq ne-end (org-back-over-empty-lines))
6017 (setq end (point))
6018 (goto-char beg0)
6019 (when (and (org-first-list-item-p) (< ne-end ne-beg))
6020 ;; include less whitespace
6021 (save-excursion
6022 (goto-char beg)
6023 (forward-line (- ne-beg ne-end))
6024 (setq beg (point))))
6025 (goto-char end0)
6026 (if (and (org-at-item-p) (= ind ind1))
6027 (progn
6028 (org-end-of-item)
6029 (org-back-over-empty-lines)
6030 (setq txt (buffer-substring beg end))
6031 (save-excursion
6032 (delete-region beg end))
6033 (setq pos (point))
6034 (insert txt)
6035 (goto-char pos) (org-skip-whitespace)
6036 (org-maybe-renumber-ordered-list))
6037 (goto-char pos)
6038 (error "Cannot move this item further down"))))
6040 (defun org-move-item-up (arg)
6041 "Move the plain list item at point up, i.e. swap with previous item.
6042 Subitems (items with larger indentation) are considered part of the item,
6043 so this really moves item trees."
6044 (interactive "p")
6045 (let (beg beg0 end ind ind1 (pos (point)) txt
6046 ne-beg ne-ins ins-end)
6047 (org-beginning-of-item)
6048 (setq beg0 (point))
6049 (setq ind (org-get-indentation))
6050 (save-excursion
6051 (setq ne-beg (org-back-over-empty-lines))
6052 (setq beg (point)))
6053 (goto-char beg0)
6054 (org-end-of-item)
6055 (org-back-over-empty-lines)
6056 (setq end (point))
6057 (goto-char beg0)
6058 (catch 'exit
6059 (while t
6060 (beginning-of-line 0)
6061 (if (looking-at "[ \t]*$")
6062 (if org-empty-line-terminates-plain-lists
6063 (progn
6064 (goto-char pos)
6065 (error "Cannot move this item further up"))
6066 nil)
6067 (if (<= (setq ind1 (org-get-indentation)) ind)
6068 (throw 'exit t)))))
6069 (condition-case nil
6070 (org-beginning-of-item)
6071 (error (goto-char beg0)
6072 (error "Cannot move this item further up")))
6073 (setq ind1 (org-get-indentation))
6074 (if (and (org-at-item-p) (= ind ind1))
6075 (progn
6076 (setq ne-ins (org-back-over-empty-lines))
6077 (setq txt (buffer-substring beg end))
6078 (save-excursion
6079 (delete-region beg end))
6080 (setq pos (point))
6081 (insert txt)
6082 (setq ins-end (point))
6083 (goto-char pos) (org-skip-whitespace)
6085 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
6086 ;; Move whitespace back to beginning
6087 (save-excursion
6088 (goto-char ins-end)
6089 (let ((kill-whole-line t))
6090 (kill-line (- ne-ins ne-beg)) (point)))
6091 (insert (make-string (- ne-ins ne-beg) ?\n)))
6093 (org-maybe-renumber-ordered-list))
6094 (goto-char pos)
6095 (error "Cannot move this item further up"))))
6097 (defun org-maybe-renumber-ordered-list ()
6098 "Renumber the ordered list at point if setup allows it.
6099 This tests the user option `org-auto-renumber-ordered-lists' before
6100 doing the renumbering."
6101 (interactive)
6102 (when (and org-auto-renumber-ordered-lists
6103 (org-at-item-p))
6104 (if (match-beginning 3)
6105 (org-renumber-ordered-list 1)
6106 (org-fix-bullet-type))))
6108 (defun org-maybe-renumber-ordered-list-safe ()
6109 (condition-case nil
6110 (save-excursion
6111 (org-maybe-renumber-ordered-list))
6112 (error nil)))
6114 (defun org-cycle-list-bullet (&optional which)
6115 "Cycle through the different itemize/enumerate bullets.
6116 This cycle the entire list level through the sequence:
6118 `-' -> `+' -> `*' -> `1.' -> `1)'
6120 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6121 0 meand `-', 1 means `+' etc."
6122 (interactive "P")
6123 (org-preserve-lc
6124 (org-beginning-of-item-list)
6125 (org-at-item-p)
6126 (beginning-of-line 1)
6127 (let ((current (match-string 0))
6128 (prevp (eq which 'previous))
6129 new)
6130 (setq new (cond
6131 ((and (numberp which)
6132 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6133 ((string-match "-" current) (if prevp "1)" "+"))
6134 ((string-match "\\+" current)
6135 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6136 ((string-match "\\*" current) (if prevp "+" "1."))
6137 ((string-match "\\." current) (if prevp "*" "1)"))
6138 ((string-match ")" current) (if prevp "1." "-"))
6139 (t (error "This should not happen"))))
6140 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6141 (org-fix-bullet-type)
6142 (org-maybe-renumber-ordered-list))))
6144 (defun org-get-string-indentation (s)
6145 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6146 (let ((n -1) (i 0) (w tab-width) c)
6147 (catch 'exit
6148 (while (< (setq n (1+ n)) (length s))
6149 (setq c (aref s n))
6150 (cond ((= c ?\ ) (setq i (1+ i)))
6151 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6152 (t (throw 'exit t)))))
6155 (defun org-renumber-ordered-list (arg)
6156 "Renumber an ordered plain list.
6157 Cursor needs to be in the first line of an item, the line that starts
6158 with something like \"1.\" or \"2)\"."
6159 (interactive "p")
6160 (unless (and (org-at-item-p)
6161 (match-beginning 3))
6162 (error "This is not an ordered list"))
6163 (let ((line (org-current-line))
6164 (col (current-column))
6165 (ind (org-get-string-indentation
6166 (buffer-substring (point-at-bol) (match-beginning 3))))
6167 ;; (term (substring (match-string 3) -1))
6168 ind1 (n (1- arg))
6169 fmt bobp)
6170 ;; find where this list begins
6171 (org-beginning-of-item-list)
6172 (setq bobp (bobp))
6173 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6174 (setq fmt (concat "%d" (match-string 1)))
6175 (beginning-of-line 0)
6176 ;; walk forward and replace these numbers
6177 (catch 'exit
6178 (while t
6179 (catch 'next
6180 (if bobp (setq bobp nil) (beginning-of-line 2))
6181 (if (eobp) (throw 'exit nil))
6182 (if (looking-at "[ \t]*$") (throw 'next nil))
6183 (skip-chars-forward " \t") (setq ind1 (current-column))
6184 (if (> ind1 ind) (throw 'next t))
6185 (if (< ind1 ind) (throw 'exit t))
6186 (if (not (org-at-item-p)) (throw 'exit nil))
6187 (delete-region (match-beginning 2) (match-end 2))
6188 (goto-char (match-beginning 2))
6189 (insert (format fmt (setq n (1+ n)))))))
6190 (goto-line line)
6191 (org-move-to-column col)))
6193 (defun org-fix-bullet-type ()
6194 "Make sure all items in this list have the same bullet as the firsst item."
6195 (interactive)
6196 (unless (org-at-item-p) (error "This is not a list"))
6197 (let ((line (org-current-line))
6198 (col (current-column))
6199 (ind (current-indentation))
6200 ind1 bullet)
6201 ;; find where this list begins
6202 (org-beginning-of-item-list)
6203 (beginning-of-line 1)
6204 ;; find out what the bullet type is
6205 (looking-at "[ \t]*\\(\\S-+\\)")
6206 (setq bullet (match-string 1))
6207 ;; walk forward and replace these numbers
6208 (beginning-of-line 0)
6209 (catch 'exit
6210 (while t
6211 (catch 'next
6212 (beginning-of-line 2)
6213 (if (eobp) (throw 'exit nil))
6214 (if (looking-at "[ \t]*$") (throw 'next nil))
6215 (skip-chars-forward " \t") (setq ind1 (current-column))
6216 (if (> ind1 ind) (throw 'next t))
6217 (if (< ind1 ind) (throw 'exit t))
6218 (if (not (org-at-item-p)) (throw 'exit nil))
6219 (skip-chars-forward " \t")
6220 (looking-at "\\S-+")
6221 (replace-match bullet))))
6222 (goto-line line)
6223 (org-move-to-column col)
6224 (if (string-match "[0-9]" bullet)
6225 (org-renumber-ordered-list 1))))
6227 (defun org-beginning-of-item-list ()
6228 "Go to the beginning of the current item list.
6229 I.e. to the first item in this list."
6230 (interactive)
6231 (org-beginning-of-item)
6232 (let ((pos (point-at-bol))
6233 (ind (org-get-indentation))
6234 ind1)
6235 ;; find where this list begins
6236 (catch 'exit
6237 (while t
6238 (catch 'next
6239 (beginning-of-line 0)
6240 (if (looking-at "[ \t]*$")
6241 (throw (if (bobp) 'exit 'next) t))
6242 (skip-chars-forward " \t") (setq ind1 (current-column))
6243 (if (or (< ind1 ind)
6244 (and (= ind1 ind)
6245 (not (org-at-item-p)))
6246 (and (= (point-at-bol) (point-min))
6247 (setq pos (point-min))))
6248 (throw 'exit t)
6249 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6250 (goto-char pos)))
6253 (defun org-end-of-item-list ()
6254 "Go to the end of the current item list.
6255 I.e. to the text after the last item."
6256 (interactive)
6257 (org-beginning-of-item)
6258 (let ((pos (point-at-bol))
6259 (ind (org-get-indentation))
6260 ind1)
6261 ;; find where this list begins
6262 (catch 'exit
6263 (while t
6264 (catch 'next
6265 (beginning-of-line 2)
6266 (if (looking-at "[ \t]*$")
6267 (throw (if (eobp) 'exit 'next) t))
6268 (skip-chars-forward " \t") (setq ind1 (current-column))
6269 (if (or (< ind1 ind)
6270 (and (= ind1 ind)
6271 (not (org-at-item-p)))
6272 (eobp))
6273 (progn
6274 (setq pos (point-at-bol))
6275 (throw 'exit t))))))
6276 (goto-char pos)))
6279 (defvar org-last-indent-begin-marker (make-marker))
6280 (defvar org-last-indent-end-marker (make-marker))
6282 (defun org-outdent-item (arg)
6283 "Outdent a local list item."
6284 (interactive "p")
6285 (org-indent-item (- arg)))
6287 (defun org-indent-item (arg)
6288 "Indent a local list item."
6289 (interactive "p")
6290 (unless (org-at-item-p)
6291 (error "Not on an item"))
6292 (save-excursion
6293 (let (beg end ind ind1 tmp delta ind-down ind-up)
6294 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6295 (setq beg org-last-indent-begin-marker
6296 end org-last-indent-end-marker)
6297 (org-beginning-of-item)
6298 (setq beg (move-marker org-last-indent-begin-marker (point)))
6299 (org-end-of-item)
6300 (setq end (move-marker org-last-indent-end-marker (point))))
6301 (goto-char beg)
6302 (setq tmp (org-item-indent-positions)
6303 ind (car tmp)
6304 ind-down (nth 2 tmp)
6305 ind-up (nth 1 tmp)
6306 delta (if (> arg 0)
6307 (if ind-down (- ind-down ind) 2)
6308 (if ind-up (- ind-up ind) -2)))
6309 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6310 (while (< (point) end)
6311 (beginning-of-line 1)
6312 (skip-chars-forward " \t") (setq ind1 (current-column))
6313 (delete-region (point-at-bol) (point))
6314 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6315 (beginning-of-line 2))))
6316 (org-fix-bullet-type)
6317 (org-maybe-renumber-ordered-list-safe)
6318 (save-excursion
6319 (beginning-of-line 0)
6320 (condition-case nil (org-beginning-of-item) (error nil))
6321 (org-maybe-renumber-ordered-list-safe)))
6323 (defun org-item-indent-positions ()
6324 "Return indentation for plain list items.
6325 This returns a list with three values: The current indentation, the
6326 parent indentation and the indentation a child should habe.
6327 Assumes cursor in item line."
6328 (let* ((bolpos (point-at-bol))
6329 (ind (org-get-indentation))
6330 ind-down ind-up pos)
6331 (save-excursion
6332 (org-beginning-of-item-list)
6333 (skip-chars-backward "\n\r \t")
6334 (when (org-in-item-p)
6335 (org-beginning-of-item)
6336 (setq ind-up (org-get-indentation))))
6337 (setq pos (point))
6338 (save-excursion
6339 (cond
6340 ((and (condition-case nil (progn (org-previous-item) t)
6341 (error nil))
6342 (or (forward-char 1) t)
6343 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6344 (setq ind-down (org-get-indentation)))
6345 ((and (goto-char pos)
6346 (org-at-item-p))
6347 (goto-char (match-end 0))
6348 (skip-chars-forward " \t")
6349 (setq ind-down (current-column)))))
6350 (list ind ind-up ind-down)))
6352 ;;; The orgstruct minor mode
6354 ;; Define a minor mode which can be used in other modes in order to
6355 ;; integrate the org-mode structure editing commands.
6357 ;; This is really a hack, because the org-mode structure commands use
6358 ;; keys which normally belong to the major mode. Here is how it
6359 ;; works: The minor mode defines all the keys necessary to operate the
6360 ;; structure commands, but wraps the commands into a function which
6361 ;; tests if the cursor is currently at a headline or a plain list
6362 ;; item. If that is the case, the structure command is used,
6363 ;; temporarily setting many Org-mode variables like regular
6364 ;; expressions for filling etc. However, when any of those keys is
6365 ;; used at a different location, function uses `key-binding' to look
6366 ;; up if the key has an associated command in another currently active
6367 ;; keymap (minor modes, major mode, global), and executes that
6368 ;; command. There might be problems if any of the keys is otherwise
6369 ;; used as a prefix key.
6371 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6372 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6373 ;; addresses this by checking explicitly for both bindings.
6375 (defvar orgstruct-mode-map (make-sparse-keymap)
6376 "Keymap for the minor `orgstruct-mode'.")
6378 (defvar org-local-vars nil
6379 "List of local variables, for use by `orgstruct-mode'")
6381 ;;;###autoload
6382 (define-minor-mode orgstruct-mode
6383 "Toggle the minor more `orgstruct-mode'.
6384 This mode is for using Org-mode structure commands in other modes.
6385 The following key behave as if Org-mode was active, if the cursor
6386 is on a headline, or on a plain list item (both in the definition
6387 of Org-mode).
6389 M-up Move entry/item up
6390 M-down Move entry/item down
6391 M-left Promote
6392 M-right Demote
6393 M-S-up Move entry/item up
6394 M-S-down Move entry/item down
6395 M-S-left Promote subtree
6396 M-S-right Demote subtree
6397 M-q Fill paragraph and items like in Org-mode
6398 C-c ^ Sort entries
6399 C-c - Cycle list bullet
6400 TAB Cycle item visibility
6401 M-RET Insert new heading/item
6402 S-M-RET Insert new TODO heading / Chekbox item
6403 C-c C-c Set tags / toggle checkbox"
6404 nil " OrgStruct" nil
6405 (org-load-modules-maybe)
6406 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6408 ;;;###autoload
6409 (defun turn-on-orgstruct ()
6410 "Unconditionally turn on `orgstruct-mode'."
6411 (orgstruct-mode 1))
6413 ;;;###autoload
6414 (defun turn-on-orgstruct++ ()
6415 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6416 In addition to setting orgstruct-mode, this also exports all indentation and
6417 autofilling variables from org-mode into the buffer. Note that turning
6418 off orgstruct-mode will *not* remove these additional settings."
6419 (orgstruct-mode 1)
6420 (let (var val)
6421 (mapc
6422 (lambda (x)
6423 (when (string-match
6424 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6425 (symbol-name (car x)))
6426 (setq var (car x) val (nth 1 x))
6427 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6428 org-local-vars)))
6430 (defun orgstruct-error ()
6431 "Error when there is no default binding for a structure key."
6432 (interactive)
6433 (error "This key has no function outside structure elements"))
6435 (defun orgstruct-setup ()
6436 "Setup orgstruct keymaps."
6437 (let ((nfunc 0)
6438 (bindings
6439 (list
6440 '([(meta up)] org-metaup)
6441 '([(meta down)] org-metadown)
6442 '([(meta left)] org-metaleft)
6443 '([(meta right)] org-metaright)
6444 '([(meta shift up)] org-shiftmetaup)
6445 '([(meta shift down)] org-shiftmetadown)
6446 '([(meta shift left)] org-shiftmetaleft)
6447 '([(meta shift right)] org-shiftmetaright)
6448 '([(shift up)] org-shiftup)
6449 '([(shift down)] org-shiftdown)
6450 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6451 '("\M-q" fill-paragraph)
6452 '("\C-c^" org-sort)
6453 '("\C-c-" org-cycle-list-bullet)))
6454 elt key fun cmd)
6455 (while (setq elt (pop bindings))
6456 (setq nfunc (1+ nfunc))
6457 (setq key (org-key (car elt))
6458 fun (nth 1 elt)
6459 cmd (orgstruct-make-binding fun nfunc key))
6460 (org-defkey orgstruct-mode-map key cmd))
6462 ;; Special treatment needed for TAB and RET
6463 (org-defkey orgstruct-mode-map [(tab)]
6464 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6465 (org-defkey orgstruct-mode-map "\C-i"
6466 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6468 (org-defkey orgstruct-mode-map "\M-\C-m"
6469 (orgstruct-make-binding 'org-insert-heading 105
6470 "\M-\C-m" [(meta return)]))
6471 (org-defkey orgstruct-mode-map [(meta return)]
6472 (orgstruct-make-binding 'org-insert-heading 106
6473 [(meta return)] "\M-\C-m"))
6475 (org-defkey orgstruct-mode-map [(shift meta return)]
6476 (orgstruct-make-binding 'org-insert-todo-heading 107
6477 [(meta return)] "\M-\C-m"))
6479 (unless org-local-vars
6480 (setq org-local-vars (org-get-local-variables)))
6484 (defun orgstruct-make-binding (fun n &rest keys)
6485 "Create a function for binding in the structure minor mode.
6486 FUN is the command to call inside a table. N is used to create a unique
6487 command name. KEYS are keys that should be checked in for a command
6488 to execute outside of tables."
6489 (eval
6490 (list 'defun
6491 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6492 '(arg)
6493 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6494 "Outside of structure, run the binding of `"
6495 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6496 "'.")
6497 '(interactive "p")
6498 (list 'if
6499 '(org-context-p 'headline 'item)
6500 (list 'org-run-like-in-org-mode (list 'quote fun))
6501 (list 'let '(orgstruct-mode)
6502 (list 'call-interactively
6503 (append '(or)
6504 (mapcar (lambda (k)
6505 (list 'key-binding k))
6506 keys)
6507 '('orgstruct-error))))))))
6509 (defun org-context-p (&rest contexts)
6510 "Check if local context is any of CONTEXTS.
6511 Possible values in the list of contexts are `table', `headline', and `item'."
6512 (let ((pos (point)))
6513 (goto-char (point-at-bol))
6514 (prog1 (or (and (memq 'table contexts)
6515 (looking-at "[ \t]*|"))
6516 (and (memq 'headline contexts)
6517 ;;????????? (looking-at "\\*+"))
6518 (looking-at outline-regexp))
6519 (and (memq 'item contexts)
6520 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6521 (goto-char pos))))
6523 (defun org-get-local-variables ()
6524 "Return a list of all local variables in an org-mode buffer."
6525 (let (varlist)
6526 (with-current-buffer (get-buffer-create "*Org tmp*")
6527 (erase-buffer)
6528 (org-mode)
6529 (setq varlist (buffer-local-variables)))
6530 (kill-buffer "*Org tmp*")
6531 (delq nil
6532 (mapcar
6533 (lambda (x)
6534 (setq x
6535 (if (symbolp x)
6536 (list x)
6537 (list (car x) (list 'quote (cdr x)))))
6538 (if (string-match
6539 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6540 (symbol-name (car x)))
6541 x nil))
6542 varlist))))
6544 ;;;###autoload
6545 (defun org-run-like-in-org-mode (cmd)
6546 (org-load-modules-maybe)
6547 (unless org-local-vars
6548 (setq org-local-vars (org-get-local-variables)))
6549 (eval (list 'let org-local-vars
6550 (list 'call-interactively (list 'quote cmd)))))
6552 ;;;; Archiving
6554 (defun org-get-category (&optional pos)
6555 "Get the category applying to position POS."
6556 (get-text-property (or pos (point)) 'org-category))
6558 (defun org-refresh-category-properties ()
6559 "Refresh category text properties in the buffer."
6560 (let ((def-cat (cond
6561 ((null org-category)
6562 (if buffer-file-name
6563 (file-name-sans-extension
6564 (file-name-nondirectory buffer-file-name))
6565 "???"))
6566 ((symbolp org-category) (symbol-name org-category))
6567 (t org-category)))
6568 beg end cat pos optionp)
6569 (org-unmodified
6570 (save-excursion
6571 (save-restriction
6572 (widen)
6573 (goto-char (point-min))
6574 (put-text-property (point) (point-max) 'org-category def-cat)
6575 (while (re-search-forward
6576 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6577 (setq pos (match-end 0)
6578 optionp (equal (char-after (match-beginning 0)) ?#)
6579 cat (org-trim (match-string 2)))
6580 (if optionp
6581 (setq beg (point-at-bol) end (point-max))
6582 (org-back-to-heading t)
6583 (setq beg (point) end (org-end-of-subtree t t)))
6584 (put-text-property beg end 'org-category cat)
6585 (goto-char pos)))))))
6588 ;;;; Link Stuff
6590 ;;; Link abbreviations
6592 (defun org-link-expand-abbrev (link)
6593 "Apply replacements as defined in `org-link-abbrev-alist."
6594 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6595 (let* ((key (match-string 1 link))
6596 (as (or (assoc key org-link-abbrev-alist-local)
6597 (assoc key org-link-abbrev-alist)))
6598 (tag (and (match-end 2) (match-string 3 link)))
6599 rpl)
6600 (if (not as)
6601 link
6602 (setq rpl (cdr as))
6603 (cond
6604 ((symbolp rpl) (funcall rpl tag))
6605 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6606 (t (concat rpl tag)))))
6607 link))
6609 ;;; Storing and inserting links
6611 (defvar org-insert-link-history nil
6612 "Minibuffer history for links inserted with `org-insert-link'.")
6614 (defvar org-stored-links nil
6615 "Contains the links stored with `org-store-link'.")
6617 (defvar org-store-link-plist nil
6618 "Plist with info about the most recently link created with `org-store-link'.")
6620 (defvar org-link-protocols nil
6621 "Link protocols added to Org-mode using `org-add-link-type'.")
6623 (defvar org-store-link-functions nil
6624 "List of functions that are called to create and store a link.
6625 Each function will be called in turn until one returns a non-nil
6626 value. Each function should check if it is responsible for creating
6627 this link (for example by looking at the major mode).
6628 If not, it must exit and return nil.
6629 If yes, it should return a non-nil value after a calling
6630 `org-store-link-props' with a list of properties and values.
6631 Special properties are:
6633 :type The link prefix. like \"http\". This must be given.
6634 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6635 This is obligatory as well.
6636 :description Optional default description for the second pair
6637 of brackets in an Org-mode link. The user can still change
6638 this when inserting this link into an Org-mode buffer.
6640 In addition to these, any additional properties can be specified
6641 and then used in remember templates.")
6643 (defun org-add-link-type (type &optional follow export)
6644 "Add TYPE to the list of `org-link-types'.
6645 Re-compute all regular expressions depending on `org-link-types'
6647 FOLLOW and EXPORT are two functions.
6649 FOLLOW should take the link path as the single argument and do whatever
6650 is necessary to follow the link, for example find a file or display
6651 a mail message.
6653 EXPORT should format the link path for export to one of the export formats.
6654 It should be a function accepting three arguments:
6656 path the path of the link, the text after the prefix (like \"http:\")
6657 desc the description of the link, if any, nil if there was no descripton
6658 format the export format, a symbol like `html' or `latex'.
6660 The function may use the FORMAT information to return different values
6661 depending on the format. The return value will be put literally into
6662 the exported file.
6663 Org-mode has a built-in default for exporting links. If you are happy with
6664 this default, there is no need to define an export function for the link
6665 type. For a simple example of an export function, see `org-bbdb.el'."
6666 (add-to-list 'org-link-types type t)
6667 (org-make-link-regexps)
6668 (if (assoc type org-link-protocols)
6669 (setcdr (assoc type org-link-protocols) (list follow export))
6670 (push (list type follow export) org-link-protocols)))
6673 ;;;###autoload
6674 (defun org-store-link (arg)
6675 "\\<org-mode-map>Store an org-link to the current location.
6676 This link is added to `org-stored-links' and can later be inserted
6677 into an org-buffer with \\[org-insert-link].
6679 For some link types, a prefix arg is interpreted:
6680 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6681 For file links, arg negates `org-context-in-file-links'."
6682 (interactive "P")
6683 (org-load-modules-maybe)
6684 (setq org-store-link-plist nil) ; reset
6685 (let (link cpltxt desc description search txt)
6686 (cond
6688 ((run-hook-with-args-until-success 'org-store-link-functions)
6689 (setq link (plist-get org-store-link-plist :link)
6690 desc (or (plist-get org-store-link-plist :description) link)))
6692 ((eq major-mode 'calendar-mode)
6693 (let ((cd (calendar-cursor-to-date)))
6694 (setq link
6695 (format-time-string
6696 (car org-time-stamp-formats)
6697 (apply 'encode-time
6698 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6699 nil nil nil))))
6700 (org-store-link-props :type "calendar" :date cd)))
6702 ((eq major-mode 'w3-mode)
6703 (setq cpltxt (url-view-url t)
6704 link (org-make-link cpltxt))
6705 (org-store-link-props :type "w3" :url (url-view-url t)))
6707 ((eq major-mode 'w3m-mode)
6708 (setq cpltxt (or w3m-current-title w3m-current-url)
6709 link (org-make-link w3m-current-url))
6710 (org-store-link-props :type "w3m" :url (url-view-url t)))
6712 ((setq search (run-hook-with-args-until-success
6713 'org-create-file-search-functions))
6714 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6715 "::" search))
6716 (setq cpltxt (or description link)))
6718 ((eq major-mode 'image-mode)
6719 (setq cpltxt (concat "file:"
6720 (abbreviate-file-name buffer-file-name))
6721 link (org-make-link cpltxt))
6722 (org-store-link-props :type "image" :file buffer-file-name))
6724 ((eq major-mode 'dired-mode)
6725 ;; link to the file in the current line
6726 (setq cpltxt (concat "file:"
6727 (abbreviate-file-name
6728 (expand-file-name
6729 (dired-get-filename nil t))))
6730 link (org-make-link cpltxt)))
6732 ((and buffer-file-name (org-mode-p))
6733 ;; Just link to current headline
6734 (setq cpltxt (concat "file:"
6735 (abbreviate-file-name buffer-file-name)))
6736 ;; Add a context search string
6737 (when (org-xor org-context-in-file-links arg)
6738 ;; Check if we are on a target
6739 (if (org-in-regexp "<<\\(.*?\\)>>")
6740 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6741 (setq txt (cond
6742 ((org-on-heading-p) nil)
6743 ((org-region-active-p)
6744 (buffer-substring (region-beginning) (region-end)))
6745 (t nil)))
6746 (when (or (null txt) (string-match "\\S-" txt))
6747 (setq cpltxt
6748 (concat cpltxt "::"
6749 (condition-case nil
6750 (org-make-org-heading-search-string txt)
6751 (error "")))
6752 desc "NONE"))))
6753 (if (string-match "::\\'" cpltxt)
6754 (setq cpltxt (substring cpltxt 0 -2)))
6755 (setq link (org-make-link cpltxt)))
6757 ((buffer-file-name (buffer-base-buffer))
6758 ;; Just link to this file here.
6759 (setq cpltxt (concat "file:"
6760 (abbreviate-file-name
6761 (buffer-file-name (buffer-base-buffer)))))
6762 ;; Add a context string
6763 (when (org-xor org-context-in-file-links arg)
6764 (setq txt (if (org-region-active-p)
6765 (buffer-substring (region-beginning) (region-end))
6766 (buffer-substring (point-at-bol) (point-at-eol))))
6767 ;; Only use search option if there is some text.
6768 (when (string-match "\\S-" txt)
6769 (setq cpltxt
6770 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6771 desc "NONE")))
6772 (setq link (org-make-link cpltxt)))
6774 ((interactive-p)
6775 (error "Cannot link to a buffer which is not visiting a file"))
6777 (t (setq link nil)))
6779 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6780 (setq link (or link cpltxt)
6781 desc (or desc cpltxt))
6782 (if (equal desc "NONE") (setq desc nil))
6784 (if (and (interactive-p) link)
6785 (progn
6786 (setq org-stored-links
6787 (cons (list link desc) org-stored-links))
6788 (message "Stored: %s" (or desc link)))
6789 (and link (org-make-link-string link desc)))))
6791 (defun org-store-link-props (&rest plist)
6792 "Store link properties, extract names and addresses."
6793 (let (x adr)
6794 (when (setq x (plist-get plist :from))
6795 (setq adr (mail-extract-address-components x))
6796 (plist-put plist :fromname (car adr))
6797 (plist-put plist :fromaddress (nth 1 adr)))
6798 (when (setq x (plist-get plist :to))
6799 (setq adr (mail-extract-address-components x))
6800 (plist-put plist :toname (car adr))
6801 (plist-put plist :toaddress (nth 1 adr))))
6802 (let ((from (plist-get plist :from))
6803 (to (plist-get plist :to)))
6804 (when (and from to org-from-is-user-regexp)
6805 (plist-put plist :fromto
6806 (if (string-match org-from-is-user-regexp from)
6807 (concat "to %t")
6808 (concat "from %f")))))
6809 (setq org-store-link-plist plist))
6811 (defun org-add-link-props (&rest plist)
6812 "Add these properties to the link property list."
6813 (let (key value)
6814 (while plist
6815 (setq key (pop plist) value (pop plist))
6816 (setq org-store-link-plist
6817 (plist-put org-store-link-plist key value)))))
6819 (defun org-email-link-description (&optional fmt)
6820 "Return the description part of an email link.
6821 This takes information from `org-store-link-plist' and formats it
6822 according to FMT (default from `org-email-link-description-format')."
6823 (setq fmt (or fmt org-email-link-description-format))
6824 (let* ((p org-store-link-plist)
6825 (to (plist-get p :toaddress))
6826 (from (plist-get p :fromaddress))
6827 (table
6828 (list
6829 (cons "%c" (plist-get p :fromto))
6830 (cons "%F" (plist-get p :from))
6831 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6832 (cons "%T" (plist-get p :to))
6833 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6834 (cons "%s" (plist-get p :subject))
6835 (cons "%m" (plist-get p :message-id)))))
6836 (when (string-match "%c" fmt)
6837 ;; Check if the user wrote this message
6838 (if (and org-from-is-user-regexp from to
6839 (save-match-data (string-match org-from-is-user-regexp from)))
6840 (setq fmt (replace-match "to %t" t t fmt))
6841 (setq fmt (replace-match "from %f" t t fmt))))
6842 (org-replace-escapes fmt table)))
6844 (defun org-make-org-heading-search-string (&optional string heading)
6845 "Make search string for STRING or current headline."
6846 (interactive)
6847 (let ((s (or string (org-get-heading))))
6848 (unless (and string (not heading))
6849 ;; We are using a headline, clean up garbage in there.
6850 (if (string-match org-todo-regexp s)
6851 (setq s (replace-match "" t t s)))
6852 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6853 (setq s (replace-match "" t t s)))
6854 (setq s (org-trim s))
6855 (if (string-match (concat "^\\(" org-quote-string "\\|"
6856 org-comment-string "\\)") s)
6857 (setq s (replace-match "" t t s)))
6858 (while (string-match org-ts-regexp s)
6859 (setq s (replace-match "" t t s))))
6860 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6861 (setq s (replace-match " " t t s)))
6862 (or string (setq s (concat "*" s))) ; Add * for headlines
6863 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6865 (defun org-make-link (&rest strings)
6866 "Concatenate STRINGS."
6867 (apply 'concat strings))
6869 (defun org-make-link-string (link &optional description)
6870 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6871 (unless (string-match "\\S-" link)
6872 (error "Empty link"))
6873 (when (stringp description)
6874 ;; Remove brackets from the description, they are fatal.
6875 (while (string-match "\\[" description)
6876 (setq description (replace-match "{" t t description)))
6877 (while (string-match "\\]" description)
6878 (setq description (replace-match "}" t t description))))
6879 (when (equal (org-link-escape link) description)
6880 ;; No description needed, it is identical
6881 (setq description nil))
6882 (when (and (not description)
6883 (not (equal link (org-link-escape link))))
6884 (setq description (org-extract-attributes link)))
6885 (concat "[[" (org-link-escape link) "]"
6886 (if description (concat "[" description "]") "")
6887 "]"))
6889 (defconst org-link-escape-chars
6890 '((?\ . "%20")
6891 (?\[ . "%5B")
6892 (?\] . "%5D")
6893 (?\340 . "%E0") ; `a
6894 (?\342 . "%E2") ; ^a
6895 (?\347 . "%E7") ; ,c
6896 (?\350 . "%E8") ; `e
6897 (?\351 . "%E9") ; 'e
6898 (?\352 . "%EA") ; ^e
6899 (?\356 . "%EE") ; ^i
6900 (?\364 . "%F4") ; ^o
6901 (?\371 . "%F9") ; `u
6902 (?\373 . "%FB") ; ^u
6903 (?\; . "%3B")
6904 (?? . "%3F")
6905 (?= . "%3D")
6906 (?+ . "%2B")
6908 "Association list of escapes for some characters problematic in links.
6909 This is the list that is used for internal purposes.")
6911 (defconst org-link-escape-chars-browser
6912 '((?\ . "%20")) ; 32 for the SPC char
6913 "Association list of escapes for some characters problematic in links.
6914 This is the list that is used before handing over to the browser.")
6916 (defun org-link-escape (text &optional table)
6917 "Escape charaters in TEXT that are problematic for links."
6918 (setq table (or table org-link-escape-chars))
6919 (when text
6920 (let ((re (mapconcat (lambda (x) (regexp-quote
6921 (char-to-string (car x))))
6922 table "\\|")))
6923 (while (string-match re text)
6924 (setq text
6925 (replace-match
6926 (cdr (assoc (string-to-char (match-string 0 text))
6927 table))
6928 t t text)))
6929 text)))
6931 (defun org-link-unescape (text &optional table)
6932 "Reverse the action of `org-link-escape'."
6933 (setq table (or table org-link-escape-chars))
6934 (when text
6935 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6936 table "\\|")))
6937 (while (string-match re text)
6938 (setq text
6939 (replace-match
6940 (char-to-string (car (rassoc (match-string 0 text) table)))
6941 t t text)))
6942 text)))
6944 (defun org-xor (a b)
6945 "Exclusive or."
6946 (if a (not b) b))
6948 (defun org-get-header (header)
6949 "Find a header field in the current buffer."
6950 (save-excursion
6951 (goto-char (point-min))
6952 (let ((case-fold-search t) s)
6953 (cond
6954 ((eq header 'from)
6955 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6956 (setq s (match-string 1)))
6957 (while (string-match "\"" s)
6958 (setq s (replace-match "" t t s)))
6959 (if (string-match "[<(].*" s)
6960 (setq s (replace-match "" t t s))))
6961 ((eq header 'message-id)
6962 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6963 (setq s (match-string 1))))
6964 ((eq header 'subject)
6965 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6966 (setq s (match-string 1)))))
6967 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6968 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6969 s)))
6972 (defun org-fixup-message-id-for-http (s)
6973 "Replace special characters in a message id, so it can be used in an http query."
6974 (while (string-match "<" s)
6975 (setq s (replace-match "%3C" t t s)))
6976 (while (string-match ">" s)
6977 (setq s (replace-match "%3E" t t s)))
6978 (while (string-match "@" s)
6979 (setq s (replace-match "%40" t t s)))
6982 ;;;###autoload
6983 (defun org-insert-link-global ()
6984 "Insert a link like Org-mode does.
6985 This command can be called in any mode to insert a link in Org-mode syntax."
6986 (interactive)
6987 (org-load-modules-maybe)
6988 (org-run-like-in-org-mode 'org-insert-link))
6990 (defun org-insert-link (&optional complete-file link-location)
6991 "Insert a link. At the prompt, enter the link.
6993 Completion can be used to select a link previously stored with
6994 `org-store-link'. When the empty string is entered (i.e. if you just
6995 press RET at the prompt), the link defaults to the most recently
6996 stored link. As SPC triggers completion in the minibuffer, you need to
6997 use M-SPC or C-q SPC to force the insertion of a space character.
6999 You will also be prompted for a description, and if one is given, it will
7000 be displayed in the buffer instead of the link.
7002 If there is already a link at point, this command will allow you to edit link
7003 and description parts.
7005 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7006 be selected using completion. The path to the file will be relative to the
7007 current directory if the file is in the current directory or a subdirectory.
7008 Otherwise, the link will be the absolute path as completed in the minibuffer
7009 \(i.e. normally ~/path/to/file).
7011 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7012 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
7013 of `org-keep-stored-link-after-insertion'.
7015 If `org-make-link-description-function' is non-nil, this function will be
7016 called with the link target, and the result will be the default
7017 link description.
7019 If the LINK-LOCATION parameter is non-nil, this value will be
7020 used as the link location instead of reading one interactively."
7021 (interactive "P")
7022 (let* ((wcf (current-window-configuration))
7023 (region (if (org-region-active-p)
7024 (buffer-substring (region-beginning) (region-end))))
7025 (remove (and region (list (region-beginning) (region-end))))
7026 (desc region)
7027 tmphist ; byte-compile incorrectly complains about this
7028 (link link-location)
7029 entry file)
7030 (cond
7031 (link-location) ; specified by arg, just use it.
7032 ((org-in-regexp org-bracket-link-regexp 1)
7033 ;; We do have a link at point, and we are going to edit it.
7034 (setq remove (list (match-beginning 0) (match-end 0)))
7035 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7036 (setq link (read-string "Link: "
7037 (org-link-unescape
7038 (org-match-string-no-properties 1)))))
7039 ((or (org-in-regexp org-angle-link-re)
7040 (org-in-regexp org-plain-link-re))
7041 ;; Convert to bracket link
7042 (setq remove (list (match-beginning 0) (match-end 0))
7043 link (read-string "Link: "
7044 (org-remove-angle-brackets (match-string 0)))))
7045 ((equal complete-file '(4))
7046 ;; Completing read for file names.
7047 (setq file (read-file-name "File: "))
7048 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7049 (pwd1 (file-name-as-directory (abbreviate-file-name
7050 (expand-file-name ".")))))
7051 (cond
7052 ((equal complete-file '(16))
7053 (setq link (org-make-link
7054 "file:"
7055 (abbreviate-file-name (expand-file-name file)))))
7056 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7057 (setq link (org-make-link "file:" (match-string 1 file))))
7058 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7059 (expand-file-name file))
7060 (setq link (org-make-link
7061 "file:" (match-string 1 (expand-file-name file)))))
7062 (t (setq link (org-make-link "file:" file))))))
7064 ;; Read link, with completion for stored links.
7065 (with-output-to-temp-buffer "*Org Links*"
7066 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7067 (when org-stored-links
7068 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7069 (princ (mapconcat
7070 (lambda (x)
7071 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7072 (reverse org-stored-links) "\n"))))
7073 (let ((cw (selected-window)))
7074 (select-window (get-buffer-window "*Org Links*"))
7075 (shrink-window-if-larger-than-buffer)
7076 (setq truncate-lines t)
7077 (select-window cw))
7078 ;; Fake a link history, containing the stored links.
7079 (setq tmphist (append (mapcar 'car org-stored-links)
7080 org-insert-link-history))
7081 (unwind-protect
7082 (setq link (org-completing-read
7083 "Link: "
7084 (append
7085 (mapcar (lambda (x) (list (concat (car x) ":")))
7086 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7087 (mapcar (lambda (x) (list (concat x ":")))
7088 org-link-types))
7089 nil nil nil
7090 'tmphist
7091 (or (car (car org-stored-links)))))
7092 (set-window-configuration wcf)
7093 (kill-buffer "*Org Links*"))
7094 (setq entry (assoc link org-stored-links))
7095 (or entry (push link org-insert-link-history))
7096 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7097 (not org-keep-stored-link-after-insertion))
7098 (setq org-stored-links (delq (assoc link org-stored-links)
7099 org-stored-links)))
7100 (setq desc (or desc (nth 1 entry)))))
7102 (if (string-match org-plain-link-re link)
7103 ;; URL-like link, normalize the use of angular brackets.
7104 (setq link (org-make-link (org-remove-angle-brackets link))))
7106 ;; Check if we are linking to the current file with a search option
7107 ;; If yes, simplify the link by using only the search option.
7108 (when (and buffer-file-name
7109 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7110 (let* ((path (match-string 1 link))
7111 (case-fold-search nil)
7112 (search (match-string 2 link)))
7113 (save-match-data
7114 (if (equal (file-truename buffer-file-name) (file-truename path))
7115 ;; We are linking to this same file, with a search option
7116 (setq link search)))))
7118 ;; Check if we can/should use a relative path. If yes, simplify the link
7119 (when (string-match "\\<file:\\(.*\\)" link)
7120 (let* ((path (match-string 1 link))
7121 (origpath path)
7122 (case-fold-search nil))
7123 (cond
7124 ((eq org-link-file-path-type 'absolute)
7125 (setq path (abbreviate-file-name (expand-file-name path))))
7126 ((eq org-link-file-path-type 'noabbrev)
7127 (setq path (expand-file-name path)))
7128 ((eq org-link-file-path-type 'relative)
7129 (setq path (file-relative-name path)))
7131 (save-match-data
7132 (if (string-match (concat "^" (regexp-quote
7133 (file-name-as-directory
7134 (expand-file-name "."))))
7135 (expand-file-name path))
7136 ;; We are linking a file with relative path name.
7137 (setq path (substring (expand-file-name path)
7138 (match-end 0)))))))
7139 (setq link (concat "file:" path))
7140 (if (equal desc origpath)
7141 (setq desc path))))
7143 (if org-make-link-description-function
7144 (setq desc (funcall org-make-link-description-function link desc)))
7146 (setq desc (read-string "Description: " desc))
7147 (unless (string-match "\\S-" desc) (setq desc nil))
7148 (if remove (apply 'delete-region remove))
7149 (insert (org-make-link-string link desc))))
7151 (defun org-completing-read (&rest args)
7152 (let ((minibuffer-local-completion-map
7153 (copy-keymap minibuffer-local-completion-map)))
7154 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7155 (apply 'completing-read args)))
7157 (defun org-extract-attributes (s)
7158 "Extract the attributes cookie from a string and set as text property."
7159 (let (a attr (start 0) key value)
7160 (save-match-data
7161 (when (string-match "{{\\([^}]+\\)}}$" s)
7162 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7163 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7164 (setq key (match-string 1 a) value (match-string 2 a)
7165 start (match-end 0)
7166 attr (plist-put attr (intern key) value))))
7167 (org-add-props s nil 'org-attributes attr))
7170 (defun org-attributes-to-string (plist)
7171 "Format a property list into an HTML attribute list."
7172 (let ((s "") key value)
7173 (while plist
7174 (setq key (pop plist) value (pop plist))
7175 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7178 ;;; Opening/following a link
7180 (defvar org-link-search-failed nil)
7182 (defun org-next-link ()
7183 "Move forward to the next link.
7184 If the link is in hidden text, expose it."
7185 (interactive)
7186 (when (and org-link-search-failed (eq this-command last-command))
7187 (goto-char (point-min))
7188 (message "Link search wrapped back to beginning of buffer"))
7189 (setq org-link-search-failed nil)
7190 (let* ((pos (point))
7191 (ct (org-context))
7192 (a (assoc :link ct)))
7193 (if a (goto-char (nth 2 a)))
7194 (if (re-search-forward org-any-link-re nil t)
7195 (progn
7196 (goto-char (match-beginning 0))
7197 (if (org-invisible-p) (org-show-context)))
7198 (goto-char pos)
7199 (setq org-link-search-failed t)
7200 (error "No further link found"))))
7202 (defun org-previous-link ()
7203 "Move backward to the previous link.
7204 If the link is in hidden text, expose it."
7205 (interactive)
7206 (when (and org-link-search-failed (eq this-command last-command))
7207 (goto-char (point-max))
7208 (message "Link search wrapped back to end of buffer"))
7209 (setq org-link-search-failed nil)
7210 (let* ((pos (point))
7211 (ct (org-context))
7212 (a (assoc :link ct)))
7213 (if a (goto-char (nth 1 a)))
7214 (if (re-search-backward org-any-link-re nil t)
7215 (progn
7216 (goto-char (match-beginning 0))
7217 (if (org-invisible-p) (org-show-context)))
7218 (goto-char pos)
7219 (setq org-link-search-failed t)
7220 (error "No further link found"))))
7222 (defun org-find-file-at-mouse (ev)
7223 "Open file link or URL at mouse."
7224 (interactive "e")
7225 (mouse-set-point ev)
7226 (org-open-at-point 'in-emacs))
7228 (defun org-open-at-mouse (ev)
7229 "Open file link or URL at mouse."
7230 (interactive "e")
7231 (mouse-set-point ev)
7232 (org-open-at-point))
7234 (defvar org-window-config-before-follow-link nil
7235 "The window configuration before following a link.
7236 This is saved in case the need arises to restore it.")
7238 (defvar org-open-link-marker (make-marker)
7239 "Marker pointing to the location where `org-open-at-point; was called.")
7241 ;;;###autoload
7242 (defun org-open-at-point-global ()
7243 "Follow a link like Org-mode does.
7244 This command can be called in any mode to follow a link that has
7245 Org-mode syntax."
7246 (interactive)
7247 (org-run-like-in-org-mode 'org-open-at-point))
7249 ;;;###autoload
7250 (defun org-open-link-from-string (s &optional arg)
7251 "Open a link in the string S, as if it was in Org-mode."
7252 (interactive "sLink: \nP")
7253 (with-temp-buffer
7254 (let ((org-inhibit-startup t))
7255 (org-mode)
7256 (insert s)
7257 (goto-char (point-min))
7258 (org-open-at-point arg))))
7260 (defun org-open-at-point (&optional in-emacs)
7261 "Open link at or after point.
7262 If there is no link at point, this function will search forward up to
7263 the end of the current subtree.
7264 Normally, files will be opened by an appropriate application. If the
7265 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7266 (interactive "P")
7267 (org-load-modules-maybe)
7268 (move-marker org-open-link-marker (point))
7269 (setq org-window-config-before-follow-link (current-window-configuration))
7270 (org-remove-occur-highlights nil nil t)
7271 (if (org-at-timestamp-p t)
7272 (org-follow-timestamp-link)
7273 (let (type path link line search (pos (point)))
7274 (catch 'match
7275 (save-excursion
7276 (skip-chars-forward "^]\n\r")
7277 (when (org-in-regexp org-bracket-link-regexp)
7278 (setq link (org-extract-attributes
7279 (org-link-unescape (org-match-string-no-properties 1))))
7280 (while (string-match " *\n *" link)
7281 (setq link (replace-match " " t t link)))
7282 (setq link (org-link-expand-abbrev link))
7283 (cond
7284 ((or (file-name-absolute-p link)
7285 (string-match "^\\.\\.?/" link))
7286 (setq type "file" path link))
7287 ((string-match org-link-re-with-space2 link)
7288 (setq type (match-string 1 link) path (match-string 2 link)))
7289 (t (setq type "thisfile" path link)))
7290 (throw 'match t)))
7292 (when (get-text-property (point) 'org-linked-text)
7293 (setq type "thisfile"
7294 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7295 (1+ (point)) (point))
7296 path (buffer-substring
7297 (previous-single-property-change pos 'org-linked-text)
7298 (next-single-property-change pos 'org-linked-text)))
7299 (throw 'match t))
7301 (save-excursion
7302 (when (or (org-in-regexp org-angle-link-re)
7303 (org-in-regexp org-plain-link-re))
7304 (setq type (match-string 1) path (match-string 2))
7305 (throw 'match t)))
7306 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7307 (setq type "tree-match"
7308 path (match-string 1))
7309 (throw 'match t))
7310 (save-excursion
7311 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7312 (setq type "tags"
7313 path (match-string 1))
7314 (while (string-match ":" path)
7315 (setq path (replace-match "+" t t path)))
7316 (throw 'match t))))
7317 (unless path
7318 (error "No link found"))
7319 ;; Remove any trailing spaces in path
7320 (if (string-match " +\\'" path)
7321 (setq path (replace-match "" t t path)))
7323 (cond
7325 ((assoc type org-link-protocols)
7326 (funcall (nth 1 (assoc type org-link-protocols)) path))
7328 ((equal type "mailto")
7329 (let ((cmd (car org-link-mailto-program))
7330 (args (cdr org-link-mailto-program)) args1
7331 (address path) (subject "") a)
7332 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7333 (setq address (match-string 1 path)
7334 subject (org-link-escape (match-string 2 path))))
7335 (while args
7336 (cond
7337 ((not (stringp (car args))) (push (pop args) args1))
7338 (t (setq a (pop args))
7339 (if (string-match "%a" a)
7340 (setq a (replace-match address t t a)))
7341 (if (string-match "%s" a)
7342 (setq a (replace-match subject t t a)))
7343 (push a args1))))
7344 (apply cmd (nreverse args1))))
7346 ((member type '("http" "https" "ftp" "news"))
7347 (browse-url (concat type ":" (org-link-escape
7348 path org-link-escape-chars-browser))))
7350 ((member type '("message"))
7351 (browse-url (concat type ":" path)))
7353 ((string= type "tags")
7354 (org-tags-view in-emacs path))
7355 ((string= type "thisfile")
7356 (if in-emacs
7357 (switch-to-buffer-other-window
7358 (org-get-buffer-for-internal-link (current-buffer)))
7359 (org-mark-ring-push))
7360 (let ((cmd `(org-link-search
7361 ,path
7362 ,(cond ((equal in-emacs '(4)) 'occur)
7363 ((equal in-emacs '(16)) 'org-occur)
7364 (t nil))
7365 ,pos)))
7366 (condition-case nil (eval cmd)
7367 (error (progn (widen) (eval cmd))))))
7369 ((string= type "tree-match")
7370 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7372 ((string= type "file")
7373 (if (string-match "::\\([0-9]+\\)\\'" path)
7374 (setq line (string-to-number (match-string 1 path))
7375 path (substring path 0 (match-beginning 0)))
7376 (if (string-match "::\\(.+\\)\\'" path)
7377 (setq search (match-string 1 path)
7378 path (substring path 0 (match-beginning 0)))))
7379 (if (string-match "[*?{]" (file-name-nondirectory path))
7380 (dired path)
7381 (org-open-file path in-emacs line search)))
7383 ((string= type "news")
7384 (require 'org-gnus)
7385 (org-gnus-follow-link path))
7387 ((string= type "shell")
7388 (let ((cmd path))
7389 (if (or (not org-confirm-shell-link-function)
7390 (funcall org-confirm-shell-link-function
7391 (format "Execute \"%s\" in shell? "
7392 (org-add-props cmd nil
7393 'face 'org-warning))))
7394 (progn
7395 (message "Executing %s" cmd)
7396 (shell-command cmd))
7397 (error "Abort"))))
7399 ((string= type "elisp")
7400 (let ((cmd path))
7401 (if (or (not org-confirm-elisp-link-function)
7402 (funcall org-confirm-elisp-link-function
7403 (format "Execute \"%s\" as elisp? "
7404 (org-add-props cmd nil
7405 'face 'org-warning))))
7406 (message "%s => %s" cmd (eval (read cmd)))
7407 (error "Abort"))))
7410 (browse-url-at-point)))))
7411 (move-marker org-open-link-marker nil)
7412 (run-hook-with-args 'org-follow-link-hook))
7414 ;;;; Time estimates
7416 (defun org-get-effort (&optional pom)
7417 "Get the effort estimate for the current entry."
7418 (org-entry-get pom org-effort-property))
7420 ;;; File search
7422 (defvar org-create-file-search-functions nil
7423 "List of functions to construct the right search string for a file link.
7424 These functions are called in turn with point at the location to
7425 which the link should point.
7427 A function in the hook should first test if it would like to
7428 handle this file type, for example by checking the major-mode or
7429 the file extension. If it decides not to handle this file, it
7430 should just return nil to give other functions a chance. If it
7431 does handle the file, it must return the search string to be used
7432 when following the link. The search string will be part of the
7433 file link, given after a double colon, and `org-open-at-point'
7434 will automatically search for it. If special measures must be
7435 taken to make the search successful, another function should be
7436 added to the companion hook `org-execute-file-search-functions',
7437 which see.
7439 A function in this hook may also use `setq' to set the variable
7440 `description' to provide a suggestion for the descriptive text to
7441 be used for this link when it gets inserted into an Org-mode
7442 buffer with \\[org-insert-link].")
7444 (defvar org-execute-file-search-functions nil
7445 "List of functions to execute a file search triggered by a link.
7447 Functions added to this hook must accept a single argument, the
7448 search string that was part of the file link, the part after the
7449 double colon. The function must first check if it would like to
7450 handle this search, for example by checking the major-mode or the
7451 file extension. If it decides not to handle this search, it
7452 should just return nil to give other functions a chance. If it
7453 does handle the search, it must return a non-nil value to keep
7454 other functions from trying.
7456 Each function can access the current prefix argument through the
7457 variable `current-prefix-argument'. Note that a single prefix is
7458 used to force opening a link in Emacs, so it may be good to only
7459 use a numeric or double prefix to guide the search function.
7461 In case this is needed, a function in this hook can also restore
7462 the window configuration before `org-open-at-point' was called using:
7464 (set-window-configuration org-window-config-before-follow-link)")
7466 (defun org-link-search (s &optional type avoid-pos)
7467 "Search for a link search option.
7468 If S is surrounded by forward slashes, it is interpreted as a
7469 regular expression. In org-mode files, this will create an `org-occur'
7470 sparse tree. In ordinary files, `occur' will be used to list matches.
7471 If the current buffer is in `dired-mode', grep will be used to search
7472 in all files. If AVOID-POS is given, ignore matches near that position."
7473 (let ((case-fold-search t)
7474 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7475 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7476 (append '(("") (" ") ("\t") ("\n"))
7477 org-emphasis-alist)
7478 "\\|") "\\)"))
7479 (pos (point))
7480 (pre nil) (post nil)
7481 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7482 (cond
7483 ;; First check if there are any special
7484 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7485 ;; Now try the builtin stuff
7486 ((save-excursion
7487 (goto-char (point-min))
7488 (and
7489 (re-search-forward
7490 (concat "<<" (regexp-quote s0) ">>") nil t)
7491 (setq type 'dedicated
7492 pos (match-beginning 0))))
7493 ;; There is an exact target for this
7494 (goto-char pos))
7495 ((string-match "^/\\(.*\\)/$" s)
7496 ;; A regular expression
7497 (cond
7498 ((org-mode-p)
7499 (org-occur (match-string 1 s)))
7500 ;;((eq major-mode 'dired-mode)
7501 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7502 (t (org-do-occur (match-string 1 s)))))
7504 ;; A normal search strings
7505 (when (equal (string-to-char s) ?*)
7506 ;; Anchor on headlines, post may include tags.
7507 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7508 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7509 s (substring s 1)))
7510 (remove-text-properties
7511 0 (length s)
7512 '(face nil mouse-face nil keymap nil fontified nil) s)
7513 ;; Make a series of regular expressions to find a match
7514 (setq words (org-split-string s "[ \n\r\t]+")
7516 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7517 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7518 "\\)" markers)
7519 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7520 re2a (concat "[ \t\r\n]" re2a_)
7521 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7522 re4 (concat "[^a-zA-Z_]" re4_)
7524 re1 (concat pre re2 post)
7525 re3 (concat pre (if pre re4_ re4) post)
7526 re5 (concat pre ".*" re4)
7527 re2 (concat pre re2)
7528 re2a (concat pre (if pre re2a_ re2a))
7529 re4 (concat pre (if pre re4_ re4))
7530 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7531 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7532 re5 "\\)"
7534 (cond
7535 ((eq type 'org-occur) (org-occur reall))
7536 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7537 (t (goto-char (point-min))
7538 (setq type 'fuzzy)
7539 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7540 (org-search-not-self 1 re1 nil t)
7541 (org-search-not-self 1 re2 nil t)
7542 (org-search-not-self 1 re2a nil t)
7543 (org-search-not-self 1 re3 nil t)
7544 (org-search-not-self 1 re4 nil t)
7545 (org-search-not-self 1 re5 nil t)
7547 (goto-char (match-beginning 1))
7548 (goto-char pos)
7549 (error "No match")))))
7551 ;; Normal string-search
7552 (goto-char (point-min))
7553 (if (search-forward s nil t)
7554 (goto-char (match-beginning 0))
7555 (error "No match"))))
7556 (and (org-mode-p) (org-show-context 'link-search))
7557 type))
7559 (defun org-search-not-self (group &rest args)
7560 "Execute `re-search-forward', but only accept matches that do not
7561 enclose the position of `org-open-link-marker'."
7562 (let ((m org-open-link-marker))
7563 (catch 'exit
7564 (while (apply 're-search-forward args)
7565 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7566 (goto-char (match-end group))
7567 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7568 (> (match-beginning 0) (marker-position m))
7569 (< (match-end 0) (marker-position m)))
7570 (save-match-data
7571 (or (not (org-in-regexp
7572 org-bracket-link-analytic-regexp 1))
7573 (not (match-end 4)) ; no description
7574 (and (<= (match-beginning 4) (point))
7575 (>= (match-end 4) (point))))))
7576 (throw 'exit (point))))))))
7578 (defun org-get-buffer-for-internal-link (buffer)
7579 "Return a buffer to be used for displaying the link target of internal links."
7580 (cond
7581 ((not org-display-internal-link-with-indirect-buffer)
7582 buffer)
7583 ((string-match "(Clone)$" (buffer-name buffer))
7584 (message "Buffer is already a clone, not making another one")
7585 ;; we also do not modify visibility in this case
7586 buffer)
7587 (t ; make a new indirect buffer for displaying the link
7588 (let* ((bn (buffer-name buffer))
7589 (ibn (concat bn "(Clone)"))
7590 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7591 (with-current-buffer ib (org-overview))
7592 ib))))
7594 (defun org-do-occur (regexp &optional cleanup)
7595 "Call the Emacs command `occur'.
7596 If CLEANUP is non-nil, remove the printout of the regular expression
7597 in the *Occur* buffer. This is useful if the regex is long and not useful
7598 to read."
7599 (occur regexp)
7600 (when cleanup
7601 (let ((cwin (selected-window)) win beg end)
7602 (when (setq win (get-buffer-window "*Occur*"))
7603 (select-window win))
7604 (goto-char (point-min))
7605 (when (re-search-forward "match[a-z]+" nil t)
7606 (setq beg (match-end 0))
7607 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7608 (setq end (1- (match-beginning 0)))))
7609 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7610 (goto-char (point-min))
7611 (select-window cwin))))
7613 ;;; The mark ring for links jumps
7615 (defvar org-mark-ring nil
7616 "Mark ring for positions before jumps in Org-mode.")
7617 (defvar org-mark-ring-last-goto nil
7618 "Last position in the mark ring used to go back.")
7619 ;; Fill and close the ring
7620 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7621 (loop for i from 1 to org-mark-ring-length do
7622 (push (make-marker) org-mark-ring))
7623 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7624 org-mark-ring)
7626 (defun org-mark-ring-push (&optional pos buffer)
7627 "Put the current position or POS into the mark ring and rotate it."
7628 (interactive)
7629 (setq pos (or pos (point)))
7630 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7631 (move-marker (car org-mark-ring)
7632 (or pos (point))
7633 (or buffer (current-buffer)))
7634 (message "%s"
7635 (substitute-command-keys
7636 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7638 (defun org-mark-ring-goto (&optional n)
7639 "Jump to the previous position in the mark ring.
7640 With prefix arg N, jump back that many stored positions. When
7641 called several times in succession, walk through the entire ring.
7642 Org-mode commands jumping to a different position in the current file,
7643 or to another Org-mode file, automatically push the old position
7644 onto the ring."
7645 (interactive "p")
7646 (let (p m)
7647 (if (eq last-command this-command)
7648 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7649 (setq p org-mark-ring))
7650 (setq org-mark-ring-last-goto p)
7651 (setq m (car p))
7652 (switch-to-buffer (marker-buffer m))
7653 (goto-char m)
7654 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7656 (defun org-remove-angle-brackets (s)
7657 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7658 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7660 (defun org-add-angle-brackets (s)
7661 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7662 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7664 (defun org-remove-double-quotes (s)
7665 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7666 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7669 ;;; Following specific links
7671 (defun org-follow-timestamp-link ()
7672 (cond
7673 ((org-at-date-range-p t)
7674 (let ((org-agenda-start-on-weekday)
7675 (t1 (match-string 1))
7676 (t2 (match-string 2)))
7677 (setq t1 (time-to-days (org-time-string-to-time t1))
7678 t2 (time-to-days (org-time-string-to-time t2)))
7679 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7680 ((org-at-timestamp-p t)
7681 (org-agenda-list nil (time-to-days (org-time-string-to-time
7682 (substring (match-string 1) 0 10)))
7684 (t (error "This should not happen"))))
7687 ;;; Following file links
7688 (defvar org-wait nil)
7689 (defun org-open-file (path &optional in-emacs line search)
7690 "Open the file at PATH.
7691 First, this expands any special file name abbreviations. Then the
7692 configuration variable `org-file-apps' is checked if it contains an
7693 entry for this file type, and if yes, the corresponding command is launched.
7694 If no application is found, Emacs simply visits the file.
7695 With optional argument IN-EMACS, Emacs will visit the file.
7696 Optional LINE specifies a line to go to, optional SEARCH a string to
7697 search for. If LINE or SEARCH is given, the file will always be
7698 opened in Emacs.
7699 If the file does not exist, an error is thrown."
7700 (setq in-emacs (or in-emacs line search))
7701 (let* ((file (if (equal path "")
7702 buffer-file-name
7703 (substitute-in-file-name (expand-file-name path))))
7704 (apps (append org-file-apps (org-default-apps)))
7705 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7706 (dirp (if remp nil (file-directory-p file)))
7707 (file (if (and dirp org-open-directory-means-index-dot-org)
7708 (concat (file-name-as-directory file) "index.org")
7709 file))
7710 (dfile (downcase file))
7711 (old-buffer (current-buffer))
7712 (old-pos (point))
7713 (old-mode major-mode)
7714 ext cmd)
7715 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7716 (setq ext (match-string 1 dfile))
7717 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7718 (setq ext (match-string 1 dfile))))
7719 (if in-emacs
7720 (setq cmd 'emacs)
7721 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7722 (and dirp (cdr (assoc 'directory apps)))
7723 (cdr (assoc ext apps))
7724 (cdr (assoc t apps)))))
7725 (when (eq cmd 'mailcap)
7726 (require 'mailcap)
7727 (mailcap-parse-mailcaps)
7728 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7729 (command (mailcap-mime-info mime-type)))
7730 (if (stringp command)
7731 (setq cmd command)
7732 (setq cmd 'emacs))))
7733 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7734 (not (file-exists-p file))
7735 (not org-open-non-existing-files))
7736 (error "No such file: %s" file))
7737 (cond
7738 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7739 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7740 (while (string-match "['\"]%s['\"]" cmd)
7741 (setq cmd (replace-match "%s" t t cmd)))
7742 (while (string-match "%s" cmd)
7743 (setq cmd (replace-match
7744 (save-match-data
7745 (shell-quote-argument
7746 (convert-standard-filename file)))
7747 t t cmd)))
7748 (save-window-excursion
7749 (start-process-shell-command cmd nil cmd)
7750 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7752 ((or (stringp cmd)
7753 (eq cmd 'emacs))
7754 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7755 (widen)
7756 (if line (goto-line line)
7757 (if search (org-link-search search))))
7758 ((consp cmd)
7759 (let ((file (convert-standard-filename file)))
7760 (eval cmd)))
7761 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7762 (and (org-mode-p) (eq old-mode 'org-mode)
7763 (or (not (equal old-buffer (current-buffer)))
7764 (not (equal old-pos (point))))
7765 (org-mark-ring-push old-pos old-buffer))))
7767 (defun org-default-apps ()
7768 "Return the default applications for this operating system."
7769 (cond
7770 ((eq system-type 'darwin)
7771 org-file-apps-defaults-macosx)
7772 ((eq system-type 'windows-nt)
7773 org-file-apps-defaults-windowsnt)
7774 (t org-file-apps-defaults-gnu)))
7776 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7777 (defun org-file-remote-p (file)
7778 "Test whether FILE specifies a location on a remote system.
7779 Return non-nil if the location is indeed remote.
7781 For example, the filename \"/user@host:/foo\" specifies a location
7782 on the system \"/user@host:\"."
7783 (cond ((fboundp 'file-remote-p)
7784 (file-remote-p file))
7785 ((fboundp 'tramp-handle-file-remote-p)
7786 (tramp-handle-file-remote-p file))
7787 ((and (boundp 'ange-ftp-name-format)
7788 (string-match (car ange-ftp-name-format) file))
7790 (t nil)))
7793 ;;;; Refiling
7795 (defun org-get-org-file ()
7796 "Read a filename, with default directory `org-directory'."
7797 (let ((default (or org-default-notes-file remember-data-file)))
7798 (read-file-name (format "File name [%s]: " default)
7799 (file-name-as-directory org-directory)
7800 default)))
7802 (defun org-notes-order-reversed-p ()
7803 "Check if the current file should receive notes in reversed order."
7804 (cond
7805 ((not org-reverse-note-order) nil)
7806 ((eq t org-reverse-note-order) t)
7807 ((not (listp org-reverse-note-order)) nil)
7808 (t (catch 'exit
7809 (let ((all org-reverse-note-order)
7810 entry)
7811 (while (setq entry (pop all))
7812 (if (string-match (car entry) buffer-file-name)
7813 (throw 'exit (cdr entry))))
7814 nil)))))
7816 (defvar org-refile-target-table nil
7817 "The list of refile targets, created by `org-refile'.")
7819 (defvar org-agenda-new-buffers nil
7820 "Buffers created to visit agenda files.")
7822 (defun org-get-refile-targets (&optional default-buffer)
7823 "Produce a table with refile targets."
7824 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7825 targets txt re files f desc descre)
7826 (with-current-buffer (or default-buffer (current-buffer))
7827 (while (setq entry (pop entries))
7828 (setq files (car entry) desc (cdr entry))
7829 (cond
7830 ((null files) (setq files (list (current-buffer))))
7831 ((eq files 'org-agenda-files)
7832 (setq files (org-agenda-files 'unrestricted)))
7833 ((and (symbolp files) (fboundp files))
7834 (setq files (funcall files)))
7835 ((and (symbolp files) (boundp files))
7836 (setq files (symbol-value files))))
7837 (if (stringp files) (setq files (list files)))
7838 (cond
7839 ((eq (car desc) :tag)
7840 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7841 ((eq (car desc) :todo)
7842 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7843 ((eq (car desc) :regexp)
7844 (setq descre (cdr desc)))
7845 ((eq (car desc) :level)
7846 (setq descre (concat "^\\*\\{" (number-to-string
7847 (if org-odd-levels-only
7848 (1- (* 2 (cdr desc)))
7849 (cdr desc)))
7850 "\\}[ \t]")))
7851 ((eq (car desc) :maxlevel)
7852 (setq descre (concat "^\\*\\{1," (number-to-string
7853 (if org-odd-levels-only
7854 (1- (* 2 (cdr desc)))
7855 (cdr desc)))
7856 "\\}[ \t]")))
7857 (t (error "Bad refiling target description %s" desc)))
7858 (while (setq f (pop files))
7859 (save-excursion
7860 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7861 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7862 (save-excursion
7863 (save-restriction
7864 (widen)
7865 (goto-char (point-min))
7866 (while (re-search-forward descre nil t)
7867 (goto-char (point-at-bol))
7868 (when (looking-at org-complex-heading-regexp)
7869 (setq txt (match-string 4)
7870 re (concat "^" (regexp-quote
7871 (buffer-substring (match-beginning 1)
7872 (match-end 4)))))
7873 (if (match-end 5) (setq re (concat re "[ \t]+"
7874 (regexp-quote
7875 (match-string 5)))))
7876 (setq re (concat re "[ \t]*$"))
7877 (when org-refile-use-outline-path
7878 (setq txt (mapconcat 'org-protect-slash
7879 (append
7880 (if (eq org-refile-use-outline-path 'file)
7881 (list (file-name-nondirectory
7882 (buffer-file-name (buffer-base-buffer))))
7883 (if (eq org-refile-use-outline-path 'full-file-path)
7884 (list (buffer-file-name (buffer-base-buffer)))))
7885 (org-get-outline-path)
7886 (list txt))
7887 "/")))
7888 (push (list txt f re (point)) targets))
7889 (goto-char (point-at-eol))))))))
7890 (nreverse targets))))
7892 (defun org-protect-slash (s)
7893 (while (string-match "/" s)
7894 (setq s (replace-match "\\" t t s)))
7897 (defun org-get-outline-path ()
7898 "Return the outline path to the current entry, as a list."
7899 (let (rtn)
7900 (save-excursion
7901 (while (org-up-heading-safe)
7902 (when (looking-at org-complex-heading-regexp)
7903 (push (org-match-string-no-properties 4) rtn)))
7904 rtn)))
7906 (defvar org-refile-history nil
7907 "History for refiling operations.")
7909 (defun org-refile (&optional goto default-buffer)
7910 "Move the entry at point to another heading.
7911 The list of target headings is compiled using the information in
7912 `org-refile-targets', which see. This list is created before each use
7913 and will therefore always be up-to-date.
7915 At the target location, the entry is filed as a subitem of the target heading.
7916 Depending on `org-reverse-note-order', the new subitem will either be the
7917 first of the last subitem.
7919 With prefix arg GOTO, the command will only visit the target location,
7920 not actually move anything.
7921 With a double prefix `C-u C-u', go to the location where the last refiling
7922 operation has put the subtree."
7923 (interactive "P")
7924 (let* ((cbuf (current-buffer))
7925 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7926 pos it nbuf file re level reversed)
7927 (if (equal goto '(16))
7928 (org-refile-goto-last-stored)
7929 (when (setq it (org-refile-get-location
7930 (if goto "Goto: " "Refile to: ") default-buffer))
7931 (setq file (nth 1 it)
7932 re (nth 2 it)
7933 pos (nth 3 it))
7934 (setq nbuf (or (find-buffer-visiting file)
7935 (find-file-noselect file)))
7936 (if goto
7937 (progn
7938 (switch-to-buffer nbuf)
7939 (goto-char pos)
7940 (org-show-context 'org-goto))
7941 (org-copy-subtree 1 nil t)
7942 (save-excursion
7943 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7944 (find-file-noselect file))))
7945 (setq reversed (org-notes-order-reversed-p))
7946 (save-excursion
7947 (save-restriction
7948 (widen)
7949 (goto-char pos)
7950 (looking-at outline-regexp)
7951 (setq level (org-get-valid-level (funcall outline-level) 1))
7952 (goto-char
7953 (if reversed
7954 (or (outline-next-heading) (point-max))
7955 (or (save-excursion (outline-get-next-sibling))
7956 (org-end-of-subtree t t)
7957 (point-max))))
7958 (if (not (bolp)) (newline))
7959 (bookmark-set "org-refile-last-stored")
7960 (org-paste-subtree level))))
7961 (org-cut-subtree)
7962 (setq org-markers-to-move nil)
7963 (message "Entry refiled to \"%s\"" (car it)))))))
7965 (defun org-refile-goto-last-stored ()
7966 "Go to the location where the last refile was stored."
7967 (interactive)
7968 (bookmark-jump "org-refile-last-stored")
7969 (message "This is the location of the last refile"))
7971 (defun org-refile-get-location (&optional prompt default-buffer)
7972 "Prompt the user for a refile location, using PROMPT."
7973 (let ((org-refile-targets org-refile-targets)
7974 (org-refile-use-outline-path org-refile-use-outline-path))
7975 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7976 (unless org-refile-target-table
7977 (error "No refile targets"))
7978 (let* ((cbuf (current-buffer))
7979 (cfunc (if org-refile-use-outline-path
7980 'org-olpath-completing-read
7981 'completing-read))
7982 (extra (if org-refile-use-outline-path "/" ""))
7983 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7984 (fname (and filename (file-truename filename)))
7985 (tbl (mapcar
7986 (lambda (x)
7987 (if (not (equal fname (file-truename (nth 1 x))))
7988 (cons (concat (car x) extra " ("
7989 (file-name-nondirectory (nth 1 x)) ")")
7990 (cdr x))
7991 (cons (concat (car x) extra) (cdr x))))
7992 org-refile-target-table))
7993 (completion-ignore-case t))
7994 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7995 tbl)))
7997 (defun org-olpath-completing-read (prompt collection &rest args)
7998 "Read an outline path like a file name."
7999 (let ((thetable collection))
8000 (apply
8001 'completing-read prompt
8002 (lambda (string predicate &optional flag)
8003 (let (rtn r s f (l (length string)))
8004 (cond
8005 ((eq flag nil)
8006 ;; try completion
8007 (try-completion string thetable))
8008 ((eq flag t)
8009 ;; all-completions
8010 (setq rtn (all-completions string thetable predicate))
8011 (mapcar
8012 (lambda (x)
8013 (setq r (substring x l))
8014 (if (string-match " ([^)]*)$" x)
8015 (setq f (match-string 0 x))
8016 (setq f ""))
8017 (if (string-match "/" r)
8018 (concat string (substring r 0 (match-end 0)) f)
8020 rtn))
8021 ((eq flag 'lambda)
8022 ;; exact match?
8023 (assoc string thetable)))
8025 args)))
8027 ;;;; Dynamic blocks
8029 (defun org-find-dblock (name)
8030 "Find the first dynamic block with name NAME in the buffer.
8031 If not found, stay at current position and return nil."
8032 (let (pos)
8033 (save-excursion
8034 (goto-char (point-min))
8035 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8036 nil t)
8037 (match-beginning 0))))
8038 (if pos (goto-char pos))
8039 pos))
8041 (defconst org-dblock-start-re
8042 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8043 "Matches the startline of a dynamic block, with parameters.")
8045 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8046 "Matches the end of a dyhamic block.")
8048 (defun org-create-dblock (plist)
8049 "Create a dynamic block section, with parameters taken from PLIST.
8050 PLIST must containe a :name entry which is used as name of the block."
8051 (unless (bolp) (newline))
8052 (let ((name (plist-get plist :name)))
8053 (insert "#+BEGIN: " name)
8054 (while plist
8055 (if (eq (car plist) :name)
8056 (setq plist (cddr plist))
8057 (insert " " (prin1-to-string (pop plist)))))
8058 (insert "\n\n#+END:\n")
8059 (beginning-of-line -2)))
8061 (defun org-prepare-dblock ()
8062 "Prepare dynamic block for refresh.
8063 This empties the block, puts the cursor at the insert position and returns
8064 the property list including an extra property :name with the block name."
8065 (unless (looking-at org-dblock-start-re)
8066 (error "Not at a dynamic block"))
8067 (let* ((begdel (1+ (match-end 0)))
8068 (name (org-no-properties (match-string 1)))
8069 (params (append (list :name name)
8070 (read (concat "(" (match-string 3) ")")))))
8071 (unless (re-search-forward org-dblock-end-re nil t)
8072 (error "Dynamic block not terminated"))
8073 (setq params
8074 (append params
8075 (list :content (buffer-substring
8076 begdel (match-beginning 0)))))
8077 (delete-region begdel (match-beginning 0))
8078 (goto-char begdel)
8079 (open-line 1)
8080 params))
8082 (defun org-map-dblocks (&optional command)
8083 "Apply COMMAND to all dynamic blocks in the current buffer.
8084 If COMMAND is not given, use `org-update-dblock'."
8085 (let ((cmd (or command 'org-update-dblock))
8086 pos)
8087 (save-excursion
8088 (goto-char (point-min))
8089 (while (re-search-forward org-dblock-start-re nil t)
8090 (goto-char (setq pos (match-beginning 0)))
8091 (condition-case nil
8092 (funcall cmd)
8093 (error (message "Error during update of dynamic block")))
8094 (goto-char pos)
8095 (unless (re-search-forward org-dblock-end-re nil t)
8096 (error "Dynamic block not terminated"))))))
8098 (defun org-dblock-update (&optional arg)
8099 "User command for updating dynamic blocks.
8100 Update the dynamic block at point. With prefix ARG, update all dynamic
8101 blocks in the buffer."
8102 (interactive "P")
8103 (if arg
8104 (org-update-all-dblocks)
8105 (or (looking-at org-dblock-start-re)
8106 (org-beginning-of-dblock))
8107 (org-update-dblock)))
8109 (defun org-update-dblock ()
8110 "Update the dynamic block at point
8111 This means to empty the block, parse for parameters and then call
8112 the correct writing function."
8113 (save-window-excursion
8114 (let* ((pos (point))
8115 (line (org-current-line))
8116 (params (org-prepare-dblock))
8117 (name (plist-get params :name))
8118 (cmd (intern (concat "org-dblock-write:" name))))
8119 (message "Updating dynamic block `%s' at line %d..." name line)
8120 (funcall cmd params)
8121 (message "Updating dynamic block `%s' at line %d...done" name line)
8122 (goto-char pos))))
8124 (defun org-beginning-of-dblock ()
8125 "Find the beginning of the dynamic block at point.
8126 Error if there is no scuh block at point."
8127 (let ((pos (point))
8128 beg)
8129 (end-of-line 1)
8130 (if (and (re-search-backward org-dblock-start-re nil t)
8131 (setq beg (match-beginning 0))
8132 (re-search-forward org-dblock-end-re nil t)
8133 (> (match-end 0) pos))
8134 (goto-char beg)
8135 (goto-char pos)
8136 (error "Not in a dynamic block"))))
8138 (defun org-update-all-dblocks ()
8139 "Update all dynamic blocks in the buffer.
8140 This function can be used in a hook."
8141 (when (org-mode-p)
8142 (org-map-dblocks 'org-update-dblock)))
8145 ;;;; Completion
8147 (defconst org-additional-option-like-keywords
8148 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8149 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8150 "BEGIN_EXAMPLE" "END_EXAMPLE"
8151 "BEGIN_QUOTE" "END_QUOTE"
8152 "BEGIN_VERSE" "END_VERSE"
8153 "BEGIN_SRC" "END_SRC"))
8155 (defcustom org-structure-template-alist
8157 ("s" "#+begin_src ?\n\n#+end_src"
8158 "<src lang=\"?\">\n\n</src>")
8159 ("e" "#+begin_example\n?\n#+end_example"
8160 "<example>\n?\n</example>")
8161 ("q" "#+begin_quote\n?\n#+end_quote"
8162 "<quote>\n?\n</quote>")
8163 ("v" "#+begin_verse\n?\n#+end_verse"
8164 "<verse>\n?\n/verse>")
8165 ("l" "#+begin_latex\n?\n#+end_latex"
8166 "<literal style=\"latex\">\n?\n</literal>")
8167 ("L" "#+latex: "
8168 "<literal style=\"latex\">?</literal>")
8169 ("h" "#+begin_html\n?\n#+end_html"
8170 "<literal style=\"html\">\n?\n</literal>")
8171 ("H" "#+html: "
8172 "<literal style=\"html\">?</literal>")
8173 ("a" "#+begin_ascii\n?\n#+end_ascii")
8174 ("A" "#+ascii: ")
8175 ("i" "#+include %file ?"
8176 "<include file=%file markup=\"?\">")
8178 "Structure completion elements.
8179 This is a list of abbreviation keys and values. The value gets inserted
8180 it you type @samp{.} followed by the key and then the completion key,
8181 usually `M-TAB'. %file will be replaced by a file name after prompting
8182 for the file uning completion.
8183 There are two templates for each key, the first uses the original Org syntax,
8184 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8185 the default when the /org-mtags.el/ module has been loaded. See also the
8186 variable `org-mtags-prefere-muse-templates'.
8187 This is an experimental feature, it is undecided if it is going to stay in."
8188 :group 'org-completion
8189 :type '(repeat
8190 (string :tag "Key")
8191 (string :tag "Template")
8192 (string :tag "Muse Template")))
8194 (defun org-try-structure-completion ()
8195 "Try to complete a structure template before point.
8196 This looks for strings like \"<e\" on an otherwise empty line and
8197 expands them."
8198 (let ((l (buffer-substring (point-at-bol) (point)))
8200 (when (and (looking-at "[ \t]*$")
8201 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8202 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8203 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8204 (match-beginning 1)) a)
8205 t)))
8207 (defun org-complete-expand-structure-template (start cell)
8208 "Expand a structure template."
8209 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8210 (rpl (nth (if musep 2 1) cell)))
8211 (delete-region start (point))
8212 (when (string-match "\\`#\\+" rpl)
8213 (cond
8214 ((bolp))
8215 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8216 (delete-region (point-at-bol) (point)))
8217 (t (newline))))
8218 (setq start (point))
8219 (if (string-match "%file" rpl)
8220 (setq rpl (replace-match
8221 (concat
8222 "\""
8223 (save-match-data
8224 (abbreviate-file-name (read-file-name "Include file: ")))
8225 "\"")
8226 t t rpl)))
8227 (insert rpl)
8228 (if (re-search-backward "\\?" start t) (delete-char 1))))
8231 (defun org-complete (&optional arg)
8232 "Perform completion on word at point.
8233 At the beginning of a headline, this completes TODO keywords as given in
8234 `org-todo-keywords'.
8235 If the current word is preceded by a backslash, completes the TeX symbols
8236 that are supported for HTML support.
8237 If the current word is preceded by \"#+\", completes special words for
8238 setting file options.
8239 In the line after \"#+STARTUP:, complete valid keywords.\"
8240 At all other locations, this simply calls the value of
8241 `org-completion-fallback-command'."
8242 (interactive "P")
8243 (org-without-partial-completion
8244 (catch 'exit
8245 (let* ((a nil)
8246 (end (point))
8247 (beg1 (save-excursion
8248 (skip-chars-backward (org-re "[:alnum:]_@"))
8249 (point)))
8250 (beg (save-excursion
8251 (skip-chars-backward "a-zA-Z0-9_:$")
8252 (point)))
8253 (confirm (lambda (x) (stringp (car x))))
8254 (searchhead (equal (char-before beg) ?*))
8255 (struct
8256 (when (and (member (char-before beg1) '(?. ?<))
8257 (setq a (assoc (buffer-substring beg1 (point))
8258 org-structure-template-alist)))
8259 (org-complete-expand-structure-template (1- beg1) a)
8260 (throw 'exit t)))
8261 (tag (and (equal (char-before beg1) ?:)
8262 (equal (char-after (point-at-bol)) ?*)))
8263 (prop (and (equal (char-before beg1) ?:)
8264 (not (equal (char-after (point-at-bol)) ?*))))
8265 (texp (equal (char-before beg) ?\\))
8266 (link (equal (char-before beg) ?\[))
8267 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8268 beg)
8269 "#+"))
8270 (startup (string-match "^#\\+STARTUP:.*"
8271 (buffer-substring (point-at-bol) (point))))
8272 (completion-ignore-case opt)
8273 (type nil)
8274 (tbl nil)
8275 (table (cond
8276 (opt
8277 (setq type :opt)
8278 (require 'org-exp)
8279 (append
8280 (mapcar
8281 (lambda (x)
8282 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8283 (cons (match-string 2 x) (match-string 1 x)))
8284 (org-split-string (org-get-current-options) "\n"))
8285 (mapcar 'list org-additional-option-like-keywords)))
8286 (startup
8287 (setq type :startup)
8288 org-startup-options)
8289 (link (append org-link-abbrev-alist-local
8290 org-link-abbrev-alist))
8291 (texp
8292 (setq type :tex)
8293 org-html-entities)
8294 ((string-match "\\`\\*+[ \t]+\\'"
8295 (buffer-substring (point-at-bol) beg))
8296 (setq type :todo)
8297 (mapcar 'list org-todo-keywords-1))
8298 (searchhead
8299 (setq type :searchhead)
8300 (save-excursion
8301 (goto-char (point-min))
8302 (while (re-search-forward org-todo-line-regexp nil t)
8303 (push (list
8304 (org-make-org-heading-search-string
8305 (match-string 3) t))
8306 tbl)))
8307 tbl)
8308 (tag (setq type :tag beg beg1)
8309 (or org-tag-alist (org-get-buffer-tags)))
8310 (prop (setq type :prop beg beg1)
8311 (mapcar 'list (org-buffer-property-keys nil t t)))
8312 (t (progn
8313 (call-interactively org-completion-fallback-command)
8314 (throw 'exit nil)))))
8315 (pattern (buffer-substring-no-properties beg end))
8316 (completion (try-completion pattern table confirm)))
8317 (cond ((eq completion t)
8318 (if (not (assoc (upcase pattern) table))
8319 (message "Already complete")
8320 (if (and (equal type :opt)
8321 (not (member (car (assoc (upcase pattern) table))
8322 org-additional-option-like-keywords)))
8323 (insert (substring (cdr (assoc (upcase pattern) table))
8324 (length pattern)))
8325 (if (memq type '(:tag :prop)) (insert ":")))))
8326 ((null completion)
8327 (message "Can't find completion for \"%s\"" pattern)
8328 (ding))
8329 ((not (string= pattern completion))
8330 (delete-region beg end)
8331 (if (string-match " +$" completion)
8332 (setq completion (replace-match "" t t completion)))
8333 (insert completion)
8334 (if (get-buffer-window "*Completions*")
8335 (delete-window (get-buffer-window "*Completions*")))
8336 (if (assoc completion table)
8337 (if (eq type :todo) (insert " ")
8338 (if (memq type '(:tag :prop)) (insert ":"))))
8339 (if (and (equal type :opt) (assoc completion table))
8340 (message "%s" (substitute-command-keys
8341 "Press \\[org-complete] again to insert example settings"))))
8343 (message "Making completion list...")
8344 (let ((list (sort (all-completions pattern table confirm)
8345 'string<)))
8346 (with-output-to-temp-buffer "*Completions*"
8347 (condition-case nil
8348 ;; Protection needed for XEmacs and emacs 21
8349 (display-completion-list list pattern)
8350 (error (display-completion-list list)))))
8351 (message "Making completion list...%s" "done")))))))
8353 ;;;; TODO, DEADLINE, Comments
8355 (defun org-toggle-comment ()
8356 "Change the COMMENT state of an entry."
8357 (interactive)
8358 (save-excursion
8359 (org-back-to-heading)
8360 (let (case-fold-search)
8361 (if (looking-at (concat outline-regexp
8362 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8363 (replace-match "" t t nil 1)
8364 (if (looking-at outline-regexp)
8365 (progn
8366 (goto-char (match-end 0))
8367 (insert org-comment-string " ")))))))
8369 (defvar org-last-todo-state-is-todo nil
8370 "This is non-nil when the last TODO state change led to a TODO state.
8371 If the last change removed the TODO tag or switched to DONE, then
8372 this is nil.")
8374 (defvar org-setting-tags nil) ; dynamically skiped
8376 (defun org-parse-local-options (string var)
8377 "Parse STRING for startup setting relevant for variable VAR."
8378 (let ((rtn (symbol-value var))
8379 e opts)
8380 (save-match-data
8381 (if (or (not string) (not (string-match "\\S-" string)))
8383 (setq opts (delq nil (mapcar (lambda (x)
8384 (setq e (assoc x org-startup-options))
8385 (if (eq (nth 1 e) var) e nil))
8386 (org-split-string string "[ \t]+"))))
8387 (if (not opts)
8389 (setq rtn nil)
8390 (while (setq e (pop opts))
8391 (if (not (nth 3 e))
8392 (setq rtn (nth 2 e))
8393 (if (not (listp rtn)) (setq rtn nil))
8394 (push (nth 2 e) rtn)))
8395 rtn)))))
8397 (defvar org-blocker-hook nil
8398 "Hook for functions that are allowed to block a state change.
8400 Each function gets as its single argument a property list, see
8401 `org-trigger-hook' for more information about this list.
8403 If any of the functions in this hook returns nil, the state change
8404 is blocked.")
8406 (defvar org-trigger-hook nil
8407 "Hook for functions that are triggered by a state change.
8409 Each function gets as its single argument a property list with at least
8410 the following elements:
8412 (:type type-of-change :position pos-at-entry-start
8413 :from old-state :to new-state)
8415 Depending on the type, more properties may be present.
8417 This mechanism is currently implemented for:
8419 TODO state changes
8420 ------------------
8421 :type todo-state-change
8422 :from previous state (keyword as a string), or nil
8423 :to new state (keyword as a string), or nil")
8426 (defun org-todo (&optional arg)
8427 "Change the TODO state of an item.
8428 The state of an item is given by a keyword at the start of the heading,
8429 like
8430 *** TODO Write paper
8431 *** DONE Call mom
8433 The different keywords are specified in the variable `org-todo-keywords'.
8434 By default the available states are \"TODO\" and \"DONE\".
8435 So for this example: when the item starts with TODO, it is changed to DONE.
8436 When it starts with DONE, the DONE is removed. And when neither TODO nor
8437 DONE are present, add TODO at the beginning of the heading.
8439 With C-u prefix arg, use completion to determine the new state.
8440 With numeric prefix arg, switch to that state.
8442 For calling through lisp, arg is also interpreted in the following way:
8443 'none -> empty state
8444 \"\"(empty string) -> switch to empty state
8445 'done -> switch to DONE
8446 'nextset -> switch to the next set of keywords
8447 'previousset -> switch to the previous set of keywords
8448 \"WAITING\" -> switch to the specified keyword, but only if it
8449 really is a member of `org-todo-keywords'."
8450 (interactive "P")
8451 (save-excursion
8452 (catch 'exit
8453 (org-back-to-heading)
8454 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8455 (or (looking-at (concat " +" org-todo-regexp " *"))
8456 (looking-at " *"))
8457 (let* ((match-data (match-data))
8458 (startpos (point-at-bol))
8459 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8460 (org-log-done org-log-done)
8461 (org-log-repeat org-log-repeat)
8462 (org-todo-log-states org-todo-log-states)
8463 (this (match-string 1))
8464 (hl-pos (match-beginning 0))
8465 (head (org-get-todo-sequence-head this))
8466 (ass (assoc head org-todo-kwd-alist))
8467 (interpret (nth 1 ass))
8468 (done-word (nth 3 ass))
8469 (final-done-word (nth 4 ass))
8470 (last-state (or this ""))
8471 (completion-ignore-case t)
8472 (member (member this org-todo-keywords-1))
8473 (tail (cdr member))
8474 (state (cond
8475 ((and org-todo-key-trigger
8476 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8477 (and (not arg) org-use-fast-todo-selection
8478 (not (eq org-use-fast-todo-selection 'prefix)))))
8479 ;; Use fast selection
8480 (org-fast-todo-selection))
8481 ((and (equal arg '(4))
8482 (or (not org-use-fast-todo-selection)
8483 (not org-todo-key-trigger)))
8484 ;; Read a state with completion
8485 (completing-read "State: " (mapcar (lambda(x) (list x))
8486 org-todo-keywords-1)
8487 nil t))
8488 ((eq arg 'right)
8489 (if this
8490 (if tail (car tail) nil)
8491 (car org-todo-keywords-1)))
8492 ((eq arg 'left)
8493 (if (equal member org-todo-keywords-1)
8495 (if this
8496 (nth (- (length org-todo-keywords-1) (length tail) 2)
8497 org-todo-keywords-1)
8498 (org-last org-todo-keywords-1))))
8499 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8500 (setq arg nil))) ; hack to fall back to cycling
8501 (arg
8502 ;; user or caller requests a specific state
8503 (cond
8504 ((equal arg "") nil)
8505 ((eq arg 'none) nil)
8506 ((eq arg 'done) (or done-word (car org-done-keywords)))
8507 ((eq arg 'nextset)
8508 (or (car (cdr (member head org-todo-heads)))
8509 (car org-todo-heads)))
8510 ((eq arg 'previousset)
8511 (let ((org-todo-heads (reverse org-todo-heads)))
8512 (or (car (cdr (member head org-todo-heads)))
8513 (car org-todo-heads))))
8514 ((car (member arg org-todo-keywords-1)))
8515 ((nth (1- (prefix-numeric-value arg))
8516 org-todo-keywords-1))))
8517 ((null member) (or head (car org-todo-keywords-1)))
8518 ((equal this final-done-word) nil) ;; -> make empty
8519 ((null tail) nil) ;; -> first entry
8520 ((eq interpret 'sequence)
8521 (car tail))
8522 ((memq interpret '(type priority))
8523 (if (eq this-command last-command)
8524 (car tail)
8525 (if (> (length tail) 0)
8526 (or done-word (car org-done-keywords))
8527 nil)))
8528 (t nil)))
8529 (next (if state (concat " " state " ") " "))
8530 (change-plist (list :type 'todo-state-change :from this :to state
8531 :position startpos))
8532 dolog now-done-p)
8533 (when org-blocker-hook
8534 (unless (save-excursion
8535 (save-match-data
8536 (run-hook-with-args-until-failure
8537 'org-blocker-hook change-plist)))
8538 (if (interactive-p)
8539 (error "TODO state change from %s to %s blocked" this state)
8540 ;; fail silently
8541 (message "TODO state change from %s to %s blocked" this state)
8542 (throw 'exit nil))))
8543 (store-match-data match-data)
8544 (replace-match next t t)
8545 (unless (pos-visible-in-window-p hl-pos)
8546 (message "TODO state changed to %s" (org-trim next)))
8547 (unless head
8548 (setq head (org-get-todo-sequence-head state)
8549 ass (assoc head org-todo-kwd-alist)
8550 interpret (nth 1 ass)
8551 done-word (nth 3 ass)
8552 final-done-word (nth 4 ass)))
8553 (when (memq arg '(nextset previousset))
8554 (message "Keyword-Set %d/%d: %s"
8555 (- (length org-todo-sets) -1
8556 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8557 (length org-todo-sets)
8558 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8559 (setq org-last-todo-state-is-todo
8560 (not (member state org-done-keywords)))
8561 (setq now-done-p (and (member state org-done-keywords)
8562 (not (member this org-done-keywords))))
8563 (and logging (org-local-logging logging))
8564 (when (and (or org-todo-log-states org-log-done)
8565 (not (memq arg '(nextset previousset))))
8566 ;; we need to look at recording a time and note
8567 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8568 (nth 2 (assoc this org-todo-log-states))))
8569 (when (and state
8570 (member state org-not-done-keywords)
8571 (not (member this org-not-done-keywords)))
8572 ;; This is now a todo state and was not one before
8573 ;; If there was a CLOSED time stamp, get rid of it.
8574 (org-add-planning-info nil nil 'closed))
8575 (when (and now-done-p org-log-done)
8576 ;; It is now done, and it was not done before
8577 (org-add-planning-info 'closed (org-current-time))
8578 (if (and (not dolog) (eq 'note org-log-done))
8579 (org-add-log-setup 'done state 'findpos 'note)))
8580 (when (and state dolog)
8581 ;; This is a non-nil state, and we need to log it
8582 (org-add-log-setup 'state state 'findpos dolog)))
8583 ;; Fixup tag positioning
8584 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8585 (when org-provide-todo-statistics
8586 (org-update-parent-todo-statistics))
8587 (run-hooks 'org-after-todo-state-change-hook)
8588 (if (and arg (not (member state org-done-keywords)))
8589 (setq head (org-get-todo-sequence-head state)))
8590 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8591 ;; Do we need to trigger a repeat?
8592 (when now-done-p (org-auto-repeat-maybe state))
8593 ;; Fixup cursor location if close to the keyword
8594 (if (and (outline-on-heading-p)
8595 (not (bolp))
8596 (save-excursion (beginning-of-line 1)
8597 (looking-at org-todo-line-regexp))
8598 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8599 (progn
8600 (goto-char (or (match-end 2) (match-end 1)))
8601 (just-one-space)))
8602 (when org-trigger-hook
8603 (save-excursion
8604 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8606 (defun org-update-parent-todo-statistics ()
8607 "Update any statistics cookie in the parent of the current headline."
8608 (interactive)
8609 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8610 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8611 (catch 'exit
8612 (save-excursion
8613 (setq level (org-up-heading-safe))
8614 (unless (and level
8615 (re-search-forward box-re (point-at-eol) t))
8616 (throw 'exit nil))
8617 (setq is-percent (match-end 2))
8618 (save-match-data
8619 (unless (outline-next-heading) (throw 'exit nil))
8620 (while (looking-at org-todo-line-regexp)
8621 (setq kwd (match-string 2))
8622 (and kwd (setq cnt-all (1+ cnt-all)))
8623 (and (member kwd org-done-keywords)
8624 (setq cnt-done (1+ cnt-done)))
8625 (condition-case nil
8626 (outline-forward-same-level 1)
8627 (error (end-of-line 1)))))
8628 (replace-match
8629 (if is-percent
8630 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8631 (format "[%d/%d]" cnt-done cnt-all)))
8632 (run-hook-with-args 'org-after-todo-statistics-hook
8633 cnt-done (- cnt-all cnt-done))))))
8635 (defvar org-after-todo-statistics-hook nil
8636 "Hook that is called after a TODO statistics cookie has been updated.
8637 Each function is called with two arguments: the number of not-done entries
8638 and the number of done entries.
8640 For example, the following function, when added to this hook, will switch
8641 an entry to DONE when all children are done, and back to TODO when new
8642 entries are set to a TODO status. Note that this hook is only called
8643 when there is a statistics cookie in the headline!
8645 (defun org-summary-todo (n-done n-not-done)
8646 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8647 (let (org-log-done org-log-states) ; turn off logging
8648 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8651 (defun org-local-logging (value)
8652 "Get logging settings from a property VALUE."
8653 (let* (words w a)
8654 ;; directly set the variables, they are already local.
8655 (setq org-log-done nil
8656 org-log-repeat nil
8657 org-todo-log-states nil)
8658 (setq words (org-split-string value))
8659 (while (setq w (pop words))
8660 (cond
8661 ((setq a (assoc w org-startup-options))
8662 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8663 (set (nth 1 a) (nth 2 a))))
8664 ((setq a (org-extract-log-state-settings w))
8665 (and (member (car a) org-todo-keywords-1)
8666 (push a org-todo-log-states)))))))
8668 (defun org-get-todo-sequence-head (kwd)
8669 "Return the head of the TODO sequence to which KWD belongs.
8670 If KWD is not set, check if there is a text property remembering the
8671 right sequence."
8672 (let (p)
8673 (cond
8674 ((not kwd)
8675 (or (get-text-property (point-at-bol) 'org-todo-head)
8676 (progn
8677 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8678 nil (point-at-eol)))
8679 (get-text-property p 'org-todo-head))))
8680 ((not (member kwd org-todo-keywords-1))
8681 (car org-todo-keywords-1))
8682 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8684 (defun org-fast-todo-selection ()
8685 "Fast TODO keyword selection with single keys.
8686 Returns the new TODO keyword, or nil if no state change should occur."
8687 (let* ((fulltable org-todo-key-alist)
8688 (done-keywords org-done-keywords) ;; needed for the faces.
8689 (maxlen (apply 'max (mapcar
8690 (lambda (x)
8691 (if (stringp (car x)) (string-width (car x)) 0))
8692 fulltable)))
8693 (expert nil)
8694 (fwidth (+ maxlen 3 1 3))
8695 (ncol (/ (- (window-width) 4) fwidth))
8696 tg cnt e c tbl
8697 groups ingroup)
8698 (save-window-excursion
8699 (if expert
8700 (set-buffer (get-buffer-create " *Org todo*"))
8701 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8702 (erase-buffer)
8703 (org-set-local 'org-done-keywords done-keywords)
8704 (setq tbl fulltable cnt 0)
8705 (while (setq e (pop tbl))
8706 (cond
8707 ((equal e '(:startgroup))
8708 (push '() groups) (setq ingroup t)
8709 (when (not (= cnt 0))
8710 (setq cnt 0)
8711 (insert "\n"))
8712 (insert "{ "))
8713 ((equal e '(:endgroup))
8714 (setq ingroup nil cnt 0)
8715 (insert "}\n"))
8717 (setq tg (car e) c (cdr e))
8718 (if ingroup (push tg (car groups)))
8719 (setq tg (org-add-props tg nil 'face
8720 (org-get-todo-face tg)))
8721 (if (and (= cnt 0) (not ingroup)) (insert " "))
8722 (insert "[" c "] " tg (make-string
8723 (- fwidth 4 (length tg)) ?\ ))
8724 (when (= (setq cnt (1+ cnt)) ncol)
8725 (insert "\n")
8726 (if ingroup (insert " "))
8727 (setq cnt 0)))))
8728 (insert "\n")
8729 (goto-char (point-min))
8730 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8731 (fit-window-to-buffer))
8732 (message "[a-z..]:Set [SPC]:clear")
8733 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8734 (cond
8735 ((or (= c ?\C-g)
8736 (and (= c ?q) (not (rassoc c fulltable))))
8737 (setq quit-flag t))
8738 ((= c ?\ ) nil)
8739 ((setq e (rassoc c fulltable) tg (car e))
8741 (t (setq quit-flag t))))))
8743 (defun org-entry-is-todo-p ()
8744 (member (org-get-todo-state) org-not-done-keywords))
8746 (defun org-entry-is-done-p ()
8747 (member (org-get-todo-state) org-done-keywords))
8749 (defun org-get-todo-state ()
8750 (save-excursion
8751 (org-back-to-heading t)
8752 (and (looking-at org-todo-line-regexp)
8753 (match-end 2)
8754 (match-string 2))))
8756 (defun org-at-date-range-p (&optional inactive-ok)
8757 "Is the cursor inside a date range?"
8758 (interactive)
8759 (save-excursion
8760 (catch 'exit
8761 (let ((pos (point)))
8762 (skip-chars-backward "^[<\r\n")
8763 (skip-chars-backward "<[")
8764 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8765 (>= (match-end 0) pos)
8766 (throw 'exit t))
8767 (skip-chars-backward "^<[\r\n")
8768 (skip-chars-backward "<[")
8769 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8770 (>= (match-end 0) pos)
8771 (throw 'exit t)))
8772 nil)))
8774 (defun org-get-repeat ()
8775 "Check if there is a deadline/schedule with repeater in this entry."
8776 (save-match-data
8777 (save-excursion
8778 (org-back-to-heading t)
8779 (if (re-search-forward
8780 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8781 (match-string 1)))))
8783 (defvar org-last-changed-timestamp)
8784 (defvar org-last-inserted-timestamp)
8785 (defvar org-log-post-message)
8786 (defvar org-log-note-purpose)
8787 (defvar org-log-note-how)
8788 (defvar org-log-note-extra)
8789 (defun org-auto-repeat-maybe (done-word)
8790 "Check if the current headline contains a repeated deadline/schedule.
8791 If yes, set TODO state back to what it was and change the base date
8792 of repeating deadline/scheduled time stamps to new date.
8793 This function is run automatically after each state change to a DONE state."
8794 ;; last-state is dynamically scoped into this function
8795 (let* ((repeat (org-get-repeat))
8796 (aa (assoc last-state org-todo-kwd-alist))
8797 (interpret (nth 1 aa))
8798 (head (nth 2 aa))
8799 (whata '(("d" . day) ("m" . month) ("y" . year)))
8800 (msg "Entry repeats: ")
8801 (org-log-done nil)
8802 (org-todo-log-states nil)
8803 (nshiftmax 10) (nshift 0)
8804 re type n what ts mb0 time)
8805 (when repeat
8806 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8807 (org-todo (if (eq interpret 'type) last-state head))
8808 (when org-log-repeat
8809 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8810 (memq 'org-add-log-note post-command-hook))
8811 ;; OK, we are already setup for some record
8812 (if (eq org-log-repeat 'note)
8813 ;; make sure we take a note, not only a time stamp
8814 (setq org-log-note-how 'note))
8815 ;; Set up for taking a record
8816 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8817 'findpos org-log-repeat)))
8818 (org-back-to-heading t)
8819 (org-add-planning-info nil nil 'closed)
8820 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8821 org-deadline-time-regexp "\\)\\|\\("
8822 org-ts-regexp "\\)"))
8823 (while (re-search-forward
8824 re (save-excursion (outline-next-heading) (point)) t)
8825 (setq type (if (match-end 1) org-scheduled-string
8826 (if (match-end 3) org-deadline-string "Plain:"))
8827 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8828 mb0 (match-beginning 0))
8829 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8830 (setq n (string-to-number (match-string 2 ts))
8831 what (match-string 3 ts))
8832 (if (equal what "w") (setq n (* n 7) what "d"))
8833 ;; Preparation, see if we need to modify the start date for the change
8834 (when (match-end 1)
8835 (setq time (save-match-data (org-time-string-to-time ts)))
8836 (cond
8837 ((equal (match-string 1 ts) ".")
8838 ;; Shift starting date to today
8839 (org-timestamp-change
8840 (- (time-to-days (current-time)) (time-to-days time))
8841 'day))
8842 ((equal (match-string 1 ts) "+")
8843 (while (or (= nshift 0)
8844 (<= (time-to-days time) (time-to-days (current-time))))
8845 (when (= (incf nshift) nshiftmax)
8846 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8847 (error "Abort")))
8848 (org-timestamp-change n (cdr (assoc what whata)))
8849 (org-at-timestamp-p t)
8850 (setq ts (match-string 1))
8851 (setq time (save-match-data (org-time-string-to-time ts))))
8852 (org-timestamp-change (- n) (cdr (assoc what whata)))
8853 ;; rematch, so that we have everything in place for the real shift
8854 (org-at-timestamp-p t)
8855 (setq ts (match-string 1))
8856 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8857 (org-timestamp-change n (cdr (assoc what whata)))
8858 (setq msg (concat msg type org-last-changed-timestamp " "))))
8859 (setq org-log-post-message msg)
8860 (message "%s" msg))))
8862 (defun org-show-todo-tree (arg)
8863 "Make a compact tree which shows all headlines marked with TODO.
8864 The tree will show the lines where the regexp matches, and all higher
8865 headlines above the match.
8866 With a \\[universal-argument] prefix, also show the DONE entries.
8867 With a numeric prefix N, construct a sparse tree for the Nth element
8868 of `org-todo-keywords-1'."
8869 (interactive "P")
8870 (let ((case-fold-search nil)
8871 (kwd-re
8872 (cond ((null arg) org-not-done-regexp)
8873 ((equal arg '(4))
8874 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8875 (mapcar 'list org-todo-keywords-1))))
8876 (concat "\\("
8877 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8878 "\\)\\>")))
8879 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8880 (regexp-quote (nth (1- (prefix-numeric-value arg))
8881 org-todo-keywords-1)))
8882 (t (error "Invalid prefix argument: %s" arg)))))
8883 (message "%d TODO entries found"
8884 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8886 (defun org-deadline (&optional remove time)
8887 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8888 With argument REMOVE, remove any deadline from the item.
8889 When TIME is set, it should be an internal time specification, and the
8890 scheduling will use the corresponding date."
8891 (interactive "P")
8892 (if remove
8893 (progn
8894 (org-remove-timestamp-with-keyword org-deadline-string)
8895 (message "Item no longer has a deadline."))
8896 (if (org-get-repeat)
8897 (error "Cannot change deadline on task with repeater, please do that by hand")
8898 (org-add-planning-info 'deadline time 'closed)
8899 (message "Deadline on %s" org-last-inserted-timestamp))))
8901 (defun org-schedule (&optional remove time)
8902 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8903 With argument REMOVE, remove any scheduling date from the item.
8904 When TIME is set, it should be an internal time specification, and the
8905 scheduling will use the corresponding date."
8906 (interactive "P")
8907 (if remove
8908 (progn
8909 (org-remove-timestamp-with-keyword org-scheduled-string)
8910 (message "Item is no longer scheduled."))
8911 (if (org-get-repeat)
8912 (error "Cannot reschedule task with repeater, please do that by hand")
8913 (org-add-planning-info 'scheduled time 'closed)
8914 (message "Scheduled to %s" org-last-inserted-timestamp))))
8916 (defun org-remove-timestamp-with-keyword (keyword)
8917 "Remove all time stamps with KEYWORD in the current entry."
8918 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8919 beg)
8920 (save-excursion
8921 (org-back-to-heading t)
8922 (setq beg (point))
8923 (org-end-of-subtree t t)
8924 (while (re-search-backward re beg t)
8925 (replace-match "")
8926 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8927 (equal (char-before) ?\ ))
8928 (backward-delete-char 1)
8929 (if (string-match "^[ \t]*$" (buffer-substring
8930 (point-at-bol) (point-at-eol)))
8931 (delete-region (point-at-bol)
8932 (min (point-max) (1+ (point-at-eol))))))))))
8934 (defun org-add-planning-info (what &optional time &rest remove)
8935 "Insert new timestamp with keyword in the line directly after the headline.
8936 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8937 If non is given, the user is prompted for a date.
8938 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8939 be removed."
8940 (interactive)
8941 (let (org-time-was-given org-end-time-was-given ts
8942 end default-time default-input)
8944 (when (and (not time) (memq what '(scheduled deadline)))
8945 ;; Try to get a default date/time from existing timestamp
8946 (save-excursion
8947 (org-back-to-heading t)
8948 (setq end (save-excursion (outline-next-heading) (point)))
8949 (when (re-search-forward (if (eq what 'scheduled)
8950 org-scheduled-time-regexp
8951 org-deadline-time-regexp)
8952 end t)
8953 (setq ts (match-string 1)
8954 default-time
8955 (apply 'encode-time (org-parse-time-string ts))
8956 default-input (and ts (org-get-compact-tod ts))))))
8957 (when what
8958 ;; If necessary, get the time from the user
8959 (setq time (or time (org-read-date nil 'to-time nil nil
8960 default-time default-input))))
8962 (when (and org-insert-labeled-timestamps-at-point
8963 (member what '(scheduled deadline)))
8964 (insert
8965 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8966 (org-insert-time-stamp time org-time-was-given
8967 nil nil nil (list org-end-time-was-given))
8968 (setq what nil))
8969 (save-excursion
8970 (save-restriction
8971 (let (col list elt ts buffer-invisibility-spec)
8972 (org-back-to-heading t)
8973 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8974 (goto-char (match-end 1))
8975 (setq col (current-column))
8976 (goto-char (match-end 0))
8977 (if (eobp) (insert "\n") (forward-char 1))
8978 (if (and (not (looking-at outline-regexp))
8979 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8980 "[^\r\n]*"))
8981 (not (equal (match-string 1) org-clock-string)))
8982 (narrow-to-region (match-beginning 0) (match-end 0))
8983 (insert-before-markers "\n")
8984 (backward-char 1)
8985 (narrow-to-region (point) (point))
8986 (and org-adapt-indentation (org-indent-to-column col)))
8987 ;; Check if we have to remove something.
8988 (setq list (cons what remove))
8989 (while list
8990 (setq elt (pop list))
8991 (goto-char (point-min))
8992 (when (or (and (eq elt 'scheduled)
8993 (re-search-forward org-scheduled-time-regexp nil t))
8994 (and (eq elt 'deadline)
8995 (re-search-forward org-deadline-time-regexp nil t))
8996 (and (eq elt 'closed)
8997 (re-search-forward org-closed-time-regexp nil t)))
8998 (replace-match "")
8999 (if (looking-at "--+<[^>]+>") (replace-match ""))
9000 (if (looking-at " +") (replace-match ""))))
9001 (goto-char (point-max))
9002 (when what
9003 (insert
9004 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9005 (cond ((eq what 'scheduled) org-scheduled-string)
9006 ((eq what 'deadline) org-deadline-string)
9007 ((eq what 'closed) org-closed-string))
9008 " ")
9009 (setq ts (org-insert-time-stamp
9010 time
9011 (or org-time-was-given
9012 (and (eq what 'closed) org-log-done-with-time))
9013 (eq what 'closed)
9014 nil nil (list org-end-time-was-given)))
9015 (end-of-line 1))
9016 (goto-char (point-min))
9017 (widen)
9018 (if (and (looking-at "[ \t]+\n")
9019 (equal (char-before) ?\n))
9020 (delete-region (1- (point)) (point-at-eol)))
9021 ts)))))
9023 (defvar org-log-note-marker (make-marker))
9024 (defvar org-log-note-purpose nil)
9025 (defvar org-log-note-state nil)
9026 (defvar org-log-note-how nil)
9027 (defvar org-log-note-extra nil)
9028 (defvar org-log-note-window-configuration nil)
9029 (defvar org-log-note-return-to (make-marker))
9030 (defvar org-log-post-message nil
9031 "Message to be displayed after a log note has been stored.
9032 The auto-repeater uses this.")
9034 (defun org-add-note ()
9035 "Add a note to the current entry.
9036 This is done in the same way as adding a state change note."
9037 (interactive)
9038 (org-add-log-setup 'note nil t nil))
9040 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9041 "Set up the post command hook to take a note.
9042 If this is about to TODO state change, the new state is expected in STATE.
9043 When FINDPOS is non-nil, find the correct position for the note in
9044 the current entry. If not, assume that it can be inserted at point.
9045 HOW is an indicator what kind of note should be created.
9046 EXTRA is additional text that will be inserted into the notes buffer."
9047 (save-excursion
9048 (when findpos
9049 (org-back-to-heading t)
9050 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9051 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9052 "[^\r\n]*\\)?"))
9053 (goto-char (match-end 0))
9054 (unless org-log-states-order-reversed
9055 (and (= (char-after) ?\n) (forward-char 1))
9056 (org-skip-over-state-notes)
9057 (skip-chars-backward " \t\n\r")))
9058 (move-marker org-log-note-marker (point))
9059 (setq org-log-note-purpose purpose
9060 org-log-note-state state
9061 org-log-note-how how
9062 org-log-note-extra extra)
9063 (add-hook 'post-command-hook 'org-add-log-note 'append)))
9065 (defun org-skip-over-state-notes ()
9066 "Skip past the list of State notes in an entry."
9067 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9068 (while (looking-at "[ \t]*- State")
9069 (condition-case nil
9070 (org-next-item)
9071 (error (org-end-of-item)))))
9073 (defun org-add-log-note (&optional purpose)
9074 "Pop up a window for taking a note, and add this note later at point."
9075 (remove-hook 'post-command-hook 'org-add-log-note)
9076 (setq org-log-note-window-configuration (current-window-configuration))
9077 (delete-other-windows)
9078 (move-marker org-log-note-return-to (point))
9079 (switch-to-buffer (marker-buffer org-log-note-marker))
9080 (goto-char org-log-note-marker)
9081 (org-switch-to-buffer-other-window "*Org Note*")
9082 (erase-buffer)
9083 (if (memq org-log-note-how '(time state))
9084 (org-store-log-note)
9085 (let ((org-inhibit-startup t)) (org-mode))
9086 (insert (format "# Insert note for %s.
9087 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9088 (cond
9089 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9090 ((eq org-log-note-purpose 'done) "closed todo item")
9091 ((eq org-log-note-purpose 'state)
9092 (format "state change to \"%s\"" org-log-note-state))
9093 ((eq org-log-note-purpose 'note)
9094 "this entry")
9095 (t (error "This should not happen")))))
9096 (if org-log-note-extra (insert org-log-note-extra))
9097 (org-set-local 'org-finish-function 'org-store-log-note)))
9099 (defvar org-note-abort nil) ; dynamically scoped
9100 (defun org-store-log-note ()
9101 "Finish taking a log note, and insert it to where it belongs."
9102 (let ((txt (buffer-string))
9103 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9104 lines ind)
9105 (kill-buffer (current-buffer))
9106 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9107 (setq txt (replace-match "" t t txt)))
9108 (if (string-match "\\s-+\\'" txt)
9109 (setq txt (replace-match "" t t txt)))
9110 (setq lines (org-split-string txt "\n"))
9111 (when (and note (string-match "\\S-" note))
9112 (setq note
9113 (org-replace-escapes
9114 note
9115 (list (cons "%u" (user-login-name))
9116 (cons "%U" user-full-name)
9117 (cons "%t" (format-time-string
9118 (org-time-stamp-format 'long 'inactive)
9119 (current-time)))
9120 (cons "%s" (if org-log-note-state
9121 (concat "\"" org-log-note-state "\"")
9122 "")))))
9123 (if lines (setq note (concat note " \\\\")))
9124 (push note lines))
9125 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9126 (when lines
9127 (save-excursion
9128 (set-buffer (marker-buffer org-log-note-marker))
9129 (save-excursion
9130 (goto-char org-log-note-marker)
9131 (move-marker org-log-note-marker nil)
9132 (end-of-line 1)
9133 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9134 (indent-relative nil)
9135 (insert "- " (pop lines))
9136 (org-indent-line-function)
9137 (beginning-of-line 1)
9138 (looking-at "[ \t]*")
9139 (setq ind (concat (match-string 0) " "))
9140 (end-of-line 1)
9141 (while lines (insert "\n" ind (pop lines)))))))
9142 (set-window-configuration org-log-note-window-configuration)
9143 (with-current-buffer (marker-buffer org-log-note-return-to)
9144 (goto-char org-log-note-return-to))
9145 (move-marker org-log-note-return-to nil)
9146 (and org-log-post-message (message "%s" org-log-post-message)))
9148 (defun org-sparse-tree (&optional arg)
9149 "Create a sparse tree, prompt for the details.
9150 This command can create sparse trees. You first need to select the type
9151 of match used to create the tree:
9153 t Show entries with a specific TODO keyword.
9154 T Show entries selected by a tags match.
9155 p Enter a property name and its value (both with completion on existing
9156 names/values) and show entries with that property.
9157 r Show entries matching a regular expression
9158 d Show deadlines due within `org-deadline-warning-days'."
9159 (interactive "P")
9160 (let (ans kwd value)
9161 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9162 (setq ans (read-char-exclusive))
9163 (cond
9164 ((equal ans ?d)
9165 (call-interactively 'org-check-deadlines))
9166 ((equal ans ?b)
9167 (call-interactively 'org-check-before-date))
9168 ((equal ans ?t)
9169 (org-show-todo-tree '(4)))
9170 ((equal ans ?T)
9171 (call-interactively 'org-tags-sparse-tree))
9172 ((member ans '(?p ?P))
9173 (setq kwd (completing-read "Property: "
9174 (mapcar 'list (org-buffer-property-keys))))
9175 (setq value (completing-read "Value: "
9176 (mapcar 'list (org-property-values kwd))))
9177 (unless (string-match "\\`{.*}\\'" value)
9178 (setq value (concat "\"" value "\"")))
9179 (org-tags-sparse-tree arg (concat kwd "=" value)))
9180 ((member ans '(?r ?R ?/))
9181 (call-interactively 'org-occur))
9182 (t (error "No such sparse tree command \"%c\"" ans)))))
9184 (defvar org-occur-highlights nil
9185 "List of overlays used for occur matches.")
9186 (make-variable-buffer-local 'org-occur-highlights)
9187 (defvar org-occur-parameters nil
9188 "Parameters of the active org-occur calls.
9189 This is a list, each call to org-occur pushes as cons cell,
9190 containing the regular expression and the callback, onto the list.
9191 The list can contain several entries if `org-occur' has been called
9192 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9193 will only contain one set of parameters. When the highlights are
9194 removed (for example with `C-c C-c', or with the next edit (depending
9195 on `org-remove-highlights-with-change'), this variable is emptied
9196 as well.")
9197 (make-variable-buffer-local 'org-occur-parameters)
9199 (defun org-occur (regexp &optional keep-previous callback)
9200 "Make a compact tree which shows all matches of REGEXP.
9201 The tree will show the lines where the regexp matches, and all higher
9202 headlines above the match. It will also show the heading after the match,
9203 to make sure editing the matching entry is easy.
9204 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9205 call to `org-occur' will be kept, to allow stacking of calls to this
9206 command.
9207 If CALLBACK is non-nil, it is a function which is called to confirm
9208 that the match should indeed be shown."
9209 (interactive "sRegexp: \nP")
9210 (unless keep-previous
9211 (org-remove-occur-highlights nil nil t))
9212 (push (cons regexp callback) org-occur-parameters)
9213 (let ((cnt 0))
9214 (save-excursion
9215 (goto-char (point-min))
9216 (if (or (not keep-previous) ; do not want to keep
9217 (not org-occur-highlights)) ; no previous matches
9218 ;; hide everything
9219 (org-overview))
9220 (while (re-search-forward regexp nil t)
9221 (when (or (not callback)
9222 (save-match-data (funcall callback)))
9223 (setq cnt (1+ cnt))
9224 (when org-highlight-sparse-tree-matches
9225 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9226 (org-show-context 'occur-tree))))
9227 (when org-remove-highlights-with-change
9228 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9229 nil 'local))
9230 (unless org-sparse-tree-open-archived-trees
9231 (org-hide-archived-subtrees (point-min) (point-max)))
9232 (run-hooks 'org-occur-hook)
9233 (if (interactive-p)
9234 (message "%d match(es) for regexp %s" cnt regexp))
9235 cnt))
9237 (defun org-show-context (&optional key)
9238 "Make sure point and context and visible.
9239 How much context is shown depends upon the variables
9240 `org-show-hierarchy-above', `org-show-following-heading'. and
9241 `org-show-siblings'."
9242 (let ((heading-p (org-on-heading-p t))
9243 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9244 (following-p (org-get-alist-option org-show-following-heading key))
9245 (entry-p (org-get-alist-option org-show-entry-below key))
9246 (siblings-p (org-get-alist-option org-show-siblings key)))
9247 (catch 'exit
9248 ;; Show heading or entry text
9249 (if (and heading-p (not entry-p))
9250 (org-flag-heading nil) ; only show the heading
9251 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9252 (org-show-hidden-entry))) ; show entire entry
9253 (when following-p
9254 ;; Show next sibling, or heading below text
9255 (save-excursion
9256 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9257 (org-flag-heading nil))))
9258 (when siblings-p (org-show-siblings))
9259 (when hierarchy-p
9260 ;; show all higher headings, possibly with siblings
9261 (save-excursion
9262 (while (and (condition-case nil
9263 (progn (org-up-heading-all 1) t)
9264 (error nil))
9265 (not (bobp)))
9266 (org-flag-heading nil)
9267 (when siblings-p (org-show-siblings))))))))
9269 (defun org-reveal (&optional siblings)
9270 "Show current entry, hierarchy above it, and the following headline.
9271 This can be used to show a consistent set of context around locations
9272 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9273 not t for the search context.
9275 With optional argument SIBLINGS, on each level of the hierarchy all
9276 siblings are shown. This repairs the tree structure to what it would
9277 look like when opened with hierarchical calls to `org-cycle'."
9278 (interactive "P")
9279 (let ((org-show-hierarchy-above t)
9280 (org-show-following-heading t)
9281 (org-show-siblings (if siblings t org-show-siblings)))
9282 (org-show-context nil)))
9284 (defun org-highlight-new-match (beg end)
9285 "Highlight from BEG to END and mark the highlight is an occur headline."
9286 (let ((ov (org-make-overlay beg end)))
9287 (org-overlay-put ov 'face 'secondary-selection)
9288 (push ov org-occur-highlights)))
9290 (defun org-remove-occur-highlights (&optional beg end noremove)
9291 "Remove the occur highlights from the buffer.
9292 BEG and END are ignored. If NOREMOVE is nil, remove this function
9293 from the `before-change-functions' in the current buffer."
9294 (interactive)
9295 (unless org-inhibit-highlight-removal
9296 (mapc 'org-delete-overlay org-occur-highlights)
9297 (setq org-occur-highlights nil)
9298 (setq org-occur-parameters nil)
9299 (unless noremove
9300 (remove-hook 'before-change-functions
9301 'org-remove-occur-highlights 'local))))
9303 ;;;; Priorities
9305 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9306 "Regular expression matching the priority indicator.")
9308 (defvar org-remove-priority-next-time nil)
9310 (defun org-priority-up ()
9311 "Increase the priority of the current item."
9312 (interactive)
9313 (org-priority 'up))
9315 (defun org-priority-down ()
9316 "Decrease the priority of the current item."
9317 (interactive)
9318 (org-priority 'down))
9320 (defun org-priority (&optional action)
9321 "Change the priority of an item by ARG.
9322 ACTION can be `set', `up', `down', or a character."
9323 (interactive)
9324 (setq action (or action 'set))
9325 (let (current new news have remove)
9326 (save-excursion
9327 (org-back-to-heading)
9328 (if (looking-at org-priority-regexp)
9329 (setq current (string-to-char (match-string 2))
9330 have t)
9331 (setq current org-default-priority))
9332 (cond
9333 ((or (eq action 'set)
9334 (if (featurep 'xemacs) (characterp action) (integerp action)))
9335 (if (not (eq action 'set))
9336 (setq new action)
9337 (message "Priority %c-%c, SPC to remove: "
9338 org-highest-priority org-lowest-priority)
9339 (setq new (read-char-exclusive)))
9340 (if (and (= (upcase org-highest-priority) org-highest-priority)
9341 (= (upcase org-lowest-priority) org-lowest-priority))
9342 (setq new (upcase new)))
9343 (cond ((equal new ?\ ) (setq remove t))
9344 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9345 (error "Priority must be between `%c' and `%c'"
9346 org-highest-priority org-lowest-priority))))
9347 ((eq action 'up)
9348 (if (and (not have) (eq last-command this-command))
9349 (setq new org-lowest-priority)
9350 (setq new (if (and org-priority-start-cycle-with-default (not have))
9351 org-default-priority (1- current)))))
9352 ((eq action 'down)
9353 (if (and (not have) (eq last-command this-command))
9354 (setq new org-highest-priority)
9355 (setq new (if (and org-priority-start-cycle-with-default (not have))
9356 org-default-priority (1+ current)))))
9357 (t (error "Invalid action")))
9358 (if (or (< (upcase new) org-highest-priority)
9359 (> (upcase new) org-lowest-priority))
9360 (setq remove t))
9361 (setq news (format "%c" new))
9362 (if have
9363 (if remove
9364 (replace-match "" t t nil 1)
9365 (replace-match news t t nil 2))
9366 (if remove
9367 (error "No priority cookie found in line")
9368 (looking-at org-todo-line-regexp)
9369 (if (match-end 2)
9370 (progn
9371 (goto-char (match-end 2))
9372 (insert " [#" news "]"))
9373 (goto-char (match-beginning 3))
9374 (insert "[#" news "] ")))))
9375 (org-preserve-lc (org-set-tags nil 'align))
9376 (if remove
9377 (message "Priority removed")
9378 (message "Priority of current item set to %s" news))))
9381 (defun org-get-priority (s)
9382 "Find priority cookie and return priority."
9383 (save-match-data
9384 (if (not (string-match org-priority-regexp s))
9385 (* 1000 (- org-lowest-priority org-default-priority))
9386 (* 1000 (- org-lowest-priority
9387 (string-to-char (match-string 2 s)))))))
9389 ;;;; Tags
9391 (defvar org-agenda-archives-mode)
9392 (defun org-scan-tags (action matcher &optional todo-only)
9393 "Scan headline tags with inheritance and produce output ACTION.
9395 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9396 or `agenda' to produce an entry list for an agenda view. It can also be
9397 a Lisp form or a function that should be called at each matched headline, in
9398 this case the return value is a list of all return values from these calls.
9400 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9401 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9402 only lines with a TODO keyword are included in the output."
9403 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9404 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9405 (org-re
9406 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9407 (props (list 'face 'default
9408 'done-face 'org-done
9409 'undone-face 'default
9410 'mouse-face 'highlight
9411 'org-not-done-regexp org-not-done-regexp
9412 'org-todo-regexp org-todo-regexp
9413 'keymap org-agenda-keymap
9414 'help-echo
9415 (format "mouse-2 or RET jump to org file %s"
9416 (abbreviate-file-name
9417 (or (buffer-file-name (buffer-base-buffer))
9418 (buffer-name (buffer-base-buffer)))))))
9419 (case-fold-search nil)
9420 lspos tags tags-list
9421 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9422 (llast 0) rtn rtn1 level category i txt
9423 todo marker entry priority)
9424 (when (not (member action '(agenda sparse-tree)))
9425 (setq action (list 'lambda nil action)))
9426 (save-excursion
9427 (goto-char (point-min))
9428 (when (eq action 'sparse-tree)
9429 (org-overview)
9430 (org-remove-occur-highlights))
9431 (while (re-search-forward re nil t)
9432 (catch :skip
9433 (setq todo (if (match-end 1) (match-string 2))
9434 tags (if (match-end 4) (match-string 4)))
9435 (goto-char (setq lspos (1+ (match-beginning 0))))
9436 (setq level (org-reduced-level (funcall outline-level))
9437 category (org-get-category))
9438 (setq i llast llast level)
9439 ;; remove tag lists from same and sublevels
9440 (while (>= i level)
9441 (when (setq entry (assoc i tags-alist))
9442 (setq tags-alist (delete entry tags-alist)))
9443 (setq i (1- i)))
9444 ;; add the next tags
9445 (when tags
9446 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9447 tags-alist
9448 (cons (cons level tags) tags-alist)))
9449 ;; compile tags for current headline
9450 (setq tags-list
9451 (if org-use-tag-inheritance
9452 (apply 'append (mapcar 'cdr tags-alist))
9453 tags))
9454 (when (and tags org-use-tag-inheritance
9455 (not (eq t org-use-tag-inheritance)))
9456 ;; selective inheritance, remove uninherited ones
9457 (setcdr (car tags-alist)
9458 (org-remove-uniherited-tags (cdar tags-alist))))
9459 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9460 (let ((case-fold-search t)) (eval matcher))
9462 (not (member org-archive-tag tags-list))
9463 ;; we have an archive tag, should we use this anyway?
9464 (or (not org-agenda-skip-archived-trees)
9465 (and (eq action 'agenda) org-agenda-archives-mode))))
9466 (unless (eq action 'sparse-tree) (org-agenda-skip))
9468 ;; select this headline
9470 (cond
9471 ((eq action 'sparse-tree)
9472 (and org-highlight-sparse-tree-matches
9473 (org-get-heading) (match-end 0)
9474 (org-highlight-new-match
9475 (match-beginning 0) (match-beginning 1)))
9476 (org-show-context 'tags-tree))
9477 ((eq action 'agenda)
9478 (setq txt (org-format-agenda-item
9480 (concat
9481 (if org-tags-match-list-sublevels
9482 (make-string (1- level) ?.) "")
9483 (org-get-heading))
9484 category tags-list)
9485 priority (org-get-priority txt))
9486 (goto-char lspos)
9487 (setq marker (org-agenda-new-marker))
9488 (org-add-props txt props
9489 'org-marker marker 'org-hd-marker marker 'org-category category
9490 'priority priority 'type "tagsmatch")
9491 (push txt rtn))
9492 ((functionp action)
9493 (save-excursion
9494 (setq rtn1 (funcall action))
9495 (push rtn1 rtn))
9496 (goto-char (point-at-eol)))
9497 (t (error "Invalid action")))
9499 ;; if we are to skip sublevels, jump to end of subtree
9500 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9501 (when (and (eq action 'sparse-tree)
9502 (not org-sparse-tree-open-archived-trees))
9503 (org-hide-archived-subtrees (point-min) (point-max)))
9504 (nreverse rtn)))
9506 (defun org-remove-uniherited-tags (tags)
9507 "Remove all tags that are not inherited from the list TAGS."
9508 (cond
9509 ((eq org-use-tag-inheritance t) tags)
9510 ((not org-use-tag-inheritance) nil)
9511 ((stringp org-use-tag-inheritance)
9512 (delq nil (mapcar
9513 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9514 tags)))
9515 ((listp org-use-tag-inheritance)
9516 (org-delete-all org-use-tag-inheritance tags))))
9518 (defvar todo-only) ;; dynamically scoped
9520 (defun org-tags-sparse-tree (&optional todo-only match)
9521 "Create a sparse tree according to tags string MATCH.
9522 MATCH can contain positive and negative selection of tags, like
9523 \"+WORK+URGENT-WITHBOSS\".
9524 If optional argument TODO_ONLY is non-nil, only select lines that are
9525 also TODO lines."
9526 (interactive "P")
9527 (org-prepare-agenda-buffers (list (current-buffer)))
9528 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9530 (defvar org-cached-props nil)
9531 (defun org-cached-entry-get (pom property)
9532 (if (or (eq t org-use-property-inheritance)
9533 (and (stringp org-use-property-inheritance)
9534 (string-match org-use-property-inheritance property))
9535 (and (listp org-use-property-inheritance)
9536 (member property org-use-property-inheritance)))
9537 ;; Caching is not possible, check it directly
9538 (org-entry-get pom property 'inherit)
9539 ;; Get all properties, so that we can do complicated checks easily
9540 (cdr (assoc property (or org-cached-props
9541 (setq org-cached-props
9542 (org-entry-properties pom)))))))
9544 (defun org-global-tags-completion-table (&optional files)
9545 "Return the list of all tags in all agenda buffer/files."
9546 (save-excursion
9547 (org-uniquify
9548 (delq nil
9549 (apply 'append
9550 (mapcar
9551 (lambda (file)
9552 (set-buffer (find-file-noselect file))
9553 (append (org-get-buffer-tags)
9554 (mapcar (lambda (x) (if (stringp (car-safe x))
9555 (list (car-safe x)) nil))
9556 org-tag-alist)))
9557 (if (and files (car files))
9558 files
9559 (org-agenda-files))))))))
9561 (defun org-make-tags-matcher (match)
9562 "Create the TAGS//TODO matcher form for the selection string MATCH."
9563 ;; todo-only is scoped dynamically into this function, and the function
9564 ;; may change it it the matcher asksk for it.
9565 (unless match
9566 ;; Get a new match request, with completion
9567 (let ((org-last-tags-completion-table
9568 (org-global-tags-completion-table)))
9569 (setq match (completing-read
9570 "Match: " 'org-tags-completion-function nil nil nil
9571 'org-tags-history))))
9573 ;; Parse the string and create a lisp form
9574 (let ((match0 match)
9575 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9576 minus tag mm
9577 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9578 orterms term orlist re-p str-p level-p level-op time-p
9579 prop-p pn pv po cat-p gv)
9580 (if (string-match "/+" match)
9581 ;; match contains also a todo-matching request
9582 (progn
9583 (setq tagsmatch (substring match 0 (match-beginning 0))
9584 todomatch (substring match (match-end 0)))
9585 (if (string-match "^!" todomatch)
9586 (setq todo-only t todomatch (substring todomatch 1)))
9587 (if (string-match "^\\s-*$" todomatch)
9588 (setq todomatch nil)))
9589 ;; only matching tags
9590 (setq tagsmatch match todomatch nil))
9592 ;; Make the tags matcher
9593 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9594 (setq tagsmatcher t)
9595 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9596 (while (setq term (pop orterms))
9597 (while (and (equal (substring term -1) "\\") orterms)
9598 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9599 (while (string-match re term)
9600 (setq minus (and (match-end 1)
9601 (equal (match-string 1 term) "-"))
9602 tag (match-string 2 term)
9603 re-p (equal (string-to-char tag) ?{)
9604 level-p (match-end 4)
9605 prop-p (match-end 5)
9606 mm (cond
9607 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9608 (level-p
9609 (setq level-op (org-op-to-function (match-string 3 term)))
9610 `(,level-op level ,(string-to-number
9611 (match-string 4 term))))
9612 (prop-p
9613 (setq pn (match-string 5 term)
9614 po (match-string 6 term)
9615 pv (match-string 7 term)
9616 cat-p (equal pn "CATEGORY")
9617 re-p (equal (string-to-char pv) ?{)
9618 str-p (equal (string-to-char pv) ?\")
9619 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9620 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9621 (if time-p (setq pv (org-matcher-time pv)))
9622 (setq po (org-op-to-function po (if time-p 'time str-p)))
9623 (if (equal pn "CATEGORY")
9624 (setq gv '(get-text-property (point) 'org-category))
9625 (setq gv `(org-cached-entry-get nil ,pn)))
9626 (if re-p
9627 (if (eq po 'org<>)
9628 `(not (string-match ,pv (or ,gv "")))
9629 `(string-match ,pv (or ,gv "")))
9630 (if str-p
9631 `(,po (or ,gv "") ,pv)
9632 `(,po (string-to-number (or ,gv ""))
9633 ,(string-to-number pv) ))))
9634 (t `(member ,(downcase tag) tags-list)))
9635 mm (if minus (list 'not mm) mm)
9636 term (substring term (match-end 0)))
9637 (push mm tagsmatcher))
9638 (push (if (> (length tagsmatcher) 1)
9639 (cons 'and tagsmatcher)
9640 (car tagsmatcher))
9641 orlist)
9642 (setq tagsmatcher nil))
9643 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9644 (setq tagsmatcher
9645 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9646 ;; Make the todo matcher
9647 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9648 (setq todomatcher t)
9649 (setq orterms (org-split-string todomatch "|") orlist nil)
9650 (while (setq term (pop orterms))
9651 (while (string-match re term)
9652 (setq minus (and (match-end 1)
9653 (equal (match-string 1 term) "-"))
9654 kwd (match-string 2 term)
9655 re-p (equal (string-to-char kwd) ?{)
9656 term (substring term (match-end 0))
9657 mm (if re-p
9658 `(string-match ,(substring kwd 1 -1) todo)
9659 (list 'equal 'todo kwd))
9660 mm (if minus (list 'not mm) mm))
9661 (push mm todomatcher))
9662 (push (if (> (length todomatcher) 1)
9663 (cons 'and todomatcher)
9664 (car todomatcher))
9665 orlist)
9666 (setq todomatcher nil))
9667 (setq todomatcher (if (> (length orlist) 1)
9668 (cons 'or orlist) (car orlist))))
9670 ;; Return the string and lisp forms of the matcher
9671 (setq matcher (if todomatcher
9672 (list 'and tagsmatcher todomatcher)
9673 tagsmatcher))
9674 (cons match0 matcher)))
9676 (defun org-op-to-function (op &optional stringp)
9677 "Turn an operator into the appropriate function."
9678 (setq op
9679 (cond
9680 ((equal op "<" ) '(< string< org-time<))
9681 ((equal op ">" ) '(> org-string> org-time>))
9682 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9683 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9684 ((member op '("=" "==")) '(= string= org-time=))
9685 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9686 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9688 (defun org<> (a b) (not (= a b)))
9689 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9690 (defun org-string>= (a b) (not (string< a b)))
9691 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9692 (defun org-string<> (a b) (not (string= a b)))
9693 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9694 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9695 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9696 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9697 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9698 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9699 (defun org-2ft (s)
9700 "Convert S to a floating point time.
9701 If S is already a number, just return it. If it is a string, parse
9702 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9703 (cond
9704 ((numberp s) s)
9705 ((stringp s)
9706 (condition-case nil
9707 (float-time (apply 'encode-time (org-parse-time-string s)))
9708 (error 0.)))
9709 (t 0.)))
9711 (defun org-matcher-time (s)
9712 (cond
9713 ((equal s "<now>") (float-time))
9714 ((equal s "<today>")
9715 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9716 (t (org-2ft s))))
9718 (defun org-match-any-p (re list)
9719 "Does re match any element of list?"
9720 (setq list (mapcar (lambda (x) (string-match re x)) list))
9721 (delq nil list))
9723 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9724 (defvar org-tags-overlay (org-make-overlay 1 1))
9725 (org-detach-overlay org-tags-overlay)
9727 (defun org-get-local-tags-at (&optional pos)
9728 "Get a list of tags defined in the current headline."
9729 (org-get-tags-at pos 'local))
9731 (defun org-get-local-tags ()
9732 "Get a list of tags defined in the current headline."
9733 (org-get-tags-at nil 'local))
9735 (defun org-get-tags-at (&optional pos local)
9736 "Get a list of all headline tags applicable at POS.
9737 POS defaults to point. If tags are inherited, the list contains
9738 the targets in the same sequence as the headlines appear, i.e.
9739 the tags of the current headline come last.
9740 When LOCAL is non-nil, only return tags from the current headline,
9741 ignore inherited ones."
9742 (interactive)
9743 (let (tags ltags lastpos parent)
9744 (save-excursion
9745 (save-restriction
9746 (widen)
9747 (goto-char (or pos (point)))
9748 (save-match-data
9749 (catch 'done
9750 (condition-case nil
9751 (progn
9752 (org-back-to-heading t)
9753 (while (not (equal lastpos (point)))
9754 (setq lastpos (point))
9755 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9756 (setq ltags (org-split-string
9757 (org-match-string-no-properties 1) ":"))
9758 (setq tags (append
9759 (if parent
9760 (org-remove-uniherited-tags ltags)
9761 ltags)
9762 tags)))
9763 (or org-use-tag-inheritance (throw 'done t))
9764 (if local (throw 'done t))
9765 (org-up-heading-all 1)
9766 (setq parent t)))
9767 (error nil)))))
9768 (append (org-remove-uniherited-tags org-file-tags) tags))))
9770 (defun org-toggle-tag (tag &optional onoff)
9771 "Toggle the tag TAG for the current line.
9772 If ONOFF is `on' or `off', don't toggle but set to this state."
9773 (unless (org-on-heading-p t) (error "Not on headling"))
9774 (let (res current)
9775 (save-excursion
9776 (beginning-of-line)
9777 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9778 (point-at-eol) t)
9779 (progn
9780 (setq current (match-string 1))
9781 (replace-match ""))
9782 (setq current ""))
9783 (setq current (nreverse (org-split-string current ":")))
9784 (cond
9785 ((eq onoff 'on)
9786 (setq res t)
9787 (or (member tag current) (push tag current)))
9788 ((eq onoff 'off)
9789 (or (not (member tag current)) (setq current (delete tag current))))
9790 (t (if (member tag current)
9791 (setq current (delete tag current))
9792 (setq res t)
9793 (push tag current))))
9794 (end-of-line 1)
9795 (if current
9796 (progn
9797 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9798 (org-set-tags nil t))
9799 (delete-horizontal-space))
9800 (run-hooks 'org-after-tags-change-hook))
9801 res))
9803 (defun org-align-tags-here (to-col)
9804 ;; Assumes that this is a headline
9805 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9806 (beginning-of-line 1)
9807 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9808 (< pos (match-beginning 2)))
9809 (progn
9810 (setq tags-l (- (match-end 2) (match-beginning 2)))
9811 (goto-char (match-beginning 1))
9812 (insert " ")
9813 (delete-region (point) (1+ (match-beginning 2)))
9814 (setq ncol (max (1+ (current-column))
9815 (1+ col)
9816 (if (> to-col 0)
9817 to-col
9818 (- (abs to-col) tags-l))))
9819 (setq p (point))
9820 (insert (make-string (- ncol (current-column)) ?\ ))
9821 (setq ncol (current-column))
9822 (when indent-tabs-mode (tabify p (point-at-eol)))
9823 (org-move-to-column (min ncol col) t))
9824 (goto-char pos))))
9826 (defun org-set-tags (&optional arg just-align)
9827 "Set the tags for the current headline.
9828 With prefix ARG, realign all tags in headings in the current buffer."
9829 (interactive "P")
9830 (let* ((re (concat "^" outline-regexp))
9831 (current (org-get-tags-string))
9832 (col (current-column))
9833 (org-setting-tags t)
9834 table current-tags inherited-tags ; computed below when needed
9835 tags p0 c0 c1 rpl)
9836 (if arg
9837 (save-excursion
9838 (goto-char (point-min))
9839 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9840 (while (re-search-forward re nil t)
9841 (org-set-tags nil t)
9842 (end-of-line 1)))
9843 (message "All tags realigned to column %d" org-tags-column))
9844 (if just-align
9845 (setq tags current)
9846 ;; Get a new set of tags from the user
9847 (save-excursion
9848 (setq table (or org-tag-alist (org-get-buffer-tags))
9849 org-last-tags-completion-table table
9850 current-tags (org-split-string current ":")
9851 inherited-tags (nreverse
9852 (nthcdr (length current-tags)
9853 (nreverse (org-get-tags-at))))
9854 tags
9855 (if (or (eq t org-use-fast-tag-selection)
9856 (and org-use-fast-tag-selection
9857 (delq nil (mapcar 'cdr table))))
9858 (org-fast-tag-selection
9859 current-tags inherited-tags table
9860 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9861 (let ((org-add-colon-after-tag-completion t))
9862 (org-trim
9863 (org-without-partial-completion
9864 (completing-read "Tags: " 'org-tags-completion-function
9865 nil nil current 'org-tags-history)))))))
9866 (while (string-match "[-+&]+" tags)
9867 ;; No boolean logic, just a list
9868 (setq tags (replace-match ":" t t tags))))
9870 (if (string-match "\\`[\t ]*\\'" tags)
9871 (setq tags "")
9872 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9873 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9875 ;; Insert new tags at the correct column
9876 (beginning-of-line 1)
9877 (cond
9878 ((and (equal current "") (equal tags "")))
9879 ((re-search-forward
9880 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9881 (point-at-eol) t)
9882 (if (equal tags "")
9883 (setq rpl "")
9884 (goto-char (match-beginning 0))
9885 (setq c0 (current-column) p0 (point)
9886 c1 (max (1+ c0) (if (> org-tags-column 0)
9887 org-tags-column
9888 (- (- org-tags-column) (length tags))))
9889 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9890 (replace-match rpl t t)
9891 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9892 tags)
9893 (t (error "Tags alignment failed")))
9894 (org-move-to-column col)
9895 (unless just-align
9896 (run-hooks 'org-after-tags-change-hook)))))
9898 (defun org-change-tag-in-region (beg end tag off)
9899 "Add or remove TAG for each entry in the region.
9900 This works in the agenda, and also in an org-mode buffer."
9901 (interactive
9902 (list (region-beginning) (region-end)
9903 (let ((org-last-tags-completion-table
9904 (if (org-mode-p)
9905 (org-get-buffer-tags)
9906 (org-global-tags-completion-table))))
9907 (completing-read
9908 "Tag: " 'org-tags-completion-function nil nil nil
9909 'org-tags-history))
9910 (progn
9911 (message "[s]et or [r]emove? ")
9912 (equal (read-char-exclusive) ?r))))
9913 (if (fboundp 'deactivate-mark) (deactivate-mark))
9914 (let ((agendap (equal major-mode 'org-agenda-mode))
9915 l1 l2 m buf pos newhead (cnt 0))
9916 (goto-char end)
9917 (setq l2 (1- (org-current-line)))
9918 (goto-char beg)
9919 (setq l1 (org-current-line))
9920 (loop for l from l1 to l2 do
9921 (goto-line l)
9922 (setq m (get-text-property (point) 'org-hd-marker))
9923 (when (or (and (org-mode-p) (org-on-heading-p))
9924 (and agendap m))
9925 (setq buf (if agendap (marker-buffer m) (current-buffer))
9926 pos (if agendap m (point)))
9927 (with-current-buffer buf
9928 (save-excursion
9929 (save-restriction
9930 (goto-char pos)
9931 (setq cnt (1+ cnt))
9932 (org-toggle-tag tag (if off 'off 'on))
9933 (setq newhead (org-get-heading)))))
9934 (and agendap (org-agenda-change-all-lines newhead m))))
9935 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9937 (defun org-tags-completion-function (string predicate &optional flag)
9938 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9939 (confirm (lambda (x) (stringp (car x)))))
9940 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9941 (setq s1 (match-string 1 string)
9942 s2 (match-string 2 string))
9943 (setq s1 "" s2 string))
9944 (cond
9945 ((eq flag nil)
9946 ;; try completion
9947 (setq rtn (try-completion s2 ctable confirm))
9948 (if (stringp rtn)
9949 (setq rtn
9950 (concat s1 s2 (substring rtn (length s2))
9951 (if (and org-add-colon-after-tag-completion
9952 (assoc rtn ctable))
9953 ":" ""))))
9954 rtn)
9955 ((eq flag t)
9956 ;; all-completions
9957 (all-completions s2 ctable confirm)
9959 ((eq flag 'lambda)
9960 ;; exact match?
9961 (assoc s2 ctable)))
9964 (defun org-fast-tag-insert (kwd tags face &optional end)
9965 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9966 (insert (format "%-12s" (concat kwd ":"))
9967 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9968 (or end "")))
9970 (defun org-fast-tag-show-exit (flag)
9971 (save-excursion
9972 (goto-line 3)
9973 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9974 (replace-match ""))
9975 (when flag
9976 (end-of-line 1)
9977 (org-move-to-column (- (window-width) 19) t)
9978 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9980 (defun org-set-current-tags-overlay (current prefix)
9981 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9982 (if (featurep 'xemacs)
9983 (org-overlay-display org-tags-overlay (concat prefix s)
9984 'secondary-selection)
9985 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9986 (org-overlay-display org-tags-overlay (concat prefix s)))))
9988 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9989 "Fast tag selection with single keys.
9990 CURRENT is the current list of tags in the headline, INHERITED is the
9991 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9992 possibly with grouping information. TODO-TABLE is a similar table with
9993 TODO keywords, should these have keys assigned to them.
9994 If the keys are nil, a-z are automatically assigned.
9995 Returns the new tags string, or nil to not change the current settings."
9996 (let* ((fulltable (append table todo-table))
9997 (maxlen (apply 'max (mapcar
9998 (lambda (x)
9999 (if (stringp (car x)) (string-width (car x)) 0))
10000 fulltable)))
10001 (buf (current-buffer))
10002 (expert (eq org-fast-tag-selection-single-key 'expert))
10003 (buffer-tags nil)
10004 (fwidth (+ maxlen 3 1 3))
10005 (ncol (/ (- (window-width) 4) fwidth))
10006 (i-face 'org-done)
10007 (c-face 'org-todo)
10008 tg cnt e c char c1 c2 ntable tbl rtn
10009 ov-start ov-end ov-prefix
10010 (exit-after-next org-fast-tag-selection-single-key)
10011 (done-keywords org-done-keywords)
10012 groups ingroup)
10013 (save-excursion
10014 (beginning-of-line 1)
10015 (if (looking-at
10016 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10017 (setq ov-start (match-beginning 1)
10018 ov-end (match-end 1)
10019 ov-prefix "")
10020 (setq ov-start (1- (point-at-eol))
10021 ov-end (1+ ov-start))
10022 (skip-chars-forward "^\n\r")
10023 (setq ov-prefix
10024 (concat
10025 (buffer-substring (1- (point)) (point))
10026 (if (> (current-column) org-tags-column)
10028 (make-string (- org-tags-column (current-column)) ?\ ))))))
10029 (org-move-overlay org-tags-overlay ov-start ov-end)
10030 (save-window-excursion
10031 (if expert
10032 (set-buffer (get-buffer-create " *Org tags*"))
10033 (delete-other-windows)
10034 (split-window-vertically)
10035 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10036 (erase-buffer)
10037 (org-set-local 'org-done-keywords done-keywords)
10038 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10039 (org-fast-tag-insert "Current" current c-face "\n\n")
10040 (org-fast-tag-show-exit exit-after-next)
10041 (org-set-current-tags-overlay current ov-prefix)
10042 (setq tbl fulltable char ?a cnt 0)
10043 (while (setq e (pop tbl))
10044 (cond
10045 ((equal e '(:startgroup))
10046 (push '() groups) (setq ingroup t)
10047 (when (not (= cnt 0))
10048 (setq cnt 0)
10049 (insert "\n"))
10050 (insert "{ "))
10051 ((equal e '(:endgroup))
10052 (setq ingroup nil cnt 0)
10053 (insert "}\n"))
10055 (setq tg (car e) c2 nil)
10056 (if (cdr e)
10057 (setq c (cdr e))
10058 ;; automatically assign a character.
10059 (setq c1 (string-to-char
10060 (downcase (substring
10061 tg (if (= (string-to-char tg) ?@) 1 0)))))
10062 (if (or (rassoc c1 ntable) (rassoc c1 table))
10063 (while (or (rassoc char ntable) (rassoc char table))
10064 (setq char (1+ char)))
10065 (setq c2 c1))
10066 (setq c (or c2 char)))
10067 (if ingroup (push tg (car groups)))
10068 (setq tg (org-add-props tg nil 'face
10069 (cond
10070 ((not (assoc tg table))
10071 (org-get-todo-face tg))
10072 ((member tg current) c-face)
10073 ((member tg inherited) i-face)
10074 (t nil))))
10075 (if (and (= cnt 0) (not ingroup)) (insert " "))
10076 (insert "[" c "] " tg (make-string
10077 (- fwidth 4 (length tg)) ?\ ))
10078 (push (cons tg c) ntable)
10079 (when (= (setq cnt (1+ cnt)) ncol)
10080 (insert "\n")
10081 (if ingroup (insert " "))
10082 (setq cnt 0)))))
10083 (setq ntable (nreverse ntable))
10084 (insert "\n")
10085 (goto-char (point-min))
10086 (if (and (not expert) (fboundp 'fit-window-to-buffer))
10087 (fit-window-to-buffer))
10088 (setq rtn
10089 (catch 'exit
10090 (while t
10091 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10092 (if groups " [!] no groups" " [!]groups")
10093 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10094 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10095 (cond
10096 ((= c ?\r) (throw 'exit t))
10097 ((= c ?!)
10098 (setq groups (not groups))
10099 (goto-char (point-min))
10100 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10101 ((= c ?\C-c)
10102 (if (not expert)
10103 (org-fast-tag-show-exit
10104 (setq exit-after-next (not exit-after-next)))
10105 (setq expert nil)
10106 (delete-other-windows)
10107 (split-window-vertically)
10108 (org-switch-to-buffer-other-window " *Org tags*")
10109 (and (fboundp 'fit-window-to-buffer)
10110 (fit-window-to-buffer))))
10111 ((or (= c ?\C-g)
10112 (and (= c ?q) (not (rassoc c ntable))))
10113 (org-detach-overlay org-tags-overlay)
10114 (setq quit-flag t))
10115 ((= c ?\ )
10116 (setq current nil)
10117 (if exit-after-next (setq exit-after-next 'now)))
10118 ((= c ?\t)
10119 (condition-case nil
10120 (setq tg (completing-read
10121 "Tag: "
10122 (or buffer-tags
10123 (with-current-buffer buf
10124 (org-get-buffer-tags)))))
10125 (quit (setq tg "")))
10126 (when (string-match "\\S-" tg)
10127 (add-to-list 'buffer-tags (list tg))
10128 (if (member tg current)
10129 (setq current (delete tg current))
10130 (push tg current)))
10131 (if exit-after-next (setq exit-after-next 'now)))
10132 ((setq e (rassoc c todo-table) tg (car e))
10133 (with-current-buffer buf
10134 (save-excursion (org-todo tg)))
10135 (if exit-after-next (setq exit-after-next 'now)))
10136 ((setq e (rassoc c ntable) tg (car e))
10137 (if (member tg current)
10138 (setq current (delete tg current))
10139 (loop for g in groups do
10140 (if (member tg g)
10141 (mapc (lambda (x)
10142 (setq current (delete x current)))
10143 g)))
10144 (push tg current))
10145 (if exit-after-next (setq exit-after-next 'now))))
10147 ;; Create a sorted list
10148 (setq current
10149 (sort current
10150 (lambda (a b)
10151 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10152 (if (eq exit-after-next 'now) (throw 'exit t))
10153 (goto-char (point-min))
10154 (beginning-of-line 2)
10155 (delete-region (point) (point-at-eol))
10156 (org-fast-tag-insert "Current" current c-face)
10157 (org-set-current-tags-overlay current ov-prefix)
10158 (while (re-search-forward
10159 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10160 (setq tg (match-string 1))
10161 (add-text-properties
10162 (match-beginning 1) (match-end 1)
10163 (list 'face
10164 (cond
10165 ((member tg current) c-face)
10166 ((member tg inherited) i-face)
10167 (t (get-text-property (match-beginning 1) 'face))))))
10168 (goto-char (point-min)))))
10169 (org-detach-overlay org-tags-overlay)
10170 (if rtn
10171 (mapconcat 'identity current ":")
10172 nil))))
10174 (defun org-get-tags-string ()
10175 "Get the TAGS string in the current headline."
10176 (unless (org-on-heading-p t)
10177 (error "Not on a heading"))
10178 (save-excursion
10179 (beginning-of-line 1)
10180 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10181 (org-match-string-no-properties 1)
10182 "")))
10184 (defun org-get-tags ()
10185 "Get the list of tags specified in the current headline."
10186 (org-split-string (org-get-tags-string) ":"))
10188 (defun org-get-buffer-tags ()
10189 "Get a table of all tags used in the buffer, for completion."
10190 (let (tags)
10191 (save-excursion
10192 (goto-char (point-min))
10193 (while (re-search-forward
10194 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10195 (when (equal (char-after (point-at-bol 0)) ?*)
10196 (mapc (lambda (x) (add-to-list 'tags x))
10197 (org-split-string (org-match-string-no-properties 1) ":")))))
10198 (mapcar 'list tags)))
10200 ;;;; The mapping API
10202 ;;;###autoload
10203 (defun org-map-entries (func &optional match scope &rest skip)
10204 "Call FUNC at each headline selected by MATCH in SCOPE.
10206 FUNC is a function or a lisp form. The function will be called without
10207 arguments, with the cursor positioned at the beginning of the headline.
10208 The return values of all calls to the function will be collected and
10209 returned as a list.
10211 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10212 Only headlines that are matched by this query will be considered during
10213 the iteration. When MATCH is nil or t, all headlines will be
10214 visited by the iteration.
10216 SCOPE determines the scope of this command. It can be any of:
10218 nil The current buffer, respecting the restriction if any
10219 tree The subtree started with the entry at point
10220 file The current buffer, without restriction
10221 file-with-archives
10222 The current buffer, and any archives associated with it
10223 agenda All agenda files
10224 agenda-with-archives
10225 All agenda files with any archive files associated with them
10226 \(file1 file2 ...)
10227 If this is a list, all files in the list will be scanned
10229 The remaining args are treated as settings for the skipping facilities of
10230 the scanner. The following items can be given here:
10232 archive skip trees with the archive tag.
10233 comment skip trees with the COMMENT keyword
10234 function or Emacs Lisp form:
10235 will be used as value for `org-agenda-skip-function', so whenever
10236 the the function returns t, FUNC will not be called for that
10237 entry and search will continue from the point where the
10238 function leaves it."
10239 (let* ((org-agenda-archives-mode nil) ; just to make sure
10240 (org-agenda-skip-archived-trees (memq 'archive skip))
10241 (org-agenda-skip-comment-trees (memq 'comment skip))
10242 (org-agenda-skip-function
10243 (car (org-delete-all '(comment archive) skip)))
10244 (org-tags-match-list-sublevels t)
10245 matcher pos file)
10247 (cond
10248 ((eq match t) (setq matcher t))
10249 ((eq match nil) (setq matcher t))
10250 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10252 (when (eq scope 'tree)
10253 (org-back-to-heading t)
10254 (org-narrow-to-subtree)
10255 (setq scope nil))
10257 (if (not scope)
10258 (progn
10259 (org-prepare-agenda-buffers
10260 (list (buffer-file-name (current-buffer))))
10261 (org-scan-tags func matcher))
10262 ;; Get the right scope
10263 (setq pos (point))
10264 (cond
10265 ((and scope (listp scope) (symbolp (car scope)))
10266 (setq scope (eval scope)))
10267 ((eq scope 'agenda)
10268 (setq scope (org-agenda-files t)))
10269 ((eq scope 'agenda-with-archives)
10270 (setq scope (org-agenda-files t))
10271 (setq scope (org-add-archive-files scope)))
10272 ((eq scope 'file)
10273 (setq scope (list (buffer-file-name))))
10274 ((eq scope 'file-with-archives)
10275 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10276 (org-prepare-agenda-buffers scope)
10277 (while (setq file (pop scope))
10278 (with-current-buffer (org-find-base-buffer-visiting file)
10279 (save-excursion
10280 (save-restriction
10281 (widen)
10282 (goto-char (point-min))
10283 (org-scan-tags func matcher))))))))
10285 ;;;; Properties
10287 ;;; Setting and retrieving properties
10289 (defconst org-special-properties
10290 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10291 "TIMESTAMP" "TIMESTAMP_IA")
10292 "The special properties valid in Org-mode.
10294 These are properties that are not defined in the property drawer,
10295 but in some other way.")
10297 (defconst org-default-properties
10298 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10299 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10300 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10301 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10302 "Some properties that are used by Org-mode for various purposes.
10303 Being in this list makes sure that they are offered for completion.")
10305 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10306 "Regular expression matching the first line of a property drawer.")
10308 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10309 "Regular expression matching the first line of a property drawer.")
10311 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10312 "Regular expression matching the first line of a property drawer.")
10314 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10315 "Regular expression matching the first line of a property drawer.")
10317 (defconst org-property-drawer-re
10318 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10319 org-property-end-re "\\)\n?")
10320 "Matches an entire property drawer.")
10322 (defconst org-clock-drawer-re
10323 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10324 org-property-end-re "\\)\n?")
10325 "Matches an entire clock drawer.")
10327 (defun org-property-action ()
10328 "Do an action on properties."
10329 (interactive)
10330 (let (c)
10331 (org-at-property-p)
10332 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10333 (setq c (read-char-exclusive))
10334 (cond
10335 ((equal c ?s)
10336 (call-interactively 'org-set-property))
10337 ((equal c ?d)
10338 (call-interactively 'org-delete-property))
10339 ((equal c ?D)
10340 (call-interactively 'org-delete-property-globally))
10341 ((equal c ?c)
10342 (call-interactively 'org-compute-property-at-point))
10343 (t (error "No such property action %c" c)))))
10345 (defun org-at-property-p ()
10346 "Is the cursor in a property line?"
10347 ;; FIXME: Does not check if we are actually in the drawer.
10348 ;; FIXME: also returns true on any drawers.....
10349 ;; This is used by C-c C-c for property action.
10350 (save-excursion
10351 (beginning-of-line 1)
10352 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10354 (defun org-get-property-block (&optional beg end force)
10355 "Return the (beg . end) range of the body of the property drawer.
10356 BEG and END can be beginning and end of subtree, if not given
10357 they will be found.
10358 If the drawer does not exist and FORCE is non-nil, create the drawer."
10359 (catch 'exit
10360 (save-excursion
10361 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10362 (end (or end (progn (outline-next-heading) (point)))))
10363 (goto-char beg)
10364 (if (re-search-forward org-property-start-re end t)
10365 (setq beg (1+ (match-end 0)))
10366 (if force
10367 (save-excursion
10368 (org-insert-property-drawer)
10369 (setq end (progn (outline-next-heading) (point))))
10370 (throw 'exit nil))
10371 (goto-char beg)
10372 (if (re-search-forward org-property-start-re end t)
10373 (setq beg (1+ (match-end 0)))))
10374 (if (re-search-forward org-property-end-re end t)
10375 (setq end (match-beginning 0))
10376 (or force (throw 'exit nil))
10377 (goto-char beg)
10378 (setq end beg)
10379 (org-indent-line-function)
10380 (insert ":END:\n"))
10381 (cons beg end)))))
10383 (defun org-entry-properties (&optional pom which)
10384 "Get all properties of the entry at point-or-marker POM.
10385 This includes the TODO keyword, the tags, time strings for deadline,
10386 scheduled, and clocking, and any additional properties defined in the
10387 entry. The return value is an alist, keys may occur multiple times
10388 if the property key was used several times.
10389 POM may also be nil, in which case the current entry is used.
10390 If WHICH is nil or `all', get all properties. If WHICH is
10391 `special' or `standard', only get that subclass."
10392 (setq which (or which 'all))
10393 (org-with-point-at pom
10394 (let ((clockstr (substring org-clock-string 0 -1))
10395 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10396 beg end range props sum-props key value string clocksum)
10397 (save-excursion
10398 (when (condition-case nil (org-back-to-heading t) (error nil))
10399 (setq beg (point))
10400 (setq sum-props (get-text-property (point) 'org-summaries))
10401 (setq clocksum (get-text-property (point) :org-clock-minutes))
10402 (outline-next-heading)
10403 (setq end (point))
10404 (when (memq which '(all special))
10405 ;; Get the special properties, like TODO and tags
10406 (goto-char beg)
10407 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10408 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10409 (when (looking-at org-priority-regexp)
10410 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10411 (when (and (setq value (org-get-tags-string))
10412 (string-match "\\S-" value))
10413 (push (cons "TAGS" value) props))
10414 (when (setq value (org-get-tags-at))
10415 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10416 props))
10417 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10418 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10419 string (if (equal key clockstr)
10420 (org-no-properties
10421 (org-trim
10422 (buffer-substring
10423 (match-beginning 3) (goto-char (point-at-eol)))))
10424 (substring (org-match-string-no-properties 3) 1 -1)))
10425 (unless key
10426 (if (= (char-after (match-beginning 3)) ?\[)
10427 (setq key "TIMESTAMP_IA")
10428 (setq key "TIMESTAMP")))
10429 (when (or (equal key clockstr) (not (assoc key props)))
10430 (push (cons key string) props)))
10434 (when (memq which '(all standard))
10435 ;; Get the standard properties, like :PORP: ...
10436 (setq range (org-get-property-block beg end))
10437 (when range
10438 (goto-char (car range))
10439 (while (re-search-forward
10440 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10441 (cdr range) t)
10442 (setq key (org-match-string-no-properties 1)
10443 value (org-trim (or (org-match-string-no-properties 2) "")))
10444 (unless (member key excluded)
10445 (push (cons key (or value "")) props)))))
10446 (if clocksum
10447 (push (cons "CLOCKSUM"
10448 (org-columns-number-to-string (/ (float clocksum) 60.)
10449 'add_times))
10450 props))
10451 (append sum-props (nreverse props)))))))
10453 (defun org-entry-get (pom property &optional inherit)
10454 "Get value of PROPERTY for entry at point-or-marker POM.
10455 If INHERIT is non-nil and the entry does not have the property,
10456 then also check higher levels of the hierarchy.
10457 If INHERIT is the symbol `selective', use inheritance only if the setting
10458 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10459 If the property is present but empty, the return value is the empty string.
10460 If the property is not present at all, nil is returned."
10461 (org-with-point-at pom
10462 (if (and inherit (if (eq inherit 'selective)
10463 (org-property-inherit-p property)
10465 (org-entry-get-with-inheritance property)
10466 (if (member property org-special-properties)
10467 ;; We need a special property. Use brute force, get all properties.
10468 (cdr (assoc property (org-entry-properties nil 'special)))
10469 (let ((range (org-get-property-block)))
10470 (if (and range
10471 (goto-char (car range))
10472 (re-search-forward
10473 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10474 (cdr range) t))
10475 ;; Found the property, return it.
10476 (if (match-end 1)
10477 (org-match-string-no-properties 1)
10478 "")))))))
10480 (defun org-property-or-variable-value (var &optional inherit)
10481 "Check if there is a property fixing the value of VAR.
10482 If yes, return this value. If not, return the current value of the variable."
10483 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10484 (if (and prop (stringp prop) (string-match "\\S-" prop))
10485 (read prop)
10486 (symbol-value var))))
10488 (defun org-entry-delete (pom property)
10489 "Delete the property PROPERTY from entry at point-or-marker POM."
10490 (org-with-point-at pom
10491 (if (member property org-special-properties)
10492 nil ; cannot delete these properties.
10493 (let ((range (org-get-property-block)))
10494 (if (and range
10495 (goto-char (car range))
10496 (re-search-forward
10497 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10498 (cdr range) t))
10499 (progn
10500 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10502 nil)))))
10504 ;; Multi-values properties are properties that contain multiple values
10505 ;; These values are assumed to be single words, separated by whitespace.
10506 (defun org-entry-add-to-multivalued-property (pom property value)
10507 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10508 (let* ((old (org-entry-get pom property))
10509 (values (and old (org-split-string old "[ \t]"))))
10510 (unless (member value values)
10511 (setq values (cons value values))
10512 (org-entry-put pom property
10513 (mapconcat 'identity values " ")))))
10515 (defun org-entry-remove-from-multivalued-property (pom property value)
10516 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10517 (let* ((old (org-entry-get pom property))
10518 (values (and old (org-split-string old "[ \t]"))))
10519 (when (member value values)
10520 (setq values (delete value values))
10521 (org-entry-put pom property
10522 (mapconcat 'identity values " ")))))
10524 (defun org-entry-member-in-multivalued-property (pom property value)
10525 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10526 (let* ((old (org-entry-get pom property))
10527 (values (and old (org-split-string old "[ \t]"))))
10528 (member value values)))
10530 (defvar org-entry-property-inherited-from (make-marker))
10532 (defun org-entry-get-with-inheritance (property)
10533 "Get entry property, and search higher levels if not present."
10534 (let (tmp)
10535 (save-excursion
10536 (save-restriction
10537 (widen)
10538 (catch 'ex
10539 (while t
10540 (when (setq tmp (org-entry-get nil property))
10541 (org-back-to-heading t)
10542 (move-marker org-entry-property-inherited-from (point))
10543 (throw 'ex tmp))
10544 (or (org-up-heading-safe) (throw 'ex nil)))))
10545 (or tmp
10546 (cdr (assoc property org-file-properties))
10547 (cdr (assoc property org-global-properties))
10548 (cdr (assoc property org-global-properties-fixed))))))
10550 (defun org-entry-put (pom property value)
10551 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10552 (org-with-point-at pom
10553 (org-back-to-heading t)
10554 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10555 range)
10556 (cond
10557 ((equal property "TODO")
10558 (when (and (stringp value) (string-match "\\S-" value)
10559 (not (member value org-todo-keywords-1)))
10560 (error "\"%s\" is not a valid TODO state" value))
10561 (if (or (not value)
10562 (not (string-match "\\S-" value)))
10563 (setq value 'none))
10564 (org-todo value)
10565 (org-set-tags nil 'align))
10566 ((equal property "PRIORITY")
10567 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10568 (string-to-char value) ?\ ))
10569 (org-set-tags nil 'align))
10570 ((equal property "SCHEDULED")
10571 (if (re-search-forward org-scheduled-time-regexp end t)
10572 (cond
10573 ((eq value 'earlier) (org-timestamp-change -1 'day))
10574 ((eq value 'later) (org-timestamp-change 1 'day))
10575 (t (call-interactively 'org-schedule)))
10576 (call-interactively 'org-schedule)))
10577 ((equal property "DEADLINE")
10578 (if (re-search-forward org-deadline-time-regexp end t)
10579 (cond
10580 ((eq value 'earlier) (org-timestamp-change -1 'day))
10581 ((eq value 'later) (org-timestamp-change 1 'day))
10582 (t (call-interactively 'org-deadline)))
10583 (call-interactively 'org-deadline)))
10584 ((member property org-special-properties)
10585 (error "The %s property can not yet be set with `org-entry-put'"
10586 property))
10587 (t ; a non-special property
10588 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10589 (setq range (org-get-property-block beg end 'force))
10590 (goto-char (car range))
10591 (if (re-search-forward
10592 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10593 (progn
10594 (delete-region (match-beginning 1) (match-end 1))
10595 (goto-char (match-beginning 1)))
10596 (goto-char (cdr range))
10597 (insert "\n")
10598 (backward-char 1)
10599 (org-indent-line-function)
10600 (insert ":" property ":"))
10601 (and value (insert " " value))
10602 (org-indent-line-function)))))))
10604 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10605 "Get all property keys in the current buffer.
10606 With INCLUDE-SPECIALS, also list the special properties that relect things
10607 like tags and TODO state.
10608 With INCLUDE-DEFAULTS, also include properties that has special meaning
10609 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10610 With INCLUDE-COLUMNS, also include property names given in COLUMN
10611 formats in the current buffer."
10612 (let (rtn range cfmt cols s p)
10613 (save-excursion
10614 (save-restriction
10615 (widen)
10616 (goto-char (point-min))
10617 (while (re-search-forward org-property-start-re nil t)
10618 (setq range (org-get-property-block))
10619 (goto-char (car range))
10620 (while (re-search-forward
10621 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10622 (cdr range) t)
10623 (add-to-list 'rtn (org-match-string-no-properties 1)))
10624 (outline-next-heading))))
10626 (when include-specials
10627 (setq rtn (append org-special-properties rtn)))
10629 (when include-defaults
10630 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10632 (when include-columns
10633 (save-excursion
10634 (save-restriction
10635 (widen)
10636 (goto-char (point-min))
10637 (while (re-search-forward
10638 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10639 nil t)
10640 (setq cfmt (match-string 2) s 0)
10641 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10642 cfmt s)
10643 (setq s (match-end 0)
10644 p (match-string 1 cfmt))
10645 (unless (or (equal p "ITEM")
10646 (member p org-special-properties))
10647 (add-to-list 'rtn (match-string 1 cfmt))))))))
10649 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10651 (defun org-property-values (key)
10652 "Return a list of all values of property KEY."
10653 (save-excursion
10654 (save-restriction
10655 (widen)
10656 (goto-char (point-min))
10657 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10658 values)
10659 (while (re-search-forward re nil t)
10660 (add-to-list 'values (org-trim (match-string 1))))
10661 (delete "" values)))))
10663 (defun org-insert-property-drawer ()
10664 "Insert a property drawer into the current entry."
10665 (interactive)
10666 (org-back-to-heading t)
10667 (looking-at outline-regexp)
10668 (let ((indent (- (match-end 0)(match-beginning 0)))
10669 (beg (point))
10670 (re (concat "^[ \t]*" org-keyword-time-regexp))
10671 end hiddenp)
10672 (outline-next-heading)
10673 (setq end (point))
10674 (goto-char beg)
10675 (while (re-search-forward re end t))
10676 (setq hiddenp (org-invisible-p))
10677 (end-of-line 1)
10678 (and (equal (char-after) ?\n) (forward-char 1))
10679 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10680 (beginning-of-line 2))
10681 (org-skip-over-state-notes)
10682 (skip-chars-backward " \t\n\r")
10683 (if (eq (char-before) ?*) (forward-char 1))
10684 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10685 (beginning-of-line 0)
10686 (org-indent-to-column indent)
10687 (beginning-of-line 2)
10688 (org-indent-to-column indent)
10689 (beginning-of-line 0)
10690 (if hiddenp
10691 (save-excursion
10692 (org-back-to-heading t)
10693 (hide-entry))
10694 (org-flag-drawer t))))
10696 (defun org-set-property (property value)
10697 "In the current entry, set PROPERTY to VALUE.
10698 When called interactively, this will prompt for a property name, offering
10699 completion on existing and default properties. And then it will prompt
10700 for a value, offering competion either on allowed values (via an inherited
10701 xxx_ALL property) or on existing values in other instances of this property
10702 in the current file."
10703 (interactive
10704 (let* ((completion-ignore-case t)
10705 (keys (org-buffer-property-keys nil t t))
10706 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10707 (prop (if (member prop0 keys)
10708 prop0
10709 (or (cdr (assoc (downcase prop0)
10710 (mapcar (lambda (x) (cons (downcase x) x))
10711 keys)))
10712 prop0)))
10713 (cur (org-entry-get nil prop))
10714 (allowed (org-property-get-allowed-values nil prop 'table))
10715 (existing (mapcar 'list (org-property-values prop)))
10716 (val (if allowed
10717 (org-completing-read "Value: " allowed nil 'req-match)
10718 (org-completing-read
10719 (concat "Value" (if (and cur (string-match "\\S-" cur))
10720 (concat "[" cur "]") "")
10721 ": ")
10722 existing nil nil "" nil cur))))
10723 (list prop (if (equal val "") cur val))))
10724 (unless (equal (org-entry-get nil property) value)
10725 (org-entry-put nil property value)))
10727 (defun org-delete-property (property)
10728 "In the current entry, delete PROPERTY."
10729 (interactive
10730 (let* ((completion-ignore-case t)
10731 (prop (completing-read
10732 "Property: " (org-entry-properties nil 'standard))))
10733 (list prop)))
10734 (message "Property %s %s" property
10735 (if (org-entry-delete nil property)
10736 "deleted"
10737 "was not present in the entry")))
10739 (defun org-delete-property-globally (property)
10740 "Remove PROPERTY globally, from all entries."
10741 (interactive
10742 (let* ((completion-ignore-case t)
10743 (prop (completing-read
10744 "Globally remove property: "
10745 (mapcar 'list (org-buffer-property-keys)))))
10746 (list prop)))
10747 (save-excursion
10748 (save-restriction
10749 (widen)
10750 (goto-char (point-min))
10751 (let ((cnt 0))
10752 (while (re-search-forward
10753 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10754 nil t)
10755 (setq cnt (1+ cnt))
10756 (replace-match ""))
10757 (message "Property \"%s\" removed from %d entries" property cnt)))))
10759 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10761 (defun org-compute-property-at-point ()
10762 "Compute the property at point.
10763 This looks for an enclosing column format, extracts the operator and
10764 then applies it to the proerty in the column format's scope."
10765 (interactive)
10766 (unless (org-at-property-p)
10767 (error "Not at a property"))
10768 (let ((prop (org-match-string-no-properties 2)))
10769 (org-columns-get-format-and-top-level)
10770 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10771 (error "No operator defined for property %s" prop))
10772 (org-columns-compute prop)))
10774 (defun org-property-get-allowed-values (pom property &optional table)
10775 "Get allowed values for the property PROPERTY.
10776 When TABLE is non-nil, return an alist that can directly be used for
10777 completion."
10778 (let (vals)
10779 (cond
10780 ((equal property "TODO")
10781 (setq vals (org-with-point-at pom
10782 (append org-todo-keywords-1 '("")))))
10783 ((equal property "PRIORITY")
10784 (let ((n org-lowest-priority))
10785 (while (>= n org-highest-priority)
10786 (push (char-to-string n) vals)
10787 (setq n (1- n)))))
10788 ((member property org-special-properties))
10790 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10792 (when (and vals (string-match "\\S-" vals))
10793 (setq vals (car (read-from-string (concat "(" vals ")"))))
10794 (setq vals (mapcar (lambda (x)
10795 (cond ((stringp x) x)
10796 ((numberp x) (number-to-string x))
10797 ((symbolp x) (symbol-name x))
10798 (t "???")))
10799 vals)))))
10800 (if table (mapcar 'list vals) vals)))
10802 (defun org-property-previous-allowed-value (&optional previous)
10803 "Switch to the next allowed value for this property."
10804 (interactive)
10805 (org-property-next-allowed-value t))
10807 (defun org-property-next-allowed-value (&optional previous)
10808 "Switch to the next allowed value for this property."
10809 (interactive)
10810 (unless (org-at-property-p)
10811 (error "Not at a property"))
10812 (let* ((key (match-string 2))
10813 (value (match-string 3))
10814 (allowed (or (org-property-get-allowed-values (point) key)
10815 (and (member value '("[ ]" "[-]" "[X]"))
10816 '("[ ]" "[X]"))))
10817 nval)
10818 (unless allowed
10819 (error "Allowed values for this property have not been defined"))
10820 (if previous (setq allowed (reverse allowed)))
10821 (if (member value allowed)
10822 (setq nval (car (cdr (member value allowed)))))
10823 (setq nval (or nval (car allowed)))
10824 (if (equal nval value)
10825 (error "Only one allowed value for this property"))
10826 (org-at-property-p)
10827 (replace-match (concat " :" key ": " nval) t t)
10828 (org-indent-line-function)
10829 (beginning-of-line 1)
10830 (skip-chars-forward " \t")))
10832 (defun org-find-entry-with-id (ident)
10833 "Locate the entry that contains the ID property with exact value IDENT.
10834 IDENT can be a string, a symbol or a number, this function will search for
10835 the string representation of it.
10836 Return the position where this entry starts, or nil if there is no such entry."
10837 (let ((id (cond
10838 ((stringp ident) ident)
10839 ((symbol-name ident) (symbol-name ident))
10840 ((numberp ident) (number-to-string ident))
10841 (t (error "IDENT %s must be a string, symbol or number" ident))))
10842 (case-fold-search nil))
10843 (save-excursion
10844 (save-restriction
10845 (widen)
10846 (goto-char (point-min))
10847 (when (re-search-forward
10848 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10849 nil t)
10850 (org-back-to-heading)
10851 (point))))))
10853 ;;;; Timestamps
10855 (defvar org-last-changed-timestamp nil)
10856 (defvar org-last-inserted-timestamp nil
10857 "The last time stamp inserted with `org-insert-time-stamp'.")
10858 (defvar org-time-was-given) ; dynamically scoped parameter
10859 (defvar org-end-time-was-given) ; dynamically scoped parameter
10860 (defvar org-ts-what) ; dynamically scoped parameter
10862 (defun org-time-stamp (arg)
10863 "Prompt for a date/time and insert a time stamp.
10864 If the user specifies a time like HH:MM, or if this command is called
10865 with a prefix argument, the time stamp will contain date and time.
10866 Otherwise, only the date will be included. All parts of a date not
10867 specified by the user will be filled in from the current date/time.
10868 So if you press just return without typing anything, the time stamp
10869 will represent the current date/time. If there is already a timestamp
10870 at the cursor, it will be modified."
10871 (interactive "P")
10872 (let* ((ts nil)
10873 (default-time
10874 ;; Default time is either today, or, when entering a range,
10875 ;; the range start.
10876 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10877 (save-excursion
10878 (re-search-backward
10879 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10880 (- (point) 20) t)))
10881 (apply 'encode-time (org-parse-time-string (match-string 1)))
10882 (current-time)))
10883 (default-input (and ts (org-get-compact-tod ts)))
10884 org-time-was-given org-end-time-was-given time)
10885 (cond
10886 ((and (org-at-timestamp-p)
10887 (eq last-command 'org-time-stamp)
10888 (eq this-command 'org-time-stamp))
10889 (insert "--")
10890 (setq time (let ((this-command this-command))
10891 (org-read-date arg 'totime nil nil default-time default-input)))
10892 (org-insert-time-stamp time (or org-time-was-given arg)))
10893 ((org-at-timestamp-p)
10894 (setq time (let ((this-command this-command))
10895 (org-read-date arg 'totime nil nil default-time default-input)))
10896 (when (org-at-timestamp-p) ; just to get the match data
10897 (replace-match "")
10898 (setq org-last-changed-timestamp
10899 (org-insert-time-stamp
10900 time (or org-time-was-given arg)
10901 nil nil nil (list org-end-time-was-given))))
10902 (message "Timestamp updated"))
10904 (setq time (let ((this-command this-command))
10905 (org-read-date arg 'totime nil nil default-time default-input)))
10906 (org-insert-time-stamp time (or org-time-was-given arg)
10907 nil nil nil (list org-end-time-was-given))))))
10909 ;; FIXME: can we use this for something else, like computing time differences?
10910 (defun org-get-compact-tod (s)
10911 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10912 (let* ((t1 (match-string 1 s))
10913 (h1 (string-to-number (match-string 2 s)))
10914 (m1 (string-to-number (match-string 3 s)))
10915 (t2 (and (match-end 4) (match-string 5 s)))
10916 (h2 (and t2 (string-to-number (match-string 6 s))))
10917 (m2 (and t2 (string-to-number (match-string 7 s))))
10918 dh dm)
10919 (if (not t2)
10921 (setq dh (- h2 h1) dm (- m2 m1))
10922 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10923 (concat t1 "+" (number-to-string dh)
10924 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10926 (defun org-time-stamp-inactive (&optional arg)
10927 "Insert an inactive time stamp.
10928 An inactive time stamp is enclosed in square brackets instead of angle
10929 brackets. It is inactive in the sense that it does not trigger agenda entries,
10930 does not link to the calendar and cannot be changed with the S-cursor keys.
10931 So these are more for recording a certain time/date."
10932 (interactive "P")
10933 (let (org-time-was-given org-end-time-was-given time)
10934 (setq time (org-read-date arg 'totime))
10935 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10936 nil nil (list org-end-time-was-given))))
10938 (defvar org-date-ovl (org-make-overlay 1 1))
10939 (org-overlay-put org-date-ovl 'face 'org-warning)
10940 (org-detach-overlay org-date-ovl)
10942 (defvar org-ans1) ; dynamically scoped parameter
10943 (defvar org-ans2) ; dynamically scoped parameter
10945 (defvar org-plain-time-of-day-regexp) ; defined below
10947 (defvar org-overriding-default-time nil) ; dynamically scoped
10948 (defvar org-read-date-overlay nil)
10949 (defvar org-dcst nil) ; dynamically scoped
10951 (defun org-read-date (&optional with-time to-time from-string prompt
10952 default-time default-input)
10953 "Read a date, possibly a time, and make things smooth for the user.
10954 The prompt will suggest to enter an ISO date, but you can also enter anything
10955 which will at least partially be understood by `parse-time-string'.
10956 Unrecognized parts of the date will default to the current day, month, year,
10957 hour and minute. If this command is called to replace a timestamp at point,
10958 of to enter the second timestamp of a range, the default time is taken from the
10959 existing stamp. For example,
10960 3-2-5 --> 2003-02-05
10961 feb 15 --> currentyear-02-15
10962 sep 12 9 --> 2009-09-12
10963 12:45 --> today 12:45
10964 22 sept 0:34 --> currentyear-09-22 0:34
10965 12 --> currentyear-currentmonth-12
10966 Fri --> nearest Friday (today or later)
10967 etc.
10969 Furthermore you can specify a relative date by giving, as the *first* thing
10970 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10971 change in days weeks, months, years.
10972 With a single plus or minus, the date is relative to today. With a double
10973 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10974 +4d --> four days from today
10975 +4 --> same as above
10976 +2w --> two weeks from today
10977 ++5 --> five days from default date
10979 The function understands only English month and weekday abbreviations,
10980 but this can be configured with the variables `parse-time-months' and
10981 `parse-time-weekdays'.
10983 While prompting, a calendar is popped up - you can also select the
10984 date with the mouse (button 1). The calendar shows a period of three
10985 months. To scroll it to other months, use the keys `>' and `<'.
10986 If you don't like the calendar, turn it off with
10987 \(setq org-read-date-popup-calendar nil)
10989 With optional argument TO-TIME, the date will immediately be converted
10990 to an internal time.
10991 With an optional argument WITH-TIME, the prompt will suggest to also
10992 insert a time. Note that when WITH-TIME is not set, you can still
10993 enter a time, and this function will inform the calling routine about
10994 this change. The calling routine may then choose to change the format
10995 used to insert the time stamp into the buffer to include the time.
10996 With optional argument FROM-STRING, read from this string instead from
10997 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10998 the time/date that is used for everything that is not specified by the
10999 user."
11000 (require 'parse-time)
11001 (let* ((org-time-stamp-rounding-minutes
11002 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11003 (org-dcst org-display-custom-times)
11004 (ct (org-current-time))
11005 (def (or org-overriding-default-time default-time ct))
11006 (defdecode (decode-time def))
11007 (dummy (progn
11008 (when (< (nth 2 defdecode) org-extend-today-until)
11009 (setcar (nthcdr 2 defdecode) -1)
11010 (setcar (nthcdr 1 defdecode) 59)
11011 (setq def (apply 'encode-time defdecode)
11012 defdecode (decode-time def)))))
11013 (calendar-move-hook nil)
11014 (calendar-view-diary-initially-flag nil)
11015 (view-diary-entries-initially nil)
11016 (calendar-view-holidays-initially-flag nil)
11017 (view-calendar-holidays-initially nil)
11018 (timestr (format-time-string
11019 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11020 (prompt (concat (if prompt (concat prompt " ") "")
11021 (format "Date+time [%s]: " timestr)))
11022 ans (org-ans0 "") org-ans1 org-ans2 final)
11024 (cond
11025 (from-string (setq ans from-string))
11026 (org-read-date-popup-calendar
11027 (save-excursion
11028 (save-window-excursion
11029 (calendar)
11030 (calendar-forward-day (- (time-to-days def)
11031 (calendar-absolute-from-gregorian
11032 (calendar-current-date))))
11033 (org-eval-in-calendar nil t)
11034 (let* ((old-map (current-local-map))
11035 (map (copy-keymap calendar-mode-map))
11036 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11037 (org-defkey map (kbd "RET") 'org-calendar-select)
11038 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11039 'org-calendar-select-mouse)
11040 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11041 'org-calendar-select-mouse)
11042 (org-defkey minibuffer-local-map [(meta shift left)]
11043 (lambda () (interactive)
11044 (org-eval-in-calendar '(calendar-backward-month 1))))
11045 (org-defkey minibuffer-local-map [(meta shift right)]
11046 (lambda () (interactive)
11047 (org-eval-in-calendar '(calendar-forward-month 1))))
11048 (org-defkey minibuffer-local-map [(meta shift up)]
11049 (lambda () (interactive)
11050 (org-eval-in-calendar '(calendar-backward-year 1))))
11051 (org-defkey minibuffer-local-map [(meta shift down)]
11052 (lambda () (interactive)
11053 (org-eval-in-calendar '(calendar-forward-year 1))))
11054 (org-defkey minibuffer-local-map [(shift up)]
11055 (lambda () (interactive)
11056 (org-eval-in-calendar '(calendar-backward-week 1))))
11057 (org-defkey minibuffer-local-map [(shift down)]
11058 (lambda () (interactive)
11059 (org-eval-in-calendar '(calendar-forward-week 1))))
11060 (org-defkey minibuffer-local-map [(shift left)]
11061 (lambda () (interactive)
11062 (org-eval-in-calendar '(calendar-backward-day 1))))
11063 (org-defkey minibuffer-local-map [(shift right)]
11064 (lambda () (interactive)
11065 (org-eval-in-calendar '(calendar-forward-day 1))))
11066 (org-defkey minibuffer-local-map ">"
11067 (lambda () (interactive)
11068 (org-eval-in-calendar '(scroll-calendar-left 1))))
11069 (org-defkey minibuffer-local-map "<"
11070 (lambda () (interactive)
11071 (org-eval-in-calendar '(scroll-calendar-right 1))))
11072 (unwind-protect
11073 (progn
11074 (use-local-map map)
11075 (add-hook 'post-command-hook 'org-read-date-display)
11076 (setq org-ans0 (read-string prompt default-input nil nil))
11077 ;; org-ans0: from prompt
11078 ;; org-ans1: from mouse click
11079 ;; org-ans2: from calendar motion
11080 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11081 (remove-hook 'post-command-hook 'org-read-date-display)
11082 (use-local-map old-map)
11083 (when org-read-date-overlay
11084 (org-delete-overlay org-read-date-overlay)
11085 (setq org-read-date-overlay nil)))))))
11087 (t ; Naked prompt only
11088 (unwind-protect
11089 (setq ans (read-string prompt default-input nil timestr))
11090 (when org-read-date-overlay
11091 (org-delete-overlay org-read-date-overlay)
11092 (setq org-read-date-overlay nil)))))
11094 (setq final (org-read-date-analyze ans def defdecode))
11096 (if to-time
11097 (apply 'encode-time final)
11098 (if (and (boundp 'org-time-was-given) org-time-was-given)
11099 (format "%04d-%02d-%02d %02d:%02d"
11100 (nth 5 final) (nth 4 final) (nth 3 final)
11101 (nth 2 final) (nth 1 final))
11102 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11103 (defvar def)
11104 (defvar defdecode)
11105 (defvar with-time)
11106 (defun org-read-date-display ()
11107 "Display the currrent date prompt interpretation in the minibuffer."
11108 (when org-read-date-display-live
11109 (when org-read-date-overlay
11110 (org-delete-overlay org-read-date-overlay))
11111 (let ((p (point)))
11112 (end-of-line 1)
11113 (while (not (equal (buffer-substring
11114 (max (point-min) (- (point) 4)) (point))
11115 " "))
11116 (insert " "))
11117 (goto-char p))
11118 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11119 " " (or org-ans1 org-ans2)))
11120 (org-end-time-was-given nil)
11121 (f (org-read-date-analyze ans def defdecode))
11122 (fmts (if org-dcst
11123 org-time-stamp-custom-formats
11124 org-time-stamp-formats))
11125 (fmt (if (or with-time
11126 (and (boundp 'org-time-was-given) org-time-was-given))
11127 (cdr fmts)
11128 (car fmts)))
11129 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11130 (when (and org-end-time-was-given
11131 (string-match org-plain-time-of-day-regexp txt))
11132 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11133 org-end-time-was-given
11134 (substring txt (match-end 0)))))
11135 (setq org-read-date-overlay
11136 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11137 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11139 (defun org-read-date-analyze (ans def defdecode)
11140 "Analyze the combined answer of the date prompt."
11141 ;; FIXME: cleanup and comment
11142 (let (delta deltan deltaw deltadef year month day
11143 hour minute second wday pm h2 m2 tl wday1
11144 iso-year iso-weekday iso-week iso-year iso-date)
11146 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11147 (setq ans "+0"))
11149 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11150 (setq ans (replace-match "" t t ans)
11151 deltan (car delta)
11152 deltaw (nth 1 delta)
11153 deltadef (nth 2 delta)))
11155 ;; Check if there is an iso week date in there
11156 ;; If yes, sore the info and ostpone interpreting it until the rest
11157 ;; of the parsing is done
11158 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11159 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11160 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11161 iso-week (string-to-number (match-string 2 ans)))
11162 (setq ans (replace-match "" t t ans)))
11164 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11165 (when (string-match
11166 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11167 (setq year (if (match-end 2)
11168 (string-to-number (match-string 2 ans))
11169 (string-to-number (format-time-string "%Y")))
11170 month (string-to-number (match-string 3 ans))
11171 day (string-to-number (match-string 4 ans)))
11172 (if (< year 100) (setq year (+ 2000 year)))
11173 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11174 t nil ans)))
11175 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11176 ;; If there is a time with am/pm, and *no* time without it, we convert
11177 ;; so that matching will be successful.
11178 (loop for i from 1 to 2 do ; twice, for end time as well
11179 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11180 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11181 (setq hour (string-to-number (match-string 1 ans))
11182 minute (if (match-end 3)
11183 (string-to-number (match-string 3 ans))
11185 pm (equal ?p
11186 (string-to-char (downcase (match-string 4 ans)))))
11187 (if (and (= hour 12) (not pm))
11188 (setq hour 0)
11189 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11190 (setq ans (replace-match (format "%02d:%02d" hour minute)
11191 t t ans))))
11193 ;; Check if a time range is given as a duration
11194 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11195 (setq hour (string-to-number (match-string 1 ans))
11196 h2 (+ hour (string-to-number (match-string 3 ans)))
11197 minute (string-to-number (match-string 2 ans))
11198 m2 (+ minute (if (match-end 5) (string-to-number
11199 (match-string 5 ans))0)))
11200 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11201 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11202 t t ans)))
11204 ;; Check if there is a time range
11205 (when (boundp 'org-end-time-was-given)
11206 (setq org-time-was-given nil)
11207 (when (and (string-match org-plain-time-of-day-regexp ans)
11208 (match-end 8))
11209 (setq org-end-time-was-given (match-string 8 ans))
11210 (setq ans (concat (substring ans 0 (match-beginning 7))
11211 (substring ans (match-end 7))))))
11213 (setq tl (parse-time-string ans)
11214 day (or (nth 3 tl) (nth 3 defdecode))
11215 month (or (nth 4 tl)
11216 (if (and org-read-date-prefer-future
11217 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11218 (1+ (nth 4 defdecode))
11219 (nth 4 defdecode)))
11220 year (or (nth 5 tl)
11221 (if (and org-read-date-prefer-future
11222 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11223 (1+ (nth 5 defdecode))
11224 (nth 5 defdecode)))
11225 hour (or (nth 2 tl) (nth 2 defdecode))
11226 minute (or (nth 1 tl) (nth 1 defdecode))
11227 second (or (nth 0 tl) 0)
11228 wday (nth 6 tl))
11230 ;; Special date definitions below
11231 (cond
11232 (iso-week
11233 ;; There was an iso week
11234 (setq year (or iso-year year)
11235 day (or iso-weekday wday 1)
11236 wday nil ; to make sure that the trigger below does not match
11237 iso-date (calendar-gregorian-from-absolute
11238 (calendar-absolute-from-iso
11239 (list iso-week day year))))
11240 ; FIXME: Should we also push ISO weeks into the future?
11241 ; (when (and org-read-date-prefer-future
11242 ; (not iso-year)
11243 ; (< (calendar-absolute-from-gregorian iso-date)
11244 ; (time-to-days (current-time))))
11245 ; (setq year (1+ year)
11246 ; iso-date (calendar-gregorian-from-absolute
11247 ; (calendar-absolute-from-iso
11248 ; (list iso-week day year)))))
11249 (setq month (car iso-date)
11250 year (nth 2 iso-date)
11251 day (nth 1 iso-date)))
11252 (deltan
11253 (unless deltadef
11254 (let ((now (decode-time (current-time))))
11255 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11256 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11257 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11258 ((equal deltaw "m") (setq month (+ month deltan)))
11259 ((equal deltaw "y") (setq year (+ year deltan)))))
11260 ((and wday (not (nth 3 tl)))
11261 ;; Weekday was given, but no day, so pick that day in the week
11262 ;; on or after the derived date.
11263 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11264 (unless (equal wday wday1)
11265 (setq day (+ day (% (- wday wday1 -7) 7))))))
11266 (if (and (boundp 'org-time-was-given)
11267 (nth 2 tl))
11268 (setq org-time-was-given t))
11269 (if (< year 100) (setq year (+ 2000 year)))
11270 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11271 (list second minute hour day month year)))
11273 (defvar parse-time-weekdays)
11275 (defun org-read-date-get-relative (s today default)
11276 "Check string S for special relative date string.
11277 TODAY and DEFAULT are internal times, for today and for a default.
11278 Return shift list (N what def-flag)
11279 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11280 N is the number of WHATs to shift.
11281 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11282 the DEFAULT date rather than TODAY."
11283 (when (and
11284 (string-match
11285 (concat
11286 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11287 "\\([0-9]+\\)?"
11288 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11289 "\\([ \t]\\|$\\)") s)
11290 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11291 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11292 (string-to-char (substring (match-string 1 s) -1))
11293 ?+))
11294 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11295 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11296 (what (if (match-end 3) (match-string 3 s) "d"))
11297 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11298 (date (if rel default today))
11299 (wday (nth 6 (decode-time date)))
11300 delta)
11301 (if wday1
11302 (progn
11303 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11304 (if (= dir ?-) (setq delta (- delta 7)))
11305 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11306 (list delta "d" rel))
11307 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11309 (defun org-eval-in-calendar (form &optional keepdate)
11310 "Eval FORM in the calendar window and return to current window.
11311 Also, store the cursor date in variable org-ans2."
11312 (let ((sw (selected-window)))
11313 (select-window (get-buffer-window "*Calendar*"))
11314 (eval form)
11315 (when (and (not keepdate) (calendar-cursor-to-date))
11316 (let* ((date (calendar-cursor-to-date))
11317 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11318 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11319 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11320 (select-window sw)))
11322 ; ;; Update the prompt to show new default date
11323 ; (save-excursion
11324 ; (goto-char (point-min))
11325 ; (when (and org-ans2
11326 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11327 ; (get-text-property (match-end 0) 'field))
11328 ; (let ((inhibit-read-only t))
11329 ; (replace-match (concat "[" org-ans2 "]") t t)
11330 ; (add-text-properties (point-min) (1+ (match-end 0))
11331 ; (text-properties-at (1+ (point-min)))))))))
11333 (defun org-calendar-select ()
11334 "Return to `org-read-date' with the date currently selected.
11335 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11336 (interactive)
11337 (when (calendar-cursor-to-date)
11338 (let* ((date (calendar-cursor-to-date))
11339 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11340 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11341 (if (active-minibuffer-window) (exit-minibuffer))))
11343 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11344 "Insert a date stamp for the date given by the internal TIME.
11345 WITH-HM means, use the stamp format that includes the time of the day.
11346 INACTIVE means use square brackets instead of angular ones, so that the
11347 stamp will not contribute to the agenda.
11348 PRE and POST are optional strings to be inserted before and after the
11349 stamp.
11350 The command returns the inserted time stamp."
11351 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11352 stamp)
11353 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11354 (insert-before-markers (or pre ""))
11355 (insert-before-markers (setq stamp (format-time-string fmt time)))
11356 (when (listp extra)
11357 (setq extra (car extra))
11358 (if (and (stringp extra)
11359 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11360 (setq extra (format "-%02d:%02d"
11361 (string-to-number (match-string 1 extra))
11362 (string-to-number (match-string 2 extra))))
11363 (setq extra nil)))
11364 (when extra
11365 (backward-char 1)
11366 (insert-before-markers extra)
11367 (forward-char 1))
11368 (insert-before-markers (or post ""))
11369 (setq org-last-inserted-timestamp stamp)))
11371 (defun org-toggle-time-stamp-overlays ()
11372 "Toggle the use of custom time stamp formats."
11373 (interactive)
11374 (setq org-display-custom-times (not org-display-custom-times))
11375 (unless org-display-custom-times
11376 (let ((p (point-min)) (bmp (buffer-modified-p)))
11377 (while (setq p (next-single-property-change p 'display))
11378 (if (and (get-text-property p 'display)
11379 (eq (get-text-property p 'face) 'org-date))
11380 (remove-text-properties
11381 p (setq p (next-single-property-change p 'display))
11382 '(display t))))
11383 (set-buffer-modified-p bmp)))
11384 (if (featurep 'xemacs)
11385 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11386 (org-restart-font-lock)
11387 (setq org-table-may-need-update t)
11388 (if org-display-custom-times
11389 (message "Time stamps are overlayed with custom format")
11390 (message "Time stamp overlays removed")))
11392 (defun org-display-custom-time (beg end)
11393 "Overlay modified time stamp format over timestamp between BEG and END."
11394 (let* ((ts (buffer-substring beg end))
11395 t1 w1 with-hm tf time str w2 (off 0))
11396 (save-match-data
11397 (setq t1 (org-parse-time-string ts t))
11398 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11399 (setq off (- (match-end 0) (match-beginning 0)))))
11400 (setq end (- end off))
11401 (setq w1 (- end beg)
11402 with-hm (and (nth 1 t1) (nth 2 t1))
11403 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11404 time (org-fix-decoded-time t1)
11405 str (org-add-props
11406 (format-time-string
11407 (substring tf 1 -1) (apply 'encode-time time))
11408 nil 'mouse-face 'highlight)
11409 w2 (length str))
11410 (if (not (= w2 w1))
11411 (add-text-properties (1+ beg) (+ 2 beg)
11412 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11413 (if (featurep 'xemacs)
11414 (progn
11415 (put-text-property beg end 'invisible t)
11416 (put-text-property beg end 'end-glyph (make-glyph str)))
11417 (put-text-property beg end 'display str))))
11419 (defun org-translate-time (string)
11420 "Translate all timestamps in STRING to custom format.
11421 But do this only if the variable `org-display-custom-times' is set."
11422 (when org-display-custom-times
11423 (save-match-data
11424 (let* ((start 0)
11425 (re org-ts-regexp-both)
11426 t1 with-hm inactive tf time str beg end)
11427 (while (setq start (string-match re string start))
11428 (setq beg (match-beginning 0)
11429 end (match-end 0)
11430 t1 (save-match-data
11431 (org-parse-time-string (substring string beg end) t))
11432 with-hm (and (nth 1 t1) (nth 2 t1))
11433 inactive (equal (substring string beg (1+ beg)) "[")
11434 tf (funcall (if with-hm 'cdr 'car)
11435 org-time-stamp-custom-formats)
11436 time (org-fix-decoded-time t1)
11437 str (format-time-string
11438 (concat
11439 (if inactive "[" "<") (substring tf 1 -1)
11440 (if inactive "]" ">"))
11441 (apply 'encode-time time))
11442 string (replace-match str t t string)
11443 start (+ start (length str)))))))
11444 string)
11446 (defun org-fix-decoded-time (time)
11447 "Set 0 instead of nil for the first 6 elements of time.
11448 Don't touch the rest."
11449 (let ((n 0))
11450 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11452 (defun org-days-to-time (timestamp-string)
11453 "Difference between TIMESTAMP-STRING and now in days."
11454 (- (time-to-days (org-time-string-to-time timestamp-string))
11455 (time-to-days (current-time))))
11457 (defun org-deadline-close (timestamp-string &optional ndays)
11458 "Is the time in TIMESTAMP-STRING close to the current date?"
11459 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11460 (and (< (org-days-to-time timestamp-string) ndays)
11461 (not (org-entry-is-done-p))))
11463 (defun org-get-wdays (ts)
11464 "Get the deadline lead time appropriate for timestring TS."
11465 (cond
11466 ((<= org-deadline-warning-days 0)
11467 ;; 0 or negative, enforce this value no matter what
11468 (- org-deadline-warning-days))
11469 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11470 ;; lead time is specified.
11471 (floor (* (string-to-number (match-string 1 ts))
11472 (cdr (assoc (match-string 2 ts)
11473 '(("d" . 1) ("w" . 7)
11474 ("m" . 30.4) ("y" . 365.25)))))))
11475 ;; go for the default.
11476 (t org-deadline-warning-days)))
11478 (defun org-calendar-select-mouse (ev)
11479 "Return to `org-read-date' with the date currently selected.
11480 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11481 (interactive "e")
11482 (mouse-set-point ev)
11483 (when (calendar-cursor-to-date)
11484 (let* ((date (calendar-cursor-to-date))
11485 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11486 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11487 (if (active-minibuffer-window) (exit-minibuffer))))
11489 (defun org-check-deadlines (ndays)
11490 "Check if there are any deadlines due or past due.
11491 A deadline is considered due if it happens within `org-deadline-warning-days'
11492 days from today's date. If the deadline appears in an entry marked DONE,
11493 it is not shown. The prefix arg NDAYS can be used to test that many
11494 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11495 (interactive "P")
11496 (let* ((org-warn-days
11497 (cond
11498 ((equal ndays '(4)) 100000)
11499 (ndays (prefix-numeric-value ndays))
11500 (t (abs org-deadline-warning-days))))
11501 (case-fold-search nil)
11502 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11503 (callback
11504 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11506 (message "%d deadlines past-due or due within %d days"
11507 (org-occur regexp nil callback)
11508 org-warn-days)))
11510 (defun org-check-before-date (date)
11511 "Check if there are deadlines or scheduled entries before DATE."
11512 (interactive (list (org-read-date)))
11513 (let ((case-fold-search nil)
11514 (regexp (concat "\\<\\(" org-deadline-string
11515 "\\|" org-scheduled-string
11516 "\\) *<\\([^>]+\\)>"))
11517 (callback
11518 (lambda () (time-less-p
11519 (org-time-string-to-time (match-string 2))
11520 (org-time-string-to-time date)))))
11521 (message "%d entries before %s"
11522 (org-occur regexp nil callback) date)))
11524 (defun org-evaluate-time-range (&optional to-buffer)
11525 "Evaluate a time range by computing the difference between start and end.
11526 Normally the result is just printed in the echo area, but with prefix arg
11527 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11528 If the time range is actually in a table, the result is inserted into the
11529 next column.
11530 For time difference computation, a year is assumed to be exactly 365
11531 days in order to avoid rounding problems."
11532 (interactive "P")
11534 (org-clock-update-time-maybe)
11535 (save-excursion
11536 (unless (org-at-date-range-p t)
11537 (goto-char (point-at-bol))
11538 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11539 (if (not (org-at-date-range-p t))
11540 (error "Not at a time-stamp range, and none found in current line")))
11541 (let* ((ts1 (match-string 1))
11542 (ts2 (match-string 2))
11543 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11544 (match-end (match-end 0))
11545 (time1 (org-time-string-to-time ts1))
11546 (time2 (org-time-string-to-time ts2))
11547 (t1 (time-to-seconds time1))
11548 (t2 (time-to-seconds time2))
11549 (diff (abs (- t2 t1)))
11550 (negative (< (- t2 t1) 0))
11551 ;; (ys (floor (* 365 24 60 60)))
11552 (ds (* 24 60 60))
11553 (hs (* 60 60))
11554 (fy "%dy %dd %02d:%02d")
11555 (fy1 "%dy %dd")
11556 (fd "%dd %02d:%02d")
11557 (fd1 "%dd")
11558 (fh "%02d:%02d")
11559 y d h m align)
11560 (if havetime
11561 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11563 d (floor (/ diff ds)) diff (mod diff ds)
11564 h (floor (/ diff hs)) diff (mod diff hs)
11565 m (floor (/ diff 60)))
11566 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11568 d (floor (+ (/ diff ds) 0.5))
11569 h 0 m 0))
11570 (if (not to-buffer)
11571 (message "%s" (org-make-tdiff-string y d h m))
11572 (if (org-at-table-p)
11573 (progn
11574 (goto-char match-end)
11575 (setq align t)
11576 (and (looking-at " *|") (goto-char (match-end 0))))
11577 (goto-char match-end))
11578 (if (looking-at
11579 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11580 (replace-match ""))
11581 (if negative (insert " -"))
11582 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11583 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11584 (insert " " (format fh h m))))
11585 (if align (org-table-align))
11586 (message "Time difference inserted")))))
11588 (defun org-make-tdiff-string (y d h m)
11589 (let ((fmt "")
11590 (l nil))
11591 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11592 l (push y l)))
11593 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11594 l (push d l)))
11595 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11596 l (push h l)))
11597 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11598 l (push m l)))
11599 (apply 'format fmt (nreverse l))))
11601 (defun org-time-string-to-time (s)
11602 (apply 'encode-time (org-parse-time-string s)))
11604 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11605 "Convert a time stamp to an absolute day number.
11606 If there is a specifyer for a cyclic time stamp, get the closest date to
11607 DAYNR.
11608 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11609 (cond
11610 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11611 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11612 daynr
11613 (+ daynr 1000)))
11614 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11615 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11616 (time-to-days (current-time))) (match-string 0 s)
11617 prefer show-all))
11618 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11620 (defun org-days-to-iso-week (days)
11621 "Return the iso week number."
11622 (require 'cal-iso)
11623 (car (calendar-iso-from-absolute days)))
11625 (defun org-small-year-to-year (year)
11626 "Convert 2-digit years into 4-digit years.
11627 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11628 The year 2000 cannot be abbreviated. Any year lager than 99
11629 is retrned unchanged."
11630 (if (< year 38)
11631 (setq year (+ 2000 year))
11632 (if (< year 100)
11633 (setq year (+ 1900 year))))
11634 year)
11636 (defun org-time-from-absolute (d)
11637 "Return the time corresponding to date D.
11638 D may be an absolute day number, or a calendar-type list (month day year)."
11639 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11640 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11642 (defun org-calendar-holiday ()
11643 "List of holidays, for Diary display in Org-mode."
11644 (require 'holidays)
11645 (let ((hl (funcall
11646 (if (fboundp 'calendar-check-holidays)
11647 'calendar-check-holidays 'check-calendar-holidays) date)))
11648 (if hl (mapconcat 'identity hl "; "))))
11650 (defun org-diary-sexp-entry (sexp entry date)
11651 "Process a SEXP diary ENTRY for DATE."
11652 (require 'diary-lib)
11653 (let ((result (if calendar-debug-sexp
11654 (let ((stack-trace-on-error t))
11655 (eval (car (read-from-string sexp))))
11656 (condition-case nil
11657 (eval (car (read-from-string sexp)))
11658 (error
11659 (beep)
11660 (message "Bad sexp at line %d in %s: %s"
11661 (org-current-line)
11662 (buffer-file-name) sexp)
11663 (sleep-for 2))))))
11664 (cond ((stringp result) result)
11665 ((and (consp result)
11666 (stringp (cdr result))) (cdr result))
11667 (result entry)
11668 (t nil))))
11670 (defun org-diary-to-ical-string (frombuf)
11671 "Get iCalendar entries from diary entries in buffer FROMBUF.
11672 This uses the icalendar.el library."
11673 (let* ((tmpdir (if (featurep 'xemacs)
11674 (temp-directory)
11675 temporary-file-directory))
11676 (tmpfile (make-temp-name
11677 (expand-file-name "orgics" tmpdir)))
11678 buf rtn b e)
11679 (save-excursion
11680 (set-buffer frombuf)
11681 (icalendar-export-region (point-min) (point-max) tmpfile)
11682 (setq buf (find-buffer-visiting tmpfile))
11683 (set-buffer buf)
11684 (goto-char (point-min))
11685 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11686 (setq b (match-beginning 0)))
11687 (goto-char (point-max))
11688 (if (re-search-backward "^END:VEVENT" nil t)
11689 (setq e (match-end 0)))
11690 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11691 (kill-buffer buf)
11692 (delete-file tmpfile)
11693 rtn))
11695 (defun org-closest-date (start current change prefer show-all)
11696 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11697 When PREFER is `past' return a date that is either CURRENT or past.
11698 When PREFER is `future', return a date that is either CURRENT or future.
11699 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11700 ;; Make the proper lists from the dates
11701 (catch 'exit
11702 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11703 dn dw sday cday n1 n2
11704 d m y y1 y2 date1 date2 nmonths nm ny m2)
11706 (setq start (org-date-to-gregorian start)
11707 current (org-date-to-gregorian
11708 (if show-all
11709 current
11710 (time-to-days (current-time))))
11711 sday (calendar-absolute-from-gregorian start)
11712 cday (calendar-absolute-from-gregorian current))
11714 (if (<= cday sday) (throw 'exit sday))
11716 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11717 (setq dn (string-to-number (match-string 1 change))
11718 dw (cdr (assoc (match-string 2 change) a1)))
11719 (error "Invalid change specifyer: %s" change))
11720 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11721 (cond
11722 ((eq dw 'day)
11723 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11724 n2 (+ n1 dn)))
11725 ((eq dw 'year)
11726 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11727 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11728 (setq date1 (list m d y1)
11729 n1 (calendar-absolute-from-gregorian date1)
11730 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11731 n2 (calendar-absolute-from-gregorian date2)))
11732 ((eq dw 'month)
11733 ;; approx number of month between the two dates
11734 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11735 ;; How often does dn fit in there?
11736 (setq d (nth 1 start) m (car start) y (nth 2 start)
11737 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11738 m (+ m nm)
11739 ny (floor (/ m 12))
11740 y (+ y ny)
11741 m (- m (* ny 12)))
11742 (while (> m 12) (setq m (- m 12) y (1+ y)))
11743 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11744 (setq m2 (+ m dn) y2 y)
11745 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11746 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11747 (while (<= n2 cday)
11748 (setq n1 n2 m m2 y y2)
11749 (setq m2 (+ m dn) y2 y)
11750 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11751 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11752 (if show-all
11753 (cond
11754 ((eq prefer 'past) n1)
11755 ((eq prefer 'future) (if (= cday n1) n1 n2))
11756 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11757 (cond
11758 ((eq prefer 'past) n1)
11759 ((eq prefer 'future) (if (= cday n1) n1 n2))
11760 (t (if (= cday n1) n1 n2)))))))
11762 (defun org-date-to-gregorian (date)
11763 "Turn any specification of DATE into a gregorian date for the calendar."
11764 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11765 ((and (listp date) (= (length date) 3)) date)
11766 ((stringp date)
11767 (setq date (org-parse-time-string date))
11768 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11769 ((listp date)
11770 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11772 (defun org-parse-time-string (s &optional nodefault)
11773 "Parse the standard Org-mode time string.
11774 This should be a lot faster than the normal `parse-time-string'.
11775 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11776 hour and minute fields will be nil if not given."
11777 (if (string-match org-ts-regexp0 s)
11778 (list 0
11779 (if (or (match-beginning 8) (not nodefault))
11780 (string-to-number (or (match-string 8 s) "0")))
11781 (if (or (match-beginning 7) (not nodefault))
11782 (string-to-number (or (match-string 7 s) "0")))
11783 (string-to-number (match-string 4 s))
11784 (string-to-number (match-string 3 s))
11785 (string-to-number (match-string 2 s))
11786 nil nil nil)
11787 (make-list 9 0)))
11789 (defun org-timestamp-up (&optional arg)
11790 "Increase the date item at the cursor by one.
11791 If the cursor is on the year, change the year. If it is on the month or
11792 the day, change that.
11793 With prefix ARG, change by that many units."
11794 (interactive "p")
11795 (org-timestamp-change (prefix-numeric-value arg)))
11797 (defun org-timestamp-down (&optional arg)
11798 "Decrease the date item at the cursor by one.
11799 If the cursor is on the year, change the year. If it is on the month or
11800 the day, change that.
11801 With prefix ARG, change by that many units."
11802 (interactive "p")
11803 (org-timestamp-change (- (prefix-numeric-value arg))))
11805 (defun org-timestamp-up-day (&optional arg)
11806 "Increase the date in the time stamp by one day.
11807 With prefix ARG, change that many days."
11808 (interactive "p")
11809 (if (and (not (org-at-timestamp-p t))
11810 (org-on-heading-p))
11811 (org-todo 'up)
11812 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11814 (defun org-timestamp-down-day (&optional arg)
11815 "Decrease the date in the time stamp by one day.
11816 With prefix ARG, change that many days."
11817 (interactive "p")
11818 (if (and (not (org-at-timestamp-p t))
11819 (org-on-heading-p))
11820 (org-todo 'down)
11821 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11823 (defun org-at-timestamp-p (&optional inactive-ok)
11824 "Determine if the cursor is in or at a timestamp."
11825 (interactive)
11826 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11827 (pos (point))
11828 (ans (or (looking-at tsr)
11829 (save-excursion
11830 (skip-chars-backward "^[<\n\r\t")
11831 (if (> (point) (point-min)) (backward-char 1))
11832 (and (looking-at tsr)
11833 (> (- (match-end 0) pos) -1))))))
11834 (and ans
11835 (boundp 'org-ts-what)
11836 (setq org-ts-what
11837 (cond
11838 ((= pos (match-beginning 0)) 'bracket)
11839 ((= pos (1- (match-end 0))) 'bracket)
11840 ((org-pos-in-match-range pos 2) 'year)
11841 ((org-pos-in-match-range pos 3) 'month)
11842 ((org-pos-in-match-range pos 7) 'hour)
11843 ((org-pos-in-match-range pos 8) 'minute)
11844 ((or (org-pos-in-match-range pos 4)
11845 (org-pos-in-match-range pos 5)) 'day)
11846 ((and (> pos (or (match-end 8) (match-end 5)))
11847 (< pos (match-end 0)))
11848 (- pos (or (match-end 8) (match-end 5))))
11849 (t 'day))))
11850 ans))
11852 (defun org-toggle-timestamp-type ()
11853 "Toggle the type (<active> or [inactive]) of a time stamp."
11854 (interactive)
11855 (when (org-at-timestamp-p t)
11856 (save-excursion
11857 (goto-char (match-beginning 0))
11858 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11859 (goto-char (1- (match-end 0)))
11860 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11861 (message "Timestamp is now %sactive"
11862 (if (equal (char-before) ?>) "in" ""))))
11864 (defun org-timestamp-change (n &optional what)
11865 "Change the date in the time stamp at point.
11866 The date will be changed by N times WHAT. WHAT can be `day', `month',
11867 `year', `minute', `second'. If WHAT is not given, the cursor position
11868 in the timestamp determines what will be changed."
11869 (let ((pos (point))
11870 with-hm inactive
11871 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11872 org-ts-what
11873 extra rem
11874 ts time time0)
11875 (if (not (org-at-timestamp-p t))
11876 (error "Not at a timestamp"))
11877 (if (and (not what) (eq org-ts-what 'bracket))
11878 (org-toggle-timestamp-type)
11879 (if (and (not what) (not (eq org-ts-what 'day))
11880 org-display-custom-times
11881 (get-text-property (point) 'display)
11882 (not (get-text-property (1- (point)) 'display)))
11883 (setq org-ts-what 'day))
11884 (setq org-ts-what (or what org-ts-what)
11885 inactive (= (char-after (match-beginning 0)) ?\[)
11886 ts (match-string 0))
11887 (replace-match "")
11888 (if (string-match
11889 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11891 (setq extra (match-string 1 ts)))
11892 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11893 (setq with-hm t))
11894 (setq time0 (org-parse-time-string ts))
11895 (when (and (eq org-ts-what 'minute)
11896 (eq current-prefix-arg nil))
11897 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11898 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11899 (setcar (cdr time0) (+ (nth 1 time0)
11900 (if (> n 0) (- rem) (- dm rem))))))
11901 (setq time
11902 (encode-time (or (car time0) 0)
11903 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11904 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11905 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11906 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11907 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11908 (nthcdr 6 time0)))
11909 (when (integerp org-ts-what)
11910 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11911 (if (eq what 'calendar)
11912 (let ((cal-date (org-get-date-from-calendar)))
11913 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11914 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11915 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11916 (setcar time0 (or (car time0) 0))
11917 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11918 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11919 (setq time (apply 'encode-time time0))))
11920 (setq org-last-changed-timestamp
11921 (org-insert-time-stamp time with-hm inactive nil nil extra))
11922 (org-clock-update-time-maybe)
11923 (goto-char pos)
11924 ;; Try to recenter the calendar window, if any
11925 (if (and org-calendar-follow-timestamp-change
11926 (get-buffer-window "*Calendar*" t)
11927 (memq org-ts-what '(day month year)))
11928 (org-recenter-calendar (time-to-days time))))))
11930 (defun org-modify-ts-extra (s pos n dm)
11931 "Change the different parts of the lead-time and repeat fields in timestamp."
11932 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11933 ng h m new rem)
11934 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11935 (cond
11936 ((or (org-pos-in-match-range pos 2)
11937 (org-pos-in-match-range pos 3))
11938 (setq m (string-to-number (match-string 3 s))
11939 h (string-to-number (match-string 2 s)))
11940 (if (org-pos-in-match-range pos 2)
11941 (setq h (+ h n))
11942 (setq n (* dm (org-no-warnings (signum n))))
11943 (when (not (= 0 (setq rem (% m dm))))
11944 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11945 (setq m (+ m n)))
11946 (if (< m 0) (setq m (+ m 60) h (1- h)))
11947 (if (> m 59) (setq m (- m 60) h (1+ h)))
11948 (setq h (min 24 (max 0 h)))
11949 (setq ng 1 new (format "-%02d:%02d" h m)))
11950 ((org-pos-in-match-range pos 6)
11951 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11952 ((org-pos-in-match-range pos 5)
11953 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11955 ((org-pos-in-match-range pos 9)
11956 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11957 ((org-pos-in-match-range pos 8)
11958 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11960 (when ng
11961 (setq s (concat
11962 (substring s 0 (match-beginning ng))
11964 (substring s (match-end ng))))))
11967 (defun org-recenter-calendar (date)
11968 "If the calendar is visible, recenter it to DATE."
11969 (let* ((win (selected-window))
11970 (cwin (get-buffer-window "*Calendar*" t))
11971 (calendar-move-hook nil))
11972 (when cwin
11973 (select-window cwin)
11974 (calendar-goto-date (if (listp date) date
11975 (calendar-gregorian-from-absolute date)))
11976 (select-window win))))
11978 (defun org-goto-calendar (&optional arg)
11979 "Go to the Emacs calendar at the current date.
11980 If there is a time stamp in the current line, go to that date.
11981 A prefix ARG can be used to force the current date."
11982 (interactive "P")
11983 (let ((tsr org-ts-regexp) diff
11984 (calendar-move-hook nil)
11985 (calendar-view-holidays-initially-flag nil)
11986 (view-calendar-holidays-initially nil)
11987 (calendar-view-diary-initially-flag nil)
11988 (view-diary-entries-initially nil))
11989 (if (or (org-at-timestamp-p)
11990 (save-excursion
11991 (beginning-of-line 1)
11992 (looking-at (concat ".*" tsr))))
11993 (let ((d1 (time-to-days (current-time)))
11994 (d2 (time-to-days
11995 (org-time-string-to-time (match-string 1)))))
11996 (setq diff (- d2 d1))))
11997 (calendar)
11998 (calendar-goto-today)
11999 (if (and diff (not arg)) (calendar-forward-day diff))))
12001 (defun org-get-date-from-calendar ()
12002 "Return a list (month day year) of date at point in calendar."
12003 (with-current-buffer "*Calendar*"
12004 (save-match-data
12005 (calendar-cursor-to-date))))
12007 (defun org-date-from-calendar ()
12008 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12009 If there is already a time stamp at the cursor position, update it."
12010 (interactive)
12011 (if (org-at-timestamp-p t)
12012 (org-timestamp-change 0 'calendar)
12013 (let ((cal-date (org-get-date-from-calendar)))
12014 (org-insert-time-stamp
12015 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12017 (defun org-minutes-to-hh:mm-string (m)
12018 "Compute H:MM from a number of minutes."
12019 (let ((h (/ m 60)))
12020 (setq m (- m (* 60 h)))
12021 (format org-time-clocksum-format h m)))
12023 (defun org-hh:mm-string-to-minutes (s)
12024 "Convert a string H:MM to a number of minutes."
12025 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12026 (+ (* (string-to-number (match-string 1 s)) 60)
12027 (string-to-number (match-string 2 s)))
12030 ;;;; Agenda files
12032 ;;;###autoload
12033 (defun org-iswitchb (&optional arg)
12034 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12035 With a prefix argument, restrict available to files.
12036 With two prefix arguments, restrict available buffers to agenda files.
12038 Due to some yet unresolved reason, the global function
12039 `iswitchb-mode' needs to be active for this function to work."
12040 (interactive "P")
12041 (require 'iswitchb)
12042 (let ((enabled iswitchb-mode) blist)
12043 (or enabled (iswitchb-mode 1))
12044 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12045 ((equal arg '(16)) (org-buffer-list 'agenda))
12046 (t (org-buffer-list))))
12047 (unwind-protect
12048 (let ((iswitchb-make-buflist-hook
12049 (lambda ()
12050 (setq iswitchb-temp-buflist
12051 (mapcar 'buffer-name blist)))))
12052 (switch-to-buffer
12053 (iswitchb-read-buffer
12054 "Switch-to: " nil t))
12055 (or enabled (iswitchb-mode -1))))))
12057 (defun org-buffer-list (&optional predicate exclude-tmp)
12058 "Return a list of Org buffers.
12059 PREDICATE can be `export', `files' or `agenda'.
12061 export restrict the list to Export buffers.
12062 files restrict the list to buffers visiting Org files.
12063 agenda restrict the list to buffers visiting agenda files.
12065 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12066 (let* ((bfn nil)
12067 (agenda-files (and (eq predicate 'agenda)
12068 (mapcar 'file-truename (org-agenda-files t))))
12069 (filter
12070 (cond
12071 ((eq predicate 'files)
12072 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12073 ((eq predicate 'export)
12074 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12075 ((eq predicate 'agenda)
12076 (lambda (b)
12077 (with-current-buffer b
12078 (and (eq major-mode 'org-mode)
12079 (setq bfn (buffer-file-name b))
12080 (member (file-truename bfn) agenda-files)))))
12081 (t (lambda (b) (with-current-buffer b
12082 (or (eq major-mode 'org-mode)
12083 (string-match "\*Org .*Export"
12084 (buffer-name b)))))))))
12085 (delq nil
12086 (mapcar
12087 (lambda(b)
12088 (if (and (funcall filter b)
12089 (or (not exclude-tmp)
12090 (not (string-match "tmp" (buffer-name b)))))
12092 nil))
12093 (buffer-list)))))
12095 (defun org-agenda-files (&optional unrestricted archives)
12096 "Get the list of agenda files.
12097 Optional UNRESTRICTED means return the full list even if a restriction
12098 is currently in place.
12099 When ARCHIVES is t, include all archive files hat are really being
12100 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12101 `org-agenda-archives-mode' is t."
12102 (let ((files
12103 (cond
12104 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12105 ((stringp org-agenda-files) (org-read-agenda-file-list))
12106 ((listp org-agenda-files) org-agenda-files)
12107 (t (error "Invalid value of `org-agenda-files'")))))
12108 (setq files (apply 'append
12109 (mapcar (lambda (f)
12110 (if (file-directory-p f)
12111 (directory-files
12112 f t org-agenda-file-regexp)
12113 (list f)))
12114 files)))
12115 (when org-agenda-skip-unavailable-files
12116 (setq files (delq nil
12117 (mapcar (function
12118 (lambda (file)
12119 (and (file-readable-p file) file)))
12120 files))))
12121 (when (or (eq archives t)
12122 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12123 (setq files (org-add-archive-files files)))
12124 files))
12126 (defun org-edit-agenda-file-list ()
12127 "Edit the list of agenda files.
12128 Depending on setup, this either uses customize to edit the variable
12129 `org-agenda-files', or it visits the file that is holding the list. In the
12130 latter case, the buffer is set up in a way that saving it automatically kills
12131 the buffer and restores the previous window configuration."
12132 (interactive)
12133 (if (stringp org-agenda-files)
12134 (let ((cw (current-window-configuration)))
12135 (find-file org-agenda-files)
12136 (org-set-local 'org-window-configuration cw)
12137 (org-add-hook 'after-save-hook
12138 (lambda ()
12139 (set-window-configuration
12140 (prog1 org-window-configuration
12141 (kill-buffer (current-buffer))))
12142 (org-install-agenda-files-menu)
12143 (message "New agenda file list installed"))
12144 nil 'local)
12145 (message "%s" (substitute-command-keys
12146 "Edit list and finish with \\[save-buffer]")))
12147 (customize-variable 'org-agenda-files)))
12149 (defun org-store-new-agenda-file-list (list)
12150 "Set new value for the agenda file list and save it correcly."
12151 (if (stringp org-agenda-files)
12152 (let ((f org-agenda-files) b)
12153 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12154 (with-temp-file f
12155 (insert (mapconcat 'identity list "\n") "\n")))
12156 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12157 (setq org-agenda-files list)
12158 (customize-save-variable 'org-agenda-files org-agenda-files))))
12160 (defun org-read-agenda-file-list ()
12161 "Read the list of agenda files from a file."
12162 (when (file-directory-p org-agenda-files)
12163 (error "`org-agenda-files' cannot be a single directory"))
12164 (when (stringp org-agenda-files)
12165 (with-temp-buffer
12166 (insert-file-contents org-agenda-files)
12167 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12170 ;;;###autoload
12171 (defun org-cycle-agenda-files ()
12172 "Cycle through the files in `org-agenda-files'.
12173 If the current buffer visits an agenda file, find the next one in the list.
12174 If the current buffer does not, find the first agenda file."
12175 (interactive)
12176 (let* ((fs (org-agenda-files t))
12177 (files (append fs (list (car fs))))
12178 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12179 file)
12180 (unless files (error "No agenda files"))
12181 (catch 'exit
12182 (while (setq file (pop files))
12183 (if (equal (file-truename file) tcf)
12184 (when (car files)
12185 (find-file (car files))
12186 (throw 'exit t))))
12187 (find-file (car fs)))
12188 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12190 (defun org-agenda-file-to-front (&optional to-end)
12191 "Move/add the current file to the top of the agenda file list.
12192 If the file is not present in the list, it is added to the front. If it is
12193 present, it is moved there. With optional argument TO-END, add/move to the
12194 end of the list."
12195 (interactive "P")
12196 (let ((org-agenda-skip-unavailable-files nil)
12197 (file-alist (mapcar (lambda (x)
12198 (cons (file-truename x) x))
12199 (org-agenda-files t)))
12200 (ctf (file-truename buffer-file-name))
12201 x had)
12202 (setq x (assoc ctf file-alist) had x)
12204 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12205 (if to-end
12206 (setq file-alist (append (delq x file-alist) (list x)))
12207 (setq file-alist (cons x (delq x file-alist))))
12208 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12209 (org-install-agenda-files-menu)
12210 (message "File %s to %s of agenda file list"
12211 (if had "moved" "added") (if to-end "end" "front"))))
12213 (defun org-remove-file (&optional file)
12214 "Remove current file from the list of files in variable `org-agenda-files'.
12215 These are the files which are being checked for agenda entries.
12216 Optional argument FILE means, use this file instead of the current."
12217 (interactive)
12218 (let* ((org-agenda-skip-unavailable-files nil)
12219 (file (or file buffer-file-name))
12220 (true-file (file-truename file))
12221 (afile (abbreviate-file-name file))
12222 (files (delq nil (mapcar
12223 (lambda (x)
12224 (if (equal true-file
12225 (file-truename x))
12226 nil x))
12227 (org-agenda-files t)))))
12228 (if (not (= (length files) (length (org-agenda-files t))))
12229 (progn
12230 (org-store-new-agenda-file-list files)
12231 (org-install-agenda-files-menu)
12232 (message "Removed file: %s" afile))
12233 (message "File was not in list: %s (not removed)" afile))))
12235 (defun org-file-menu-entry (file)
12236 (vector file (list 'find-file file) t))
12238 (defun org-check-agenda-file (file)
12239 "Make sure FILE exists. If not, ask user what to do."
12240 (when (not (file-exists-p file))
12241 (message "non-existent file %s. [R]emove from list or [A]bort?"
12242 (abbreviate-file-name file))
12243 (let ((r (downcase (read-char-exclusive))))
12244 (cond
12245 ((equal r ?r)
12246 (org-remove-file file)
12247 (throw 'nextfile t))
12248 (t (error "Abort"))))))
12250 (defun org-get-agenda-file-buffer (file)
12251 "Get a buffer visiting FILE. If the buffer needs to be created, add
12252 it to the list of buffers which might be released later."
12253 (let ((buf (org-find-base-buffer-visiting file)))
12254 (if buf
12255 buf ; just return it
12256 ;; Make a new buffer and remember it
12257 (setq buf (find-file-noselect file))
12258 (if buf (push buf org-agenda-new-buffers))
12259 buf)))
12261 (defun org-release-buffers (blist)
12262 "Release all buffers in list, asking the user for confirmation when needed.
12263 When a buffer is unmodified, it is just killed. When modified, it is saved
12264 \(if the user agrees) and then killed."
12265 (let (buf file)
12266 (while (setq buf (pop blist))
12267 (setq file (buffer-file-name buf))
12268 (when (and (buffer-modified-p buf)
12269 file
12270 (y-or-n-p (format "Save file %s? " file)))
12271 (with-current-buffer buf (save-buffer)))
12272 (kill-buffer buf))))
12274 (defun org-prepare-agenda-buffers (files)
12275 "Create buffers for all agenda files, protect archived trees and comments."
12276 (interactive)
12277 (let ((pa '(:org-archived t))
12278 (pc '(:org-comment t))
12279 (pall '(:org-archived t :org-comment t))
12280 (inhibit-read-only t)
12281 (rea (concat ":" org-archive-tag ":"))
12282 bmp file re)
12283 (save-excursion
12284 (save-restriction
12285 (while (setq file (pop files))
12286 (if (bufferp file)
12287 (set-buffer file)
12288 (org-check-agenda-file file)
12289 (set-buffer (org-get-agenda-file-buffer file)))
12290 (widen)
12291 (setq bmp (buffer-modified-p))
12292 (org-refresh-category-properties)
12293 (setq org-todo-keywords-for-agenda
12294 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12295 (setq org-done-keywords-for-agenda
12296 (append org-done-keywords-for-agenda org-done-keywords))
12297 (setq org-todo-keyword-alist-for-agenda
12298 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12299 (setq org-tag-alist-for-agenda
12300 (append org-tag-alist-for-agenda org-tag-alist))
12302 (save-excursion
12303 (remove-text-properties (point-min) (point-max) pall)
12304 (when org-agenda-skip-archived-trees
12305 (goto-char (point-min))
12306 (while (re-search-forward rea nil t)
12307 (if (org-on-heading-p t)
12308 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12309 (goto-char (point-min))
12310 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12311 (while (re-search-forward re nil t)
12312 (add-text-properties
12313 (match-beginning 0) (org-end-of-subtree t) pc)))
12314 (set-buffer-modified-p bmp))))
12315 (setq org-todo-keyword-alist-for-agenda
12316 (org-uniquify org-todo-keyword-alist-for-agenda)
12317 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12319 ;;;; Embedded LaTeX
12321 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12322 "Keymap for the minor `org-cdlatex-mode'.")
12324 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12325 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12326 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12327 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12328 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12330 (defvar org-cdlatex-texmathp-advice-is-done nil
12331 "Flag remembering if we have applied the advice to texmathp already.")
12333 (define-minor-mode org-cdlatex-mode
12334 "Toggle the minor `org-cdlatex-mode'.
12335 This mode supports entering LaTeX environment and math in LaTeX fragments
12336 in Org-mode.
12337 \\{org-cdlatex-mode-map}"
12338 nil " OCDL" nil
12339 (when org-cdlatex-mode (require 'cdlatex))
12340 (unless org-cdlatex-texmathp-advice-is-done
12341 (setq org-cdlatex-texmathp-advice-is-done t)
12342 (defadvice texmathp (around org-math-always-on activate)
12343 "Always return t in org-mode buffers.
12344 This is because we want to insert math symbols without dollars even outside
12345 the LaTeX math segments. If Orgmode thinks that point is actually inside
12346 en embedded LaTeX fragement, let texmathp do its job.
12347 \\[org-cdlatex-mode-map]"
12348 (interactive)
12349 (let (p)
12350 (cond
12351 ((not (org-mode-p)) ad-do-it)
12352 ((eq this-command 'cdlatex-math-symbol)
12353 (setq ad-return-value t
12354 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12356 (let ((p (org-inside-LaTeX-fragment-p)))
12357 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12358 (setq ad-return-value t
12359 texmathp-why '("Org-mode embedded math" . 0))
12360 (if p ad-do-it)))))))))
12362 (defun turn-on-org-cdlatex ()
12363 "Unconditionally turn on `org-cdlatex-mode'."
12364 (org-cdlatex-mode 1))
12366 (defun org-inside-LaTeX-fragment-p ()
12367 "Test if point is inside a LaTeX fragment.
12368 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12369 sequence appearing also before point.
12370 Even though the matchers for math are configurable, this function assumes
12371 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12372 delimiters are skipped when they have been removed by customization.
12373 The return value is nil, or a cons cell with the delimiter and
12374 and the position of this delimiter.
12376 This function does a reasonably good job, but can locally be fooled by
12377 for example currency specifications. For example it will assume being in
12378 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12379 fragments that are properly closed, but during editing, we have to live
12380 with the uncertainty caused by missing closing delimiters. This function
12381 looks only before point, not after."
12382 (catch 'exit
12383 (let ((pos (point))
12384 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12385 (lim (progn
12386 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12387 (point)))
12388 dd-on str (start 0) m re)
12389 (goto-char pos)
12390 (when dodollar
12391 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12392 re (nth 1 (assoc "$" org-latex-regexps)))
12393 (while (string-match re str start)
12394 (cond
12395 ((= (match-end 0) (length str))
12396 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12397 ((= (match-end 0) (- (length str) 5))
12398 (throw 'exit nil))
12399 (t (setq start (match-end 0))))))
12400 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12401 (goto-char pos)
12402 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12403 (and (match-beginning 2) (throw 'exit nil))
12404 ;; count $$
12405 (while (re-search-backward "\\$\\$" lim t)
12406 (setq dd-on (not dd-on)))
12407 (goto-char pos)
12408 (if dd-on (cons "$$" m))))))
12411 (defun org-try-cdlatex-tab ()
12412 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12413 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12414 - inside a LaTeX fragment, or
12415 - after the first word in a line, where an abbreviation expansion could
12416 insert a LaTeX environment."
12417 (when org-cdlatex-mode
12418 (cond
12419 ((save-excursion
12420 (skip-chars-backward "a-zA-Z0-9*")
12421 (skip-chars-backward " \t")
12422 (bolp))
12423 (cdlatex-tab) t)
12424 ((org-inside-LaTeX-fragment-p)
12425 (cdlatex-tab) t)
12426 (t nil))))
12428 (defun org-cdlatex-underscore-caret (&optional arg)
12429 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12430 Revert to the normal definition outside of these fragments."
12431 (interactive "P")
12432 (if (org-inside-LaTeX-fragment-p)
12433 (call-interactively 'cdlatex-sub-superscript)
12434 (let (org-cdlatex-mode)
12435 (call-interactively (key-binding (vector last-input-event))))))
12437 (defun org-cdlatex-math-modify (&optional arg)
12438 "Execute `cdlatex-math-modify' in LaTeX fragments.
12439 Revert to the normal definition outside of these fragments."
12440 (interactive "P")
12441 (if (org-inside-LaTeX-fragment-p)
12442 (call-interactively 'cdlatex-math-modify)
12443 (let (org-cdlatex-mode)
12444 (call-interactively (key-binding (vector last-input-event))))))
12446 (defvar org-latex-fragment-image-overlays nil
12447 "List of overlays carrying the images of latex fragments.")
12448 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12450 (defun org-remove-latex-fragment-image-overlays ()
12451 "Remove all overlays with LaTeX fragment images in current buffer."
12452 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12453 (setq org-latex-fragment-image-overlays nil))
12455 (defun org-preview-latex-fragment (&optional subtree)
12456 "Preview the LaTeX fragment at point, or all locally or globally.
12457 If the cursor is in a LaTeX fragment, create the image and overlay
12458 it over the source code. If there is no fragment at point, display
12459 all fragments in the current text, from one headline to the next. With
12460 prefix SUBTREE, display all fragments in the current subtree. With a
12461 double prefix `C-u C-u', or when the cursor is before the first headline,
12462 display all fragments in the buffer.
12463 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12464 (interactive "P")
12465 (org-remove-latex-fragment-image-overlays)
12466 (save-excursion
12467 (save-restriction
12468 (let (beg end at msg)
12469 (cond
12470 ((or (equal subtree '(16))
12471 (not (save-excursion
12472 (re-search-backward (concat "^" outline-regexp) nil t))))
12473 (setq beg (point-min) end (point-max)
12474 msg "Creating images for buffer...%s"))
12475 ((equal subtree '(4))
12476 (org-back-to-heading)
12477 (setq beg (point) end (org-end-of-subtree t)
12478 msg "Creating images for subtree...%s"))
12480 (if (setq at (org-inside-LaTeX-fragment-p))
12481 (goto-char (max (point-min) (- (cdr at) 2)))
12482 (org-back-to-heading))
12483 (setq beg (point) end (progn (outline-next-heading) (point))
12484 msg (if at "Creating image...%s"
12485 "Creating images for entry...%s"))))
12486 (message msg "")
12487 (narrow-to-region beg end)
12488 (goto-char beg)
12489 (org-format-latex
12490 (concat "ltxpng/" (file-name-sans-extension
12491 (file-name-nondirectory
12492 buffer-file-name)))
12493 default-directory 'overlays msg at 'forbuffer)
12494 (message msg "done. Use `C-c C-c' to remove images.")))))
12496 (defvar org-latex-regexps
12497 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12498 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12499 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12500 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12501 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12502 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12503 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12504 "Regular expressions for matching embedded LaTeX.")
12506 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12507 "Replace LaTeX fragments with links to an image, and produce images."
12508 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12509 (let* ((prefixnodir (file-name-nondirectory prefix))
12510 (absprefix (expand-file-name prefix dir))
12511 (todir (file-name-directory absprefix))
12512 (opt org-format-latex-options)
12513 (matchers (plist-get opt :matchers))
12514 (re-list org-latex-regexps)
12515 (cnt 0) txt link beg end re e checkdir
12516 m n block linkfile movefile ov)
12517 ;; Check if there are old images files with this prefix, and remove them
12518 (when (file-directory-p todir)
12519 (mapc 'delete-file
12520 (directory-files
12521 todir 'full
12522 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12523 ;; Check the different regular expressions
12524 (while (setq e (pop re-list))
12525 (setq m (car e) re (nth 1 e) n (nth 2 e)
12526 block (if (nth 3 e) "\n\n" ""))
12527 (when (member m matchers)
12528 (goto-char (point-min))
12529 (while (re-search-forward re nil t)
12530 (when (or (not at) (equal (cdr at) (match-beginning n)))
12531 (setq txt (match-string n)
12532 beg (match-beginning n) end (match-end n)
12533 cnt (1+ cnt)
12534 linkfile (format "%s_%04d.png" prefix cnt)
12535 movefile (format "%s_%04d.png" absprefix cnt)
12536 link (concat block "[[file:" linkfile "]]" block))
12537 (if msg (message msg cnt))
12538 (goto-char beg)
12539 (unless checkdir ; make sure the directory exists
12540 (setq checkdir t)
12541 (or (file-directory-p todir) (make-directory todir)))
12542 (org-create-formula-image
12543 txt movefile opt forbuffer)
12544 (if overlays
12545 (progn
12546 (setq ov (org-make-overlay beg end))
12547 (if (featurep 'xemacs)
12548 (progn
12549 (org-overlay-put ov 'invisible t)
12550 (org-overlay-put
12551 ov 'end-glyph
12552 (make-glyph (vector 'png :file movefile))))
12553 (org-overlay-put
12554 ov 'display
12555 (list 'image :type 'png :file movefile :ascent 'center)))
12556 (push ov org-latex-fragment-image-overlays)
12557 (goto-char end))
12558 (delete-region beg end)
12559 (insert link))))))))
12561 ;; This function borrows from Ganesh Swami's latex2png.el
12562 (defun org-create-formula-image (string tofile options buffer)
12563 (let* ((tmpdir (if (featurep 'xemacs)
12564 (temp-directory)
12565 temporary-file-directory))
12566 (texfilebase (make-temp-name
12567 (expand-file-name "orgtex" tmpdir)))
12568 (texfile (concat texfilebase ".tex"))
12569 (dvifile (concat texfilebase ".dvi"))
12570 (pngfile (concat texfilebase ".png"))
12571 (fnh (if (featurep 'xemacs)
12572 (font-height (get-face-font 'default))
12573 (face-attribute 'default :height nil)))
12574 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12575 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12576 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12577 "Black"))
12578 (bg (or (plist-get options (if buffer :background :html-background))
12579 "Transparent")))
12580 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12581 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12582 (with-temp-file texfile
12583 (insert org-format-latex-header
12584 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12585 (let ((dir default-directory))
12586 (condition-case nil
12587 (progn
12588 (cd tmpdir)
12589 (call-process "latex" nil nil nil texfile))
12590 (error nil))
12591 (cd dir))
12592 (if (not (file-exists-p dvifile))
12593 (progn (message "Failed to create dvi file from %s" texfile) nil)
12594 (condition-case nil
12595 (call-process "dvipng" nil nil nil
12596 "-E" "-fg" fg "-bg" bg
12597 "-D" dpi
12598 ;;"-x" scale "-y" scale
12599 "-T" "tight"
12600 "-o" pngfile
12601 dvifile)
12602 (error nil))
12603 (if (not (file-exists-p pngfile))
12604 (progn (message "Failed to create png file from %s" texfile) nil)
12605 ;; Use the requested file name and clean up
12606 (copy-file pngfile tofile 'replace)
12607 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12608 (delete-file (concat texfilebase e)))
12609 pngfile))))
12611 (defun org-dvipng-color (attr)
12612 "Return an rgb color specification for dvipng."
12613 (apply 'format "rgb %s %s %s"
12614 (mapcar 'org-normalize-color
12615 (color-values (face-attribute 'default attr nil)))))
12617 (defun org-normalize-color (value)
12618 "Return string to be used as color value for an RGB component."
12619 (format "%g" (/ value 65535.0)))
12622 ;;;; Key bindings
12624 ;; Make `C-c C-x' a prefix key
12625 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12627 ;; TAB key with modifiers
12628 (org-defkey org-mode-map "\C-i" 'org-cycle)
12629 (org-defkey org-mode-map [(tab)] 'org-cycle)
12630 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12631 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12632 (org-defkey org-mode-map "\M-\t" 'org-complete)
12633 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12634 ;; The following line is necessary under Suse GNU/Linux
12635 (unless (featurep 'xemacs)
12636 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12637 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12638 (define-key org-mode-map [backtab] 'org-shifttab)
12640 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12641 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12642 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12644 ;; Cursor keys with modifiers
12645 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12646 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12647 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12648 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12650 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12651 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12652 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12653 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12655 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12656 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12657 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12658 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12660 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12661 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12663 ;;; Extra keys for tty access.
12664 ;; We only set them when really needed because otherwise the
12665 ;; menus don't show the simple keys
12667 (when (or org-use-extra-keys
12668 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12669 (not window-system))
12670 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12671 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12672 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12673 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12674 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12675 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12676 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12677 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12678 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12679 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12680 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12681 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12682 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12683 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12684 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12685 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12686 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12687 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12688 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12689 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12690 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12691 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12693 ;; All the other keys
12695 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12696 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12697 (if (boundp 'narrow-map)
12698 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12699 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12700 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12701 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12702 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12703 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12704 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12705 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12706 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12707 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12708 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12709 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12710 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12711 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12712 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12713 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12714 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12715 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12716 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12717 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12718 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12719 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12720 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12721 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12722 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12723 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12724 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12725 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12726 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12727 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12728 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12729 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12730 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12731 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12732 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12733 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12734 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12735 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12736 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12737 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12738 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12739 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12740 (org-defkey org-mode-map "\C-c^" 'org-sort)
12741 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12742 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12743 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12744 (org-defkey org-mode-map "\C-m" 'org-return)
12745 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12746 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12747 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12748 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12749 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12750 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12751 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12752 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12753 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12754 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12755 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12756 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12757 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12758 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12759 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12760 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12762 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12763 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12764 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12765 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12767 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12768 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12769 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12770 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12771 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12772 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12773 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12774 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12775 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12776 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12777 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12778 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12780 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12782 (when (featurep 'xemacs)
12783 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12785 (defvar org-table-auto-blank-field) ; defined in org-table.el
12786 (defun org-self-insert-command (N)
12787 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12788 If the cursor is in a table looking at whitespace, the whitespace is
12789 overwritten, and the table is not marked as requiring realignment."
12790 (interactive "p")
12791 (if (and (org-table-p)
12792 (progn
12793 ;; check if we blank the field, and if that triggers align
12794 (and (featurep 'org-table) org-table-auto-blank-field
12795 (member last-command
12796 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12797 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12798 ;; got extra space, this field does not determine column width
12799 (let (org-table-may-need-update) (org-table-blank-field))
12800 ;; no extra space, this field may determine column width
12801 (org-table-blank-field)))
12803 (eq N 1)
12804 (looking-at "[^|\n]* |"))
12805 (let (org-table-may-need-update)
12806 (goto-char (1- (match-end 0)))
12807 (delete-backward-char 1)
12808 (goto-char (match-beginning 0))
12809 (self-insert-command N))
12810 (setq org-table-may-need-update t)
12811 (self-insert-command N)
12812 (org-fix-tags-on-the-fly)))
12814 (defun org-fix-tags-on-the-fly ()
12815 (when (and (equal (char-after (point-at-bol)) ?*)
12816 (org-on-heading-p))
12817 (org-align-tags-here org-tags-column)))
12819 (defun org-delete-backward-char (N)
12820 "Like `delete-backward-char', insert whitespace at field end in tables.
12821 When deleting backwards, in tables this function will insert whitespace in
12822 front of the next \"|\" separator, to keep the table aligned. The table will
12823 still be marked for re-alignment if the field did fill the entire column,
12824 because, in this case the deletion might narrow the column."
12825 (interactive "p")
12826 (if (and (org-table-p)
12827 (eq N 1)
12828 (string-match "|" (buffer-substring (point-at-bol) (point)))
12829 (looking-at ".*?|"))
12830 (let ((pos (point))
12831 (noalign (looking-at "[^|\n\r]* |"))
12832 (c org-table-may-need-update))
12833 (backward-delete-char N)
12834 (skip-chars-forward "^|")
12835 (insert " ")
12836 (goto-char (1- pos))
12837 ;; noalign: if there were two spaces at the end, this field
12838 ;; does not determine the width of the column.
12839 (if noalign (setq org-table-may-need-update c)))
12840 (backward-delete-char N)
12841 (org-fix-tags-on-the-fly)))
12843 (defun org-delete-char (N)
12844 "Like `delete-char', but insert whitespace at field end in tables.
12845 When deleting characters, in tables this function will insert whitespace in
12846 front of the next \"|\" separator, to keep the table aligned. The table will
12847 still be marked for re-alignment if the field did fill the entire column,
12848 because, in this case the deletion might narrow the column."
12849 (interactive "p")
12850 (if (and (org-table-p)
12851 (not (bolp))
12852 (not (= (char-after) ?|))
12853 (eq N 1))
12854 (if (looking-at ".*?|")
12855 (let ((pos (point))
12856 (noalign (looking-at "[^|\n\r]* |"))
12857 (c org-table-may-need-update))
12858 (replace-match (concat
12859 (substring (match-string 0) 1 -1)
12860 " |"))
12861 (goto-char pos)
12862 ;; noalign: if there were two spaces at the end, this field
12863 ;; does not determine the width of the column.
12864 (if noalign (setq org-table-may-need-update c)))
12865 (delete-char N))
12866 (delete-char N)
12867 (org-fix-tags-on-the-fly)))
12869 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12870 (put 'org-self-insert-command 'delete-selection t)
12871 (put 'orgtbl-self-insert-command 'delete-selection t)
12872 (put 'org-delete-char 'delete-selection 'supersede)
12873 (put 'org-delete-backward-char 'delete-selection 'supersede)
12875 ;; Make `flyspell-mode' delay after some commands
12876 (put 'org-self-insert-command 'flyspell-delayed t)
12877 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12878 (put 'org-delete-char 'flyspell-delayed t)
12879 (put 'org-delete-backward-char 'flyspell-delayed t)
12881 ;; Make pabbrev-mode expand after org-mode commands
12882 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12883 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12885 ;; How to do this: Measure non-white length of current string
12886 ;; If equal to column width, we should realign.
12888 (defun org-remap (map &rest commands)
12889 "In MAP, remap the functions given in COMMANDS.
12890 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12891 (let (new old)
12892 (while commands
12893 (setq old (pop commands) new (pop commands))
12894 (if (fboundp 'command-remapping)
12895 (org-defkey map (vector 'remap old) new)
12896 (substitute-key-definition old new map global-map)))))
12898 (when (eq org-enable-table-editor 'optimized)
12899 ;; If the user wants maximum table support, we need to hijack
12900 ;; some standard editing functions
12901 (org-remap org-mode-map
12902 'self-insert-command 'org-self-insert-command
12903 'delete-char 'org-delete-char
12904 'delete-backward-char 'org-delete-backward-char)
12905 (org-defkey org-mode-map "|" 'org-force-self-insert))
12907 (defun org-shiftcursor-error ()
12908 "Throw an error because Shift-Cursor command was applied in wrong context."
12909 (error "This command is active in special context like tables, headlines or timestamps"))
12911 (defun org-shifttab (&optional arg)
12912 "Global visibility cycling or move to previous table field.
12913 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12914 on context.
12915 See the individual commands for more information."
12916 (interactive "P")
12917 (cond
12918 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12919 ((integerp arg)
12920 (message "Content view to level: %d" arg)
12921 (org-content (prefix-numeric-value arg))
12922 (setq org-cycle-global-status 'overview))
12923 (t (call-interactively 'org-global-cycle))))
12925 (defun org-shiftmetaleft ()
12926 "Promote subtree or delete table column.
12927 Calls `org-promote-subtree', `org-outdent-item',
12928 or `org-table-delete-column', depending on context.
12929 See the individual commands for more information."
12930 (interactive)
12931 (cond
12932 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12933 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12934 ((org-at-item-p) (call-interactively 'org-outdent-item))
12935 (t (org-shiftcursor-error))))
12937 (defun org-shiftmetaright ()
12938 "Demote subtree or insert table column.
12939 Calls `org-demote-subtree', `org-indent-item',
12940 or `org-table-insert-column', depending on context.
12941 See the individual commands for more information."
12942 (interactive)
12943 (cond
12944 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12945 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12946 ((org-at-item-p) (call-interactively 'org-indent-item))
12947 (t (org-shiftcursor-error))))
12949 (defun org-shiftmetaup (&optional arg)
12950 "Move subtree up or kill table row.
12951 Calls `org-move-subtree-up' or `org-table-kill-row' or
12952 `org-move-item-up' depending on context. See the individual commands
12953 for more information."
12954 (interactive "P")
12955 (cond
12956 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12957 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12958 ((org-at-item-p) (call-interactively 'org-move-item-up))
12959 (t (org-shiftcursor-error))))
12960 (defun org-shiftmetadown (&optional arg)
12961 "Move subtree down or insert table row.
12962 Calls `org-move-subtree-down' or `org-table-insert-row' or
12963 `org-move-item-down', depending on context. See the individual
12964 commands for more information."
12965 (interactive "P")
12966 (cond
12967 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12968 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12969 ((org-at-item-p) (call-interactively 'org-move-item-down))
12970 (t (org-shiftcursor-error))))
12972 (defun org-metaleft (&optional arg)
12973 "Promote heading or move table column to left.
12974 Calls `org-do-promote' or `org-table-move-column', depending on context.
12975 With no specific context, calls the Emacs default `backward-word'.
12976 See the individual commands for more information."
12977 (interactive "P")
12978 (cond
12979 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12980 ((or (org-on-heading-p) (org-region-active-p))
12981 (call-interactively 'org-do-promote))
12982 ((org-at-item-p) (call-interactively 'org-outdent-item))
12983 (t (call-interactively 'backward-word))))
12985 (defun org-metaright (&optional arg)
12986 "Demote subtree or move table column to right.
12987 Calls `org-do-demote' or `org-table-move-column', depending on context.
12988 With no specific context, calls the Emacs default `forward-word'.
12989 See the individual commands for more information."
12990 (interactive "P")
12991 (cond
12992 ((org-at-table-p) (call-interactively 'org-table-move-column))
12993 ((or (org-on-heading-p) (org-region-active-p))
12994 (call-interactively 'org-do-demote))
12995 ((org-at-item-p) (call-interactively 'org-indent-item))
12996 (t (call-interactively 'forward-word))))
12998 (defun org-metaup (&optional arg)
12999 "Move subtree up or move table row up.
13000 Calls `org-move-subtree-up' or `org-table-move-row' or
13001 `org-move-item-up', depending on context. See the individual commands
13002 for more information."
13003 (interactive "P")
13004 (cond
13005 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13006 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13007 ((org-at-item-p) (call-interactively 'org-move-item-up))
13008 (t (transpose-lines 1) (beginning-of-line -1))))
13010 (defun org-metadown (&optional arg)
13011 "Move subtree down or move table row down.
13012 Calls `org-move-subtree-down' or `org-table-move-row' or
13013 `org-move-item-down', depending on context. See the individual
13014 commands for more information."
13015 (interactive "P")
13016 (cond
13017 ((org-at-table-p) (call-interactively 'org-table-move-row))
13018 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13019 ((org-at-item-p) (call-interactively 'org-move-item-down))
13020 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13022 (defun org-shiftup (&optional arg)
13023 "Increase item in timestamp or increase priority of current headline.
13024 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13025 depending on context. See the individual commands for more information."
13026 (interactive "P")
13027 (cond
13028 ((org-at-timestamp-p t)
13029 (call-interactively (if org-edit-timestamp-down-means-later
13030 'org-timestamp-down 'org-timestamp-up)))
13031 ((org-on-heading-p) (call-interactively 'org-priority-up))
13032 ((org-at-item-p) (call-interactively 'org-previous-item))
13033 ((org-clocktable-try-shift 'up arg))
13034 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13036 (defun org-shiftdown (&optional arg)
13037 "Decrease item in timestamp or decrease priority of current headline.
13038 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13039 depending on context. See the individual commands for more information."
13040 (interactive "P")
13041 (cond
13042 ((org-at-timestamp-p t)
13043 (call-interactively (if org-edit-timestamp-down-means-later
13044 'org-timestamp-up 'org-timestamp-down)))
13045 ((org-on-heading-p) (call-interactively 'org-priority-down))
13046 ((org-clocktable-try-shift 'down arg))
13047 (t (call-interactively 'org-next-item))))
13049 (defun org-shiftright (&optional arg)
13050 "Next TODO keyword or timestamp one day later, depending on context."
13051 (interactive "P")
13052 (cond
13053 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13054 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13055 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13056 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13057 ((org-clocktable-try-shift 'right arg))
13058 (t (org-shiftcursor-error))))
13060 (defun org-shiftleft (&optional arg)
13061 "Previous TODO keyword or timestamp one day earlier, depending on context."
13062 (interactive "P")
13063 (cond
13064 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13065 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13066 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13067 ((org-at-property-p)
13068 (call-interactively 'org-property-previous-allowed-value))
13069 ((org-clocktable-try-shift 'left arg))
13070 (t (org-shiftcursor-error))))
13072 (defun org-shiftcontrolright ()
13073 "Switch to next TODO set."
13074 (interactive)
13075 (cond
13076 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13077 (t (org-shiftcursor-error))))
13079 (defun org-shiftcontrolleft ()
13080 "Switch to previous TODO set."
13081 (interactive)
13082 (cond
13083 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13084 (t (org-shiftcursor-error))))
13086 (defun org-ctrl-c-ret ()
13087 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13088 (interactive)
13089 (cond
13090 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13091 (t (call-interactively 'org-insert-heading))))
13093 (defun org-copy-special ()
13094 "Copy region in table or copy current subtree.
13095 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13096 See the individual commands for more information."
13097 (interactive)
13098 (call-interactively
13099 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13101 (defun org-cut-special ()
13102 "Cut region in table or cut current subtree.
13103 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13104 See the individual commands for more information."
13105 (interactive)
13106 (call-interactively
13107 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13109 (defun org-paste-special (arg)
13110 "Paste rectangular region into table, or past subtree relative to level.
13111 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13112 See the individual commands for more information."
13113 (interactive "P")
13114 (if (org-at-table-p)
13115 (org-table-paste-rectangle)
13116 (org-paste-subtree arg)))
13118 (defun org-edit-special ()
13119 "Call a special editor for the stuff at point.
13120 When at a table, call the formula editor with `org-table-edit-formulas'.
13121 When at the first line of an src example, call `org-edit-src-code'.
13122 When in an #+include line, visit the include file. Otherwise call
13123 `ffap' to visit the file at point."
13124 (interactive)
13125 (cond
13126 ((org-at-table-p)
13127 (call-interactively 'org-table-edit-formulas))
13128 ((save-excursion
13129 (beginning-of-line 1)
13130 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13131 (find-file (org-trim (match-string 1))))
13132 ((org-edit-src-code))
13133 ((org-edit-fixed-width-region))
13134 (t (call-interactively 'ffap))))
13136 (defun org-ctrl-c-ctrl-c (&optional arg)
13137 "Set tags in headline, or update according to changed information at point.
13139 This command does many different things, depending on context:
13141 - If the cursor is in a headline, prompt for tags and insert them
13142 into the current line, aligned to `org-tags-column'. When called
13143 with prefix arg, realign all tags in the current buffer.
13145 - If the cursor is in one of the special #+KEYWORD lines, this
13146 triggers scanning the buffer for these lines and updating the
13147 information.
13149 - If the cursor is inside a table, realign the table. This command
13150 works even if the automatic table editor has been turned off.
13152 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13153 the entire table.
13155 - If the cursor is a the beginning of a dynamic block, update it.
13157 - If the cursor is inside a table created by the table.el package,
13158 activate that table.
13160 - If the current buffer is a remember buffer, close note and file it.
13161 with a prefix argument, file it without further interaction to the default
13162 location.
13164 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13165 links in this buffer.
13167 - If the cursor is on a numbered item in a plain list, renumber the
13168 ordered list.
13170 - If the cursor is on a checkbox, toggle it."
13171 (interactive "P")
13172 (let ((org-enable-table-editor t))
13173 (cond
13174 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13175 org-occur-highlights
13176 org-latex-fragment-image-overlays)
13177 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13178 (org-remove-occur-highlights)
13179 (org-remove-latex-fragment-image-overlays)
13180 (message "Temporary highlights/overlays removed from current buffer"))
13181 ((and (local-variable-p 'org-finish-function (current-buffer))
13182 (fboundp org-finish-function))
13183 (funcall org-finish-function))
13184 ((org-at-property-p)
13185 (call-interactively 'org-property-action))
13186 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13187 ((org-on-heading-p) (call-interactively 'org-set-tags))
13188 ((org-at-table.el-p)
13189 (require 'table)
13190 (beginning-of-line 1)
13191 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13192 (call-interactively 'table-recognize-table))
13193 ((org-at-table-p)
13194 (org-table-maybe-eval-formula)
13195 (if arg
13196 (call-interactively 'org-table-recalculate)
13197 (org-table-maybe-recalculate-line))
13198 (call-interactively 'org-table-align))
13199 ((org-at-item-checkbox-p)
13200 (call-interactively 'org-toggle-checkbox))
13201 ((org-at-item-p)
13202 (call-interactively 'org-maybe-renumber-ordered-list))
13203 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13204 ;; Dynamic block
13205 (beginning-of-line 1)
13206 (save-excursion (org-update-dblock)))
13207 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13208 (cond
13209 ((equal (match-string 1) "TBLFM")
13210 ;; Recalculate the table before this line
13211 (save-excursion
13212 (beginning-of-line 1)
13213 (skip-chars-backward " \r\n\t")
13214 (if (org-at-table-p)
13215 (org-call-with-arg 'org-table-recalculate t))))
13217 ; (org-set-regexps-and-options)
13218 ; (org-restart-font-lock)
13219 (let ((org-inhibit-startup t)) (org-mode-restart))
13220 (message "Local setup has been refreshed"))))
13221 (t (error "C-c C-c can do nothing useful at this location.")))))
13223 (defun org-mode-restart ()
13224 "Restart Org-mode, to scan again for special lines.
13225 Also updates the keyword regular expressions."
13226 (interactive)
13227 (org-mode)
13228 (message "Org-mode restarted"))
13230 (defun org-kill-note-or-show-branches ()
13231 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13232 (interactive)
13233 (if (not org-finish-function)
13234 (call-interactively 'show-branches)
13235 (let ((org-note-abort t))
13236 (funcall org-finish-function))))
13238 (defun org-return (&optional indent)
13239 "Goto next table row or insert a newline.
13240 Calls `org-table-next-row' or `newline', depending on context.
13241 See the individual commands for more information."
13242 (interactive)
13243 (cond
13244 ((bobp) (if indent (newline-and-indent) (newline)))
13245 ((and (org-at-heading-p)
13246 (looking-at
13247 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13248 (org-show-entry)
13249 (end-of-line 1)
13250 (newline))
13251 ((org-at-table-p)
13252 (org-table-justify-field-maybe)
13253 (call-interactively 'org-table-next-row))
13254 (t (if indent (newline-and-indent) (newline)))))
13256 (defun org-return-indent ()
13257 "Goto next table row or insert a newline and indent.
13258 Calls `org-table-next-row' or `newline-and-indent', depending on
13259 context. See the individual commands for more information."
13260 (interactive)
13261 (org-return t))
13263 (defun org-ctrl-c-star ()
13264 "Compute table, or change heading status of lines.
13265 Calls `org-table-recalculate' or `org-toggle-region-headings',
13266 depending on context. This will also turn a plain list item or a normal
13267 line into a subheading."
13268 (interactive)
13269 (cond
13270 ((org-at-table-p)
13271 (call-interactively 'org-table-recalculate))
13272 ((org-region-active-p)
13273 ;; Convert all lines in region to list items
13274 (call-interactively 'org-toggle-region-headings))
13275 ((org-on-heading-p)
13276 (org-toggle-region-headings (point-at-bol)
13277 (min (1+ (point-at-eol)) (point-max))))
13278 ((org-at-item-p)
13279 ;; Convert to heading
13280 (let ((level (save-match-data
13281 (save-excursion
13282 (condition-case nil
13283 (progn
13284 (org-back-to-heading t)
13285 (funcall outline-level))
13286 (error 0))))))
13287 (replace-match
13288 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13289 (t (org-toggle-region-headings (point-at-bol)
13290 (min (1+ (point-at-eol)) (point-max))))))
13292 (defun org-ctrl-c-minus ()
13293 "Insert separator line in table or modify bullet status of line.
13294 Also turns a plain line or a region of lines into list items.
13295 Calls `org-table-insert-hline', `org-toggle-region-items', or
13296 `org-cycle-list-bullet', depending on context."
13297 (interactive)
13298 (cond
13299 ((org-at-table-p)
13300 (call-interactively 'org-table-insert-hline))
13301 ((org-on-heading-p)
13302 ;; Convert to item
13303 (save-excursion
13304 (beginning-of-line 1)
13305 (if (looking-at "\\*+ ")
13306 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13307 ((org-region-active-p)
13308 ;; Convert all lines in region to list items
13309 (call-interactively 'org-toggle-region-items))
13310 ((org-in-item-p)
13311 (call-interactively 'org-cycle-list-bullet))
13312 (t (org-toggle-region-items (point-at-bol)
13313 (min (1+ (point-at-eol)) (point-max))))))
13315 (defun org-toggle-region-items (beg end)
13316 "Convert all lines in region to list items.
13317 If the first line is already an item, convert all list items in the region
13318 to normal lines."
13319 (interactive "r")
13320 (let (l2 l)
13321 (save-excursion
13322 (goto-char end)
13323 (setq l2 (org-current-line))
13324 (goto-char beg)
13325 (beginning-of-line 1)
13326 (setq l (1- (org-current-line)))
13327 (if (org-at-item-p)
13328 ;; We already have items, de-itemize
13329 (while (< (setq l (1+ l)) l2)
13330 (when (org-at-item-p)
13331 (goto-char (match-beginning 2))
13332 (delete-region (match-beginning 2) (match-end 2))
13333 (and (looking-at "[ \t]+") (replace-match "")))
13334 (beginning-of-line 2))
13335 (while (< (setq l (1+ l)) l2)
13336 (unless (org-at-item-p)
13337 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13338 (replace-match "\\1- \\2")))
13339 (beginning-of-line 2))))))
13341 (defun org-toggle-region-headings (beg end)
13342 "Convert all lines in region to list items.
13343 If the first line is already an item, convert all list items in the region
13344 to normal lines."
13345 (interactive "r")
13346 (let (l2 l)
13347 (save-excursion
13348 (goto-char end)
13349 (setq l2 (org-current-line))
13350 (goto-char beg)
13351 (beginning-of-line 1)
13352 (setq l (1- (org-current-line)))
13353 (if (org-on-heading-p)
13354 ;; We already have headlines, de-star them
13355 (while (< (setq l (1+ l)) l2)
13356 (when (org-on-heading-p t)
13357 (and (looking-at outline-regexp) (replace-match "")))
13358 (beginning-of-line 2))
13359 (let* ((stars (save-excursion
13360 (re-search-backward org-complex-heading-regexp nil t)
13361 (or (match-string 1) "*")))
13362 (add-stars (if org-odd-levels-only "**" "*"))
13363 (rpl (concat stars add-stars " \\2")))
13364 (while (< (setq l (1+ l)) l2)
13365 (unless (org-on-heading-p)
13366 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13367 (replace-match rpl)))
13368 (beginning-of-line 2)))))))
13370 (defun org-meta-return (&optional arg)
13371 "Insert a new heading or wrap a region in a table.
13372 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13373 See the individual commands for more information."
13374 (interactive "P")
13375 (cond
13376 ((org-at-table-p)
13377 (call-interactively 'org-table-wrap-region))
13378 (t (call-interactively 'org-insert-heading))))
13380 ;;; Menu entries
13382 ;; Define the Org-mode menus
13383 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13384 '("Tbl"
13385 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13386 ["Next Field" org-cycle (org-at-table-p)]
13387 ["Previous Field" org-shifttab (org-at-table-p)]
13388 ["Next Row" org-return (org-at-table-p)]
13389 "--"
13390 ["Blank Field" org-table-blank-field (org-at-table-p)]
13391 ["Edit Field" org-table-edit-field (org-at-table-p)]
13392 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13393 "--"
13394 ("Column"
13395 ["Move Column Left" org-metaleft (org-at-table-p)]
13396 ["Move Column Right" org-metaright (org-at-table-p)]
13397 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13398 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13399 ("Row"
13400 ["Move Row Up" org-metaup (org-at-table-p)]
13401 ["Move Row Down" org-metadown (org-at-table-p)]
13402 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13403 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13404 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13405 "--"
13406 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13407 ("Rectangle"
13408 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13409 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13410 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13411 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13412 "--"
13413 ("Calculate"
13414 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13415 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13416 ["Edit Formulas" org-edit-special (org-at-table-p)]
13417 "--"
13418 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13419 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13420 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13421 "--"
13422 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13423 "--"
13424 ["Sum Column/Rectangle" org-table-sum
13425 (or (org-at-table-p) (org-region-active-p))]
13426 ["Which Column?" org-table-current-column (org-at-table-p)])
13427 ["Debug Formulas"
13428 org-table-toggle-formula-debugger
13429 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13430 ["Show Col/Row Numbers"
13431 org-table-toggle-coordinate-overlays
13432 :style toggle
13433 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13434 "--"
13435 ["Create" org-table-create (and (not (org-at-table-p))
13436 org-enable-table-editor)]
13437 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13438 ["Import from File" org-table-import (not (org-at-table-p))]
13439 ["Export to File" org-table-export (org-at-table-p)]
13440 "--"
13441 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13443 (easy-menu-define org-org-menu org-mode-map "Org menu"
13444 '("Org"
13445 ("Show/Hide"
13446 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13447 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13448 ["Sparse Tree..." org-sparse-tree t]
13449 ["Reveal Context" org-reveal t]
13450 ["Show All" show-all t]
13451 "--"
13452 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13453 "--"
13454 ["New Heading" org-insert-heading t]
13455 ("Navigate Headings"
13456 ["Up" outline-up-heading t]
13457 ["Next" outline-next-visible-heading t]
13458 ["Previous" outline-previous-visible-heading t]
13459 ["Next Same Level" outline-forward-same-level t]
13460 ["Previous Same Level" outline-backward-same-level t]
13461 "--"
13462 ["Jump" org-goto t])
13463 ("Edit Structure"
13464 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13465 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13466 "--"
13467 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13468 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13469 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13470 "--"
13471 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13472 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13473 ["Demote Heading" org-metaright (not (org-at-table-p))]
13474 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13475 "--"
13476 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13477 "--"
13478 ["Convert to odd levels" org-convert-to-odd-levels t]
13479 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13480 ("Editing"
13481 ["Emphasis..." org-emphasize t]
13482 ["Edit Source Example" org-edit-special t])
13483 ("Archive"
13484 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13485 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13486 ; :active t :keys "C-u C-c C-x C-a"]
13487 ["Sparse trees open ARCHIVE trees"
13488 (setq org-sparse-tree-open-archived-trees
13489 (not org-sparse-tree-open-archived-trees))
13490 :style toggle :selected org-sparse-tree-open-archived-trees]
13491 ["Cycling opens ARCHIVE trees"
13492 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13493 :style toggle :selected org-cycle-open-archived-trees]
13494 "--"
13495 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13496 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13497 ; ["Check and Move Children" (org-archive-subtree '(4))
13498 ; :active t :keys "C-u C-c C-x C-s"]
13500 "--"
13501 ("TODO Lists"
13502 ["TODO/DONE/-" org-todo t]
13503 ("Select keyword"
13504 ["Next keyword" org-shiftright (org-on-heading-p)]
13505 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13506 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13507 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13508 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13509 ["Show TODO Tree" org-show-todo-tree t]
13510 ["Global TODO list" org-todo-list t]
13511 "--"
13512 ["Set Priority" org-priority t]
13513 ["Priority Up" org-shiftup t]
13514 ["Priority Down" org-shiftdown t])
13515 ("TAGS and Properties"
13516 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13517 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13518 "--"
13519 ["Set property" 'org-set-property t]
13520 ["Column view of properties" org-columns t]
13521 ["Insert Column View DBlock" org-insert-columns-dblock t])
13522 ("Dates and Scheduling"
13523 ["Timestamp" org-time-stamp t]
13524 ["Timestamp (inactive)" org-time-stamp-inactive t]
13525 ("Change Date"
13526 ["1 Day Later" org-shiftright t]
13527 ["1 Day Earlier" org-shiftleft t]
13528 ["1 ... Later" org-shiftup t]
13529 ["1 ... Earlier" org-shiftdown t])
13530 ["Compute Time Range" org-evaluate-time-range t]
13531 ["Schedule Item" org-schedule t]
13532 ["Deadline" org-deadline t]
13533 "--"
13534 ["Custom time format" org-toggle-time-stamp-overlays
13535 :style radio :selected org-display-custom-times]
13536 "--"
13537 ["Goto Calendar" org-goto-calendar t]
13538 ["Date from Calendar" org-date-from-calendar t])
13539 ("Logging work"
13540 ["Clock in" org-clock-in t]
13541 ["Clock out" org-clock-out t]
13542 ["Clock cancel" org-clock-cancel t]
13543 ["Goto running clock" org-clock-goto t]
13544 ["Display times" org-clock-display t]
13545 ["Create clock table" org-clock-report t]
13546 "--"
13547 ["Record DONE time"
13548 (progn (setq org-log-done (not org-log-done))
13549 (message "Switching to %s will %s record a timestamp"
13550 (car org-done-keywords)
13551 (if org-log-done "automatically" "not")))
13552 :style toggle :selected org-log-done])
13553 "--"
13554 ["Agenda Command..." org-agenda t]
13555 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13556 ("File List for Agenda")
13557 ("Special views current file"
13558 ["TODO Tree" org-show-todo-tree t]
13559 ["Check Deadlines" org-check-deadlines t]
13560 ["Timeline" org-timeline t]
13561 ["Tags Tree" org-tags-sparse-tree t])
13562 "--"
13563 ("Hyperlinks"
13564 ["Store Link (Global)" org-store-link t]
13565 ["Insert Link" org-insert-link t]
13566 ["Follow Link" org-open-at-point t]
13567 "--"
13568 ["Next link" org-next-link t]
13569 ["Previous link" org-previous-link t]
13570 "--"
13571 ["Descriptive Links"
13572 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13573 :style radio
13574 :selected (member '(org-link) buffer-invisibility-spec)]
13575 ["Literal Links"
13576 (progn
13577 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13578 :style radio
13579 :selected (not (member '(org-link) buffer-invisibility-spec))])
13580 "--"
13581 ["Export/Publish..." org-export t]
13582 ("LaTeX"
13583 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13584 :selected org-cdlatex-mode]
13585 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13586 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13587 ["Modify math symbol" org-cdlatex-math-modify
13588 (org-inside-LaTeX-fragment-p)]
13589 ["Export LaTeX fragments as images"
13590 (if (featurep 'org-exp)
13591 (setq org-export-with-LaTeX-fragments
13592 (not org-export-with-LaTeX-fragments))
13593 (require 'org-exp))
13594 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13595 org-export-with-LaTeX-fragments)])
13596 "--"
13597 ("Documentation"
13598 ["Show Version" org-version t]
13599 ["Info Documentation" org-info t])
13600 ("Customize"
13601 ["Browse Org Group" org-customize t]
13602 "--"
13603 ["Expand This Menu" org-create-customize-menu
13604 (fboundp 'customize-menu-create)])
13605 "--"
13606 ["Refresh setup" org-mode-restart t]
13609 (defun org-info (&optional node)
13610 "Read documentation for Org-mode in the info system.
13611 With optional NODE, go directly to that node."
13612 (interactive)
13613 (info (format "(org)%s" (or node ""))))
13615 (defun org-install-agenda-files-menu ()
13616 (let ((bl (buffer-list)))
13617 (save-excursion
13618 (while bl
13619 (set-buffer (pop bl))
13620 (if (org-mode-p) (setq bl nil)))
13621 (when (org-mode-p)
13622 (easy-menu-change
13623 '("Org") "File List for Agenda"
13624 (append
13625 (list
13626 ["Edit File List" (org-edit-agenda-file-list) t]
13627 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13628 ["Remove Current File from List" org-remove-file t]
13629 ["Cycle through agenda files" org-cycle-agenda-files t]
13630 ["Occur in all agenda files" org-occur-in-agenda-files t]
13631 "--")
13632 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13634 ;;;; Documentation
13636 ;;;###autoload
13637 (defun org-require-autoloaded-modules ()
13638 (interactive)
13639 (mapc 'require
13640 '(org-agenda org-archive org-clock org-colview
13641 org-exp org-id org-export-latex org-publish
13642 org-remember org-table)))
13644 ;;;###autoload
13645 (defun org-customize ()
13646 "Call the customize function with org as argument."
13647 (interactive)
13648 (org-load-modules-maybe)
13649 (org-require-autoloaded-modules)
13650 (customize-browse 'org))
13652 (defun org-create-customize-menu ()
13653 "Create a full customization menu for Org-mode, insert it into the menu."
13654 (interactive)
13655 (org-load-modules-maybe)
13656 (org-require-autoloaded-modules)
13657 (if (fboundp 'customize-menu-create)
13658 (progn
13659 (easy-menu-change
13660 '("Org") "Customize"
13661 `(["Browse Org group" org-customize t]
13662 "--"
13663 ,(customize-menu-create 'org)
13664 ["Set" Custom-set t]
13665 ["Save" Custom-save t]
13666 ["Reset to Current" Custom-reset-current t]
13667 ["Reset to Saved" Custom-reset-saved t]
13668 ["Reset to Standard Settings" Custom-reset-standard t]))
13669 (message "\"Org\"-menu now contains full customization menu"))
13670 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13672 ;;;; Miscellaneous stuff
13674 ;;; Generally useful functions
13676 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13677 "Display the given MESSAGE as a warning."
13678 (if (fboundp 'display-warning)
13679 (display-warning 'org message
13680 (if (featurep 'xemacs)
13681 'warning
13682 :warning))
13683 (let ((buf (get-buffer-create "*Org warnings*")))
13684 (with-current-buffer buf
13685 (goto-char (point-max))
13686 (insert "Warning (Org): " message)
13687 (unless (bolp)
13688 (newline)))
13689 (display-buffer buf)
13690 (sit-for 0))))
13692 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13693 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13694 (if (and marker (marker-buffer marker)
13695 (buffer-live-p (marker-buffer marker)))
13696 (progn
13697 (switch-to-buffer (marker-buffer marker))
13698 (if (or (> marker (point-max)) (< marker (point-min)))
13699 (widen))
13700 (goto-char marker))
13701 (if bookmark
13702 (bookmark-jump bookmark)
13703 (error "Cannot find location"))))
13705 (defun org-quote-csv-field (s)
13706 "Quote field for inclusion in CSV material."
13707 (if (string-match "[\",]" s)
13708 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13711 (defun org-plist-delete (plist property)
13712 "Delete PROPERTY from PLIST.
13713 This is in contrast to merely setting it to 0."
13714 (let (p)
13715 (while plist
13716 (if (not (eq property (car plist)))
13717 (setq p (plist-put p (car plist) (nth 1 plist))))
13718 (setq plist (cddr plist)))
13721 (defun org-force-self-insert (N)
13722 "Needed to enforce self-insert under remapping."
13723 (interactive "p")
13724 (self-insert-command N))
13726 (defun org-string-width (s)
13727 "Compute width of string, ignoring invisible characters.
13728 This ignores character with invisibility property `org-link', and also
13729 characters with property `org-cwidth', because these will become invisible
13730 upon the next fontification round."
13731 (let (b l)
13732 (when (or (eq t buffer-invisibility-spec)
13733 (assq 'org-link buffer-invisibility-spec))
13734 (while (setq b (text-property-any 0 (length s)
13735 'invisible 'org-link s))
13736 (setq s (concat (substring s 0 b)
13737 (substring s (or (next-single-property-change
13738 b 'invisible s) (length s)))))))
13739 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13740 (setq s (concat (substring s 0 b)
13741 (substring s (or (next-single-property-change
13742 b 'org-cwidth s) (length s))))))
13743 (setq l (string-width s) b -1)
13744 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13745 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13748 (defun org-base-buffer (buffer)
13749 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13750 (if (not buffer)
13751 buffer
13752 (or (buffer-base-buffer buffer)
13753 buffer)))
13755 (defun org-trim (s)
13756 "Remove whitespace at beginning and end of string."
13757 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13758 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13761 (defun org-wrap (string &optional width lines)
13762 "Wrap string to either a number of lines, or a width in characters.
13763 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13764 that costs. If there is a word longer than WIDTH, the text is actually
13765 wrapped to the length of that word.
13766 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13767 many lines, whatever width that takes.
13768 The return value is a list of lines, without newlines at the end."
13769 (let* ((words (org-split-string string "[ \t\n]+"))
13770 (maxword (apply 'max (mapcar 'org-string-width words)))
13771 w ll)
13772 (cond (width
13773 (org-do-wrap words (max maxword width)))
13774 (lines
13775 (setq w maxword)
13776 (setq ll (org-do-wrap words maxword))
13777 (if (<= (length ll) lines)
13779 (setq ll words)
13780 (while (> (length ll) lines)
13781 (setq w (1+ w))
13782 (setq ll (org-do-wrap words w)))
13783 ll))
13784 (t (error "Cannot wrap this")))))
13786 (defun org-do-wrap (words width)
13787 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13788 (let (lines line)
13789 (while words
13790 (setq line (pop words))
13791 (while (and words (< (+ (length line) (length (car words))) width))
13792 (setq line (concat line " " (pop words))))
13793 (setq lines (push line lines)))
13794 (nreverse lines)))
13796 (defun org-split-string (string &optional separators)
13797 "Splits STRING into substrings at SEPARATORS.
13798 No empty strings are returned if there are matches at the beginning
13799 and end of string."
13800 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13801 (start 0)
13802 notfirst
13803 (list nil))
13804 (while (and (string-match rexp string
13805 (if (and notfirst
13806 (= start (match-beginning 0))
13807 (< start (length string)))
13808 (1+ start) start))
13809 (< (match-beginning 0) (length string)))
13810 (setq notfirst t)
13811 (or (eq (match-beginning 0) 0)
13812 (and (eq (match-beginning 0) (match-end 0))
13813 (eq (match-beginning 0) start))
13814 (setq list
13815 (cons (substring string start (match-beginning 0))
13816 list)))
13817 (setq start (match-end 0)))
13818 (or (eq start (length string))
13819 (setq list
13820 (cons (substring string start)
13821 list)))
13822 (nreverse list)))
13824 (defun org-context ()
13825 "Return a list of contexts of the current cursor position.
13826 If several contexts apply, all are returned.
13827 Each context entry is a list with a symbol naming the context, and
13828 two positions indicating start and end of the context. Possible
13829 contexts are:
13831 :headline anywhere in a headline
13832 :headline-stars on the leading stars in a headline
13833 :todo-keyword on a TODO keyword (including DONE) in a headline
13834 :tags on the TAGS in a headline
13835 :priority on the priority cookie in a headline
13836 :item on the first line of a plain list item
13837 :item-bullet on the bullet/number of a plain list item
13838 :checkbox on the checkbox in a plain list item
13839 :table in an org-mode table
13840 :table-special on a special filed in a table
13841 :table-table in a table.el table
13842 :link on a hyperlink
13843 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13844 :target on a <<target>>
13845 :radio-target on a <<<radio-target>>>
13846 :latex-fragment on a LaTeX fragment
13847 :latex-preview on a LaTeX fragment with overlayed preview image
13849 This function expects the position to be visible because it uses font-lock
13850 faces as a help to recognize the following contexts: :table-special, :link,
13851 and :keyword."
13852 (let* ((f (get-text-property (point) 'face))
13853 (faces (if (listp f) f (list f)))
13854 (p (point)) clist o)
13855 ;; First the large context
13856 (cond
13857 ((org-on-heading-p t)
13858 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13859 (when (progn
13860 (beginning-of-line 1)
13861 (looking-at org-todo-line-tags-regexp))
13862 (push (org-point-in-group p 1 :headline-stars) clist)
13863 (push (org-point-in-group p 2 :todo-keyword) clist)
13864 (push (org-point-in-group p 4 :tags) clist))
13865 (goto-char p)
13866 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13867 (if (looking-at "\\[#[A-Z0-9]\\]")
13868 (push (org-point-in-group p 0 :priority) clist)))
13870 ((org-at-item-p)
13871 (push (org-point-in-group p 2 :item-bullet) clist)
13872 (push (list :item (point-at-bol)
13873 (save-excursion (org-end-of-item) (point)))
13874 clist)
13875 (and (org-at-item-checkbox-p)
13876 (push (org-point-in-group p 0 :checkbox) clist)))
13878 ((org-at-table-p)
13879 (push (list :table (org-table-begin) (org-table-end)) clist)
13880 (if (memq 'org-formula faces)
13881 (push (list :table-special
13882 (previous-single-property-change p 'face)
13883 (next-single-property-change p 'face)) clist)))
13884 ((org-at-table-p 'any)
13885 (push (list :table-table) clist)))
13886 (goto-char p)
13888 ;; Now the small context
13889 (cond
13890 ((org-at-timestamp-p)
13891 (push (org-point-in-group p 0 :timestamp) clist))
13892 ((memq 'org-link faces)
13893 (push (list :link
13894 (previous-single-property-change p 'face)
13895 (next-single-property-change p 'face)) clist))
13896 ((memq 'org-special-keyword faces)
13897 (push (list :keyword
13898 (previous-single-property-change p 'face)
13899 (next-single-property-change p 'face)) clist))
13900 ((org-on-target-p)
13901 (push (org-point-in-group p 0 :target) clist)
13902 (goto-char (1- (match-beginning 0)))
13903 (if (looking-at org-radio-target-regexp)
13904 (push (org-point-in-group p 0 :radio-target) clist))
13905 (goto-char p))
13906 ((setq o (car (delq nil
13907 (mapcar
13908 (lambda (x)
13909 (if (memq x org-latex-fragment-image-overlays) x))
13910 (org-overlays-at (point))))))
13911 (push (list :latex-fragment
13912 (org-overlay-start o) (org-overlay-end o)) clist)
13913 (push (list :latex-preview
13914 (org-overlay-start o) (org-overlay-end o)) clist))
13915 ((org-inside-LaTeX-fragment-p)
13916 ;; FIXME: positions wrong.
13917 (push (list :latex-fragment (point) (point)) clist)))
13919 (setq clist (nreverse (delq nil clist)))
13920 clist))
13922 ;; FIXME: Compare with at-regexp-p Do we need both?
13923 (defun org-in-regexp (re &optional nlines visually)
13924 "Check if point is inside a match of regexp.
13925 Normally only the current line is checked, but you can include NLINES extra
13926 lines both before and after point into the search.
13927 If VISUALLY is set, require that the cursor is not after the match but
13928 really on, so that the block visually is on the match."
13929 (catch 'exit
13930 (let ((pos (point))
13931 (eol (point-at-eol (+ 1 (or nlines 0))))
13932 (inc (if visually 1 0)))
13933 (save-excursion
13934 (beginning-of-line (- 1 (or nlines 0)))
13935 (while (re-search-forward re eol t)
13936 (if (and (<= (match-beginning 0) pos)
13937 (>= (+ inc (match-end 0)) pos))
13938 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13940 (defun org-at-regexp-p (regexp)
13941 "Is point inside a match of REGEXP in the current line?"
13942 (catch 'exit
13943 (save-excursion
13944 (let ((pos (point)) (end (point-at-eol)))
13945 (beginning-of-line 1)
13946 (while (re-search-forward regexp end t)
13947 (if (and (<= (match-beginning 0) pos)
13948 (>= (match-end 0) pos))
13949 (throw 'exit t)))
13950 nil))))
13952 (defun org-occur-in-agenda-files (regexp &optional nlines)
13953 "Call `multi-occur' with buffers for all agenda files."
13954 (interactive "sOrg-files matching: \np")
13955 (let* ((files (org-agenda-files))
13956 (tnames (mapcar 'file-truename files))
13957 (extra org-agenda-text-search-extra-files)
13959 (when (eq (car extra) 'agenda-archives)
13960 (setq extra (cdr extra))
13961 (setq files (org-add-archive-files files)))
13962 (while (setq f (pop extra))
13963 (unless (member (file-truename f) tnames)
13964 (add-to-list 'files f 'append)
13965 (add-to-list 'tnames (file-truename f) 'append)))
13966 (multi-occur
13967 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13968 regexp)))
13970 (if (boundp 'occur-mode-find-occurrence-hook)
13971 ;; Emacs 23
13972 (add-hook 'occur-mode-find-occurrence-hook
13973 (lambda ()
13974 (when (org-mode-p)
13975 (org-reveal))))
13976 ;; Emacs 22
13977 (defadvice occur-mode-goto-occurrence
13978 (after org-occur-reveal activate)
13979 (and (org-mode-p) (org-reveal)))
13980 (defadvice occur-mode-goto-occurrence-other-window
13981 (after org-occur-reveal activate)
13982 (and (org-mode-p) (org-reveal)))
13983 (defadvice occur-mode-display-occurrence
13984 (after org-occur-reveal activate)
13985 (when (org-mode-p)
13986 (let ((pos (occur-mode-find-occurrence)))
13987 (with-current-buffer (marker-buffer pos)
13988 (save-excursion
13989 (goto-char pos)
13990 (org-reveal)))))))
13992 (defun org-uniquify (list)
13993 "Remove duplicate elements from LIST."
13994 (let (res)
13995 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13996 res))
13998 (defun org-delete-all (elts list)
13999 "Remove all elements in ELTS from LIST."
14000 (while elts
14001 (setq list (delete (pop elts) list)))
14002 list)
14004 (defun org-back-over-empty-lines ()
14005 "Move backwards over witespace, to the beginning of the first empty line.
14006 Returns the number of empty lines passed."
14007 (let ((pos (point)))
14008 (skip-chars-backward " \t\n\r")
14009 (beginning-of-line 2)
14010 (goto-char (min (point) pos))
14011 (count-lines (point) pos)))
14013 (defun org-skip-whitespace ()
14014 (skip-chars-forward " \t\n\r"))
14016 (defun org-point-in-group (point group &optional context)
14017 "Check if POINT is in match-group GROUP.
14018 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14019 match. If the match group does ot exist or point is not inside it,
14020 return nil."
14021 (and (match-beginning group)
14022 (>= point (match-beginning group))
14023 (<= point (match-end group))
14024 (if context
14025 (list context (match-beginning group) (match-end group))
14026 t)))
14028 (defun org-switch-to-buffer-other-window (&rest args)
14029 "Switch to buffer in a second window on the current frame.
14030 In particular, do not allow pop-up frames."
14031 (let (pop-up-frames special-display-buffer-names special-display-regexps
14032 special-display-function)
14033 (apply 'switch-to-buffer-other-window args)))
14035 (defun org-combine-plists (&rest plists)
14036 "Create a single property list from all plists in PLISTS.
14037 The process starts by copying the first list, and then setting properties
14038 from the other lists. Settings in the last list are the most significant
14039 ones and overrule settings in the other lists."
14040 (let ((rtn (copy-sequence (pop plists)))
14041 p v ls)
14042 (while plists
14043 (setq ls (pop plists))
14044 (while ls
14045 (setq p (pop ls) v (pop ls))
14046 (setq rtn (plist-put rtn p v))))
14047 rtn))
14049 (defun org-move-line-down (arg)
14050 "Move the current line down. With prefix argument, move it past ARG lines."
14051 (interactive "p")
14052 (let ((col (current-column))
14053 beg end pos)
14054 (beginning-of-line 1) (setq beg (point))
14055 (beginning-of-line 2) (setq end (point))
14056 (beginning-of-line (+ 1 arg))
14057 (setq pos (move-marker (make-marker) (point)))
14058 (insert (delete-and-extract-region beg end))
14059 (goto-char pos)
14060 (org-move-to-column col)))
14062 (defun org-move-line-up (arg)
14063 "Move the current line up. With prefix argument, move it past ARG lines."
14064 (interactive "p")
14065 (let ((col (current-column))
14066 beg end pos)
14067 (beginning-of-line 1) (setq beg (point))
14068 (beginning-of-line 2) (setq end (point))
14069 (beginning-of-line (- arg))
14070 (setq pos (move-marker (make-marker) (point)))
14071 (insert (delete-and-extract-region beg end))
14072 (goto-char pos)
14073 (org-move-to-column col)))
14075 (defun org-replace-escapes (string table)
14076 "Replace %-escapes in STRING with values in TABLE.
14077 TABLE is an association list with keys like \"%a\" and string values.
14078 The sequences in STRING may contain normal field width and padding information,
14079 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14080 so values can contain further %-escapes if they are define later in TABLE."
14081 (let ((case-fold-search nil)
14082 e re rpl)
14083 (while (setq e (pop table))
14084 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14085 (while (string-match re string)
14086 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14087 (cdr e)))
14088 (setq string (replace-match rpl t t string))))
14089 string))
14092 (defun org-sublist (list start end)
14093 "Return a section of LIST, from START to END.
14094 Counting starts at 1."
14095 (let (rtn (c start))
14096 (setq list (nthcdr (1- start) list))
14097 (while (and list (<= c end))
14098 (push (pop list) rtn)
14099 (setq c (1+ c)))
14100 (nreverse rtn)))
14102 (defun org-find-base-buffer-visiting (file)
14103 "Like `find-buffer-visiting' but alway return the base buffer and
14104 not an indirect buffer."
14105 (let ((buf (find-buffer-visiting file)))
14106 (if buf
14107 (or (buffer-base-buffer buf) buf)
14108 nil)))
14110 (defun org-image-file-name-regexp ()
14111 "Return regexp matching the file names of images."
14112 (if (fboundp 'image-file-name-regexp)
14113 (image-file-name-regexp)
14114 (let ((image-file-name-extensions
14115 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14116 "xbm" "xpm" "pbm" "pgm" "ppm")))
14117 (concat "\\."
14118 (regexp-opt (nconc (mapcar 'upcase
14119 image-file-name-extensions)
14120 image-file-name-extensions)
14122 "\\'"))))
14124 (defun org-file-image-p (file)
14125 "Return non-nil if FILE is an image."
14126 (save-match-data
14127 (string-match (org-image-file-name-regexp) file)))
14129 (defun org-get-cursor-date ()
14130 "Return the date at cursor in as a time.
14131 This works in the calendar and in the agenda, anywhere else it just
14132 returns the current time."
14133 (let (date day defd)
14134 (cond
14135 ((eq major-mode 'calendar-mode)
14136 (setq date (calendar-cursor-to-date)
14137 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14138 ((eq major-mode 'org-agenda-mode)
14139 (setq day (get-text-property (point) 'day))
14140 (if day
14141 (setq date (calendar-gregorian-from-absolute day)
14142 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14143 (nth 2 date))))))
14144 (or defd (current-time))))
14146 (defvar org-agenda-action-marker (make-marker)
14147 "Marker pointing to the entry for the next agenda action.")
14149 (defun org-mark-entry-for-agenda-action ()
14150 "Mark the current entry as target of an agenda action.
14151 Agenda actions are actions executed from the agenda with the key `k',
14152 which make use of the date at the cursor."
14153 (interactive)
14154 (move-marker org-agenda-action-marker
14155 (save-excursion (org-back-to-heading t) (point))
14156 (current-buffer))
14157 (message
14158 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14160 ;;; Paragraph filling stuff.
14161 ;; We want this to be just right, so use the full arsenal.
14163 (defun org-indent-line-function ()
14164 "Indent line like previous, but further if previous was headline or item."
14165 (interactive)
14166 (let* ((pos (point))
14167 (itemp (org-at-item-p))
14168 column bpos bcol tpos tcol bullet btype bullet-type)
14169 ;; Find the previous relevant line
14170 (beginning-of-line 1)
14171 (cond
14172 ((looking-at "#") (setq column 0))
14173 ((looking-at "\\*+ ") (setq column 0))
14175 (beginning-of-line 0)
14176 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14177 (beginning-of-line 0))
14178 (cond
14179 ((looking-at "\\*+[ \t]+")
14180 (if (not org-adapt-indentation)
14181 (setq column 0)
14182 (goto-char (match-end 0))
14183 (setq column (current-column))))
14184 ((org-in-item-p)
14185 (org-beginning-of-item)
14186 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14187 (setq bpos (match-beginning 1) tpos (match-end 0)
14188 bcol (progn (goto-char bpos) (current-column))
14189 tcol (progn (goto-char tpos) (current-column))
14190 bullet (match-string 1)
14191 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14192 (if (> tcol (+ bcol org-description-max-indent))
14193 (setq tcol (+ bcol 5)))
14194 (if (not itemp)
14195 (setq column tcol)
14196 (goto-char pos)
14197 (beginning-of-line 1)
14198 (if (looking-at "\\S-")
14199 (progn
14200 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14201 (setq bullet (match-string 1)
14202 btype (if (string-match "[0-9]" bullet) "n" bullet))
14203 (setq column (if (equal btype bullet-type) bcol tcol)))
14204 (setq column (org-get-indentation)))))
14205 (t (setq column (org-get-indentation))))))
14206 (goto-char pos)
14207 (if (<= (current-column) (current-indentation))
14208 (org-indent-line-to column)
14209 (save-excursion (org-indent-line-to column)))
14210 (setq column (current-column))
14211 (beginning-of-line 1)
14212 (if (looking-at
14213 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14214 (replace-match (concat "\\1" (format org-property-format
14215 (match-string 2) (match-string 3)))
14216 t nil))
14217 (org-move-to-column column)))
14219 (defun org-set-autofill-regexps ()
14220 (interactive)
14221 ;; In the paragraph separator we include headlines, because filling
14222 ;; text in a line directly attached to a headline would otherwise
14223 ;; fill the headline as well.
14224 (org-set-local 'comment-start-skip "^#+[ \t]*")
14225 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14226 ;; The paragraph starter includes hand-formatted lists.
14227 (org-set-local 'paragraph-start
14228 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14229 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14230 ;; But only if the user has not turned off tables or fixed-width regions
14231 (org-set-local
14232 'auto-fill-inhibit-regexp
14233 (concat "\\*+ \\|#\\+"
14234 "\\|[ \t]*" org-keyword-time-regexp
14235 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14236 (concat
14237 "\\|[ \t]*["
14238 (if org-enable-table-editor "|" "")
14239 (if org-enable-fixed-width-editor ":" "")
14240 "]"))))
14241 ;; We use our own fill-paragraph function, to make sure that tables
14242 ;; and fixed-width regions are not wrapped. That function will pass
14243 ;; through to `fill-paragraph' when appropriate.
14244 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14245 ; Adaptive filling: To get full control, first make sure that
14246 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14247 (org-set-local 'adaptive-fill-regexp "\000")
14248 (org-set-local 'adaptive-fill-function
14249 'org-adaptive-fill-function)
14250 (org-set-local
14251 'align-mode-rules-list
14252 '((org-in-buffer-settings
14253 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14254 (modes . '(org-mode))))))
14256 (defun org-fill-paragraph (&optional justify)
14257 "Re-align a table, pass through to fill-paragraph if no table."
14258 (let ((table-p (org-at-table-p))
14259 (table.el-p (org-at-table.el-p)))
14260 (cond ((and (equal (char-after (point-at-bol)) ?*)
14261 (save-excursion (goto-char (point-at-bol))
14262 (looking-at outline-regexp)))
14263 t) ; skip headlines
14264 (table.el-p t) ; skip table.el tables
14265 (table-p (org-table-align) t) ; align org-mode tables
14266 (t nil)))) ; call paragraph-fill
14268 ;; For reference, this is the default value of adaptive-fill-regexp
14269 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14271 (defun org-adaptive-fill-function ()
14272 "Return a fill prefix for org-mode files.
14273 In particular, this makes sure hanging paragraphs for hand-formatted lists
14274 work correctly."
14275 (cond ((looking-at "#[ \t]+")
14276 (match-string 0))
14277 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14278 (save-excursion
14279 (if (> (match-end 1) (+ (match-beginning 1)
14280 org-description-max-indent))
14281 (goto-char (+ (match-beginning 1) 5))
14282 (goto-char (match-end 0)))
14283 (make-string (current-column) ?\ )))
14284 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14285 (save-excursion
14286 (goto-char (match-end 0))
14287 (make-string (current-column) ?\ )))
14288 (t nil)))
14290 ;;; Other stuff.
14292 (defun org-toggle-fixed-width-section (arg)
14293 "Toggle the fixed-width export.
14294 If there is no active region, the QUOTE keyword at the current headline is
14295 inserted or removed. When present, it causes the text between this headline
14296 and the next to be exported as fixed-width text, and unmodified.
14297 If there is an active region, this command adds or removes a colon as the
14298 first character of this line. If the first character of a line is a colon,
14299 this line is also exported in fixed-width font."
14300 (interactive "P")
14301 (let* ((cc 0)
14302 (regionp (org-region-active-p))
14303 (beg (if regionp (region-beginning) (point)))
14304 (end (if regionp (region-end)))
14305 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14306 (case-fold-search nil)
14307 (re "[ \t]*\\(:\\)")
14308 off)
14309 (if regionp
14310 (save-excursion
14311 (goto-char beg)
14312 (setq cc (current-column))
14313 (beginning-of-line 1)
14314 (setq off (looking-at re))
14315 (while (> nlines 0)
14316 (setq nlines (1- nlines))
14317 (beginning-of-line 1)
14318 (cond
14319 (arg
14320 (org-move-to-column cc t)
14321 (insert ":\n")
14322 (forward-line -1))
14323 ((and off (looking-at re))
14324 (replace-match "" t t nil 1))
14325 ((not off) (org-move-to-column cc t) (insert ":")))
14326 (forward-line 1)))
14327 (save-excursion
14328 (org-back-to-heading)
14329 (if (looking-at (concat outline-regexp
14330 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14331 (replace-match "" t t nil 1)
14332 (if (looking-at outline-regexp)
14333 (progn
14334 (goto-char (match-end 0))
14335 (insert org-quote-string " "))))))))
14337 ;;;; Functions extending outline functionality
14339 (defun org-beginning-of-line (&optional arg)
14340 "Go to the beginning of the current line. If that is invisible, continue
14341 to a visible line beginning. This makes the function of C-a more intuitive.
14342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14343 first attempt, and only move to after the tags when the cursor is already
14344 beyond the end of the headline."
14345 (interactive "P")
14346 (let ((pos (point)) refpos)
14347 (beginning-of-line 1)
14348 (if (bobp)
14350 (backward-char 1)
14351 (if (org-invisible-p)
14352 (while (and (not (bobp)) (org-invisible-p))
14353 (backward-char 1)
14354 (beginning-of-line 1))
14355 (forward-char 1)))
14356 (when org-special-ctrl-a/e
14357 (cond
14358 ((and (looking-at org-complex-heading-regexp)
14359 (= (char-after (match-end 1)) ?\ ))
14360 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14361 (point-at-eol)))
14362 (goto-char
14363 (if (eq org-special-ctrl-a/e t)
14364 (cond ((> pos refpos) refpos)
14365 ((= pos (point)) refpos)
14366 (t (point)))
14367 (cond ((> pos (point)) (point))
14368 ((not (eq last-command this-command)) (point))
14369 (t refpos)))))
14370 ((org-at-item-p)
14371 (goto-char
14372 (if (eq org-special-ctrl-a/e t)
14373 (cond ((> pos (match-end 4)) (match-end 4))
14374 ((= pos (point)) (match-end 4))
14375 (t (point)))
14376 (cond ((> pos (point)) (point))
14377 ((not (eq last-command this-command)) (point))
14378 (t (match-end 4))))))))
14379 (org-no-warnings
14380 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14382 (defun org-end-of-line (&optional arg)
14383 "Go to the end of the line.
14384 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14385 first attempt, and only move to after the tags when the cursor is already
14386 beyond the end of the headline."
14387 (interactive "P")
14388 (if (or (not org-special-ctrl-a/e)
14389 (not (org-on-heading-p)))
14390 (end-of-line arg)
14391 (let ((pos (point)))
14392 (beginning-of-line 1)
14393 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14394 (if (eq org-special-ctrl-a/e t)
14395 (if (or (< pos (match-beginning 1))
14396 (= pos (match-end 0)))
14397 (goto-char (match-beginning 1))
14398 (goto-char (match-end 0)))
14399 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14400 (goto-char (match-end 0))
14401 (goto-char (match-beginning 1))))
14402 (end-of-line arg))))
14403 (org-no-warnings
14404 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14407 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14408 (define-key org-mode-map "\C-e" 'org-end-of-line)
14410 (defun org-kill-line (&optional arg)
14411 "Kill line, to tags or end of line."
14412 (interactive "P")
14413 (cond
14414 ((or (not org-special-ctrl-k)
14415 (bolp)
14416 (not (org-on-heading-p)))
14417 (call-interactively 'kill-line))
14418 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14419 (kill-region (point) (match-beginning 1))
14420 (org-set-tags nil t))
14421 (t (kill-region (point) (point-at-eol)))))
14424 (define-key org-mode-map "\C-k" 'org-kill-line)
14426 (defun org-yank ()
14427 "Yank, and if the yanked text is a single subtree, fold it.
14428 In fact, if the yanked text is a sequence of subtrees, fold all of them."
14429 (interactive)
14430 (if org-yank-folded-subtrees
14431 (let ((beg (point)) end)
14432 (call-interactively 'yank)
14433 (setq end (point))
14434 (goto-char beg)
14435 (when (and (bolp)
14436 (org-kill-is-subtree-p))
14437 (or (looking-at outline-regexp)
14438 (re-search-forward (concat "^" outline-regexp) end t))
14439 (while (and (< (point) end) (looking-at outline-regexp))
14440 (hide-subtree)
14441 (org-cycle-show-empty-lines 'folded)
14442 (condition-case nil
14443 (outline-forward-same-level 1)
14444 (error (goto-char end)))))
14445 (goto-char end)
14446 (skip-chars-forward " \t\n\r"))
14447 (call-interactively 'yank)))
14449 (define-key org-mode-map "\C-y" 'org-yank)
14451 (defun org-invisible-p ()
14452 "Check if point is at a character currently not visible."
14453 ;; Early versions of noutline don't have `outline-invisible-p'.
14454 (if (fboundp 'outline-invisible-p)
14455 (outline-invisible-p)
14456 (get-char-property (point) 'invisible)))
14458 (defun org-invisible-p2 ()
14459 "Check if point is at a character currently not visible."
14460 (save-excursion
14461 (if (and (eolp) (not (bobp))) (backward-char 1))
14462 ;; Early versions of noutline don't have `outline-invisible-p'.
14463 (if (fboundp 'outline-invisible-p)
14464 (outline-invisible-p)
14465 (get-char-property (point) 'invisible))))
14467 (defalias 'org-back-to-heading 'outline-back-to-heading)
14468 (defalias 'org-on-heading-p 'outline-on-heading-p)
14469 (defalias 'org-at-heading-p 'outline-on-heading-p)
14470 (defun org-at-heading-or-item-p ()
14471 (or (org-on-heading-p) (org-at-item-p)))
14473 (defun org-on-target-p ()
14474 (or (org-in-regexp org-radio-target-regexp)
14475 (org-in-regexp org-target-regexp)))
14477 (defun org-up-heading-all (arg)
14478 "Move to the heading line of which the present line is a subheading.
14479 This function considers both visible and invisible heading lines.
14480 With argument, move up ARG levels."
14481 (if (fboundp 'outline-up-heading-all)
14482 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14483 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14485 (defun org-up-heading-safe ()
14486 "Move to the heading line of which the present line is a subheading.
14487 This version will not throw an error. It will return the level of the
14488 headline found, or nil if no higher level is found."
14489 (let ((pos (point)) start-level level
14490 (re (concat "^" outline-regexp)))
14491 (catch 'exit
14492 (outline-back-to-heading t)
14493 (setq start-level (funcall outline-level))
14494 (if (equal start-level 1) (throw 'exit nil))
14495 (while (re-search-backward re nil t)
14496 (setq level (funcall outline-level))
14497 (if (< level start-level) (throw 'exit level)))
14498 nil)))
14500 (defun org-first-sibling-p ()
14501 "Is this heading the first child of its parents?"
14502 (interactive)
14503 (let ((re (concat "^" outline-regexp))
14504 level l)
14505 (unless (org-at-heading-p t)
14506 (error "Not at a heading"))
14507 (setq level (funcall outline-level))
14508 (save-excursion
14509 (if (not (re-search-backward re nil t))
14511 (setq l (funcall outline-level))
14512 (< l level)))))
14514 (defun org-goto-sibling (&optional previous)
14515 "Goto the next sibling, even if it is invisible.
14516 When PREVIOUS is set, go to the previous sibling instead. Returns t
14517 when a sibling was found. When none is found, return nil and don't
14518 move point."
14519 (let ((fun (if previous 're-search-backward 're-search-forward))
14520 (pos (point))
14521 (re (concat "^" outline-regexp))
14522 level l)
14523 (when (condition-case nil (org-back-to-heading t) (error nil))
14524 (setq level (funcall outline-level))
14525 (catch 'exit
14526 (or previous (forward-char 1))
14527 (while (funcall fun re nil t)
14528 (setq l (funcall outline-level))
14529 (when (< l level) (goto-char pos) (throw 'exit nil))
14530 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14531 (goto-char pos)
14532 nil))))
14534 (defun org-show-siblings ()
14535 "Show all siblings of the current headline."
14536 (save-excursion
14537 (while (org-goto-sibling) (org-flag-heading nil)))
14538 (save-excursion
14539 (while (org-goto-sibling 'previous)
14540 (org-flag-heading nil))))
14542 (defun org-show-hidden-entry ()
14543 "Show an entry where even the heading is hidden."
14544 (save-excursion
14545 (org-show-entry)))
14547 (defun org-flag-heading (flag &optional entry)
14548 "Flag the current heading. FLAG non-nil means make invisible.
14549 When ENTRY is non-nil, show the entire entry."
14550 (save-excursion
14551 (org-back-to-heading t)
14552 ;; Check if we should show the entire entry
14553 (if entry
14554 (progn
14555 (org-show-entry)
14556 (save-excursion
14557 (and (outline-next-heading)
14558 (org-flag-heading nil))))
14559 (outline-flag-region (max (point-min) (1- (point)))
14560 (save-excursion (outline-end-of-heading) (point))
14561 flag))))
14563 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14564 ;; This is an exact copy of the original function, but it uses
14565 ;; `org-back-to-heading', to make it work also in invisible
14566 ;; trees. And is uses an invisible-OK argument.
14567 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14568 (org-back-to-heading invisible-OK)
14569 (let ((first t)
14570 (level (funcall outline-level)))
14571 (while (and (not (eobp))
14572 (or first (> (funcall outline-level) level)))
14573 (setq first nil)
14574 (outline-next-heading))
14575 (unless to-heading
14576 (if (memq (preceding-char) '(?\n ?\^M))
14577 (progn
14578 ;; Go to end of line before heading
14579 (forward-char -1)
14580 (if (memq (preceding-char) '(?\n ?\^M))
14581 ;; leave blank line before heading
14582 (forward-char -1))))))
14583 (point))
14585 (defun org-show-subtree ()
14586 "Show everything after this heading at deeper levels."
14587 (outline-flag-region
14588 (point)
14589 (save-excursion
14590 (outline-end-of-subtree) (outline-next-heading) (point))
14591 nil))
14593 (defun org-show-entry ()
14594 "Show the body directly following this heading.
14595 Show the heading too, if it is currently invisible."
14596 (interactive)
14597 (save-excursion
14598 (condition-case nil
14599 (progn
14600 (org-back-to-heading t)
14601 (outline-flag-region
14602 (max (point-min) (1- (point)))
14603 (save-excursion
14604 (re-search-forward
14605 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14606 (or (match-beginning 1) (point-max)))
14607 nil))
14608 (error nil))))
14610 (defun org-make-options-regexp (kwds)
14611 "Make a regular expression for keyword lines."
14612 (concat
14614 "#?[ \t]*\\+\\("
14615 (mapconcat 'regexp-quote kwds "\\|")
14616 "\\):[ \t]*"
14617 "\\(.+\\)"))
14619 ;; Make isearch reveal the necessary context
14620 (defun org-isearch-end ()
14621 "Reveal context after isearch exits."
14622 (when isearch-success ; only if search was successful
14623 (if (featurep 'xemacs)
14624 ;; Under XEmacs, the hook is run in the correct place,
14625 ;; we directly show the context.
14626 (org-show-context 'isearch)
14627 ;; In Emacs the hook runs *before* restoring the overlays.
14628 ;; So we have to use a one-time post-command-hook to do this.
14629 ;; (Emacs 22 has a special variable, see function `org-mode')
14630 (unless (and (boundp 'isearch-mode-end-hook-quit)
14631 isearch-mode-end-hook-quit)
14632 ;; Only when the isearch was not quitted.
14633 (org-add-hook 'post-command-hook 'org-isearch-post-command
14634 'append 'local)))))
14636 (defun org-isearch-post-command ()
14637 "Remove self from hook, and show context."
14638 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14639 (org-show-context 'isearch))
14642 ;;;; Integration with and fixes for other packages
14644 ;;; Imenu support
14646 (defvar org-imenu-markers nil
14647 "All markers currently used by Imenu.")
14648 (make-variable-buffer-local 'org-imenu-markers)
14650 (defun org-imenu-new-marker (&optional pos)
14651 "Return a new marker for use by Imenu, and remember the marker."
14652 (let ((m (make-marker)))
14653 (move-marker m (or pos (point)))
14654 (push m org-imenu-markers)
14657 (defun org-imenu-get-tree ()
14658 "Produce the index for Imenu."
14659 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14660 (setq org-imenu-markers nil)
14661 (let* ((n org-imenu-depth)
14662 (re (concat "^" outline-regexp))
14663 (subs (make-vector (1+ n) nil))
14664 (last-level 0)
14665 m tree level head)
14666 (save-excursion
14667 (save-restriction
14668 (widen)
14669 (goto-char (point-max))
14670 (while (re-search-backward re nil t)
14671 (setq level (org-reduced-level (funcall outline-level)))
14672 (when (<= level n)
14673 (looking-at org-complex-heading-regexp)
14674 (setq head (org-match-string-no-properties 4)
14675 m (org-imenu-new-marker))
14676 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14677 (if (>= level last-level)
14678 (push (cons head m) (aref subs level))
14679 (push (cons head (aref subs (1+ level))) (aref subs level))
14680 (loop for i from (1+ level) to n do (aset subs i nil)))
14681 (setq last-level level)))))
14682 (aref subs 1)))
14684 (eval-after-load "imenu"
14685 '(progn
14686 (add-hook 'imenu-after-jump-hook
14687 (lambda ()
14688 (if (eq major-mode 'org-mode)
14689 (org-show-context 'org-goto))))))
14691 ;; Speedbar support
14693 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14694 "Overlay marking the agenda restriction line in speedbar.")
14695 (org-overlay-put org-speedbar-restriction-lock-overlay
14696 'face 'org-agenda-restriction-lock)
14697 (org-overlay-put org-speedbar-restriction-lock-overlay
14698 'help-echo "Agendas are currently limited to this item.")
14699 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14701 (defun org-speedbar-set-agenda-restriction ()
14702 "Restrict future agenda commands to the location at point in speedbar.
14703 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14704 (interactive)
14705 (require 'org-agenda)
14706 (let (p m tp np dir txt w)
14707 (cond
14708 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14709 'org-imenu t))
14710 (setq m (get-text-property p 'org-imenu-marker))
14711 (save-excursion
14712 (save-restriction
14713 (set-buffer (marker-buffer m))
14714 (goto-char m)
14715 (org-agenda-set-restriction-lock 'subtree))))
14716 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14717 'speedbar-function 'speedbar-find-file))
14718 (setq tp (previous-single-property-change
14719 (1+ p) 'speedbar-function)
14720 np (next-single-property-change
14721 tp 'speedbar-function)
14722 dir (speedbar-line-directory)
14723 txt (buffer-substring-no-properties (or tp (point-min))
14724 (or np (point-max))))
14725 (save-excursion
14726 (save-restriction
14727 (set-buffer (find-file-noselect
14728 (let ((default-directory dir))
14729 (expand-file-name txt))))
14730 (unless (org-mode-p)
14731 (error "Cannot restrict to non-Org-mode file"))
14732 (org-agenda-set-restriction-lock 'file))))
14733 (t (error "Don't know how to restrict Org-mode's agenda")))
14734 (org-move-overlay org-speedbar-restriction-lock-overlay
14735 (point-at-bol) (point-at-eol))
14736 (setq current-prefix-arg nil)
14737 (org-agenda-maybe-redo)))
14739 (eval-after-load "speedbar"
14740 '(progn
14741 (speedbar-add-supported-extension ".org")
14742 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14743 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14744 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14745 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14746 (add-hook 'speedbar-visiting-tag-hook
14747 (lambda () (org-show-context 'org-goto)))))
14750 ;;; Fixes and Hacks for problems with other packages
14752 ;; Make flyspell not check words in links, to not mess up our keymap
14753 (defun org-mode-flyspell-verify ()
14754 "Don't let flyspell put overlays at active buttons."
14755 (not (get-text-property (point) 'keymap)))
14757 ;; Make `bookmark-jump' show the jump location if it was hidden.
14758 (eval-after-load "bookmark"
14759 '(if (boundp 'bookmark-after-jump-hook)
14760 ;; We can use the hook
14761 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14762 ;; Hook not available, use advice
14763 (defadvice bookmark-jump (after org-make-visible activate)
14764 "Make the position visible."
14765 (org-bookmark-jump-unhide))))
14767 (defun org-bookmark-jump-unhide ()
14768 "Unhide the current position, to show the bookmark location."
14769 (and (org-mode-p)
14770 (or (org-invisible-p)
14771 (save-excursion (goto-char (max (point-min) (1- (point))))
14772 (org-invisible-p)))
14773 (org-show-context 'bookmark-jump)))
14775 ;; Make session.el ignore our circular variable
14776 (eval-after-load "session"
14777 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14779 ;;;; Experimental code
14781 (defun org-closed-in-range ()
14782 "Sparse tree of items closed in a certain time range.
14783 Still experimental, may disappear in the future."
14784 (interactive)
14785 ;; Get the time interval from the user.
14786 (let* ((time1 (time-to-seconds
14787 (org-read-date nil 'to-time nil "Starting date: ")))
14788 (time2 (time-to-seconds
14789 (org-read-date nil 'to-time nil "End date:")))
14790 ;; callback function
14791 (callback (lambda ()
14792 (let ((time
14793 (time-to-seconds
14794 (apply 'encode-time
14795 (org-parse-time-string
14796 (match-string 1))))))
14797 ;; check if time in interval
14798 (and (>= time time1) (<= time time2))))))
14799 ;; make tree, check each match with the callback
14800 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14803 ;;;; Finish up
14805 (provide 'org)
14807 (run-hooks 'org-load-hook)
14809 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14811 ;;; org.el ends here